PageSourceSearch

https://edgemxtiming.com/assets/Dashboard-TUqRGYUb.js

js edgemxtiming.com collected 2026-09-24 14:42:11 UTC 733,105 bytes, 409 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/mysqlEventBridge-i9SJNJp2.js","assets/index-BCH4IFx8.js","assets/index-0Cwll2Tp.css","assets/eventDeletion-7FDNiyZ3.js"])))=>i.map(i=>d[i]);
2import{c as Pt,i as da,r as a,j as e,D as ts,w as as,x as rs,y as is,K as Fs,B as w,d as Cl,M as Os,m as ie,u as K,a as Oa,O as Cs,b as v,I as A,S as Pe,n as Ie,o as qe,P as Je,k as Gt,Q as Ms,q as Be,t as ae,R as be,s as z,l as ms,X as vt,V as wt,Y as Us,Z as zs,_ as Vs,v as Hs,H as Ht,$ as Fr,a0 as ks,a1 as Cn,T as Na,a2 as kl,e as kn,a3 as En,G as mt,p as Vt,a4 as $t,F as Ar,L as sr,U as Xs,a5 as xa,z as Ys,a6 as El,a7 as Ml,a8 as Tl,a9 as tr,C as Pa,h as Lr,aa as Rl,A as $l}from"./index-BCH4IFx8.js";import{C as re,b as ke,c as Ee,d as ns,a as xe}from"./card-DaE3Hwfn.js";import{T as Ns}from"./textarea-C9Po2OuC.js";import{S as Ds}from"./switch-D8RIYbw7.js";import{S as zt}from"./skeleton-Dt7yWY4K.js";import{u as Dl,a as Fl,e as sn,w as Sa}from"./useEventShareLink-BuFD548V.js";import{I as Ia}from"./image-CG8pJg5g.js";import{R as kt}from"./refresh-cw-Bp2bbqxH.js";import{C as Nt}from"./copy-CIGjrFWu.js";import{E as ea}from"./external-link-C5SQDLFH.js";import{M as bt}from"./message-square-DUlqPTXD.js";import{M as Ks}from"./mail-a7kSoD61.js";import{C as sa}from"./chart-column-CE7gfWWI.js";import{g as ta}from"./baseUrl-1OnSOMcw.js";import{i as Al,a as ar,c as Ll,d as Pl}from"./KioskAdapterContext-CQ7aRBR0.js";import{u as Pr,a as Il,S as Ir,e as tn,E as ql,b as Bl,D as Ul,c as zl,d as Vl,A as Ol,f as Ga,g as Gl,h as Yl,i as Kl,j as Ya,k as Hl,l as Ql,m as qr,n as Wl,o as Zl,p as Jl,q as Xl,r as ec,s as sc,t as tc,v as ac,w as nc,x as rc}from"./usePosCoupons-CJJqfmMa.js";import{E as Ot,V as ic,T as Br,C as lc,A as Fa,a as cc,B as oc,M as nr,u as dc}from"./raceTypeRegistry-DbAseYb-.js";import{S as qs}from"./scroll-area-hNK22iDX.js";import{P as Ka}from"./progress-CL2A5cKM.js";import{a as mc,p as ma,R as uc,b as pn,F as rr,T as hc,i as xc}from"./formTemplates-C2Tiiina.js";import{C as As}from"./checkbox-D7mWENF4.js";import{R as ut,a as js}from"./radio-group-CA2dgSse.js";import{S as St}from"./separator-BJTOU-8g.js";import{S as aa}from"./sparkles-Bw29Z9hN.js";import{S as Ur}from"./star-CILQxhrW.js";import{S as ir}from"./shield-CYKtwov5.js";import{C as zr}from"./credit-card-DWFX6dPl.js";import{A as Mn}from"./award-BWT5GFkf.js";import{C as yt}from"./clock-DEKHqbRJ.js";import{U as Gs}from"./users-Cp35uMGZ.js";import{S as Vr}from"./shirt-BdRF3pfH.js";import{U as Dt}from"./upload-DCg56Dks.js";import{M as Tn}from"./map-pin-Eqsqtagn.js";import{C as At}from"./calendar-BcfRHKCP.js";import{B as oe}from"./BpSpinner-Bqvfph1h.js";import{A as ht,a as Or,b as xt}from"./alert-DYNhal_T.js";import{u as ba,a as pc}from"./useSeriesNames-DWxLNrfK.js";import{u as Qt,a as gc,b as fc}from"./useTimingClassesForOrg-CU6BNWOr.js";import{A as et,a as Lt,b as st,c as Et,d as tt,e as at,f as Mt,g as nt,h as rt}from"./alert-dialog-CJdQZTQ5.js";import{I as Rn}from"./info-D-iSIGln.js";import{P as Es}
2from"./plus-BhX-wvbj.js";import{T as ws}from"./trash-2-CrxPrdNf.js";import{P as Ha}from"./pen-line-LUsxtxOS.js";import{S as Qa}from"./save-C6KbuPF0.js";import{T as na,a as ra,b as Qs,c as Ss,d as ia,e as We}from"./table-BgVITkDQ.js";import{B as an}from"./book-open-B48QPdHE.js";import{A as Wa}from"./arrow-left-CX5CfIFs.js";import{P as Ft}from"./pencil-D5KWG9zo.js";import{L as ct}from"./lock-By386ZB3.js";import{C as Zs,S as gn}from"./SetupWizard-CdXrP2Fa.js";import{F as $n}from"./folder-open-B4wk2AUO.js";import{C as Kt}from"./circle-alert-BU1rIcjn.js";import{L as Za}from"./link-CRYWBnin.js";import{V as jc}from"./video-p_tYJZV_.js";import{D as Tt}from"./database-BkgB7DsT.js";import{C as ya}from"./chevron-left-BfsUvDbz.js";import{u as Wt}from"./useTimingEnabled-jfD7nqrK.js";import{F as jt}from"./file-text-BuQtBEyd.js";import{C as Dn}from"./circle-help-h2AkoHBZ.js";import{D as _a}from"./dollar-sign-DZ3kPgTb.js";import{B as Gr}from"./bike-Dps5BhUi.js";import{T as qa}from"./timer-C6AhmeTR.js";import{T as la}from"./trophy-vILI8AG3.js";import{H as vc}from"./heart-DlsJc9lx.js";import{L as Nc,a as Yr}from"./lock-open-C7rbpyt4.js";import{S as bc}from"./settings-2-CB6x7-YK.js";import{R as ca}from"./rotate-ccw-DpN8aSUP.js";import{L as Ba}from"./layers-CuqFRUiS.js";import{W as fn}from"./wand-sparkles-Bw0wz20k.js";import{u as Fn}from"./useContractGate-BQj0yEu5.js";import{L as An}from"./link-2-BbA-YcEU.js";import{C as yc,u as _c,a as wc,b as Sc,c as Cc,d as kc,g as Ec,e as Mc,f as Tc,I as Rc,S as Ln,h as Kr,i as $c}from"./useCommunicationsEnabled-DgqFDStI.js";import{S as Ua}from"./settings-BTLJRKc5.js";import{S as lr}from"./share-2-BRqKvXQJ.js";import{E as Dc}from"./eye-off-UCwc6mQx.js";import{E as Zt}from"./eye-EzNZygao.js";import{f as Js}from"./format-ybceeo2k.js";import{T as ot,a as pt,b as Qe,c as Ae}from"./tabs-eUqQwHgv.js";import{Q as Hr}from"./index-mlJThOBY.js";import{P as ja}from"./printer-wj9v_pVV.js";import{C as Pn,a as In,b as qn}from"./collapsible-xcd2iWHA.js";import{Q as Qr}from"./qr-code-OaITFpYD.js";import{P as Fc}from"./PayoutStatusBanner-BvR45_NY.js";import{c as cr}from"./useBridgeUpdateStatus-D0BV41kB.js";import{T as Is}from"./triangle-alert-m5K6MENR.js";import{W as Wr}from"./wifi-CaPQO4eW.js";import{u as Bn}from"./useOrganizationContract-DwGg0vL7.js";import{u as Un}from"./useOrgStripeAccount-OJw6A_Z0.js";import{S as Zr}from"./shield-alert-BMOy4B7c.js";import{B as jn}from"./banknote-CPxVp1Z4.js";import{R as Jr,D as Aa,u as Xr,i as ei,a as zn,b as Ja,M as Jt,c as Vn,E as Ac,d as Lc,e as Pc,f as Ic}from"./EmailBlastWizard-D4YkKa7r.js";import{S as gt}from"./send-CJD-Z0Nl.js";import{P as Rt}from"./phone-BoQi_8-c.js";import{u as Xa}from"./useRidersForOrg-Dz50QkTj.js";import{S as Ws}from"./search-GvbQAZxx.js";import{u as si}from"./useSendSMS-BFCgixls.js";import{E as ti}from"./ExtrasRecipientPicker-u9tI4Ozs.js";import{H as ai}from"./hash-Ca99qMeV.js";import{u as ni}from"./useRaceFeed-CLeEh0wE.js";import{C as qc}from"./calendar-clock-BiSYhr8S.js";import{C as or}from"./calendar-range-9Xefpm0m.js";import{S as ri}from"./shopping-bag-Dkab3ewO.js";import{R as vn}from"./radio-DbgeS3_C.js";import{P as Bc}from"./phone-input-CqSS1MA6.js";import{u as ii}from"./useSaveRider-Bnhoxod6.js";import{R as Uc,u as li,a as ci,A as zc,b as Vc,c as oi,d as Oc,e as Gc,f as Yc,g as Kc}from"./AssignCouponPackDialog-ChWPtPBI.js";import{B as Hc}from"./barcode-scanner-button-BK1woQQZ.js";import{C as Qc}from"./calendar-days-YI2yIyuJ.js";import{S as Wc}from"./square-pen-DGpFzMTR.js";import{u as di}from"./useTimingSettings-BS0Iq4io.js";import{S as On}from"./shield-check-CeYzatjO.js";import{u as mi,i as ui,a as hi,b as xi,A as pi,L as gi,E as fi}from"./index-CNSwMYTP.js";import{i as ji,H as vi,a as Ni}from"./index-oTw1S9FG.js";import{H as bi,S as Zc,u as Jc,a as Xc,b as eo}from"./useLiveTimingUsage-iaCffUp-.js";import{B as yi,I as _i,U as wi,A as Si,a as Ci,b as ki}from"./underline-BSHnBAnM.js";import{L as Gn}from"./list-ordered-DMG1_MP3.js";import{U as Ei}from"./unlink-bKKG2pa6.js";import{S as Mi}from"./sanitized-html-DPAQvfI8.js";import{C as so,a as dr}from"./calendar-B9rBEyrA.js";import{P as Ti,a as Ri,b as $i}from"./popover-BVAS7-gK.js";import{U as wa}from"./user-plus-Czkg6EX3.js";import{U as to,F as ao}from"./user-search-Uo2mynR8.js";import{T as Di}from"./tag-Mk6oilZH.js";import{C as oa}from"./CouponPosterPreview-DCFItFc0.js";import{Z as za}from"./zap-Cjz0tJy0.js";import{P as Fi}from"./palette-BG3SnNBH.js";import{K as mr}from"./key-round-DESqIiUD.js";import{C as Yn}from"./circle-check-big-C6zQJrMP.js";import{C as Ai}from"./circle-x-CCb710d9.js";import{P as va}from"./package-DNqMdpAz.js";import{read as no,utils as ro}from"./xlsx-B6sNpj_1.js";import{H as Nn}from"./handshake-BeDeP9KB.js";import{u as io,a as lo,P as co,G as Li,D as oo,c as mo,S as uo,v as ho,b as xo,C as po,d as go}from"./sortable.esm-BklNrvu_.js";import{S as fo}from"./scale-BWnIFLaA.js";import{H as Pi}from"./history-Bo2cYU1t.js";import{U as Ii}from"./user-cog-BIIJsLPt.js";import{T as jo}from"./trending-up-oNvFqoXH.js";import{U as Kn}from"./user-check-DJgc59q-.js";import{B as vo}from"./bot-BqG0y9ls.js";import{s as No}from"./startOfMonth-B1VOnNUT.js";import{e as bo}from"./endOfMonth--R-WtYph.js";import{R as yo,L as _o,C as wo,X as So,Y as Co,T as ko,a as ur,A as Eo}
2from"./AdminAnalytics-Cs4tGsAg.js";import{A as Mo}from"./arrow-up-down-B8egXO6U.js";import{c as nn}from"./orgNetRevenue-Bfw6BRxN.js";import{u as To}from"./usePlatformServiceFees-vIFArYyg.js";import{F as Ro}from"./file-check-Dv96N6dK.js";import{P as hr}from"./pen-DnmiT5dx.js";import{U as $o}from"./user-x-BBDJccig.js";import{u as Do,a as Fo,b as Ao,c as Lo,d as Po,e as Io,f as qi,g as Bi}from"./useRiderDatabaseLookup-Ck207LjN.js";import{R as qo,a as Bo,W as Uo,M as zo,b as Vo,c as Oo}from"./RiderScheduleSection-QQ4roKYW.js";import{L as Hn}from"./list-checks-B6tbvk60.js";import{u as Go}from"./useTimingCombinedSchedule-B4_boewu.js";import{S as Yo}from"./SignatureCanvas-ufOzCVFd.js";import{A as Ko}from"./ContractViewer-C0cbxPj3.js";import{F as La}from"./file-pen-line-CUrpn3Uh.js";import{E as Ho}from"./estimated-progress-CETNSrc9.js";import{d as Qo,a as Wo,R as Zo}from"./generateReconciliationCsv-D_QdC8tf.js";import{u as Jo,a as Xo,O as Ui}from"./useRaceReadiness-BAJ6igw_.js";import{A as ed,a as sd,b as td,c as ad}from"./accordion-BhWFpyA1.js";import{u as nd}from"./TutorialProgress-Cht675Gb.js";import{L as rd}from"./layout-dashboard-BYB_9_fX.js";import{G as xr}from"./graduation-cap-C5S13oTK.js";import"./useClassTierPricing-C18zMvw6.js";import"./useEvents-Ck6r64Ep.js";import"./teams-Dc2EtOTA.js";import"./crown-CjpfTJ_4.js";import"./useTrackLayouts-CWVr--sK.js";import"./TrackFormDialog-CKHyo1j4.js";import"./slider-DP7akdCw.js";import"./flag-CvB2R2ls.js";import"./youtube-C2Lay5Hh.js";import"./tv-CkcHwQXY.js";import"./youtube-DPBrFqvB.js";import"./play-CSYR7nMW.js";import"./square-TGQLwe2J.js";import"./user-minus-p5ZywIrz.js";import"./tags-D1W6ZGsU.js";import"./wrench-BCM-PgAk.js";import"./en-US-CGO0aXMi.js";import"./index-DKPz-1vL.js";import"./megaphone-DSpUXlnT.js";import"./code-CKWNp3Gy.js";import"./phone-Ltld9YKt.js";import"./useBikeMakeLogos-B-qqkSzN.js";import"./BikeMakeChip-DYEJrZnJ.js";import"./bikeMakeStyle-RND07Se0.js";import"./camera-DhQTGO9F.js";import"./index-7Wu8hD2L.js";import"./index-Dh4i1-J3.js";import"./purify.es-C5KSVp3G.js";import"./differenceInCalendarMonths-D2gXU8RP.js";import"./useProxiedImageUrl-B6wMlU7_.js";import"./useEventAnalytics-C_TU_ZH1.js";import"./resolveClassName-DvVkNNVP.js";import"./ellipsis-B1WFyn5h.js";import"./bell-DZvW1LWc.js";import"./useUserEmails-64UGJRED.js";import"./eraser-BjlB-yev.js";import"./jspdf.plugin.autotable-R0NBoJzi.js";/**
3 * @license lucide-react v0.462.0 - ISC
4 *
5 * This source code is licensed under the ISC license.
6 * See the LICENSE file in the root directory of this source tree.
7 */const id=Pt("BellOff",[["path",{d:"M8.7 3A6 6 0 0 1 18 8a21.3 21.3 0 0 0 .6 5",key:"o7mx20"}],["path",{d:"M17 17H3s3-2 3-9a4.67 4.67 0 0 1 .3-1.7",key:"16f1lm"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/**
8 * @license lucide-react v0.462.0 - ISC
9 *
10 * This source code is licensed under the ISC license.
11 * See the LICENSE file in the root directory of this source tree.
12 */const ld=Pt("FolderPlus",[["path",{d:"M12 10v6",key:"1bos4e"}],["path",{d:"M9 13h6",key:"1uhe8q"}],["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]]);/**
13 * @license lucide-react v0.462.0 - ISC
14 *
15 * This source code is licensed under the ISC license.
16 * See the LICENSE file in the root directory of this source tree.
17 */const cd=Pt("Import",[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m8 11 4 4 4-4",key:"1dohi6"}],["path",{d:"M8 5H4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-4",key:"1ywtjm"}]]);/**
18 * @license lucide-react v0.462.0 - ISC
19 *
20 * This source code is licensed under the ISC license.
21 * See the LICENSE file in the root directory of this source tree.
22 */const od=Pt("ListPlus",[["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"M18 9v6",key:"1twb98"}],["path",{d:"M21 12h-6",key:"bt1uis"}]]);/**
23 * @license lucide-react v0.462.0 - ISC
24 *
25 * This source code is licensed under the ISC license.
26 * See the LICENSE file in the root directory of this source tree.
27 */const dd=Pt("MailOpen",[["path",{d:"M21.2 8.4c.5.38.8.97.8 1.6v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V10a2 2 0 0 1 .8-1.6l8-6a2 2 0 0 1 2.4 0l8 6Z",key:"1jhwl8"}],["path",{d:"m22 10-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 10",key:"1qfld7"}]]);/**
28 * @license lucide-react v0.462.0 - ISC
29 *
30 * This source code is licensed under the ISC license.
31 * See the LICENSE file in the root directory of this source tree.
32 */const pr=Pt("MailQuestion",[["path",{d:"M22 10.5V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h12.5",key:"e61zoh"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"M18 15.28c.2-.4.5-.8.9-1a2.1 2.1 0 0 1 2.6.4c.3.4.5.8.5 1.3 0 1.3-2 2-2 2",key:"7z9rxb"}],["path",{d:"M20 22v.01",key:"12bgn6"}]]);/**
33 * @license lucide-react v0.462.0 - ISC
34 *
35 * This source code is licensed under the ISC license.
36 * See the LICENSE file in the root directory of this source tree.
37 */const md=Pt("MousePointerClick",[["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"M9.037 9.69a.498.498 0 0 1 .653-.653l11 4.5a.5.5 0 0 1-.074.949l-4.349 1.041a1 1 0 0 0-.74.739l-1.04 4.35a.5.5 0 0 1-.95.
37074z",key:"s0h3yz"}]]);/**
38 * @license lucide-react v0.462.0 - ISC
39 *
40 * This source code is licensed under the ISC license.
41 * See the LICENSE file in the root directory of this source tree.
42 */const ud=Pt("PenTool",[["path",{d:"M15.707 21.293a1 1 0 0 1-1.414 0l-1.586-1.586a1 1 0 0 1 0-1.414l5.586-5.586a1 1 0 0 1 1.414 0l1.586 1.586a1 1 0 0 1 0 1.414z",key:"nt11vn"}],["path",{d:"m18 13-1.375-6.874a1 1 0 0 0-.746-.776L3.235 2.028a1 1 0 0 0-1.207 1.207L5.35 15.879a1 1 0 0 0 .776.746L13 18",key:"15qc1e"}],["path",{d:"m2.3 2.3 7.286 7.286",key:"1wuzzi"}],["circle",{cx:"11",cy:"11",r:"2",key:"xmgehs"}]]);/**
43 * @license lucide-react v0.462.0 - ISC
44 *
45 * This source code is licensed under the ISC license.
46 * See the LICENSE file in the root directory of this source tree.
47 */const hd=Pt("TicketPercent",[["path",{d:"M2 9a3 3 0 1 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 1 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z",key:"1l48ns"}],["path",{d:"M9 9h.01",key:"1q5me6"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M15 15h.01",key:"lqbp3k"}]]),xd={facebook:"Facebook",x:"X",instagram:"Instagram",copy:"Copied link",sms:"Text",email:"Email",qr:"QR code",direct:"Direct",other:"Other"};function pd(s){if(!s)return"";const[n,i,t]=s.split("T")[0].split("-").map(Number);return!n||!i||!t?"":new Date(n,i-1,t).toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"})}function gd({open:s,onOpenChange:n,eventId:i,organizationId:t,eventName:d,targetUrl:r,eventDate:x,location:c}){const o=da(),[m,p]=a.useState(null),[u,l]=a.useState(!1),[N,j]=a.useState(!1),[g,y]=a.useState(0),k=a.useMemo(()=>{const $=pd(x),b=c?` at ${c}`:"";return`🏁 ${d}${$?` — ${$}`:""}${b}. Registration is open — grab your spot!`},[d,x,c]),[S,f]=a.useState(k),{data:h,isLoading:M}=Dl({eventId:i,organizationId:t,eventName:d,targetUrl:r,description:k,create:!0,enabled:s}),{data:T}=Fl(h==null?void 0:h.code),C=(h==null?void 0:h.shortUrl)??r,L=($,b)=>{const I=Sa(C,$);window.open(b(I),"_blank","noopener,noreferrer,width=680,height=680")},Q=async($,b)=>{try{await navigator.clipboard.writeText($),p(b),K.success("Copied to clipboard"),setTimeout(()=>p(null),2e3)}catch{K.error("Could not copy")}},Z=(h==null?void 0:h.clickCount)??0,R=$=>{if($==="sms"){const b=r;sessionStorage.setItem("bp_share_prefill_sms",`${S} Register here: ${b} — See you there!`),sessionStorage.setItem("bp_share_prefill_sms_media",sn(i)),o("/admin?tab=timing&section=communications&subtab=messaging"),setTimeout(()=>window.dispatchEvent(new Event("bp:share-prefill")),150)}else{const b=Sa(C,$),I=sn(i);sessionStorage.setItem("bp_share_prefill_email",JSON.stringify({subject:d,body:`<p><a href="${b}"><img src="${I}" alt="${d}" width="600" style="max-width:100%;height:auto;border-radius:8px;display:block" /></a></p><p>${S}</p><p><a href="${b}">${b}</a></p>`})),o("/admin?tab=timing&section=communications&subtab=email")}n(!1)},E=()=>{l(!1),j(!1),y($=>$+1)};return e.jsx(ts,{open:s,onOpenChange:n,children:e.jsxs(as,{className:"flex max-h-[92dvh] w-[calc(100vw-1.5rem)] max-w-2xl flex-col gap-0 overflow-hidden p-0",children:[e.jsxs(rs,{className:"shrink-0 space-y-1 border-b px-4 py-4 pr-12 sm:px-6",children:[e.jsxs(is,{children:["Share ",d]}),e.jsx(Fs,{children:"Post this link anywhere — it shows a branded preview card with the event name, date and venue."})]}),e.jsxs("div",{className:"min-h-0 flex-1 space-y-4 overflow-y-auto px-4 py-4 sm:px-6",children:[e.jsxs("div",{className:"relative aspect-[1200/630] w-full overflow-hidden rounded-lg border bg-muted",children:[!u&&!N&&e.jsx(zt,{className:"absolute inset-0"}),N?e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-3 p-6 text-center",children:[e.jsx(Ia,{className:"h-8 w-8 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Preview could not be generated"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Your share link still works. Try loading the preview again."})]}),e.jsxs(w,{type:"button",variant:"outline",size:"sm",onClick:E,children:[e.jsx(kt,{className:"mr-2 h-4 w-4"}),"Retry preview"]})]}):e.jsx("img",{src:`${sn(i)}${g?`&v=${g}`:""}`,alt:`Social preview card for ${d}`,className:`h-full w-full object-contain transition-opacity ${u?"opacity-100":"opacity-0"}`,onLoad:()=>l(!0),onError:()=>j(!0)},g)]}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-start gap-1.5",children:[e.jsx(Ia,{className:"mt-0.5 h-3 w-3 shrink-0"}),"Facebook and X cache previews — a changed image can take a while to refresh on already-shared links."]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-sm font-medium",children:"Post caption"}),e.jsx(Ns,{value:S,onChange:$=>f($.target.value),rows:2})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-sm font-medium",children:"Share link"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex-1 min-w-0 text-xs bg-muted rounded-md px-3 py-2 truncate",children:M?e.jsx(Cl,{className:"h-3 w-3 animate-spin"}):C}),e.jsx(w,{variant:"outline",size:"sm",onClick:()=>Q(Sa(C,"copy"),"link"),disabled:M,children:m==="link"?e.jsx(Os,{className:"h-4 w-4"}):e.jsx(Nt,{className:"h-4 w-4"})}),e.jsx(w,{variant:"outline",size:"sm",asChild:!0,children:e.jsx("a",{href:C,target:"_blank",rel:"noopener noreferrer",children:e.jsx(ea,{className:"h-4 w-4"})})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-2",children:[e.jsx(w,{className:"bg-[#1877F2] hover:bg-[#1877F2]/90 text-white",disabled:M,onClick:()=>L("facebook",$=>`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent($)}&quote=${encodeURIComponent(S)}`),children:"Share on Facebook"}),e.jsx(w,{variant:"secondary",disabled:M,onClick:()=>L("x",$=>`https://twitter.com/intent/tweet?text=${encodeURIComponent(S)}&url=${encodeURIComponent($)}`),children:"Share on X"}),e.jsxs(w,{variant:"outline",disabled:M,onClick:()=>R("sms"),children:[e.jsx(bt,{className:"h-4 w-4 mr-2"}),"Text to riders"]}),e.jsxs(w,{variant:"outline",disabled:M,onClick:()=>R("email"),children:[e.jsx(Ks,{className:"h-4 w-4 mr-2"}),"Email to riders"]}),e.jsxs(w,{variant:"outline",className:"sm:col-span-2",disabled:M,onClick:()=>Q(`${S} ${Sa(C,"instagram")}`,"ig"),children:[m==="ig"?e.jsx(Os,{className:"h-4 w-4 mr-2"}):e.jsx(Nt,{className:"h-4 w-4 mr-2"}),"Copy caption + link for Instagram"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground -mt-1",children:"In texts the link unfurls into the same preview card — put the link on its own line (or at the end) so Messages can attach the card."}),e.jsx("p",{className:"text-xs text-muted-foreground -mt-1",children:"Instagram doesn't allow posting from the web — paste the caption into your post or story and add the link in your bio or as a story sticker."}),e.jsxs("div",{className:"rounded-lg border p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(sa,{className:"h-4 w-4 text-primary"}),"Link clicks"]}),e.jsxs(ie,{variant:"secondary",children:[Z," total"]})]}),T&&T.length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:T.map($=>e.jsxs(ie,{variant:"outline",className:"text-xs",children:[xd[$.channel]??$.channel,": ",$.clicks]},$.channel))}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No clicks yet. Clicks are tracked per channel once riders start tapping the link."})]})]})]})})}const zi="/assets/motocross-banner-Cq6426JZ.jpg",Vi="/assets/enduro-banner-CcajrV1D.jpg",Oi="/assets/flattrack-banner-sd1OJJ5t.jpg",Gi="/assets/hillclimb-banner-nuiBB-oD.jpg",Yi="/assets/trials-banner-CJlHZ7Bq.jpg",Ki="/assets/vintage-banner-9hMtuMRn.jpg",Hi="/assets/running-banner-CH_Rj9tZ.jpg",Qi="/assets/triathlon-banner-D3XfbZaf.jpg",Wi="/assets/cycling-banner-C2Y6rFKU.jpg",Zi="/assets/swimming-banner-CZibFXkp.jpg",Ji="/assets/obstacle-banner-DDSFL7mq.jpg",Xi="/assets/golf-banner-B3hK0DaL.jpg",el="/assets/charity-banner-BFGhyC6a.jpg",sl="/assets/conference-banner-C8ZuD1un.jpg",tl="/assets/youth-sports-banner-DFSaeB4q.jpg",al="/assets/fitness-banner-Yfwjqcox.jpg",nl="/assets/basic-banner-I_QZh77u.jpg",fd={motocross:zi,enduro:Vi,"flat-track":Oi,"hill-climb":Gi,trials:Yi,vintage:Ki,"running-race":Hi,triathlon:Qi,cycling:Wi,swimming:Zi,"obstacle-course":Ji,"golf-tournament":Xi,"charity-walk":el,conference:sl,"youth-sports":tl,"fitness-class":al,basic:nl};
47function jd({template:s}){const{fields:n,bannerGradient:i,bannerEmoji:t,name:d,accentColor:r,id:x}=s,c=fd[x],o=(m,p)=>{var N,j;const l={full:"col-span-12",half:"col-span-6",third:"col-span-4",quarter:"col-span-3"}[m.width||"full"]||"col-span-12";switch(m.field_type){case"heading":return e.jsxs("div",{className:"col-span-12 pt-6 first:pt-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("div",{className:`w-1 h-6 rounded-full bg-gradient-to-b ${i}`}),e.jsx("h3",{className:"text-lg font-bold text-foreground",children:m.label})]}),m.help_text&&e.jsx("p",{className:"text-sm text-muted-foreground ml-3",children:m.help_text})]},p);case"line_break":case"divider":return e.jsx("div",{className:"col-span-12 py-3",children:e.jsxs("div",{className:"relative",children:[e.jsx(St,{className:"bg-border/60"}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:`w-8 h-0.5 rounded-full bg-gradient-to-r ${i} opacity-50`})})]})},p);case"paragraph":return e.jsx("div",{className:"col-span-12",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:m.label})},p);case"name":case"text":return e.jsxs("div",{className:Cs(l,"space-y-2"),children:[e.jsxs(v,{className:"text-sm font-medium flex items-center gap-1.5",children:[m.label,m.is_required&&e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(A,{placeholder:m.placeholder||`Enter ${(N=m.label)==null?void 0:N.toLowerCase()}`,disabled:!0,className:"bg-muted/30 border-border/60"}),m.help_text&&e.jsx("p",{className:"text-xs text-muted-foreground",children:m.help_text})]},p);case"email":return e.jsxs("div",{className:Cs(l,"space-y-2"),children:[e.jsxs(v,{className:"text-sm font-medium flex items-center gap-1.5",children:[m.label,m.is_required&&e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(A,{type:"email",placeholder:"[email protected]",disabled:!0,className:"bg-muted/30 border-border/60"})]},p);case"phone":return e.jsxs("div",{className:Cs(l,"space-y-2"),children:[e.jsxs(v,{className:"text-sm font-medium flex items-center gap-1.5",children:[m.label,m.is_required&&e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(A,{type:"tel",placeholder:"(555) 123-4567",disabled:!0,className:"bg-muted/30 border-border/60"})]},p);case"date":return e.jsxs("div",{className:Cs(l,"space-y-2"),children:[e.jsxs(v,{className:"text-sm font-medium flex items-center gap-1.5",children:[m.label,m.is_required&&e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsxs(w,{variant:"outline",disabled:!0,className:"w-full justify-start text-left font-normal bg-muted/30 border-border/60",children:[e.jsx(At,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"text-muted-foreground",children:"Pick a date"})]})]},p);case"gender":return e.jsxs("div",{className:Cs(l,"space-y-2"),children:[e.jsxs(v,{className:"text-sm font-medium flex items-center gap-1.5",children:[m.label,m.is_required&&e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(Pe,{disabled:!0,children:e.jsx(Ie,{className:"bg-muted/30 border-border/60",children:e.jsx(qe,{placeholder:"Select gender"})})})]},p);case"address":return e.jsxs("div",{className:"col-span-12 space-y-2",children:[e.jsxs(v,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Tn,{className:"h-4 w-4 text-muted-foreground"}),m.label,m.is_required&&e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(A,{placeholder:"Street Address",disabled:!0,className:"col-span-2 bg-muted/30 border-border/60"}),e.jsx(A,{placeholder:"City",disabled:!0,className:"bg-muted/30 border-border/60"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(A,{placeholder:"State",disabled:!0,className:"bg-muted/30 border-border/60"}),e.jsx(A,{placeholder:"ZIP",disabled:!0,className:"bg-muted/30 border-border/60"})]})]})]},p);case"radio":return e.jsxs("div",{className:"col-span-12 space-y-2",children:[e.jsxs(v,{className:"text-sm font-medium flex items-center gap-1.5",children:[m.label,m.is_required&&e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(ut,{disabled:!0,className:"grid grid-cols-2 gap-2",children:(j=m.options)==null?void 0:j.slice(0,4).map((g,y)=>e.jsxs("div",{className:"flex items-center space-x-2 p-2.5 border rounded-lg bg-muted/20 border-border/60 hover:border-border transition-colors",children:[e.jsx(js,{value:g.value,id:`${p}-${y}`,disabled:!0}),e.jsx(v,{htmlFor:`${p}-${y}`,className:"text-sm cursor-pointer flex-1",children:g.label})]},y))}),m.help_text&&e.jsx("p",{className:"text-xs text-muted-foreground",children:m.help_text})]},p);case"checkbox":return e.jsxs("div",{className:"col-span-12 flex items-start space-x-3 p-3 border rounded-lg bg-muted/20 border-border/60",children:[e.jsx(As,{disabled:!0,className:"mt-0.5"}),e.jsxs("div",{className:"grid gap-1 leading-none",children:[e.jsxs(v,{className:"text-sm font-medium flex items-center gap-1.5",children:[m.label,m.is_required&&e.jsx("span",{className:"text-destructive",children:"*"})]}),m.help_text&&e.jsx("p",{className:"text-xs text-muted-foreground",children:m.help_text})]})]},p);case"file":case"image":return e.jsxs("div",{className:"col-span-12 space-y-2",children:[e.jsxs(v,{className:"text-sm font-medium flex items-center gap-1.5",children:[m.label,m.is_required&&e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-6 text-center bg-muted/20 border-border/60",children:[e.jsx(Dt,{className:"h-8 w-8 mx-auto text-muted-foreground
47/60 mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Click to upload"}),e.jsx("p",{className:"text-xs text-muted-foreground/60 mt-1",children:"PNG, JPG up to 10MB"})]})]},p);case"waiver":return e.jsxs("div",{className:"col-span-12 space-y-3",children:[e.jsxs(v,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(ir,{className:"h-4 w-4 text-muted-foreground"}),m.label,m.is_required&&e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsxs("div",{className:"border rounded-lg p-4 bg-muted/20 border-border/60 space-y-3",children:[e.jsxs("div",{className:"h-24 bg-muted/40 rounded-md p-3 text-xs text-muted-foreground overflow-hidden",children:[e.jsx("p",{className:"font-medium mb-1",children:"Liability Waiver Agreement"}),e.jsx("p",{className:"line-clamp-3",children:"I hereby agree to participate in this event at my own risk and waive any claims against the organizers for any injuries or damages that may occur during participation..."})]}),e.jsxs("div",{className:"border-t border-dashed pt-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-2",children:[e.jsx(ud,{className:"h-4 w-4"}),e.jsx("span",{children:"Sign below"})]}),e.jsx("div",{className:"h-16 border-2 border-dashed rounded-md flex items-end justify-center text-muted-foreground/50 text-sm pb-2 bg-background/50",children:"Your signature here"})]})]})]},p);case"terms":return e.jsx("div",{className:"col-span-12 space-y-2",children:e.jsxs("div",{className:"flex items-start space-x-3 p-3 border rounded-lg bg-muted/20 border-border/60",children:[e.jsx(As,{disabled:!0,className:"mt-0.5"}),e.jsxs("div",{className:"grid gap-1 leading-none",children:[e.jsxs(v,{className:"text-sm font-medium flex items-center gap-1.5",children:["I agree to the Terms and Conditions",m.is_required&&e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Read our terms and privacy policy"})]})]})},p);case"tshirt_size":return e.jsxs("div",{className:Cs(l,"space-y-2"),children:[e.jsxs(v,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Vr,{className:"h-4 w-4 text-muted-foreground"}),m.label,m.is_required&&e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx("div",{className:"flex gap-1.5 flex-wrap",children:["XS","S","M","L","XL","2XL"].map(g=>e.jsx("div",{className:"px-3 py-1.5 border rounded-md text-xs font-medium bg-muted/30 text-muted-foreground border-border/60 hover:border-border transition-colors",children:g},g))})]},p);case"age_division":return e.jsxs("div",{className:Cs(l,"space-y-2"),children:[e.jsxs(v,{className:"text-sm font-medium flex items-center gap-1.5",children:[m.label,m.is_required&&e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(Pe,{disabled:!0,children:e.jsx(Ie,{className:"bg-muted/30 border-border/60",children:e.jsx(qe,{placeholder:"Select age division"})})})]},p);case"team":return e.jsxs("div",{className:Cs(l,"space-y-2"),children:[e.jsxs(v,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Gs,{className:"h-4 w-4 text-muted-foreground"}),m.label,m.is_required&&e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(A,{placeholder:"Team name",disabled:!0,className:"bg-muted/30 border-border/60"}),m.help_text&&e.jsx("p",{className:"text-xs text-muted-foreground",children:m.help_text})]},p);case"wave_time":case"finish_time":return e.jsxs("div",{className:Cs(l,"space-y-2"),children:[e.jsxs(v,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(yt,{className:"h-4 w-4 text-muted-foreground"}),m.label,m.is_required&&e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(Pe,{disabled:!0,children:e.jsx(Ie,{className:"bg-muted/30 border-border/60",children:e.jsx(qe,{placeholder:"Select time"})})}),m.help_text&&e.jsx("p",{className:"text-xs text-muted-foreground",children:m.help_text})]},p);case"class_entry":return e.jsxs("div",{className:"col-span-12 space-y-2",children:[e.jsxs(v,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Mn,{className:"h-4 w-4 text-muted-foreground"}),m.label,m.is_required&&e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx("div",{className:"border rounded-lg p-3 bg-muted/20 border-border/60 space-y-2",children:e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(Pe,{disabled:!0,children:e.jsx(Ie,{className:"bg-background border-border/60",children:e.jsx(qe,{placeholder:"Class"})})}),e.jsx(Pe,{disabled:!0,children:e.jsx(Ie,{className:"bg-background border-border/60",children:e.jsx(qe,{placeholder:"Make"})})}),e.jsx(A,{placeholder:"CC",disabled:!0,className:"bg-background border-border/60"})]})})]},p);case"donation":return e.jsxs("div",{className:"col-span-12 space-y-2",children:[e.jsxs(v,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(zr,{className:"h-4 w-4 text-muted-foreground"}),m.label]}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:["$25","$50","$100","Custom"].map(g=>e.jsx("div",{className:"px-4 py-2 border rounded-lg text-sm font-medium bg-muted/30 text-muted-foreground border-border/60 hover:border-border transition-colors",children:g},g))}),m.help_text&&e.jsx("p",{className:"text-xs text-muted-foreground",children:m.help_text})]},p);case"sessions":return e.jsxs("div",{className:"col-span-12 space-y-2",children:[e.jsxs(v,{className:"text-sm font-medium flex items-center gap-1.5",children:[m.label,m.is_required&&e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:["Session A","Session B","Session C","Session D"].map(g=>e.jsxs("div",{className:"flex items-center space-x-2 p-2.5 border rounded-lg bg-muted/20 border-border/60",children:[e.jsx(As,{disabled:!0}),e.jsx("span",{className:"text-sm",children:g})]},g))}),m.help_text&&e.jsx("p",{className:"text-xs text-muted-foreground",children:m.help_text})]},p);default:return e.jsxs("div",{className:Cs(l,"space-y-2"),children:[e.jsxs(v,{className:"text-sm font-medium flex items-center gap-1.5",children:[m.label,m.is_required&&e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(A,{placeholder:m.placeholder||m.label,disabled:!0,className:"bg-muted/30 border-border/60"})]},p)}};return e.jsxs("div",{className:"bg-card border rounded-xl shadow-lg overflow-hidden",children:[e.jsxs("div",{className:"relative h-48 overflow-hidden",children:[c?e.jsx("img",{src:c,alt:d,className:"w-full h-full object-cover"}):e.jsx("div",{className:`w-full h-full bg-gradient-to-r ${i}`}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/80 via-black/40 to-transparent"}),e.jsx("div",{className:"absolute bottom-0 left-0 right-0 p-6",children:e.jsxs("div",{className:"flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("span",{className:"text-4xl drop-shadow-lg",children:t}),e.jsx("h2",{className:"text-2xl font-bold text-white drop-shadow-lg",children:d})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ie,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(aa,{className:"h-3 w-3 mr-1"}),n.length," fields"]}),e.jsxs(ie,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(Oa,{className:"h-3 w-3 mr-1"}),"Ready to use"]})]})]}),e.jsx("div",{className:"hidden sm:flex items-center gap-1",children:[1,2,3,4,5].map(m=>e.jsx(Ur,{className:"h-5 w-5 text-yellow-300 fill-yellow-300 drop-shadow-lg"},m))})]})})]}),e.jsxs("div",{className:"bg-muted/30 border-b px-6 py-3 flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:"Registration Form Preview"}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(ir,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Secure form"})]})]}),e.jsxs("div",{className:"p-6",children:[e.jsx("div",{className:"grid grid-cols-12 gap-4",children:n.map((m,p)=>o(m,p))}),e.jsxs("div",{className:"mt-8 pt-6 border-t",children:[e.jsx(w,{disabled:!0,className:`w-full bg-gradient-to-r ${i} text-white hover:opacity-90 h-12 text-lg font-semibold shadow-lg`,children:"Complete Registration"}),e.jsx("p",{className:"text-center text-xs text-muted-foreground mt-3",children:"By registering, you agree to our terms and conditions"})]})]})]})}function Ca({visibleSection:s="all",preselectedSeries:n,onEventSaved:i}){const{currentOrganization:t}=Je(),d=Gt(),r=Ms(),{data:x=[],isLoading:c}=ba(),{data:o=[]}=pc(),{data:m=[]}=Qt(),[p,u]=a.useState(null),[l,N]=a.useState(!1),[j,g]=a.useState(""),[y,k]=a.useState(!1),[S,f]=a.useState(""),[h,M]=a.use
47State(""),[T,C]=a.useState(""),[L,Q]=a.useState(""),[Z,R]=a.useState(""),[E,$]=a.useState(""),[b,I]=a.useState("16"),[V,H]=a.useState("2"),[Y,W]=a.useState("Olympic"),[te,B]=a.useState("88"),[le,Me]=a.useState("89"),[_,X]=a.useState("90"),[F,ne]=a.useState("0"),[J,_e]=a.useState("40"),[me,$e]=a.useState(""),[ee,pe]=a.useState(""),[je,we]=a.useState(!1),[U,se]=a.useState(!1),[ue,ve]=a.useState(null),[he,ze]=a.useState(null),[He,Ve]=a.useState(s==="edit"?"edit":"create"),[Ue,de]=a.useState(null),[Le,ye]=a.useState(null),[Ze,Ls]=a.useState(null);a.useState("");const[P,Te]=a.useState(null);a.useState(""),a.useState(""),a.useState(""),a.useState(!0),a.useState(!1);const Fe=async()=>{if(!j.trim()){be({title:"Please enter a series name",variant:"destructive"});return}if(!(t!=null&&t.id)){be({title:"Organization not loaded",variant:"destructive"});return}k(!0);try{const{data:O,error:Ne}=await z.functions.invoke("save-series",{body:{organization_id:t.id,series_name:j.trim()}});if(Ne)throw Ne;if(O!=null&&O.error)throw new Error(O.error);be({title:"Series created",description:`"${j}" added to staging table for sync`}),g(""),r.invalidateQueries({queryKey:["series-names"]}),r.invalidateQueries({queryKey:["mysql-events"]})}catch(O){console.error("Error creating series:",O),be({title:"Failed to create series",description:O instanceof Error?O.message:"Unknown error",variant:"destructive"})}finally{k(!1)}},Ye=async(O,Ne)=>{if(t!=null&&t.id){u(O);try{const{error:Se}=await z.from("events").delete().eq("organization_id",t.id).or(`mysql_series_name.eq.${O},name.eq.${O}`);if(Se)throw Se;be({title:"Series deleted",description:`"${O}" and its events have been removed`}),r.invalidateQueries({queryKey:["series-names"]}),r.invalidateQueries({queryKey:["series-details"]}),r.invalidateQueries({queryKey:["mysql-events"]})}catch(Se){be({title:"Failed to delete series",description:Se instanceof Error?Se.message:"Unknown error",variant:"destructive"})}finally{u(null)}}},Xe=async(O=!1)=>{if(!(!(t!=null&&t.id)||!Ze)){N(!0);try{const{error:Ne}=await z.from("events").delete().eq("organization_id",t.id).or(`mysql_event_name.eq.${Ze},name.eq.${Ze}`);if(Ne)throw Ne;be({title:"Event deleted",description:`"${Ze}" has been removed`}),Ls(null),ve(null),f(""),r.invalidateQueries({queryKey:["mysql-events"]}),r.invalidateQueries({queryKey:["mysql-classes"]}),r.invalidateQueries({queryKey:["series-names"]}),r.invalidateQueries({queryKey:["series-details"]})}catch(Ne){be({title:"Failed to delete event",description:Ne instanceof Error?Ne.message:"Unknown error",variant:"destructive"})}finally{N(!1)}}},bs=async()=>{if(!S.trim()||!he){be({title:"Please select a series and enter an event name",variant:"destructive"});return}if(!(t!=null&&t.id)){be({title:"Organization not loaded",variant:"destructive"});return}we(!0);try{const O={series_name:he,event_name:S.trim(),track_name:h,event_location:T,event_date_month:L,event_date_day:Z,event_date_year:E,number_of_gates:b,moto_format:V,overall_method:Y,dnf:te,dns:le,dsq:_,min_lap_time_min:F,min_lap_time_sec:J,promoter_name:me,sanction_number:ee},{data:Ne,error:Se}=await z.functions.invoke("save-event",{body:{organization_id:t.id,event_data:O}});if(Se)throw Se;if(Ne!=null&&Ne.error)throw new Error(Ne.error);be({title:"Event created",description:`"${S}" added to staging table for sync`});const us=S.trim(),ps=he||"";f(""),M(""),C(""),Q(""),R(""),$(""),I("16"),H("2"),W("Olympic"),B("88"),Me("89"),X("90"),ne("0"),_e("40"),$e(""),pe(""),ze(null),r.invalidateQueries({queryKey:["mysql-events"]}),r.invalidateQueries({queryKey:["series-names"]}),i==null||i(ps,us)}catch(O){console.error("Error creating event:",O),be({title:"Failed to create event",description:O instanceof Error?O.message:"Unknown error",variant:"destructive"})}finally{we(!1)}},Ts=async()=>{if(!Ze){be({title:"Please select an event to load",variant:"destructive"});return}if(!(t!=null&&t.id)){be({title:"Organization not loaded",variant:"destructive"});return}se(!0);try{const{data:O,error:Ne}=await z.functions.invoke("fetch-timing-event-details",{body:{organization_id:t.id,event_name:Ze}});if(Ne)throw Ne;if(O!=null&&O.event){const Se=O.event;f(Se.event_name||""),M(Se.track_name||""),C(Se.event_location||""),Q(String(Se.event_date_month||"")),R(String(Se.event_date_day||"")),$(String(Se.event_date_year||"")),I(String(Se.number_of_gates||"16")),H(String(Se.moto_format||"2")),W(Se.overall_method||"Olympic"),B(String(Se.dnf||"88")),Me(String(Se.dns||"89")),X(String(Se.dsq||"90")),ne(String(Se.min_lap_time_min||"0")),_e(String(Se.min_lap_time_sec||"40")),$e(Se.promoter_name||""),pe(Se.sanction_number||""),ve(Ze),ze(Se.series_name||null),be({title:"Event loaded",description:`"${Ze}" loaded into form for editing`})}}catch(O){console.error("Error loading event:",O),be({title:"Failed to load event",description:O instanceof Error?O.message:"Unknown error",variant:"destructive"})}finally{se(!1)}}
47,[Ps,Rs]=a.useState(!1),D=async()=>{if(!ue){be({title:"Please load an event first",variant:"destructive"});return}if(!(t!=null&&t.id)){be({title:"Organization not loaded",variant:"destructive"});return}Rs(!0);try{const O={series_name:he||"",event_name:S,track_name:h,event_location:T,event_date_month:L,event_date_day:Z,event_date_year:E,number_of_gates:b,moto_format:V,overall_method:Y,dnf:te,dns:le,dsq:_,min_lap_time_min:F,min_lap_time_sec:J,promoter_name:me,sanction_number:ee},{data:Ne,error:Se}=await z.functions.invoke("save-event",{body:{organization_id:t.id,event_data:O,original_event_name:ue}});if(Se)throw Se;be({title:"Event saved",description:`Changes to "${S}" saved to staging table`}),r.invalidateQueries({queryKey:["mysql-events"]}),r.invalidateQueries({queryKey:["mysql-classes"]}),i==null||i(he||"",S)}catch(O){console.error("Error saving event:",O),be({title:"Failed to save event",description:O instanceof Error?O.message:"Unknown error",variant:"destructive"})}finally{Rs(!1)}};return e.jsxs("div",{className:"space-y-6",children:[(s==="all"||s==="create-series")&&e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsxs(Ee,{className:"flex items-center gap-2",children:[e.jsx(ie,{variant:"outline",children:"①"}),"Create a Series"]}),e.jsx(ns,{children:"Create a new race series for your organization"})]}),e.jsxs(xe,{className:"space-y-4",children:[e.jsxs(ht,{children:[e.jsx(Rn,{className:"h-4 w-4"}),e.jsx(Or,{children:"How to set up a series the right way"}),e.jsxs(xt,{children:[e.jsxs("ol",{className:"list-decimal pl-5 space-y-1 mt-1",children:[e.jsx("li",{children:"Create the series here."}),e.jsxs("li",{children:["Build ",e.jsx("strong",{children:"one"})," complete event in it: event details, every class, and a race order on every class. Race order 
47can still be tweaked later."]}),e.jsxs("li",{children:["Then go to ",e.jsx("strong",{children:"Copy Race Across Series"})," below to create the rest of the rounds (or push that setup into existing rounds) in one click."]})]}),e.jsx("div",{className:"mt-2 text-xs",children:"If you skip the full setup on your first event, the other rounds will not populate correctly."})]})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-[280px]",children:[e.jsx(v,{htmlFor:"seriesName",children:"Series Name"}),e.jsx(A,{id:"seriesName",placeholder:"e.g., 2026 Summer Series",value:j,onChange:O=>g(O.target.value),maxLength:40})]}),e.jsxs(w,{onClick:Fe,disabled:y,children:[y?e.jsx(oe,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Es,{className:"h-4 w-4 mr-2"}),"Create Series"]})]}),o.length>0&&e.jsxs("div",{className:"mt-4",children:[e.jsx(v,{className:"text-sm text-muted-foreground mb-2 block",children:"Series (click to delete)"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:o.map(O=>{const Ne=!!O.staging_only;return e.jsxs(et,{children:[e.jsx(Lt,{asChild:!0,children:e.jsxs(ie,{variant:Ne?"secondary":"outline",className:"cursor-pointer gap-1 hover:bg-destructive/10 transition-colors",children:[O.series_name,!Ne&&e.jsx("span",{className:"text-[10px] opacity-60",children:"(synced)"}),p===O.series_name?e.jsx(oe,{className:"h-3 w-3 animate-spin"}):e.jsx(ws,{className:"h-3 w-3"})]})}),e.jsxs(st,{children:[e.jsxs(Et,{children:[e.jsxs(tt,{children:['Delete series "',O.series_name,'"?']}),e.jsx(at,{children:Ne?"This will permanently remove this series and all its staged events from the staging tables. This cannot be undone.":"This series has been synced to the timing system. Deleting it will remove it and ALL its events, classes, and race orders from the timing database. This cannot be undone."})]}),e.jsxs(Mt,{children:[e.jsx(nt,{children:"Cancel"}),e.jsx(rt,{onClick:()=>Ye(O.series_name),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:Ne?"Delete Series":"Delete from Timing System"})]})]})]},O.series_name)})})]})]})]}),(s==="all"||s==="create"||s==="edit"||s==="copy")&&e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsxs(Ee,{className:"flex items-center gap-2",children:[e.jsx(ie,{variant:"outline",children:"②"}),"Event Management",ue&&He==="edit"&&e.jsxs(ie,{variant:"secondary",className:"ml-2",children:["Editing: ",ue]})]}),e.jsx(ns,{children:"Create a new event or edit an existing one"})]}),e.jsxs(xe,{className:"space-y-6",children:[s==="all"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{children:"What would you like to do?"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(w,{variant:He==="create"?"default":"outline",onClick:()=>{Ve("create"),ve(null),f(""),M(""),C(""),Q(""),R(""),$(""),I("16"),H("2"),W("Olympic"),B("88"),Me("89"),X("90"),ne("0"),_e("40"),$e(""),pe(""),ze(null)},children:[e.jsx(Es,{className:"h-4 w-4 mr-2"}),"Create New Event"]}),e.jsxs(w,{variant:He==="edit"?"default":"outline",onClick:()=>{Ve("edit"),ve(null),f(""),M(""),C(""),Q(""),R(""),$(""),I("16"),H("2"),W("Olympic"),B("88"),Me("89"),X("90"),ne("0"),_e("40"),$e(""),pe(""),ze(null)},children:[e.jsx(Ha,{className:"h-4 w-4 mr-2"}),"Edit Existing Event"]})]})]}),e.jsx(St,{})]}),(He==="edit"||s==="edit"||s==="copy")&&s!=="create"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ot,{selectedYear:Ue,selectedSeries:Le,selectedEvent:Ze,selectedClass:null,onYearChange:O=>{de(O),ye(null),Ls(null)},onSeriesChange:O=>{ye(O),Ls(null),O&&!P&&Te(O)},onEventChange:Ls,onClassChange:()=>{},hideClassSelector:!0}),s!=="copy"&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(w,{variant:"outline",onClick:Ts,disabled:U||!Ze,children:[U?e.jsx(oe,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(kt,{className:"h-4 w-4 mr-2"}),"Load Event Into Form"]}),Ze&&(()=>{var Ne;const O=((Ne=m.find(Se=>Se.event_name===Ze))==null?void 0:Ne.stagingOnly)===1;return e.jsxs(et,{children:[e.jsx(Lt,{asChild:!0,children:e.jsx(w,{variant:"destructive",size:"icon",disabled:l,children:l?e.jsx(oe,{className:"h-4 w-4 animate-spin"}):e.jsx(ws,{className:"h-4 w-4"})})}),e.jsxs(st,{children:[e.jsxs(Et,{children:[e.jsxs(tt,{children:['Delete event "',Ze,'"?']}),e.jsx(at,{children:O?"This will permanently remove this event and its staged classes/race order from the staging tables. This cannot be undone.":"This event has been synced to the timing system. Deleting it will remove it from the timing database along with all its classes and race order. This cannot be undone."})]}),e.jsxs(Mt,{children:[e.jsx(nt,{children:"Cancel"}),e.jsx(rt,{onClick:()=>Xe(!O),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:O?"Delete Event":"Delete from Timing System"})]})]})]})})()]})]}),s!=="copy"&&s!=="edit"&&He==="create"&&e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:e.jsxs("div",{children:[e.jsx(v,{htmlFor:"createEventSeries",children:"Series *"}),e.jsxs(Pe,{value:he||"",onValueChange:ze,children:[e.jsx(Ie,{id:"createEventSeries",children:e.jsx(qe,{placeholder:c?"
47Loading...":"Select a series"})}),e.jsx(Be,{children:x.map(O=>e.jsx(ae,{value:O,children:O},O))})]})]})}),He==="edit"&&ue&&he&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Series: ",e.jsx("span",{className:"font-medium text-foreground",children:he})]}),s!=="copy"&&(He==="create"||He==="edit"&&ue)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(v,{htmlFor:"eventName",children:"Event Name *"}),e.jsx(A,{id:"eventName",placeholder:"e.g., Round 1 - Season Opener",value:S,onChange:O=>f(O.target.value),maxLength:40})]}),e.jsxs("div",{children:[e.jsx(v,{htmlFor:"trackName",children:"Track Name"}),e.jsx(A,{id:"trackName",placeholder:"e.g., Edge MX Park",value:h,onChange:O=>M(O.target.value),maxLength:40})]}),e.jsxs("div",{children:[e.jsx(v,{htmlFor:"eventLocation",children:"Location"}),e.jsx(A,{id:"eventLocation",placeholder:"City, ST",value:T,onChange:O=>C(O.target.value),maxLength:40})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-4",children:[e.jsxs("div",{className:"w-20",children:[e.jsx(v,{htmlFor:"eventMonth",children:"Month"}),e.jsx(A,{id:"eventMonth",placeholder:"MM",value:L,onChange:O=>Q(O.target.value),maxLength:2})]}),e.jsxs("div",{className:"w-20",children:[e.jsx(v,{htmlFor:"eventDay",children:"Day"}),e.jsx(A,{id:"eventDay",placeholder:"DD",value:Z,onChange:O=>R(O.target.value),maxLength:2})]}),e.jsxs("div",{className:"w-24",children:[e.jsx(v,{htmlFor:"eventYear",children:"Year"}),e.jsx(A,{id:"eventYear",placeholder:"YYYY",value:E,onChange:O=>$(O.target.value),maxLength:4})]}),e.jsxs("div",{className:"w-24",children:[e.jsx(v,{htmlFor:"numberOfGates",children:"# Gates"}),e.jsx(A,{id:"numberOfGates",placeholder:"16",value:b,onChange:O=>I(O.target.value),maxLength:2})]}),e.jsxs("div",{className:"w-36",children:[e.jsx(v,{htmlFor:"motoFormat",children:"Moto Format"}),e.jsxs(Pe,{value:V,onValueChange:H,children:[e.jsx(Ie,{id:"motoFormat",children:e.jsx(qe,{})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"1",children:"1 Moto"}),e.jsx(ae,{value:"2",children:"2 Motos"}),e.jsx(ae,{value:"3",children:"3 Motos"})]})]})]}),e.jsxs("div",{className:"w-40",children:[e.jsx(v,{htmlFor:"overallMethod",children:"Overall Method"}),e.jsxs(Pe,{value:Y,onValueChange:W,children:[e.jsx(Ie,{id:"overallMethod",children:e.jsx(qe,{})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"Olympic",children:"Olympic"}),e.jsxs(ae,{value:"Motos Combined",children:[d.races," Combined"]}),e.jsx(ae,{value:"Points",children:"Points"})]})]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-4",children:[e.jsxs("div",{className:"w-20",children:[e.jsx(v,{htmlFor:"dnfPoints",children:"DNF"}),e.jsx(A,{id:"dnfPoints",type:"number",value:te,onChange:O=>B(O.target.value),min:0,max:999})]}),e.jsxs("div",{className:"w-20",children:[e.jsx(v,{htmlFor:"dnsPoints",children:"DNS"}),e.jsx(A,{id:"dnsPoints",type:"number",value:le,onChange:O=>Me(O.target.value),min:0,max:999})]}),e.jsxs("div",{className:"w-20",children:[e.jsx(v,{htmlFor:"dsqPoints",children:"DSQ"}),e.jsx(A,{id:"dsqPoints",type:"number",value:_,onChange:O=>X(O.target.value),min:0,max:999})]}),e.jsxs("div",{className:"w-28",children:[e.jsx(v,{htmlFor:"minLapMinutes",children:"Min Lap (min)"}),e.jsx(A,{id:"minLapMinutes",placeholder:"0",value:F,onChange:O=>ne(O.target.value),maxLength:2})]}),e.jsxs("div",{className:"w-28",children:[e.jsx(v,{htmlFor:"minLapSeconds",children:"Min Lap (sec)"}),e.jsx(A,{id:"minLapSeconds",placeholder:"40",value:J,onChange:O=>_e(O.target.value),maxLength:2})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(v,{htmlFor:"promoter",children:"Promoter"}),e.jsx(A,{id:"promoter",placeholder:"Promoter Name",value:me,onChange:O=>$e(O.target.value),maxLength:40})]}),e.jsxs("div",{children:[e.jsx(v,{htmlFor:"sanctionNumber",children:"Sanction #"}),e.jsx(A,{id:"sanctionNumber",placeholder:"Optional",value:ee,onChange:O=>pe(O.target.value),maxLength:20})]})]}),He==="create"?e.jsxs(w,{onClick:bs,disabled:je,children:[je?e.jsx(oe,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(At,{className:"h-4 w-4 mr-2"}),"Create Event"]}):e.jsxs(w,{onClick:D,disabled:Ps,children:[Ps?e.jsx(oe,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Qa,{className:"h-4 w-4 mr-2"}),"Save Changes"]})]}),(s==="all"||s==="copy")&&e.jsxs(e.Fragment,{children:[e.jsx(St,{}),e.jsxs("div",{className:"p-4 border border-dashed rounded-lg bg-muted/30 text-sm text-muted-foreground",children:["Copying a configured template across rounds now lives in"," ",e.jsx("span",{className:"font-medium",children:"Timing Lab → Duplicate Event"})," ","(Postgres-native). The legacy MySQL propagator has been retired."]})]})]})]})]})}function vd({preselectedEvent:s,preselectedSeries:n,onComplete:i,initialMethod:t}={}){var xs;const d=Ms(),{currentOrganization:r}=Je(),[x,c]=a.useState(null),[o,m]=a.useState(n||null),[p,u]=a.useState(s||null),[l,N]=a.useState(t??null);a.useEffect(()=>{t!==void 0&&N(t)},[t]);const[j,g]=a.useState(""),[y,k]=a.useState(""),[S,f]=a.useState(""),[h,M]=a.use
47State(""),[T,C]=a.useState(""),[L,Q]=a.useState(!1),[Z,R]=a.useState(null),[E,$]=a.useState(null),[b,I]=a.useState(null),[V,H]=a.useState(!1),[Y,W]=a.useState("all"),[te,B]=a.useState(new Set),[le,Me]=a.useState(!1),[_,X]=a.useState(!1),{data:F}=Pr(r==null?void 0:r.id),ne=Il(F),{data:J}=Qt(),{data:_e,isLoading:me,error:$e,refetch:ee}=gc(p),[pe,je]=a.useState(null),[we,U]=a.useState(""),[se,ue]=a.useState(null),[ve,he]=a.useState(!1),{data:ze}=ms({queryKey:["class-rename-eligibility",r==null?void 0:r.id,p],enabled:!!(r!=null&&r.id)&&!!p,staleTime:3e4,queryFn:async()=>{const{data:G,error:De}=await z.functions.invoke("check-class-rename-eligibility",{body:{organization_id:r.id,event_name:p}});if(De)throw De;return G}}),He=G=>G.normalize("NFKC").replace(/[\u200B-\u200D\uFEFF]/g,"").replace(/[\u00A0\u1680\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/g," ").replace(/\s+/g," ").trim(),Ve=G=>He(G).replace(/[‐‑‒–—―−]/g,"-").replace(/\s*-\s*/g,"-").toLocaleLowerCase("en-US"),Ue=G=>{if(G==null)return null;const De=Number(G);return Number.isFinite(De)?De:null},de=(()=>{if(!_e)return[];const G=new Map;for(const De of _e){if(!De.class_name)continue;const ds=Ve(De.class_name),Ge=He(De.class_name),ss=Ue(De.moto_number),es=G.get(ds);if(!es)G.set(ds,{...De,class_name:Ge,moto_count:ss?1:0,moto_numbers:ss?new Set([ss]):new Set});else{ss&&es.moto_numbers.add(ss),es.moto_count=es.moto_numbers.size,es.pendingSync=es.pendingSync||De.pendingSync?1:0;const cs=Ue(es.race_number),ys=Ue(De.race_number);(cs===null||ys!==null&&ys<cs)&&(es.race_number=ys),Ge.length<es.class_name.length&&(es.class_name=Ge)}}return Array.from(G.values()).map(({moto_numbers:De,...ds})=>ds)})(),Le=de.map(G=>G.class_name).sort(),ye=(()=>{if(!p||!J)return[];const G=J.find(De=>De.event_name===p);return G?J.filter(De=>De.series_name===G.series_name&&Number(De.event_date_year)===Number(G.event_date_year)&&De.event_name!==p).map(De=>De.event_name):[]})(),Ze=p&&J?((xs=J.find(G=>G.event_name===p))==null?void 0:xs.series_name)??null:null,Ls=async()=>{const G=y.trim()||j;if(!G){be({title:"Please enter or select a class name",variant:"destructive"});return}if(!p){be({title:"Please select an event first",variant:"destructive"});return}if(!(r!=null&&r.id)){be({title:"Organization not found",variant:"destructive"});return}Q(!0);try{const De=_?[p,...ye]:[p],ds=[{class_name:G,age_minimum:S.trim()?Number(S):null,age_limit:h.trim()?Number(h):null,copy_from_class_name:T||null}],Ge=await Promise.allSettled(De.map(cs=>z.functions.invoke("import-predefined-classes",{body:{organization_id:r.id,event_name:cs,classes:ds}}))),ss=[];Ge.forEach((cs,ys)=>{var ft;const Ce=De[ys];cs.status==="rejected"?ss.push(`${Ce}: ${cs.reason instanceof Error?cs.reason.message:"unknown error"}`):cs.value.error?ss.push(`${Ce}: ${cs.value.error.message??"invoke error"}`):(ft=cs.value.data)!=null&&ft.error&&ss.push(`${Ce}: ${cs.value.data.error}`)});const es=De.length-ss.length;ss.length===0?be({title:"Class added",description:_&&De.length>1?`"${G}" added to ${es} events in this series`:`"${G}" added to ${p}`}):es>0?be({title:`Added to ${es} of ${De.length} events`,description:ss.slice(0,3).join(" • "),variant:"destructive"}):be({title:"Failed to add class",description:ss.slice(0,3).join(" • "),variant:"destructive"}),es>0&&(k(""),g(""),f(""),M(""),C(""),ee(),d.invalidateQueries({queryKey:["mysql-classes"]}))}catch(De){be({title:"Error adding class",description:De instanceof Error?De.message:"Unknown error",variant:"destructive"})}finally{Q(!1)}},P=async()=>{if(!b){be({title:"Please select a source event",variant:"destructive"});return}if(!p){be({title:"Please select a target event first",variant:"destructive"});return}if(b===p){be({title:"Source and target events cannot be the same",variant:"destructive"});return}if(!(r!=null&&r.id)){be({title:"Organization not found",variant:"destructive"});return}H(!0);try{const{data:G,error:De}=await z.functions.invoke("copy-event-classes",{body:{organization_id:r.id,source_event_name:b,target_event_name:p}});if(De)throw De;G!=null&&G.error?be({title:"Copy failed",description:G.error,variant:"destructive"}):(be({title:"Classes copied successfully",description:(G==null?void 0:G.message)||`Copied ${(G==null?void 0:G.copied)||0} classes`}),ee(),d.invalidateQueries({queryKey:["mysql-classes"]}
47))}catch(G){be({title:"Error copying classes",description:G instanceof Error?G.message:"Unknown error",variant:"destructive"})}finally{H(!1)}},[Te,Fe]=a.useState(null),[Ye,Xe]=a.useState(!1),bs=G=>{p&&Fe(G)},Ts=async()=>{if(!(!Te||!(r!=null&&r.id)||!p)){Xe(!0);try{const{data:G,error:De}=await z.functions.invoke("delete-event-class",{body:{organization_id:r.id,event_name:p,class_name:Te}});if(De)throw De;if(G!=null&&G.error){be({title:"Cannot delete class",description:G.error,variant:"destructive"});return}be({title:"Class removed",description:(G==null?void 0:G.message)??`"${Te}" was flagged for removal on the next sync.`}),Fe(null),ee(),d.invalidateQueries({queryKey:["mysql-classes"]}),d.invalidateQueries({queryKey:["eventClasses"]})}catch(G){be({title:"Delete failed",description:G instanceof Error?G.message:"Unknown error",variant:"destructive"})}finally{Xe(!1)}}},Ps=G=>{je(G),U(G)},Rs=()=>{je(null),U("")},D=async G=>{const De=we.trim();if(!De||De===G){Rs();return}const ds=De.toLowerCase();if(Le.some(es=>es.toLowerCase()===ds&&es!==G)){be({title:"Name already used",description:`"${De}" already exists in this event`,variant:"destructive"});return}if(!(r!=null&&r.id)||!p)return;let Ge=0,ss=0;try{const{data:es}=await z.from("events").select("id").eq("organization_id",r.id).eq("mysql_event_name",p).maybeSingle();if(es!=null&&es.id){const{data:cs}=await z.from("registrations").select("form_data").eq("event_id",es.id),ys=JSON.stringify(cs??[]),Ce=`"${G.replace(/[\\"]/g,ft=>"\\"+ft)}"`;Ge=(ys.match(new RegExp(Ce.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"))??[]).length}}catch{}ue({oldName:G,newName:De,regCount:Ge,entryCount:ss})},O=async()=>{if(!(!se||!(r!=null&&r.id)||!p)){he(!0);try{const{data:G,error:De}=await z.functions.invoke("rename-event-class",{body:{organization_id:r.id,event_name:p,old_class_name:se.oldName,new_class_name:se.newName}});if(De)throw De;G!=null&&G.error?(be({title:"Rename failed",description:G.error,variant:"destructive"}),G.reason&&d.invalidateQueries({queryKey:["class-rename-eligibility"]})):(be({title:"Class renamed",description:`Updated ${G.classes_renamed??0} class, ${G.entries_renamed??0} entries, ${G.supabase_registrations_updated??0} registrations`}),Rs(),ue(null),ee(),d.invalidateQueries({queryKey:["mysql-classes"]}),d.invalidateQueries({queryKey:["eventClasses"]}))}catch(G){be({title:"Rename failed",description:G instanceof Error?G.message:"Unknown",variant:"destructive"})}finally{he(!1)}}},Ne=G=>{B(De=>{const ds=new Set(De);return ds.has(G)?ds.delete(G):ds.add(G),ds})},Se=G=>{const De=(F??[]).filter(ds=>G==="all"||ds.category===G);B(ds=>{const Ge=new Set(ds);return De.every(es=>Ge.has(es.class_name))?De.forEach(es=>Ge.delete(es.class_name)):De.forEach(es=>Ge.add(es.class_name)),Ge})},us=async()=>{if(te.size===0){be({title:"Please select at least one class",variant:"destructive"});return}if(!(!p||!(r!=null&&r.id))){Me(!0);try{const G=(F??[]).filter(cs=>te.has(cs.class_name)).map(cs=>({class_name:cs.class_name,age_minimum:cs.age_minimum,age_limit:cs.age_limit})),De=_?[p,...ye]:[p],ds=await Promise.allSettled(De.map(cs=>z.functions.invoke("import-predefined-classes",{body:{organization_id:r.id,event_name:cs,classes:G}}))),Ge=[];let ss=0;ds.forEach((cs,ys)=>{var ft,It;const Ce=De[ys];cs.status==="rejected"?Ge.push(`${Ce}: ${cs.reason instanceof Error?cs.reason.message:"unknown error"}`):cs.value.error?Ge.push(`${Ce}: ${cs.value.error.message??"invoke error"}`):(ft=cs.value.data)!=null&&ft.error?Ge.push(`${Ce}: ${cs.value.data.error}`):ss+=((It=cs.value.data)==null?void 0:It.imported)??G.length});const es=De.length-Ge.length;Ge.length===0?be({title:"Classes imported",description:_&&De.length>1?`Imported ${G.length} class${G.length!==1?"es":""} into ${es} events`:`Imported ${ss} class${ss!==1?"es":""}`}):es>0?be({title:`Imported into ${es} of ${De.length} events`,description:Ge.slice(0,3).join(" • "),variant:"destructive"}):be({title:"Import failed",description:Ge.slice(0,3).join(" • "),variant:"destructive"}),es>0&&(B(new Set),ee(),d.invalidateQueries({queryKey:["mysql-classes"]}))}catch(G){be({title:"Error importing classes",description:G instanceof Error?G.message:"Unknown error",variant:"destructive"})}finally{Me(!1)}}},ps=(F??[]).filter(G=>Y==="all"||G.category===Y);return e.jsxs("div",{className:"space-y-6",children:[!s&&e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsxs(Ee,{className:"flex items-center gap-2",children:[e.jsx(ie,{variant:"outline",children:"④"}),"Event Classes"]}
47),e.jsx(ns,{children:"Manage classes for a specific event"})]}),e.jsx(xe,{children:e.jsx(Ot,{selectedYear:x,selectedSeries:o,selectedEvent:p,selectedClass:null,onYearChange:c,onSeriesChange:m,onEventChange:u,onClassChange:()=>{},hideClassSelector:!0})})]}),p&&e.jsxs(e.Fragment,{children:[!t&&l===null&&e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsx(Ee,{children:"How would you like to add classes?"}),e.jsx(ns,{children:"Choose one method to get started"})]}),e.jsx(xe,{children:e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs("button",{onClick:()=>N("manual"),className:"flex flex-col items-center gap-3 p-6 rounded-lg border-2 border-border hover:border-primary hover:bg-accent/50 transition-colors text-center group",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center group-hover:bg-primary/20 transition-colors",children:e.jsx(Ha,{className:"h-6 w-6 text-primary"})}),e.jsx("span",{className:"font-semibold",children:"Add Classes Manually"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Create classes one at a time"})]}),e.jsxs("button",{onClick:()=>N("copy"),className:"flex flex-col items-center gap-3 p-6 rounded-lg border-2 border-border hover:border-primary hover:bg-accent/50 transition-colors text-center group",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center group-hover:bg-primary/20 transition-colors",children:e.jsx(Nt,{className:"h-6 w-6 text-primary"})}),e.jsx("span",{className:"font-semibold",children:"Import from Another Race"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Copy a class list from an existing event"})]}),e.jsxs("button",{onClick:()=>N("template"),className:"flex flex-col items-center gap-3 p-6 rounded-lg border-2 border-border hover:border-primary hover:bg-accent/50 transition-colors text-center group",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center group-hover:bg-primary/20 transition-colors",children:e.jsx(an,{className:"h-6 w-6 text-primary"})}),e.jsx("span",{className:"font-semibold",children:"Import from Templates"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Use your saved class template list"})]})]})})]}),!t&&l!==null&&e.jsxs(w,{variant:"ghost",size:"sm",onClick:()=>N(null),className:"gap-2",children:[e.jsx(Wa,{className:"h-4 w-4"}),"Choose a different method"]}),l==="manual"&&e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsx(Ee,{children:"Add Class to Event"}),e.jsx(ns,{children:"Add an existing class or create a new one for this event"})]}),e.jsxs(xe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-end gap-4",children:[e.jsxs("div",{className:"min-w-[260px]",children:[e.jsx(v,{htmlFor:"existingClass",children:"Choose Existing Class"}),e.jsxs(Pe,{value:j,onValueChange:g,children:[e.jsx(Ie,{id:"existingClass",children:e.jsx(qe,{placeholder:"Select a class..."})}),e.jsx(Be,{children:Le.map(G=>e.jsx(ae,{value:G,children:G},G))})]})]}),e.jsxs("div",{className:"min-w-[260px]",children:[e.jsx(v,{htmlFor:"newClassName",children:"Or New Class Name"}),e.jsx(A,{id:"newClassName",placeholder:"Type a new class name…",value:y,onChange:G=>k(G.target.value),maxLength:60})]})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-4",children:[e.jsxs("div",{className:"w-[120px]",children:[e.jsx(v,{htmlFor:"newAgeMin",children:"Age Min"}),e.jsx(A,{id:"newAgeMin",type:"number",min:0,placeholder:"—",value:S,onChange:G=>f(G.target.value)})]}),e.jsxs("div",{className:"w-[120px]",children:[e.jsx(v,{htmlFor:"newAgeMax",children:"Age Max"}),e.jsx(A,{id:"newAgeMax",type:"number",min:0,placeholder:"—",value:h,onChange:G=>M(G.target.value)})]}),e.jsxs("div",{className:"min-w-[260px]",children:[e.jsx(v,{htmlFor:"copyDefaultsFrom",children:"Copy defaults from (optional)"}),e.jsxs(Pe,{value:T||"__none__",onValueChange:G=>C(G==="__none__"?"":G),children:[e.jsx(Ie,{id:"copyDefaultsFrom",children:e.jsx(qe,{placeholder:"Use sensible defaults"})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"__none__",children:"Use sensible defaults"}),Le.map(G=>e.jsx(ae,{value:G,children:G},G))]})]})]}),e.jsxs(w,{onClick:Ls,disabled:L,children:[L?e.jsx(oe,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Es,{className:"h-4 w-4 mr-2"}),_&&ye.length>0?`Add to ${ye.length+1} Events`:"Add to Event"]})]}),Ze&&ye.length>0&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md border bg-muted/30",children:[e.jsx(As,{id:"applyToAllManual",checked:_,onCheckedChange:G=>X(G===!0),className:"mt-0.5"}),e.jsxs(v,{htmlFor:"applyToAllManual",className:"text-sm font-normal cursor-pointer leading-snug",children:["Also add this class to all ",e.jsx("strong",{children:ye.length})," other event",ye.length!==1?"s":""," in"," ",e.jsx("strong",{children:Ze}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:'Skip going round-by-round — the same class (and any "copy defaults from" peer settings) will be added to every event in this series.'})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pick a peer class to copy its gates, laps, divisions, and other timing settings. Otherwise sensible defaults are used (practice group 1, 1 division, 8 gates)."})]})]}),l==="copy"&&e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsx(Ee,{children:"Copy Class List"}),e.jsx(ns,{children:"Copy class list from another event to this one"})]}),e.jsxs(xe,{className:"space-y-4",children:[e.jsx(Ot,{selectedYear:Z,selectedSeries:E,selectedEvent:b,selectedClass:null,onYearChange:G=>{R(G),$(null),I(null)},onSeriesChange:G=>{$(G),I(null)},onEventChange:I,onClassChange:()=>{},hideClassSelector:!0}),(b||p)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-x-6 gap-y-2 p-3 bg-muted/50 rounded-md border",children:[b&&e.jsxs("span",{className:"text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Copy from:"})," ",e.jsx("strong",{children:b})]}),b&&p&&e.jsx("span",{className:"text-muted-foreground",children:"→"}),p&&e.jsxs("span",{className:"text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Copy to:"})," ",e.jsx("strong",{children:p})]})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(w,{onClick:P,disabled:V||!b,children:[V?e.jsx(oe,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Nt,{className:"h-4 w-4 mr-2"}),"Copy Classes"]}
47),b&&p&&b===p&&e.jsx("span",{className:"text-sm text-destructive",children:"Source and target cannot be the same"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Copies from canonical event_classes plus any pending rows in webhook_event_classes_synced."})]})]}),l==="template"&&e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsxs(Ee,{className:"flex items-center gap-2",children:[e.jsx(an,{className:"h-5 w-5"}),"Import from Class Templates"]}),e.jsx(ns,{children:"Import classes from your saved class template list"})]}),e.jsxs(xe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"min-w-[200px]",children:[e.jsx(v,{children:"Filter by Category"}),e.jsxs(Pe,{value:Y,onValueChange:W,children:[e.jsx(Ie,{children:e.jsx(qe,{placeholder:"All categories"})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"all",children:"All Categories"}),ne.map(G=>e.jsx(ae,{value:G,children:G},G))]})]})]}),e.jsxs("div",{className:"flex items-end gap-2 mt-auto pt-5",children:[e.jsx(w,{variant:"outline",size:"sm",onClick:()=>Se(Y),children:ps.every(G=>te.has(G.class_name))&&ps.length>0?"Deselect All":"Select All"}),e.jsxs(ie,{variant:"secondary",children:[te.size," selected"]})]})]}),ps.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No class templates found. You can add templates in your organization settings."}):e.jsx("div",{className:"max-h-[300px] overflow-y-auto border rounded-md",children:e.jsxs(na,{children:[e.jsx(ra,{children:e.jsxs(Qs,{children:[e.jsx(Ss,{className:"w-[40px]"}),e.jsx(Ss,{children:"Class Name"}),e.jsx(Ss,{children:"Category"}),e.jsx(Ss,{children:"Age Range"})]})}),e.jsx(ia,{children:ps.map(G=>e.jsxs(Qs,{className:"cursor-pointer",onClick:()=>Ne(G.class_name),children:[e.jsx(We,{children:e.jsx(As,{checked:te.has(G.class_name),onCheckedChange:()=>Ne(G.class_name)})}),e.jsx(We,{className:"font-medium",children:G.class_name}),e.jsx(We,{children:e.jsx(ie,{variant:"outline",children:G.category})}),e.jsx(We,{children:G.age_minimum||G.age_limit?`${G.age_minimum??"—"} – ${G.age_limit??"—"}`:"—"})]},G.id))})]})}),Ze&&ye.length>0&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md border bg-muted/30",children:[e.jsx(As,{id:"applyToAllTemplate",checked:_,onCheckedChange:G=>X(G===!0),className:"mt-0.5"}),e.jsxs(v,{htmlFor:"applyToAllTemplate",className:"text-sm font-normal cursor-pointer leading-snug",children:["Also import these classes into all ",e.jsx("strong",{children:ye.length})," other event",ye.length!==1?"s":""," in"," ",e.jsx("strong",{children:Ze})]})]}),e.jsxs(w,{onClick:us,disabled:le||te.size===0,children:[le?e.jsx(oe,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(an,{className:"h-4 w-4 mr-2"}),"Import ",te.size," Class",te.size!==1?"es":"",_&&ye.length>0?` × ${ye.length+1} Events`:""]})]})]}),e.jsxs(re,{children:[e.jsxs(ke,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Ee,{children:"Classes for this Event"}),e.jsxs(ns,{children:[Le.length," class",Le.length!==1?"es":""," found"]})]}),e.jsxs(w,{variant:"outline",size:"sm",onClick:()=>ee(),children:[e.jsx(kt,{className:"h-4 w-4 mr-2"}),"Refresh"]})]}),e.jsx(xe,{children:me?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(oe,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):$e?e.jsx("div",{className:"text-center py-8 text-destructive",children:"Error loading classes"}):Le.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No classes found for this event"}):e.jsxs(na,{children:[e.jsx(ra,{children:e.jsxs(Qs,{children:[e.jsx(Ss,{children:"Class Name"}),e.jsx(Ss,{children:"Practice Group"}),e.jsx(Ss,{children:"Age Range"}),e.jsx(Ss,{children:"Gates"}),e.jsx(Ss,{children:"Status"}),e.jsx(Ss,{className:"w-[100px]",children:"Actions"})]})}),e.jsx(ia,{children:de.sort((G,De)=>G.class_name.localeCompare(De.class_name)).map(G=>{const De=pe===G.class_name,ds=(ze==null?void 0:ze.eligible)===!0;return e.jsxs(Qs,{children:[e.jsx(We,{className:"font-medium",children:De?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(A,{value:we,onChange:Ge=>U(Ge.target.value),onKeyDown:Ge=>{Ge.key==="Enter"&&D(G.class_name),Ge.key==="Escape"&&Rs()},autoFocus:!0,className:"h-8 max-w-[260px]"}),e.jsx(w,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>D(G.class_name),children:e.jsx(Os,{className:"h-4 w-4 text-green-600"})}),e.jsx(w,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:Rs,children:e.jsx(vt,{className:"h-4 w-4"})})]}):e.jsxs("span",{className:"inline-flex items-center gap-2",children:[G.class_name,G.moto_count>1&&e.jsxs(ie,{variant:"outline",className:"text-xs font-normal",children:[G.moto_count," motos"]})]})}),e.jsx(We,{children:G.practice_group||"—"}),e.jsx(We,{children:G.age_minimum||G.age_limit?`${G.age_minimum??"—"} – ${G.age_limit??"—"}`:"—"}),e.jsx(We,{children:G.num_gates||"—"}),e.jsx(We,{children:G.pendingSync?e.jsx(ie,{variant:"outline",className:"text-amber-600 border-amber-400",children:"Pending Sync"}):e.jsx(ie,{variant:"secondary",children:"Synced"})}),e.jsx(We,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[ds&&!De&&e.jsx(w,{variant:"ghost",size:"sm",onClick:()=>Ps(G.class_name),title:"Rename class",children:e.jsx(Ft,{className:"h-4 w-4"})}),!ds&&e.jsx(wt,{children:e.jsxs(Us,{children:[e.jsx(zs,{asChild:!0,children:e.jsx("span",{className:"inline-flex",children:e.jsx(ct,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(Vs,{children:"Class names are locked because this event has race results recorded, or the event date has passed."})]})}),e.jsx(w,{variant:"ghost",size:"sm",onClick:()=>bs(G.class_name),children:e.jsx(ws,{className:"h-4 w-4 text-destructive"})})]})})]},G.class_name)})})]})})]})]}),e.jsx(et,{open:!!se,onOpenChange:G=>{G||ue(null)},children:e.jsxs(st,{children:[e.jsxs(Et,{children:[e.jsx(tt,{children:"Rename class?"}),e.jsxs(at,{children:["Rename ",e.jsx("strong",{children:se==null?void 0:se.oldName})," to ",e.jsx("strong",{children:se==null?void 0:se.newName}),".",e.jsx("br",{}),e.jsx("br",{}),"This will update the timing system (via the sync queue) and rewrite"," ",e.jsx("strong",{children:(se==null?void 0:se.regCount)??0})," registration field",(se==null?void 0:se.regCount)===1?"":"s"," that reference the old name.",e.jsx("br",{}),e.jsx("br",{}),"Allowed only because this event is in the future and has no race results yet."]})]}),e.jsxs(Mt,{children:[e.jsx(nt,{disabled:ve,children:"Cancel"}),e.jsxs(rt,{onClick:G=>{G.preventDefault(),O()},disabled:ve,children:[ve?e.jsx(oe,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Rename"]})]})]})}),e.jsx(et,{open:!!Te,onOpenChange:G=>{!G&&!Ye&&Fe(null)},children:e.jsxs(st,{children:[e.jsxs(Et,{children:[e.jsx(tt,{children:"Remove class?"}),e.jsxs(at,{children:["Remove ",e.jsx("strong",{children:Te})," from ",e.jsx("strong",{children:p}),"?",e.jsx("br",{}),e.jsx("br",{}),"The class and any rider entries in it will be flagged for deleti
47on. The change will appear in the timing system on the next sync.",e.jsx("br",{}),e.jsx("br",{}),"Allowed only because this event is in the future and the class has no race results."]})]}),e.jsxs(Mt,{children:[e.jsx(nt,{disabled:Ye,children:"Cancel"}),e.jsxs(rt,{onClick:G=>{G.preventDefault(),Ts()},disabled:Ye,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:[Ye?e.jsx(oe,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Remove"]})]})]})})]})}function Nd(){const{currentOrganization:s}=Je(),[n,i]=a.useState(null),[t,d]=a.useState(null),[r,x]=a.useState(null),[c,o]=a.useState(""),[m,p]=a.useState("10"),[u,l]=a.useState(!1),[N,j]=a.useState(!1),[g,y]=a.useState(!1),{data:k}=Qt(),S=fc(k,n,t);a.useEffect(()=>{r&&(s!=null&&s.id)&&f()},[r,s==null?void 0:s.id]);const f=async()=>{if(!(!r||!(s!=null&&s.id))){j(!0);try{const{data:M,error:T}=await z.functions.invoke("load-race-start-time",{body:{organization_id:s.id,event_name:r}});if(T)throw T;M&&(o(M.race_start_time||""),p(String(M.default_race_duration_minutes||10)))}catch(M){console.error("Error loading race start time:",M)}finally{j(!1)}}},h=async()=>{if(!r){be({title:"Please select an event first",variant:"destructive"});return}if(!c){be({title:"Please enter a start time",variant:"destructive"});return}if(!(s!=null&&s.id)){be({title:"No organization selected",variant:"destructive"});return}y(!0);try{const M=u&&S.length>0?Array.from(new Set(S.map(L=>L.event_name))):[r];let T=0;const C=[];for(const L of M){const{error:Q}=await z.functions.invoke("save-race-start-time",{body:{organization_id:s.id,event_name:L,start_time:c,duration_minutes:parseInt(m,10)}});Q?C.push(L):T++}C.length===0?be({title:"Schedule saved",description:M.length>1?`Race start time set to ${c} for ${T} events in the series`:`Race start time set to ${c} with ${m} minute duration`}):be({title:`Saved ${T} of ${M.length}`,description:`Failed: ${C.join(", ")}`,variant:"destructive"})}catch(M){console.error("Error saving race start time:",M),be({title:"Error saving schedule",description:M.message||"Failed to save race start time",variant:"destructive"})}finally{y(!1)}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsxs(Ee,{className:"flex items-center gap-2",children:[e.jsx(yt,{className:"h-5 w-5"}),"Race Schedule Settings"]}),e.jsx(ns,{children:"Set race start time and duration for an event"})]}),e.jsx(xe,{children:e.jsx(Ot,{selectedYear:n,selectedSeries:t,selectedEvent:r,selectedClass:null,onYearChange:i,onSeriesChange:d,onEventChange:x,onClassChange:()=>{},hideClassSelector:!0})})]}),r&&e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsx(Ee,{children:"Set Race Start Time"}),e.jsx(ns,{children:"Configure when races begin and the default race duration"})]}),e.jsx(xe,{children:N?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(oe,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-end gap-6",children:[e.jsxs("div",{className:"min-w-[180px]",children:[e.jsx(v,{htmlFor:"raceStartTime",children:"Start Time"}),e.jsx(A,{id:"raceStartTime",type:"time",value:c,onChange:M=>o(M.target.value),className:"w-full"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"When the first race begins"})]}),e.jsxs("div",{className:"min-w-[180px]",children:[e.jsx(v,{htmlFor:"raceDuration",children:"Race Duration (minutes)"}),e.jsx(A,{id:"raceDuration",type:"number",value:m,onChange:M=>p(M.target.value),min:1,max:60,className:"w-full"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Default time per race"})]})]}),c&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsxs(ie,{variant:"outline",className:"font-mono",children:[e.jsx(yt,{className:"h-3 w-3 mr-1"}),"First race: ",c]}),e.jsxs(ie,{variant:"secondary",children:[m," min per race"]})]}),S.length>1&&e.jsxs("div",{className:"flex items-start gap-2 rounded-md border bg-muted/40 p-3",children:[e.jsx(As,{id:"applyToSeries",checked:u,onCheckedChange:M=>l(M===!0),className:"mt-0.5"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(v,{htmlFor:"applyToSeries",className:"cursor-pointer font-medium",children:"Apply this 
47start time to all races in the series"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Will update ",S.length,' events in "',t,'" with the same start time and duration.']})]})]}),e.jsxs(w,{onClick:h,disabled:g,children:[g?e.jsx(oe,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Qa,{className:"h-4 w-4 mr-2"}),u&&S.length>1?`Save for ${S.length} Events`:"Save Start Time"]})]})})]})]})}function rl({onComplete:s,onSkip:n,embedded:i=!1,availableSeriesNames:t=[],currentLinkedSeries:d=null,onSeriesLink:r}){const x=i&&!!r,{currentOrganization:c}=Je(),{data:o=[]}=ba(),{data:m=[]}=Qt(),{data:p=[]}=Pr(c==null?void 0:c.id),u=o.length>0,l=m.length>0,N=p.length>0,j=[{key:"series",label:"Series",number:1},{key:"event",label:"Event Setup",number:2},{key:"settings",label:"Settings",number:3},...x?[{key:"link",label:"Link",number:4}]:[]],[g,y]=a.useState(0),[k,S]=a.useState(null),[f,h]=a.useState(null),[M,T]=a.useState(null),[C,L]=a.useState(null),[Q,Z]=a.useState(null),[R,E]=a.useState(""),[$,b]=a.useState(""),[I,V]=a.useState("details"),[H,Y]=a.useState(!1),[W,te]=a.useState([]),[B,le]=a.useState(null),[Me,_]=a.useState(null),[X,F]=a.useState(null),[ne,J]=a.useState(null),[_e,me]=a.useState(null),[$e,ee]=a.useState(null),pe=a.useCallback(Le=>{y(Le)},[]),je=()=>{g<j.length-1&&pe(g+1)},we=()=>{g>0&&pe(g-1)},U=()=>{s&&R&&$?s(R,$):s?n==null||n():y(0)},se=Le=>{me(Le),Le&&ne&&(E(ne),b(Le))},ue=(Le,ye,Ze)=>{_(Le),le(ye),E(Le),b(ye),Ze?V("addMore"):(V("classes"),T(null))},ve=()=>{V("addMore")},he=Le=>{Le==="done"?(Me&&B&&te(ye=>[...ye,{series:Me,event:B}]),Y(!0),je()):Le==="new"?(Me&&B&&te(ye=>[...ye,{series:Me,event:B}]),h("create"),le(null),V("details"),T(null),L(null),ee(null)):Le==="copy"&&(Me&&B&&te(ye=>[...ye,{series:Me,event:B}]),ee(B),h("copy"),le(null),V("details"),T(null),L(null))},ze=(g+1)/j.length*100,He=x&&g===j.length-1,Ve=[{key:"details",label:"Event Details"},{key:"classes",label:"Classes & Schedule"},{key:"addMore",label:"Done"}],Ue=Ve.findIndex(Le=>Le.key===I),de=g===1&&!H;return e.jsxs("div",{className:Cs("space-y-6",i&&"space-y-4"),children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex items-center justify-between",children:j.map((Le,ye)=>e.jsxs("button",{onClick:()=>pe(ye),className:Cs("flex items-center gap-1.5 text-sm font-medium transition-colors",ye===g?"text-primary":ye<g?"text-primary/60":"text-muted-foreground"),children:[e.jsx("div",{className:Cs("flex items-center justify-center h-7 w-7 rounded-full text-xs font-bold border-2 transition-colors",ye===g?"bg-primary text-primary-foreground border-primary":ye<g?"bg-primary/20 text-primary border-primary/40":"bg-muted text-muted-foreground border-border"),children:ye<g?e.jsx(Os,{className:"h-3.5 w-3.5"}):Le.number}),e.jsx("span",{className:"hidden sm:inline",children:Le.label})]},Le.key))}),e.jsx(Ka,{value:ze,className:"h-1.5"})]}),W.length>0&&g===1&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Events created:"}),W.map((Le,ye)=>e.jsx(ie,{variant:"secondary",className:"text-xs",children:Le.event},ye))]}),g===0&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsx(Ee,{children:"Series Setup"}),e.jsx(ns,{children:"Choose or create the series for your race events"})]}),e.jsxs(xe,{className:"space-y-3",children:[e.jsx(Zs,{icon:e.jsx(ld,{className:"h-5 w-5"}),label:"Create a new series",description:"Start fresh with a brand new race series",selected:k==="create",onClick:()=>S("create")}),e.jsx(Zs,{icon:e.jsx($n,{className:"h-5 w-5"}),label:"Use an existing series",description:u?"Add races to a series you've already created":"No series found — create one first",selected:k==="existing",onClick:()=>{if(!u){S("existing");return}S("existing"),pe(1)}}),k==="existing"&&!u&&e.jsxs(ht,{variant:"destructive",className:"border-destructive/50",children:[e.jsx(Kt,{className:"h-4 w-4"}),e.jsx(xt,{children:"There are no series in the system yet. Please create a new series first."})]}),n&&e.jsx(Zs,{icon:e.jsx(gn,{className:"h-5 w-5"}),label:"Skip — no timing integration",description:"You can configure timing integration later",selected:!1,onClick:()=>n()})]})]}),k==="create"&&e.jsx(Ca,{visibleSection:"create-series"})]}),g===1&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex items-center gap-1 text-xs",children:Ve.map((Le,ye)=>e.jsxs("div",{className:"flex items-center gap-1",children:[ye>0&&e.jsx(Hs,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("button",{onClick:()=>
47{ye<=Ue&&V(Le.key)},className:Cs("px-2 py-1 rounded-md font-medium transition-colors",Le.key===I?"bg-primary text-primary-foreground":ye<Ue?"text-primary cursor-pointer hover:bg-primary/10":"text-muted-foreground"),children:Le.label})]},Le.key))}),I==="details"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsx(Ee,{children:"Set up your event"}),e.jsx(ns,{children:"Create a new race, edit an existing one, or copy from a previous event"})]}),e.jsxs(xe,{className:"space-y-3",children:[e.jsx(Zs,{icon:e.jsx(Es,{className:"h-5 w-5"}),label:"Create a new race",description:"Set up a brand new race event with all the details",selected:f==="create",onClick:()=>{h("create"),ee(null)}}),e.jsx(Zs,{icon:e.jsx(Ha,{className:"h-5 w-5"}),label:"Edit an existing race",description:l?"Load and modify an event you've already created":"No races found — create one first",selected:f==="edit",onClick:()=>{h("edit"),ee(null)}}),e.jsx(Zs,{icon:e.jsx(Nt,{className:"h-5 w-5"}),label:"Copy an existing race",description:l?"Duplicate a previous race's settings, classes, and race order":"No races found — create one first",selected:f==="copy",onClick:()=>h("copy")}),e.jsx(Zs,{icon:e.jsx(Za,{className:"h-5 w-5"}),label:"Link an existing race",description:l?"Select an existing race from the timing system to connect to this event":"No races found — create one first",selected:f==="link",onClick:()=>h("link")}),(f==="edit"||f==="copy"||f==="link")&&!l&&e.jsxs(ht,{variant:"destructive",className:"border-destructive/50",children:[e.jsx(Kt,{className:"h-4 w-4"}),e.jsx(xt,{children:"There are no races in the system yet. Please create a new race first."})]})]})]}),f==="create"&&e.jsx(Ca,{visibleSection:"create",preselectedSeries:Me,onEventSaved:ue}),f==="edit"&&l&&e.jsx(Ca,{visibleSection:"edit",onEventSaved:ue}),f==="copy"&&l&&e.jsx(Ca,{visibleSection:"copy",preselectedSeries:Me,onEventSaved:ue}),f==="link"&&l&&e.jsx(re,{children:e.jsxs(xe,{className:"pt-6 space-y-4",children:[e.jsx(Ot,{selectedYear:X,selectedSeries:ne,selectedEvent:_e,selectedClass:null,onYearChange:Le=>{F(Le),J(null),me(null)},onSeriesChange:Le=>{J(Le),me(null),Le&&E(Le)},onEventChange:se,onClassChange:()=>{},hideClassSelector:!0}),_e&&ne&&e.jsxs("div",{className:"bg-primary/10 rounded-lg p-3 text-sm flex items-center gap-2",children:[e.jsx(Os,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"font-medium text-primary",children:["Ready to link: ",_e," (",ne,")"]})]})]})})]}),I==="classes"&&B&&e.jsx(bd,{seriesName:Me,eventName:B,orgId:(c==null?void 0:c.id)??null,hasEvents:l,hasTemplates:N,classesChoice:M,setClassesChoice:T,onContinue:ve}),I==="addMore"&&e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsx(Ee,{children:"Add another event to this series?"}),e.jsxs(ns,{children:["You can create more events in the same series, or continue to settings.",B&&e.jsxs("span",{className:"block mt-1 text-foreground font-medium",children:["Just completed: ",B]})]})]}),e.jsxs(xe,{className:"space-y-3",children:[e.jsx(Zs,{icon:e.jsx(Es,{className:"h-5 w-5"}),label:"Yes, create a new event",description:"Start fresh with a new event in the same series",selected:!1,onClick:()=>he("new")}),e.jsx(Zs,{icon:e.jsx(Nt,{className:"h-5 w-5"}),label:"Yes, copy this event",description:`Duplicate "${B||"this event"}" with the same settings`,selected:!1,onClick:()=>he("copy")}),e.jsx(Zs,{icon:e.jsx(Hs,{className:"h-5 w-5"}),label:"No, continue to settings",description:"Move on to schedule and video configuration",selected:!1,onClick:()=>he("done")})]})]})]}),g===2&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsx(Ee,{children:"Any additional settings?"}),e.jsx(ns,{children:"Configure timing, scheduling, and video for your event"})]}),e.jsxs(xe,{className:"space-y-3",children:[e.jsx(Zs,{icon:e.jsx(yt,{className:"h-5 w-5"}),label:"Set start times & schedule",description:"Configure when races begin and the duration per race",selected:Q==="schedule",onClick:()=>Z("schedule")}),e.jsx(Zs,{icon:e.jsx(jc,{className:"h-5 w-5"}),label:"Configure video / YouTube",description:"Set up live streaming broadcast codes",selected:Q==="video",onClick:()=>Z("video")}),e.jsx(Zs,{icon:e.jsx(gn,{className:"h-5 w-5"}),label:"Skip — I'm done",description:"You can configure these settings anytime",selected:Q==="skip",onClick:()=>Z("skip")})]})]}),Q==="schedule"&&e.jsx(Nd,{}),Q==="video"&&e.jsx(ic,{})]}),He&&e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsxs(Ee,{className:"flex items-center gap-2",children:[e.jsx(Tt,{className:"h-5 w-5"})," Connect to Series"]}),e.jsxs(ns,{children:["Select which series this event should be linked to for Kiosk Mode and registration sync.",R&&` We recommend linking to "${R}" based on your selections above.`]})]}),e.jsxs(xe,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{children:"Linked Series"}),e.jsxs(Pe,{value:d||"none",onValueChange:Le=>{const ye=Le==="none"?null:Le;r==null||r(ye)},children:[e.jsx(Ie,{className:"bg-background",children:e.jsx(qe,{placeholder:"Select a series..."})}),e.jsxs(Be,{className:"bg-popover border-border z-50",children:[e.jsx(ae,{value:"none",children:"None (Unlink)"}),t.map(Le=>e.jsx(ae,{value:Le,children:Le},Le))]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"All races in this series will resolve to this event in Kiosk Mode. If you just created a new series, select it here."})]}),d&&e.jsxs("div",{className:"bg-primary/10 rounded-lg p-3 text-sm flex items-center gap-2",children:[e.jsx(Os,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"font-medium text-primary",children:["Linked to: ",d]})]})]})]}),!de&&e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsxs(w,{variant:"outline",onClick:we,disabled:g===0,className:"gap-2",children:[e.jsx(ya,{className:"h-4 w-4"}),"Back"]}),g<j.length-1?e.jsxs(w,{onClick:je,className:"gap-2",children:["Next",e.jsx(Hs,{className:"h-4 w-4"})]}):e.jsxs(w,{onClick:U,className:"gap-2",children:[e.jsx(Os,{className:"h-4 w-4"}),s?"Finish & Link":"Finish"]}
47)]})]})}function bd({seriesName:s,eventName:n,orgId:i,hasEvents:t,hasTemplates:d,classesChoice:r,setClassesChoice:x,onContinue:c}){const{data:o,isLoading:m}=ms({queryKey:["race-mgmt-series-event-id",i,s],queryFn:async()=>{if(!i||!s)return null;const{data:p,error:u}=await z.from("events").select("id").eq("organization_id",i).eq("name",s).is("parent_event_id",null).maybeSingle();return u?null:(p==null?void 0:p.id)??null},enabled:!!i&&!!s,staleTime:6e4});return!m&&!o?e.jsxs("div",{className:"space-y-4",children:[e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsx(Ee,{children:"How do you want to set up classes?"}),e.jsxs(ns,{children:["Classes define the racing categories for"," ",e.jsx("span",{className:"font-semibold text-foreground",children:n})]})]}),e.jsxs(xe,{className:"space-y-3",children:[e.jsx(Zs,{icon:e.jsx(Ha,{className:"h-5 w-5"}),label:"Add classes manually",description:"Create classes one at a time",selected:r==="manual",onClick:()=>x("manual")}),e.jsx(Zs,{icon:e.jsx(cd,{className:"h-5 w-5"}),label:"Import classes from another race",description:t?"Copy an existing class list from a previous event":"No races found — create one first",selected:r==="import",onClick:()=>x("import")}),e.jsx(Zs,{icon:e.jsx(od,{className:"h-5 w-5"}),label:"Import from templates",description:d?"Use your saved class template list":"No class templates found — add templates first",selected:r==="template",onClick:()=>x("template")}),e.jsx(Zs,{icon:e.jsx(gn,{className:"h-5 w-5"}),label:"Skip — I'll do this later",description:"You can always come back and set up classes",selected:r==="skip",onClick:()=>{x("skip"),c()}})]})]}),r&&r!=="skip"&&!(r==="import"&&!t)&&!(r==="template"&&!d)&&e.jsxs(e.Fragment,{children:[e.jsx(vd,{preselectedEvent:n,preselectedSeries:s,initialMethod:r==="manual"?"manual":r==="import"?"copy":r==="template"?"template":void 0}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(w,{onClick:c,className:"gap-2",children:["Continue",e.jsx(Hs,{className:"h-4 w-4"})]})})]})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsx(Ee,{children:"Classes & Schedule"}),e.jsxs(ns,{children:["Pick classes & build the schedule on one round (your template), then copy them to every other round in ",e.jsx("span",{className:"font-semibold text-foreground",children:s}),". This is the single place to manage rounds for this series."]})]}),e.jsx(xe,{children:e.jsx(Ir,{seriesEventId:o??null})})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(w,{onClick:c,className:"gap-2",children:["Continue",e.jsx(Hs,{className:"h-4 w-4"})]})})]})}const yd=s=>({class_name:"",distance_value:"",distance_unit:s==="running"?"km":"",category_code:"",wave_start_time:"",price:"",max_participants:""});function _d({eventType:s,terms:n,classes:i,onChange:t}){const d=s==="running",r=s==="cycling",x=d?"Distance":r?"Category":"Class",c=d?"Distances":r?"Categories":"Classes",o=(u,l)=>{t(i.map((N,j)=>j===u?{...N,...l}:N))},m=u=>t(i.filter((l,N)=>N!==u)),p=()=>t([...i,yd(s)]);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-center mb-2",children:[e.jsxs("h3",{className:"text-lg font-semibold",children:["Define your ",c.toLowerCase()]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Each ",x.toLowerCase()," has its own price. Racers will pick one when they register."]})]}),i.length===0&&e.jsxs("div",{className:"text-sm text-muted-foreground italic text-center py-6 border border-dashed rounded-md",children:["No ",c.toLowerCase()," yet. Add your first one below."]}),e.jsx("div",{className:"space-y-3",children:i.map((u,l)=>e.jsx("div",{className:"border rounded-md p-3 space-y-3 bg-muted/30",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("div",{className:"flex-1 grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5 sm:col-span-2",children:[e.jsxs(v,{children:[x," name *"]}),e.jsx(A,{value:u.class_name,placeholder:d?"e.g. 10K":r?"e.g. Cat 3 Men":"",onChange:N=>o(l,{class_name:N.target.value})})]}),d&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(v,{children:"Distance value"}),e.jsx(A,{type:"number",step:"0.01",value:u.distance_value,onChange:N=>o(l,{distance_value:N.target.value}),placeholder:"e.g. 10"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(v,{children:"Unit"}),e.jsxs(Pe,{value:u.distance_unit||"km",onValueChange:N=>o(l,{distance_unit:N}),children:[e.jsx(Ie,{children:e.jsx(qe,{})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"km",children:"km"}),e.jsx(ae,{value:"mi",children:"mi"}),e.jsx(ae,{value:"m",children:"m"})]})]})]})]}),r&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(v,{children:"Category code (optional)"}),e.jsx(A,{value:u.category_code,onChange:N=>o(l,{category_code:N.target.value}),placeholder:"e.g. Cat 3, Pro/1, Junior"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(v,{children:"Price (USD) *"}),e.jsx(A,{type:"number",step:"0.01",min:"0",value:u.price,onChange:N=>o(l,{price:N.target.value}),placeholder:"0.00"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(v,{children:"Max participants (optional)"}),e.jsx(A,{type:"number",min:"0",value:u.max_participants,onChange:N=>o(l,{max_participants:N.target.value}),placeholder:"No limit"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(v,{children:"Wave start time (optional)"}),e.jsx(A,{type:"time",value:u.wave_start_time,onChange:N=>o(l,{wave_start_time:N.target.value})})]})]}),e.jsx(w,{variant:"ghost",size:"icon",onClick:()=>m(l),"aria-label":`Remove ${x.toLowerCase()}`,children:e.jsx(ws,{className:"h-4 w-4"})})]})},l))}),e.jsxs(w,{variant:"outline",onClick:p,className:"w-full",children:[e.jsx(Es,{className:"mr-2 h-4 w-4"})," Add ",x.toLowerCase()]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:`Tip: After the event is created, drop a "Distance / Category Picker" element into your registration form (Form Builder) wherever you'd like racers to choose.`})]})}const wd={motocross:zi,enduro:Vi,"flat-track":Oi,"hill-climb":Gi,trials:Yi,vintage:Ki,"running-race":Hi,triathlon:Qi,cycling:Wi,swimming:Zi,"obstacle-course":Ji,"golf-tournament":Xi,"charity-walk":el,conference:sl,"youth-sports":tl,"fitness-class":al,basic:nl},rn={selectedTemplate:null,templateAnswers:{},name:"",slug:"",event_date:"",location:"",venue_name:"",description:"",max_participants:100,regular_price:0,late_price:null,override_fees:!1,flat_service_fee:null,percentage_service_fee:null,pass_cc_fees:null,mysql_series_name:"",mysql_event_name:"",is_published:!1,image_url:"",track_info:"",track_id:null,classes:[],rounds:[]},Sd={Bike:Gr,Timer:qa,Trophy:la,Heart:vc,Award:Mn,Users:Gs,FileText:jt}
47,ka=[{id:0,title:"Template",icon:Nc,description:"Choose a form template"},{id:1,title:"Customize",icon:bc,description:"Configure template options"},{id:2,title:"Basic Info",icon:At,description:"Event name, date, and location"},{id:3,title:"Fees",icon:Na,description:"Service and processing fees"},{id:4,title:"Integration",icon:Tt,description:"Link to timing system"},{id:5,title:"Distances",icon:la,description:"Define distances or categories"},{id:6,title:"Review",icon:Os,description:"Review and publish"}];function Cd({open:s,onOpenChange:n}){var B,le,Me;const{toast:i}=Ht(),t=da(),d=Ms(),{currentOrganization:r}=Je(),{isTimingEnabled:x}=Wt(),c=kl(),o=Fr(),m=Gt(),p=o==="running"||o==="cycling",u=!p,[l,N]=a.useState(0),[j,g]=a.useState(rn),[y,k]=a.useState(null),[S,f]=a.useState(!1),[h,M]=a.useState(null);a.useState(!1),ms({queryKey:["mysql-events",r==null?void 0:r.id],queryFn:async()=>{if(!(r!=null&&r.id))return[];const{data:_,error:X}=await z.functions.invoke("fetch-timing-events",{body:{organization_id:r.id}});if(X)throw X;return(_==null?void 0:_.events)||[]},enabled:!!(r!=null&&r.id)&&x});const{data:T}=ms({queryKey:["fee-settings"],queryFn:async()=>{const{data:_,error:X}=await z.from("fee_settings").select("*").limit(1).single();if(X)throw X;return _}}),C=ks({mutationFn:async _=>{const{data:X,error:F}=await z.from("events").insert({name:_.name,slug:_.slug||null,description:_.description||null,event_date:_.event_date,location:_.location,venue_name:_.venue_name||null,max_participants:_.max_participants,track_info:_.track_info||null,track_id:_.track_id,image_url:_.image_url||null,is_published:_.is_published,mysql_series_name:_.mysql_series_name||null,mysql_event_name:_.mysql_event_name||null,regular_price:_.regular_price,late_price:_.late_price,override_fees:_.override_fees,flat_service_fee:_.override_fees?_.flat_service_fee:null,percentage_service_fee:_.override_fees?_.percentage_service_fee:null,pass_cc_fees:_.override_fees?_.pass_cc_fees:null,organization_id:(r==null?void 0:r.id)||null}).select().single();if(F)throw F;if(h&&(r!=null&&r.id)){const pe=_.event_date.split("-"),je={...h,event_date_year:pe[0]||h.event_date_year,event_date_month:String(parseInt(pe[1]||"0"))||h.event_date_month,event_date_day:String(parseInt(pe[2]||"0"))||h.event_date_day,event_location:_.location||h.event_location,track_name:_.venue_name||h.track_name};try{await z.functions.invoke("save-event",{body:{organization_id:r.id,event_data:je}})}catch(we){console.error("Failed to sync event to MySQL staging:",we)}}const J=(_.rounds||[]).filter(pe=>{var je;return((je=pe.name)==null?void 0:je.trim())&&pe.event_date}).length>0?"series":"single",_e=_.selectedTemplate?mc(ma(_.selectedTemplate,_.templateAnswers),J):[],$e=_e.some(pe=>uc.includes(pe.field_type))?_e:[..._e,...pn(o,J)];if($e.length>0){const pe=$e.map((we,U)=>({event_id:X.id,field_type:we.field_type,label:we.label,placeholder:we.placeholder||null,help_text:we.help_text||null,is_required:we.is_required||!1,field_order:U,width:we.width||"full",options:we.options?we.options:null})),{error:je}=await z.from("form_fields").insert(pe);je&&console.error("Error creating form fields:",je)}if(_.classes&&_.classes.length>0){const pe=_.classes.filter(je=>je.class_name.trim().length>0).map((je,we)=>({event_id:X.id,class_name:je.class_name.trim(),distance_value:je.distance_value?Number(je.distance_value):null,distance_unit:je.distance_unit||null,category_code:je.category_code||null,wave_start_time:je.wave_start_time||null,price:je.price!==""?Number(je.price):null,max_participants:je.max_participants!==""?Number(je.max_participants):null,sort_order:we}));if(pe.length>0){const{error:je}=await z.from("event_classes").insert(pe);je&&console.error("Error creating event classes:",je)}}const ee=(_.rounds||[]).filter(pe=>pe.name.trim().length>0&&pe.event_date);if(ee.length>0){const pe=ee.map((U,se)=>({name:U.name.trim(),event_date:U.event_date,location:_.location,venue_name:_.venue_name||null,track_id:_.track_id,regular_price:_.regular_price,max_participants:_.max_participants,is_published:_.is_published,organization_id:(r==null?void 0:r.id)||null,parent_event_id:X.id,event_kind:"round",child_race_index:se+1,is_child_race:!0})),{data:je,error:we}=await z.from("events").insert(pe).select("id");if(we)console.error("Failed to create round events:",we),i({title:"Series created with errors",description:`Parent event created, but rounds failed: ${we.message}`,variant:"destructive"});else if(je&&je.length>0){const U=pn(o,"round");if(U.length>0){const se=je.flatMap(ve=>U.map((he,ze)=>({event_id:ve.id,field_type:he.field_type,label:he.label,placeholder:he.placeholder||null,help_text:he.help_text||null,is_required:he.is_required||!1,field_order:ze,width:he.width||"full",options:he.options?he.options:null}))),{error:ue}=await z.from("form_fields").insert(se);ue&&console.error("Failed to seed round form fields:",ue)}}await z.from("events").update({event_kind:"series"}).eq("id",X.id)}if(!h&&ee.length===0&&(r!=null&&r.id)&&X.name)try{const{isOrgMysqlConfigured:pe,pushEventToMysql:je}=await Cn(async()=>{const{isOrgMysqlConfigured:we,pushEventToMysql:U}=await import("./mysqlEventBridge-i9SJNJp2.js");return{isOrgMysqlConfigured:we,pushEventToMysql:U}},__vite__mapDeps([0,1,2]));await pe(r.id)&&await je({orgId:r.id,event:{id:X.id,name:X.name,event_date:_.event_date,location:_.location,venue_name:_.venue_name,mysql_event_name:_.mysql_event_name||null,mysql_series_name:_.mysql_series_name||null},seriesName:_.mysql_series_name||null})}catch(pe){console.error("Failed to push new event to MySQL:",pe)}return X},onSuccess:_=>{d.invalidateQueries({queryKey:["admin-events"]}),i({title:"Event created successfully!"}),n(!1),N(0),g(rn),k(null),M(null),t(`/admin/events/${_.id}/form-builder`)},onError:_=>{i({title:"Error creating event",description:_.message,variant:"destructive"})}}),L=()=>{let _=l+1;l===0&&!I&&(_=2),_===4&&c&&(_=5),_===5&&u&&(_=6),_<ka.length&&N(_)},Q=()=>{let _=l-1;l===2&&!I&&(_=0),_===5&&u&&(_=4),_===4&&c&&(_=3),_>=0&&N(_)},Z=()=>{n(!1),N(0),g(rn),k(null),M(null)},R=()=>{C.mutate(j)},E=_=>{const X={};_!=null&&_.questions&&_.questions.forEach(F=>{X[F.id]=F.default}),g({...j,selectedTemplate:_,templateAnswers:X})},$=(_,X)=>{g({...j,templateAnswers:{...j.templateAnswers,[_]:X}})},b=(_,X)=>{const F=j.templateAnswers[_],ne=Array.isArray(F)?F:[],J=ne.includes(X)?ne.filter(_e=>_e!==X):[...ne,X];$(_,J)},I=((B=j.selectedTemplate)==null?void 0:B.questions)&&j.selectedTemplate.questions.length>0,V=S?rr:rr.filter(_=>!_.eventTypes||_.eventTypes.length===0||_.eventTypes.includes(o)),H=y?V.filter(_=>_.category===y):V,Y=()=>{switch(l){case 0:return!0;case 1:return!0;case 2:return j.name&&j.event_date&&j.location;case 3:return!0;case 4:return!0;case 5:return j.classes.length>0&&j.classes.every(_=>_.class_name.trim().length>0&&_.price!=="");case 6:return!0;default:return!1}},W=ka.filter(_=>_.id!==4&&!(u&&_.id===5)),te=(l+1)/ka.length*100;return e.jsx(ts,{open:s,onOpenChange:n,children:e.jsxs(as,{className:"max-w-3xl max-h-[90vh] overflow-y-auto bg-card border-border",children:[e.jsx(rs,{children:e.jsx(is,{className:"font-display text-xl flex items-center gap-2",children:"Create New Event"})}),e.jsxs("div",{className:"mb-6",children:[e.jsx(Ka,{value:te,className:"h-2"}),e.jsx("div",{className:"flex justify-between mt-4",children:W.map(_=>e.jsxs("div",{className:`flex flex-col items-center gap-1 ${_.id===l?"text-primary":_.id<l?"text-success":"text-muted-foreground"}`,children:[e.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center border-2 ${_.id===l?"border-primary bg-primary/10":_.id<l?"border-success bg-success/10":"border-muted"}`,children:e.jsx(_.icon,{className:"w-4 h-4"})}),e.jsx("span",{className:"text-xs font-medium hidden sm:block",children:_.title})]},_.id))})]}),e.jsxs("div",{className:"min-h-[300px]",children:[l===0&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-center mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Choose a Template"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Start with a pre-built form or create from scratch"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(w,{variant:y===null?"default":"outline",size:"sm",onClick:()=>k(null),children:"All"}),hc.map(_=>e.jsx(w,{variant:y===_?"default":"outline",size:"sm",onClick:()=>k(_),children:_},_)),e.jsx("div",{className:"ml-auto",children:e.jsx(w,{variant:S?"default":"outline",size:"sm",onClick:()=>f(_=>!_),title:`Currently showing templates for: ${o}`,children:S?"Showing all templates":`Only ${o} templates`})})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:[e.jsx(re,{className:`curs
47or-pointer transition-colors ${j.selectedTemplate===null?"border-primary bg-primary/5 ring-2 ring-primary":"hover:border-primary/50 hover:bg-primary/5"}`,onClick:()=>E(null),children:e.jsxs(ke,{className:"p-3",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("div",{className:"p-2 rounded-lg bg-muted",children:e.jsx(jt,{className:"h-4 w-4 text-muted-foreground"})}),j.selectedTemplate===null&&e.jsx("div",{className:"p-1 rounded-full bg-primary",children:e.jsx(Os,{className:"h-3 w-3 text-primary-foreground"})})]}),e.jsx(Ee,{className:"text-xs mt-2",children:"Blank Form"})]})}),H.map(_=>{var ne;Sd[_.icon]||jt;const X=((ne=j.selectedTemplate)==null?void 0:ne.id)===_.id,F=wd[_.id];return e.jsxs(re,{className:`cursor-pointer transition-all overflow-hidden ${X?"border-primary ring-2 ring-primary":"hover:border-primary/50 hover:shadow-lg"}`,onClick:()=>E(_),children:[e.jsxs("div",{className:"relative h-16 overflow-hidden",children:[F?e.jsx("img",{src:F,alt:_.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:`w-full h-full bg-gradient-to-br ${_.bannerGradient}`}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/60 to-transparent"}),X&&e.jsx("div",{className:"absolute top-1.5 right-1.5 p-1 rounded-full bg-primary",children:e.jsx(Os,{className:"h-3 w-3 text-primary-foreground"})}),e.jsx("span",{className:"absolute bottom-1.5 left-2 text-lg drop-shadow-lg",children:_.bannerEmoji})]}),e.jsxs(ke,{className:"p-2",children:[e.jsx(Ee,{className:"text-xs",children:_.name}),e.jsxs(ie,{variant:"secondary",className:"text-[10px] w-fit",children:[_.fields.length," fields"]})]})]},_.id)})]}),j.selectedTemplate&&e.jsx("div",{className:"mt-4",children:e.jsx(qs,{className:"h-[400px]",children:e.jsx(jd,{template:j.selectedTemplate})})}),!j.selectedTemplate&&e.jsxs("div",{className:"mt-4 p-8 border rounded-xl bg-muted/20 text-center",children:[e.jsx(jt,{className:"h-12 w-12 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("h4",{className:"text-base font-medium text-muted-foreground",children:"Blank Form Selected"}),e.jsx("p",{className:"text-sm text-muted-foreground/70 mt-1 max-w-md mx-auto",children:"You'll build your form from scratch using our form builder after creating the event."})]})]}),l===1&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"text-center mb-6",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Customize Your Template"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Answer a few questions to tailor the form to your event"})]}),(Me=(le=j.selectedTemplate)==null?void 0:le.questions)==null?void 0:Me.map(_=>xc(_,j.templateAnswers)?e.jsxs("div",{className:"p-4 bg-muted/30 rounded-lg space-y-3 animate-in fade-in-50 duration-200",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Dn,{className:"h-5 w-5 text-primary mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1",children:[e.jsx(v,{className:"text-base font-medium",children:_.question}),_.helpText&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:_.helpText})]})]}),e.jsxs("div",{className:"ml-7",children:[_.type==="select"&&_.options&&e.jsxs(Pe,{value:String(j.templateAnswers[_.id]??_.default),onValueChange:F=>$(_.id,Number(F)),children:[e.jsx(Ie,{className:"w-full max-w-xs",children:e.jsx(qe,{})}),e.jsx(Be,{children:_.options.map(F=>e.jsx(ae,{value:String(F.value),children:F.label},String(F.value)))})]}),_.type==="checkbox"&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ds,{id:_.id,checked:j.templateAnswers[_.id]===!0,onCheckedChange:F=>$(_.id,F)}),e.jsx(v,{htmlFor:_.id,className:"text-sm",children:j.templateAnswers[_.id]===!0?"Yes":"No"})]}),_.type==="number"&&e.jsx(A,{type:"number",min:_.min,max:_.max,value:Number(j.templateAnswers[_.id]??_.default),onChange:F=>$(_.id,parseInt(F.target.value)||0),className:"w-32"}),_.type==="multiselect"&&_.options&&e.jsx("div",{className:"space-y-2",children:_.options.map(F=>{const ne=j.templateAnswers[_.id],_e=(Array.isArray(ne)?ne:[]).includes(F.value);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ds,{id:`${_.id}-${F.value}`,checked:_e,onCheckedChange:()=>b(_.id,F.value)}),e.jsx(v,{htmlFor:`${_.id}-${F.value}`,className:`text-sm ${_e?"text-foreground":"text-muted-foreground"}`,children:F.label})]},String(F.value))})}),_.type==="radio"&&_.options&&e.jsx("div",{className:"space-y-2",children:_.options.map(F=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("input",{type:"radio",id:`${_.id}-${F.value}
47`,name:_.id,value:String(F.value),checked:j.templateAnswers[_.id]===F.value,onChange:()=>$(_.id,F.value),className:"h-4 w-4 text-primary"}),e.jsx(v,{htmlFor:`${_.id}-${F.value}`,className:"text-sm",children:F.label})]},String(F.value)))})]})]},_.id):null),e.jsxs("div",{className:"mt-6 p-4 border rounded-lg bg-background",children:[e.jsxs("h4",{className:"text-sm font-medium mb-3 flex items-center gap-2",children:[e.jsx(jt,{className:"h-4 w-4"}),"Form Preview (",ma(j.selectedTemplate,j.templateAnswers).length," fields)"]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[ma(j.selectedTemplate,j.templateAnswers).filter(_=>_.field_type!=="line_break"&&_.field_type!=="heading").slice(0,12).map((_,X)=>e.jsx(ie,{variant:"secondary",className:"text-xs",children:_.label},X)),ma(j.selectedTemplate,j.templateAnswers).filter(_=>_.field_type!=="line_break"&&_.field_type!=="heading").length>12&&e.jsxs(ie,{variant:"outline",className:"text-xs",children:["+",ma(j.selectedTemplate,j.templateAnswers).filter(_=>_.field_type!=="line_break"&&_.field_type!=="heading").length-12," more"]})]})]})]}),l===2&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-center mb-6",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Basic Information"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Let's start with the essential details"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"name",children:"Event Name *"}),e.jsx(A,{id:"name",value:j.name,onChange:_=>g({...j,name:_.target.value}),placeholder:"e.g. Spring Championship",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"slug",children:"URL Slug"}),e.jsx(A,{id:"slug",value:j.slug,onChange:_=>g({...j,slug:_.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-")}),placeholder:"spring-championship"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"event_date",children:"Event Date *"}),e.jsx(A,{id:"event_date",type:"date",value:j.event_date,onChange:_=>g({...j,event_date:_.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"max_participants",children:"Max Participants"}),e.jsx(A,{id:"max_participants",type:"number",value:j.max_participants,onChange:_=>g({...j,max_participants:parseInt(_.target.value)||100})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"location",children:"Location *"}),e.jsx(A,{id:"location",value:j.location,onChange:_=>g({...j,location:_.target.value}),placeholder:"City, State",required:!0})]}),e.jsx("div",{className:"space-y-2 md:col-span-2",children:e.jsx(Br,{value:j.track_id,onChange:_=>g(X=>({...X,track_id:(_==null?void 0:_.id)??null,venue_name:X.venue_name||(_==null?void 0:_.name)||"",location:X.location||[_==null?void 0:_.city,_==null?void 0:_.state].filter(Boolean).join(", ")})),label:"Track (shared library)"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"venue_name",children:"Venue Name"}),e.jsx(A,{id:"venue_name",value:j.venue_name,onChange:_=>g({...j,venue_name:_.target.value}),placeholder:"Track or venue name"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"description",children:"Description"}),e.jsx(Ns,{id:"description",value:j.description,onChange:_=>g({...j,description:_.target.value}),placeholder:"Describe your event...",rows:3})]})]}),l===3&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-center mb-6",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Fee Configuration"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure service fees for this event or use global defaults"})]}),e.jsx("div",{className:"p-4 bg-muted/50 rounded-lg mb-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Override Global Fee Settings"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:j.override_fees?"Using custom fees for this event":`Using global: $${(T==null?void 0:T.flat_service_fee)||0} + ${(T==null?void 0:T.percentage_service_fee)||0}%`})]}),e.jsx(Ds,{checked:j.override_fees,onCheckedChange:_=>g({...j,override_fees:_})})]})}),j.override_fees&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"flat_service_fee",children:"Flat Service Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx(_a,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(A,{id:"flat_service_fee",type:"number",step:"0.01",value:j.flat_service_fee??"",onChange:_=>g({...j,flat_service_fee:_.target.value?parseFloat(_.target.value):null}),className:"pl-9"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"percentage_service_fee",children:"Percentage Fee (%)"}),e.jsx(A,{id:"percentage_service_fee",type:"number",step:"0.1",value:j.percentage_service_fee??"",onChange:_=>g({...j,percentage_service_fee:_.target.value?parseFloat(_.target.value):null})})]}),e.jsx("div",{className:"col-span-full",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ds,{id:"pass_cc_fees",checked:j.pass_cc_fees??!1,onCheckedChange:_=>g({...j,pass_cc_fees:_})}),e.jsx(v,{htmlFor:"pass_cc_fees",children:"Pass credit card processing fees to customer"})]})})]})]}),l===4&&e.jsxs("div",{className:"space-y-4",children:[j.mysql_event_name&&e.jsxs("div",{className:"bg-primary/10 rounded-lg p-3 text-sm flex items-center gap-2",children:[e.jsx(Os,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"font-medium text-primary",children:["Linked to: ",j.mysql_event_name,j.mysql_series_name&&` (${j.mysql_series_name})`]})]}),e.jsx(rl,{embedded:!0,onComplete:(_,X)=>{g(F=>({...F,mysql_series_name:_,mysql_event_name:X}))},onSkip:()=>{g(_=>({..._,mysql_series_name:"",mysql_event_name:""}))}})]}),l===5&&p&&e.jsx(_d,{eventType:o,terms:m,classes:j.classes,onChange:_=>g(X=>({...X,classes:_}))}),l===6&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-center mb-6",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Review & Publish"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Review your event details before creating"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Event Name"}),e.jsx("p",{className:"font-medium",children:j.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Date"}),e.jsx("p",{className:"font-medium",children:j.event_date||"Not set"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Location"}),e.jsx("p",{className:"font-medium",children:j.location})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Venue"}),e.jsx("p",{className:"font-medium",children:j.venue_name||"Not set"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Max Participants"}),e.jsx("p",{className:"font-medium",children:j.max_participants})]}),j.mysql_series_name&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Linked Series"}),e.jsx("p",{className:"font-medium",children:j.mysql_series_name})]})]}),e.jsxs("div",{className:"space-y-4 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"image_url",children:"Event Image URL (optional)"}),e.jsx(A,{id:"image_url",value:j.image_url,onChange:_=>g({...j,image_url:_.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"track_info",children:"Track Info (optional)"}),e.jsx(Ns,{id:"track_info",value:j.track_info,onChange:_=>g({...j,track_info:_.target.value}),rows:2})]}),e.jsxs("div",{className:"space-y-3 p-4 border border-border rounded-lg",children:[e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsx(v,{className:"text-base font-semibold",children:"Single event or series?"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Leave empty for a single event. Add rounds below to make this a series — each round becomes its own race that riders register for, all under the parent name."})]})}),j.rounds.length>0&&e.jsx("div",{className:"space-y-2",children:j.rounds.map((_,X)=>e.jsxs("div",{className:"grid grid-cols-[auto_1fr_auto_auto] gap-2 items-center",children:[e.jsxs("span",{className:"text-xs font-mono text-muted-foreground w-12",children:["Round ",X+1]}),e.jsx(A,{placeholder:`Round ${X+1} name (e.g. "Round ${X+1}")`,value:_.name,onChange:F=>{const ne=[...j.rounds];ne[X]={...ne[X],name:F.target.value}
47,g({...j,rounds:ne})}}),e.jsx(A,{type:"date",value:_.event_date,onChange:F=>{const ne=[...j.rounds];ne[X]={...ne[X],event_date:F.target.value},g({...j,rounds:ne})}}),e.jsx(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>{g({...j,rounds:j.rounds.filter((F,ne)=>ne!==X)})},children:"Remove"})]},X))}),e.jsx(w,{type:"button",variant:"outline",size:"sm",onClick:()=>{const _=j.rounds.length+1;g({...j,rounds:[...j.rounds,{name:`Round ${_}`,event_date:""}]})},children:"+ Add round"}),j.rounds.length>0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["This event will be created as a ",e.jsx("strong",{children:"series container"})," with ",j.rounds.length," round",j.rounds.length===1?"":"s"," underneath. Riders register for individual rounds."]})]}),e.jsxs("div",{className:"flex items-center space-x-2 p-4 bg-primary/10 rounded-lg",children:[e.jsx(Ds,{id:"is_published",checked:j.is_published,onCheckedChange:_=>g({...j,is_published:_})}),e.jsxs("div",{children:[e.jsx(v,{htmlFor:"is_published",children:"Publish Event Now"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"When published, the event will be visible to the public"})]})]})]})]})]}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx(w,{variant:"outline",onClick:l===0?Z:Q,children:l===0?"Cancel":e.jsxs(e.Fragment,{children:[e.jsx(ya,{className:"mr-2 h-4 w-4"})," Back"]})}),l<ka.length-1?e.jsxs(w,{onClick:L,disabled:!Y(),className:"bg-gradient-fire hover:opacity-90",children:["Next ",e.jsx(Hs,{className:"ml-2 h-4 w-4"})]}):e.jsx(w,{onClick:R,disabled:C.isPending,className:"bg-gradient-fire hover:opacity-90",children:C.isPending?"Creating...":"Create Event"})]})]})})}const kd={maxClasses:3,singleEventClassPrices:[0,0,0]};function Ed({value:s,onChange:n,showSeasonTier:i,title:t,description:d}){const r=s??kd,x=Math.min(5,Math.max(1,Number(r.maxClasses)||3)),c=m=>{n({...r,...m})},o=(m,p,u)=>{const l=Array.isArray(r[m])?[...r[m]]:[];for(;l.length<x;)l.push(0);l[p]=parseFloat(u)||0,c({[m]:l.slice(0,x)})};return e.jsxs("div",{className:"space-y-4",children:[(t||d)&&e.jsxs("div",{children:[t&&e.jsx(v,{className:"text-sm font-medium",children:t}),d&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:d})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{className:"text-xs",children:"Max classes per rider (1–5)"}),e.jsxs(Pe,{value:String(x),onValueChange:m=>c({maxClasses:parseInt(m,10)}),children:[e.jsx(Ie,{className:"w-24",children:e.jsx(qe,{})}),e.jsx(Be,{children:[1,2,3,4,5].map(m=>e.jsx(ae,{value:String(m),children:m},m))})]})]}),e.jsxs("div",{className:"space-y-2 p-3 bg-background rounded border",children:[e.jsx(v,{className:"text-xs font-medium text-primary",children:"Per-round price by class count"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total a rider pays for one round, by how many classes they enter."}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:Array.from({length:x},(m,p)=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs(v,{className:"text-xs",children:[p+1," class",p>0?"es":""]}),e.jsx(A,{type:"number",min:"0",step:"0.01",value:(r.singleEventClassPrices??[])[p]??0,onChange:u=>o("singleEventClassPrices",p,u.target.value),placeholder:`Price for ${p+1}`})]},`single-${p}`))})]}),i&&e.jsxs("div",{className:"space-y-2 p-3 bg-background rounded border",children:[e.jsx(v,{className:"text-xs font-medium text-primary",children:"Season pass price by class count"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"One-time season-pass price covering every round, by class count."}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:Array.from({length:x},(m,p)=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs(v,{className:"text-xs",children:[p+1," class",p>0?"es":""]}),e.jsx(A,{type:"number",min:"0",step:"0.01",value:(r.seasonClassPrices??[])[p]??0,onChange:u=>o("seasonClassPrices",p,u.target.value),placeholder:`Season for ${p+1}`})]},`season-${p}`))})]})]})}function Md({rounds:s,defaults:n,overrides:i,selectedKey:t,onSelectedKeyChange:d,onDefaultsChange:r,onOverridesChange:x}){var k;const c=s.length,o=t==="all",m=o?-1:t,p=a.useMemo(()=>o?n:i[m]??n,[o,m,n,i]),u=!o&&!!i[m]&&!tn(i[m],n),l=S=>{o?r(S):x({...i,[m]:S})},N=()=>{c!==0&&d(o?c-1:m===0?"all":m-1)},j=()=>{c!==0&&(o?d(0):m>=c-1?d("all"):d(m+1))},g=()=>{if(o)x({});else{const{[m]:S,...f}=i;x(f)}},y=Object.keys(i).filter(S=>{const f=Number(S);return i[f]&&!tn(i[f],n)}).length;return e.jsxs("div",{className:"space-y-3 rounded-lg border bg-card p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Event Settings"}),e.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[e.jsx(w,{type:"button",size:"icon",variant:"outline",className:"h-8 w-8",onClick:N,disabled:c===0,"aria-label":"Previous round",children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsxs(Pe,{value:o?"all":String(m),onValueChange:S=>d(S==="all"?"all":Number(S)),children:[e.jsx(Ie,{className:"h-8 w-[220px] text-sm",children:e.jsx(qe,{})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"all",children:"All rounds (defaults)"}),s.map((S,f)=>{const h=!!i[f]&&!tn(i[f],n);return e.jsx(ae,{value:String(f),children:`${f+1}. ${S.name||`Round ${f+1}`}${h?" • customized":""}`},f)})]})]}),e.jsx(w,{type:"button",size:"icon",variant:"outline",className:"h-8 w-8",onClick:j,disabled:c===0,"aria-label":"Next round",children:e.jsx(Hs,{className:"h-4 w-4"})})]})]}),e.jsx("div",{className:"flex items-center gap-2 flex-wrap text-xs text-muted-foreground",children:o?e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"Editing defaults — applies to every round that hasn't been customized."}),y>0&&e.jsxs(w,{type:"button",size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:g,children:[e.jsx(ca,{className:"mr-1 h-3 w-3"}),"Reset all overrides (",y,")"]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{children:["Editing only: ",e.jsx("strong",{children:((k=s[m])==null?void 0:k.name)||`Round ${m+1}`})]}),u&&e.jsx(ie,{variant:"secondary",className:"text-[10px]",children:"Customized"}),u&&e.jsxs(w,{type:"button",size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:g,children:[e.jsx(ca,{className:"mr-1 h-3 w-3"}),"Revert to defaults"]})]})}),e.jsx(ql,{value:p,onChange:l,compact:!0})]})}const gr={name:"",description:"",default_location:"",default_venue:"",image_url:"",rounds:[],regular_price:0,late_price:null,max_participants:100,class_price_tiers:{maxClasses:3,singleEventClassPrices:[0,0,0],seasonClassPrices:[0,0,0]},mysql_series_name:"",default_event_settings:{...Ul},event_settings_overrides:{},publish_all:!1},ln=[{id:0,title:"Series",desc:"Name & default details"},{id:1,title:"Rounds",desc:"Add each round/race"},{id:2,title:"Pricing",desc:"Applied to every round"},{id:3,title:"Review",desc:"Confirm & create"}];function Td(s,n){const[i,t,d]=s.split("-").map(Number),r=new Date(i,(t??1)-1,d??1);r.setDate(r.getDate()+n*7);const x=r.getFullYear(),c=String(r.getMonth()+1).padStart(2,"0"),o=String(r.getDate()).padStart(2,"0");return`${x}-${c}-${o}`}function Rd({open:s,onOpenChange:n,onCreated:i}){const{toast:t}=Ht(),d=Ms(),{currentOrganization:r}=Je(),{isTimingEnabled:x}=Wt(),{data:c=[]}
47=ba(),o=Fr(),[m,p]=a.useState(0),[u,l]=a.useState(gr),[N,j]=a.useState("all"),[g,y]=a.useState(8),[k,S]=a.useState(""),[f,h]=a.useState("biweekly");ms({queryKey:["series-names-for-wizard",r==null?void 0:r.id],queryFn:async()=>c,enabled:x});const M=()=>{p(0),l(gr),y(8),S(""),h("biweekly"),j("all")},T=()=>{n(!1),setTimeout(M,200)},C=ks({mutationFn:async()=>{var _e;if(!(r!=null&&r.id))throw new Error("No organization selected");if(!u.name.trim())throw new Error("Series name is required");if(u.rounds.length===0)throw new Error("Add at least one round");const b=u.rounds.map((me,$e)=>({r:me,originalIdx:$e})).filter(({r:me})=>me.name.trim()&&me.event_date).sort((me,$e)=>me.r.event_date.localeCompare($e.r.event_date)).map(({r:me,originalIdx:$e})=>({...me,__originalIdx:$e}));if(b.length===0)throw new Error("Each round needs a name and date");const I=(u.mysql_series_name||"").trim()||u.name.trim(),V=b[0].event_date,H=b[b.length-1].event_date,{data:Y,error:W}=await z.from("events").insert({name:u.name.trim(),description:u.description||null,event_date:V,end_date:H,location:u.default_location||b[0].location||"TBD",venue_name:u.default_venue||null,image_url:u.image_url||null,regular_price:0,max_participants:null,is_published:u.publish_all,organization_id:r.id,event_kind:"series",mysql_series_name:I,class_price_tiers:u.class_price_tiers}).select("id").single();if(W)throw W;const te=Y.id,B=b.map((me,$e)=>({name:me.name.trim(),event_date:me.event_date,location:me.location||u.default_location||"TBD",venue_name:u.default_venue||null,regular_price:u.regular_price,late_price:u.late_price,max_participants:u.max_participants,is_published:u.publish_all,organization_id:r.id,event_kind:"round",parent_event_id:te,is_child_race:!0,child_race_index:$e+1,mysql_series_name:I})),{data:le,error:Me}=await z.from("events").insert(B).select("id, name, event_date, location, venue_name, mysql_event_name, mysql_series_name");if(Me)throw Me;const _=pn(o,"round");if(_.length>0&&le&&le.length>0){const me=le.flatMap(ee=>_.map((pe,je)=>({event_id:ee.id,field_type:pe.field_type,label:pe.label,placeholder:pe.placeholder||null,help_text:pe.help_text||null,is_required:pe.is_required||!1,field_order:je,width:pe.width||"full",options:pe.options?pe.options:null}))),{error:$e}=await z.from("form_fields").insert(me);
47$e&&console.error("Failed to seed round form fields:",$e)}let X=0;if(le&&le.length>0)for(let me=0;me<le.length;me++){const $e=le[me],ee=((_e=b[me])==null?void 0:_e.__originalIdx)??me,pe=u.event_settings_overrides[ee]??u.default_event_settings,je=await Bl($e.id,pe);je.ok||(X+=1,console.warn("[series-wizard] apply settings failed",$e.id,je.error))}let F=!0,ne,J=!1;if(r!=null&&r.id){const{isOrgMysqlConfigured:me,ensureMysqlSeries:$e,pushEventToMysql:ee}=await Cn(async()=>{const{isOrgMysqlConfigured:pe,ensureMysqlSeries:je,pushEventToMysql:we}=await import("./mysqlEventBridge-i9SJNJp2.js");return{isOrgMysqlConfigured:pe,ensureMysqlSeries:je,pushEventToMysql:we}},__vite__mapDeps([0,1,2]));if(await me(r.id)){J=!0;const pe=await $e({orgId:r.id,seriesName:I});pe.ok||(F=!1,ne=`ensureMysqlSeries: ${pe.error??"unknown"}`);for(const je of le??[]){const we=await ee({orgId:r.id,event:je,seriesName:I});we.ok||(F=!1,ne=`pushEventToMysql(${je.name}): ${we.error??"unknown"}`)}}}return{parentId:te,roundCount:B.length,mysqlOk:F,mysqlError:ne,mysqlAttempted:J,labSettingsFailures:X}},onSuccess:({parentId:b,roundCount:I,mysqlOk:V,mysqlError:H,mysqlAttempted:Y,labSettingsFailures:W})=>{d.invalidateQueries({queryKey:["admin-events"]}),d.invalidateQueries({queryKey:["timing-lab","events"]});const te=`${I} round${I===1?"":"s"}`,B=W>0?` (${W} round event-settings did not save — edit them in Timing Lab.)`:"";t({title:"Series created",description:(Y?V?`${te} saved to Postgres & MySQL.`:`${te} saved to Postgres. MySQL push had issues${H?`: ${H}`:""}.`:`${te} saved to Postgres. (MySQL not configured for this org.)`)+B,variant:V&&W===0?"default":"destructive"}),i==null||i(b),T()},onError:b=>{t({title:"Could not create series",description:b.message,variant:"destructive"})}}),L=a.useMemo(()=>m===0?u.name.trim().length>0:m===1?u.rounds.length>0&&u.rounds.every(b=>b.name.trim()&&b.event_date):!0,[m,u]),Q=()=>{l(b=>({...b,rounds:[...b.rounds,{name:`Round ${b.rounds.length+1}`,event_date:""}]}))},Z=(b,I)=>{l(V=>({...V,rounds:V.rounds.map((H,Y)=>Y===b?{...H,...I}:H)}))},R=b=>{l(I=>{const V={};return Object.entries(I.event_settings_overrides).forEach(([H,Y])=>{const W=Number(H);W<b?V[W]=Y:W>b&&(V[W-1]=Y)}),{...I,rounds:I.rounds.filter((H,Y)=>Y!==b),event_settings_overrides:V}}),j("all")},E=()=>
47{if(!k||g<1)return;const b=f==="weekly"?1:f==="biweekly"?2:4,I=Array.from({length:g},(V,H)=>({name:`Round ${H+1}`,event_date:Td(k,H*b),location:""}));l(V=>({...V,rounds:I,event_settings_overrides:{}})),j("all")},$=(m+1)/ln.length*100;return e.jsx(ts,{open:s,onOpenChange:b=>b?n(!0):T(),children:e.jsxs(as,{className:"w-[96vw] max-w-[1100px] max-h-[92vh] overflow-y-auto overflow-x-hidden bg-card border-border",children:[e.jsx(rs,{children:e.jsxs(is,{className:"font-display text-xl flex items-center gap-2",children:[e.jsx(Ba,{className:"h-5 w-5 text-primary"}),"Create Series"]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-center justify-between text-xs",children:ln.map(b=>e.jsxs("div",{className:`flex-1 text-center ${b.id===m?"text-primary font-semibold":b.id<m?"text-muted-foreground":"text-muted-foreground/60"}`,children:[e.jsx("div",{className:"flex items-center justify-center mb-1",children:e.jsx("div",{className:`h-7 w-7 rounded-full flex items-center justify-center text-xs ${b.id===m?"bg-primary text-primary-foreground":b.id<m?"bg-success/30 text-success":"bg-muted text-muted-foreground"}`,children:b.id<m?e.jsx(Os,{className:"h-3.5 w-3.5"}):b.id+1})}),b.title]},b.id))}),e.jsx(Ka,{value:$,className:"h-1"})]}),e.jsxs("div",{className:"mt-4 space-y-4",children:[m===0&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{children:"Series Name *"}),e.jsx(A,{value:u.name,onChange:b=>l({...u,name:b.target.value}),placeholder:"e.g. Jordan River MX Series 2026",autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{children:"Description"}),e.jsx(Ns,{value:u.description,onChange:b=>l({...u,description:b.target.value}),placeholder:"Optional series description, shown to riders",rows:3})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{children:"Default Location"}),e.jsx(A,{value:u.default_location,onChange:b=>l({...u,default_location:b.target.value}),placeholder:"City, ST"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{children:"Default Venue"}),e.jsx(A,{value:u.default_venue,onChange:b=>l({...u,default_venue:b.target.value}),placeholder:"Track / venue name"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{children:"Series Image URL"}),e.jsx(A,{value:u.image_url,onChange:b=>l({...u,image_url:b.target.value}),placeholder:"https://..."})]})]}),m===1&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-lg border bg-muted/40 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(fn,{className:"h-4 w-4 text-primary"}),"Quick-generate rounds"]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-2",children:[e.jsxs("div",{children:[e.jsx(v,{className:"text-xs",children:"Count"}),e.jsx(A,{type:"number",min:1,max:20,value:g,onChange:b=>y(Math.max(1,parseInt(b.target.value)||1))})]}),e.jsxs("div",{children:[e.jsx(v,{className:"text-xs",children:"First date"}),e.jsx(A,{type:"date",value:k,onChange:b=>S(b.target.value)})]}),e.jsxs("div",{children:[e.jsx(v,{className:"text-xs",children:"Cadence"}),e.jsxs(Pe,{value:f,onValueChange:b=>h(b),children:[e.jsx(Ie,{children:e.jsx(qe,{})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"weekly",children:"Weekly"}),e.jsx(ae,{value:"biweekly",children:"Every 2 weeks"}),e.jsx(ae,{value:"monthly",children:"Monthly (4 wks)"})]})]})]}),e.jsx("div",{className:"flex items-end",children:e.jsx(w,{type:"button",variant:"outline",onClick:E,disabled:!k,className:"w-full",children:"Generate"})})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(v,{className:"text-sm font-medium",children:["Rounds (",u.rounds.length,")"]}),e.jsxs(w,{type:"button",size:"sm",variant:"outline",onClick:Q,children:[e.jsx(Es,{className:"mr-1 h-3.5 w-3.5"})," Add round"]})]}),u.rounds.length===0?e.jsx("div",{className:"text-center text-sm text-muted-foreground py-8 border-2 border-dashed rounded-lg",children:'No rounds yet. Use the generator above, or click "Add round".'}):e.jsx(qs,{className:"max-h-[40vh] pr-2",children:e.jsx("div",{className:"space-y-2",children:u.rounds.map((b,I)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-background",children:[e.jsx(ie,{variant:"outline",className:"shrink-0",children:I+1}),e.jsx(A,{placeholder:"Round name",value:b.name,onChange:V=>Z(I,{name:V.target.value}),className:"flex-1"}),e.jsx(A,{type:"date",value:b.event_date,onChange:V=>Z(I,{event_date:V.target.value}),className:"w-44"}),e.jsx(A,{placeholder:"Location (optional)",value:b.location||"",onChange:V=>Z(I,{location:V.target.value}),className:"w-48"}),e.jsx(w,{type:"button",size:"icon",variant:"ghost",onClick:()=>R(I),children:e.jsx(ws,{className:"h-4 w-4 text-destructive"})})]},I))})}),u.rounds.length>0&&e.jsx(Md,{rounds:u.rounds.map((b,I)=>({name:b.name||`Round ${I+1}`})),defaults:u.default_event_settings,overrides:u.event_settings_overrides,selectedKey:N,onSelectedKeyChange:j,onDefaultsChange:b=>l(I=>({...I,default_event_settings:b})),onOverridesChange:b=>l(I=>({...I,event_settings_overrides:b}))})]}),m===2&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Tier prices apply to every round by default. You can override pricing per round later from Series setup."}),e.jsx(Ed,{value:u.class_price_tiers,onChange:b=>{var I;return l({...u,class_price_tiers:b,regular_price:((I=b.singleEventClassPrices)==null?void 0:I[0])??u.regular_price})},showSeasonTier:!0,title:"Per-round pricing by class count",description:"e.g. 1 class = $50, 2 
47classes = $80, 3+ = $100. Used by the registration form when its pricing source is set to 'Inherit from series'."}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 pt-2 border-t",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{children:"Late Price (optional, flat fallback)"}),e.jsxs("div",{className:"relative",children:[e.jsx(_a,{className:"absolute left-2 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(A,{type:"number",min:0,step:"0.01",value:u.late_price??"",onChange:b=>l({...u,late_price:b.target.value?parseFloat(b.target.value):null}),className:"pl-8"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{children:"Max Participants per Round"}),e.jsx(A,{type:"number",min:1,value:u.max_participants,onChange:b=>l({...u,max_participants:parseInt(b.target.value)||100})})]})]})]}),m===3&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-lg bg-muted/40 p-4 grid grid-cols-1 md:grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground text-xs",children:"Series"}),e.jsx("div",{className:"font-medium",children:u.name||"—"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground text-xs",children:"Default Location"}),e.jsx("div",{className:"font-medium",children:u.default_location||"—"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground text-xs",children:"Rounds"}),e.jsx("div",{className:"font-medium",children:u.rounds.length})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground text-xs",children:"Pricing"}),e.jsxs("div",{className:"font-medium",children:["$",u.regular_price.toFixed(2),u.late_price!=null?` / late $${u.late_price.toFixed(2)}`:""]})]}),u.mysql_series_name&&e.jsxs("div",{className:"md:col-span-2",children:[e.jsx("div",{className:"text-muted-foreground text-xs",children:"MySQL Series"}),e.jsx("div",{className:"font-medium",children:u.mysql_series_name})]})]}),e.jsxs("div",{className:"border rounded-lg",children:[e.jsx("div",{className:"px-3 py-2 border-b text-xs font-semibold text-muted-foreground uppercase",children:"Rounds preview"}),e.jsx(qs,{className:"max-h-[30vh]",children:e.jsx("div",{className:"divide-y",children:[...u.rounds].sort((b,I)=>b.event_date.localeCompare(I.event_date)).map((b,I)=>e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 text-sm",children:[e.jsx(ie,{variant:"outline",children:I+1}),e.jsx("span",{className:"flex-1",children:b.name}),e.jsxs("span",{className:"text-muted-foreground flex items-center gap-1",children:[e.jsx(At,{className:"h-3.5 w-3.5"}),b.event_date]}),b.location&&e.jsx("span",{className:"text-muted-foreground",children:b.location})]},I))})})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ds,{id:"publish_all",checked:u.publish_all,onCheckedChange:b=>l({...u,publish_all:b})}),e.jsx(v,{htmlFor:"publish_all",children:"Publish series and all rounds immediately"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsx(w,{variant:"outline",onClick:m===0?T:()=>p(b=>b-1),children:m===0?"Cancel":e.jsxs(e.Fragment,{children:[e.jsx(ya,{className:"mr-1 h-4 w-4"})," Back"]})}),m<ln.length-1?e.jsxs(w,{onClick:()=>p(b=>b+1),disabled:!L,className:"bg-gradient-fire hover:opacity-90",children:["Next ",e.jsx(Hs,{className:"ml-1 h-4 w-4"})]}):e.jsx(w,{onClick:()=>C.mutate(),disabled:C.isPending||u.rounds.length===0||!u.name.trim(),className:"bg-gradient-fire hover:opacity-90",children:C.isPending?e.jsxs(e.Fragment,{children:[e.jsx(oe,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating…"]}):e.jsxs(e.Fragment,{children:["Create Series ",e.jsx(Os,{className:"ml-1 h-4 w-4"})]})})]})]})})}function $d({open:s,onOpenChange:n,seriesEventId:i,seriesName:t}){return e.jsx(ts,{open:s,onOpenChange:n,children:e.jsxs(as,{className:"w-[96vw] max-w-[1400px] max-h-[92vh] overflow-y-auto overflow-x-hidden bg-card border-border",children:[e.jsxs(rs,{children:[e.jsxs(is,{className:"font-display text-xl flex items-center gap-2",children:[e.jsx(Ba,{className:"h-5 w-5 text-primary"}),"Series Setup",t?` — ${t}`:""]}),e.jsx(Fs,{children:"Set up one round as your template, then use Copy round setup for its format, classes, prices and schedule."})]}),e.jsx(Ir,{seriesEventId:i})]})})}
47function Dd(s,n,i){const[t,d]=a.useState(null),[r,x]=a.useState([]),[c,o]=a.useState(!1);return a.useEffect(()=>{if(!i||!s)return;let m=!1;return o(!0),(async()=>{const[{data:p},{data:u}]=await Promise.all([n?z.from("timing_lab_events").select("id, name, event_date").eq("source_event_id",n).maybeSingle():Promise.resolve({data:null}),z.from("timing_lab_events").select("id, name, event_date").eq("organization_id",s).is("source_event_id",null).order("event_date",{ascending:!1}).limit(200)]);m||(d(p??null),x(u??[]),o(!1))})(),()=>{m=!0}},[s,n,i]),{sourceLabEvent:t,unlinked:r,loading:c}}function Fd(s,n){return s.mode==="copy"?n:s.mode==="existing"?!!s.labEventId:!0}function Ad({value:s,onChange:n,sourceLabEvent:i,unlinked:t,loading:d}){const r=c=>n({...s,...c}),x=[{mode:"copy",label:"Copy the Timing Lab event too",hint:i?`Duplicates “${i.name}” (classes, race order, schedule) and links it to the new event.`:"The event you are copying has no Timing Lab event, so there is nothing to copy.",icon:lc,disabled:!i},{mode:"existing",label:"Link an existing Timing Lab event",hint:"Use a lab event you already built. Only unclaimed lab events are listed.",icon:An},{mode:"none",label:"No timing for this copy",hint:"Registration only. You can link a Timing Lab event later.",icon:yc}];return e.jsxs("div",{className:"space-y-2 rounded-md border p-3",children:[e.jsx(v,{className:"text-sm",children:"Timing Lab event for the copy"}),e.jsx("div",{className:"grid gap-2",children:x.map(c=>{const o=c.icon,m=s.mode===c.mode;return e.jsxs("button",{type:"button",disabled:c.disabled,onClick:()=>r({mode:c.mode}),className:`flex items-start gap-2 rounded-md border p-2 text-left transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${m?"border-primary bg-primary/5":"border-border hover:bg-muted/50"}`,children:[e.jsx(o,{className:`mt-0.5 h-4 w-4 shrink-0 ${m?"text-primary":"text-muted-foreground"}`}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-medium",children:c.label}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:c.hint})]})]},c.mode)})}),s.mode==="existing"&&e.jsx("div",{className:"pt-1",children:e.jsxs(Pe,{value:s.labEventId,onValueChange:c=>r({labEventId:c}),children:[e.jsx(Ie,{children:e.jsx(qe,{placeholder:d?"Loading…":"Select a Timing Lab event"})}),e.jsxs(Be,{children:[t.length===0&&!d&&e.jsx("div",{className:"px-2 py-3 text-xs text-muted-foreground",children:"No unlinked Timing Lab events — copy the source one instead."}),t.map(c=>e.jsxs(ae,{value:c.id,children:[c.name,c.event_date?` — ${c.event_date}`:""]},c.id))]})]})})]})}async function Ld(s){const{value:n,newEventId:i,newEventName:t,newEventDate:d,sourceLabEventId:r}=s;if(n.mode==="none")return{linked:!1};if(n.mode==="copy"){if(!r)return{linked:!1};const{data:o,error:m}=await z.functions.invoke("timing-lab-duplicate-event",{body:{source_event_id:r,new_event:{name:t,event_date:d},link_source_event_id:i,copy_classes:!0,copy_race_order:!0,copy_schedule_slots:!0,copy_riders:!1}});if(m)throw m;if(o!=null&&o.error)throw new Error(o.error);return{linked:!0,created:!0}}const{data:x,error:c}=await z.functions.invoke("timing-lab-link-registration-event",{body:{lab_event_id:n.labEventId,mode:"existing",pg_event_id:i}});if(c)throw c;if(x!=null&&x.error)throw new Error(x.error);return{linked:!0,created:!1}}const Ea={name:"",slug:"",description:"",event_date:"",location:"",venue_name:"",max_participants:100,track_info:"",image_url:"",is_published:!1,mysql_series_name:"",track_id:null};function Pd({autoOpenCreateEvent:s=!1,reviewCountsByEvent:n={},abandonedCountsByEvent:i={}}){const{toast:t}=Ht(),d=da(),r=Ms(),{isSuperAdmin:x}=kn(),{currentOrganization:c}=Je(),[o,m]=a.useState(!1),[p,u]=a.useState(s),[l,N]=a.useState(!1),[j,g]=a.useState(null),[y,k]=a.useState(void 0),[S,f]=a.useState(!1),[h,M]=a.useState(null),[T,C]=a.useState(null),[L,Q]=a.useState(""),[Z,R]=a.useState(null),[E,$]=a.useState(Ea),b=zl(Z==null?void 0:Z.id),I=b.locked&&!x,[V,H]=a.useState({mode:"copy",labEventId:""}),Y=Dd(c==null?void 0:c.id,T==null?void 0:T.id,S);a.useEffect(()=>{!S||Y.loading||V.mode==="copy"&&!Y.sourceLabEvent&&H(D=>({...D,mode:Y.unlinked.length>0?"existing":"none"}))},[S,Y.loading,Y.sourceLabEvent,Y.unlinked.length,V.mode]);const{features:W}=En(["event_create","event_edit"]),te=W.event_create||x,B=W.event_edit||x,{canPublish:le}=Fn(),{data:Me=[],isLoading:_}=ms({queryKey:["admin-events",c==null?void 0:c.id,"series-aware-v1"],queryFn:async()=>{let D=z.from("events").select("*").order("event_date",{ascending:!0});c&&(D=D.eq("organization_id",c.id));const{data:O,error:Ne}=await D;if(Ne)throw Ne;return O},enabled:!!c}),X=Me.filter(D=>Al(D)||ar(D)).filter(D=>!D.is_child_race&&!D.parent_event_id),F=new Map;for(const D of Me)if(D.is_child_race&&D.parent_event_id){const O=F.get(D.parent_event_id)??[];O.push(D),F.set(D.parent_event_id,O)}for(const D of F.values())D.sort((O,Ne)=>(O.child_race_index??0)-(Ne.child_race_index??0));const ne=D=>{var O;return ar(D)||(((O=F.get(D.id))==null?void 0:O.length)??0)>0},J=X.filter(D=>!D.archived_at),_e=X.filter(D=>!!D.archived_at),me=J.filter(D=>!ne(D)),$e=J.filter(D=>ne(D)),[ee,pe]=a.useState(!1),je=new Intl.DateTimeFormat("en-CA",{timeZone:"America/Denver",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date),we=D=>{const O=F.get(D.id)??[];return O.length?[...O].map(Ne=>String(Ne.event_date)).sort((Ne,Se)=>Ne.localeCompare(Se)).pop():String(D.end_date||D.event_date||"")},U=D=>{const O=we(D);return!!O&&O<je},se=ks({mutationFn:async({id:D,archive:O,alsoLab:Ne})=>{var ss;const{data:Se}=await z.auth.getUser(),us=O?{archived_at:new Date().toISOString(),archived_by:((ss=Se==null?void 0:Se.user)==null?void 0:ss.id)??null}:{archived_at:null,archived_by:null},{error:ps}=await z.from("events").update(us).eq("id",D);if(ps)throw ps;const{data:xs,error:G}=await z.from("events").update(us).eq("parent_event_id",D).select("id");if(G)throw G;if(!Ne)return;const{data:De}=await z.from("timing_lab_series").update(us).eq("source_series_event_id",D).select("id"),ds=(De??[]).map(es=>es.id);ds.length&&await z.from("timing_lab_events").update(us).in("series_id",ds);const Ge=[D,...(xs??[]).map(es=>es.id)];await z.from("timing_lab_events").update(us).in("source_event_id",Ge)},onSuccess:(D,O)=>{r.invalidateQueries({queryKey:["admin-events"]}),t({title:O.archive?"Archived":"Restored from archive"})},onError:D=>{t({title:"Could not archive",description:D.message,variant:"destructive"})}}),ue=async(D,O)=>{if(O){const Se=U(D)?`Archive "${D.name}"? It will be hidden from the public site and moved to the Archived section. You can still duplicate or restore it.`:`"${D.name}" is not finished yet. Archive it anyway? It will be hidden from the public site.`;if(!confirm(Se))return}let Ne=!1;try{const Se=(F.get(D.id)??[]).map(G=>
47G.id),[{count:us},{count:ps}]=await Promise.all([z.from("timing_lab_series").select("id",{count:"exact",head:!0}).eq("source_series_event_id",D.id),z.from("timing_lab_events").select("id",{count:"exact",head:!0}).in("source_event_id",[D.id,...Se])]);(us??0)+(ps??0)>0&&(Ne=confirm(O?`This is linked to Timing Lab. Also archive the linked Timing Lab series/rounds?
48
49Results and live timing stay available either way — archiving only hides them from the pickers.`:"Also restore the linked Timing Lab series/rounds from the archive?"))}catch{}se.mutate({id:D.id,archive:O,alsoLab:Ne})},ve=D=>(n[D]||0)+(F.get(D)??[]).reduce((O,Ne)=>O+(n[Ne.id]||0),0),he=D=>(i[D]||0)+(F.get(D)??[]).reduce((O,Ne)=>O+(i[Ne.id]||0),0),[ze,He]=a.useState(new Set),[Ve,Ue]=a.useState(null),de=async(D,O,Ne)=>{try{const Se=await Ll(D);if(!Se.canDelete){t({title:"Cannot delete round",description:Se.reason,variant:"destructive"});return}if(!confirm(`Delete "${Ne}"? This cannot be undone.`))return;await Pl(D,O),t({title:"Round deleted"}),r.invalidateQueries({queryKey:["admin-events"]})}catch(Se){t({title:"Could not delete",description:Se instanceof Error?Se.message:"Unknown error",variant:"destructive"})}},Le=D=>{He(O=>{const Ne=new Set(O);return Ne.has(D)?Ne.delete(D):Ne.add(D),Ne})},{isTimingEnabled:ye}=Wt(),{data:Ze=[]}=ms({queryKey:["mysql-events",c==null?void 0:c.id],queryFn:async()=>{if(!(c!=null&&c.id))return[];const{data:D,error:O}=await z.functions.invoke("fetch-timing-events",{body:{organization_id:c.id}});if(O)throw O;return(D==null?void 0:D.events)||[]},enabled:!!(c!=null&&c.id)&&ye}),{data:Ls=[]}=ba(),P=ks({mutationFn:async D=>{const{error:O}=await z.from("events").insert({name:D.name,slug:D.slug||null,description:D.description||null,event_date:D.event_date,location:D.location,venue_name:D.venue_name||null,max_participants:D.max_participants,track_info:D.track_info||null,image_url:D.image_url||null,is_published:D.is_published,mysql_series_name:D.mysql_series_name||null,track_id:D.track_id,regular_price:0,organization_id:(c==null?void 0:c.id)||null});if(O)throw O},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-events"]}),m(!1),$(Ea),t({title:"Event created successfully"})},onError:D=>{t({title:"Error creating event",description:D.message,variant:"destructive"})}}),Te=ks({mutationFn:async({id:D,data:O})=>{const{error:Ne}=await z.from("events").update({name:O.name,slug:O.slug||null,description:O.description||null,event_date:O.event_date,location:O.location,venue_name:O.venue_name||null,max_participants:O.max_participants,track_info:O.track_info||null,image_url:O.image_url||null,is_published:O.is_published,mysql_series_name:O.mysql_series_name||null,track_id:O.track_id}).eq("id",D);if(Ne)throw Ne},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-events"]}),m(!1),R(null),$(Ea),t({title:"Event updated successfully"})},onError:D=>{t({title:"Error updating event",description:D.message,variant:"destructive"})}}),Fe=ks({mutationFn:async D=>{const{cascadeDeletePgEvent:O}=await Cn(async()=>{const{cascadeDeletePgEvent:Ne}=await import("./eventDeletion-7FDNiyZ3.js");return{cascadeDeletePgEvent:Ne}},__vite__mapDeps([3,1,2]));return O(D)},onSuccess:D=>{r.invalidateQueries({queryKey:["admin-events"]}),D!=null&&D.mysqlError?t({title:"Event deleted (MySQL cascade had issues)",description:D.mysqlError,variant:"destructive"}):t({title:"Event deleted successfully"})},onError:D=>{t({title:"Error deleting event",description:D.message,variant:"destructive"})}}),Ye=ks({mutationFn:async({id:D,is_published:O})=>{const{error:Ne}=await z.from("events").update({is_published:O}).eq("id",D);if(Ne)throw Ne},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-events"]})}}),Xe=ks({mutationFn:async({sourceEvent:D,newName:O})=>{var cs;const Ne=O.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-"),{data:Se,error:us}=await z.from("events").insert({name:O,slug:Ne,description:D.description,event_date:D.event_date,location:D.location,venue_name:D.venue_name,max_participants:D.max_participants,track_info:D.track_info,image_url:D.image_url,is_published:!1,mysql_event_name:null,regular_price:D.regular_price,flat_service_fee:D.flat_service_fee,percentage_service_fee:D.percentage_service_fee,pass_cc_fees:D.pass_cc_fees,class_change_fee:D.class_change_fee,override_fees:D.override_fees,override_class_change_fee:D.override_class_change_fee,enforce_class_capacity:D.enforce_class_capacity,background_color:D.background_color,form_color:D.form_color,confirmation_icon_url:D.confirmation_icon_url,organization_id:D.organization_id,registration_start_date:D.registration_start_date,registration_deadline:D.registration_deadline,edit_deadline:D.edit_deadline}).select().single();if(us)throw us;const{data:ps}=await z.from("event_classes").select("*").eq("event_id",D.id);if(ps&&ps.length>0){const ys=ps.map(Ce=>({event_id:Se.id,class_name:Ce.class_name,racing_class:Ce.racing_class,additional_fee:Ce.additional_fee,max_participants:Ce.max_participants,age_limit:Ce.age_limit,age_minimum:Ce.age_minimum,class_restrictions:Ce.class_restrictions,practice_group:Ce.practice_group,class_group_id:Ce.class_group_id,sort_order:Ce.sort_order,description:Ce.description,mysql_class_name:Ce.mysql_class_name}));await z.from("event_classes").insert(ys)}const{data:xs}=await z.from("add_ons").select("*").eq("event_id",D.id);if(xs&&xs.length>0){const ys=xs.map(Ce=>({event_id:Se.id,name:Ce.name,price:Ce.price,description:Ce.description,is_available:Ce.is_available,image_url:Ce.image_url,max_quantity:Ce.max_quantity}));await z.from("add_ons").insert(ys)}const{data:G}=await z.from("form_fields").select("*").eq("event_id",D.id);if(G&&G.length>0){const ys=G.map(Ce=>({event_id:Se.id,label:Ce.label,field_type:Ce.field_type,placeholder:Ce.placeholder,help_text:Ce.help_text,is_required:Ce.is_required,options:Ce.options,field_order:Ce.field_order,default_value:Ce.default_value,validation_rules:Ce.validation_rules,conditional_rules:Ce.conditional_rules,width:Ce.width,divider_styles:Ce.divider_styles,heading_styles:Ce.heading_styles,label_styles:Ce.label_styles,help_text_styles:Ce.help_text_styles,text_color:Ce.text_color,image_url:Ce.image_url}));await z.from("form_fields").insert(ys)}const{data:De}=await z.from("confirmation_fields").select("*").eq("event_id",D.id);if(De&&De.length>0){const ys=De.map(Ce=>({event_id:Se.id,field_type:Ce.field_type,field_order:Ce.field_order,label:Ce.label,help_text:Ce.help_text,options:Ce.options,width:Ce.width,divider_styles:Ce.divider_styles,heading_styles:Ce.heading_styles,label_styles:Ce.label_styles,help_text_styles:Ce.help_text_styles,text_color:Ce.text_color,image_url:Ce.image_url}));await z.from("confirmation_fields").insert(ys)}const{data:ds}=await z.from("bike_makes").select("*").eq("event_id",D.id);if(ds&&ds.length>0){const ys=ds.map(Ce=>({event_id:Se.id,name:Ce.name,abbreviation:Ce.abbreviation}));await z.from("bike_makes").insert(ys)}const{data:Ge}=await z.from("class_groups").select("*").eq("event_id",D.id);if(Ge&&Ge.length>0){const ys=Ge.map(Ce=>({event_id:Se.id,name:Ce.name,max_participants:Ce.max_participants}));await z.from("class_groups").insert(ys)}const{data:ss}=await z.from("coupons").select("*").eq("event_id",D.id);if(ss&&ss.length>0){const ys=ss.map(Ce=>({event_id:Se.id,code:Ce.code,discount_type:Ce.discount_type,discount_value:Ce.discount_value,max_uses:Ce.max_uses,current_uses:0,expires_at:Ce.expires_at,is_active:Ce.is_active}));await z.from("coupons").insert(ys)}let es={linked:!1};return ye&&(es=await Ld({value:V,newEventId:Se.id,newEventName:O,newEventDate:D.event_date??null,sourceLabEventId:((cs=Y.sourceLabEvent)==null?void 0:cs.id)??null})),{newEvent:Se,labResult:es}},onSuccess:({labResult:D})=>{r.invalidateQueries({queryKey:["admin-events"]}),f(!1),C(null),Q(""),H({mode:"copy",labEventId:""}),t({title:"Event duplicated successfully",description:D.created?"Timing Lab event copied and linked to the new event."
49:D.linked?"Timing Lab event linked to the new event.":"Registration only — no Timing Lab event is linked."})},onError:D=>{t({title:"Error duplicating event",description:D.message,variant:"destructive"})}}),bs=D=>{D.preventDefault(),Z?Te.mutate({id:Z.id,data:E}):P.mutate(E)},Ts=()=>{m(!1),R(null),$(Ea)},Ps=D=>{C(D),Q(`${D.name} (Copy)`),H({mode:"copy",labEventId:""}),f(!0)},Rs=D=>{D.preventDefault(),T&&L.trim()&&Xe.mutate({sourceEvent:T,newName:L.trim()})};return _?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading events..."}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center","data-tour":"events-list",children:[e.jsx("h2",{className:"font-display text-2xl text-foreground",children:"Manage Events"}),e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Us,{children:[e.jsx(zs,{asChild:!0,children:e.jsx("span",{children:e.jsxs(w,{variant:"outline",onClick:()=>N(!0),disabled:!te,children:[te?e.jsx(Ba,{className:"mr-2 h-4 w-4"}):e.jsx(ct,{className:"mr-2 h-4 w-4"}),"Create Series"]})})}),!te&&e.jsx(Vs,{children:e.jsx("p",{children:"Creating series is not enabled for your organization"})})]}),e.jsxs(Us,{children:[e.jsx(zs,{asChild:!0,children:e.jsx("span",{"data-tour":"create-event-btn",children:e.jsxs(w,{className:"bg-gradient-fire hover:opacity-90",onClick:()=>u(!0),disabled:!te,children:[te?e.jsx(Es,{className:"mr-2 h-4 w-4"}):e.jsx(ct,{className:"mr-2 h-4 w-4"}),"Add Event"]})})}),!te&&e.jsx(Vs,{children:e.jsx("p",{children:"Creating events is not enabled for your organization"})})]})]})})]}),e.jsx(Cd,{open:p,onOpenChange:u}),e.jsx(Rd,{open:l,onOpenChange:N,onCreated:D=>{g(D),k(void 0)}}),e.jsx($d,{open:!!j,onOpenChange:D=>{D||g(null)},seriesEventId:j,seriesName:y}),e.jsx(ts,{open:o,onOpenChange:m,children:e.jsxs(as,{className:"max-w-2xl max-h-[90vh] overflow-y-auto bg-card border-border",children:[e.jsx(rs,{children:e.jsx(is,{className:"font-display text-xl",children:"Edit Event"})}),e.jsxs("form",{onSubmit:bs,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(v,{htmlFor:"name",className:"flex items-center gap-2",children:["Event Name *",b.locked&&e.jsx(ct,{className:"h-3.5 w-3.5 text-muted-foreground"})]}),e.jsx(A,{id:"name",value:E.name,onChange:D=>$({...E,name:D.target.value}),required:!0,disabled:I}),b.locked&&e.jsx("p",{className:"text-xs text-muted-foreground",children:Vl(b.reason,x)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"slug",children:"URL Slug"}),e.jsx(A,{id:"slug",value:E.slug,onChange:D=>$({...E,slug:D.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-")}),placeholder:"my-event-name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"event_date",children:"Event Date *"}),e.jsx(A,{id:"event_date",type:"date",value:E.event_date,onChange:D=>$({...E,event_date:D.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"location",children:"Location *"}),e.jsx(A,{id:"location",value:E.location,onChange:D=>$({...E,location:D.target.value}),required:!0})]}),e.jsx("div",{className:"space-y-2 md:col-span-2",children:e.jsx(Br,{value:E.track_id,onChange:D=>$(O=>({...O,track_id:(D==null?void 0:D.id)??null,venue_name:O.venue_name||(D==null?void 0:D.name)||"",location:O.location||[D==null?void 0:D.city,D==null?void 0:D.state].filter(Boolean).join(", ")})),label:"Track (shared library)"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"venue_name",children:"Venue Name"}),e.jsx(A,{id:"venue_name",value:E.venue_name,onChange:D=>$({...E,venue_name:D.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"max_participants",children:"Max Participants"}),e.jsx(A,{id:"max_participants",type:"number",value:E.max_participants,onChange:D=>$({...E,max_participants:parseInt(D.target.value)})})]})]}),e.jsxs("div",{className:"space-y-4 p-4 border border-border rounded-lg",children:[e.jsxs(v,{className:"flex items-center gap-2 text-base font-semibold",children:[e.jsx(Tt,{className:"h-4 w-4"}),"Timing System Link"]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"mysql_series_name",children:"Linked Series"}),e.jsxs(Pe,{value:E.mysql_series_name||"none",onValueChange:D=>{$({...E,mysql_series_name:D==="none"?"":D})},children:[e.jsx(Ie,{children:e.jsx(qe,{placeholder:"Select a series..."})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"none",children:"None"}),Ls.map(D=>e.jsx(ae,{value:D,children:D},D))]})]})]}),E.mysql_series_name&&(()=>{const D=(Ze||[]).filter(O=>O.series_name===E.mysql_series_name).sort((O,Ne)=>{const Se=new Date(Number(O.event_date_year),Number(O.event_date_month)-1,Number(O.event_date_day)),us=new Date(Number(Ne.event_date_year),Number(Ne.event_date_month)-1,Number(Ne.event_date_day));return Se.getTime()-us.getTime()});return e.jsx("div",{className:"bg-muted/30 rounded-lg p-2 space-y-1 max-h-32 overflow-y-auto text-sm",children:D.map(O=>e.jsxs("div",{className:"flex justify-between py-0.5 px-2",children:[e.jsx("span",{children:O.event_name}),e.jsxs("span",{className:"text-muted-foreground text-xs",children:[O.event_date_month,"/",O.event_date_day,"/",O.event_date_year]})]},O.event_name))})})()]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"description",children:"Description"}),e.jsx(Ns,{id:"description",value:E.description,onChange:D=>$({...E,description:D.target.value}),rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"track_info",children:"Track Info"}),e.jsx(Ns,{id:"track_info",value:E.track_info,onChange:D=>$({...E,track_info:D.target.value}),rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"image_url",children:"Image URL"}),e.jsx(A,{id:"image_url",value:E.image_url,onChange:D=>$({...E,image_url:D.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ds,{id:"is_published",checked:E.is_published,onCheckedChange:D=>$({...E,is_published:D}),disabled:!le&&!E.is_published}),e.jsxs(v,{htmlFor:"is_published",children:["Publish Event",!le&&e.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:"(requires signed agreement)"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-4",children:[e.jsx(w,{type:"button",variant:"outline",onClick:Ts,children:"Cancel"}),e.jsx(w,{type:"submit",className:"bg-gradient-fire hover:opacity-90",children:"Update Event"})]})]})]})}),e.jsx(ts,{open:S,onOpenChange:f,children:e.jsxs(as,{className:"max-w-md bg-card border-border",children:[e.jsx(rs,{children:e.jsx(is,{className:"font-display text-xl",children:"Duplicate Event"})}),e.jsxs("form",{onSubmit:Rs,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"duplicate_name",children:"New Event Name *"}),e.jsx(A,{id:"duplicate_name",value:L,onChange:D=>Q(D.target.value),placeholder:"Enter name for the new event",required:!0}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:['This will copy all settings, classes, add-ons, form fields, and coupons from "',T==null?void 0:T.name,'" to a new draft event.']})]}
49),ye&&e.jsx(Ad,{value:V,onChange:H,sourceLabEvent:Y.sourceLabEvent,unlinked:Y.unlinked,loading:Y.loading}),e.jsxs("div",{className:"flex gap-2 pt-4",children:[e.jsx(w,{type:"button",variant:"outline",onClick:()=>{f(!1),C(null),Q("")},children:"Cancel"}),e.jsx(w,{type:"submit",className:"bg-gradient-fire hover:opacity-90",disabled:Xe.isPending||ye&&!Fd(V,!!Y.sourceLabEvent),children:Xe.isPending?"Duplicating...":"Duplicate Event"})]})]})]})}),X.length===0?e.jsx(re,{className:"bg-card border-border",children:e.jsxs(xe,{className:"py-12 text-center",children:[e.jsx(At,{className:"h-12 w-12 text-muted-foreground mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"No events yet. Create your first event!"})]})}):e.jsxs("div",{className:"grid gap-4",children:[$e.length>0&&e.jsxs("h3",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide mt-2",children:["Series (",$e.length,")"]}),[...$e,...me,...ee?_e:[]].map((D,O)=>{const Ne=ne(D),Se=!!D.archived_at,us=F.get(D.id)??[],ps=ze.has(D.id),xs=us.length?(()=>{const Ge=[...us].sort((ss,es)=>String(ss.event_date).localeCompare(String(es.event_date)));return{first:Ge[0].event_date,last:Ge[Ge.length-1].event_date}})():null,G=!Se&&U(D),De=Ne?`/admin/events/${D.id}/registrations?scope=series`:`/admin/events/${D.id}/registrations`,ds=!Se&&!Ne&&O===$e.length?e.jsxs("h3",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide mt-4",children:["Single events (",me.length,")"]},"single-header"):Se&&O===$e.length+me.length?e.jsx(fr,{count:_e.length,open:ee,onToggle:()=>pe(Ge=>!Ge)},"archived-header"):null;return e.jsxs("div",{className:"contents",children:[ds,e.jsx(re,{className:`bg-card border-border ${Se?"opacity-70":""}`,children:e.jsxs(xe,{className:"p-4",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[Ne&&e.jsx(w,{variant:"ghost",size:"icon",className:"h-7 w-7 -ml-1",onClick:()=>Le(D.id),title:ps?"Collapse rounds":"Expand rounds",children:ps?e.jsx(mt,{className:"h-4 w-4"}):e.jsx(Hs,{className:"h-4 w-4"})}),e.jsx("h3",{className:"font-display text-lg text-foreground",children:D.name}),Ne&&e.jsxs("span",{className:"text-xs bg-accent/40 text-accent-foreground px-2 py-0.5 rounded flex items-center gap-1",children:[e.jsx(Ba,{className:"h-3 w-3"}),"Series · ",us.length," round",us.length===1?"":"s"]}),D.is_published?e.jsx("span",{className:"text-xs bg-success/20 text-success px-2 py-0.5 rounded",children:"Published"}):e.jsx("span",{className:"text-xs bg-muted text-muted-foreground px-2 py-0.5 rounded",children:"Draft"}),D.mysql_series_name&&e.jsxs("span",{className:"text-xs bg-primary/20 text-primary px-2 py-0.5 rounded flex items-center gap-1",children:[e.jsx(Tt,{className:"h-3 w-3"}),"Linked"]}),Se&&e.jsxs("span",{className:"text-xs bg-muted text-muted-foreground px-2 py-0.5 rounded flex items-center gap-1",children:[e.jsx(Fa,{className:"h-3 w-3"}),"Archived"]}),G&&e.jsxs("button",{type:"button",onClick:()=>{ue(D,!0)},disabled:!B||se.isPending,className:"text-xs bg-amber-500/15 text-amber-700 px-2 py-0.5 rounded flex items-center gap-1 hover:bg-amber-500/25 disabled:opacity-50",title:"This event is finished — click to archive it",children:[e.jsx(Fa,{className:"h-3 w-3"}),"Ready to archive"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-4 text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(At,{className:"h-4 w-4"}),Ne&&xs?`${Js(Vt(xs.first),"MMM d, yyyy")} – ${Js(Vt(xs.last),"MMM d, yyyy")}`:Js(Vt(D.event_date),"MMM d, yyyy")]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Tn,{className:"h-4 w-4"}),D.location]}),!Ne&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(_a,{className:"h-4 w-4"}),"Dynamic pricing"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(w,{variant:"ghost",size:"icon",onClick:()=>d(`/admin/events/${D.id}/analytics`),title:"Event Analytics",children:e.jsx(sa,{className:"h-4 w-4"})}),e.jsxs("div",{className:"relative",children:[e.jsx(w,{variant:"ghost",size:"icon",onClick:()=>d(De),title:"Registrations",children:e.jsx(Gs,{className:"h-4 w-4"})}),(()=>{const Ge=Ne?ve(D.id):n[D.id]||0,ss=Ne?he(D.id):i[D.id]||0;return e.jsxs(e.Fragment,{children:[Ge>0&&e.jsx(wt,{children:e.jsxs(Us,{children:[e.jsx(zs,{asChild:!0,children:e.jsx("span",{className:"absolute -top-1 -right-1 flex h-5 min-w-[1.25rem] items-center justify-center rounded-full bg-destructive px-1 text-[10px] font-bold text-destructive-foreground cursor-help",children:Ge})}),e.jsx(Vs,{children:e.jsxs("p",{children:[Ge," pending rider match review",Ge===1?"":"s",Ne?" across rounds":""]})})]})}),ss>0&&e.jsx(wt,{children:e.jsxs(Us,{children:[e.jsx(zs,{asChild:!0,children:e.jsx("span",{className:"absolute -bottom-1 -right-1 flex h-5 min-w-[1.25rem] items-center justify-center rounded-full bg-amber-500 px-1 text-[10px] font-bold text-white cursor-help",children:ss})}),e.jsx(Vs,{children:e.jsxs("p",{children:[ss," abandoned registration",ss===1?"":"s",Ne?" across rounds":""]})})]})})]})})()]}),e.jsx(wt,{children:e.jsxs(Us,{children:[e.jsx(zs,{asChild:!0,children:e.jsx("span",{children:e.jsx(w,{variant:"ghost",size:"icon",onClick:()=>d(`/admin/events/${D.id}
49/settings`),title:Ne?"Series Setup":"Event Settings",disabled:!B,children:B?e.jsx(Ua,{className:"h-4 w-4"}):e.jsx(ct,{className:"h-4 w-4"})})})}),!B&&e.jsx(Vs,{children:e.jsx("p",{children:"Editing events is not enabled for your organization"})})]})}),e.jsx(wt,{children:e.jsxs(Us,{children:[e.jsx(zs,{asChild:!0,children:e.jsx("span",{children:e.jsx(w,{variant:"ghost",size:"icon",onClick:()=>d(`/admin/events/${D.id}/form-builder`),title:"Edit Registration Form",disabled:!B,children:B?e.jsx(jt,{className:"h-4 w-4"}):e.jsx(ct,{className:"h-4 w-4"})})})}),!B&&e.jsx(Vs,{children:e.jsx("p",{children:"Editing events is not enabled for your organization"})})]})}),e.jsx(w,{variant:"ghost",size:"icon",onClick:()=>M(D),title:"Share Event",children:e.jsx(lr,{className:"h-4 w-4"})}),e.jsx(wt,{children:e.jsxs(Us,{children:[e.jsx(zs,{asChild:!0,children:e.jsx("span",{children:e.jsx(w,{variant:"ghost",size:"icon",onClick:()=>Ye.mutate({id:D.id,is_published:!D.is_published}),title:D.is_published?"Unpublish":le?"Publish":"Sign service agreement to publish",disabled:!B||!D.is_published&&!le,children:!B||!D.is_published&&!le?e.jsx(ct,{className:"h-4 w-4"}):D.is_published?e.jsx(Dc,{className:"h-4 w-4"}):e.jsx(Zt,{className:"h-4 w-4"})})})}),(!B||!D.is_published&&!le)&&e.jsx(Vs,{children:e.jsx("p",{children:B?"Sign the service agreement to publish events":"Editing events is not enabled for your organization"})})]})}),e.jsx(w,{variant:"ghost",size:"icon",onClick:()=>{ue(D,!Se)},title:Se?"Unarchive":"Archive",disabled:!B||se.isPending,children:Se?e.jsx(cc,{className:"h-4 w-4"}):e.jsx(Fa,{className:"h-4 w-4"})}),e.jsx(wt,{children:e.jsxs(Us,{children:[e.jsx(zs,{asChild:!0,children:e.jsx("span",{children:e.jsx(w,{variant:"ghost",size:"icon",onClick:()=>Ps(D),title:"Duplicate Event",disabled:!te,children:te?e.jsx(Nt,{className:"h-4 w-4"}):e.jsx(ct,{className:"h-4 w-4"})})})}),!te&&e.jsx(Vs,{children:e.jsx("p",{children:"Creating events is not enabled for your organization"})})]})}),e.jsx(wt,{children:e.jsxs(Us,{children:[e.jsx(zs,{asChild:!0,children:e.jsx("span",{children:e.jsx(w,{variant:"ghost",size:"icon",onClick:()=>{confirm("Are you sure you want to delete this event?")&&Fe.mutate(D.id)},className:"text-destructive hover:text-destructive",disabled:!B,children:B?e.jsx(ws,{className:"h-4 w-4"}):e.jsx(ct,{className:"h-4 w-4"})})})}),!B&&e.jsx(Vs,{children:e.jsx("p",{children:"Editing events is not enabled for your organization"})})]})})]})]}),Ne&&ps&&e.jsxs("div",{className:"mt-3 pt-3 border-t border-border space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide",children:["Series rounds (",us.length,")"]}),e.jsxs(w,{size:"sm",variant:"outline",className:"h-7",onClick:()=>Ue({id:D.id,name:D.name}),disabled:!B,children:[e.jsx(Es,{className:"mr-1 h-3.5 w-3.5"}),"Add round"]})]}),us.map(Ge=>e.jsxs("div",{className:"flex items-center justify-between gap-2 py-1 px-2 rounded hover:bg-muted/50 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsxs("span",{className:"text-xs font-mono text-muted-foreground w-16 shrink-0",children:["Round ",Ge.child_race_index??"?"]}),e.jsx("span",{className:"truncate",children:Ge.name})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:Js(Vt(Ge.event_date),"MMM d, yyyy")}),e.jsxs(w,{variant:"outline",size:"sm",className:"h-7 px-2 gap-1",onClick:()=>d(`/admin/events/${Ge.id}/registrations`),title:"Registrations, Check-In & Review for this round",children:[e.jsx(Gs,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs",children:"Registrations"})]}),e.jsx(w,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>M(Ge),title:"Share this round",children:e.jsx(lr,{className:"h-3.5 w-3.5"})}),e.jsx(w,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>d(`/admin/events/${Ge.id}/settings`),title:"Settings",disabled:!B,children:e.jsx(Ua,{className:"h-3.5 w-3.5"})}),e.jsx(w,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:()=>de(Ge.id,D.id,Ge.name),title:"Delete round (only if no registrations or MySQL link)",disabled:!B,children:e.jsx(ws,{className:"h-3.5 w-3.5"})})]})]},Ge.id)),us.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground py-2",children:'No rounds yet — click "Add round" to create one.'})]})]})})]},D.id)}),!ee&&_e.length>0&&e.jsx(fr,{count:_e.length,open:!1,onToggle:()=>pe(!0)})]}),e.jsx(Ol,{open:!!Ve,onOpenChange:D=>{D||Ue(null)},seriesId:(Ve==null?void 0:Ve.id)??null,seriesName:Ve==null?void 0:Ve.name}),h&&c&&e.jsx(gd,{open:!!h,onOpenChange:D=>{D||M(null)},eventId:h.id,organizationId:c.id,eventName:h.name,eventDate:h.event_date,location:h.location,targetUrl:`${ta()}/org/${c.slug}/events/${h.slug||h.id}`})]})}function fr({count:s,open:n,onToggle:i}){return e.jsxs("button",{type:"button",onClick:i,className:"mt-6 flex w-full items-center gap-2 rounded border border-dashed border-border px-3 py-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground hover:bg-muted/50",children:[n?e.jsx(mt,{className:"h-4 w-4"}):e.jsx(Hs,{className:"h-4 w-4"}),e.jsx(Fa,{className:"h-3.5 w-3.5"}
49),"Archived (",s,")",e.jsx("span",{className:"ml-auto normal-case font-normal",children:n?"Hide":"Show"})]})}function Id({open:s,onOpenChange:n,url:i,label:t,orgName:d}){const r=a.useRef(null),x=()=>{var p;return(p=r.current)==null?void 0:p.querySelector("canvas")},c=`${d}-${t}`.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),o=()=>{const p=x();if(!p)return;const u=document.createElement("a");u.download=`${c}-qr.png`,u.href=p.toDataURL("image/png"),u.click(),K.success("QR code downloaded")},m=()=>{const p=x();if(!p)return;const u=p.toDataURL("image/png"),l=window.open("","_blank","width=800,height=900");if(!l){K.error("Allow pop-ups to print the QR code");return}l.document.write(`<!doctype html><html><head><title>${d} — ${t}</title>
50      <style>
51        body{font-family:system-ui,sans-serif;text-align:center;padding:48px;}
52        h1{font-size:28px;margin:0 0 4px;}
53        h2{font-size:18px;font-weight:500;margin:0 0 24px;color:#555;}
54        img{width:420px;height:420px;}
55        p{font-size:13px;color:#444;word-break:break-all;margin-top:16px;}
56      </style></head><body>
57      <h1>${d}</h1><h2>${t}</h2>
58      <img src="${u}" alt="QR code" />
59      <p>${i}</p>
60      <script>window.onload=function(){window.focus();window.print();}<\/script>
61      </body></html>`),l.document.close()};return e.jsx(ts,{open:s,onOpenChange:n,children:e.jsxs(as,{className:"sm:max-w-md",children:[e.jsxs(rs,{children:[e.jsxs(is,{children:[t," QR Code"]}),e.jsx(Fs,{className:"break-all",children:i})]}),e.jsx("div",{ref:r,className:"flex justify-center rounded-lg border bg-background p-6",children:e.jsx(Hr,{value:i,size:256,level:"M",marginSize:2})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(w,{variant:"outline",className:"flex-1",onClick:o,children:[e.jsx($t,{className:"mr-2 h-4 w-4"})," Download PNG"]}),e.jsxs(w,{className:"flex-1",onClick:m,children:[e.jsx(ja,{className:"mr-2 h-4 w-4"})," Print"]})]})]})})}function qd({defaultOpen:s=!1}={}){const{currentOrganization:n}=Je(),[i,t]=a.useState(null),[d,r]=a.useState(s),[x,c]=a.useState(null);if(!n)return null;const o=ta(),m=`${o}/org/${n.slug}/main`,p=`${o}/org/${n.slug}/events`,u=`${o}/org/${n.slug}/login`,l=`${o}/org/${n.slug}/timing`,N=[{label:"Main Page",url:m,key:"home"},{label:"Events Page",url:p,key:"events"},{label:"Live Timing",url:l,key:"timing"},{label:"Rider Login",url:u,key:"login"}],j=async(g,y)=>{await navigator.clipboard.writeText(g),t(y),K.success("Copied to clipboard"),setTimeout(()=>t(null),2e3)};return e.jsxs(re,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(Pn,{open:d,onOpenChange:r,children:[e.jsx(In,{asChild:!0,children:e.jsx(ke,{className:"cursor-pointer hover:bg-muted/50 transition-colors py-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(An,{className:"h-4 w-4 text-primary"}),e.jsx(Ee,{className:"text-sm font-medium",children:"Shareable Links"}),e.jsx(ie,{variant:"outline",className:"text-xs",children:n.name})]}),d?e.jsx(Ar,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(mt,{className:"h-4 w-4 text-muted-foreground"})]})})}
61),e.jsx(qn,{children:e.jsxs(xe,{className:"pt-0 pb-3",children:[e.jsx(ns,{className:"text-xs mb-3",children:"Share these links with riders."}),e.jsx("div",{className:"space-y-2",children:N.map(g=>e.jsxs("div",{className:"p-2 bg-background rounded-md border flex items-center gap-3",children:[e.jsx("button",{type:"button",onClick:()=>c({label:g.label,url:g.url}),className:"flex-shrink-0 rounded border bg-background p-1 hover:ring-2 hover:ring-primary/40 transition",title:`Open ${g.label} QR code`,"aria-label":`Open ${g.label} QR code`,children:e.jsx(Hr,{value:g.url,size:44,level:"M",marginSize:1})}),e.jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:g.label}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("a",{href:g.url,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline truncate block min-w-0 flex-1",children:g.url}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsx(w,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>c({label:g.label,url:g.url}),title:"QR code",children:e.jsx(Qr,{className:"h-3 w-3"})}),e.jsx(w,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>j(g.url,g.key),title:"Copy link",children:i===g.key?e.jsx(Os,{className:"h-3 w-3 text-green-600"}):e.jsx(Nt,{className:"h-3 w-3"})}),e.jsx(w,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",asChild:!0,children:e.jsx("a",{href:g.url,target:"_blank",rel:"noopener noreferrer",children:e.jsx(ea,{className:"h-3 w-3"})})})]})]})]})]},g.key))})]})})]}),x&&e.jsx(Id,{open:!!x,onOpenChange:g=>!g&&c(null),url:x.url,label:x.label,orgName:n.name})]})}const Bd=7,Ud=10;function zd(){return new Intl.DateTimeFormat("en-CA",{timeZone:"America/Denver",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date)}function Vd(s,n){const[i,t,d]=s.split("-").map(Number),r=new Date(Date.UTC(i,t-1,d));return r.setUTCDate(r.getUTCDate()+n),r.toISOString().slice(0,10)}function Od(s,n){const[i,t,d]=s.split("-").map(Number),[r,x,c]=n.split("-").map(Number);return Math.round((Date.UTC(r,x-1,c)-Date.UTC(i,t-1,d))/864e5)}function Gd(s){const[n,i]=a.useState({loading:!0,needsAttention:!1,reason:null,daysOut:null,eventName:null,eventDate:null,latestVersion:null,installedVersion:null,lastSeenAt:null});return a.useEffect(()=>{if(!s){i(r=>({...r,loading:!1,needsAttention:!1}));return}let t=!1;return(async()=>{const r=zd(),[{data:x},{data:c},{data:o}]=await Promise.all([z.from("timing_lab_events").select("id, name, event_date").eq("organization_id",s).gte("event_date",r).lte("event_date",Vd(r,Ud)).order("event_date",{ascending:!0}).limit(1),z.from("rfid_bridges").select("id, app_version, last_heartbeat_at, is_active").eq("organization_id",s),z.from("bridge_releases").select("version").eq("is_active",!0).order("created_at",{ascending:!1}).limit(1).maybeSingle()]);if(t)return;const m=x==null?void 0:x[0],p=(o==null?void 0:o.version)??null;if(!m){i({loading:!1,needsAttention:!1,reason:null,daysOut:null,eventName:null,eventDate:null,latestVersion:p,installedVersion:null,lastSeenAt:null});return}const u=(c??[]).filter(S=>S.is_active!==!1),l=Date.now()-Bd*864e5,N=u.filter(S=>S.last_heartbeat_at&&new Date(S.last_heartbeat_at).getTime()>=l),j=[...u].sort((S,f)=>new Date(f.last_heartbeat_at??0).getTime()-new Date(S.last_heartbeat_at??0).getTime())[0];let g=null,y=null,k=null;if(u.length===0)g="not_installed";else if(N.length===0)g="stale_heartbeat",y=(j==null?void 0:j.app_version)??null,k=(j==null?void 0:j.last_heartbeat_at)??null;else{const S=[...N].sort((f,h)=>cr(h.app_version,f.app_version))[0];y=(S==null?void 0:S.app_version)??null,k=(S==null?void 0:S.last_heartbeat_at)??null,p&&cr(S==null?void 0:S.app_version,p)<0&&(g="outdated_version")}i({loading:!1,needsAttention:!!g,reason:g,daysOut:Od(r,m.event_date),eventName:m.name??null,eventDate:m.event_date??null,latestVersion:p,installedVersion:y,lastSeenAt:k})})(),()=>{t=!0}},[s]),n}function Yd({organizationId:s}){const n=Gd(s);if(n.loading||!n.needsAttention||n.daysOut==null)return null;const i=n.daysOut===0?"today":n.daysOut===1?"tomorrow":`in ${n.daysOut} days`,t=n.reason==="not_installed"?"Timing bridge not installed yet":n.reason==="stale_heartbeat"?"Timing bridge hasn't checked in":`Timing bridge update available — v${n.latestVersion}`,d=n.reason==="not_installed"?"We don't see a paired bridge for your organization. Download, install and pair it on the timing laptop, then take a few test reads before race day.":n.reason==="stale_heartbeat"?`Your bridge is paired but hasn't checked in recently${n.lastSeenAt?` (last seen ${new Date(n.lastSeenAt).toLocaleDateString()})`:""}. Open the bridge app on the timing laptop, confirm it says Paired, connect the reader and take a test read.`:`Your bridge is running v${n.installedVersion??"unknown"}. Install v${n.latestVersion} and re-test before the gate drops.`;return e.jsxs("div",{className:"mb-4 flex items-start gap-3 rounded-lg border border-amber-500/60 bg-amber-500/10 p-3",children:[e.jsx(Is,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-amber-600"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"text-sm font-semibold text-amber-900",children:[t," — ",n.eventName??"Your event"," is ",i]}),e.jsx("p",{className:"mt-0.5 text-xs text-amber-800",children:d}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[e.jsx(w,{asChild:!0,size:"sm",className:"h-7 bg-amber-600 text-white hover:bg-amber-700",children:e.jsxs(sr,{to:"/admin/bridge-download",children:[e.jsx($t,{className:"mr-1 h-3.5 w-3.5"}),"Download & pair the bridge"]})}),e.jsx(w,{asChild:!0,size:"sm",variant:"outline",className:"h-7 border-amber-500 text-amber-800",children:e.jsxs(sr,{to:"/admin/guides/bridge-install",children:[e.jsx(Wr,{className:"mr-1 h-3.5 w-3.5"}),"Install guide"]})})]})]})]})}function Kd({organizationId:s}){const[n,i]=a.useState(!1),{contract:t,hasSignedCurrentVersion:d,isLoading:r}=Bn(s),{account:x,isLoading:c,createAccount:o,getOnboardLink:m}=Un(s);if(r||c||!d||!t||!!t.stripe_onboarding_completed_at||!!x&&x.charges_enabled&&x.payouts_enabled&&x.details_submitted||x!=null&&x.stripe_account_id)return null;const u=async()=>{i(!0);try{x!=null&&x.stripe_account_id||await o.mutateAsync(s);const l=await m.mutateAsync(s);if(l!=null&&l.url){window.location.href=l.url;return}throw new Error("No onboarding URL returned")}catch(l){K.error((l==null?void 0:l.message)||"Failed to start bank setup"),i(!1)}};return e.jsxs("div",{className:"rounded-lg border border-destructive/40 bg-destructive/10 p-4 flex items-start gap-3 mb-3",children:[e.jsx(Zr,{className:"h-5 w-5 mt-0.5 text-destructive flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm",children:"Bank account setup required to receive payouts"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Your service agreement was signed before bank setup was added to onboarding. Until you connect a Stripe account, weekly net revenue is held by the platform and new events cannot be published."})]}),e.jsxs(w,{size:"sm",onClick:u,disabled:n,className:"flex-shrink-0",children:[n?e.jsx(oe,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(jn,{className:"h-4 w-4 mr-2"}),"Set up bank account"]})]})}const jr=160,Hd=153;function Qd({message:s,onMessageChange:n,recipientCount:i,onSend:t,isSending:d,disabled:r=!1,crossPost:x,onCrossPostChange:c,sendLabel:o}){const m=s.length,p=m<=jr?1:Math.ceil(m/Hd),u=p>1,l=m>320,N=s.trim().length>0&&i>0&&!r&&!l;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(v,{htmlFor:"message-input",children:"Message"}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[u&&e.jsxs("span",{className:"text-amber-600 flex items-center gap-1",children:[e.jsx(Is,{className:"h-3 w-3"}),p," segments"]}),e.jsxs("span",{className:Cs("tabular-nums",l?"text-destructive":m>jr?"text-amber-600":"text-muted-foreground"),children:[m,"/320"]})]})]}),e.jsx(Ns,{id:"message-input",placeholder:"Type your message here...",value:s,onChange:j=>n(j.target.value),rows:4,className:"resize-none",disabled:d}),u&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Messages over 160 characters are sent as multiple segments and may cost more."})]}),x&&c&&e.jsx(Jr,{value:x,onChange:c}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:i>0?e.jsxs("span",{children:["Sending to ",e.jsx("strong",{className:"text-foreground",children:i})," recipient",i!==1?"s":""]}):e.jsx("span",{children:"Select recipients above"})}),e.jsx(w,{onClick:t,disabled:!N||d,size:"lg",children:d?e.jsxs(e.Fragment,{children:[e.jsx(oe,{className:"mr-2 h-4 w-4 animate-spin"}),o?"Scheduling...":"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(gt,{className:"mr-2 h-4 w-4"}),o??(x!=null&&x.enabled?"Send & Post to Feed":"Send Message")]})})]})]})}function Wd({recipients:s,onRemove:n,isLoading:i=!1,onClear:t}){return i?e.jsx("div",{className:"border rounded-lg p-4",children:e.jsx("div",{className:"flex items-center justify-center py-8 text-muted-foreground",children:"Loading recipients..."})}):s.length===0?e.jsx("div",{className:"border rounded-lg p-4",children:e.jsx("div",{className:"flex items-center justify-center py-8 text-muted-foreground",children:"No recipients selected. Choose an event/class or search for riders above."})}):e.jsxs("div",{className:"border rounded-lg",children:[e.jsxs("div",{className:"p-3 border-b bg-muted/50 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-sm",children:"Recipients"}),e.jsx(ie,{variant:"secondary",children:s.length})]}),t&&e.jsxs(w,{variant:"ghost",size:"sm",className:"h-7 text-xs text-muted-foreground hover:text-destructive",onClick:t,children:[e.jsx(ws,{className:"h-3 w-3 mr-1"}),"Clear All"]})]}),e.jsx(qs,{className:"h-[200px]",children:e.jsx("div",{className:"divide-y",children:s.map(d=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 hover:bg-muted/50",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-muted flex items-center justify-center",children:e.jsx(Xs,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-medium",children:d.name||`Member #${d.memberNumber}`}),e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Rt,{className:"h-3 w-3"}),d.phone,d.source==="rider_alerts"&&e.jsx(ie,{variant:"outline",className:"ml-1 text-[10px] px-1 py-0",children:"Alert"}),d.source==="manual"&&e.jsx(ie,{variant:"outline",className:"ml-1 text-[10px] px-1 py-0",children:"Manual"})]})]})]}),e.jsx(w,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>n(d.phone),children:e.jsx(vt,{className:"h-3 w-3"})})]},d.phone))})})]})}function vr(s){const n=s.replace(/\D/g,"");return n.length===10?`1${n}`:n.length===11&&n.startsWith("1")?n:s}function Qn({onAddRecipient:s,existingPhones:n}){const[i,t]=a.useState(""),[d,r]=a.useState(null),{data:x,isLoading:c}=Xa(i,i.length>=2),{currentOrganization:o}=Je(),m=async u=>{var l;if(o!=null&&o.id){r(u.memberNumber);try{const{data:N,error:j}=await z.functions.invoke("expand-rider-alert-phones",{body:{organization_id:o.id,member_numbers:[u.memberNumber]}}),g=!j&&((l=N==null?void 0:N.phones)!=null&&l.length)?N.phones.map(k=>({phone:k.phone,name:k.name||`${u.firstName} ${u.lastName}`})):[],y=`${u.firstName} ${u.lastName}`.trim();if(g.length>0)for(const k of g)s({phone:k.phone,name:k.name||y,memberNumber:u.memberNumber});else u.phoneNumber&&s({phone:vr(u.phoneNumber),name:y,memberNumber:u.memberNumber})}finally{r(null)}}},p=u=>{if(!u.phoneNumber)return!1;const l=vr(u.phoneNumber);return n.has(l)};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Ws,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(A,{placeholder:"Search riders by name or member #...",value:i,onChange:u=>t(u.target.value),className:"pl-10"})]}),i.length>=2&&e.jsx(qs,{className:"h-[200px] rounded-md border",children:c?e.jsx("div",{className:"flex items-center justify-center h-full p-4",children:e.jsx(oe,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):x&&x.length>0?e.jsx("div",{className:"p-2 space-y-1",children:x.map(u=>{const l=!!u.phoneNumber,N=p(u),j=d===u.memberNumber;return e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-md hover:bg-muted/50",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(Xs,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium text-sm",children:[u.firstName," ",u.lastName]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["#",u.memberNumber," • ",u.phoneNumber||"No phone"]})]})]}),e.jsx(w,{size:"sm",variant:N?"secondary":"outline",onClick:()=>m(u),disabled:!l||N||j,children:j?e.jsx(oe,{className:"h-3 w-3 animate-spin"}):N?"Added":e.jsxs(e.Fragment,{children:[e.jsx(Es,{className:"h-3 w-3 mr-1"}),"Add"]})})]},u.memberNumber)})}):e.jsx("div",{className:"flex items-center justify-center h-full p-4 text-muted-foreground text-sm",children:"No riders found"})}),i.length>0&&i.length<2&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Type at least 2 characters to search"})]})}function en(){const{currentOrganization:s}=Je();return ks({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("No organization selected");const{data:i,error:t}=await z.functions.invoke("fetch-sms-recipients",{body:{organization_id:s.id,year:n.year,series_name:n.seriesName,event_name:n.eventName,class_name:n.className,member_numbers:n.memberNumbers,temp_transponders_only:n.tempTranspondersOnly,all_riders:n.allRiders,registered_from:n.registeredFrom,registered_to:n.registeredTo,event_id:n.eventId}});if(t)throw t;return i.recipients}})}function il(){const{currentOrganization:s}=Je();return ms({queryKey:["message-groups",s==null?void 0:s.id],queryFn:async()=>
61{if(!(s!=null&&s.id))return[];const{data:n,error:i}=await z.from("message_groups").select("*").eq("organization_id",s.id).order("name");if(i)throw i;return n},enabled:!!(s!=null&&s.id)})}function ll(s){return ms({queryKey:["group-members",s],queryFn:async()=>{if(!s)return[];const{data:n,error:i}=await z.from("message_group_members").select("*").eq("group_id",s).order("created_at",{ascending:!1});if(i)throw i;return n},enabled:!!s})}function Zd(){const{currentOrganization:s}=Je(),n=Ms();return ks({mutationFn:async({name:i,notes:t})=>{if(!(s!=null&&s.id))throw new Error("No organization selected");const{data:d,error:r}=await z.from("message_groups").insert({name:i,notes:t||null,organization_id:s.id}).select().single();if(r)throw r;return d},onSuccess:()=>{K.success("Group created"),n.invalidateQueries({queryKey:["message-groups"]})},onError:()=>{K.error("Failed to create group")}})}function Jd(){const s=Ms();return ks({mutationFn:async({groupId:n,name:i,notes:t})=>{const{data:d,error:r}=await z.from("message_groups").update({name:i,notes:t||null,updated_at:new Date().toISOString()}).eq("id",n).select().single();if(r)throw r;return d},onSuccess:()=>{K.success("Group updated"),s.invalidateQueries({queryKey:["message-groups"]})},onError:()=>{K.error("Failed to update group")}})}function Xd(){const s=Ms();return ks({mutationFn:async n=>{const{error:i}=await z.from("message_group_members").delete().eq("group_id",n);if(i)throw i;const{error:t}=await z.from("message_groups").delete().eq("id",n);if(t)throw t},onSuccess:()=>{K.success("Group deleted"),s.invalidateQueries({queryKey:["message-groups"]})},onError:()=>{K.error("Failed to delete group")}})}function em(){const s=Ms();return ks({mutationFn:async({groupId:n,members:i})=>{const t=i.map(r=>({group_id:n,member_number:r.member_number||null,phone_number:r.phone_number||null,display_name:r.display_name||null,source:r.source||"manual"})),{error:d}=await z.from("message_group_members").insert(t);if(d)throw d},onSuccess:()=>{K.success("Members added to group"),s.invalidateQueries({queryKey:["group-members"]})},onError:n=>{K.error(`Failed to add members: ${(n==null?void 0:n.message)||"Unknown error"}`)}})}function sm(){const s=Ms();return ks({mutationFn:async n=>{const{error:i}=await z.from("message_group_members").delete().eq("id",n);if(i)throw i},onSuccess:()=>{s.invalidateQueries({queryKey:["group-members"]})},onError:()=>{K.error("Failed to remove member")}})}const cn="__ignore__";function tm(s){let n=s,i="";for(;n>=0;)i=String.fromCharCode(65+n%26)+i,n=Math.floor(n/26)-1;return i}function am(s,n,i){const t={};if(n.forEach(o=>t[o.key]=-1),s.length===0)return t;const d=i?s[0]:[],r=i?s[1]||[]:s[0]||[],x=Math.max(d.length,r.length),c=new Set;if(i){for(const o of n)if(o.suggest)for(let m=0;m<x;m++){if(c.has(m))continue;const p=(d[m]||"").trim();if(p&&o.suggest(p)){t[o.key]=m,c.add(m);break}}}for(const o of n)if(t[o.key]===-1&&o.validate)for(let m=0;m<x;m++){if(c.has(m))continue;const p=(r[m]||"").trim();if(p&&o.validate(p)){t[o.key]=m,c.add(m);break}}return t}function Wn({rows:s,fields:n,hasHeader:i,onHasHeaderChange:t,mapping:d,onMappingChange:r}){const x=i?s[0]||[]:[],c=i?s.slice(1):s,o=Math.max(x.length,...s.slice(0,5).map(l=>l.length)),m=c.slice(0,5);a.useEffect(()=>{n.every(N=>d[N.key]===void 0||d[N.key]===-1)&&s.length>0&&r(am(s,n,i))},[i]);const p=a.useMemo(()=>{let l=0,N=0;const j=[];for(let g=0;g<c.length;g++){const y=c[g];let k=!0;for(const S of n){if(!S.required)continue;const f=d[S.key];if(f===void 0||f<0){k=!1;break}const h=(y[f]||"").trim();if(!h){k=!1;break}if(S.validate&&!S.validate(h)){k=!1;break}}k?l++:(N++,j.length<10&&j.push(g+(i?2:1)))}return{valid:l,skipped:N,skippedRows:j}},[c,n,d,i]),u=(l,N)=>{r({...d,[l]:N===cn?-1:parseInt(N,10)})};return e.jsxs(re,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Map Your Columns"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Tell us which column from your file holds each piece of information."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(As,{id:"has-header",checked:i,onCheckedChange:l=>t(l===!0)}),e.jsx(v,{htmlFor:"has-header",className:"text-sm cursor-pointer",children:"First row is a header"})]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:n.map(l=>{const N=d[l.key],j=N===void 0||N<0?cn:String(N);return e.jsxs("div",{className:"space-y-1",children:[e.jsxs(v,{className:"text-xs",children:[l.label,l.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(Pe,{value:j,onValueChange:g=>u(l.key,g),children:[e.jsx(Ie,{className:"h-9",children:e.jsx(qe,{placeholder:"Choose a column"})}),e.jsxs(Be,{children:[e.jsx(ae,{value:cn,children:l.required?"— Select column —":"Ignore (not in file)"}),Array.from({length:o}).map((g,y)=>{var f;const k=i?(x[y]||"").trim():"",S=(((f=c[0])==null?void 0:f[y])||"").trim();return e.jsxs(ae,{value:String(y),children:["Column ",tm(y),k?` — "${k}"`:"",!k&&S?` — e.g. "${S.slice(0,20)}"`:""]},y)})]})]})]},l.key)})}),m.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("p",{className:"text-xs font-medium text-muted-foreground",children:["Preview (first ",m.length," row",m.length===1?"":"s",")"]}),e.jsx("div",{className:"border rounded-md overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{className:"bg-muted/50",children:e.jsx("tr",{children:n.map(l=>e.jsx("th",{className:"text-left px-2 py-1.5 font-medium",children:l.label},l.key))})}),e.jsx("tbody",{children:m.map((l,N)=>e.jsx("tr",{className:"border-t",children:n.map(j=>{const g=d[j.key],y=g!==void 0&&g>
61=0?(l[g]||"").trim():"",k=y&&(!j.validate||j.validate(y)),S=j.required;return e.jsx("td",{className:`px-2 py-1.5 ${S&&!k?"text-destructive":"text-foreground"}`,children:y||e.jsx("span",{className:"text-muted-foreground italic",children:"empty"})},j.key)})},N))})]})})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(ie,{variant:p.valid>0?"default":"secondary",className:"gap-1",children:[e.jsx(Oa,{className:"h-3 w-3"}),p.valid," valid"]}),p.skipped>0&&e.jsxs(ie,{variant:"outline",className:"gap-1 text-amber-600 border-amber-300",children:[e.jsx(Kt,{className:"h-3 w-3"}),p.skipped," skipped",p.skippedRows.length>0&&e.jsxs("span",{className:"ml-1 text-muted-foreground",children:["(rows ",p.skippedRows.join(", "),p.skipped>p.skippedRows.length?"…":"",")"]})]})]})]})}function nm(s){const n=s.split(/\r?\n/).find(r=>r.trim())||"",i={",":(n.match(/,/g)||[]).length,"	":(n.match(/\t/g)||[]).length,";":(n.match(/;/g)||[]).length,"|":(n.match(/\|/g)||[]).length};let t=",",d=0;for(const[r,x]of Object.entries(i))x>d&&(t=r,d=x);return t}function Zn(s,n){const i=nm(s),t=s.split(/\r?\n/).filter(r=>r.length>0),d=[];for(const r of t){const x=[];let c="",o=!1;for(let m=0;m<r.length;m++){const p=r[m];p==='"'?o&&r[m+1]==='"'?(c+='"',m++):o=!o:p===i&&!o?(x.push(c.trim()),c=""):c+=p}x.push(c.trim()),x.some(m=>m.length>0)&&d.push(x)}return d}function Jn(s){return s.length<2?!1:s[0].filter(t=>t&&/^[\d\s().+-]+$/.test(t)).length===0}function rm(s){const n=s.replace(/\D/g,"");return n.length===10?`1${n}`:n.length===11&&n.startsWith("1")?n:s}function cl(s){const n=s.replace(/\D/g,"");return n.length===10||n.length===11&&n.startsWith("1")}const im=[{key:"phone",label:"Phone Number",required:!0,suggest:s=>/phone|mobile|cell|number|tel/i.test(s),validate:cl},{key:"name",label:"Name",suggest:s=>/name|first|last|rider|contact/i.test(s)},{key:"memberNumber",label:"Member #",suggest:s=>/member|^#$|number\s*#|rider\s*#/i.test(s)&&!/phone/i.test(s),validate:s=>/^\d+$/.test(s.replace(/\D/g,""))}];function ol({onRecipientsLoaded:s,label:n}){const[i,t]=a.useState([]),[d,r]=a.useState(!0),[x,c]=a.useState({}),[o,m]=a.useState([]),[p,u]=a.useState(null),l=a.useRef(null),N=S=>{var M;const f=(M=S.target.files)==null?void 0:M[0];if(!f)return;if(!f.name.endsWith(".csv")&&!f.name.endsWith(".txt")){K.error("Please upload a CSV or TXT file");return}u(f.name);const h=new FileReader;h.onload=T=>{var Q;const C=(Q=T.target)==null?void 0:Q.result,L=Zn(C);if(L.length===0){K.error("No data found in file");return}t(L),r(Jn(L)),c({}),m([])},h.readAsText(f)},j=()=>{t([]),m([]),u(null),c({}),s([]),l.current&&(l.current.value="")},g=a.useMemo(()=>{if(i.length===0)return[];const S=x.phone;if(S===void 0||S<0)return[];const f=d?i.slice(1):i,h=new Set,M=[];for(const T of f){const C=(T[S]||"").trim();if(!cl(C))continue;const L=rm(C);if(h.has(L))continue;h.add(L);const Q=x.name,Z=x.memberNumber,R=Q!==void 0&&Q>=0?(T[Q]||"").trim():"",E=Z!==void 0&&Z>=0?(T[Z]||"").trim():"";M.push({name:R||"Unknown",phone:L,memberNumber:E&&parseInt(E.replace(/\D/g,""),10)||void 0})}return M},[i,x,d]),y=()=>{if(g.length===0){K.error("No valid recipients. Check your column mapping.");return}m(g),s(g),K.success(`Loaded ${g.length} recipient(s)`)},k=x.phone!==void 0&&x.phone>=0;return e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:n||"Upload a CSV with names and phone numbers — you can map columns after upload."}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsxs(w,{type:"button",variant:"outline",size:"sm",onClick:()=>{var S;return(S=l.current)==null?void 0:S.click()},children:[e.jsx(Dt,{className:"h-4 w-4 mr-1"}),"Choose File"]}),p&&e.jsx("span",{className:"text-sm text-muted-foreground truncate max-w-64",children:p}),(i.length>0||o.length>0)&&e.jsx(w,{type:"button",variant:"ghost",size:"icon",onClick:j,children:e.jsx(vt,{className:"h-4 w-4"})}),e.jsx("input",{ref:l,type:"file",accept:".csv,.txt",onChange:N,className:"hidden"})]}),i.length>0&&o.length===0&&e.jsxs(e.Fragment,{children:[e.jsx(Wn,{rows:i,fields:im,hasHeader:d,onHasHeaderChange:r,mapping:x,onMappingChange:c}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(w,{type:"button",size:"sm",disabled:!k||g.length===0,onClick:y,children:["Use ",g.length," recipient",g.length===1?"":"s"]})})]}),o.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(qs,{className:"h-48 border rounded-lg",children:e.jsx("div",{className:"divide-y",children:o.map((S,f)=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 text-sm",children:[e.jsx("span",{className:"font-medium truncate",children:S.name}),e.jsx("span",{className:"text-muted-foreground font-mono text-xs",children:S.phone})]},f))})}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Gs,{className:"h-4 w-4"}),o.length," recipient(s) loaded"]})]})]})}function lm(){const{data:s,isLoading:n}
61=il(),i=Zd(),t=Jd(),d=Xd(),[r,x]=a.useState(null),[c,o]=a.useState(""),[m,p]=a.useState(""),[u,l]=a.useState(!1),[N,j]=a.useState(""),[g,y]=a.useState(""),[k,S]=a.useState(!1),f=()=>{c.trim()&&i.mutate({name:c.trim(),notes:m.trim()||void 0},{onSuccess:()=>{o(""),p(""),S(!1)}})};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(re,{className:"lg:col-span-1",children:[e.jsxs(ke,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Ee,{children:"Groups"}),e.jsx(ns,{children:"Saved recipient lists"})]}),e.jsxs(ts,{open:k,onOpenChange:S,children:[e.jsx(xa,{asChild:!0,children:e.jsxs(w,{size:"sm",children:[e.jsx(Es,{className:"h-4 w-4 mr-1"}),"New"]})}),e.jsxs(as,{children:[e.jsxs(rs,{children:[e.jsx(is,{children:"Create Group"}),e.jsx(Fs,{children:"Create a new group to save recipients for quick messaging."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"group-name",children:"Group Name"}),e.jsx(A,{id:"group-name",value:c,onChange:h=>o(h.target.value),placeholder:"e.g., 50cc Parents"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"group-notes",children:"Notes (optional)"}),e.jsx(Ns,{id:"group-notes",value:m,onChange:h=>p(h.target.value),placeholder:"Any notes about this group...",rows:3})]})]}),e.jsxs(Ys,{children:[e.jsx(w,{variant:"outline",onClick:()=>S(!1),children:"Cancel"}),e.jsxs(w,{onClick:f,disabled:i.isPending||!c.trim(),children:[i.isPending&&e.jsx(oe,{className:"h-4 w-4 mr-2 animate-spin"}),"Create Group"]})]})]})]})]}),e.jsx(xe,{className:"p-0",children:e.jsx(qs,{className:"h-[500px]",children:n?e.jsx("div",{className:"flex items-center justify-center h-32",children:e.jsx(oe,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):(s==null?void 0:s.length)===0?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"No groups yet. Create one to get started."}):e.jsx("div",{className:"divide-y",children:s==null?void 0:s.map(h=>e.jsx("button",{onClick:()=>x(h),className:Cs("w-full text-left p-4 hover:bg-muted/50 transition-colors",(r==null?void 0:r.id)===h.id&&"bg-muted"),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(Gs,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:h.name}),h.notes&&e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:h.notes})]})]})},h.id))})})})]}),e.jsxs(re,{className:"lg:col-span-2",children:[e.jsxs(ke,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Ee,{children:(r==null?void 0:r.name)||"Group Details"}),(r==null?void 0:r.notes)&&e.jsx(ns,{children:r.notes})]}),r&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ts,{open:u,onOpenChange:h=>{l(h),h&&r&&(j(r.name),y(r.notes||""))},children:[e.jsx(xa,{asChild:!0,children:e.jsxs(w,{size:"sm",variant:"outline",children:[e.jsx(Ft,{className:"h-4 w-4 mr-1"}),"Edit"]})}),e.jsxs(as,{children:[e.jsxs(rs,{children:[e.jsx(is,{children:"Edit Group"}),e.jsx(Fs,{children:"Update the group name and notes."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"edit-group-name",children:"Group Name"}),e.jsx(A,{id:"edit-group-name",value:N,onChange:h=>j(h.target.value),placeholder:"e.g., 50cc Parents"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"edit-group-notes",children:"Notes (optional)"}),e.jsx(Ns,{id:"edit-group-notes",value:g,onChange:h=>y(h.target.value),placeholder:"Any notes about this group...",rows:3})]})]}),e.jsxs(Ys,{children:[e.jsx(w,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(w,{onClick:()=>{N.trim()&&t.mutate({groupId:r.id,name:N.trim(),notes:g.trim()||void 0},{onSuccess:h=>{x(h),l(!1)}})},disabled:t.isPending||!N.trim(),children:[t.isPending&&e.jsx(oe,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Changes"]})]})]})]}),e.jsxs(et,{children:[e.jsx(Lt,{asChild:!0,children:e.jsxs(w,{variant:"destructive",size:"sm",children:[e.jsx(ws,{className:"h-4 w-4 mr-1"}),"Delete Group"]})}),e.jsxs(st,{children:[e.jsxs(Et,{children:[e.jsx(tt,{children:"Delete Group"}),e.jsxs(at,{children:['Are you sure you want to delete "',r.name,'"? This will also remove all members from the group. This action cannot be undone.']})]}),e.jsxs(Mt,{children:[e.jsx(nt,{children:"Cancel"}),e.jsx(rt,{onClick:()=>{d.mutate(r.id),x(null)},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})]})]})]}),e.jsx(xe,{children:r?e.jsx(cm,{groupId:r.id}):e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Select a group to view and manage members"})})]})]})}function cm({groupId:s}){const{data:n,isLoading:i}=ll(s),t=em(),d=sm(),r=en(),[x,c]=a.useState(!1),[o,m]=a.useState(!1),[p,u]=a.useState(!1),[l,N]=a.useState("search"),[j,g]=a.useState(""),{data:y,isLoading:k}=Xa(j,j.length>
61=2),[S,f]=a.useState(""),[h,M]=a.useState(""),[T,C]=a.useState(null),[L,Q]=a.useState(null),[Z,R]=a.useState(null),[E,$]=a.useState(null),[b,I]=a.useState([]),V=a.useMemo(()=>new Set((n==null?void 0:n.filter(_=>_.member_number).map(_=>_.member_number))||[]),[n]),H=_=>{R(_),I([]),_&&r.mutate({eventName:_,className:E||void 0},{onSuccess:X=>I(X)})},Y=_=>{$(_),I([]),Z&&r.mutate({eventName:Z,className:_||void 0},{onSuccess:X=>I(X)})},W=_=>{const X=_.replace(/\D/g,"");return X.length===10?`1${X}`:X.length===11&&X.startsWith("1")?X:_},te=_=>{const X=`${_.firstName} ${_.lastName}`.trim(),F=_.phoneNumber?W(_.phoneNumber):null;t.mutate({groupId:s,members:[{member_number:_.memberNumber,phone_number:F,display_name:X,source:"rider"}]},{onSuccess:()=>{g("")}})},B=()=>{S.trim()&&t.mutate({groupId:s,members:[{phone_number:W(S.trim()),display_name:h.trim()||null,source:"manual"}]},{onSuccess:()=>{f(""),M(""),c(!1)}})},le=()=>{if(!b||b.length===0){K.error("No recipients to import");return}const _=b.map(X=>({member_number:X.memberNumber,display_name:X.name,source:"rider"}));t.mutate({groupId:s,members:_},{onSuccess:()=>{K.success(`Imported ${_.length} members`),m(!1),C(null),Q(null),R(null),$(null),I([])}})},Me=_=>{if(_.length===0)return;const X=_.map(F=>({phone_number:F.phone,display_name:F.name!=="Unknown"?F.name:void 0,member_number:F.memberNumber,source:"manual"}));t.mutate({groupId:s,members:X},{onSuccess:()=>{K.success(`Imported ${X.length} members from CSV`),u(!1)}})};return i?e.jsx("div",{className:"flex items-center justify-center h-32",children:e.jsx(oe,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[(n==null?void 0:n.length)||0," member",(n==null?void 0:n.length)!==1?"s":""]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ts,{open:o,onOpenChange:m,children:[e.jsx(xa,{asChild:!0,children:e.jsxs(w,{size:"sm",variant:"outline",children:[e.jsx($t,{className:"h-4 w-4 mr-1"}),"Import from Event"]})}),e.jsxs(as,{className:"max-w-2xl",children:[e.jsxs(rs,{children:[e.jsx(is,{children:"Import from Event"}),e.jsx(Fs,{children:"Import all riders from an event or class into this group."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ot,{selectedYear:T,selectedSeries:L,selectedEvent:Z,selectedClass:E,onYearChange:C,onSeriesChange:Q,onEventChange:H,onClassChange:Y}),Z&&e.jsx("div",{className:"p-4 bg-muted rounded-lg",children:r.isPending?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oe,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:"Loading recipients..."})]}):e.jsxs("p",{className:"text-sm",children:[e.jsx("span",{className:"font-medium",children:b.length})," riders found",E&&E!=="ALL"&&` in ${E}`]})})]}),e.jsxs(Ys,{children:[e.jsx(w,{variant:"outline",onClick:()=>m(!1),children:"Cancel"}),e.jsxs(w,{onClick:le,disabled:t.isPending||b.length===0,children:[t.isPending&&e.jsx(oe,{className:"h-4 w-4 mr-2 animate-spin"}),"Import ",b.length," Riders"]})]})]})]}),e.jsxs(ts,{open:p,onOpenChange:u,children:[e.jsx(xa,{asChild:!0,children:e.jsxs(w,{size:"sm",variant:"outline",children:[e.jsx(Dt,{className:"h-4 w-4 mr-1"}),"Upload CSV"]})}),e.jsxs(as,{className:"max-w-lg",children:[e.jsxs(rs,{children:[e.jsx(is,{children:"Upload CSV"}),e.jsx(Fs,{children:"Upload a CSV file with Name and Phone columns to bulk-add members."})]}),e.jsx(ol,{onRecipientsLoaded:Me,label:"Upload a CSV with Name, Phone (and optionally Member Number) columns."})]})]}),e.jsxs(ts,{open:x,onOpenChange:_=>{c(_),_||(g(""),f(""),M(""),N("search"))},children:[e.jsx(xa,{asChild:!0,children:e.jsxs(w,{size:"sm",variant:"outline",children:[e.jsx(Es,{className:"h-4 w-4 mr-1"}),"Add Member"]})}),e.jsxs(as,{className:"max-w-lg",children:[e.jsxs(rs,{children:[e.jsx(is,{children:"Add Member"}),e.jsx(Fs,{children:"Search for a rider or enter a phone number manually."})]}),e.jsxs(ot,{value:l,onValueChange:_=>N(_),children:[e.jsxs(pt,{className:"grid w-full grid-cols-2",children:[e.jsxs(Qe,{value:"search",children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"}),"Search Rider"]}),e.jsxs(Qe,{value:"manual",children:[e.jsx(Rt,{className:"h-4 w-4 mr-1"}),"Manual Entry"]})]}
61),e.jsxs(Ae,{value:"search",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"rider-search",children:"Search by name or member #"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ws,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(A,{id:"rider-search",value:j,onChange:_=>g(_.target.value),placeholder:"Type at least 2 characters...",className:"pl-9"})]})]}),j.length>=2&&e.jsx(qs,{className:"h-64 border rounded-lg",children:k?e.jsx("div",{className:"flex items-center justify-center h-full p-4",children:e.jsx(oe,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):(y==null?void 0:y.length)===0?e.jsx("div",{className:"text-center text-muted-foreground p-4",children:"No riders found"}):e.jsx("div",{className:"divide-y",children:y==null?void 0:y.map(_=>{const X=V.has(_.memberNumber);return e.jsxs("div",{className:Cs("flex items-center justify-between p-3",X&&"opacity-50"),children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-primary/10 flex items-center justify-center flex-shrink-0",children:e.jsx(Xs,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium truncate",children:[_.firstName," ",_.lastName]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["#",_.memberNumber," • ",_.phoneNumber||"No phone"]})]})]}),e.jsx(w,{size:"sm",variant:"outline",disabled:X||t.isPending,onClick:()=>te(_),children:X?"Added":"Add"})]},_.memberNumber)})})})]}),e.jsxs(Ae,{value:"manual",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"manual-phone",children:"Phone Number *"}),e.jsx(A,{id:"manual-phone",type:"tel",value:S,onChange:_=>f(_.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"manual-name",children:"Name (optional)"}),e.jsx(A,{id:"manual-name",value:h,onChange:_=>M(_.target.value),placeholder:"John Doe"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add a name so you can identify this number later"})]}),e.jsxs(w,{onClick:B,disabled:t.isPending||!S.trim(),className:"w-full",children:[t.isPending&&e.jsx(oe,{className:"h-4 w-4 mr-2 animate-spin"}),"Add to Group"]})]})]})]})]})]})]}),(n==null?void 0:n.length)===0?e.jsx("div",{className:"text-center py-12 text-muted-foreground border rounded-lg",children:"No members in this group yet. Add members manually or import from an event."}):e.jsx("div",{className:"border rounded-lg divide-y max-h-96 overflow-y-auto",children:n==null?void 0:n.map(_=>e.jsxs("div",{className:"flex items-center justify-between p-3",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[_.member_number?e.jsx(ai,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}):e.jsx(Rt,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("div",{className:"min-w-0 flex-1",children:_.display_name?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"font-medium truncate",children:_.display_name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:_.member_number?`#${_.member_number}`:_.phone_number})]}):e.jsx("span",{className:"font-mono",children:_.member_number?`#${_.member_number}`:_.phone_number})}),e.jsx(ie,{variant:"outline",className:"text-xs truncate max-w-32 flex-shrink-0",children:_.source})]}),e.jsx(w,{variant:"ghost",size:"icon",onClick:()=>d.mutate(_.id),disabled:d.isPending,className:"flex-shrink-0",children:e.jsx(vt,{className:"h-4 w-4"})})]},_.id))})]})}function om({url:s,index:n}){return e.jsx("a",{href:s,target:"_blank",rel:"noopener noreferrer",className:"group relative block overflow-hidden rounded-lg border hover:ring-2 ring-primary transition-all",title:"Open attachment in new tab",children:e.jsx("img",{src:s,alt:`Attachment ${n+1}`,className:"w-full h-auto",loading:"lazy"})})}function bn(s){const n=s.replace(/\D/g,"");return n.length===11&&n.startsWith("1")?`(${n.slice(1,4)}) ${n.slice(4,7)}-${n.slice(7)}`:s}function dm({message:s}){const{data:n,isLoading:i}=Mc(s.from_number),t=si(),[d,r]=a.useState(""),x=a.useRef(null);a.useEffect(()=>{x.current&&(x.current.scrollTop=x.current.scrollHeight)},[n==null?void 0:n.length]);const c=async()=>{var m,p;const o=d.trim();o&&(await t.mutateAsync({recipients:[{phone:s.from_number,name:(m=s.matched_rider_names)==null?void 0:m[0],memberNumber:(p=s.matched_member_numbers)==null?void 0:p[0]}],message:o,source:"incoming_reply"}),r(""))};return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{ref:x,className:"border rounded-lg bg-muted/20 p-3 space-y-2 max-h-[420px] overflow-y-auto",children:i?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(oe,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):!n||n.length===0?e.jsx("div",{className:"text-center py-6 text-sm text-muted-foreground",children:"No messages yet"}):n.map(o=>{const m=o.direction==="outbound";return e.jsx("div",{className:Cs("flex",m?"justify-end":"justify-start"),children:e.jsxs("div",{className:Cs("max-w-[75%] rounded-2xl px-3 py-2 text-sm shadow-sm",m?"bg-primary text-primary-foreground rounded-br-sm":"bg-card border rounded-bl-sm"),children:[o.body&&e.jsx("p",{className:"whitespace-pre-wrap break-words",children:o.body}),o.media_urls.length>0&&e.jsx("div",{className:"grid grid-cols-2 gap-2 mt-2",children:o.media_urls.map((p,u)=>e.jsx(om,{url:p,index:u},u))}),e.jsxs("div",{className:Cs("mt-1 text-[10px]",m?"text-primary-foreground
61/70":"text-muted-foreground"),children:[Js(new Date(o.timestamp),"MMM d, h:mm a"),m&&o.status&&o.status!=="sent"&&e.jsxs("span",{className:"ml-1",children:["· ",o.status]})]})]})},o.id)})}),e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsx(Ns,{value:d,onChange:o=>r(o.target.value),placeholder:`Reply to ${bn(s.from_number)}...`,className:"min-h-[60px] resize-none",onKeyDown:o=>{o.key==="Enter"&&(o.metaKey||o.ctrlKey)&&(o.preventDefault(),c())}}),e.jsx(w,{onClick:c,disabled:!d.trim()||t.isPending,size:"icon",className:"h-[60px] w-[60px] shrink-0",children:t.isPending?e.jsx(oe,{className:"h-4 w-4 animate-spin"}):e.jsx(gt,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Press ⌘/Ctrl + Enter to send"})]})}function mm(){var S,f,h;const{data:s,isLoading:n,refetch:i,isRefetching:t}=_c(),d=wc(),r=Sc(),x=Cc(),c=kc(),[o,m]=a.useState(null),[p,u]=a.useState(null),[l,N]=a.useState(""),j=s?Ec(s):[],g=(()=>{const M=l.trim().toLowerCase();if(!M)return j;const T=M.replace(/\D/g,"");return j.filter(C=>{var L,Q;return!!(C.body&&C.body.toLowerCase().includes(M)||T&&C.from_number.replace(/\D/g,"").includes(T)||(L=C.matched_rider_names)!=null&&L.some(Z=>Z.toLowerCase().includes(M))||T&&((Q=C.matched_member_numbers)!=null&&Q.some(Z=>String(Z).includes(T))))})})();a.useEffect(()=>{if(!o||g.length===0){o&&s&&g.length===0&&m(null);return}const M=g.find(T=>T.all_ids.some(C=>o.all_ids.includes(C)));M?M!==o&&m(M):m(null)},[s]);const y=async M=>{m(M),M.unread_ids.length>0&&await d.mutateAsync(M.unread_ids)},k=async()=>{if(!p||p.length===0)return;const M=p;u(null),o&&o.all_ids.some(T=>M.includes(T))&&m(null),await Promise.all(M.map(T=>x.mutateAsync(T)))};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(re,{className:"lg:col-span-1",children:[e.jsxs(ke,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Ee,{children:"Inbox"}),e.jsx(ns,{children:"Incoming SMS messages"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(El,{children:[e.jsx(Ml,{asChild:!0,children:e.jsxs(w,{variant:"outline",size:"sm",disabled:c.isPending,className:"gap-1",children:[c.isPending?e.jsx(oe,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx($t,{className:"h-3.5 w-3.5"}),"Sync from Twilio",e.jsx(mt,{className:"h-3 w-3"})]})}),e.jsxs(Tl,{align:"end",children:[e.jsx(tr,{onClick:()=>c.mutate(7),children:"Last 7 days"}),e.jsx(tr,{onClick:()=>c.mutate(30),children:"Last 30 days"})]})]}),e.jsx(w,{variant:"ghost",size:"icon",onClick:()=>i(),disabled:t,children:e.jsx(kt,{className:Cs("h-4 w-4",t&&"animate-spin")})})]})]}),e.jsxs(xe,{className:"p-0",children:[e.jsx("div",{className:"px-4 pb-3 pt-1 border-b",children:e.jsxs("div",{className:"relative",children:[e.jsx(Ws,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none"}),e.jsx(A,{type:"text",value:l,onChange:M=>N(M.target.value),placeholder:"Search name, number, or message...",className:"pl-8 pr-8 h-9"}),l&&e.jsx("button",{type:"button",onClick:()=>N(""),className:"absolute right-2 top-1/2 -translate-y-1/2 p-0.5 rounded text-muted-foreground hover:text-foreground","aria-label":"Clear search",children:e.jsx(vt,{className:"h-3.5 w-3.5"})})]})}),e.jsx(qs,{className:"h-[600px]",children:n?e.jsx("div",{className:"flex items-center justify-center h-32",children:e.jsx(oe,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):g.length===0?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:l?"No messages match your search":"No messages yet"}):e.jsx("div",{className:"divide-y",children:g.map(M=>{var C;const T=(o==null?void 0:o.all_ids[0])===M.all_ids[0];return e.jsxs("div",{className:Cs("group relative flex items-stretch hover:bg-muted/50 transition-colors",T&&"bg-muted",!M.is_read&&"bg-primary/5"),children:[e.jsx("button",{onClick:()=>y(M),className:"flex-1 text-left p-4 pr-12 min-w-0",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-1",children:M.is_read?e.jsx(dd,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Ks,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:Cs("font-medium text-sm",!M.is_read&&"font-semibold"),children:bn(M.from_number)}),((C=M.matched_rider_names)==null?void 0:C[0])&&e.jsx(ie,{variant:"secondary",className:"text-xs",children:M.matched_rider_names[0]})]}),e.jsx("p",{className:"text-sm text-muted-foreground truncate mt-1",children:M.body||"(No message body)"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[Js(new Date(M.received_at),"MMM d, h:mm a"),M.message_count>1&&e.jsxs("span",{className:"ml-1",children:["· ",M.message_count," msgs"]})]})]})]})}),e.jsxs("div",{className:"absolute right-2 top-1/2 -translate-y-1/2 flex items-center gap-1 opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition-opacity",children:[M.is_read&&e.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),r.mutate(M.all_ids)},className:"p-2 rounded-md text-muted-foreground hover:text-primary hover:bg-primary/10","aria-label":"Mark conversation as unread",title:"Mark as unread",children:e.jsx(pr,{className:"h-4 w-4"})}),e.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),u(M.all_ids)},className:"p-2 rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10","aria-label":"Delete conversation",title:"Delete conversation",children:e.jsx(ws,{className:"h-4 w-4"})})]})]},M.all_ids[0])})})})]})]}),e.jsxs(re,{className:"lg:col-span-2",children:[e.jsxs(ke,{className:"flex flex-row items-center justify-between",children:[e.jsx(Ee,{children:"Conversation"}),o&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(w,{variant:"outline",size:"sm",onClick:async()=>{const M=o.all_ids;m(null),await r.mutateAsync(M)},className:"gap-1",children:[e.jsx(pr,{className:"h-3.5 w-3.5"}),"Mark as unread"]}),e.jsxs(w,{variant:"outline",size:"sm",onClick:()=>u(o.all_ids),className:"gap-1 text-destructive hover:text-destructive",children:[e.jsx(ws,{className:"h-3.5 w-3.5"}),"Delete"]})]})]}),e.jsx(xe,{children:o?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-muted flex items-center justify-center",children:e.jsx(Rt,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:bn(o.from_number)}),(S=o.matched_rider_names)!=null&&S.length||(f=o.matched_member_numbers)!=null&&f.length?e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Xs,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:(h=o.matched_rider_names)==null?void 0:h.map((M,T)=>{var C;return e.jsxs(ie,{variant:"outline",className:"text-xs",children:[M,((C=o.matched_member_numbers)==null?void 0:C[T])&&e.jsxs("span",{className:"ml-1 text-muted-foreground",children:["#",o.matched_member_numbers[T]]})]},T)})})]}):null]})]}),e.jsx(dm,{message:o})]}):e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Select a message to view the conversation"})})]})]}),e.jsx(et,{open:!!p,onOpenChange:M=>!M&&u(null),children:e.jsxs(st,{children:[e.jsxs(Et,{children:[e.jsx(tt,{children:"Delete entire conversation from inbox?"}),e.jsxs(at,{children:["This will permanently remove ",(p==null?void 0:p.length)??0," inbound message",((p==null?void 0:p.length)??0)===1?"":"s"," from this sender. The conversation history will still show prior outbound replies."]})]}),e.jsxs(Mt,{children:[e.jsx(nt,{children:"Cancel"}),e.jsx(rt,{onClick:k,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}const on=1e3,Nr=2e4;function dl(){const{currentOrganization:s}=Je(),{data:n=[],isLoading:i}=ms({queryKey:["sms-logs",s==null?void 0:s.id],queryFn:async()=>
61{if(!(s!=null&&s.id))return[];const t=[];let d=0;for(;d<Nr;){const r=Math.min(d+on-1,Nr-1),{data:x,error:c}=await z.from("sms_logs").select("id, recipient_phone, recipient_name, member_number, message_body, status, error_message, sent_at, created_at, source, event_name").eq("organization_id",s.id).order("created_at",{ascending:!1}).range(d,r);if(c)throw c;if(!x||x.length===0||(t.push(...x),x.length<on))break;d+=on}return t},enabled:!!(s!=null&&s.id),refetchInterval:1e4});return{logs:n,isLoading:i}}const yn="{name}";function um(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _n(s,n){if(!s)return"";let i=s;if(i=i.replace(/^\s*(hey|hi|hello|dear)\s+[A-Za-z][A-Za-z'’\-]{0,40}\s*[!,.\-:]?\s*/i,`Hey ${yn} `),n){const t=n.trim().split(/\s+/)[0];if(t&&t.length>=2){const d=new RegExp(`\\b${um(t)}\\b`,"gi");i=i.replace(d,yn)}}return i=i.replace(/https?:\/\/\S+/gi,"{url}"),i=i.replace(/[?&][a-z_]+=\S+/gi,""),i=i.replace(/\b(?=[A-Z0-9-]*\d)[A-Z0-9][A-Z0-9-]{5,}\b/g,"{code}"),i=i.replace(/\s+/g," ").trim(),i}function ml(s,n=2*60*60*1e3){const i=new Date(s).getTime();return Math.floor(i/n)}function ul(s,n){const i=(n||"").trim().split(/\s+/)[0]||"there";return s.split(yn).join(i)}const hm=new Set(["wallet_coupon_sms","wallet_coupon_email","sponsor_batch_sms","sponsor_batch_email","timing_email","timing_email_resend","bulk_email","bulk_sms","race_alert_sms","race_alert_email","practice_alert_sms","races_away_sms"]);function hl(s){return s?hm.has(s):!1}function xm(s){const n=new Map,i=[...s].sort((t,d)=>new Date(d.created_at).getTime()-new Date(t.created_at).getTime());for(const t of i){const d=_n(t.message_body,t.recipient_name),r=ml(t.created_at),x=t.source||"manual",c=hl(x)?`${x}|${r}`:`${x}|${d}|${r}`;let o=n.get(c);o||(o={id:t.id,message:ul(d,t.recipient_name)||t.message_body,status:t.status==="sent"?"sent":"failed",recipients:0,sentDate:t.created_at,eventName:t.event_name,logs:[]},n.set(c,o)),o.recipients++,o.logs.push({id:t.id,recipient_phone:t.recipient_phone,recipient_name:t.recipient_name,member_number:t.member_number,status:t.status,error_message:t.error_message,sent_at:t.sent_at,created_at:t.created_at}),new Date(t.created_at).getTime()>new Date(o.sentDate).getTime()&&(o.sentDate=t.created_at),t.status==="failed"&&o.status==="sent"&&(o.status="partial"),t.status==="sent"&&o.status==="failed"&&(o.status="partial")}return[...n.values()].sort((t,d)=>new Date(d.sentDate).getTime()-new Date(t.sentDate).getTime())}function pm(){const{logs:s,isLoading:n}=dl(),[i,t]=a.useState(""),[d,r]=a.useState("all"),[x,c]=a.useState(null),[o,m]=a.useState(null),[p,u]=a.useState(new Set),l=S=>{u(f=>{const h=new Set(f);return h.has(S)?h.delete(S):h.add(S),h})},N=a.useMemo(()=>xm(s),[s]),j=a.useMemo(()=>N.filter(S=>{if(d!=="all"&&S.status!==d)return!1;if(i){const f=i.toLowerCase();return S.message.toLowerCase().includes(f)||S.logs.some(h=>{var M;return h.recipient_phone.includes(f)||((M=h.recipient_name)==null?void 0:M.toLowerCase().includes(f))})}return!0}),[N,i,d]),g=async S=>{m(S.id);try{const f=S.logs.map(M=>M.id),{error:h}=await z.from("sms_logs").delete().in("id",f);if(h)throw h;K.success("SMS log deleted")}catch(f){K.error(`Failed to delete: ${f.message}`)}finally{m(null)}},y=S=>{const f=new Date(S);return{date:f.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),time:f.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}},k=(S,f=60)=>S.length>f?S.slice(0,f)+"…":S;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:"SMS Log"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"View all sent SMS messages grouped by campaign"})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Ws,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(A,{placeholder:"Search by message or recipient...",value:i,onChange:S=>t(S.target.value),className:"pl-10"})]}),e.jsxs(Pe,{value:d,onValueChange:r,children:[e.jsx(Ie,{className:"w-[140px]",children:e.jsx(qe,{placeholder:"Status"})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"all",children:"All Status"}),e.jsx(ae,{value:"sent",children:"Sent"}),e.jsx(ae,{value:"failed",children:"Failed"}),e.jsx(ae,{value:"partial",children:"Partial"})]})]})]}),n?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(oe,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):j.length===0?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:N.length===0?e.jsxs("div",{className:"space-y-2",children:[e.jsx(bt,{className:"h-12 w-12 mx-auto opacity-30"}),e.jsx("p",{children:"No SMS messages sent yet"})]}):e.jsx("p",{children:"No messages match your search"})}):e.jsx(re,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b text-left",children:[e.jsx("th",{className:"w-8 px-2 py-3"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground",children:"Message"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground",children:"Status"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground text-center",children:"Recipients"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground",children:"Send Date"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground text-right",children:"Actions"})]})}),e.jsx("tbody",{children:j.map(S=>{const{date:f,time:h}=y(S.sentDate),M=p.has(S.id),T=S.recipients>1;return e.jsxs(a.Fragment,{children:[e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/50 transition-colors",children:[e.jsx("td",{className:"px-2 py-3 align-top",children:T?e.jsx("button",{onClick:()=>l(S.id),className:"p-1 rounded hover:bg-muted","aria-label":M?"Collapse":"Expand",children:M?e.jsx(mt,{className:"h-4 w-4"}):e.jsx(Hs,{className:"h-4 w-4"})}):null}),e.jsxs("td",{className:"px-4 py-3 max-w-xs",children:[e.jsx("button",{onClick:()=>c(S),className:"text-primary hover:underline text-left font-medium text-sm",children:k(S.message)}),S.eventName&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:S.eventName})]}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(ie,{variant:S.status==="sent"?"default":S.status==="partial"?"secondary":"destructive",className:S.status==="sent"?"bg-emerald-100 text-emerald-700 hover:bg-emerald-100":"",children:S.status.toUpperCase()})}),e.jsx("td",{className:"px-4 py-3 text-center text-sm",children:T?e.jsx("button",{onClick:()=>l(S.id),className:"hover:underline",children:S.recipients}):S.recipients}),e.jsxs("td",{className:"px-4 py-3",children:[e.jsx("div",{className:"text-sm font-medium",children:f}),e.jsx("div",{className:"text-xs text-muted-foreground",children:h})]}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(w,{variant:"ghost",size:"icon",className:"h-8 w-8",title:"View details",onClick:()=>c(S),children:e.jsx(Zt,{className:"h-4 w-4"})}),e.jsxs(et,{children:[e.jsx(Lt,{asChild:!0,children:e.jsx(w,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",title:"Delete log",disabled:o===S.id,children:o===S.id?e.jsx(oe,{className:"h-4 w-4 animate-spin"}):e.jsx(ws,{className:"h-4 w-4"})})}),e.jsxs(st,{children:[e.jsx(tt,{children:"Delete SMS Log"}),e.jsxs(at,{children:["This will permanently delete all ",S.recipients," SMS log(s) for this message. This action cannot be undone."]}),e.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[e.jsx(nt,{children:"Cancel"}),e.jsx(rt,{onClick:()=>g(S),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})]})]})})]},S.id),M&&T&&e.jsxs("tr",{className:"bg-muted/30 border-b",children:[e.jsx("td",{}),e.jsx("td",{colSpan:5,className:"px-4 py-3",children:e.jsx("div",{className:"max-h-72 overflow-y-auto rounded border bg-background",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"text-xs text-muted-foreground",children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"px-3 py-1.5 text-left font-medium",children:"Recipient"}),e.jsx("th",{className:"px-3 py-1.5 text-left font-medium",children:"Phone"}),e.jsx("th",{className:"px-3 py-1.5 text-left font-medium",children:"Status"}),e.jsx("th",{className:"px-3 py-1.5 text-left font-medium",children:"Error"})]})}),e.jsx("tbody",{children:S.logs.map(C=>e.jsxs("tr",{className:"border-b last:border-0",children:[e.jsxs("td",{className:"px-3 py-1.5",children:[C.recipient_name||"—",C.member_number?` #${C.member_number}`:""]}),e.jsx("td",{className:"px-3 py-1.5 text-muted-foreground",children:C.recipient_phone}),e.jsx("td",{className:"px-3 py-1.5",children:e.jsx(ie,{variant:C.status==="sent"?"outline":"destructive",className:"text-xs",children:C.status})}),e.jsx("td",{className:"px-3 py-1.5 text-xs text-destructive",children:C.error_message||""})]},C.id))})]})})})]},S.id+"-exp")]},S.id)})})]})})}),x&&e.jsx(gm,{campaign:x,open:!!x,onClose:()=>c(null)})]})}function gm({campaign:s,open:n,onClose:i}){const t=d=>
61new Date(d).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit",hour12:!0});return e.jsx(ts,{open:n,onOpenChange:d=>!d&&i(),children:e.jsxs(as,{className:"max-w-2xl max-h-[90vh] flex flex-col",children:[e.jsx(rs,{children:e.jsx(is,{className:"text-xl",children:"SMS Details"})}),e.jsx(qs,{className:"flex-1 pr-4",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground text-xs",children:"Status"}),e.jsx(ie,{variant:s.status==="sent"?"default":"destructive",className:s.status==="sent"?"bg-emerald-100 text-emerald-700 hover:bg-emerald-100":"",children:s.status.toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground text-xs",children:"Send Date"}),e.jsx("p",{className:"font-medium",children:t(s.sentDate)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground text-xs",children:"Recipients"}),e.jsx("p",{className:"font-medium",children:s.recipients})]}),s.eventName&&e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground text-xs",children:"Event"}),e.jsx("p",{className:"font-medium",children:s.eventName})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-2",children:"Message"}),e.jsx("div",{className:"border rounded-md p-3 text-sm bg-muted/30 whitespace-pre-wrap",children:s.message})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-2",children:"Recipients"}),e.jsx("div",{className:"border rounded-md max-h-48 overflow-y-auto",children:s.logs.map(d=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 text-sm border-b last:border-0",children:[e.jsxs("div",{children:[e.jsx("span",{children:d.recipient_name||"Unknown"}),e.jsx("span",{className:"text-muted-foreground ml-2",children:d.recipient_phone}),d.member_number&&e.jsxs("span",{className:"text-muted-foreground ml-1",children:["#",d.member_number]})]}),e.jsx(ie,{variant:d.status==="sent"?"outline":"destructive",className:"text-xs",children:d.status})]},d.id))})]}),s.logs.some(d=>d.error_message)&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-2 text-destructive",children:"Errors"}),e.jsx("div",{className:"border border-destructive/30 rounded-md",children:s.logs.filter(d=>d.error_message).map(d=>e.jsxs("div",{className:"px-3 py-1.5 text-sm border-b last:border-0",children:[e.jsxs("span",{className:"font-medium",children:[d.recipient_phone,":"]})," ",e.jsx("span",{className:"text-destructive",children:d.error_message})]},d.id))})]})]})})]})})}const Va={enabled:!1,localValue:""};function Xn(s){if(!s)return null;const n=new Date(s);return Number.isNaN(n.getTime())?null:n.toISOString()}function xl(){const s=new Date(Date.now()+36e5);s.setSeconds(0,0);const n=i=>String(i).padStart(2,"0");return`${s.getFullYear()}-${n(s.getMonth()+1)}-${n(s.getDate())}T${n(s.getHours())}:${n(s.getMinutes())}`}function pl({value:s,onChange:n,disabled:i}){const t=a.useMemo(()=>Intl.DateTimeFormat().resolvedOptions().timeZone,[]),d=a.useMemo(()=>{const r=new Date(Date.now()-6e4),x=c=>String(c).padStart(2,"0");return`${r.getFullYear()}-${x(r.getMonth()+1)}-${x(r.getDate())}T${x(r.getHours())}:${x(r.getMinutes())}`},[s.enabled]);return e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(v,{htmlFor:"schedule-toggle",className:"cursor-pointer text-sm font-medium",children:"Send later"})]}),e.jsx(Ds,{id:"schedule-toggle",checked:s.enabled,onCheckedChange:r=>n({enabled:r,localValue:r&&!s.localValue?xl():s.localValue}),disabled:i})]}),s.enabled&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(A,{type:"datetime-local",value:s.localValue,min:d,onChange:r=>n({...s,localValue:r.target.value}),disabled:i}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Timezone: ",e.jsx("span",{className:"font-mono",children:t})," (your browser). We'll convert to UTC and fire within the minute."]})]})]})}function fm(s){return ms({queryKey:["scheduled-sends",s??null],enabled:!!s,queryFn:async()=>{const{data:n,error:i}=await z.from("scheduled_sends").select("*").eq("organization_id",s).order("scheduled_for",{ascending:!0});if(i)throw i;return n??[]}})}function gl(){const s=Ms();return ks({mutationFn:async n=>{const{data:{user:i}}=await z.auth.getUser(),{data:t,error:d}=await z.from("scheduled_sends").insert({organization_id:n.organization_id,created_by:(i==null?void 0:i.id)??null,kind:n.kind,label:n.label,scheduled_for:n.scheduled_for,timezone:n.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone,payload:n.payload,recipient_count:n.recipient_count}).select("*").single();if(d)throw d;return t},onSuccess:n=>{s.invalidateQueries({queryKey:["scheduled-sends"]});const i=new Date(n.scheduled_for);
61K.success(`Scheduled for ${i.toLocaleString()}`)},onError:n=>{K.error(`Failed to schedule: ${(n==null?void 0:n.message)??"unknown error"}`)}})}function jm(){const s=Ms();return ks({mutationFn:async n=>{const{data:{user:i}}=await z.auth.getUser(),{error:t}=await z.from("scheduled_sends").update({status:"canceled",canceled_at:new Date().toISOString(),canceled_by:(i==null?void 0:i.id)??null}).eq("id",n).eq("status","pending");if(t)throw t},onSuccess:()=>{s.invalidateQueries({queryKey:["scheduled-sends"]}),K.success("Canceled")},onError:n=>K.error(`Cancel failed: ${n==null?void 0:n.message}`)})}function vm(){const s=Ms();return ks({mutationFn:async({id:n,scheduled_for:i})=>{const{error:t}=await z.from("scheduled_sends").update({scheduled_for:i}).eq("id",n).eq("status","pending");if(t)throw t},onSuccess:()=>{s.invalidateQueries({queryKey:["scheduled-sends"]}),K.success("Rescheduled")},onError:n=>K.error(`Reschedule failed: ${n==null?void 0:n.message}`)})}const Nm={pending:"bg-amber-100 text-amber-800 border-amber-300",processing:"bg-blue-100 text-blue-800 border-blue-300",sent:"bg-emerald-100 text-emerald-800 border-emerald-300",failed:"bg-red-100 text-red-800 border-red-300",canceled:"bg-muted text-muted-foreground border"};function bm(s){return s==="email"?e.jsx(Ks,{className:"h-4 w-4"}):s==="sms"?e.jsx(bt,{className:"h-4 w-4"}):e.jsx(Na,{className:"h-4 w-4"})}function ym(s){return s==="email"?"Email":s==="sms"?"SMS":"Coupon SMS"}function _m({organizationId:s}){const{data:n,isLoading:i}=fm(s),t=jm(),d=vm(),[r,x]=a.useState(null),[c,o]=a.useState(""),m=n??[],p=m.filter(g=>g.status==="pending"||g.status==="processing"),u=m.filter(g=>g.status!=="pending"&&g.status!=="processing"),l=g=>{x(g);const y=new Date(g.scheduled_for),k=S=>String(S).padStart(2,"0");o(`${y.getFullYear()}-${k(y.getMonth()+1)}-${k(y.getDate())}T${k(y.getHours())}:${k(y.getMinutes())}`)},N=async()=>{if(!r)return;const g=Xn(c||xl());g&&(await d.mutateAsync({id:r.id,scheduled_for:g}),x(null))},j=g=>{const y=g.status==="pending";return e.jsxs("div",{className:"flex flex-wrap items-center gap-3 rounded-md border bg-card p-3 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[bm(g.kind),e.jsx("span",{className:"font-medium",children:ym(g.kind)})]}),e.jsxs("div",{className:"flex-1 min-w-[200px]",children:[e.jsx("div",{className:"font-medium",children:g.label||"(no label)"}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(qc,{className:"h-3 w-3"}),new Date(g.scheduled_for).toLocaleString()," · ",g.recipient_count," recipient",g.recipient_count===1?"":"s"]}),g.last_error&&e.jsxs("div",{className:"text-xs text-red-600 mt-1 flex items-start gap-1",children:[e.jsx(Kt,{className:"h-3 w-3 mt-0.5 shrink-0"}),e.jsx("span",{className:"break-all",children:g.last_error})]})]}),e.jsx(ie,{variant:"outline",className:Nm[g.status],children:g.status}),y&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(w,{size:"sm",variant:"outline",onClick:()=>l(g),children:"Reschedule"}),e.jsxs(w,{size:"sm",variant:"ghost",className:"text-red-600 hover:text-red-700",onClick:()=>t.mutate(g.id),disabled:t.isPending,children:[e.jsx(vt,{className:"h-4 w-4 mr-1"})," Cancel"]})]})]},g.id)};return e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yt,{className:"h-5 w-5"}),e.jsx(Ee,{children:"Scheduled sends"})]}),e.jsx(ns,{children:"Emails, SMS blasts, and coupon sends queued to fire at a later time. Cancel or reschedule before they run."})]}),e.jsxs(xe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-sm font-semibold mb-2",children:["Upcoming (",p.length,")"]}),i?e.jsxs("p",{className:"text-sm text-muted-foreground inline-flex items-center gap-2",children:[e.jsx(oe,{className:"h-4 w-4"}),"Loading…"]}):p.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing scheduled."}):e.jsx("div",{className:"space-y-2",children:p.map(j)})]}),u.length>0&&e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-semibold mb-2",children:"Recent history"}),e.jsx("div",{className:"space-y-2",children:u.slice(0,20).map(j)})]})]}),e.jsx(ts,{open:!!r,onOpenChange:g=>!g&&x(null),children:e.jsxs(as,{children:[e.jsx(rs,{children:e.jsx(is,{children:"Reschedule send"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"New send time (your timezone)"}),e.jsx(A,{type:"datetime-local",value:c,onChange:g=>o(g.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Timezone: ",Intl.DateTimeFormat().resolvedOptions().timeZone]})]}),e.jsxs(Ys,{children:[e.jsx(w,{variant:"ghost",onClick:()=>x(null),children:"Cancel"}),e.jsx(w,{onClick:N,disabled:d.isPending,children:"Save new time"})]})]})})]})}const br="REMINDER: You are using a TEMP transponder for today's event. Please return it to the scoring tower at the end of your last moto. Lost transponders will be charged to your account. Thank y
61ou!",wm=/(?:\+?1[\s.-]*)?(?:\(?\d{3}\)?[\s.-]*)\d{3}[\s.-]*\d{4}/g;function dn(s){const n=s.replace(/\D/g,"");return n.length===10?`+1${n}`:n.length===11&&n.startsWith("1")?`+${n}`:null}function Sm(s){const n=s.split(/[,;\n]+/).map(i=>i.trim()).filter(Boolean);return(n.length>0?n:[s.trim()]).flatMap(i=>{const t=i.match(wm);return t!=null&&t.length?t:[i]})}function Cm(){const[s,n]=a.useState(null),[i,t]=a.useState(null),[d,r]=a.useState(null),[x,c]=a.useState(null),[o,m]=a.useState(null),[p,u]=a.useState(null),[l,N]=a.useState(null),[j,g]=a.useState(null),[y,k]=a.useState(null),[S,f]=a.useState([]),[h,M]=a.useState(""),[T,C]=a.useState(null);a.useEffect(()=>{const P=()=>{const Te=sessionStorage.getItem("bp_share_prefill_sms"),Fe=sessionStorage.getItem("bp_share_prefill_sms_media");!Te&&!Fe||(sessionStorage.removeItem("bp_share_prefill_sms"),sessionStorage.removeItem("bp_share_prefill_sms_media"),Te&&M(Te),Fe&&C(Fe))};return P(),window.addEventListener("bp:share-prefill",P),()=>window.removeEventListener("bp:share-prefill",P)},[]);const[L,Q]=a.useState(Aa),[Z,R]=a.useState("bulk"),[E,$]=a.useState(""),[b,I]=a.useState(""),[V,H]=a.useState(""),[Y,W]=a.useState("all"),te=en(),B=si(),{canSendSMS:le,smsRemaining:Me,hasContract:_,trialSmsLimit:X}=Fn(),{data:F}=il(),{data:ne}=ll(y||""),{currentOrganization:J}=Je(),{data:_e=[]}=Xr(J==null?void 0:J.id),me=ni(),[$e,ee]=a.useState(null),[pe,je]=a.useState(!1),[we,U]=a.useState(Va),se=gl(),ue=a.useMemo(()=>new Set(S.map(P=>dn(P.phone)||P.phone)),[S]);a.useEffect(()=>{Z==="bulk"&&(s||i||d?te.mutate({year:s||void 0,seriesName:i||void 0,eventName:d||void 0,className:x||void 0,tempTranspondersOnly:!1},{onSuccess:P=>{f(P)}}):f([]))},[s,i,d,x,Z]),a.useEffect(()=>{Z==="temp-transponders"&&(o||p||l?te.mutate({year:o||void 0,seriesName:p||void 0,eventName:l||void 0,className:j||void 0,tempTranspondersOnly:!0},{onSuccess:P=>{f(P)}}):f([]))},[o,p,l,j,Z]),a.useEffect(()=>{Z!=="group"||!y||!ne||te.mutate({memberNumbers:ne.filter(P=>P.member_number).map(P=>P.member_number)},{onSuccess:P=>{const Te=ne.filter(Fe=>Fe.phone_number&&!Fe.member_number).map(Fe=>({phone:Fe.phone_number,name:Fe.display_name||"Unknown",memberNumber:0,source:"manual"}));f([...P,...Te])}})},[y,ne,Z]);const ve=P=>{f(Te=>Te.filter(Fe=>Fe.phone!==P))},he=P=>{const Te=dn(P.phone)||P.phone;ue.has(Te)||f(Fe=>[...Fe,{phone:Te,name:P.name,memberNumber:P.memberNumber,source:"manual"}])},ze=()=>{f([]),n(null),t(null),r(null),c(null),k(null),m(null),u(null),N(null),g(null)},He=P=>{if(P==="manage-groups")return;const Te=P;R(Te),f([]),$(""),n(null),t(null),r(null),c(null),k(null),m(null),u(null),N(null),g(null),I(""),H(""),W("all"),M(Te==="temp-transponders"?Fe=>Fe.trim()?Fe:br:Fe=>Fe===br?"":Fe)},Ve=()=>{te.mutate({allRiders:!0},{onSuccess:P=>{f(P)}})},Ue=()=>{!b||!V||te.mutate({registeredFrom:b,registeredTo:V,eventId:Y&&Y!=="all"?Y:void 0},{onSuccess:P=>f(P)})},de=()=>{const P=E.trim();if(!P)return;const Te=Sm(P),Fe=[],Ye=[];if(Te.forEach(Xe=>{const bs=dn(Xe);if(!bs){Ye.push(Xe);return}ue.has(bs)||Fe.some(Ts=>Ts.phone===bs)||Fe.push({phone:bs,name:"Manual Entry",memberNumber:0,source:"manual"})}),Fe.length===0&&Ye.length>0){K.error("No valid US phone numbers found. Each must have 10 digits, or 11 digits starting with 1.");return}f(Xe=>[...Xe,...Fe]),$(""),Fe.length>0&&K.success(`Added ${Fe.length} number${Fe.length>1?"s":""}${Ye.length>0?` (${Ye.length} skipped)`:""}`)},Le=()=>{if(S.length===0||!h.trim())return;const P=h.trim(),Te=L.enabled&&!!(J!=null&&J.id);if(we.enabled){const Fe=Xn(we.localValue);if(!Fe){K.error("Pick a valid future date/time to schedule the send.");return}if(new Date(Fe).getTime()<=Date.now()+30*1e3){K.error("Scheduled time must be at least a minute in the future.");return}if(!(J!=null&&J.id)){K.error("No organization selected.");return}z.auth.getUser().then(({data:{user:Ye}})=>{se.mutate({organization_id:J.id,kind:"sms",label:d?`SMS: ${d}`:"SMS blast",scheduled_for:Fe,recipient_count:S.length,payload:{organization_id:J.id,recipients:S.map(Xe=>({phone:Xe.phone,name:Xe.name,memberNumber:Xe.memberNumber})),message:P,event_name:d||void 0,sent_by_user_id:Ye==null?void 0:Ye.id,source:"timing_messaging_scheduled"}},{onSuccess:()=>{M(""),U(Va),Te&&(K.info("Race Feed cross-post is skipped for scheduled sends."),Q(Aa))}})});return}B.mutate({recipients:S.map(Fe=>({phone:Fe.phone,name:Fe.name,memberNumber:Fe.memberNumber})),message:P,eventName:d||void 0,mediaUrl:T,source:"timing_messaging"},{onSuccess:async Fe=>{if(ee({channel:"sms",sent:(Fe==null?void 0:Fe.sent)??S.length,failed:(Fe==null?void 0:Fe.failed)??0,timestamp:new Date().toISOString(),detail:d||void 0}),je(!0),M(""),Te)try{await me.mutateAsync({organization_id:J.id,content:P.slice(0,2e3),category:L.category,is_pinned:L.isPinned,is_published:!0}),K.success("Posted to Race Feed"),Q(Aa)}catch(Ye){const Xe=Ye instanceof Error?Ye.message:"Unknown error";K.warning(`Race Feed post failed: ${Xe}`)}}})},{data:ye}
61=Tc(),[Ze,Ls]=a.useState("send");return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ot,{value:Ze,onValueChange:P=>Ls(P),className:"w-full",children:[e.jsxs(pt,{className:"grid w-full max-w-xl grid-cols-4",children:[e.jsxs(Qe,{value:"send",className:"gap-2",children:[e.jsx(gt,{className:"h-4 w-4"}),"Send SMS"]}),e.jsxs(Qe,{value:"scheduled",className:"gap-2",children:[e.jsx(Pa,{className:"h-4 w-4"}),"Scheduled"]}),e.jsxs(Qe,{value:"inbox",className:"gap-2 relative",children:[e.jsx(Rc,{className:"h-4 w-4"}),"Inbox",ye&&ye>0&&e.jsx(ie,{variant:"destructive",className:"ml-2 h-5 min-w-5 px-1.5 text-xs flex items-center justify-center",children:ye>9?"9+":ye})]}),e.jsxs(Qe,{value:"log",className:"gap-2",children:[e.jsx(Pa,{className:"h-4 w-4"}),"Sent Log"]})]}),e.jsx(Ae,{value:"scheduled",className:"mt-6",children:e.jsx(_m,{organizationId:J==null?void 0:J.id})}),e.jsx(Ae,{value:"inbox",className:"mt-6",children:e.jsx(mm,{})}),e.jsx(Ae,{value:"log",className:"mt-6",children:e.jsx(pm,{})}),e.jsxs(Ae,{value:"send",className:"mt-6",children:[e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsx(Ee,{children:"Select Recipients"}),e.jsx(ns,{children:"Choose recipients by event/class, search for riders, or select a saved group"})]}),e.jsx(xe,{children:e.jsxs(ot,{defaultValue:"bulk",className:"w-full",onValueChange:He,children:[e.jsxs(pt,{className:"grid w-full max-w-7xl grid-cols-10 mb-4",children:[e.jsxs(Qe,{value:"bulk",className:"gap-2",children:[e.jsx(Gs,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"By Event/Class"})]}),e.jsxs(Qe,{value:"date-range",className:"gap-2",children:[e.jsx(or,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"By Date"})]}),e.jsxs(Qe,{value:"extras",className:"gap-2",children:[e.jsx(ri,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"By Extras"})]}),e.jsxs(Qe,{value:"all-riders",className:"gap-2",children:[e.jsx(Tt,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"All Riders"})]}),e.jsxs(Qe,{value:"temp-transponders",className:"gap-2",children:[e.jsx(vn,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Temp Trans"})]}),e.jsxs(Qe,{value:"individual",className:"gap-2",children:[e.jsx(Xs,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Search Rider"})]}),e.jsxs(Qe,{value:"manual-entry",className:"gap-2",children:[e.jsx(Rt,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Manual Entry"})]}),e.jsxs(Qe,{value:"upload",className:"gap-2",children:[e.jsx(Dt,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Upload List"})]}),e.jsxs(Qe,{value:"group",className:"gap-2",children:[e.jsx($n,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"From Group"})]}),e.jsxs(Qe,{value:"manage-groups",className:"gap-2",children:[e.jsx(Gs,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Manage Groups"})]})]}),e.jsx(Ae,{value:"bulk",className:"mt-0 space-y-4",children:e.jsx(Ot,{selectedYear:s,selectedSeries:i,selectedEvent:d,selectedClass:x,onYearChange:n,onSeriesChange:t,onEventChange:r,onClassChange:c})}),e.jsx(Ae,{value:"date-range",className:"mt-0 space-y-4",children:e.jsxs("div",{className:"p-4 bg-muted/40 border rounded-lg space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(or,{className:"h-5 w-5 text-primary mt-0.5 shrink-0"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium",children:"Target recent registrants by date range"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Optionally pick a specific event, then a sign-up date range. Dates are in Mountain Time. Deduped by phone."})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(v,{htmlFor:"sms-date-event",className:"text-xs",children:"Event (optional)"}),e.jsxs(Pe,{value:Y,onValueChange:W,children:[e.jsx(Ie,{id:"sms-date-event",children:e.jsx(qe,{placeholder:"All events in this org"})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"all",children:"All events in this org"}),_e.map(P=>e.jsxs(ae,{value:P.id,children:[P.name,P.event_date?` — ${P.event_date}`:""]},P.id))]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(v,{htmlFor:"sms-date-from",className:"text-xs",children:"From"}),e.jsx(A,{id:"sms-date-from",type:"date",value:b,onChange:P=>I(P.target.value)})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(v,{htmlFor:"sms-date-to",className:"text-xs",children:"To"}),e.jsx(A,{id:"sms-date-to",type:"date",value:V,onChange:P=>H(P.target.value)})]}),e.jsx("div",{className:"flex items-end",children:e.jsx(w,{size:"sm",onClick:Ue,disabled:!b||!V||te.isPending,className:"w-full",children:te.isPending?"Loading…":"Load Recipients"})})]}),S.length>0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Loaded ",e.jsx("strong",{children:S.length})," phone numbers."]})]})}),e.jsx(Ae,{value:"extras",className:"mt-0 space-y-4",children:e.jsx(ti,{mode:"sms",onLoaded:P=>{f(P.map(Te=>({phone:Te.phone,name:Te.name,memberNumber:Te.memberNumber||0,source:"riderinfo"})))}})}),e.jsx(Ae,{value:"all-riders",className:"mt-0 space-y-4",children:e.jsxs("div",{className:"p-4 bg-muted/40 border rounded-lg space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Tt,{className:"h-5 w-5 text-primary mt-0.5 shrink-0"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium",children:"Send to every rider in your database"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pulls all riders with a phone number directly from your rider database — no event or year filter required. Use this when you haven't created a race yet, or want to reach your full membership."})]})]}),e.jsx(w,{size:"sm",onClick:Ve,disabled:te.isPending,children:te.isPending?"Loading…":"Load Recipients"}),S.length>0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Loaded ",e.jsx("strong",{children:S.length})," riders with phone numbers."]})]})}),e.jsxs(Ae,{value:"temp-transponders",className:"mt-0 space-y-4",children:[e.jsx("div",{className:"p-3 bg-orange-50 border border-orange-200 rounded-lg",children:e.jsxs("div",{className:"flex items-center gap-2 text-orange-700",children:[e.jsx(vn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Showing only riders with temporary transponders"})]})}),e.jsx(Ot,{selectedYear:o,selectedSeries:p,selectedEvent:l,selectedClass:j,onYearChange:m,onSeriesChange:u,onEventChange:N,onClassChange:g})]}),e.jsx(Ae,{value:"individual",className:"mt-0",children:e.jsx(Qn,{onAddRecipient:he,existingPhones:ue})}),e.jsx(Ae,{value:"manual-entry",className:"mt-0 space-y-4",children:e.jsxs("div",{className:"p-4 bg-muted/40 border rounded-lg space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Rt,{className:"h-5 w-5 text-primary mt-0.5 shrink-0"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium",children:"Send to any phone number"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Type or paste one or more phone numbers — they don't need to be in your database. Separate multiple numbers with commas, spaces, or new lines. US numbers without a country code will get +1 added automatically."})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(A,{placeholder:"e.g. 555-123-4567, +14155551234",value:E,onChange:P=>$(P.target.value),onKeyDown:P=>{P.key==="Enter"&&(P.preventDefault(),de())},className:"flex-1"}),e.jsxs(w,{type:"button",onClick:de,disabled:!E.trim(),className:"gap-2",children:[e.jsx(Es,{className:"h-4 w-4"}),"Add"]})]})]})}),e.jsx(Ae,{value:"upload",className:"mt-0",children:e.jsx(ol,{onRecipientsLoaded:P=>{f(P.map(Te=>({phone:Te.phone,name:Te.name,memberNumber:Te.memberNumber||0,source:"manual"})))}})}),e.jsx(Ae,{value:"group",className:"mt-0",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{children:"Select a Group"}),e.jsxs(Pe,{value:y||"",onValueChange:P=>k(P||null),children:[e.jsx(Ie,{children:e.jsx(qe,{placeholder:"Choose a saved group..."})}),e.jsx(Be,{children:F==null?void 0:F.map(P=>e.jsxs(ae,{value:P.id,children:[P.name,P.notes&&e.jsxs("span",{className:"text-muted-foreground ml-2",children:["- ",P.notes]})]},P.id))})]})]}),(F==null?void 0:F.length)===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:'No groups yet. Go to "Manage Groups" to create one.'})]})}),e.jsx(Ae,{value:"manage-groups",className:"mt-0",children:e.jsx(lm,{})})]})})]}),te.isError&&e.jsxs(ht,{variant:"destructive",children:[e.jsx(Kt,{className:"h-4 w-4"}),e.jsx(xt,{children:"Failed to fetch recipients. Please try again or c
61ontact support if the issue persists."})]}),Z!==null&&e.jsxs(e.Fragment,{children:[e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsx(Ee,{children:"Recipients"}),e.jsx(ns,{children:"Preview and manage the list of recipients"})]}),e.jsx(xe,{children:e.jsx(Wd,{recipients:S,onRemove:ve,isLoading:te.isPending,onClear:S.length>0?ze:void 0})})]}),e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsx(Ee,{children:"Compose Message"}),e.jsx(ns,{children:"Write your message and send to all selected recipients"})]}),e.jsxs(xe,{children:[!_&&e.jsxs("div",{className:"mb-4 p-3 bg-amber-50 border border-amber-200 rounded-lg text-sm text-amber-700",children:["Trial mode: ",Me," of ",X," test messages remaining. Sign the service agreement to unlock unlimited messaging."]}),e.jsx("div",{className:"mb-4",children:e.jsx(pl,{value:we,onChange:U})}),T&&e.jsxs("div",{className:"mb-4 flex items-center gap-3 rounded-lg border p-3",children:[e.jsx("img",{src:T,alt:"Attached event graphic",className:"h-16 w-28 rounded object-cover"}),e.jsxs("div",{className:"min-w-0 flex-1 text-sm",children:[e.jsx("p",{className:"font-medium",children:"Event graphic attached"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sends as an MMS (picture message) — costs more than a plain text."})]}),e.jsx(w,{variant:"ghost",size:"sm",onClick:()=>C(null),children:"Remove"})]}),e.jsx(Qd,{message:h,onMessageChange:M,recipientCount:S.length,onSend:Le,isSending:B.isPending||se.isPending,disabled:!le,crossPost:J!=null&&J.id?L:void 0,onCrossPostChange:J!=null&&J.id?Q:void 0,sendLabel:we.enabled?"Schedule Message":void 0})]})]})]})]})]}),e.jsx(Ln,{open:pe,onOpenChange:je,result:$e})]})}function km(){return e.jsx(rl,{})}function Em(){Je();
61const s=Gt(),[n,i]=a.useState(""),[t,d]=a.useState(""),[r,x]=a.useState(null),[c,o]=a.useState(!1),m=h=>{i(h);const M=setTimeout(()=>{d(h)},300);return()=>clearTimeout(M)},{data:p,isLoading:u,error:l,refetch:N}=Xa(t,t.length>=2),j=ii(),g=()=>{o(!0),x({memberNumber:0,firstName:"",middleInitial:"",lastName:"",email:"",phoneNumber:"",transponder_id:"",birthMonth:void 0,birthDay:void 0,birthYear:void 0,address:"",city:"",state:"",zip:"",country:"USA",sponsors:"",amaMemberId:"",amaExpDate:"1299",clubMember:"N",cmcMemberId:"",licenseSuspended:"N",sex:"",age:0,team:"",signature_data:""})},y=h=>{o(!1),x({...h})},k=async()=>{if(!r)return;const h={memberNumber:c?void 0:r.memberNumber,firstName:r.firstName,middleInitial:r.middleInitial,lastName:r.lastName,email:r.email,phoneNumber:r.phoneNumber,transponder_id:r.transponder_id,birthMonth:r.birthMonth,birthDay:r.birthDay,birthYear:r.birthYear,address:r.address,city:r.city,state:r.state,zip:r.zip,country:r.country,sponsors:r.sponsors,amaMemberId:r.amaMemberId,amaExpDate:r.amaExpDate,clubMember:r.clubMember,cmcMemberId:r.cmcMemberId,licenseSuspended:r.licenseSuspended,sex:r.sex,age:r.age,team:r.team,signature_data:r.signature_data};await j.mutateAsync(h),x(null),N()},S=(h,M,T)=>{if(!h||!M||!T)return;const C=new Date,L=new Date(T,h-1,M);let Q=C.getFullYear()-L.getFullYear();const Z=C.getMonth()-L.getMonth();return(Z<0||Z===0&&C.getDate()<L.getDate())&&Q--,Q>=0?Q:void 0},f=(h,M)=>{if(!r)return;const T={...r,[h]:M};if(h==="birthMonth"||h==="birthDay"||h==="birthYear"){const C=S(h==="birthMonth"?M:T.birthMonth,h==="birthDay"?M:T.birthDay,h==="birthYear"?M:T.birthYear);T.age=C??0}x(T)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(re,{children:[e.jsxs(ke,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Ee,{children:"Rider Management"}),e.jsx(ns,{children:"Search, view, and edit rider profiles"})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(w,{onClick:g,children:[e.jsx(Es,{className:"h-4 w-4 mr-2"}),"New Rider"]})})]}),e.jsx(xe,{children:e.jsxs("div",{className:"relative",children:[e.jsx(Ws,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(A,{placeholder:"Search by name or transponder (min 2 characters)...",value:n,onChange:h=>m(h.target.value),className:"pl-10"})]})})]}),t.length>=2&&e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsx(Ee,{children:"Results"}),e.jsx(ns,{children:u?"Searching...":`${(p==null?void 0:p.length)||0} rider${((p==null?void 0:p.length)||0)!==1?"s":""} found`})]}),e.jsx(xe,{className:"p-0",children:u?e.jsx("div",{className:"flex items-center justify-center h-48",children:e.jsx(oe,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):l?e.jsxs("div",{className:"flex flex-col items-center justify-center h-48 text-destructive",children:[e.jsx(Kt,{className:"h-8 w-8 mb-2"}),e.jsx("p",{children:"Error searching riders"})]}):(p==null?void 0:p.length)===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:['No riders found matching "',t,'"']}):e.jsx(qs,{className:"h-[500px]",children:e.jsxs(na,{children:[e.jsx(ra,{children:e.jsxs(Qs,{children:[e.jsx(Ss,{className:"w-20",children:"Member #"}),e.jsx(Ss,{children:"Name"}),e.jsx(Ss,{children:"Contact"}),e.jsx(Ss,{children:"Location"}),e.jsx(Ss,{children:"Transponder"}),e.jsx(Ss,{className:"w-24",children:"DOB"}),e.jsx(Ss,{className:"w-16"})]})}),e.jsx(ia,{children:p==null?void 0:p.map(h=>e.jsx(Mm,{rider:h,onEdit:()=>y(h)},h.memberNumber))})]})})})]}),e.jsx(ts,{open:!!r,onOpenChange:h=>!h&&x(null),children:e.jsxs(as,{className:"max-w-4xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsxs(rs,{children:[e.jsx(is,{children:c?"Create New Rider":`Edit Rider #${r==null?void 0:r.memberNumber}`}),e.jsx(Fs,{children:c?"Fill in the rider details. A new member number will be assigned automatically.":"Update the rider profile and manage class entries."})]}),r&&e.jsxs(ot,{defaultValue:"info",className:"flex-1 overflow-hidden",children:[e.jsxs(pt,{className:"grid w-full grid-cols-2",children:[e.jsxs(Qe,{value:"info",className:"flex items-center gap-2",children:[e.jsx(Xs,{className:"h-4 w-4"}),"Rider Info"]}),e.jsxs(Qe,{value:"classes",className:"flex items-center gap-2",disabled:c,
61children:[e.jsx(Qc,{className:"h-4 w-4"}),"Class Entries"]})]}),e.jsxs(Ae,{value:"info",className:"mt-4 overflow-auto max-h-[60vh]",children:[e.jsxs("div",{className:"grid grid-cols-12 gap-4 pb-4",children:[!c&&e.jsxs("div",{className:"col-span-12 space-y-2",children:[e.jsx(v,{children:"Member Number"}),e.jsx(A,{value:r.memberNumber,disabled:!0,className:"bg-muted"})]}),e.jsxs("div",{className:"col-span-6 space-y-2",children:[e.jsx(v,{htmlFor:"firstName",children:"First Name"}),e.jsx(A,{id:"firstName",value:r.firstName,onChange:h=>f("firstName",h.target.value)})]}),e.jsxs("div",{className:"col-span-6 space-y-2",children:[e.jsx(v,{htmlFor:"lastName",children:"Last Name"}),e.jsx(A,{id:"lastName",value:r.lastName,onChange:h=>f("lastName",h.target.value)})]}),e.jsxs("div",{className:"col-span-12 space-y-2",children:[e.jsxs(v,{htmlFor:"transponder",children:[s.transponder," ID"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(A,{id:"transponder",value:r.transponder_id||"",onChange:h=>f("transponder_id",h.target.value),placeholder:"Scan or enter EPC"}),e.jsx(Hc,{onScan:h=>f("transponder_id",h)})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"MySQL timing supports one transponder per rider. Multi-transponder support will activate after the Postgres cutover."})]}),e.jsxs("div",{className:"col-span-4 space-y-2",children:[e.jsx(v,{htmlFor:"address",children:"Address"}),e.jsx(A,{id:"address",value:r.address||"",onChange:h=>f("address",h.target.value)})]}),e.jsxs("div",{className:"col-span-3 space-y-2",children:[e.jsx(v,{htmlFor:"city",children:"City"}),e.jsx(A,{id:"city",value:r.city||"",onChange:h=>f("city",h.target.value)})]}),e.jsxs("div",{className:"col-span-2 space-y-2",children:[e.jsx(v,{htmlFor:"state",children:"State"}),e.jsx(A,{id:"state",value:r.state||"",onChange:h=>f("state",h.target.value)})]}),e.jsxs("div",{className:"col-span-3 space-y-2",children:[e.jsx(v,{htmlFor:"zip",children:"Zip"}),e.jsx(A,{id:"zip",value:r.zip||"",onChange:h=>f("zip",h.target.value)})]}),e.jsxs("div",{className:"col-span-4 space-y-2",children:[e.jsx(v,{children:"Birth Month"}),e.jsx(A,{placeholder:"MM",type:"number",min:1,max:12,value:r.birthMonth||"",onChange:h=>f("birthMonth",parseInt(h.target.value)||void 0)})]}),e.jsxs("div",{className:"col-span-4 space-y-2",children:[e.jsx(v,{children:"Birth Day"}),e.jsx(A,{placeholder:"DD",type:"number",min:1,max:31,value:r.birthDay||"",onChange:h=>f("birthDay",parseInt(h.target.value)||void 0)})]}),e.jsxs("div",{className:"col-span-4 space-y-2",children:[e.jsx(v,{children:"Birth Year"}),e.jsx(A,{placeholder:"YYYY",type:"number",min:1900,max:new Date().getFullYear(),value:r.birthYear||"",onChange:h=>f("birthYear",parseInt(h.target.value)||void 0)})]}),e.jsxs("div",{className:"col-span-4 space-y-2",children:[e.jsx(v,{htmlFor:"phone",children:"Phone Number"}),e.jsx(Bc,{id:"phone",value:r.phoneNumber||"",onChange:h=>f("phoneNumber",h)})]}),e.jsxs("div",{className:"col-span-4 space-y-2",children:[e.jsx(v,{htmlFor:"sponsors",children:"Sponsors"}),e.jsx(A,{id:"sponsors",value:r.sponsors||"",onChange:h=>f("sponsors",h.target.value)})]}),e.jsxs("div",{className:"col-span-4 space-y-2",children:[e.jsx(v,{htmlFor:"email",children:"Email"}),e.jsx(A,{id:"email",type:"email",value:r.email||"",onChange:h=>f("email",h.target.value)})]}),e.jsxs("div",{className:"col-span-6 space-y-2",children:[e.jsx(v,{htmlFor:"amaMemberId",children:"AMA Member ID"}),e.jsx(A,{id:"amaMemberId",value:r.amaMemberId||"",onChange:h=>f("amaMemberId",h.target.value)})]}),e.jsxs("div",{className:"col-span-6 space-y-2",children:[e.jsx(v,{htmlFor:"cmcMemberId",children:"CMC Member ID"}),e.jsx(A,{id:"cmcMemberId",value:r.cmcMemberId||"",onChange:h=>f("cmcMemberId",h.target.value)})]}),e.jsxs("div",{className:"col-span-4 space-y-2",children:[e.jsx(v,{htmlFor:"country",children:"Country"}),e.jsx(A,{id:"country",value:r.country||"USA",onChange:h=>f("country",h.target.value)})]}),e.jsxs("div",{className:"col-span-4 space-y-2",children:[e.jsx(v,{htmlFor:"sex",children:"Sex"}),e.jsxs(Pe,{value:r.sex||"",onValueChange:h=>f("sex",h),children:[e.jsx(Ie,{children:e.jsx(qe,{placeholder:"Select..."})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"M",children:"M"}),e.jsx(ae,{value:"F",children:"F"})]})]})]}),e.jsxs("div",{className:"col-span-4 space-y-2",children:[e.jsx(v,{children:"Age"}),e.jsx(A,{value:r.age||"",disabled:!0,className:"bg-muted"})]}),e.jsxs("div",{className:"col-span-12 space-y-2",children:[e.jsx(v,{htmlFor:"team",children:"Team"}),e.jsx(A,{id:"team",value:r.team||"",onChange:h=>f("team",h.target.value)})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t sticky bottom-0 bg-background",children:[e.jsx(w,{variant:"outline",onClick:()=>x(null),children:"Cancel"}),e.jsxs(w,{onClick:k,disabled:j.isPending,children:[j.isPending?e.jsx(oe,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Qa,{className:"h-4 w-4 mr-2"}),c?"Create Rider":"Save Changes"]})]})]}),e.jsx(Ae,{value:"classes",className:"mt-4 overflow-auto max-h-[60vh]",children:!c&&e.jsx(Uc,{memberNumber:r.memberNumber,riderName:`${r.firstName} ${r.lastName}`})})]})]})})]})}function Mm({rider:s,onEdit:n}){const i=s.birthMonth&&s.birthDay&&s.birthYear?`${s.birthMonth}/${s.birthDay}/${s.birthYear}
61`:"-",t=[s.city,s.state,s.country].filter(Boolean).join(", ")||"-";return e.jsxs(Qs,{className:s.pendingSync===1?"bg-amber-50 dark:bg-amber-950/20":"",children:[e.jsx(We,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ie,{variant:"outline",className:"font-mono",children:["#",s.memberNumber]}),s.pendingSync===1&&e.jsxs(ie,{variant:"secondary",className:"bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-200 text-xs",children:[e.jsx(yt,{className:"h-3 w-3 mr-1"}),"Pending"]})]})}),e.jsx(We,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xs,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:"font-medium",children:[s.firstName," ",s.lastName]})]})}),e.jsx(We,{children:e.jsxs("div",{className:"space-y-1",children:[s.email&&e.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[e.jsx(Ks,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-48",children:s.email})]}),s.phoneNumber&&e.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[e.jsx(Rt,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{children:s.phoneNumber})]}),!s.email&&!s.phoneNumber&&e.jsx("span",{className:"text-muted-foreground text-sm",children:"No contact info"})]})}),e.jsx(We,{children:e.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[e.jsx(Tn,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{children:t})]})}),e.jsx(We,{children:e.jsx("code",{className:"text-xs bg-muted px-2 py-1 rounded",children:s.transponder_id||"None"})}),e.jsx(We,{className:"text-sm text-muted-foreground",children:i}),e.jsx(We,{children:e.jsx(w,{variant:"ghost",size:"icon",onClick:n,children:e.jsx(Wc,{className:"h-4 w-4"})})})]})}function Tm(){const{settings:s,isLoading:n,updateSettings:i,isSaving:t}=di(),{currentOrganization:d}=Je(),{isSuperAdmin:r}=kn(),x=Ms(),c=d==null?void 0:d.id,{data:o,isLoading:m}=ms({queryKey:["org-compliance",c],enabled:!!c,queryFn:async()=>{const{data:me,error:$e}=await z.from("organizations").select("mailing_address, email_reply_to, bulk_email_enabled, high_volume_email_enabled, high_volume_sms_enabled").eq("id",c).maybeSingle();if($e)throw $e;return me}}),[p,u]=a.useState(""),[l,N]=a.useState(""),[j,g]=a.useState(!1);a.useEffect(()=>{o&&(u(o.mailing_address??""),N(o.email_reply_to??""))},[o]);const y=((o==null?void 0:o.mailing_address)??"")!==p||((o==null?void 0:o.email_reply_to)??"")!==l,k=async()=>{if(c){g(!0);try{const{error:me}=await z.from("organizations").update({mailing_address:p.trim()||null,email_reply_to:l.trim()||null}).eq("id",c);if(me)throw me;K.success("Compliance settings saved"),x.invalidateQueries({queryKey:["org-compliance",c]})}catch(me){K.error(`Save failed: ${me.message}`)}finally{g(!1)}}},S=async(me,$e)=>{if(!c)return;const{error:ee}=await z.from("organizations").update({[me]:$e}).eq("id",c);if(ee){K.error(`Update failed: ${ee.message}`);return}K.success("Updated"),x.invalidateQueries({queryKey:["org-compliance",c]})},[f,h]=a.useState(!0),[M,T]=a.useState(!1),[C,L]=a.useState(5),[Q,Z]=a.useState(90),[R,E]=a.useState(!1),[$,b]=a.useState(2),[I,V]=a.useState(4),[H,Y]=a.useState(!1),[W,te]=a.useState(!1),[B,le]=a.useState(""),[Me,_]=a.useState(""),[X,F]=a.useState(!1);a.useEffect(()=>{s&&(h(s.sms_race_alerts_enabled),T(s.podium_alerts_enabled),L(s.podium_delay_minutes),Z(s.podium_staleness_minutes??90),E(s.practice_reset_enabled),b(s.max_alert_phones??2),V(s.max_alert_emails??4),te(s.unread_transponder_alerts_enabled??!1),le(s.unread_transponder_msg_has_tag??""),_(s.unread_transponder_msg_no_tag??""),F(s.results_exclude_first_lap??!1))},[s]);const ne=async()=>{if(d!=null&&d.id){Y(!0);try{const{data:me,error:$e}=await z.functions.invoke("trigger-timing-sync",{body:{org_id:d.id}});if($e)throw $e;me!=null&&me.synced?K.success("Settings synced to timing server"):me!=null&&me.message&&K.message(me.message)}catch(me){console.error("Sync failed:",me)}finally{Y(!1)}}},J=async()=>{i({sms_race_alerts_enabled:f,podium_alerts_enabled:M,podium_delay_minutes:C,podium_staleness_minutes:Q,practice_reset_enabled:R,max_alert_phones:$,max_alert_emails:I,unread_transponder_alerts_enabled:W,unread_transponder_msg_has_tag:B,unread_transponder_msg_no_tag:Me,results_exclude_first_lap:X}),setTimeout(async()=>{await ne(),R&&E(!1)},500)},_e=s?f!==s.sms_race_alerts_enabled||M!==s.podium_alerts_enabled||C!==s.podium_delay_minutes||Q!==(s.podium_staleness_minutes??90)||$!==(s.max_alert_phones??2)||I!==(s.max_alert_emails??4)||W!==(s.unread_transponder_alerts_enabled??!1)||B!==(s.unread_transponder_msg_has_tag??"")||Me!==(s.unread_transponder_msg_no_tag??"")||X!==(s.results_exclude_first_lap??!1)||R:!0;return n?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(oe,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsxs(Ee,{className:"flex items-center gap-2",children:[e.jsx(On,{className:"h-5 w-5"}),"Compliance & Sending"]}),e.jsx(ns,{children:"Sender identity and legal info appended to every bulk email. Required before bulk sends are accepted."})]}),e.jsxs(xe,{className:"space-y-4",children:[!(o!=null&&o.mailing_address)&&e.jsxs(ht,{variant:"destructive",children:[e.jsx(Is,{className:"h-4 w-4"}),e.jsx(xt,{children:"A physical mailing address is required by CAN-SPAM before you can send bulk email. Sends will be blocked until this is filled in."})]}),o&&o.bulk_email_enabled===!1&&e.jsxs(ht,{variant:"destructive",children:[e.jsx(Is,{className:"h-4 w-4"}),e.jsxs(xt,{children:["Bulk email is currently ",e.jsx("strong",{children:"disabled"})," for your organization by Beyond Pro. Contact support to re-enable."]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"mailing-address",children:"Physical mailing address"}),e.jsx(Ns,{id:"mailing-address",value:p,onChange:me=>u(me.target.value),placeholder:`Beyond Pro
62123 Main Street
63Denver, CO 80202`,rows:4,disabled:m}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Appears in the unsubscribe footer of every bulk email."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"reply-to",children:"Reply-To email (optional)"}
63),e.jsx(A,{id:"reply-to",type:"email",value:l,onChange:me=>N(me.target.value),placeholder:"[email protected]",disabled:m}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Where replies to your bulk emails are routed. Defaults to your org's primary email."})]}),e.jsx("div",{className:"flex gap-2 pt-2 border-t",children:e.jsxs(w,{onClick:k,disabled:!y||j,children:[j&&e.jsx(oe,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Compliance Settings"]})}),r&&e.jsxs("div",{className:"space-y-3 pt-4 border-t border-dashed",children:[e.jsx("div",{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Super-admin controls"}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:"Bulk email enabled"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Master switch — turn off to immediately block all bulk sends."})]}),e.jsx(Ds,{checked:(o==null?void 0:o.bulk_email_enabled)??!0,onCheckedChange:me=>S("bulk_email_enabled",me)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:"High-volume email (over 5,000 recipients)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Required to send a single email blast to more than 5,000 people."})]}),e.jsx(Ds,{checked:(o==null?void 0:o.high_volume_email_enabled)??!1,onCheckedChange:me=>S("high_volume_email_enabled",me)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:"High-volume SMS (over 5,000 recipients)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Required to send a single SMS blast to more than 5,000 people."})]}),e.jsx(Ds,{checked:(o==null?void 0:o.high_volume_sms_enabled)??!1,onCheckedChange:me=>S("high_volume_sms_enabled",me)})]})]})]})]}),e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsxs(Ee,{className:"flex items-center gap-2",children:[e.jsx(Ua,{className:"h-5 w-5"}),"Text Alert Settings"]}),e.jsx(ns,{children:"Configure automated SMS alerts for race events and podium announcements"})]}),e.jsxs(xe,{className:"space-y-6",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.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(v,{htmlFor:"sms-race-alerts",className:"font-medium",children:"SMS Race Alerts"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Send automated SMS notifications when races are about to start"})]}),e.jsx(Ds,{id:"sms-race-alerts",checked:f,onCheckedChange:h})]}),e.jsxs("div",{className:"rounded-lg border p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(v,{htmlFor:"unread-transponder-alerts",className:"font-medium",children:"Transponder didn't read alerts"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"When a race is stopped, text riders who never read so they can get their transponder fixed at timing. Each rider is only texted once per race."})]}),e.jsx(Ds,{id:"unread-transponder-alerts",checked:W,onCheckedChange:te})]}),W&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(v,{htmlFor:"unread-msg-has-tag",className:"text-sm",children:"Message — has a tag on file, but nothing read"}),e.jsx(Ns,{id:"unread-msg-has-tag",rows:2,value:B,onChange:me=>le(me.target.value)})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(v,{htmlFor:"unread-msg-no-tag",className:"text-sm",children:"Message — no transponder on file"}),e.jsx(Ns,{id:"unread-msg-no-tag",rows:2,value:Me,onChange:me=>_(me.target.value)})]})]})]}),e.jsxs("div",{className:"rounded-lg border p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(la,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(v,{htmlFor:"podium-alerts",className:"font-medium",children:"Podium Alerts"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Sends SMS to top-3 overall finishers (and their alert contacts) once ",e.jsx("strong",{children:"all motos"})," of a class are finalized and the delay below has passed. Overall = sum of moto finishes, latest moto breaks ties."]})]}),e.jsx(Ds,{id:"podium-alerts",checked:M,onCheckedChange:T})]}),M&&e.jsxs("div",{className:"flex flex-col gap-3 pl-6 pt-2 border-t",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(v,{htmlFor:"podium-delay",className:"text-sm whitespace-nowrap",children:"Delay before sending:"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(A,{id:"podium-delay",type:"number",min:1,max:60,value:C,onChange:me=>L(Math.max(1,parseInt(me.target.value)||1)),className:"w-20"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"minutes"})]})]}),e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(v,{htmlFor:"podium-staleness",className:"text-sm whitespace-nowrap",children:"Suppress if race ended over:"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Skips podium/race-feed/YouTube sends when manual results are saved long after the race ended. RFID auto-finalize is unaffected."})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(A,{id:"podium-staleness",type:"number",min:5,max:1440,value:Q,onChange:me=>Z(Math.max(5,parseInt(me.target.value)||90)),className:"w-20"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"minutes"})]})]})]})]}),e.jsxs("div",{className:"rounded-lg border p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gs,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(v,{htmlFor:"max-alert-phones",className:"font-medium",children:"Rider Alert Phone Limit"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Maximum number of phone numbers each rider can register for race alerts"}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(A,{id:"max-alert-phones",type:"number",min:1,max:10,value:$,onChange:me=>b(Math.max(1,Math.min(10,parseInt(me.target.value)||1))),className:"w-20"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"per rider"})]})]}),e.jsxs("div",{className:"rounded-lg border p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ks,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(v,{htmlFor:"max-alert-emails",className:"font-medium",children:"Rider Email List Limit"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Maximum number of email addresses each rider can add to their email list"}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(A,{id:"max-alert-emails",type:"number",min:1,max:10,value:
63I,onChange:me=>V(Math.max(1,Math.min(10,parseInt(me.target.value)||1))),className:"w-20"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"per rider"})]})]}),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(v,{htmlFor:"exclude-first-lap",className:"font-medium",children:"Fastest lap excludes first lap"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"On results, show each rider's fastest lap ignoring their first lap (the timer isn't always started at the gate drop). Scoring and tiebreakers are unchanged."})]}),e.jsx(Ds,{id:"exclude-first-lap",checked:X,onCheckedChange:F})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4 border-dashed",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kt,{className:`h-4 w-4 ${R?"text-orange-500":"text-muted-foreground"}`}),e.jsx(v,{htmlFor:"practice-reset",className:"font-medium",children:"Reset Practice State"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Toggle on and save to reset the practice alert state file on the timing server"}),R&&e.jsx("p",{className:"text-xs text-orange-600 font-medium",children:"⚡ Will reset practice state when you save"})]}),e.jsx(Ds,{id:"practice-reset",checked:R,onCheckedChange:E})]}),e.jsx("div",{className:"pt-4 border-t",children:e.jsxs(w,{onClick:J,disabled:t||!_e,children:[t&&e.jsx(oe,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Settings"]})})]})]})]})}const fl=/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;function pa(s){return s.replace(/[\s\u00a0\u200b]+/g,"").replace(/^[<("']+|[>)"',.;]+$/g,"").toLowerCase()}function ga(s){return fl.test(s.trim())}function Rm(s){const n=[];for(const i of s.split(/[\r\n]+/))if(i.trim())for(const t of i.split(/[,;\t|]/))t.trim()&&n.push(t.trim());return n}function yr(s){const n=[],i=[],t=new Set;let d=0;for(const r of Rm(s)){const x=r.match(/^(.*)<([^>]+)>\s*$/),c=x&&x[1].trim()||void 0,o=x?x[2]:r,m=jl(o,c);if("email"in m){if(t.has(m.email))continue;t.add(m.email),m.repaired&&d++,n.push(m)}else i.push(m)}return{valid:n,invalid:i,repairedCount:d}}function jl(s,n){const i=s.trim();if(!i)return{original:s,name:n,reason:"Empty value"};if(ga(i))return{email:i.toLowerCase(),name:n,original:i};const t=pa(i);if(ga(t))return{email:t,name:n,repaired:!0,original:i};const d=i.includes("@")?/[\s\u00a0]/.test(i)?"Contains spaces and is still invalid after cleanup":t.split("@").length>2?"Multiple @ symbols":/\.[a-zA-Z]{2,}$/.test(t)?"Invalid email format":"Missing or invalid domain ending":"Missing @ — not an email address";return{original:i,name:n,reason:d}}const $m=fl,Dm=[{key:"email",label:"Email",required:!0,suggest:s=>/e?mail|address/i.test(s),validate:s=>$m.test(pa(s))},{key:"name",label:"Name",suggest:s=>/name|first|last|rider|contact/i.test(s)}];function vl({onEmailsImported:s}
63){const[n,i]=a.useState(""),[t,d]=a.useState([]),[r,x]=a.useState([]),c=a.useRef(null),[o,m]=a.useState([]),[p,u]=a.useState(!0),[l,N]=a.useState({}),[j,g]=a.useState(null),y=E=>E.map(($,b)=>({...$,id:`${b}-${$.original}`,value:$.original})),k=(E,$,b)=>{K.success(`Found ${E} email(s)${$?` · auto-fixed ${$}`:""}`),b>0&&K.warning(`${b} address(es) need your review before sending`)},S=E=>{var I;const $=(I=E.target.files)==null?void 0:I[0];if(!$)return;const b=new FileReader;b.onload=V=>{var B;const H=((B=V.target)==null?void 0:B.result)||"",Y=Zn(H);if(Y.length===0){K.error("No data found in file");return}const W=H.split(/\r?\n/).find(le=>le.trim())||"";if(/[,;\t|]/.test(W))g($.name),m(Y),u(Jn(Y)),N({}),d([]),x([]);else{const{valid:le,invalid:Me,repairedCount:_}=yr(H);d(le),x(y(Me)),m([]),k(le.length,_,Me.length)}},b.readAsText($),c.current&&(c.current.value="")},f=E=>{if(i(E),E.trim()){const{valid:$,invalid:b}=yr(E);d($),x(y(b))}else d([]),x([])},h=a.useMemo(()=>{if(o.length===0)return{valid:[],invalid:[]};const E=l.email;if(E===void 0||E<0)return{valid:[],invalid:[]};const $=p?o.slice(1):o,b=new Set,I=[],V=[];for(const H of $){const Y=H[E]||"";if(!Y.trim())continue;const W=l.name,te=W!==void 0&&W>=0&&(H[W]||"").trim()||void 0,B=jl(Y,te);if("email"in B){if(b.has(B.email))continue;b.add(B.email),I.push({email:B.email,name:B.name,repaired:B.repaired})}else V.push(B)}return{valid:I,invalid:V}},[o,l,p]),M=()=>{if(h.valid.length===0&&h.invalid.length===0){K.error("No emails found. Check your column mapping.");return}d(h.valid),x(y(h.invalid)),m([]),k(h.valid.length,h.valid.filter(E=>E.repaired).length,h.invalid.length)},T=()=>{m([]),N({}),g(null)},C=()=>{if(t.length===0){K.error("No valid emails to import");return}r.length>0&&K.warning(`${r.length} flagged address(es) were not imported`),s(t.map(({email:E,name:$})=>({email:E,name:$}))),i(""),d([]),x([]),K.success(`Imported ${t.length} email(s)`)},L=E=>{d($=>$.filter(b=>b.email!==E))},Q=(E,$)=>{x(b=>b.map(I=>I.id===E?{...I,value:$}:I))},Z=E=>{const $=pa(E.value);if(!ga($)){K.error("Still not a valid email address");return}d(b=>b.some(I=>I.email===$)?b:[...b,{email:$,name:E.name}]),x(b=>b.filter(I=>I.id!==E.id))},R=E=>x($=>$.filter(b=>b.id!==E));return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx(re,{className:"p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(jt,{className:"h-4 w-4"}),"Upload CSV File"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Upload a CSV or text file. If it has multiple columns, you'll be asked to map them."}),e.jsx("input",{ref:c,type:"file",accept:".csv,.txt",className:"hidden",onChange:S}),e.jsxs(w,{variant:"outline",className:"w-full",onClick:()=>{var E;return(E=c.current)==null?void 0:E.click()},children:[e.jsx(Dt,{className:"h-4 w-4 mr-2"}),"Choose File"]})]})}),e.jsx(re,{className:"p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(jt,{className:"h-4 w-4"}),"Paste Emails"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paste emails separated by commas, semicolons, or new lines."}),e.jsx(Ns,{placeholder:`[email protected], [email protected]
64or
65[email protected]; [email protected]`,value:n,onChange:E=>f(E.target.value),rows:3,className:"text-sm"})]})})]}),o.length>0&&e.jsxs("div",{className:"space-y-3",children:[j&&e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("span",{className:"text-muted-foreground truncate",children:["File: ",j]}),e.jsx(w,{variant:"ghost",size:"icon",onClick:T,children:e.jsx(vt,{className:"h-4 w-4"})})]}),e.jsx(Wn,{rows:o,fields:Dm,hasHeader:p,onHasHeaderChange:u,mapping:l,onMappingChange:N}),e.jsxs("div",{className:"flex items-center justify-end gap-3",children:[h.invalid.length>0&&e.jsxs("span",{className:"text-xs text-amber-600 flex items-center gap-1",children:[e.jsx(Is,{className:"h-3 w-3"}),h.invalid.length," need review"]}),e.jsxs(w,{size:"sm",disabled:l.email===void 0||l.email<0||h.valid.length===0&&h.invalid.length===0,onClick:M,children:["Use ",h.valid.length," email",h.valid.length===1?"":"s"]})]})]}),r.length>0&&e.jsx(re,{className:"p-4 border-amber-300 bg-amber-50",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-amber-800",children:[e.jsx(Is,{className:"h-4 w-4"}),r.length," address",r.length===1?"":"es"," need correction"]}),e.jsx("p",{className:"text-xs text-amber-700",children:"These won't be sent until you fix them. Common cause: addresses that got broken across lines when copied from a spreadsheet or PDF."}),e.jsx("div",{className:"space-y-2 max-h-64 overflow-y-auto",children:r.map(E=>{const $=pa(E.value),b=ga($)&&$!==E.value;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(A,{value:E.value,onChange:I=>Q(E.id,I.target.value),className:"h-8 text-sm bg-background"}),e.jsx("p",{className:"text-[11px] text-amber-700 mt-0.5 truncate",children:E.reason})]}),b&&e.jsx(w,{size:"sm",variant:"outline",className:"h-8",onClick:()=>Q(E.id,$),title:`Fix to ${$}`,children:e.jsx(fn,{className:"h-3 w-3"})}),e.jsx(w,{size:"sm",className:"h-8",disabled:!ga(pa(E.value)),onClick:()=>Z(E),children:e.jsx(Os,{className:"h-3 w-3"})}),e.jsx(w,{size:"sm",variant:"ghost",className:"h-8",onClick:()=>R(E.id),children:e.jsx(vt,{className:"h-3 w-3"})})]},E.id)})})]})}),t.length>0&&e.jsx(re,{className:"p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-sm font-medium",children:["Preview (",t.length," emails)"]}),e.jsx(w,{size:"sm",onClick:C,children:"Import All"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 max-h-32 overflow-y-auto",children:[t.slice(0,50).map(E=>e.jsxs(ie,{variant:"secondary",className:"text-xs",children:[E.repaired&&e.jsx(fn,{className:"h-3 w-3 mr-1 text-amber-600"}),E.name?`${E.name} <${E.email}>`:E.email,e.jsx("button",{onClick:()=>L(E.email),className:"ml-1 hover:text-destructive",children:e.jsx(vt,{className:"h-3 w-3"})})]},E.email)),t.length>50&&e.jsxs(ie,{variant:"outline",className:"text-xs",children:["+",t.length-50," more"]})]})]})})]})}function Fm({recipients:s,onRemoveRecipient:n,onSend:i,isSending:t,initialSubject:d="",initialBody:r=""}){const{currentOrganization:x}
65=Je(),[c,o]=a.useState(d),[m,p]=a.useState(!1),u=a.useRef(null),l=mi({extensions:[ui.configure({bulletList:{keepMarks:!0,keepAttributes:!1},orderedList:{keepMarks:!0,keepAttributes:!1},heading:{levels:[1,2,3]}}),hi,xi.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline cursor-pointer"}}),ei.configure({inline:!1,allowBase64:!1,HTMLAttributes:{style:"max-width: 100%; height: auto; border-radius: 8px; margin: 8px 0;"}}),ji.configure({types:["heading","paragraph"],alignments:["left","center","right","justify"],defaultAlignment:"left"})],content:r,editorProps:{attributes:{class:"prose prose-sm max-w-none focus:outline-none min-h-[200px] p-4 text-foreground"}}}),N=a.useCallback(async h=>{if(l){if(!h.type.startsWith("image/")){K.error("Please select an image file");return}if(h.size>5*1024*1024){K.error("Image must be under 5MB");return}if(!(x!=null&&x.id)){K.error("Select an organization before uploading images");return}p(!0);try{const M=h.name.split(".").pop(),T=`${x.id}/email-compose/${Date.now()}-${Math.random().toString(36).substring(2)}.${M}`,{error:C}=await z.storage.from("form-uploads").upload(T,h,{cacheControl:"3600",upsert:!1});if(C)throw C;const{data:{publicUrl:L}}=z.storage.from("form-uploads").getPublicUrl(T),Q=window.prompt("Optional: enter a URL to make this image clickable (leave blank for none):","");if(Q&&Q.trim()){const Z=Q.trim();l.chain().focus().insertContent(`<p><a href="${Z.replace(/"/g,"&quot;")}" target="_blank" rel="noopener noreferrer"><img src="${L}" alt="" style="max-width:100%;height:auto;border-radius:8px;margin:8px 0;" /></a></p>`).run()}else l.chain().focus().setImage({src:L}).run();K.success("Image added")}catch(M){console.error("Image upload error:",M),K.error(M.message||"Failed to upload image")}finally{p(!1),u.current&&(u.current.value="")}}},[l,x==null?void 0:x.id]),j=a.useCallback(h=>{var T;const M=(T=h.target.files)==null?void 0:T[0];M&&N(M)},[N]),g=a.useCallback(()=>{if(!l)return;const{from:h,to:M}=l.state.selection,T=h!==M,C=l.getAttributes("link").href,L=window.prompt("Enter URL:",C||"https://");if(L!==null){if(L===""){l.chain().focus().extendMarkRange("link").unsetLink().run();return}T?l.chain().focus().setLink({href:L}).run():C?l.chain().focus().extendMarkRange("link").setLink({href:L}).run():K.error("Please select some text first to create a link")}},[l]),y=a.useCallback(()=>{l&&l.chain().focus().extendMarkRange("link").unsetLink().run()},[l]),k=a.useCallback(()=>{if(!l)return;const h=window.prompt("Button label:","Click Here");if(!h)return;const M=window.prompt("Button URL:","https://");if(!M)return;const T=M.replace(/"/g,"&quot;"),C=h.replace(/</g,"&lt;").replace(/>/g,"&gt;");l.chain().focus().insertContent(`<p style="text-align:center;margin:24px 0;"><a href="${T}" target="_blank" rel="noopener noreferrer" style="display:inline-block;padding:12px 28px;background-color:#dc2626;color:#ffffff;text-decoration:none;border-radius:6px;font-weight:600;font-size:16px;">${C}</a></p>`).run()},[l]),S=()=>{c.trim()&&(!(l!=null&&l.getHTML())||l.isEmpty||i(c,l.getHTML()))},f=()=>!c.trim()||s.length===0?!1:l&&!l.isEmpty;return l?e.jsxs("div",{className:"space-y-4",children:[e.jsxs(re,{className:"p-4",children:[e.jsxs(v,{className:"text-sm font-medium mb-2 block",children:["Recipients (",s.length,")"]}),s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No recipients selected"}):e.jsxs("div",{className:"flex flex-wrap gap-2 max-h-24 overflow-y-auto",children:[s.slice(0,20).map(h=>e.jsxs(ie,{variant:"secondary",className:"text-xs",children:[h.name||h.email,e.jsx("button",{onClick:()=>n(h.email),className:"ml-1 hover:text-destructive",children:e.jsx(vt,{className:"h-3 w-3"})})]},h.email)),s.length>20&&e.jsxs(ie,{variant:"outline",className:"text-xs",children:["+",s.length-20," more"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"email-subject",children:"Subject"}),e.jsx(A,{id:"email-subject",placeholder:"Enter email subject...",value:c,onChange:h=>o(h.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{children:"Message"}),e.jsxs("div",{className:"border border-input rounded-md overflow-hidden bg-background",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1 p-2 border-b border-input bg-muted/30",children:[e.jsx(w,{type:"button",variant:l.isActive("heading",{level:1})?"default":"ghost",size:"sm",onClick:()=>l.chain().focus().toggleHeading({level:1}).run(),className:"h-8 w-8 p-0",title:"Heading 1",children:e.jsx(vi,{className:"h-4 w-4"})}),e.jsx(w,{type:"button",variant:l.isActive("heading",{level:2})?"default":"ghost",size:"sm",onClick:()=>l.chain().focus().toggleHeading({level:2}).run(),className:"h-8 w-8 p-0",title:"Heading 2",children:e.jsx(Ni,{className:"h-4 w-4"})}),e.jsx(w,{type:"button",variant:l.isActive("heading",{level:3})?"default":"ghost",size:"sm",onClick:()=>l.chain().focus().toggleHeading({level:3}).run(),className:"h-8 w-8 p-0",title:"Heading 3",children:e.jsx(bi,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(w,{type:"button",variant:l.isActive("bold")?"default":"ghost",size:"sm",onClick:()=>l.chain().focus().toggleBold().run(),className:"h-8 w-8 p-0",title:"Bold",children:e.jsx(yi,{className:"h-4 w-4"})}),e.jsx(w,{type:"button",variant:l.isActive("italic")?"default":"ghost",size:"sm",onClick:()=>l.chain().focus().toggleItalic().run(),className:"h-8 w-8 p-0",title:"Italic",children:e.jsx(_i,{className:"h-4 w-4"})}),e.jsx(w,{type:"button",variant:l.isActive("underline")?"default":"ghost",size:"sm",onClick:()=>l.chain().focus().toggleUnderline().run(),className:"h-8 w-8 p-0",title:"Underline",children:e.jsx(wi,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(w,{type:"button",variant:l.isActive({textAlign:"left"})?"default":"ghost",size:"sm",onClick:()=>l.chain().focus().setTextAlign("left").run(),className:"h-8 w-8 p-0",title:"Align left",children:e.jsx(Si,{className:"h-4 w-4"})}),e.jsx(w,{type:"button",variant:l.isActive({textAlign:"center"})?"default":"ghost",size:"sm",onClick:()=>l.chain().focus().setTextAlign("center").run(),className:"h-8 w-8 p-0",title:"Align center",children:e.jsx(Ci,{className:"h-4 w-4"})}),e.jsx(w,{type:"button",variant:l.isActive({textAlign:"right"})?"default":"ghost",size:"sm",onClick:()=>l.chain().focus().setTextAlign("right").run(),className:"h-8 w-8 p-0",title:"Align right",children:e.jsx(ki,{className:"h-4 w-4"})}),e.jsx(w,{type:"button",variant:l.isActive({textAlign:"justify"})?"default":"ghost",size:"sm",onClick:()=>l.chain().focus().setTextAlign("justify").run(),className:"h-8 w-8 p-0",title:"Justify",children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(w,{type:"button",variant:l.isActive("bulletList")?"default":"ghost",size:"sm",onClick:()=>l.chain().focus().toggleBulletList().run(),className:"h-8 w-8 p-0",title:"Bullet List",children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx(w,{type:"button",variant:l.isActive("orderedList")?"default":"ghost",size:"sm",onClick:()=>l.chain().focus().toggleOrderedList().run(),className:"h-8 w-8 p-0",title:"Numbered List",children:e.jsx(Gn,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(w,{type:"button",variant:l.isActive("link")?"default":"ghost",size:"sm",onClick:g,className:"h-8 w-8 p-0",title:"Add Link",children:e.jsx(Za,{className:"h-4 w-4"})}),l.isActive("link")&&e.jsx(w,{type:"button",variant:"ghost",size:"sm",onClick:y,className:"h-8 w-8 p-0",title:"Remove Link",children:e.jsx(Ei,{className:"h-4 w-4"})}),e.jsx(w,{type:"button",variant:"ghost",size:"sm",onClick:k,className:"h-8 w-8 p-0",title:"Insert button",children:e.jsx(md,{className:"h-4 w-4"})}),e.jsx(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>{var h;
65return(h=u.current)==null?void 0:h.click()},className:"h-8 w-8 p-0",title:"Add Image",disabled:m,children:m?e.jsx(oe,{className:"h-4 w-4 animate-spin"}):e.jsx(Ia,{className:"h-4 w-4"})}),e.jsx("input",{ref:u,type:"file",accept:"image/*",className:"hidden",onChange:j})]}),e.jsx(fi,{editor:l})]})]}),e.jsx(w,{className:"w-full",onClick:S,disabled:t||!f(),children:t?e.jsxs(e.Fragment,{children:[e.jsx(oe,{className:"h-4 w-4 mr-2 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(gt,{className:"h-4 w-4 mr-2"})," Send to ",s.length," recipient(s)"]})})]}):null}function Am({channel:s,onOpenSettings:n}){const{currentOrganization:i}=Je(),t=i==null?void 0:i.id,{data:d}=ms({queryKey:["org-compliance-banner",t],enabled:!!t,queryFn:async()=>{const{data:x}=await z.from("organizations").select("mailing_address, bulk_email_enabled, high_volume_email_enabled, high_volume_sms_enabled").eq("id",t).maybeSingle();return x},staleTime:6e4});if(!d)return null;const r=[];return s==="email"&&((!d.mailing_address||!d.mailing_address.toString().trim())&&r.push({variant:"destructive",icon:Is,title:"Mailing address required",body:"Bulk emails will be rejected until you add a physical mailing address (required by CAN-SPAM). Open Settings → Compliance & Sending."}),d.bulk_email_enabled===!1&&r.push({variant:"destructive",icon:Zc,title:"Bulk email disabled",body:"Bulk email sending is currently disabled for your organization by Beyond Pro. Contact support to re-enable."})),r.length===0?null:e.jsx("div",{className:"space-y-2 mb-4",children:r.map((x,c)=>{const o=x.icon;return e.jsxs(ht,{variant:x.variant,children:[e.jsx(o,{className:"h-4 w-4"}),e.jsx(Or,{children:x.title}),e.jsxs(xt,{className:"flex items-start justify-between gap-3",children:[e.jsx("span",{children:x.body}),n&&e.jsx(w,{size:"sm",variant:"outline",onClick:n,children:"Open Settings"})]})]},c)})})}function Lm({open:s,onClose:n,onSend:i,isSending:t,initialSubject:d="",initialBody:r=""}){const{currentOrganization:x}=Je(),[c,o]=a.useState(1),[m,p]=a.useState(""),[u,l]=a.useState("manual"),[N,j]=a.useState(""),[g,y]=a.useState(null),[k,S]=a.useState([]),[f,h]=a.useState([]),[M,T]=a.useState([]),[C,L]=a.useState([]),[Q,Z]=a.useState(""),[R,E]=a.useState(""),[$,b]=a.useState("all"),[I,V]=a.useState([]),[H,Y]=a.useState(d),{groups:W}=zn(),te=Ja(),{data:B=[]}=Xr(x==null?void 0:x.id);a.useEffect(()=>{if(u!=="contacts"||!g){u==="contacts"&&V([]);return}(async()=>{const{data:ve,error:he}=await z.from("email_group_members").select("*").eq("group_id",g);if(he){K.error("Failed to load group members");return}V((ve||[]).map(ze=>({email:ze.email,name:ze.display_name||void 0})))})()},[u,g]),a.useEffect(()=>{s&&(o(1),p(d||""),l("manual"),j(""),y(null),S([]),h([]),T([]),L([]),Z(""),E(""),b("all"),V([]),Y(d))},[s,d]),a.useEffect(()=>{u==="events"&&(k.length>0||f.length>0||M.length>0?te.mutate({years:k.length>0?k:void 0,seriesNames:f.length>0?f:void 0,eventNames:M.length>0?M:void 0,classNames:C.length>0?C:void 0},{onSuccess:ue=>{V(ue.map(ve=>({email:ve.email,name:ve.name})))}}):V([]))},[k,f,M,C,u]),a.useEffect(()=>{u==="date-range"&&(Q&&R?te.mutate({registeredFrom:Q,registeredTo:R,eventId:$&&$!=="all"?$:void 0},{onSuccess:ue=>{V(ue.map(ve=>({email:ve.email,name:ve.name})))}}):V([]))},[Q,R,$,u]);const le=a.useMemo(()=>u==="manual"?N.split(/[,;\n]+/).map(ue=>ue.trim()).filter(ue=>ue.includes("@")).map(ue=>({email:ue})):I,[u,N,I]),Me=()=>{if(le.length===0){K.error("Please add at least one recipient");return}o(2)},_=()=>o(1),X=()=>o(2),F=()=>{if(!H.trim()){K.error("Please enter a subject line");return}o(3)},ne=()=>{let ue;if(me==="schedule"&&ee){const[ve,he]=je.split(":").map(Number);ue=new Date(ee),ue.setHours(ve,he,0,0)}i({subject:H,messageBody:J,recipients:le,scheduledAt:ue,crossPost:U})},[J,_e]=a.useState(r),[me,$e]=a.useState("now"),[ee,pe]=a.useState(void 0),[je,we]=a.useState("09:00"),[U,se]=a.useState(Aa);return e.jsx(ts,{open:s,onOpenChange:ue=>!ue&&n(),children:e.jsxs(as,{className:"max-w-5xl max-h-[90vh] flex flex-col p-0 gap-0",children:[e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-b",children:[c>1&&e.jsx("button",{onClick:c===2?_:X,className:"text-muted-foreground hover:text-foreground",children:e.jsx(ya,{className:"h-5 w-5"})}),e.jsxs("h2",{className:"text-lg font-semibold",children:[c===1&&"Create Email Blast",c===2&&"Create Email Blast",c===3&&"Review & Send Email Blast"]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-4",children:[c===1&&e.jsx(Pm,{campaignName:m,setCampaignName:p,sendToMode:u,setSendToMode:l,manualEmails:N,setManualEmails:j,selectedGroupId:g,setSelectedGroupId:y,selectedYears:k,setSelectedYears:S,selectedSeries:f,setSelectedSeries:h,selectedEvents:M,setSelectedEvents:T,selectedClasses:C,setSelectedClasses:L,dateFrom:Q,setDateFrom:Z,dateTo:R,setDateTo:E,dateRangeEventId:$,setDateRangeEventId:b,orgEvents:B,recipients:I,setRecipients:V,groups:W,resolvedRecipientCount:le.length}),c===2&&e.jsx(Im,{subject:H,setSubject:Y,initialBody:r,onBodyChange:_e,organizationId:x==null?void 0:x.id}),c===3&&e.jsx(qm,{recipientCount:le.length,subject:H,messageBody:J,sendMode:me,setSendMode:$e,scheduledDate:ee,setScheduledDate:pe,scheduledTime:je,setScheduledTime:we,crossPost:U,setCrossPost:se})]}),e.jsxs("div",{className:"flex gap-3 px-6 py-4 border-t",children:[c===1&&e.jsxs(e.Fragment,{children:[e.jsx(w,{onClick:Me,children:"Continue"}),e.jsx(w,{variant:"outline",onClick:n,children:"Cancel"})]}),c===2&&e.jsxs(e.Fragment,{children:[e.jsx(w,{onClick:F,children:"Review & Send"}),e.jsx(w,{variant:"outline",onClick:n,children:"Cancel"})]}),c===3&&e.jsxs(e.Fragment,{children:[e.jsx(w,{onClick:ne,disabled:t||me==="schedule"&&!ee,children:t?e.jsxs(e.Fragment,{children:[e.jsx(oe,{className:"h-4 w-4 mr-2 animate-spin"})," Sending..."]}):me==="schedule"?e.jsxs(e.Fragment,{children:[e.jsx(yt,{className:"h-4 w-4 mr-2"})," Schedule Campaign"]}):e.jsxs(e.Fragment,{children:[e.jsx(gt,{className:"h-4 w-4 mr-2"})," Send Now"]})}),e.jsx(w,{variant:"outline",onClick:n,children:"Cancel"})]})]})]})})}function Pm({campaignName:s,setCampaignName:n,sendToMode:i,setSendToMode:t,manualEmails:d,setManualEmails:r,selectedGroupId:x,setSelectedGroupId:c,selectedYears:o,setSelectedYears:m,selectedSeries:p,setSelectedSeries:u,selectedEvents:l,setSelectedEvents:N,selectedClasses:j,setSelectedClasses:g,dateFrom:y,setDateFrom:k,dateTo:S,setDateTo:f,dateRangeEventId:h,setDateRangeEventId:M,orgEvents:T,recipients:C,setRecipients:L,groups:Q,resolvedRecipientCount:Z}){return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:"Campaign Settings"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Step 1 of 2"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{children:"Campaign Name *"}),e.jsx(A,{value:s,onChange:R=>n(R.target.value),placeholder:"e.g. 2026 Season Announcement"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(v,{children:"Send to *"}),e.jsxs(ut,{value:i,onValueChange:R=>t(R),className:"flex gap-6",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(js,{value:"events",id:"send-events"}),e.jsx(v,{htmlFor:"send-events",className:"cursor-pointer",children:"Past Registrants"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(js,{value:"manual",id:"send-manual"}),e.jsx(v,{htmlFor:"send-manual",className:"cursor-pointer",children:"Manually Enter or Import"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(js,{value:"contacts",id:"send-contacts"}),e.jsx(v,{htmlFor:"send-contacts",className:"cursor-pointer",children:"Contacts"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(js,{value:"date-range",id:"send-date-range"}),e.jsx(v,{htmlFor:"send-date-range",className:"cursor-pointer",children:"Registration Date Range"})]})]}),i==="manual"&&e.jsx(Ns,{placeholder:"Enter email addresses, one per line or comma-separated",value:d,onChange:R=>r(R.target.value),className:"min-h-[100px]"}),i==="events"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(Jt,{selectedYears:o,selectedSeries:p,selectedEvents:l,selectedClasses:j,onYearsChange:m,onSeriesChange:u,onEventsChange:N,onClasse
65sChange:g}),C.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[C.length," recipient(s) found"]})]}),i==="contacts"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Pe,{value:x||"",onValueChange:c,children:[e.jsx(Ie,{children:e.jsx(qe,{placeholder:"Choose an email group..."})}),e.jsx(Be,{children:Q==null?void 0:Q.map(R=>e.jsx(ae,{value:R.id,children:R.name},R.id))})]}),(Q==null?void 0:Q.length)===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No email groups yet. Create one in the Groups tab."})]}),i==="date-range"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Optionally pick a specific event, then a sign-up date range. Dates are in Mountain Time. Deduped by email."}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(v,{htmlFor:"email-date-event",className:"text-xs",children:"Event (optional)"}),e.jsxs(Pe,{value:h,onValueChange:M,children:[e.jsx(Ie,{id:"email-date-event",children:e.jsx(qe,{placeholder:"All events in this org"})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"all",children:"All events in this org"}),T.map(R=>e.jsxs(ae,{value:R.id,children:[R.name,R.event_date?` — ${R.event_date}`:""]},R.id))]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(v,{htmlFor:"email-date-from",className:"text-xs",children:"From"}),e.jsx(A,{id:"email-date-from",type:"date",value:y,onChange:R=>k(R.target.value)})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(v,{htmlFor:"email-date-to",className:"text-xs",children:"To"}),e.jsx(A,{id:"email-date-to",type:"date",value:S,onChange:R=>f(R.target.value)})]})]}),C.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[C.length," recipient(s) found"]})]}),Z>0&&e.jsxs(ie,{variant:"secondary",children:[Z," recipient(s)"]})]})]})}function Im({subject:s,setSubject:n,initialBody:i,onBodyChange:t,organizationId:d}){const[r,x]=a.useState(!1),c=a.useRef(null),o=mi({extensions:[ui.configure({bulletList:{keepMarks:!0,keepAttributes:!1},orderedList:{keepMarks:!0,keepAttributes:!1},heading:{levels:[1,2,3]}}),hi,xi.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline cursor-pointer"}}),ei.configure({inline:!1,allowBase64:!1,HTMLAttributes:{style:"max-width: 100%; height: auto; border-radius: 8px; margin: 8px 0;"}}),ji.configure({types:["heading","paragraph"],alignments:["left","center","right","justify"],defaultAlignment:"left"})],content:i,editorProps:{attributes:{class:"prose prose-sm max-w-none focus:outline-none min-h-[200px] p-4 text-foreground"}},onUpdate:({editor:l})=>{t(l.getHTML())}});a.useEffect(()=>{o&&i&&t(i)},[o]);const m=a.useCallback(async l=>{if(o){if(!l.type.startsWith("image/")){K.error("Please select an image file");return}if(l.size>5*1024*1024){K.error("Image must be under 5MB");return}if(!d){K.error("Select an organization before uploading images");return}x(!0);try{const N=l.name.split(".").pop(),j=`${d}/email-compose/${Date.now()}-${Math.random().toString(36).substring(2)}.${N}`,{error:g}=await z.storage.from("form-uploads").upload(j,l,{cacheControl:"3600",upsert:!1});if(g)throw g;const{data:{publicUrl:y}}=z.storage.from("form-uploads").getPublicUrl(j);o.chain().focus().setImage({src:y}).run(),K.success("Image added")}catch(N){K.error(N.message||"Failed to upload image")}finally{x(!1),c.current&&(c.current.value="")}}},[o,d]),p=a.useCallback(()=>{if(!o)return;const l=o.getAttributes("link").href,N=window.prompt("Enter URL:",l||"https://");if(N!==null){if(N===""){o.chain().focus().extendMarkRange("link").unsetLink().run();return}o.chain().focus().extendMarkRange("link").setLink({href:N}).run()}},[o]),u=a.useCallback(()=>{o&&o.chain().focus().extendMarkRange("link").unsetLink().run()},[o]);return o?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:"Message Details"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Step 2 of 2"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{children:"Subject *"}),e.jsx(A,{value:s,onChange:l=>n(l.target.value),placeholder:"Email subject line"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{children:"Message *"}),e.jsxs("div",{className:"border border-input rounded-md overflow-hidden bg-background",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1 p-2 border-b border-input bg-muted/30",children:[e.jsx(w,{type:"button",variant:o.isActive("heading",{level:1})?"default":"ghost",size:"sm",onClick:()=>o.chain().focus().toggleHeading({level:1}).run(),className:"h-8 w-8 p-0",title:"Heading 1",children:e.jsx(vi,{className:"h-4 w-4"})}),e.jsx(w,{type:"button",variant:o.isActive("heading",{level:2})?"default":"ghost",size:"sm",onClick:()=>o.chain().focus().toggleHeading({level:2}).run(),className:"h-8 w-8 p-0",title:"Heading 2",children:e.jsx(Ni,{className:"h-4 w-4"})}),e.jsx(w,{type:"button",variant:o.isActive("heading",{level:3})?"default":"ghost",size:"sm",onClick:()=>o.chain().focus().toggleHeading({level:3}).run(),className:"h-8 w-8 p-0",title:"Heading 3",children:e.jsx(bi,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(w,{type:"button",variant:o.isActive("bold")?"default":"ghost",size:"sm",onClick:()=>o.chain().focus().toggleBold().run(),className:"h-8 w-8 p-0",title:"Bold",children:e.jsx(yi,{className:"h-4 w-4"})}),e.jsx(w,{type:"button",variant:o.isActive("italic")?"default":"ghost",size:"sm",onClick:()=>o.chain().focus().toggleItalic().run(),className:"h-8 w-8 p-0",title:"Italic",children:e.jsx(_i,{className:"h-4 w-4"})}),e.jsx(w,{type:"button",variant:o.isActive("underline")?"default":"ghost",size:"sm",onClick:()=>o.chain().focus().toggleUnderline().run(),className:"h-8 w-8 p-0",title:"Underline",children:e.jsx(wi,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(w,{type:"button",variant:o.isActive({textAlign:"left"})?"default":"ghost",size:"sm",onClick:()=>o.chain().focus().setTextAlign("left").run(),className:"h-8 w-8 p-0",title:"Align left",children:e.jsx(Si,{className:"h-4 w-4"})}),e.jsx(w,{type:"button",variant:o.isActive({textAlign:"center"})?"default":"ghost",size:"sm",onClick:()=>o.chain().focus().setTextAlign("center").run(),className:"h-8 w-8 p-0",title:"Align center",children:e.jsx(Ci,{className:"h-4 w-4"})}),e.jsx(w,{type:"button",variant:o.isActive({textAlign:"right"})?"default":"ghost",size:"sm",onClick:()=>o.chain().focus().setTextAlign("right").run(),className:"h-8 w-8 p-0",title:"Align right",children:e.jsx(ki,{className:"h-4 w-4"})}),e.jsx(w,{type:"button",variant:o.isActive({textAlign:"justify"})?"default":"ghost",size:"sm",onClick:()=>o.chain().focus().setTextAlign("justify").run(),className:"h-8 w-8 p-0",title:"Justify",children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(w,{type:"button",variant:o.isActive("bulletList")?"default":"ghost",size:"sm",onClick:()=>o.chain().focus().toggleBulletList().run(),className:"h-8 w-8 p-0",title:"Bullet List",children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx(w,{type:"button",variant:o.isActive("orderedList")?"default":"ghost",size:"sm",onClick:()=>o.chain().focus().toggleOrderedList().run(),className:"h-8 w-8 p-0",title:"Numbered List",children:e.jsx(Gn,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(w,{type:"button",variant:o.isActive("link")?"default":"ghost",size:"sm",onClick:p,className:"h-8 w-8 p-0",title:"Add Link",children:e.jsx(Za,{className:"h-4 w-4"})}),o.isActive("link")&&e.jsx(w,{type:"button",variant:"ghost",size:"sm",onClick:u,className:"h-8 w-8 p-0",title:"Remove Link",children:e.jsx(Ei,{className:"h-4 w-4"})}),e.jsx(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>{var l;return(l=c.current)==null?void 0:l.click()},className:"h-8 w-8 p-0",title:"Add Image",disabled:r,children:r?e.jsx(oe,{className:"h-4 w-4 animate-spin"}):e.jsx(Ia,{className:"h-4 w-4"})}),e.jsx("input",{ref:c,type:"file",accept:"image/*",className:"hidden",onChange:l=>{var j;const N=(j=l.target.files)==null?void 0:j[0];N&&m(N)}})]}),e.jsx(fi,{editor:o})]})]})]}):null}function qm({recipientCount:s,subject:n,messageBody:i,sendMode:t,setSendMode:d,scheduledDate:r,setScheduledDate:x,scheduledTime:c,setScheduledTime:o,crossPost:m,setCrossPost:p}){return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(v,{className:"font-semibold",children:"When to 
65send"}),e.jsxs(ut,{value:t,onValueChange:u=>d(u),className:"flex gap-6",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(js,{value:"now",id:"send-now"}),e.jsx(v,{htmlFor:"send-now",className:"cursor-pointer",children:"Send Immediately"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(js,{value:"schedule",id:"send-schedule"}),e.jsx(v,{htmlFor:"send-schedule",className:"cursor-pointer",children:"Schedule for Later"})]})]}),t==="schedule"&&e.jsxs("div",{className:"flex items-center gap-3 pl-1",children:[e.jsxs(Ti,{children:[e.jsx(Ri,{asChild:!0,children:e.jsxs(w,{variant:"outline",className:Cs("w-[180px] justify-start text-left font-normal",!r&&"text-muted-foreground"),children:[e.jsx(At,{className:"mr-2 h-4 w-4"}),r?Js(r,"PPP"):"Pick a date"]})}),e.jsx($i,{className:"w-auto p-0",align:"start",children:e.jsx(so,{mode:"single",selected:r,onSelect:x,disabled:u=>u<new Date(new Date().setHours(0,0,0,0)),initialFocus:!0,className:Cs("p-3 pointer-events-auto")})})]}),e.jsx(A,{type:"time",value:c,onChange:u=>o(u.target.value),className:"w-[130px]"})]})]}),e.jsx("hr",{}),e.jsxs("div",{className:"flex gap-6",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-1",children:"Recipients"}),e.jsx("p",{className:"font-medium text-primary",children:s})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-1",children:"Subject"}),e.jsx("p",{className:"font-medium",children:n})]})]}),e.jsx("hr",{}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Email Preview"}),e.jsxs("div",{className:"border rounded-lg overflow-hidden bg-white shadow-sm",children:[e.jsxs("div",{className:"bg-muted/50 px-4 py-3 border-b space-y-1 text-sm",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"text-muted-foreground w-14 text-right",children:"From:"}),e.jsx("span",{className:"font-medium text-foreground",children:"[email protected]"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"text-muted-foreground w-14 text-right",children:"To:"}),e.jsxs("span",{className:"text-foreground",children:[s," recipient",s!==1?"s":""]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"text-muted-foreground w-14 text-right",children:"Subject:"}),e.jsx("span",{className:"font-semibold text-foreground",children:n})]})]}),e.jsx("div",{className:"p-6 max-h-[350px] overflow-y-auto",children:e.jsx(Mi,{html:i,className:"prose prose-sm max-w-none text-foreground"})})]})]}),e.jsx(Jr,{value:m,onChange:p,hint:"The email body will be converted to plain text for the feed. The first inline image (if any) will be reused."})]})}const Bm="https://hhkjvpdlkhxblpqzugic.supabase.co/storage/v1/object/public/form-uploads/9610a950-18d3-47e1-8d05-f6d9f8da3bd4/timing-tour",mn="https://beyondproreg.com/org/edgepowersports/timing",Um="Your Guide to the New Edge Powersports Live Timing Site 🏁",fa="#dc2626";function _t(s){const{step:n,title:i,body:t,img:d,imgAlt:r,link:x}=s;return`
66<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin-bottom:32px;">
67<tr>
68<td width="36" valign="top"><div style="width:28px;height:28px;border-radius:50%;background-color:${fa};color:#ffffff;font-size:14px;font-weight:700;text-align:center;line-height:28px;">${n}</div></td>
69<td style="padding-left:12px;">
70<h2 style="margin:0 0 8px;color:#18181b;font-size:18px;font-weight:700;line-height:1.3;">${i}</h2>
71<p style="margin:0 0 14px;color:#3f3f46;font-size:14px;line-height:1.6;">${t}</p>
72${d?`<img src="${Bm}/${d}" alt="${r||i}" width="280" style="display:block;width:280px;max-width:100%;height:auto;border:1px solid #e4e4e7;border-radius:12px;box-shadow:0 2px 6px rgba(0,0,0,0.08);margin:0 0 14px;" />`:""}
73${x?`<p style="margin:0;"><a href="${x.href}" target="_blank" rel="noopener noreferrer" style="color:${fa};font-size:14px;font-weight:600;text-decoration:underline;">${x.label} →</a></p>`:""}
74</td>
75</tr>
76</table>`}const zm=`
77<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background-color:#f4f4f5;">
78<tr><td align="center" style="padding:24px 12px;">
79<table role="presentation" width="600" cellpadding="0" cellspacing="0" style="max-width:600px;width:100%;background-color:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 2px 8px rgba(0,0,0,0.08);font-family:Arial,Helvetica,sans-serif;">
80
81<!-- Header -->
82<tr><td style="background-color:${fa};padding:32px 32px;text-align:center;">
83<h1 style="margin:0;color:#ffffff;font-size:24px;font-weight:800;line-height:1.3;">EDGE POWERSPORTS RACE TIMING</h1>
84<p style="margin:8px 0 0;color:rgba(255,255,255,0.92);font-size:15px;">A quick tour of the new live timing website</p>
85</td></tr>
86
87<!-- Body -->
88<tr><td style="padding:32px 32px 8px;">
89
90<p style="margin:0 0 16px;color:#27272a;font-size:15px;line-height:1.6;">
91Hey Edge racers and families! We have a brand-new <strong>live timing website</strong> where you can follow the schedule, watch live results, check gate picks, and see series points — all from your phone. Here's a quick walkthrough of everything on the site.
92</p>
93
94<p style="margin:0 0 28px;text-align:center;">
95<a href="${mn}" target="_blank" rel="noopener noreferrer" style="display:inline-block;padding:14px 32px;background-color:${fa};color:#ffffff;text-decoration:none;border-radius:8px;font-weight:700;font-size:16px;">Open the Timing Site</a>
96</p>
97
98${_t({step:1,title:"Pick Your Event",body:"When you open the site, choose the <strong>year</strong>, <strong>series</strong> (like MiniMX PeeWee or Main Track), and the <strong>race</strong> you want to follow. Once you pick an event, everything else on the site — schedule, results, gate picks — is for that event. The banner at the very top always shows what's running and what's up next.",img:"01-home.png",imgAlt:"Timing site home page with year, series, and event pickers",link:{href:mn,label:"Go to the timing site"}})}
99
100${_t({step:2,title:"Sign In & Add Your Riders — Make the Site Yours",body:`This is the best part: <strong>sign in to your rider account</strong> and add your riders, and the whole site becomes personal. A <strong>"My Riders"</strong> button appears at the top of the Schedule, Gate Pick, Results, Lap Times, and Classes pages — tap it and everything filters down to <strong>just your riders</strong>. Your riders' classes are highlighted in the schedule so you can spot them at a glance, their gate picks are front and center, and results show exactly how your crew finished without scrolling through every class. Don't have an account yet? Creating one is free and only takes a minute.`,link:{href:"https://beyondproreg.com/org/edgepowersports/login",label:"Sign in or create your account"}})}
101
102${_t({step:3,title:"The Bottom Menu Is Your Map",body:"Across the bottom of the screen you'll find four tabs: <strong>Schedule</strong>, <strong>Race Day</strong>, <strong>Results</strong>, and <strong>
102Classes</strong>. Tap any of them at any time — they work just like the tabs in your favorite apps."})}
103
104${_t({step:4,title:"Schedule — Know When You Race",body:"The <strong>Schedule</strong> tab lists every moto in running order, with the class, rider count, and estimated start time. Find your class to see exactly where you are in the day — or tap <strong>My Riders</strong> when signed in to see only your motos.",img:"02-schedule.png",imgAlt:"Schedule tab with motos, classes, and times"})}
105
106${_t({step:5,title:"Race Day — Live Timing",body:'On race day, the <strong>Race Day</strong> tab opens to <strong>Live Timing</strong> — a live leaderboard that updates as the race runs. Between races it shows "Waiting for the next race to start," and the green "Up next" banner at the top tells you which class is heading to the gate.',img:"03-live-timing.png",imgAlt:"Live Timing tab waiting for the next race"})}
107
108${_t({step:6,title:"Gate Pick — See Your Gate Order",body:"Inside Race Day, tap <strong>Gate Pick</strong> to see the gate selection order for every moto. Search by rider name, bike number, or class to jump straight to your rider — or use the <strong>My Riders</strong> filter to see only your family's gate picks.",img:"04-gate-pick.png",imgAlt:"Gate Pick tab with rider gate order"})}
109
110${_t({step:7,title:"Race Feed — News & Announcements",body:"The <strong>Race Feed</strong> is where Edge posts schedules, announcements, and updates. Check it before race day for gate times and any changes.",img:"05-race-feed.png",imgAlt:"Race Feed with announcements"})}
111
112${_t({step:8,title:"Results — Finishes & Points",body:"The <strong>Results</strong> tab shows finished motos with each rider's moto finishes and overall points. Use the class dropdown to filter to just your class — signed-in parents can flip on <strong>My Riders</strong> to jump straight to their riders' results.",img:"06-race-results.png",imgAlt:"Race Results tab with finishes and points"})}
113
114${_t({step:9,title:"Podium — Top 3 in Every Class",body:"Tap <strong>Podium</strong> inside Results for a clean top-3 view of every class — perfect for a quick screenshot to share.",img:"07-podium.png",imgAlt:"Podium tab with top three riders"})}
115
116${_t({step:10,title:"Series Points — The Championship Chase",body:"<strong>Series Points</strong> tracks the season standings race by race. Pick the series and class to see where every rider sits in the championship.",img:"08-series-points.png",imgAlt:"Series Points standings"})}
117
118${_t({step:11,title:"Classes — Who&#39;s Racing",body:"The <strong>Classes</strong> tab lists every entry for the event — rider names, numbers, and bike makes. Search by name, number, or class to find anyone.",img:"09-classes.png",imgAlt:"Classes tab with rider entries"})}
119
120<!-- Tips -->
121<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin-bottom:28px;">
122<tr><td style="background-color:#fef3c7;border:1px solid #fcd34d;border-radius:8px;padding:16px 20px;">
123<p style="margin:0;color:#92400e;font-size:14px;font-weight:700;">💡 Pro Tips</p>
124<p style="margin:6px 0 0;color:#92400e;font-size:14px;line-height:1.6;">
125• Tap the <strong>download icon</strong> at the top of the site to install it like an app on your phone.<br />
126• Sign up for <strong>"races away" text alerts</strong> in your rider account so you never miss a gate drop.
127</p>
128</td></tr>
129</table>
130
131<p style="margin:0 0 28px;text-align:center;">
132<a href="${mn}" target="_blank" rel="noopener noreferrer" style="display:inline-block;padding:14px 32px;background-color:${fa};color:#ffffff;text-decoration:none;border-radius:8px;font-weight:700;font-size:16px;">Explore the Timing Site</a>
133</p>
134
135<p style="margin:0 0 24px;color:#52525b;font-size:14px;line-height:1.6;text-align:center;">
136Bookmark it, share it with your pit crew, and we'll see you at the gate! 🏁
137</p>
138
139</td></tr>
140
141<!-- Footer -->
142<tr><td style="background-color:#f4f4f5;padding:20px 32px;text-align:center;">
143<p style="margin:0;color:#71717a;font-size:12px;line-height:1.5;">Edge Powersports • Salt Lake City, UT<br />Powered by Beyond Pro</p>
144</td></tr>
145
146</table>
147</td></tr>
148</table>
149`,Nl="#dc2626",un="https://beyondproreg.com",hn={findTeam:`${un}/__l5e/assets-v1/bf2a5647-2be6-49ef-9577-bd0b745687a1/team-guide-find-your-team-original.jpg`,inviteRiders:`${un}/__l5e/assets-v1/54d32d9c-4228-47bd-a963-6a30fb172034/team-guide-invite-your-riders-original.jpg`,manageTeam:`${un}/__l5e/assets-v1/2ddec3c4-ab93-490e-a63f-027640e18116/team-guide-manage-your-team-original.jpg`};function xn(s,n){return`<img src="${s}" alt="${n}" width="560" style="display:block;width:100%;max-width:560px;height:auto;margin:14px 0 0;border:1px solid #e4e4e7;border-radius:8px;" />`}const Vm="Your endurance team — how to manage it and invite your riders 🏁";function ua(s,n,i){return`
150<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin-bottom:28px;">
151<tr>
152<td width="36" valign="top"><div style="width:28px;height:28px;border-radius:50%;background-color:${Nl};color:#ffffff;font-size:14px;font-weight:700;text-align:center;line-height:28px;">${s}</div></td>
153<td style="padding-left:12px;">
154<h2 style="margin:0 0 8px;color:#18181b;font-size:18px;font-weight:700;line-height:1.3;">${n}</h2>
155<div style="margin:0;color:#3f3f46;font-size:14px;line-height:1.6;">${i}</div>
156</td>
157</tr>
158</table>`}const Om=`
159<div style="font-family:-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif;max-width:640px;margin:0 auto;padding:8px;">
160<h1 style="margin:0 0 6px;color:#18181b;font-size:24px;font-weight:800;">Managing your endurance team</h1>
161<p style="margin:0 0 24px;color:#52525b;font-size:15px;line-height:1.6;">Everything you need to find your team page, invite your riders by text or email, and make changes before race day.</p>
162
163${ua(1,"Find your team",`
164Sign in at <a href="https://beyondproreg.com" style="color:${Nl};font-weight:600;">beyondproreg.com</a> with the email you used to register.
165Your account home has a <strong>My Teams</strong> section — tap your team to open its page.
166You can also open the team link your captain shared and bookmark it.
167${xn(hn.findTeam,"My Teams section in a rider account")}`)}
168
169${ua(2,"Invite your riders",`
170On the team page use <strong>Invite your riders</strong>:
171<ul style="margin:8px 0 0;padding-left:18px;">
172<li>Copy the <strong>signup link</strong> or the <strong>team code</strong> and send it yourself, or</li>
173<li>Type a rider's name plus their cell number or email and hit <strong>Send invite</strong> — we text/email them their own signup link.</li>
174</ul>
175The <strong>Invited riders</strong> list shows who's been sent a link, and you can resend any time.
176${xn(hn.inviteRiders,"Team invitation tools")}`)}
177
178${ua(3,"What your teammates do",`
179They open the link, the team code fills in automatically, and they finish signup.
180If the captain is paying for the team, their checkout is $0. On split or per-rider teams they pay their share.
181If a link ever gets lost, they can enter the team code by hand on the signup form.`)}
182
183${ua(4,"Making changes",`
184From the team page a captain can:
185<ul style="margin:8px 0 0;padding-left:18px;">
186<li>Rename the team</li>
187<li>Set or change the single <strong>Team race number</strong> used by the whole team</li>
188<li>Remove a rider</li>
189<li>Hand the captain role to someone else</li>
190<li>Reset the team code if it got shared too widely (old links stop working)</li>
191</ul>
192${xn(hn.manageTeam,"Team roster and captain tools")}`)}
193
194${ua(5,"Before race day",`
195Once rosters are locked, captains can't change the roster anymore — come see us at the tent and we'll take care of it.
196Your team races on <strong>one team transponder</strong>, so decide who carries it before the start.`)}
197
198<p style="margin:24px 0 0;color:#52525b;font-size:14px;line-height:1.6;">See you at the races!</p>
199</div>`;function Gm(){const{currentOrganization:s}
199=Je(),[n,i]=a.useState("campaigns"),[t,d]=a.useState(!1),[r,x]=a.useState(!1),[c,o]=a.useState(""),[m,p]=a.useState(""),[u,l]=a.useState(!1),{sendEmail:N,isSending:j}=Vn(),{canSendEmail:g,emailsRemaining:y,hasContract:k,trialEmailLimit:S}=Fn(),f=ni(),[h,M]=a.useState(null),[T,C]=a.useState(!1);a.useEffect(()=>{const b=sessionStorage.getItem("bp_share_prefill_email");if(b){sessionStorage.removeItem("bp_share_prefill_email");try{const{subject:I,body:V}=JSON.parse(b);o(I??""),p(V??""),x(!0)}catch{}}},[]);const L=(b,I)=>{o(b),p(I),d(!0)},Q=()=>{o(""),p(""),x(!0)},Z=()=>{o(Um),p(zm),x(!0)},R=()=>{o(Vm),p(Om),x(!0)},E=async()=>{if(s!=null&&s.id){l(!0);try{const{data:b,error:I}=await z.functions.invoke("generate-signup-guide-email",{body:{organization_id:s.id}});if(I)throw I;o(b.subject),p(b.html),x(!0)}catch(b){K.error(`Failed to generate signup guide: ${b.message}`)}finally{l(!1)}}},$=b=>{if(!g){K.error("Email trial limit reached. Please sign the service agreement to continue.");return}N({subject:b.subject,message_body:b.messageBody,recipients:b.recipients,source:"timing_email"},{onSuccess:async I=>{var V;if(M({channel:"email",sent:(I==null?void 0:I.totalSent)??0,failed:(I==null?void 0:I.totalFailed)??0,timestamp:new Date().toISOString(),detail:b.subject}),C(!0),K.success(`Emails sent! ${I.totalSent} successful, ${I.totalFailed} failed`),d(!1),(V=b.crossPost)!=null&&V.enabled&&(s!=null&&s.id))try{const H=b.messageBody||"",Y=H.replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<br\s*\/?>/gi,`
200`).replace(/<\/(p|div|h[1-6]|li)>/gi,`
201`).replace(/<[^>]+>/g,"").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&#\d+;/g,"").replace(/\n{3,}/g,`
202
203`).trim(),W=H.match(/<img[^>]+src=["']([^"']+)["']/i),te=`${b.subject}
204
205${Y}`.slice(0,2e3);await f.mutateAsync({organization_id:s.id,content:te,title:b.subject||null,body_html:H||null,content_format:H?"html":"text",image_url:(W==null?void 0:W[1])||null,category:b.crossPost.category,is_pinned:b.crossPost.isPinned,is_published:!0}),K.success("Posted to Race Feed")}catch(H){K.warning(`Race Feed post failed: ${H.message||"Unknown error"}`)}},onError:I=>{K.error(`Failed to send: ${I.message}`)}})};return s!=null&&s.id?e.jsxs(e.Fragment,{children:[e.jsx(Am,{channel:"email"}),!k&&e.jsxs("div",{className:"mb-4 p-3 bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-800 rounded-lg text-sm text-amber-700 dark:text-amber-400",children:["Trial mode: ",y," of ",S," test emails remaining. Sign the service agreement to unlock unlimited email."]}),e.jsxs(ot,{value:n,onValueChange:i,className:"w-full",children:[e.jsxs(pt,{children:[e.jsxs(Qe,{value:"compose",className:"gap-2",children:[e.jsx(gt,{className:"h-4 w-4"}),"Quick Email"]}),e.jsxs(Qe,{value:"campaigns",className:"gap-2",children:[e.jsx(Ks,{className:"h-4 w-4"}),"Email Campaigns"]}),e.jsxs(Qe,{value:"groups",className:"gap-2",children:[e.jsx(Gs,{className:"h-4 w-4"}),"Groups"]})]}),e.jsx(Ae,{value:"campaigns",children:e.jsx(Km,{onComposeNew:Q,onCopyCampaign:L,onSendSignupGuide:E,generatingGuide:u,onSendTimingTour:Z,onSendTeamGuide:R})}),e.jsx(Ae,{value:"compose",children:e.jsx(Qm,{})}),e.jsx(Ae,{value:"groups",children:e.jsx(Wm,{})})]}),e.jsx(Lm,{open:t,onClose:()=>d(!1),onSend:$,isSending:j,initialSubject:c,initialBody:m},`${c}-${m}-${t}`),r&&e.jsx(ts,{open:r,onOpenChange:b=>!b&&x(!1),children:e.jsx(as,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:e.jsx(Ac,{onSend:b=>{$(b),x(!1)},isSending:j,onCancel:()=>x(!1),initialSubject:c,initialBody:m})})}),e.jsx(Ln,{open:T,onOpenChange:C,result:h})]}):e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("p",{className:"text-muted-foreground",children:"Please select an organization"})})}function Ym(s){const n=new Map,i=[...s].sort((t,d)=>new Date(d.created_at).getTime()-new Date(t.created_at).getTime());for(const t of i){const d=_n(t.subject,t.recipient_name),r=_n(t.message_body,t.recipient_name),x=ml(t.created_at),c=t.source||t.email_type||"manual",o=hl(c)?`${c}|${d}|${x}`:`${c}|${d}|${r}|${x}`;let m=n.get(o);m||(m={id:t.id,subject:ul(d,t.recipient_name)||t.subject,status:t.status==="sent"?"sent":"failed",recipients:0,sentDate:t.created_at,eventName:t.event_name,messageBody:t.message_body,logs:[]},n.set(o,m)),m.recipients++,m.logs.push({id:t.id,recipient_email:t.recipient_email,recipient_name:t.recipient_name,status:t.status,error_message:t.error_message,sent_at:t.sent_at,created_at:t.created_at}),new Date(t.created_at).getTime()>
205new Date(m.sentDate).getTime()&&(m.sentDate=t.created_at),t.status==="failed"&&m.status==="sent"&&(m.status="partial"),t.status==="sent"&&m.status==="failed"&&(m.status="partial")}return[...n.values()].sort((t,d)=>new Date(d.sentDate).getTime()-new Date(t.sentDate).getTime())}function Km({onComposeNew:s,onCopyCampaign:n,onSendSignupGuide:i,generatingGuide:t,onSendTimingTour:d,onSendTeamGuide:r}){const{logs:x,isLoading:c}=Lc(),[o,m]=a.useState(""),[p,u]=a.useState("all"),[l,N]=a.useState(null),[j,g]=a.useState(null),[y,k]=a.useState(new Set),S=C=>{k(L=>{const Q=new Set(L);return Q.has(C)?Q.delete(C):Q.add(C),Q})},f=async C=>{g(C.id);try{const L=C.logs.map(Z=>Z.id),{error:Q}=await z.from("email_logs").delete().in("id",L);if(Q)throw Q;K.success("Campaign deleted")}catch(L){K.error(`Failed to delete: ${L.message}`)}finally{g(null)}},h=a.useMemo(()=>Ym(x),[x]),M=a.useMemo(()=>h.filter(C=>{if(p!=="all"&&C.status!==p)return!1;if(o){const L=o.toLowerCase();return C.subject.toLowerCase().includes(L)||C.logs.some(Q=>Q.recipient_email.toLowerCase().includes(L))}return!0}),[h,o,p]),T=C=>{const L=new Date(C);return{date:L.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),time:L.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Email Campaigns"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"View sent emails, copy content, and resend campaigns"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(w,{variant:"outline",onClick:r,className:"gap-2",children:[e.jsx(Gs,{className:"h-4 w-4"}),"Team Guide"]}),e.jsxs(w,{variant:"outline",onClick:d,className:"gap-2",children:[e.jsx(Ks,{className:"h-4 w-4"}),"Timing Site Tour"]}),e.jsxs(w,{variant:"outline",onClick:i,disabled:t,className:"gap-2",children:[t?e.jsx(oe,{className:"h-4 w-4 animate-spin"}):e.jsx(wa,{className:"h-4 w-4"}),"Send Signup Guide"]}),e.jsxs(w,{onClick:s,className:"gap-2",children:[e.jsx(Es,{className:"h-4 w-4"}),"Create Campaign"]})]})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Ws,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(A,{placeholder:"Search campaigns...",value:o,onChange:C=>m(C.target.value),className:"pl-10"})]}),e.jsxs(Pe,{value:p,onValueChange:u,children:[e.jsx(Ie,{className:"w-[140px]",children:e.jsx(qe,{placeholder:"Status"})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"all",children:"All Status"}),e.jsx(ae,{value:"sent",children:"Sent"}),e.jsx(ae,{value:"failed",children:"Failed"}),e.jsx(ae,{value:"partial",children:"Partial"})]})]})]}),c?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(oe,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):M.length===0?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:h.length===0?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ks,{className:"h-12 w-12 mx-auto opacity-30"}),e.jsx("p",{children:"No emails sent yet"}),e.jsx("p",{className:"text-sm",children:"Create your first campaign to get started"})]}):e.jsx("p",{children:"No campaigns match your search"})}):e.jsx(re,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b text-left",children:[e.jsx("th",{className:"w-8 px-2 py-3"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground",children:"Subject"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground",children:"Status"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground text-center",children:"Recipients"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground",children:"Send Date"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground text-right",children:"Actions"})]})}),e.jsx("tbody",{children:M.map(C=>{const{date:L,time:Q}=T(C.sentDate),Z=y.has(C.id),R=C.recipients>1;return e.jsxs(a.Fragment,{children:[e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/50 transition-colors",children:[e.jsx("td",{className:"px-2 py-3 align-top",children:R?e.jsx("button",{onClick:()=>S(C.id),className:"p-1 rounded hover:bg-muted","aria-label":Z?"Collapse":"Expand",children:Z?e.jsx(mt,{className:"h-4 w-4"}):e.jsx(Hs,{className:"h-4 w-4"})}):null}),e.jsxs("td",{className:"px-4 py-3",children:[e.jsx("button",{onClick:()=>N(C),className:"text-primary hover:underline text-left font-medium text-sm",children:C.subject}),C.eventName&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:C.eventName})]}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(ie,{variant:C.status==="sent"?"default":C.status==="partial"?"secondary":"destructive",className:C.status==="sent"?"bg-emerald-100 text-emerald-700 hover:bg-emerald-100":"",children:C.status.toUpperCase()})}),e.jsx("td",{className:"px-4 py-3 text-center text-sm",children:R?e.jsx("button",{onClick:()=>S(C.id),className:"hover:underline",children:C.recipients}):C.recipients}),e.jsxs("td",{className:"px-4 py-3",children:[e.jsx("div",{className:"text-sm font-medium",children:L}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Q})]}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(w,{variant:"ghost",size:"icon",className:"h-8 w-8",title:"Copy & compose new email",onClick:()=>n(C.subject,C.messageBody),children:e.jsx(Nt,{className:"h-4 w-4"})}),e.jsx(w,{variant:"ghost",size:"icon",className:"h-8 w-8",title:"View campaign details",onClick:()=>N(C),children:e.jsx(Zt,{className:"h-4 w-4"})}),e.jsxs(et,{children:[e.jsx(Lt,{asChild:!0,children:e.jsx(w,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",title:"Delete campaign",disabled:j===C.id,children:j===C.id?e.jsx(oe,{className:"h-4 w-4 animate-spin"}):e.jsx(ws,{className:"h-4 w-4"})})}),e.jsxs(st,{children:[e.jsx(tt,{children:"Delete Campaign"}),e.jsxs(at,{children:["This will permanently delete all ",C.recipients,' email log(s) for "',C.subject,'". This action cannot be undone.']}),e.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[e.jsx(nt,{children:"Cancel"}),e.jsx(rt,{onClick:()=>f(C),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})]})]})})]}),Z&&R&&e.jsxs("tr",{className:"bg-muted/30 border-b",children:[e.jsx("td",{}),e.jsx("td",{colSpan:5,className:"px-4 py-3",children:e.jsx("div",{className:"max-h-72 overflow-y-auto rounded border bg-background",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"text-xs text-muted-foreground",children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"px-3 py-1.5 text-left font-medium",children:"Recipient"}),e.jsx("th",{className:"px-3 py-1.5 text-left font-medium",children:"Email"}),e.jsx("th",{className:"px-3 py-1.5 text-left font-medium",children:"Status"}),e.jsx("th",{className:"px-3 py-1.5 text-left font-medium",children:"Error"})]})}),e.jsx("tbody",{children:C.logs.map(E=>e.jsxs("tr",{className:"border-b last:border-0",children:[e.jsx("td",{className:"px-3 py-1.5",children:E.recipient_name||"—"}),e.jsx("td",{className:"px-3 py-1.5 text-muted-foreground",children:E.recipient_email}),e.jsx("td",{className:"px-3 py-1.5",children:e.jsx(ie,{variant:E.status==="sent"?"outline":"destructive",className:"text-xs",children:E.status})}),e.jsx("td",{className:"px-3 py-1.5 text-xs text-destructive",children:E.error_message||""})]},E.id))})]})})})]})]},C.id)})})]})})}),l&&e.jsx(Hm,{campaign:l,open:!!l,onClose:()=>N(null),onCopyCampaign:n})]})}function Hm({campaign:s,open:n,onClose:i,onCopyCampaign:t}){const{sendEmail:d,isSending:r}=Vn(),[x,c]=a.useState(""),[o,m]=a.useState(!1),p=()=>{const l=x.split(/[,;\n]+/).map(N=>N.trim()).filter(N=>N.includes("@"));if(l.length===0){K.error("Please enter at least one email address");return}d({subject:s.subject,message_body:s.messageBody,recipients:l.map(N=>({email:N})),source:"timing_email_resend"},{onSuccess:N=>{K.success(`Resent to ${l.length} recipient(s)`),m(!1),c("")},onError:N=>{K.error(`Failed to resend: ${N.message}`)}})},u=l=>
205new Date(l).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit",hour12:!0});return e.jsx(ts,{open:n,onOpenChange:l=>!l&&i(),children:e.jsxs(as,{className:"max-w-5xl max-h-[90vh] flex flex-col overflow-hidden",children:[e.jsx(rs,{children:e.jsx(is,{className:"text-xl",children:s.subject})}),e.jsx("div",{className:"flex-1 overflow-y-auto pr-4 pb-4",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1 text-sm",children:[e.jsx(ie,{variant:s.status==="sent"?"default":"destructive",className:s.status==="sent"?"bg-emerald-100 text-emerald-700 hover:bg-emerald-100":"",children:s.status.toUpperCase()}),e.jsx("span",{className:"text-muted-foreground",children:u(s.sentDate)}),e.jsxs("span",{className:"text-muted-foreground",children:[s.recipients," recipients"]}),s.eventName&&e.jsx("span",{className:"text-muted-foreground",children:s.eventName})]}),e.jsxs("details",{className:"group",children:[e.jsxs("summary",{className:"text-sm font-medium cursor-pointer select-none hover:text-primary",children:["Recipients (",s.logs.length,")"]}),e.jsx("div",{className:"border rounded-md max-h-32 overflow-y-auto mt-2",children:s.logs.map(l=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 text-sm border-b last:border-0",children:[e.jsx("span",{children:l.recipient_name?`${l.recipient_name} (${l.recipient_email})`:l.recipient_email}),e.jsx(ie,{variant:l.status==="sent"?"outline":"destructive",className:"text-xs",children:l.status})]},l.id))})]}),e.jsxs("div",{className:"flex-1 min-h-0",children:[e.jsx("p",{className:"text-sm font-medium mb-2",children:"Message"}),e.jsx("div",{className:"border rounded-md p-4 bg-muted/30 max-h-[50vh] overflow-y-auto",children:s.messageBody==="[Template Email]"?e.jsx("p",{className:"text-muted-foreground italic",children:"Sent using an email template"}):e.jsx(Mi,{html:s.messageBody,className:"prose prose-sm max-w-none"})})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(w,{variant:"outline",onClick:()=>{t(s.subject,s.messageBody),i()},className:"gap-2",children:[e.jsx(Nt,{className:"h-4 w-4"}),"Copy & Compose New"]}),s.logs.some(l=>l.status==="failed")&&e.jsxs(w,{variant:"outline",className:"gap-2 border-destructive/50 text-destructive hover:bg-destructive/10",onClick:()=>{const l=s.logs.filter(N=>N.status==="failed").map(N=>N.recipient_email);c(l.join(`
206`)),m(!0)},children:[e.jsx(ca,{className:"h-4 w-4"}),"Resend to Failed (",s.logs.filter(l=>l.status==="failed").length,")"]}),e.jsxs(w,{variant:"outline",onClick:()=>m(!o),className:"gap-2",children:[e.jsx(ca,{className:"h-4 w-4"}),"Resend"]})]}),o&&e.jsx(re,{className:"p-4 border-primary/30",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx(v,{className:"text-sm font-medium",children:"Resend to (enter email addresses, one per line or comma-separated)"}),e.jsx("textarea",{className:"w-full min-h-[80px] p-3 border rounded-md text-sm bg-background resize-y",placeholder:`[email protected]
207[email protected]`,value:x,onChange:l=>c(l.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(w,{onClick:p,disabled:r,className:"gap-2",children:r?e.jsxs(e.Fragment,{children:[e.jsx(oe,{className:"h-4 w-4 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(gt,{className:"h-4 w-4"})," Send"]})}),e.jsx(w,{variant:"ghost",onClick:()=>{m(!1),c("")},children:"Cancel"})]})]})})]})})]})})}function Qm(){const[s,n]=a.useState("events"),[i,t]=a.useState([]),[d,r]=a.useState([]),[x,c]=a.useState([]),[o,m]=a.useState([]),[p,u]=a.useState(null),[l,N]=a.useState([]),j=Ja(),{sendEmail:g,isSending:y}=Vn(),{groups:k}=zn(),S=a.useMemo(()=>new Set(l.map(Z=>Z.email.toLowerCase())),[l]);a.useEffect(()=>{s==="events"&&(i.length>0||d.length>0||x.length>0?j.mutate({years:i.length>0?i:void 0,seriesNames:d.length>0?d:void 0,eventNames:x.length>0?x:void 0,classNames:o.length>0?o:void 0},{onSuccess:Z=>{N(Z.map(R=>
207({email:R.email,name:R.name,memberNumber:R.memberNumber})))}}):N([]))},[i,d,x,o,s]);const f=Z=>{n(Z),N([]),t([]),r([]),c([]),m([]),u(null)},h=Z=>{N(R=>R.filter(E=>E.email!==Z))},M=Z=>{j.mutate({memberNumbers:[Z.memberNumber]},{onSuccess:R=>{for(const E of R)S.has(E.email.toLowerCase())||N($=>[...$,{email:E.email,name:E.name,memberNumber:E.memberNumber}])}})},T=Z=>{const R=Z.filter(b=>!S.has(b.email.toLowerCase())),E=new Set,$=R.filter(b=>{const I=b.email.toLowerCase();return E.has(I)?!1:(E.add(I),!0)});N(b=>[...b,...$])},C=async Z=>{u(Z);try{const{data:R,error:E}=await z.from("email_group_members").select("*").eq("group_id",Z).order("created_at",{ascending:!0});if(E)throw E;R&&N(R.map($=>({email:$.email,name:$.display_name||void 0})))}catch{K.error("Failed to load group members")}},L=(Z,R,E)=>{if(l.length===0){K.error("No recipients selected");return}g({subject:Z,message_body:E?void 0:R,template_id:E,recipients:l.map($=>({email:$.email,name:$.name})),source:"timing_email"},{onSuccess:$=>{K.success(`Emails sent! ${$.totalSent} successful, ${$.totalFailed} failed`),N([]),t([]),r([]),c([]),m([])},onError:$=>{K.error(`Failed to send emails: ${$.message}`)}})},Q=()=>{N([]),t([]),r([]),c([]),m([]),u(null)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsx(Ee,{children:"Select Recipients"}),e.jsx(ns,{children:"Choose recipients from past events, search for riders, select a group, or upload a list"})]}),e.jsx(xe,{children:e.jsxs(ot,{defaultValue:"events",className:"w-full",onValueChange:f,children:[e.jsxs(pt,{className:"grid w-full max-w-2xl grid-cols-4 mb-4",children:[e.jsxs(Qe,{value:"events",className:"gap-2",children:[e.jsx(Gs,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"By Events"})]}),e.jsxs(Qe,{value:"individual",className:"gap-2",children:[e.jsx(Ws,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Search"})]}),e.jsxs(Qe,{value:"group",className:"gap-2",children:[e.jsx($n,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"From Group"})]}),e.jsxs(Qe,{value:"upload",className:"gap-2",children:[e.jsx(Dt,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Upload"})]})]}),e.jsxs(Ae,{value:"events",className:"mt-0 space-y-4",children:[e.jsxs(ht,{children:[e.jsx(Ks,{className:"h-4 w-4"}),e.jsx(xt,{children:"Select years, series, and/or events to find riders who participated. Emails will be pulled from rider info based on member numbers in class entries."})]}),e.jsx(Jt,{selectedYears:i,selectedSeries:d,selectedEvents:x,selectedClasses:o,onYearsChange:t,onSeriesChange:r,onEventsChange:c,onClasse
207sChange:m})]}),e.jsxs(Ae,{value:"individual",className:"mt-0",children:[e.jsx(Qn,{onAddRecipient:M,existingPhones:new Set}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Search for riders to add their email addresses."})]}),e.jsx(Ae,{value:"group",className:"mt-0",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{children:"Select an Email Group"}),e.jsxs(Pe,{value:p||"",onValueChange:C,children:[e.jsx(Ie,{children:e.jsx(qe,{placeholder:"Choose a saved group..."})}),e.jsx(Be,{children:k==null?void 0:k.map(Z=>e.jsx(ae,{value:Z.id,children:Z.name},Z.id))})]})]}),(k==null?void 0:k.length)===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:'No email groups yet. Go to "Groups" tab to create one.'})]})}),e.jsx(Ae,{value:"upload",className:"mt-0",children:e.jsx(vl,{onEmailsImported:T})})]})})]}),j.isError&&e.jsxs(ht,{variant:"destructive",children:[e.jsx(Kt,{className:"h-4 w-4"}),e.jsx(xt,{children:"Failed to fetch recipients. Make sure MySQL is configured for your organization."})]}),j.isPending&&e.jsx(ht,{children:e.jsx(xt,{children:"Loading recipients..."})}),s!==null&&e.jsxs(re,{children:[e.jsx(ke,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Ee,{children:"Compose Email"}),e.jsx(ns,{children:"Write your email and send to selected recipients"})]}),l.length>0&&e.jsx(w,{variant:"outline",size:"sm",onClick:Q,children:"Clear All"})]})}),e.jsx(xe,{children:e.jsx(Fm,{recipients:l,onRemoveRecipient:h,onSend:L,isSending:y})})]})]})}function Wm(){const{groups:s,isLoading:n,createGroup:i,deleteGroup:t,isCreating:d}=zn(),[r,x]=a.useState(""),[c,o]=a.useState(null),m=()=>{if(!r.trim()){K.error("Please enter a group name");return}i(r,{onSuccess:()=>{x(""),K.success("Email group created")},onError:p=>{K.error(`Failed to create group: ${p.message}`)}})};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(re,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-3",children:"Create New Email Group"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(A,{placeholder:"Group name (e.g., 'VIP Riders', 'Morning Class')",value:r,onChange:p=>x(p.target.value),onKeyDown:p=>p.key==="Enter"&&m()}),e.jsxs(w,{onClick:m,disabled:d,children:[e.jsx(Es,{className:"h-4 w-4 mr-2"}),"Create"]})]})]}),e.jsx("div",{className:"space-y-2",children:n?e.jsx("p",{className:"text-muted-foreground",children:"Loading groups..."}):s.length===0?e.jsx("p",{className:"text-muted-foreground",children:"No email groups yet"}):s.map(p=>e.jsx(Zm,{group:p,isSelected:c===p.id,onSelect:o,onDelete:()=>{t(p.id,{onSuccess:()=>{K.success("Group deleted")},onError:u=>{K.error(`Failed to delete group: ${u.message}`)}})}},p.id))}),c&&e.jsx(Jm,{groupId:c})]})}function Zm({group:s,isSelected:n,onSelect:i,onDelete:t}){return e.jsx(re,{className:`p-4 cursor-pointer transition ${n?"border-primary bg-primary/5":"hover:border-primary/50"}`,onClick:()=>i(s.id),children:e.jsxs("div",{className:"flex justify-between items-start",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold",children:s.name}),s.notes&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:s.notes})]}),e.jsxs(et,{children:[e.jsx(Lt,{asChild:!0,onClick:d=>d.stopPropagation(),children:e.jsx(w,{variant:"ghost",size:"sm",children:e.jsx(ws,{className:"h-4 w-4 text-destructive"})})}),e.jsxs(st,{children:[e.jsx(tt,{children:"Delete Email Group?"}),e.jsx(at,{children:"This will delete the group and all its members. This action cannot be undone."}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(nt,{children:"Cancel"}),e.jsx(rt,{onClick:t,className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]})})}function Jm({groupId:s}){const{members:n,isLoading:i,addMember:t,removeMember:d,isAdding:r,addMultipleMembers:x,isAddingMultiple:c}=Pc(s),[o,m]=a.useState(""),[p,u]=a.useState(""),[l,N]=a.useState("manual"),[j,g]=a.useState([]),[y,k]=a.useState([]),[S,f]=a.useState([]),[h,M]=a.useState([]),T=Ja(),C=new Set(n.map($=>$.email.toLowerCase())),L=()=>
207{if(!o.trim()){K.error("Please enter an email address");return}t({email:o,display_name:p||void 0},{onSuccess:()=>{m(""),u(""),K.success("Member added to group")},onError:$=>{K.error(`Failed to add member: ${$.message}`)}})},Q=()=>{if(j.length===0&&y.length===0&&S.length===0){K.error("Please select at least one year, series, or event");return}T.mutate({years:j.length>0?j:void 0,seriesNames:y.length>0?y:void 0,eventNames:S.length>0?S:void 0},{onSuccess:$=>{const b=$.filter(H=>!C.has(H.email.toLowerCase())),I=new Set,V=b.filter(H=>{const Y=H.email.toLowerCase();return I.has(Y)?!1:(I.add(Y),!0)});M(V.map(H=>({email:H.email,name:H.name}))),b.length===0?K.info("All found emails are already in this group"):K.success(`Found ${V.length} new email(s)`)},onError:$=>{K.error(`Failed to fetch: ${$.message}`)}})},Z=()=>{h.length!==0&&x(h.map($=>({email:$.email,display_name:$.name})),{onSuccess:()=>{K.success(`Added ${h.length} members to group`),M([]),g([]),k([]),f([])},onError:$=>{K.error(`Failed to add members: ${$.message}`)}})},R=$=>{T.mutate({memberNumbers:[$.memberNumber]},{onSuccess:b=>{for(const I of b)C.has(I.email.toLowerCase())?K.info(`${I.email} is already in this group`):t({email:I.email,display_name:I.name},{onSuccess:()=>K.success(`Added ${I.email}`),onError:V=>K.error(`Failed: ${V.message}`)})}})},E=$=>{const b=$.filter(H=>!C.has(H.email.toLowerCase()));if(b.length===0){K.info("All emails are already in this group");return}const I=new Set,V=b.filter(H=>{const Y=H.email.toLowerCase();return I.has(Y)?!1:(I.add(Y),!0)});x(V.map(H=>({email:H.email,display_name:H.name})),{onSuccess:()=>{K.success(`Added ${V.length} members to group`)},onError:H=>{K.error(`Failed to add members: ${H.message}`)}})};return e.jsxs(re,{className:"p-4 border-primary/20",children:[e.jsxs("h4",{className:"font-semibold mb-3",children:["Group Members (",n.length,")"]}),e.jsxs(ot,{value:l,onValueChange:$=>N($),className:"mb-4",children:[e.jsxs(pt,{className:"grid w-full grid-cols-4",children:[e.jsx(Qe,{value:"manual",className:"text-xs",children:"Manual"}),e.jsx(Qe,{value:"events",className:"text-xs",children:"By Events"}),e.jsx(Qe,{value:"search",className:"text-xs",children:"Search"}),e.jsx(Qe,{value:"upload",className:"text-xs",children:"Upload"})]}),e.jsxs(Ae,{value:"manual",className:"mt-3 space-y-2",children:[e.jsx(A,{placeholder:"Email address",type:"email",value:o,onChange:$=>m($.target.value),onKeyDown:$=>$.key==="Enter"&&L()}),e.jsx(A,{placeholder:"Display name (optional)",value:p,onChange:$=>u($.target.value),onKeyDown:$=>$.key==="Enter"&&L()}),e.jsxs(w,{onClick:L,disabled:r,className:"w-full",children:[e.jsx(Es,{className:"h-4 w-4 mr-2"}),"Add Member"]})]}),e.jsxs(Ae,{value:"events",className:"mt-3 space-y-3",children:[e.jsx(Jt,{selectedYears:j,selectedSeries:y,selectedEvents:S,onYearsChange:g,onSeriesChange:k,onEventsChange:f}),e.jsx(w,{onClick:Q,disabled:T.isPending,className:"w-full",children:T.isPending?"Fetching...":"Fetch Recipients"}),h.length>0&&e.jsxs("div",{className:"p-3 bg-secondary/50 rounded space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium",children:["Found ",h.length," new email(s)"]}),e.jsxs("div",{className:"flex flex-wrap gap-1 max-h-24 overflow-y-auto",children:[h.slice(0,10).map(($,b)=>e.jsx(ie,{variant:"outline",className:"text-xs",children:$.name||$.email},b)),h.length>10&&e.jsxs(ie,{variant:"secondary",className:"text-xs",children:["+",h.length-10," more"]})]}),e.jsxs(w,{onClick:Z,disabled:c,size:"sm",className:"w-full",children:[e.jsx(Es,{className:"h-4 w-4 mr-2"}),"Add All to Group"]})]})]}),e.jsxs(Ae,{value:"search",className:"mt-3",children:[e.jsx(Qn,{onAddRecipient:R,existingPhones:new Set}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Search for riders to add their email to this group."})]}),e.jsx(Ae,{value:"upload",className:"mt-3",children:e.jsx(vl,{onEmailsImported:E})})]}),e.jsx("div",{className:"space-y-2 max-h-48 overflow-y-auto border-t pt-3",children:i?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading members..."}):n.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No members in this group"}):n.map($=>e.jsxs("div",{className:"flex justify-between items-center p-2 bg-secondary/50 rounded",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:$.email}),$.display_name&&e.jsx("p",{className:"text-xs text-muted-foreground",children:$.display_name})]}),e.jsx(w,{variant:"ghost",size:"sm",onClick:()=>{d($.id,{onSuccess:()=>K.success("Member removed"),onError:b=>K.error(`Failed to remove: ${b.message}`)})},children:e.jsx(ws,{className:"h-4 w-4 text-destructive"})})]},$.id))})]})}function Xm(){const s=Ms(),{currentOrganization:n}=Je();return ks({mutationFn:async()=>{var r,x;if(!(n!=null&&n.id))throw new Error("No organization selected");const i=new Date().toISOString(),[t,d]=await Promise.all([z.from("email_logs").update({dismissed_at:i}).eq("organization_id",n.id).eq("status","failed").is("dismissed_at",null).select("id"),z.from("sms_logs").update({dismissed_at:i}).eq("organization_id",n.id).eq("status","failed").is("dismissed_at",null).select("id")]);if(t.error)throw t.error;if(d.error)throw d.error;return{emailCount:((r=t.data)==null?void 0:r.length)??0,smsCount:((x=d.data)==null?void 0:x.length)??0}},onSuccess:({emailCount:i,smsCount:t})=>{const d=i+t;K.success(d===0?"No failed messages to dismiss":`Dismissed ${d} failed message${d===1?"":"s"} from notifications`),s.invalidateQueries({queryKey:["admin-notifications-failed-emails",n==null?void 0:n.id]}),s.invalidateQueries({queryKey:["sms-logs",n==null?void 0:n.id]}),s.invalidateQueries({queryKey:["email-logs",n==null?void 0:n.id]}),s.invalidateQueries({queryKey:["all-email-logs",n==null?void 0:n.id]})},onError:i=>
207{console.error("Dismiss failed logs error:",i),K.error(i instanceof Error?i.message:"Failed to dismiss notifications")}})}const wn={check_in_status:{label:"Check-In Status",className:"bg-blue-100 text-blue-800 border-blue-200"},timing_messaging:{label:"Timing Messaging",className:"bg-red-100 text-red-800 border-red-200"},timing_email:{label:"Timing Email",className:"bg-red-100 text-red-800 border-red-200"},timing_email_resend:{label:"Timing Email Resend",className:"bg-red-100 text-red-800 border-red-200"},incoming_reply:{label:"Reply (Incoming Msg)",className:"bg-purple-100 text-purple-800 border-purple-200"},incoming_sms:{label:"Incoming SMS",className:"bg-purple-100 text-purple-800 border-purple-200"},early_access_sms:{label:"Early Access SMS",className:"bg-amber-100 text-amber-800 border-amber-200"},early_access_email:{label:"Early Access Email",className:"bg-amber-100 text-amber-800 border-amber-200"},pos_coupon_sms:{label:"POS Coupon",className:"bg-emerald-100 text-emerald-800 border-emerald-200"},pos_coupon_followup_sms:{label:"POS Coupon Follow-up SMS",className:"bg-emerald-100 text-emerald-800 border-emerald-200"},pos_coupon_followup_email:{label:"POS Coupon Follow-up Email",className:"bg-emerald-100 text-emerald-800 border-emerald-200"},admin_resend_confirmation:{label:"Admin Resend",className:"bg-sky-100 text-sky-800 border-sky-200"},admin_lookup_resend:{label:"Lookup Resend",className:"bg-sky-100 text-sky-800 border-sky-200"},admin_edit_confirmation:{label:"Admin Edit",className:"bg-sky-100 text-sky-800 border-sky-200"},kiosk_confirmation:{label:"Kiosk Confirmation",className:"bg-indigo-100 text-indigo-800 border-indigo-200"},confirmation_builder_test:{label:"Builder Test",className:"bg-slate-100 text-slate-800 border-slate-200"},bulk_email:{label:"Bulk Email",className:"bg-red-100 text-red-800 border-red-200"},class_change:{label:"Class Change",className:"bg-orange-100 text-orange-800 border-orange-200"},refund_confirmation:{label:"Refund Confirmation",className:"bg-rose-100 text-rose-800 border-rose-200"},updated_confirmation:{label:"Updated Confirmation",className:"bg-sky-100 text-sky-800 border-sky-200"},registration_confirmation:{label:"Registration Confirmation",className:"bg-teal-100 text-teal-800 border-teal-200"},registration_confirmation_extra:{label:"Confirmation (Email List)",className:"bg-teal-50 text-teal-700 border-teal-200"},registration_coupon_sms:{label:"Registration Coupon SMS",className:"bg-emerald-100 text-emerald-800 border-emerald-200"},registration_coupon_email:{label:"Registration Coupon Email",className:"bg-emerald-100 text-emerald-800 border-emerald-200"},abandoned_followup:{label:"Abandoned Follow-up",className:"bg-amber-100 text-amber-800 border-amber-200"},pos_coupon_bulk_sms:{label:"POS Coupon Bulk SMS",className:"bg-emerald-100 text-emerald-800 border-emerald-200"},pos_coupon_bulk_email:{label:"POS Coupon Bulk Email",className:"bg-emerald-100 text-emerald-800 border-emerald-200"},legacy:{label:"Legacy (untagged)",className:"bg-gray-100 text-gray-700 border-gray-200"},unknown:{label:"Unknown",className:"bg-yellow-100 text-yellow-800 border-yellow-200"}};function bl(s){return s?wn[s]??{label:s,className:"bg-gray-100 text-gray-700 border-gray-200"}:wn.unknown}function eu(){return Object.entries(wn).map(([s,{label:n}])=>({value:s,label:n}))}function su(){const{logs:s,isLoading:n}=dl(),{logs:i,isLoading:t}=Ic(),{failedEmailCount:d}=Kr(),r=Xm(),{currentOrganization:x}=Je(),c=Ms(),[o,m]=a.useState(""),[p,u]=a.useState("all"),[l,N]=a.useState("all"),[j,g]=a.useState("all"),[y,k]=a.useState(null),S=n||t,f=ks({mutationFn:async()=>{if(!(x!=null&&x.id))throw new Error("No organization selected");const{data:R,error:E}=await z.functions.invoke("backfill-sms-log-names",{body:{organization_id:x.id}});if(E)throw E;if(R!=null&&R.error)throw new Error(R.error);return R},onSuccess:R=>{K.success(`Backfill complete: updated ${R.updated} of ${R.scanned} unmatched SMS log${R.scanned===1?"":"s"}`),c.invalidateQueries({queryKey:["sms-logs",x==null?void 0:x.id]})},onError:R=>{K.error(R instanceof Error?R.message:"Backfill failed")}}),h=a.useMemo(()=>{const R=[];for(const E of s)R.push({id:E.id,type:"sms",recipient:E.recipient_phone,recipientName:E.recipient_name,memberNumber:E.member_number??null,subject:null,body:E.message_body,status:E.status,errorMessage:E.error_message,sentAt:E.sent_at||E.created_at,eventName:E.event_name,source:E.source??null});for(const E of i)R.push({id:E.id,type:"email",recipient:E.recipient_email,recipientName:E.recipient_name,memberNumber:null,subject:E.subject,body:E.message_body,status:E.status,errorMessage:E.error_message,sentAt:E.sent_at||E.created_at,eventName:E.event_name,source:E.source??null});return R.sort((E,$)=>new Date($.sentAt).getTime()-new Date(E.sentAt).getTime())},[s,i]),M=a.useMemo(()=>h.filter(R=>{var E,$;if(p!=="all"&&R.type!==p||l!=="all"&&R.status!==l||j!=="all"&&(R.source||"unknown")!==j)return!1;if(o){const b=o.toLowerCase();return R.recipient.toLowerCase().includes(b)||((E=R.recipientName)==null?void 0:E.toLowerCase().includes(b))||(($=R.subject)==null?void 0:$.toLowerCase().includes(b))||R.body.toLowerCase().includes(b)}return!0}),[h,o,p,l,j]),T=a.useMemo(()=>{const R=new Set;for(const $ of h)R.add($.source||"unknown");return eu().filter($=>R.has($.value))}
207,[h]),C=R=>{const E=new Date(R);return{date:E.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),time:E.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}},L=(R,E=60)=>R.length>E?R.slice(0,E)+"…":R,Q=a.useMemo(()=>s.filter(R=>!R.recipient_name||R.recipient_name==="Unmatched").length,[s]),Z=R=>{if(R.recipientName&&R.recipientName!=="Unmatched")return e.jsx("div",{className:"text-sm font-medium",children:R.recipientName});if(R.memberNumber)return e.jsxs("div",{className:"text-sm font-medium",children:["Member #",R.memberNumber]});const E=R.recipientName==="Unmatched"?"Unmatched":"Unknown";return e.jsx("div",{className:"text-sm font-medium text-destructive/80",children:E})};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Communication Logs"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"All SMS and email messages sent from your organization"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[Q>0&&e.jsxs(w,{variant:"outline",size:"sm",onClick:()=>f.mutate(),disabled:f.isPending,className:"gap-2",title:"Look up missing rider names from the timing system's rider_alerts table",children:[f.isPending?e.jsx(oe,{className:"h-4 w-4 animate-spin"}):e.jsx(to,{className:"h-4 w-4"}),"Backfill ",Q," unmatched name",Q===1?"":"s"]}),d>0&&e.jsxs(w,{variant:"outline",size:"sm",onClick:()=>r.mutate(),disabled:r.isPending,className:"gap-2",children:[r.isPending?e.jsx(oe,{className:"h-4 w-4 animate-spin"}):e.jsx(id,{className:"h-4 w-4"}),"Clear ",d," failed notification",d===1?"":"s"]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(Ws,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(A,{placeholder:"Search recipient, subject, or message...",value:o,onChange:R=>m(R.target.value),className:"pl-10"})]}),e.jsxs(Pe,{value:p,onValueChange:u,children:[e.jsx(Ie,{className:"w-[130px]",children:e.jsx(qe,{placeholder:"Type"})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"all",children:"All Types"}),e.jsx(ae,{value:"sms",children:"SMS"}),e.jsx(ae,{value:"email",children:"Email"})]})]}),e.jsxs(Pe,{value:l,onValueChange:N,children:[e.jsx(Ie,{className:"w-[130px]",children:e.jsx(qe,{placeholder:"Status"})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"all",children:"All Status"}),e.jsx(ae,{value:"sent",children:"Sent"}),e.jsx(ae,{value:"failed",children:"Failed"}),e.jsx(ae,{value:"pending",children:"Pending"})]})]}),e.jsxs(Pe,{value:j,onValueChange:g,children:[e.jsx(Ie,{className:"w-[200px]",children:e.jsx(qe,{placeholder:"Sent From"})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"all",children:"All Sources"}),T.map(R=>e.jsx(ae,{value:R.value,children:R.label},R.value))]})]})]}),e.jsxs("div",{className:"flex gap-4 text-sm text-muted-foreground",children:[e.jsxs("span",{children:["Showing ",M.length," of ",h.length," logs"]}),e.jsx("span",{children:"•"}),e.jsxs("span",{children:[h.filter(R=>R.type==="sms").length," SMS"]}),e.jsx("span",{children:"•"}),e.jsxs("span",{children:[h.filter(R=>R.type==="email").length," Emails"]})]}),S?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(oe,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):M.length===0?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:h.length===0?e.jsxs("div",{className:"space-y-2",children:[e.jsx(jt,{className:"h-12 w-12 mx-auto opacity-30"}),e.jsx("p",{children:"No communication logs yet"})]}):e.jsx("p",{children:"No logs match your filters"})}):e.jsx(re,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b text-left",children:[e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground w-[70px]",children:"Type"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground",children:"Recipient"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground",children:"Message"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground",children:"Sent From"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground",children:"Status"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground",children:"Date"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground text-right",children:"Actions"})]})}),e.jsx("tbody",{children:M.map(R=>{const{date:E,time:$}=C(R.sentAt);return e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/50 transition-colors",children:[e.jsx("td",{className:"px-4 py-3",children:e.jsx(ie,{variant:"outline",className:"gap-1 text-xs",children:R.type==="sms"?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-3 w-3"})," SMS"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ks,{className:"h-3 w-3"})," Email"]})})}),e.jsxs("td",{className:"px-4 py-3",children:[Z(R),e.jsx("div",{className:"text-xs text-muted-foreground",children:R.recipient})]}),e.jsxs("td",{className:"px-4 py-3 max-w-xs",children:[e.jsx("button",{onClick:()=>k(R),className:"text-primary hover:underline text-left text-sm",children:R.subject?L(R.subject):L(R.body)}),R.eventName&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:R.eventName})]}),e.jsx("td",{className:"px-4 py-3",children:(()=>{const b=bl(R.source);return e.jsx(ie,{variant:"outline",className:`text-xs ${b.className}`,children:b.label})})()}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(ie,{variant:R.status==="sent"?"default":R.status==="pending"?"secondary":"destructive",className:R.status==="sent"?"bg-emerald-100 text-emerald-700 hover:bg-emerald-100":"",children:R.status.toUpperCase()})}),e.jsxs("td",{className:"px-4 py-3",children:[e.jsx("div",{className:"text-sm font-medium",children:E}),e.jsx("div",{className:"text-xs text-muted-foreground",children:$})]}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsx(w,{variant:"ghost",size:"icon",className:"h-8 w-8",title:"View details",onClick:()=>k(R),children:e.jsx(Zt,{className:"h-4 w-4"})})})]},`${R.type}-${R.id}`)})})]})})}),y&&e.jsx(tu,{log:y,open:!!y,onClose:()=>k(null)})]})}function tu({log:s,open:n,onClose:i}){const t=d=>
207new Date(d).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit",hour12:!0});return e.jsx(ts,{open:n,onOpenChange:d=>!d&&i(),children:e.jsxs(as,{className:"max-w-2xl max-h-[90vh] flex flex-col",children:[e.jsx(rs,{children:e.jsxs(is,{className:"flex items-center gap-2 text-xl",children:[s.type==="sms"?e.jsx(bt,{className:"h-5 w-5"}):e.jsx(Ks,{className:"h-5 w-5"}),s.type==="sms"?"SMS":"Email"," Details"]})}),e.jsx(qs,{className:"flex-1 pr-4",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground text-xs",children:"Recipient"}),e.jsx("p",{className:"font-medium",children:s.recipientName&&s.recipientName!=="Unmatched"?s.recipientName:s.memberNumber?`Member #${s.memberNumber}`:s.recipientName==="Unmatched"?"Unmatched":"Unknown"}),e.jsx("p",{className:"text-muted-foreground text-xs",children:s.recipient})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground text-xs",children:"Status"}),e.jsx(ie,{variant:s.status==="sent"?"default":"destructive",className:s.status==="sent"?"bg-emerald-100 text-emerald-700 hover:bg-emerald-100":"",children:s.status.toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground text-xs",children:"Sent At"}),e.jsx("p",{className:"font-medium",children:t(s.sentAt)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground text-xs",children:"Sent From"}),(()=>{const d=bl(s.source);return e.jsx(ie,{variant:"outline",className:`text-xs ${d.className}`,children:d.label})})()]}),s.eventName&&e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground text-xs",children:"Event"}),e.jsx("p",{className:"font-medium",children:s.eventName})]})]}),s.subject&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-2",children:"Subject"}),e.jsx("div",{className:"border rounded-md p-3 text-sm bg-muted/30",children:s.subject})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-2",children:"Message"}),e.jsx("div",{className:"border rounded-md p-3 text-sm bg-muted/30 whitespace-pre-wrap max-h-64 overflow-y-auto",children:s.body})]}),s.errorMessage&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-2 text-destructive",children:"Error"}),e.jsx("div",{className:"border border-destructive/30 rounded-md p-3 text-sm text-destructive",children:s.errorMessage})]})]})})]})})}function au(){const{currentOrganization:s}=Je(),{data:n,isLoading:i}=Ga(s==null?void 0:s.id),t=Gl(),d=Yl(),r=Kl(),[x,c]=a.useState(!1),[o,m]=a.useState(null),[p,u]=a.useState({offer_key:"",discount_type:"amount",discount_value:"",description:"",expires_at:"",is_active:!0,fine_print:""}),l=()=>{m(null),u({offer_key:"",discount_type:"amount",discount_value:"",description:"",expires_at:"",is_active:!0,fine_print:""}),c(!0)},N=y=>{m(y),u({offer_key:y.offer_key,discount_type:y.discount_type,discount_value:String(y.discount_value),description:y.description||"",expires_at:y.expires_at?new Date(y.expires_at).toISOString().slice(0,16):"",is_active:y.is_active,fine_print:y.fine_print||""}),c(!0)},j=()=>{const y={...p,discount_value:Number(p.discount_value)||0,expires_at:p.expires_at||null,organization_id:s==null?void 0:s.id};o?d.mutate({id:o.id,...y},{onSuccess:()=>c(!1)}):t.mutate(y,{onSuccess:()=>c(!1)})},g=y=>y.discount_type==="percent"?`${y.discount_value}%`:y.discount_type==="free_item"?"Free Item":`$${y.discount_value}`;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Offers"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Define discount types that can be assigned to coupons"})]}),e.jsxs(w,{onClick:l,className:"gap-2",children:[e.jsx(Es,{className:"h-4 w-4"}),"Create Offer"]})]}),i?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(oe,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):n!=null&&n.length?e.jsx(re,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b text-left",children:[e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground",children:"Name"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground",children:"Discount"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground",children:"Description"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground",children:"Expires"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground",children:"Status"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground text-right",children:"Actions"})]})}),e.jsx("tbody",{children:n.map(y=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/50",children:[e.jsx("td",{className:"px-4 py-3 font-medium text-sm",children:y.offer_key}),e.jsx("td",{className:"px-4 py-3 text-sm",children:g(y)}),e.jsx("td",{className:"px-4 py-3 text-sm text-muted-foreground",children:y.description||"—"}),e.jsx("td",{className:"px-4 py-3 text-sm",children:y.expires_at?new Date(y.expires_at).toLocaleDateString():"Never"}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(ie,{variant:y.is_active?"default":"secondary",children:y.is_active?"Active":"Inactive"})}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(w,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>N(y),children:e.jsx(Ft,{className:"h-4 w-4"})}),e.jsxs(et,{children:[e.jsx(Lt,{asChild:!0,children:e.jsx(w,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",children:e.jsx(ws,{className:"h-4 w-4"})})}),e.jsxs(st,{children:[e.jsx(tt,{children:"Delete Offer"}),e.jsxs(at,{children:['This will permanently delete "',y.offer_key,'". Existing coupons using this offer will remain but lose their offer reference.']}),e.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[e.jsx(nt,{children:"Cancel"}),e.jsx(rt,{onClick:()=>r.mutate(y.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})]})]})})]},y.id))})]})})}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Di,{className:"h-12 w-12 mx-auto opacity-30 mb-2"}),e.jsx("p",{children:"No offers yet. Create your first offer to get started."})]}),e.jsx(ts,{open:x,onOpenChange:c,children:e.jsxs(as,{children:[e.jsx(rs,{children:e.jsx(is,{children:o?"Edit Offer":"Create Offer"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(v,{children:"Offer Name / Key"}),e.jsx(A,{value:p.offer_key,onChange:y=>u(k=>
207({...k,offer_key:y.target.value})),placeholder:"e.g. SPRING_SALE"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(v,{children:"Discount Type"}),e.jsxs(Pe,{value:p.discount_type,onValueChange:y=>u(k=>({...k,discount_type:y})),children:[e.jsx(Ie,{children:e.jsx(qe,{})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"amount",children:"$ Amount"}),e.jsx(ae,{value:"percent",children:"% Percent"}),e.jsx(ae,{value:"free_item",children:"Free Item"})]})]})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Value"}),e.jsx(A,{type:"number",value:p.discount_value,onChange:y=>u(k=>({...k,discount_value:y.target.value})),placeholder:p.discount_type==="percent"?"10":"5.00",disabled:p.discount_type==="free_item"})]})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Description"}),e.jsx(A,{value:p.description,onChange:y=>u(k=>({...k,description:y.target.value})),placeholder:"Short description"})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Expires At (optional)"}),e.jsx(A,{type:"datetime-local",value:p.expires_at,onChange:y=>u(k=>({...k,expires_at:y.target.value}))})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Fine Print (optional)"}),e.jsx(A,{value:p.fine_print,onChange:y=>u(k=>({...k,fine_print:y.target.value})),placeholder:"NOT VALID W/ OTHER OFFERS..."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ds,{checked:p.is_active,onCheckedChange:y=>u(k=>({...k,is_active:y}))}),e.jsx(v,{children:"Active"})]}),e.jsxs(w,{onClick:j,disabled:!p.offer_key||t.isPending||d.isPending,className:"w-full",children:[(t.isPending||d.isPending)&&e.jsx(oe,{className:"h-4 w-4 animate-spin mr-2"}),o?"Update":"Create"]})]})]})})]})}function nu(){const s=Gt(),{currentOrganization:n}
207=Je(),i=n==null?void 0:n.id,[t,d]=a.useState(""),[r,x]=a.useState("all"),[c,o]=a.useState("all"),[m,p]=a.useState(null),[u,l]=a.useState(!1),[N,j]=a.useState(""),[g,y]=a.useState(!1),[k,S]=a.useState(new Set),[f,h]=a.useState(!1),M=Ms(),{data:T}=Ga(i),{data:C}=Ya(i),{data:L,isLoading:Q}=Hl(i,{offerId:r!=="all"?r:void 0,active:c==="all"?void 0:c==="active"}),Z=Ql(),R=qr(),E=Wl(),$=J=>{S(_e=>{const me=new Set(_e);return me.has(J)?me.delete(J):me.add(J),me})},b=()=>{k.size===H.length?S(new Set):S(new Set(H.map(J=>J.id)))},I=()=>{k.size!==0&&h(!0)},V=()=>{E.mutate({coupon_ids:Array.from(k),organization_id:i},{onSuccess:()=>{S(new Set),h(!1)}})},H=(L||[]).filter(J=>{if(!t)return!0;const _e=t.toLowerCase();return J.code.toLowerCase().includes(_e)||(J.rider_name||"").toLowerCase().includes(_e)||String(J.member_number||"").includes(_e)}),Y=(L||[]).filter(J=>!J.template_id).length,W=(n==null?void 0:n.slug)||"",B=`${ta()}/org/${W}/pos`,le=J=>{R.mutate({coupon_ids:[J],organization_id:i,pos_url:B})},Me=J=>J.discount_type==="percent"?`${J.discount_value}%`:J.discount_type==="free_item"?"Free Item":`$${J.discount_value}`,_=J=>!(J!=null&&J.template_id)||!C?null:C.find(_e=>_e.id===J.template_id)||null,X=J=>!(J!=null&&J.offer_id)||!T?null:T.find(_e=>_e.id===J.offer_id)||null,F=J=>{var _e;return(J==null?void 0:J.fine_print)||((_e=X(J))==null?void 0:_e.fine_print)||null},ne=async()=>{if(!(!N||!i)){y(!0);try{const{error:J}=await z.from("pos_coupons").update({template_id:N}).eq("organization_id",i).is("template_id",null);if(J)throw J;K.success(`Linked ${Y} coupons to template`),M.invalidateQueries({queryKey:["pos-coupons"]}),l(!1)}catch(J){K.error("Failed: "+J.message)}finally{y(!1)}}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Coupons"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Browse and manage individual coupon codes"})]}),Y>0&&e.jsxs(w,{variant:"outline",className:"gap-2",onClick:()=>l(!0),children:[e.jsx(An,{className:"h-4 w-4"}),"Link ",Y," to Template"]}),k.size>0&&e.jsxs(w,{variant:"destructive",size:"sm",className:"gap-2",onClick:I,disabled:E.isPending,children:[E.isPending?e.jsx(oe,{className:"h-4 w-4 animate-spin"}):e.jsx(ws,{className:"h-4 w-4"}),"Delete ",k.size," Selected"]})]}),e.jsxs("div",{className:"flex gap-3 flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(Ws,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(A,{placeholder:"Search by code, name, or member #...",value:t,onChange:J=>d(J.target.value),className:"pl-10"})]}),e.jsxs(Pe,{value:r,onValueChange:x,children:[e.jsx(Ie,{className:"w-[160px]",children:e.jsx(qe,{placeholder:"Offer"})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"all",children:"All Offers"}),T==null?void 0:T.map(J=>e.jsx(ae,{value:J.id,children:J.offer_key},J.id))]})]}),e.jsxs(Pe,{value:c,onValueChange:o,children:[e.jsx(Ie,{className:"w-[130px]",children:e.jsx(qe,{placeholder:"Status"})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"all",children:"All"}),e.jsx(ae,{value:"active",children:"Active"}),e.jsx(ae,{value:"inactive",children:"Inactive"})]})]})]}),Q?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(oe,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):H.length?e.jsx(re,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b text-left",children:[e.jsx("th",{className:"px-4 py-3 w-10",children:e.jsx(As,{checked:k.size===H.length&&H.length>0,onCheckedChange:b})}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground",children:"Code"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground",children:s.racer}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground",children:"Member #"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground",children:"Discount"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground",children:"Template"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground text-center",children:"Uses"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground",children:"Active"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground text-right",children:"Actions"})]})}),e.jsx("tbody",{children:H.map(J=>{const _e=_(J);return e.jsxs("tr",{className:`border-b last:border-0 hover:bg-muted/50 ${k.has(J.id)?"bg-muted/30":""}`,children:[e.jsx("td",{className:"px-4 py-3",children:e.jsx(As,{checked:k.has(J.id),onCheckedChange:()=>$(J.id)})}),e.jsx("td",{className:"px-4 py-3 font-mono text-sm font-medium",children:J.code}),e.jsx("td",{className:"px-4 py-3 text-sm",children:J.rider_name||"—"}),e.jsx("td",{className:"px-4 py-3 text-sm",children:J.member_number||"—"}),e.jsx("td",{className:"px-4 py-3 text-sm",children:Me(J)}),e.jsx("td",{className:"px-4 py-3 text-sm",children:_e?e.jsx(ie,{variant:"outline",className:"text-xs",children:_e.template_name}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"None"})}),e.jsxs("td",{className:"px-4 py-3 text-sm text-center",children:[J.uses,"/",J.max_uses]}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(Ds,{checked:J.active,onCheckedChange:me=>Z.mutate({id:J.id,active:me})})}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(w,{variant:"ghost",size:"icon",className:"h-8 w-8",title:"View QR",onClick:()=>p(J),children:e.jsx(Qr,{className:"h-4 w-4"})}),e.jsx(w,{variant:"ghost",size:"icon",className:"h-8 w-8",title:"Send SMS",onClick:()=>le(J.id),disabled:R.isPending,children:e.jsx(gt,{className:"h-4 w-4"})})]})})]},J.id)})})]})})}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Na,{className:"h-12 w-12 mx-auto opacity-30 mb-2"}
207),e.jsx("p",{children:"No coupons found"})]}),e.jsx(ts,{open:!!m,onOpenChange:()=>p(null),children:e.jsxs(as,{className:"max-w-sm",children:[e.jsx(rs,{children:e.jsxs(is,{children:["Coupon Preview – ",m==null?void 0:m.code]})}),m&&e.jsx("div",{className:"py-4",children:e.jsx(oa,{coupon:m,template:_(m),organizationId:i,posUrl:B,finePrint:F(m)})})]})}),e.jsx(ts,{open:u,onOpenChange:l,children:e.jsxs(as,{className:"max-w-sm",children:[e.jsx(rs,{children:e.jsx(is,{children:"Link Coupons to Template"})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Y," coupons have no template assigned. Select a template to apply to all of them."]}),e.jsxs(Pe,{value:N,onValueChange:j,children:[e.jsx(Ie,{children:e.jsx(qe,{placeholder:"Select template..."})}),e.jsx(Be,{children:C==null?void 0:C.map(J=>e.jsx(ae,{value:J.id,children:J.template_name},J.id))})]}),e.jsxs(w,{onClick:ne,disabled:!N||g,className:"w-full",children:[g&&e.jsx(oe,{className:"h-4 w-4 animate-spin mr-2"}),"Link ",Y," Coupons"]})]})}),e.jsx(et,{open:f,onOpenChange:h,children:e.jsxs(st,{children:[e.jsxs(Et,{children:[e.jsxs(tt,{children:["Delete ",k.size," coupon(s)?"]}),e.jsx(at,{children:"This will permanently delete the selected coupons and their redemption history from both the cloud database and your MySQL server. This action cannot be undone."})]}),e.jsxs(Mt,{children:[e.jsx(nt,{children:"Cancel"}),e.jsxs(rt,{onClick:V,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:[E.isPending?e.jsx(oe,{className:"h-4 w-4 animate-spin mr-2"}):null,"Delete"]})]})]})})]})}function er({onSelectRider:s,deliveryMethod:n}){const[i,t]=a.useState(""),{data:d,isLoading:r}=Xa(i,i.length>=2),x=c=>{const o=c.phoneNumber?ru(c.phoneNumber):"";s({name:`${c.firstName} ${c.lastName}`.trim(),phone:o,email:c.email||"",memberNumber:c.memberNumber}),t("")};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Ws,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(A,{placeholder:"Search riders by name or #...",value:i,onChange:c=>t(c.target.value),className:"pl-10"})]}),i.length>=2&&e.jsx(qs,{className:"h-[160px] rounded-md border",children:r?e.jsx("div",{className:"flex items-center justify-center h-full p-4",children:e.jsx(oe,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):d&&d.length>0?e.jsx("div",{className:"p-1 space-y-0.5",children:d.map(c=>{const o=n==="email"?c.email:c.phoneNumber;return e.jsxs("button",{type:"button",onClick:()=>x(c),className:"w-full flex items-center gap-3 p-2 rounded-md hover:bg-muted/50 text-left",children:[e.jsx("div",{className:"h-7 w-7 rounded-full bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(Xs,{className:"h-3.5 w-3.5 text-primary"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[c.firstName," ",c.lastName]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:["#",c.memberNumber," • ",o||"No contact"]})]})]},c.memberNumber)})}):e.jsx("div",{className:"flex items-center justify-center h-full p-4 text-muted-foreground text-sm",children:"No riders found"})}),i.length>0&&i.length<2&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Type at least 2 characters"})]})}function ru(s){const n=s.replace(/\D/g,"");return n.length===10?`1${n}`:n.length===11&&n.startsWith("1")?n:s}function iu(){var Ce,ft,It,Ct;const{currentOrganization:s}=Je(),{data:n}=Ga(s==null?void 0:s.id),{data:i}=Ya(s==null?void 0:s.id),t=Zl();qr();const{isTimingEnabled:d}=Wt(),[r,x]=a.useState("database"),[c,o]=a.useState("existing"),[m,p]=a.useState(""),[u,l]=a.useState("amount"),[N,j]=a.useState(""),[g,y]=a.useState(""),[k,S]=a.useState("none"),[f,h]=a.useState(""),[M,T]=a.useState(""),[C,L]=a.useState("1"),[Q,Z]=a.useState(""),[R,E]=a.useState(""),[$,b]=a.useState(""),[I,V]=a.useState(""),[H,Y]=a.useState("Hey {name}! Here's a special coupon just for you: {code} for {discount} off. View & redeem: {url}"),[W,te]=a.useState(""),[B,le]=a.useState(!1),[Me,_]=a.useState(""),[X,F]=a.use
207State("sms"),[ne,J]=a.useState("sms"),[_e,me]=a.useState(""),[$e,ee]=a.useState(""),[pe,je]=a.useState(""),[we,U]=a.useState([]),[se,ue]=a.useState(!0),[ve,he]=a.useState({}),[ze,He]=a.useState(null),Ve=a.useRef(null),[Ue,de]=a.useState(null),[Le,ye]=a.useState(!1),[Ze,Ls]=a.useState(Va),P=gl(),[Te,Fe]=a.useState([]),[Ye,Xe]=a.useState([]),[bs,Ts]=a.useState([]),[Ps,Rs]=a.useState([]),[D,O]=a.useState([]),Ne=en(),Se=()=>{if(!Te.length&&!Ye.length&&!bs.length&&!Ps.length){O([]);return}Ne.mutate({year:Te[0],seriesName:Ye[0],eventName:bs[0],className:Ps[0]},{onSuccess:ce=>O(ce)})},us=ce=>{var Bs;const vs=(Bs=ce.target.files)==null?void 0:Bs[0];if(!vs)return;if(!vs.name.match(/\.(csv|txt)$/i)){K.error("Please upload a CSV or TXT file");return}He(vs.name);const ls=new FileReader;ls.onload=q=>{var Re;const ge=(Re=q.target)==null?void 0:Re.result,fe=Zn(ge);if(fe.length===0){K.error("No data found in file");return}U(fe),ue(Jn(fe)),he({})},ls.readAsText(vs)},ps=a.useMemo(()=>{const ce=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return[{key:"name",label:"Name",suggest:ls=>/name|rider|contact|first|last/i.test(ls)},{key:"phone",label:"Phone",required:ne==="sms",suggest:ls=>/phone|mobile|cell|tel/i.test(ls),validate:ls=>{const Bs=ls.replace(/\D/g,"");return Bs.length===10||Bs.length===11&&Bs.startsWith("1")}},{key:"email",label:"Email",required:ne==="email",suggest:ls=>/email|e-mail/i.test(ls),validate:ls=>ce.test(ls)},{key:"memberNumber",label:"Member #",suggest:ls=>/member|^#$|bp\s*#?|rider\s*#/i.test(ls)&&!/phone/i.test(ls),validate:ls=>/^\d+$/.test(ls.replace(/\D/g,""))}]},[ne]),xs=a.useMemo(()=>{if(we.length===0)return[];const ce=se?we.slice(1):we,vs=ve.name,ls=ve.phone,Bs=ve.email,q=ve.memberNumber,ge=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,fe=[],Re=new Set;for(const Ke of ce){const Oe={};if(vs!==void 0&&vs>=0&&(Oe.name=(Ke[vs]||"").trim()||void 0),ls!==void 0&&ls>=0){const _s=(Ke[ls]||"").trim().replace(/\D/g,"");_s.length===10?Oe.phone=`1${_s}`:_s.length===11&&_s.startsWith("1")&&(Oe.phone=_s)}if(Bs!==void 0&&Bs>=0){const os=(Ke[Bs]||"").trim();ge.test(os)&&(Oe.email=os)}if(q!==void 0&&q>=0){const os=(Ke[q]||"").trim().replace(/\D/g,"");os&&(Oe.member_number=parseInt(os,10)||void 0)}if(ne==="sms"&&!Oe.phone||ne==="email"&&!Oe.email)continue;const hs=Oe.email||Oe.phone||"";!hs||Re.has(hs)||(Re.add(hs),fe.push(Oe))}return fe},[we,se,ve,ne]),G=()=>{if(r==="single"){const ce={name:_e||void 0};return pe&&(ce.member_number=parseInt(pe)||void 0),ne==="email"?ce.email=$e:ce.phone=$e,[ce]}return r==="csv"?xs:D.map(ce=>({member_number:ce.memberNumber,name:ce.name||`Rider ${ce.memberNumber}`,phone:ce.phone}))},De=()=>r==="single"?$e?1:0:r==="csv"?xs.length:D.length,ds=()=>c==="existing"?{offer_id:m}:{custom_offer:{discount_type:u,discount_value:Number(N)||0,description:g||R||void 0}},Ge=()=>{const ce=H.trim();return!(ne==="sms"&&!ce||ne==="email"&&!W.trim()||ce&&(!ce.includes("{name}")||!ce.includes("{code}")||!ce.includes("{url}"))||De()===0||c==="existing"&&!m||c==="custom"&&u!=="custom"&&!N)},ss=n==null?void 0:n.find(ce=>ce.id===m),es=$||c==="existing"&&(ss==null?void 0:ss.fine_print)||"",cs=()=>{p(""),j(""),y(""),h(""),T(""),E(""),b(""),V(""),te(""),me(""),ee(""),je(""),U([]),he({}),He(null),O([]),Ve.current&&(Ve.current.value="")},ys=()=>{if(!Ge()){K.error("Please fill in all required fields");return}const ce=G(),vs=ce.length,ls=ds(),Bs={organization_id:s==null?void 0:s.id,app_base_url:ta(),...ls,template_id:k!=="none"?k:null,riders:ce.map(q=>({member_number:q.member_number||null,name:q.name||null,phone:q.phone||null,email:q.email||null})),title:f,subtitle:M,description:R||null,fine_print:es||null,notes:I||null,delivery_message:H||null,email_subject:W||null,followup_text:B&&Me||null,followup_method:B?X:null,max_uses:Number(C)||1,expires_at:Q||null,delivery_method:ne,send_immediately:!0};if(Ze.enabled){const q=Xn(Ze.localValue);if(!q){K.error("Pick a valid future date/time to schedule the send.");return}if(new Date(q).getTime()<=Date.now()+30*1e3){K.error("Scheduled time must be at least a minute in the future.");return}if(!(s!=null&&s.id)){K.error("No organization selected.");return}P.mutate({organization_id:s.id,kind:"pos_coupon_sms",label:f?`Coupon: ${f}`:"Coupon send",scheduled_for:q,recipient_count:vs,payload:Bs},{onSuccess:()=>Ls(Va)});return}t.mutate(Bs,{onSuccess:q=>{de({created:(q==null?void 0:q.created)??0,sent:(q==null?void 0:q.sent)??0,failed:(q==null?void 0:q.failed)??0,recipientCount:vs,deliveryMethod:ne,bulk_id:q==null?void 0:q.bulk_id,timestamp:new Date().toISOString()}),ye(!0)}})};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Create & Send Coupons"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Generate and deliver coupons to riders via SMS or Email"})]}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[1fr,400px]",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs(re,{children:[e.jsx(ke,{children:e.jsx(Ee,{className:"text-base",children:"1. Delivery Method"})}),e.jsx(xe,{children:e.jsxs(ut,{value:ne,onValueChange:ce=>J(ce),className:"flex gap-6",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(js,{value:"sms",id:"delivery-sms"}),e.jsxs(v,{htmlFor:"delivery-sms",className:"flex items-center gap-1 cursor-pointer",children:[e.jsx(bt,{className:"h-4 w-4"})," SMS Text"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(js,{value:"email",id:"delivery-email"}),e.jsxs(v,{htmlFor:"delivery-email",className:"flex items-center gap-1 cursor-pointer",children:[e.jsx(Ks,{className:"h-4 w-4"})," Email"]})]})]})})]}),e.jsxs(re,{children:[e.jsx(ke,{children:e.jsx(Ee,{className:"text-base",children:"2. Select Recipients"})}),e.jsxs(xe,{className:"space-y-4",children:[e.jsxs(ut,{value:r,onValueChange:ce=>x(ce),className:"flex flex-wrap gap-4",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(js,{value:"single",id:"mode-single"}),e.jsxs(v,{htmlFor:"mode-single",className:"flex items-center gap-1 cursor-pointer",children:[e.jsx(Xs,{className:"h-4 w-4"})," Single Person"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(js,{value:"database",id:"mode-database"}),e.jsxs(v,{htmlFor:"mode-database",className:"flex items-center gap-1 cursor-pointer",children:[e.jsx(Tt,{className:"h-4 w-4"})," From Database"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(js,{value:"csv",id:"mode-csv"}),e.jsxs(v,{htmlFor:"mode-csv",className:"flex items-center gap-1 cursor-pointer",children:[e.jsx(Dt,{className:"h-4 w-4"})," Upload List"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(js,{value:"extras",id:"mode-extras"}),e.jsxs(v,{htmlFor:"mode-extras",className:"flex items-center gap-1 cursor-pointer",children:[e.jsx(Vr,{className:"h-4 w-4"})," By Form Item"]})]})]}),r==="extras"&&e.jsx(ti,{mode:ne,onLoaded:ce=>O(ce)}),r==="single"&&e.jsxs("div",{className:"space-y-3",children:[d&&e.jsxs("div",{children:[e.jsx(v,{className:"text-xs text-muted-foreground mb-1 block",children:"Search rider database"}),e.jsx(er,{deliveryMethod:ne,onSelectRider:ce=>{me(ce.name),ee(ne==="email"?ce.email:ce.phone),je(String(ce.memberNumber))}})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Name"}),e.jsx(A,{value:_e,onChange:ce=>me(ce.target.value),placeholder:"John Smith"})]}),e.jsxs("div",{children:[e.jsx(v,{children:ne==="email"?"Email Address":"Phone Number"}),e.jsx(A,{value:$e,onChange:ce=>ee(ce.target.value),placeholder:ne==="email"?"[email protected]":"555-123-4567",type:ne==="email"?"email":"tel"})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Member/Rider Number (optional)"}
207),e.jsx(A,{value:pe,onChange:ce=>je(ce.target.value),placeholder:"e.g. 123"})]})]}),r==="database"&&e.jsxs(e.Fragment,{children:[e.jsx(Jt,{selectedYears:Te,selectedSeries:Ye,selectedEvents:bs,selectedClasses:Ps,onYearsChange:Fe,onSeriesChange:Xe,onEventsChange:Ts,onClassesChange:Rs}),e.jsxs(w,{variant:"outline",className:"w-full gap-2",onClick:Se,disabled:Ne.isPending||!Te.length&&!Ye.length&&!bs.length&&!Ps.length,children:[Ne.isPending?e.jsx(oe,{className:"h-4 w-4 animate-spin"}):e.jsx(Ws,{className:"h-4 w-4"}),"Fetch Riders"]})]}),r==="csv"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Upload a CSV with any column layout — you'll map columns to Name, ",ne==="email"?"Email":"Phone",", and Member # after upload."]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(A,{ref:Ve,type:"file",accept:".csv,.txt",onChange:us,className:"cursor-pointer max-w-xs"}),ze&&e.jsx("span",{className:"text-xs text-muted-foreground truncate max-w-[200px]",children:ze}),we.length>0&&e.jsx(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>{U([]),he({}),He(null),Ve.current&&(Ve.current.value="")},children:"Clear"})]}),we.length>0&&e.jsx(Wn,{rows:we,fields:ps,hasHeader:se,onHasHeaderChange:ue,mapping:ve,onMappingChange:he}),xs.length>0&&e.jsxs("div",{className:"rounded border p-2 max-h-40 overflow-y-auto text-xs space-y-1",children:[xs.slice(0,20).map((ce,vs)=>e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:ce.name||"(no name)"}),e.jsx("span",{className:"text-muted-foreground",children:ce.email||ce.phone})]},vs)),xs.length>20&&e.jsxs("p",{className:"text-muted-foreground",children:["...and ",xs.length-20," more"]})]})]}),De()>0&&e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(Gs,{className:"h-4 w-4"}),De()," recipient(s) selected"]})]})]}),e.jsxs(re,{children:[e.jsx(ke,{children:e.jsx(Ee,{className:"text-base",children:"3. Configure Offer"})}),e.jsxs(xe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(v,{children:"Template (select first to see a live preview)"}),e.jsxs(Pe,{value:k,onValueChange:S,children:[e.jsx(Ie,{children:e.jsx(qe,{placeholder:"No template"})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"none",children:"No template"}),i==null?void 0:i.map(ce=>e.jsx(ae,{value:ce.id,children:ce.template_name},ce.id))]})]})]}),e.jsxs(ut,{value:c,onValueChange:ce=>o(ce),className:"flex gap-6",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(js,{value:"existing",id:"offer-existing"}),e.jsx(v,{htmlFor:"offer-existing",className:"cursor-pointer",children:"Select Existing Offer"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(js,{value:"custom",id:"offer-custom"}),e.jsx(v,{htmlFor:"offer-custom",className:"cursor-pointer",children:"Custom Offer"})]})]}),c==="existing"&&e.jsxs("div",{children:[e.jsx(v,{children:"Offer *"}),e.jsxs(Pe,{value:m,onValueChange:p,children:[e.jsx(Ie,{children:e.jsx(qe,{placeholder:"Select an offer"})}),e.jsx(Be,{children:n==null?void 0:n.filter(ce=>ce.is_active).map(ce=>e.jsxs(ae,{value:ce.id,children:[ce.offer_key," (",ce.discount_type==="percent"?`${ce.discount_value}%`:ce.discount_type==="free_item"?"Free":`$${ce.discount_value}`,")"]},ce.id))})]})]}),c==="custom"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(v,{children:"Discount Type"}),e.jsxs(Pe,{value:u,onValueChange:l,children:[e.jsx(Ie,{children:e.jsx(qe,{})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"amount",children:"$ Amount Off"}),e.jsx(ae,{value:"percent",children:"% Percent Off"}),e.jsx(ae,{value:"free_item",children:"Free Item"}),e.jsx(ae,{value:"custom",children:"Custom Text (no set discount)"})]})]})]}),u!=="custom"&&u!=="free_item"&&e.jsxs("div",{children:[e.jsx(v,{children:"Discount Value"}),e.jsx(A,{type:"number",value:N,onChange:ce=>j(ce.target.value),placeholder:u==="percent"?"10":"5.00"})]}),u==="custom"&&e.jsxs("div",{children:[e.jsx(v,{children:"Custom Offer Text"}),e.jsx(Ns,{value:g,onChange:ce=>y(ce.target.value),placeholder:"e.g. Buy 1 Get 1 Free on all accessories",rows:2})]})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Coupon Title"}),e.jsx(A,{value:f,onChange:ce=>h(ce.target.value),placeholder:"e.g. Spring Sale Coupon"})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Subtitle"}),e.jsx(A,{value:M,onChange:ce=>
207T(ce.target.value),placeholder:"e.g. Thank you for racing!"})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Description"}),e.jsx(A,{value:R,onChange:ce=>E(ce.target.value),placeholder:"Short description of the coupon"})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Fine Print"}),e.jsx(A,{value:$,onChange:ce=>b(ce.target.value),placeholder:"e.g. NOT VALID W/ OTHER OFFERS..."}),!$&&c==="existing"&&(ss==null?void 0:ss.fine_print)&&e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["Using selected offer fine print: ",ss.fine_print]})]}),ne==="sms"?e.jsxs("div",{children:[e.jsx(v,{children:"SMS Message *"}),e.jsxs(Pn,{children:[e.jsx(In,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex items-center gap-1 text-xs text-primary hover:text-primary/80 mb-1.5 font-medium transition-colors",children:[e.jsx(Dn,{className:"h-3.5 w-3.5"}),"How do placeholders work? (click to learn)"]})}),e.jsx(qn,{children:e.jsxs("div",{className:"bg-muted/50 border border-border rounded-md p-3 mb-2 text-xs space-y-1.5",children:[e.jsx("p",{className:"text-muted-foreground",children:"Use these tags in your message. Each recipient gets a personalized version with the tags replaced automatically."}),e.jsxs("ul",{className:"text-muted-foreground space-y-0.5 list-none pl-0",children:[e.jsxs("li",{children:[e.jsx("span",{className:"font-semibold text-primary",children:"{name}"}),` — Rider's name (e.g. "John")`]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-semibold text-primary",children:"{code}"}),' — Unique coupon code (e.g. "SAVE20")']}),e.jsxs("li",{children:[e.jsx("span",{className:"font-semibold text-primary",children:"{url}"})," — Link to view/redeem coupon"]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-semibold text-muted-foreground",children:"{discount}"}),' — Discount amount (e.g. "20% off")']})]}),e.jsx("p",{className:"text-muted-foreground",children:"Click the tag buttons below the message box to insert them at your cursor position."})]})})]}),e.jsx(Ns,{id:"pos-sms-message",value:H,onChange:ce=>Y(ce.target.value),placeholder:"e.g. Hey {name}, thanks for racing with us! Here's a coupon just for you: {discount}. View & redeem: {url}",rows:3}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1 mt-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground mr-1",children:"Insert:"}),["{name}","{code}","{url}","{discount}"].map(ce=>e.jsxs("button",{type:"button",className:`text-xs px-1.5 py-0.5 rounded border cursor-pointer hover:bg-accent ${["{name}","{code}","{url}"].includes(ce)?"border-primary text-primary":"border-border text-muted-foreground"}`,onClick:()=>{const vs=document.getElementById("pos-sms-message");if(vs){const ls=vs.selectionStart??H.length,Bs=vs.selectionEnd??ls,q=H.slice(0,ls)+ce+H.slice(Bs);Y(q),setTimeout(()=>{vs.focus(),vs.setSelectionRange(ls+ce.length,ls+ce.length)},0)}else Y(ls=>ls+ce)},children:[ce,["{name}","{code}","{url}"].includes(ce)?" *":""]},ce))]}),H&&(!H.includes("{name}")||!H.includes("{code}")||!H.includes("{url}"))&&e.jsxs("p",{className:"text-xs text-destructive mt-1",children:["⚠️ Message must include ","{name}",", ","{code}",", and ","{url}"," placeholders."]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(v,{children:"Email Subject *"}),e.jsx(A,{value:W,onChange:ce=>te(ce.target.value),placeholder:"e.g. Your Coupon from {org} — {discount}"})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Email Body (optional)"}),e.jsx(Ns,{id:"pos-email-body",value:H,onChange:ce=>Y(ce.target.value),placeholder:"e.g. Thanks for racing with us! We wanted to send you a special coupon as a thank you.",rows:3}),e.jsxs("div",{className:"flex flex-wrap gap-1 mt-1.5",children:[["{name}","{code}","{discount}","{url}"].map(ce=>e.jsx("button",{type:"button",className:"text-xs px-1.5 py-0.5 rounded border border-border text-muted-foreground cursor-pointer hover:bg-accent",onClick:()=>{const vs=document.getElementById("pos-email-body");if(vs){const ls=vs.selectionStart??H.length,Bs=vs.selectionEnd??ls,q=H.slice(0,ls)+ce+H.slice(Bs);Y(q),setTimeout(()=>{vs.focus(),vs.setSelectionRange(ls+ce.length,ls+ce.length)},0)}else Y(ls=>ls+ce)},children:ce},ce)),e.jsx("span",{className:"text-xs text-muted-foreground self-center ml-1",children:"Click to insert"})]})]})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Notes (internal, not shown on coupon)"}),e.jsx(A,{value:I,onChange:ce=>V(ce.target.value),placeholder:"Internal notes"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(As,{id:"enable-followup",checked:B,onCheckedChange:ce=>le(ce===!0)}),e.jsx(v,{htmlFor:"enable-followup",className:"cursor-pointer",children:"Send follow-up message after redemption"})]}),B&&e.jsxs("div",{className:"space-y-3 pl-6 border-l-2 border-muted",children:[e.jsxs("div",{children:[e.jsx(v,{children:"Follow-up Method"}),e.jsxs(ut,{value:X,onValueChange:ce=>F(ce),className:"flex gap-6 mt-1",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(js,{value:"sms",id:"followup-sms"}),e.jsxs(v,{htmlFor:"followup-sms",className:"flex items-center gap-1 cursor-pointer",children:[e.jsx(bt,{className:"h-4 w-4"})," SMS"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(js,{value:"email",id:"followup-email"}),e.jsxs(v,{htmlFor:"followup-email",className:"flex items-center gap-1 cursor-pointer",children:[e.jsx(Ks,{className:"h-4 w-4"})," Email"]})]})]})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Follow-up Message"}),e.jsx(Ns,{value:Me,onChange:ce=>_(ce.target.value),placeholder:"e.g. Thanks for using your coupon! Come back soon for more deals.",rows:2}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["This will be sent via ",X==="sms"?"SMS":"email"," after the customer redeems their coupon."]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(v,{children:"Max Uses"}),e.jsx(A,{type:"number",value:C,onChange:ce=>L(ce.target.value),min:"1"})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Expires"}),e.jsx(A,{type:"datetime-local",value:Q,onChange:ce=>Z(ce.target.value)})]})]}),e.jsx("div",{className:"mb-3",children:e.jsx(pl,{value:Ze,onCh
207ange:Ls,disabled:t.isPending||P.isPending})}),e.jsxs(w,{onClick:ys,disabled:t.isPending||P.isPending||!Ge(),className:"w-full gap-2",children:[t.isPending||P.isPending?e.jsx(oe,{className:"h-4 w-4 animate-spin"}):e.jsx(za,{className:"h-4 w-4"}),Ze.enabled?`Schedule ${De()} Coupon(s)`:`Generate & Send ${De()} Coupon(s) via ${ne==="sms"?"SMS":"Email"}`]})]})]})]}),e.jsx("div",{className:"lg:sticky lg:top-4 lg:self-start",children:e.jsx(re,{children:e.jsxs(xe,{children:[e.jsx(oa,{coupon:{code:"SAMPLE123",title:f||"COUPON",subtitle:M||null,rider_name:r==="single"?_e||null:((Ce=D[0])==null?void 0:Ce.name)||"RIDER NAME",member_number:r==="single"?parseInt(pe)||null:((ft=D[0])==null?void 0:ft.memberNumber)||123,discount_type:c==="existing"?((It=n==null?void 0:n.find(ce=>ce.id===m))==null?void 0:It.discount_type)||"amount":u==="custom"?"free_item":u,discount_value:c==="existing"?((Ct=n==null?void 0:n.find(ce=>ce.id===m))==null?void 0:Ct.discount_value)||0:Number(N)||0,expires_at:Q||null},template:k!=="none"?i==null?void 0:i.find(ce=>ce.id===k):null,organizationId:s==null?void 0:s.id,posUrl:`${ta()}/org/${(s==null?void 0:s.slug)||""}/pos`,finePrint:es||null}),e.jsx("p",{className:"text-xs text-muted-foreground text-center mt-3",children:"This is a preview — actual coupon codes will be unique per recipient."})]})})})]}),e.jsx(ts,{open:Le,onOpenChange:ye,children:e.jsxs(as,{className:"sm:max-w-md",children:[e.jsxs(rs,{children:[e.jsx(is,{className:"flex items-center gap-2",children:Ue&&Ue.failed===0?e.jsxs(e.Fragment,{children:[e.jsx(Oa,{className:"h-5 w-5 text-primary"})," Coupons Sent"]}):e.jsxs(e.Fragment,{children:[e.jsx(Is,{className:"h-5 w-5 text-amber-500"})," Send Complete (with issues)"]})}),e.jsx(Fs,{children:Ue?`Delivered via ${Ue.deliveryMethod==="sms"?"SMS Text":"Email"} at ${new Date(Ue.timestamp).toLocaleTimeString()}`:""})]}),Ue&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-center",children:[e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsx("div",{className:"text-2xl font-bold",children:Ue.created}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Created"})]}),e.jsxs("div",{className:"rounded-lg border p-3 border-primary/40 bg-primary/5",children:[e.jsx("div",{className:"text-2xl font-bold text-primary",children:Ue.sent}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Delivered"})]}),e.jsxs("div",{className:`rounded-lg border p-3 ${Ue.failed>0?"border-destructive/40 bg-destructive/5":""}`,children:[e.jsx("div",{className:`text-2xl font-bold ${Ue.failed>0?"text-destructive":""}`,children:Ue.failed}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Failed"})]})]}),Ue.failed>0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ue.failed," recipient(s) failed to receive their coupon. Check the Coupons tab to review and resend."]}),Ue.sent>0&&Ue.failed===0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["All ",Ue.sent," recipient(s) received their coupon successfully. You can view them in the Coupons tab."]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Want to send the same offer to another list? Choose ",e.jsx("strong",{children:"Duplicate"})," to keep every field filled in — just swap the recipients and send again."]})]}),e.jsxs(Ys,{className:"flex-col sm:flex-row gap-2",children:[e.jsxs(w,{variant:"outline",className:"gap-2 w-full sm:w-auto",onClick:()=>{cs(),ye(!1)},children:[e.jsx(ca,{className:"h-4 w-4"})," Start Fresh"]}),e.jsxs(w,{variant:"secondary",className:"gap-2 w-full sm:w-auto",onClick:()=>ye(!1),children:[e.jsx(Nt,{className:"h-4 w-4"})," Duplicate (keep fields)"]}),e.jsx(w,{className:"w-full sm:w-auto",onClick:()=>ye(!1),children:"Done"})]})]})})]})}const lu=["Bebas Neue","Inter","Roboto","Oswald","Montserrat","Raleway","Poppins","Anton","Barlow Condensed","Teko","Arial","Helvetica","Impact"],cu=[{value:"400",label:"Regular (400)"},{value:"500",label:"Medium (500)"},{value:"600",label:"Semi-Bold (600)"},{value:"700",label:"Bold (700)"},{value:"800",label:"Extra-Bold (800)"},{value:"900",label:"Black (900)"}];function ou(){const{currentOrganization:s}=Je(),n=s==null?void 0:s.id,{data:i,isLoading:t}
207=Ya(n),d=Jl(),r=Xl(),x=ec(),[c,o]=a.useState(!1),[m,p]=a.useState(null),[u,l]=a.useState(!1),N=a.useRef(null),j={template_name:"",border_color:"#FF6300",background_color:"#F5F5F5",title_color:"#1A1A1A",accent_color:"#FF6300",font_family:"Bebas Neue",font_weight:"700",logo_url:"",notes:""},[g,y]=a.useState(j),[k,S]=a.useState("COUPON"),[f,h]=a.useState("YOUR NEXT PURCHASE"),[M,T]=a.useState("RIDER NAME"),[C,L]=a.useState("100"),[Q,Z]=a.useState("amount"),[R,E]=a.useState("25"),[$,b]=a.useState("NOT VALID W/ OTHER OFFERS / RESTRICTIONS MAY APPLY"),I=()=>{p(null),y(j),S("COUPON"),h("YOUR NEXT PURCHASE"),T("RIDER NAME"),L("100"),Z("amount"),E("25"),b("NOT VALID W/ OTHER OFFERS / RESTRICTIONS MAY APPLY"),o(!0)},V=B=>{p(B),y({template_name:B.template_name,border_color:B.border_color,background_color:B.background_color,title_color:B.title_color,accent_color:B.accent_color,font_family:B.font_family,font_weight:B.font_weight,logo_url:B.logo_url||"",notes:B.notes||""}),o(!0)},H=()=>{const B={...g,organization_id:n};m?r.mutate({id:m.id,...B},{onSuccess:()=>o(!1)}):d.mutate(B,{onSuccess:()=>o(!1)})},Y=async B=>{var Me;const le=(Me=B.target.files)==null?void 0:Me[0];if(!(!le||!n)){l(!0);try{const _=le.name.split(".").pop(),X=`${n}/coupon-logos/${Date.now()}.${_}`,{error:F}=await z.storage.from("org-assets").upload(X,le,{upsert:!0});if(F)throw F;const{data:{publicUrl:ne}}=z.storage.from("org-assets").getPublicUrl(X);y(J=>({...J,logo_url:ne})),K.success("Logo uploaded")}catch(_){K.error("Upload failed: "+_.message)}finally{l(!1),N.current&&(N.current.value="")}}},W={code:"SAMPLE123",title:k||"COUPON",subtitle:f||null,rider_name:M||null,member_number:parseInt(C)||null,discount_type:Q,discount_value:Number(R)||0,expires_at:new Date(Date.now()+90*864e5).toISOString()},te={border_color:g.border_color,background_color:g.background_color,title_color:g.title_color,accent_color:g.accent_color,font_family:g.font_family,font_weight:g.font_weight,logo_url:g.logo_url||null};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Templates"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Design branded coupon poster templates"})]}),e.jsxs(w,{onClick:I,className:"gap-2",children:[e.jsx(Es,{className:"h-4 w-4"}),"Create Template"]})]}),t?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(oe,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):i!=null&&i.length?e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:i.map(B=>e.jsx(re,{className:"overflow-hidden",children:e.jsxs(xe,{className:"p-4 space-y-3",children:[e.jsx(oa,{coupon:{code:"SAMPLE",title:B.template_name,subtitle:"SAMPLE DISCOUNT",rider_name:"RIDER NAME",member_number:100,discount_type:"amount",discount_value:25,expires_at:new Date(Date.now()+90*864e5).toISOString()},template:B,organizationId:n,posUrl:"#",compact:!0,finePrint:"NOT VALID W/ OTHER OFFERS"}),e.jsxs("div",{className:"flex items-center justify-between pt-1",children:[e.jsx("span",{className:"text-sm font-medium truncate",children:B.template_name}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(w,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>V(B),children:e.jsx(Ft,{className:"h-4 w-4"})}),e.jsxs(et,{children:[e.jsx(Lt,{asChild:!0,children:e.jsx(w,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",children:e.jsx(ws,{className:"h-4 w-4"})})}),e.jsxs(st,{children:[e.jsx(tt,{children:"Delete Template"}),e.jsxs(at,{children:['Delete "',B.template_name,'"?']}),e.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[e.jsx(nt,{children:"Cancel"}),e.jsx(rt,{onClick:()=>x.mutate(B.id),className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})]})]})]})]})},B.id))}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Fi,{className:"h-12 w-12 mx-auto opacity-30 mb-2"}),e.jsx("p",{children:"No templates yet"})]}),e.jsx(ts,{open:c,onOpenChange:o,children:e.jsxs(as,{className:"max-w-4xl max-h-[90vh]",children:[e.jsx(rs,{children:e.jsx(is,{children:m?"Edit Template":"Create Template"})}),e.jsx("div",{className:"overflow-y-auto max-h-[calc(90vh-80px)] pr-1",children:e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(v,{children:"Template Name *"}),e.jsx(A,{value:g.template_name,onChange:B=>y(le=>({...le,template_name:B.target.value})),placeholder:"e.g. Beyond Pro Orange"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{className:"text-sm font-semibold",children:"Colors"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(v,{className:"text-xs",children:"Border"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(A,{type:"color",value:g.border_color,onChange:B=>y(le=>({...le,border_color:B.target.value})),className:"w-10 h-9 p-1 cursor-pointer"}),e.jsx(A,{value:g.border_color,onChange:B=>y(le=>({...le,border_color:B.target.value})),className:"text-xs"})]})]}),e.jsxs("div",{children:[e.jsx(v,{className:"text-xs",children:"Backgroun
207d"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(A,{type:"color",value:g.background_color,onChange:B=>y(le=>({...le,background_color:B.target.value})),className:"w-10 h-9 p-1 cursor-pointer"}),e.jsx(A,{value:g.background_color,onChange:B=>y(le=>({...le,background_color:B.target.value})),className:"text-xs"})]})]}),e.jsxs("div",{children:[e.jsx(v,{className:"text-xs",children:"Title Text"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(A,{type:"color",value:g.title_color,onChange:B=>y(le=>({...le,title_color:B.target.value})),className:"w-10 h-9 p-1 cursor-pointer"}),e.jsx(A,{value:g.title_color,onChange:B=>y(le=>({...le,title_color:B.target.value})),className:"text-xs"})]})]}),e.jsxs("div",{children:[e.jsx(v,{className:"text-xs",children:"Accent"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(A,{type:"color",value:g.accent_color,onChange:B=>y(le=>({...le,accent_color:B.target.value})),className:"w-10 h-9 p-1 cursor-pointer"}),e.jsx(A,{value:g.accent_color,onChange:B=>y(le=>({...le,accent_color:B.target.value})),className:"text-xs"})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{className:"text-sm font-semibold",children:"Typography"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(v,{className:"text-xs",children:"Font Family"}),e.jsxs(Pe,{value:g.font_family,onValueChange:B=>y(le=>({...le,font_family:B})),children:[e.jsx(Ie,{className:"text-xs",children:e.jsx(qe,{})}),e.jsx(Be,{children:lu.map(B=>e.jsx(ae,{value:B,style:{fontFamily:B},children:B},B))})]})]}),e.jsxs("div",{children:[e.jsx(v,{className:"text-xs",children:"Font Weight"}),e.jsxs(Pe,{value:g.font_weight,onValueChange:B=>y(le=>({...le,font_weight:B})),children:[e.jsx(Ie,{className:"text-xs",children:e.jsx(qe,{})}),e.jsx(Be,{children:cu.map(B=>e.jsx(ae,{value:B.value,children:B.label},B.value))})]})]})]})]}),e.jsxs("div",{children:[e.jsx(v,{className:"text-xs",children:"Logo"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(A,{value:g.logo_url,onChange:B=>y(le=>({...le,logo_url:B.target.value})),placeholder:"URL or upload →",className:"text-xs flex-1"}),e.jsx("input",{type:"file",ref:N,accept:"image/*",className:"hidden",onChange:Y}),e.jsx(w,{variant:"outline",size:"icon",className:"h-9 w-9 shrink-0",onClick:()=>{var B;return(B=N.current)==null?void 0:B.click()},disabled:u,children:u?e.jsx(oe,{className:"h-4 w-4 animate-spin"}):e.jsx(Dt,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{children:[e.jsx(v,{className:"text-xs",children:"Notes (internal)"}),e.jsx(A,{value:g.notes,onChange:B=>y(le=>({...le,notes:B.target.value})),className:"text-xs"})]}),e.jsxs("div",{className:"space-y-2 border-t pt-3",children:[e.jsx(v,{className:"text-sm font-semibold",children:"Preview Content"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Edit these to see how your text looks on the poster. These are not saved with the template."}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(v,{className:"text-xs",children:"Title"}),e.jsx(A,{value:k,onChange:B=>S(B.target.value),className:"text-xs"})]}),e.jsxs("div",{children:[e.jsx(v,{className:"text-xs",children:"Subtitle"}),e.jsx(A,{value:f,onChange:B=>h(B.target.value),className:"text-xs"})]}),e.jsxs("div",{children:[e.jsx(v,{className:"text-xs",children:"Rider Name"}),e.jsx(A,{value:M,onChange:B=>T(B.target.value),className:"text-xs"})]}),e.jsxs("div",{children:[e.jsx(v,{className:"text-xs",children:"Member #"}),e.jsx(A,{value:C,onChange:B=>L(B.target.value),className:"text-xs"})]}),e.jsxs("div",{children:[e.jsx(v,{className:"text-xs",children:"Discount Type"}),e.jsxs(Pe,{value:Q,onValueChange:Z,children:[e.jsx(Ie,{className:"text-xs",children:e.jsx(qe,{})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"amount",children:"$ Amount"}),e.jsx(ae,{value:"percent",children:"% Percent"}),e.jsx(ae,{value:"free_item",children:"Free Item"})]})]})]}),e.jsxs("div",{children:[e.jsx(v,{className:"text-xs",children:"Discount Value"}),e.jsx(A,{type:"number",value:R,onChange:B=>E(B.target.value),className:"text-xs"})]})]}),e.jsxs("div",{children:[e.jsx(v,{className:"text-xs",children:"Fine Print"}),e.jsx(A,{value:$,onChange:B=>b(B.target.value),className:"text-xs"})]})]}),e.jsxs(w,{onClick:H,disabled:!g.template_name||d.isPending||r.isPending,className:"w-full",children:[(d.isPending||r.isPending)&&e.jsx(oe,{className:"h-4 w-4 animate-spin mr-2"}),m?"Update Template":"Create Template"]})]}),e.jsxs("div",{className:"sticky top-0",children:[e.jsx(v,{className:"text-sm font-semibold mb-2 block",children:"Live Preview"}),e.jsx(oa,{coupon:W,template:te,organizationId:n,posUrl:"#",finePrint:$||null})]})]})})]})})]})}function du(){const{currentOrganization:s}=Je(),{data:n,isLoading:i}
207=sc(s==null?void 0:s.id),[t,d]=a.useState(""),r=a.useMemo(()=>{if(!n)return[];if(!t)return n;const c=t.toLowerCase();return n.filter(o=>{var m,p,u;return((m=o.code)==null?void 0:m.toLowerCase().includes(c))||((p=o.redeemed_by)==null?void 0:p.toLowerCase().includes(c))||((u=o.redeemed_location)==null?void 0:u.toLowerCase().includes(c))||String(o.member_number||"").includes(c)})},[n,t]),x=c=>{const o=new Date(c);return`${o.toLocaleDateString("en-US",{month:"short",day:"numeric"})} ${o.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}`};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Redemptions"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Audit log of all redeemed coupons"})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Ws,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(A,{placeholder:"Search by code, staff, location...",value:t,onChange:c=>d(c.target.value),className:"pl-10"})]}),i?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(oe,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):r.length?e.jsx(re,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b text-left",children:[e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground",children:"Code"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground",children:"Member #"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground",children:"Offer"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground",children:"Redeemed By"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground",children:"Location"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground",children:"Note"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground",children:"When"})]})}),e.jsx("tbody",{children:r.map(c=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/50",children:[e.jsx("td",{className:"px-4 py-3 font-mono text-sm",children:c.code}),e.jsx("td",{className:"px-4 py-3 text-sm",children:c.member_number||"—"}),e.jsx("td",{className:"px-4 py-3 text-sm",children:c.offer_key||"—"}),e.jsx("td",{className:"px-4 py-3 text-sm",children:c.redeemed_by||"—"}),e.jsx("td",{className:"px-4 py-3 text-sm",children:c.redeemed_location||"—"}),e.jsx("td",{className:"px-4 py-3 text-sm text-muted-foreground",children:c.redeemed_note||"—"}),e.jsx("td",{className:"px-4 py-3 text-sm",children:x(c.redeemed_at)})]},c.id))})]})})}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Pa,{className:"h-12 w-12 mx-auto opacity-30 mb-2"}),e.jsx("p",{children:"No redemptions yet"})]})]})}function mu(){const{currentOrganization:s}=Je();Ms();
207const[n,i]=a.useState(null),[t,d]=a.useState(""),[r,x]=a.useState(""),[c,o]=a.useState("percent"),[m,p]=a.useState(""),[u,l]=a.useState(""),[N,j]=a.useState(""),[g,y]=a.useState(!1),[k,S]=a.useState("sms"),[f,h]=a.useState("Hey {name}! Use code {code} for {discount} off registration. Sign up here: {url}"),[M,T]=a.useState("Your Registration Discount Code"),[C,L]=a.useState("single"),[Q,Z]=a.useState(""),[R,E]=a.useState(""),[$,b]=a.useState(""),[I,V]=a.useState([]),H=a.useRef(null),[Y,W]=a.useState([]),[te,B]=a.useState([]),[le,Me]=a.useState([]),[_,X]=a.useState([]),[F,ne]=a.useState([]),J=en(),[_e,me]=a.useState(!1),[$e,ee]=a.useState(null),[pe,je]=a.useState(!1),{isTimingEnabled:we}=Wt(),{data:U=[]}=ms({queryKey:["org-events",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:P,error:Te}=await z.from("events").select("id, name, slug, event_date, organization_id, registration_start_date, archived_at").eq("organization_id",s.id).eq("is_published",!0).order("event_date",{ascending:!0});if(Te)throw Te;return P||[]},enabled:!!(s!=null&&s.id)}),{data:se}=ms({queryKey:["org-slug",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:P,error:Te}=await z.from("organizations").select("slug").eq("id",s.id).single();if(Te)throw Te;return P},enabled:!!(s!=null&&s.id)}),{data:ue=[],refetch:ve}=ms({queryKey:["org-reg-coupons",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:P}=await z.from("events").select("id").eq("organization_id",s.id);if(!(P!=null&&P.length))return[];const Te=P.map(Xe=>Xe.id),{data:Fe,error:Ye}=await z.from("coupons").select("*, events!inner(name)").in("event_id",Te).order("created_at",{ascending:!1}).limit(50);if(Ye)throw Ye;return Fe||[]},enabled:!!(s!=null&&s.id)}),he=U.find(P=>P.id===t),ze=()=>{if(!Y.length&&!te.length&&!le.length&&!_.length){ne([]);return}J.mutate({year:Y[0],seriesName:te[0],eventName:le[0],className:_[0]},{onSuccess:P=>ne(P)})},He=P=>{var Ye;const Te=(Ye=P.target.files)==null?void 0:Ye[0];if(!Te)return;const Fe=new FileReader;Fe.onload=Xe=>{var D,O,Ne,Se;const Ts=((D=Xe.target)==null?void 0:D.result).split(`
208`).map(us=>us.trim()).filter(Boolean),Ps=(O=Ts[0])!=null&&O.toLowerCase().includes("name")||(Ne=Ts[0])!=null&&Ne.toLowerCase().includes("email")||(Se=Ts[0])!=null&&Se.toLowerCase().includes("phone")?1:0,Rs=[];for(let us=Ps;us<Ts.length;us++){const ps=Ts[us].split(",").map(xs=>xs.trim().replace(/^["']|["']$/g,""));if(ps.length>=2){const xs={name:ps[0]},G=ps[1];G.includes("@")?xs.email=G:xs.phone=G,ps[2]&&(xs.member_number=parseInt(ps[2])||void 0),Rs.push(xs)}else if(ps.length===1){const xs=ps[0];xs.includes("@")?Rs.push({email:xs}):Rs.push({phone:xs})}}V(Rs),K.success(`Loaded ${Rs.length} recipient(s) from CSV`)},Fe.readAsText(Te)},Ve=()=>{if(C==="single"){const P={name:Q||void 0};return k==="email"?P.email=R:(P.phone=R,g&&$&&(P.email=$)),[P]}return C==="csv"?I:F.map(P=>({member_number:P.memberNumber,name:P.name||`Rider ${P.memberNumber}`,phone:P.phone,email:P.email||void 0}))},Ue=()=>C==="single"?R?1:0:C==="csv"?I.length:F.length,de=()=>{if(!t||!r.trim()||c!=="free"&&(!m||Number(m)<=0)||Ue()===0||k==="sms"&&!f.trim()||k==="email"&&!M.trim()||!f.trim())return!1;const P=f.trim();return!(!P.includes("{name}")||!P.includes("{code}")||!P.includes("{url}")||g&&C==="single"&&k==="sms"&&!$.trim())},Le=()=>{const P="ABCDEFGHJKLMNPQRSTUVWXYZ23456789";let Te="";for(let Fe=0;Fe<8;Fe++)Te+=P[Math.floor(Math.random()*P.length)];x(Te)},ye=async()=>{if(!de()){K.error("Please fill in all required fields");return}me(!0);try{const P=Ve(),Te=ta(),Fe=(he==null?void 0:he.slug)||t,Ye=se==null?void 0:se.slug,{data:Xe,error:bs}=await z.functions.invoke("send-registration-coupon",{body:{organization_id:s==null?void 0:s.id,event_id:t,event_slug:Fe,org_slug:Ye,base_url:Te,coupon:{code:r.toUpperCase().trim(),discount_type:c,discount_value:c==="free"?100:Number(m),max_uses:u?Number(u):null,expires_at:N||null},recipients:P,delivery_method:k,message_template:f,email_subject:M,grant_early_access:g}});if(bs)throw bs;const Ts=(Xe==null?void 0:Xe.sent)||0,Ps=(Xe==null?void 0:Xe.failed)||0,Rs=(Xe==null?void 0:Xe.early_access_created)||0;let D=`Coupon sent to ${Ts} recipient(s)`;Rs>0&&(D+=`, ${Rs} early access code(s) created`),Ps>0&&(D+=`, ${Ps} failed`),K.success(D),ee({channel:k==="sms"?"sms":"email",sent:Ts,failed:Ps,extra:Rs>0?{label:"Early Access",value:Rs}:void 0,timestamp:new Date().toISOString(),detail:`Code ${r.toUpperCase().trim()}`}),je(!0),x(""),p(""),Z(""),E(""),b(""),y(!1),V([]),ne([]),ve()}catch(P){K.error("Failed to send: "+(P.message||"Unknown error"))}finally{me(!1)}},Ze=c==="percent"?`${m||"0"}%`:`$${m||"0"}`,Ls=["{name}","{code}","{url}","{discount}",...g?["{pin}","{email}"]:[]];return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(Na,{className:"h-5 w-5"}),"Send Registration Coupons"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Create a registration discount code and send it to riders via SMS or Email. The link auto-applies the coupon on the registration page."})]}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-2",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs(re,{children:[e.jsx(ke,{children:e.jsx(Ee,{className:"text-base",children:"1. Select Event"})}),e.jsx(xe,{children:e.jsxs(Pe,{value:t,onValueChange:d,children:[e.jsx(Ie,{children:e.jsx(qe,{placeholder:"Choose an event"})}),e.jsx(Be,{children:[...U].sort((P,Te)=>+!!P.archived_at-+!!Te.archived_at).map((P,Te,Fe)=>e.jsxs("div",{className:"contents",children:[P.archived_at&&(Te===0||!Fe[Te-1].archived_at)&&e.jsx("div",{className:"px-2 py-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Archived"}),e.jsxs(ae,{value:P.id,children:[P.name," (",Vt(P.event_date).toLocaleDateString(),")"]})]},P.id))})]})})]}),e.jsxs(re,{children:[e.jsx(ke,{children:e.jsx(Ee,{className:"text-base",children:"2. Coupon Details"})}),e.jsxs(xe,{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(v,{children:"Coupon Code *"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(A,{value:r,onChange:P=>x(P.target.value.toUpperCase()),placeholder:"e.g. SAVE20",className:"uppercase"}),e.jsx(w,{variant:"outline",size:"sm",onClick:Le,type:"button",children:"Auto"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(v,{children:"Discount Type"}),e.jsxs(Pe,{value:c,onValueChange:P=>
208o(P),children:[e.jsx(Ie,{children:e.jsx(qe,{})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"percent",children:"% Percent Off"}),e.jsx(ae,{value:"amount",children:"$ Amount Off"}),e.jsx(ae,{value:"free",children:"🎁 Free (100% off)"})]})]})]}),c!=="free"?e.jsxs("div",{children:[e.jsx(v,{children:"Discount Value *"}),e.jsx(A,{type:"number",value:m,onChange:P=>p(P.target.value),placeholder:c==="percent"?"e.g. 20":"e.g. 25.00",min:"0"})]}):e.jsx("div",{className:"flex items-end",children:e.jsx("p",{className:"text-sm text-muted-foreground pb-2",children:"Full amount covered"})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(v,{children:"Max Uses (blank = unlimited)"}),e.jsx(A,{type:"number",value:u,onChange:P=>l(P.target.value),placeholder:"Unlimited",min:"1"})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Expires"}),e.jsx(A,{type:"date",value:N,onChange:P=>j(P.target.value)})]})]}),e.jsxs("div",{className:"flex items-start space-x-3 pt-2 border-t border-border",children:[e.jsx(As,{id:"grant-early-access",checked:g,onCheckedChange:P=>{const Te=P===!0;y(Te);const Fe=`
209
210You also have EARLY registration access! Use email: {email} and PIN: {pin} to unlock registration before it opens to the public.`;Te&&!f.includes("{pin}")?h(Ye=>Ye+Fe):Te||h(Ye=>Ye.replace(Fe,""))}}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(v,{htmlFor:"grant-early-access",className:"flex items-center gap-1.5 cursor-pointer font-medium",children:[e.jsx(mr,{className:"h-4 w-4"}),"Also grant early registration access"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Recipients will receive a unique PIN to unlock registration before the public opening date. Requires an email address for each recipient."})]})]})]})]}),e.jsxs(re,{children:[e.jsx(ke,{children:e.jsx(Ee,{className:"text-base",children:"3. Delivery"})}),e.jsxs(xe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(v,{className:"mb-2 block",children:"Delivery Method"}),e.jsxs(ut,{value:k,onValueChange:P=>S(P),className:"flex gap-6",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(js,{value:"sms",id:"reg-del-sms"}),e.jsxs(v,{htmlFor:"reg-del-sms",className:"flex items-center gap-1 cursor-pointer",children:[e.jsx(bt,{className:"h-4 w-4"})," SMS Text"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(js,{value:"email",id:"reg-del-email"}),e.jsxs(v,{htmlFor:"reg-del-email",className:"flex items-center gap-1 cursor-pointer",children:[e.jsx(Ks,{className:"h-4 w-4"})," Email"]})]})]})]}),k==="email"&&e.jsxs("div",{children:[e.jsx(v,{children:"Email Subject *"}),e.jsx(A,{value:M,onChange:P=>T(P.target.value),placeholder:"Your Registration Discount Code"})]}),e.jsxs("div",{children:[e.jsx(v,{children:k==="sms"?"Message *":"Email Body *"}),e.jsxs(Pn,{children:[e.jsx(In,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex items-center gap-1 text-xs text-primary hover:text-primary/80 mb-1.5 font-medium transition-colors",children:[e.jsx(Dn,{className:"h-3.5 w-3.5"}),"How do placeholders work? (click to learn)"]})}
210),e.jsx(qn,{children:e.jsxs("div",{className:"bg-muted/50 border border-border rounded-md p-3 mb-2 text-xs space-y-1.5",children:[e.jsx("p",{className:"text-muted-foreground",children:"Use these tags in your message. Each recipient gets a personalized version with the tags replaced automatically."}),e.jsxs("ul",{className:"text-muted-foreground space-y-0.5 list-none pl-0",children:[e.jsxs("li",{children:[e.jsx("span",{className:"font-semibold text-primary",children:"{name}"}),` — Rider's name (e.g. "John")`]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-semibold text-primary",children:"{code}"}),' — Unique coupon code (e.g. "SAVE20")']}),e.jsxs("li",{children:[e.jsx("span",{className:"font-semibold text-primary",children:"{url}"})," — Link to registration with coupon pre-applied"]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-semibold text-muted-foreground",children:"{discount}"}),' — Discount amount (e.g. "20% off")']}),g&&e.jsxs(e.Fragment,{children:[e.jsxs("li",{children:[e.jsx("span",{className:"font-semibold text-primary",children:"{pin}"})," — Early access PIN code"]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-semibold text-primary",children:"{email}"})," — Email used for early access login"]})]})]}),e.jsx("p",{className:"text-muted-foreground",children:"Click the tag buttons below the message box to insert them at your cursor position."})]})})]}),e.jsx(Ns,{id:"reg-coupon-message",value:f,onChange:P=>h(P.target.value),rows:4,placeholder:"Hey {name}! Use code {code} for {discount} off..."}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1 mt-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground mr-1",children:"Insert:"}),Ls.map(P=>{const Te=["{name}","{code}","{url}"].includes(P),Fe=["{pin}","{email}"].includes(P);return e.jsxs("button",{type:"button",className:`text-xs px-1.5 py-0.5 rounded border cursor-pointer hover:bg-accent ${Te?"border-primary text-primary":Fe?"border-accent-foreground text-accent-foreground":"border-border text-muted-foreground"}`,onClick:()=>{const Ye=document.getElementById("reg-coupon-message");if(Ye){const Xe=Ye.selectionStart??f.length,bs=Ye.selectionEnd??Xe,Ts=f.slice(0,Xe)+P+f.slice(bs);h(Ts),setTimeout(()=>{Ye.focus(),Ye.setSelectionRange(Xe+P.length,Xe+P.length)},0)}else h(Xe=>Xe+P)},children:[P,Te?" *":""]},P)})]}),f&&(!f.includes("{name}")||!f.includes("{code}")||!f.includes("{url}"))&&e.jsxs("p",{className:"text-xs text-destructive mt-1",children:["⚠️ Message must include ","{name}",", ","{code}",", and ","{url}"," placeholders."]})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(re,{children:[e.jsx(ke,{children:e.jsx(Ee,{className:"text-base",children:"4. Select Recipients"})}),e.jsxs(xe,{className:"space-y-4",children:[e.jsxs(ut,{value:C,onValueChange:P=>L(P),className:"flex flex-wrap gap-4",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(js,{value:"single",id:"reg-mode-single"}),e.jsxs(v,{htmlFor:"reg-mode-single",className:"flex items-center gap-1 cursor-pointer",children:[e.jsx(Xs,{className:"h-4 w-4"})," Single Person"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(js,{value:"database",id:"reg-mode-database"}),e.jsxs(v,{htmlFor:"reg-mode-database",className:"flex items-center gap-1 cursor-pointer",children:[e.jsx(Tt,{className:"h-4 w-4"})," From Database"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(js,{value:"csv",id:"reg-mode-csv"}),e.jsxs(v,{htmlFor:"reg-mode-csv",className:"flex items-center gap-1 cursor-pointer",children:[e.jsx(Dt,{className:"h-4 w-4"})," Upload List"]})]})]}),C==="single"&&e.jsxs("div",{className:"space-y-3",children:[we&&e.jsxs("div",{children:[e.jsx(v,{className:"text-xs text-muted-foreground mb-1 block",children:"Search rider database"}),e.jsx(er,{deliveryMethod:k,onSelectRider:P=>{Z(P.name),E(k==="email"?P.email:P.phone)}})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Name"}),e.jsx(A,{value:Q,onChange:P=>Z(P.target.value),placeholder:"John Smith"})]}),e.jsxs("div",{children:[e.jsx(v,{children:k==="email"?"Email Address":"Phone Number"}),e.jsx(A,{value:R,onChange:P=>E(P.target.value),placeholder:k==="email"?"[email protected]":"555-123-4567",type:k==="email"?"email":"tel"})]}),k==="sms"&&g&&e.jsxs("div",{children:[e.jsx(v,{children:"Email (for early access) *"}),e.jsx(A,{value:$,onChange:P=>b(P.target.value),placeholder:"[email protected]",type:"email"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Required for early access PIN lookup"})]})]}),C==="database"&&e.jsxs(e.Fragment,{children:[e.jsx(Jt,{selectedYears:Y,selectedSeries:te,selectedEvents:le,selectedClasses:_,onYearsChange:W,onSeriesChange:B,onEventsChange:Me,onClasse
210sChange:X}),e.jsxs(w,{variant:"outline",className:"w-full gap-2",onClick:ze,disabled:J.isPending||!Y.length&&!te.length&&!le.length&&!_.length,children:[J.isPending?e.jsx(oe,{className:"h-4 w-4 animate-spin"}):e.jsx(Ws,{className:"h-4 w-4"}),"Fetch Riders"]})]}),C==="csv"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Upload a CSV: Name, Phone/Email (and optionally Member Number)."}),e.jsx(A,{ref:H,type:"file",accept:".csv,.txt",onChange:He,className:"cursor-pointer"}),I.length>0&&e.jsxs("div",{className:"rounded border p-2 max-h-40 overflow-y-auto text-xs space-y-1",children:[I.slice(0,20).map((P,Te)=>e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:P.name||"(no name)"}),e.jsx("span",{className:"text-muted-foreground",children:P.email||P.phone})]},Te)),I.length>20&&e.jsxs("p",{className:"text-muted-foreground",children:["...and ",I.length-20," more"]})]})]}),Ue()>0&&e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(Gs,{className:"h-4 w-4"}),Ue()," recipient(s) selected"]})]})]}),he&&r&&e.jsxs(re,{children:[e.jsx(ke,{children:e.jsx(Ee,{className:"text-base",children:"Preview"})}),e.jsxs(xe,{className:"space-y-2 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Event:"}),e.jsx("span",{className:"font-medium",children:he.name})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Code:"}),e.jsx("span",{className:"font-mono font-bold",children:r.toUpperCase()})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Discount:"}),e.jsx("span",{className:"font-medium",children:Ze})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Recipients:"}),e.jsx("span",{className:"font-medium",children:Ue()})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Via:"}),e.jsx("span",{className:"font-medium capitalize",children:k})]}),g&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Early Access:"}),e.jsxs(ie,{variant:"default",className:"gap-1 text-xs",children:[e.jsx(mr,{className:"h-3 w-3"})," Enabled"]})]}),he.registration_start_date&&e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Reg. Opens:"}),e.jsxs("span",{className:"font-medium text-xs",children:[new Date(he.registration_start_date).toLocaleString("en-US",{timeZone:"America/Denver",dateStyle:"medium",timeStyle:"short"})," MT"]})]})]}),e.jsxs("div",{className:"pt-2 border-t border-border",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sample link:"}),e.jsx("p",{className:"text-xs font-mono break-all",children:`/org/${se==null?void 0:se.slug}/events/${he.slug||t}?coupon=${r.toUpperCase()}`})]})]})]}),e.jsx(w,{className:"w-full gap-2",size:"lg",onClick:ye,disabled:!de()||_e,children:_e?e.jsxs(e.Fragment,{children:[e.jsx(oe,{className:"h-4 w-4 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(gt,{className:"h-4 w-4"})," Create Coupon & Send to ",Ue()," Recipient(s)"]})})]})]}),ue.length>0&&e.jsxs(re,{children:[e.jsx(ke,{children:e.jsx(Ee,{className:"text-base",children:"Registration Coupons Log"})}),e.jsx(xe,{children:e.jsx("div",{className:"rounded-md border overflow-auto",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:"text-left p-2 font-medium",children:"Code"}),e.jsx("th",{className:"text-left p-2 font-medium",children:"Event"}),e.jsx("th",{className:"text-left p-2 font-medium",children:"Sent To"}),e.jsx("th",{className:"text-left p-2 font-medium",children:"Discount"}),e.jsx("th",{className:"text-left p-2 font-medium",children:"Uses"}),e.jsx("th",{className:"text-left p-2 font-medium",children:"Expires"}),e.jsx("th",{className:"text-left p-2 font-medium",children:"Status"}),e.jsx("th",{className:"text-left p-2 font-medium",children:"Created"}),e.jsx("th",{className:"text-left p-2 font-medium"})]})}),e.jsx("tbody",{children:ue.map(P=>{var Xe;const Te=P.expires_at&&new Date(P.expires_at)<new Date,Fe=P.max_uses!==null&&P.current_uses>=P.max_uses,Ye=P.is_active?Te?"expired":Fe?"maxed":"active":"inactive";return e.jsxs("tr",{className:"border-b last:border-0",children:[e.jsx("td",{className:"p-2 font-mono font-bold",children:P.code}),e.jsx("td",{className:"p-2 text-muted-foreground",children:((Xe=P.events)==null?void 0:Xe.name)||"—"}),e.jsx("td",{className:"p-2 text-muted-foreground max-w-[200px] truncate",title:P.sent_to||"",children:P.sent_to||"—"}),e.jsx("td",{className:"p-2",children:P.discount_type==="free"?"🎁 Free":P.discount_type==="percent"?`${P.discount_value}%`:`$${P.discount_value}`}),e.jsxs("td",{className:"p-2",children:[P.current_uses,P.max_uses!==null?` / ${P.max_uses}`:""]}),e.jsx("td",{className:"p-2 text-muted-foreground",children:P.expires_at?new Date(P.expires_at).toLocaleDateString():"—"}),e.jsx("td",{className:"p-2",children:e.jsxs(ie,{variant:Ye==="active"?"default":"secondary",className:"gap-1 text-xs",children:[Ye==="active"&&e.jsx(Yn,{className:"h-3 w-3"}),Ye==="expired"&&e.jsx(yt,{className:"h-3 w-3"}),(Ye==="inactive"||Ye==="maxed")&&e.jsx(Ai,{className:"h-3 w-3"}),Ye]})}),e.jsx("td",{className:"p-2 text-muted-foreground",children:new Date(P.created_at).toLocaleDateString()}),e.jsx("td",{className:"p-2",children:e.jsx(w,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive hover:text-destructive",disabled:n===P.id,onClick:async()=>
210{if(confirm(`Delete coupon ${P.code}?`)){i(P.id);try{const{error:bs}=await z.from("coupons").delete().eq("id",P.id);if(bs)throw bs;K.success(`Coupon ${P.code} deleted`),ve()}catch(bs){K.error("Failed to delete: "+bs.message)}finally{i(null)}}},children:n===P.id?e.jsx(oe,{className:"h-4 w-4 animate-spin"}):e.jsx(ws,{className:"h-4 w-4"})})})]},P.id)})})]})})})]}),e.jsx(Ln,{open:pe,onOpenChange:je,result:$e})]})}function uu({open:s,onOpenChange:n}){const{currentOrganization:i}=Je(),[t,d]=a.useState("single"),[r,x]=a.useState(null),[c,o]=a.useState([]),[m,p]=a.useState([]),[u,l]=a.useState([]),[N,j]=a.useState([]),[g,y]=a.useState([]),[k,S]=a.useState(""),[f,h]=a.useState(!1),[M,T]=a.useState(!1),[C,L]=a.useState({success:0,failed:0,errors:[]}),Q=Ja(),{data:Z=[]}=li(i==null?void 0:i.id),R=Z.filter(Y=>Y.is_active),{data:E=[]}=ci(k||void 0),$=()=>{n(!1),setTimeout(()=>{x(null),o([]),p([]),l([]),j([]),y([]),S(""),T(!1),L({success:0,failed:0,errors:[]})},300)};if(!i)return null;if(t==="single"&&r)return e.jsx(zc,{open:s,onOpenChange:Y=>{Y||$()},organizationId:i.id,riderEmail:r.email,riderName:r.name,onSuccess:$});const b=async()=>{try{const Y=await Q.mutateAsync({years:c.length>0?c:void 0,seriesNames:m.length>0?m:void 0,eventNames:u.length>0?u:void 0,classNames:N.length>0?N:void 0});y(Y),Y.length===0&&K.info("No riders with email addresses found for the selected filters.")}catch(Y){K.error(Y.message||"Failed to load recipients")}},I=Y=>{y(W=>W.filter(te=>te.email!==Y))},V=async()=>{if(!k||g.length===0)return;h(!0);let Y=0,W=0;const te=[],B=5;for(let le=0;le<g.length;le+=B){const Me=g.slice(le,le+B),_=await Promise.allSettled(Me.map(X=>z.functions.invoke("assign-coupon-pack",{body:{organization_id:i.id,pack_id:k,rider_email:X.email,rider_name:X.name,member_number:X.memberNumber||null}}).then(({data:F,error:ne})=>{if(ne)throw ne;if(F!=null&&F.error)throw new Error(F.error);return F})));for(let X=0;X<_.length;X++)if(_[X].status==="fulfilled")Y++;else{W++;const F=_[X].reason;te.push(`${Me[X].name} (${Me[X].email}): ${(F==null?void 0:F.message)||"Unknown error"}`)}}L({success:Y,failed:W,errors:te}),T(!0),h(!1),Y>0?K.success(`Pack assigned to ${Y} rider${Y!==1?"s":""}${W>0?` (${W} failed)`:""}`):K.error(`All ${W} assignments failed`)},H=c.length>0||m.length>0||u.length>0;return e.jsx(ts,{open:s,onOpenChange:$,children:e.jsxs(as,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(rs,{children:[e.jsxs(is,{className:"flex items-center gap-2",children:[e.jsx(va,{className:"h-5 w-5"})," Assign Pack to Riders"]}),e.jsx(Fs,{children:"Search for a single rider or assign packs in bulk by event, series, or class."})]}),M?e.jsxs("div",{className:"flex flex-col items-center py-6 gap-3",children:[e.jsx(Yn,{className:"h-12 w-12 text-primary"}),e.jsx("p",{className:"text-foreground font-medium",children:"Bulk assignment complete!"}),e.jsxs("div",{className:"flex gap-4 text-sm",children:[e.jsxs(ie,{variant:"default",children:[C.success," assigned"]}),C.failed>0&&e.jsxs(ie,{variant:"destructive",children:[C.failed," failed"]})]}),C.errors.length>0&&e.jsx(qs,{className:"h-[120px] w-full rounded-md border p-3",children:e.jsx("div",{className:"space-y-1",children:C.errors.map((Y,W)=>e.jsx("p",{className:"text-xs text-destructive",children:Y},W))})})]}):e.jsxs(ot,{value:t,onValueChange:Y=>d(Y),children:[e.jsxs(pt,{className:"grid w-full grid-cols-2",children:[e.jsxs(Qe,{value:"single",className:"gap-2",children:[e.jsx(Xs,{className:"h-4 w-4"})," Single Rider"]}),e.jsxs(Qe,{value:"bulk",className:"gap-2",children:[e.jsx(Gs,{className:"h-4 w-4"})," Bulk Assign"]})]}),e.jsxs(Ae,{value:"single",className:"space-y-3 mt-4",children:[e.jsx(er,{deliveryMethod:"email",onSelectRider:Y=>{if(!Y.email){K.error("Rider must have an email address on file.");return}x({name:Y.name,email:Y.email,memberNumber:Y.memberNumber})}}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Rider must have an email address on file to receive a coupon pack."})]}),e.jsxs(Ae,{value:"bulk",className:"space-y-4 mt-4",children:[e.jsx(Jt,{selectedYears:c,selectedSeries:m,selectedEvents:u,selectedClasses:N,onYearsChange:o,onSeriesChange:p,onEventsChange:l,onClasse
210sChange:j}),e.jsxs(w,{onClick:b,disabled:!H||Q.isPending,variant:"outline",className:"w-full gap-2",children:[Q.isPending?e.jsx(oe,{className:"h-4 w-4 animate-spin"}):e.jsx(Ws,{className:"h-4 w-4"}),"Load Riders"]}),g.length>0&&e.jsxs("div",{className:"border rounded-lg",children:[e.jsxs("div",{className:"p-3 border-b bg-muted/50 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-sm",children:"Recipients"}),e.jsx(ie,{variant:"secondary",children:g.length})]}),e.jsxs(w,{variant:"ghost",size:"sm",className:"h-7 text-xs text-muted-foreground hover:text-destructive",onClick:()=>y([]),children:[e.jsx(ws,{className:"h-3 w-3 mr-1"})," Clear All"]})]}),e.jsx(qs,{className:"h-[160px]",children:e.jsx("div",{className:"divide-y",children:g.map(Y=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 hover:bg-muted/50",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-muted flex items-center justify-center",children:e.jsx(Xs,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-medium",children:Y.name||`Member #${Y.memberNumber}`}),e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ks,{className:"h-3 w-3"})," ",Y.email]})]})]}),e.jsx(w,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>I(Y.email),children:e.jsx(vt,{className:"h-3 w-3"})})]},Y.email))})})]}),g.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(v,{children:"Coupon Pack"}),e.jsxs(Pe,{value:k,onValueChange:S,children:[e.jsx(Ie,{children:e.jsx(qe,{placeholder:"Select a pack..."})}),e.jsx(Be,{children:R.map(Y=>e.jsx(ae,{value:Y.id,children:Y.name},Y.id))})]})]}),k&&E.length>0&&e.jsxs("div",{className:"rounded-lg border p-3 space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Pack contains:"}),E.map(Y=>e.jsxs("p",{className:"text-sm text-foreground",children:["• ",Y.title," (",Y.discount_type==="free"||Y.discount_type==="free_item"?"🎁 Free":Y.discount_type==="percent"?`${Y.discount_value}%`:`$${Y.discount_value}`,", ",Y.max_uses," use",Y.max_uses!==1?"s":"",")"]},Y.id))]})]})]})]}),e.jsx(Ys,{children:M?e.jsx(w,{onClick:$,children:"Done"}):t==="bulk"&&g.length>0?e.jsxs(e.Fragment,{children:[e.jsx(w,{variant:"outline",onClick:$,disabled:f,children:"Cancel"}),e.jsxs(w,{onClick:V,disabled:!k||f,className:"gap-2",children:[f?e.jsx(oe,{className:"h-4 w-4 animate-spin"}):e.jsx(va,{className:"h-4 w-4"}),f?"Assigning...":`Assign to ${g.length} Rider${g.length!==1?"s":""}`]})]}):null})]})})}function hu(){const{currentOrganization:s}=Je(),n=s==null?void 0:s.id,{data:i=[],isLoading:t}=li(n),{data:d=[]}=Ga(n),{data:r=[]}=Ya(n),x=Vc();oi();const c=Oc(),[o,m]=a.useState(!1),[p,u]=a.useState(!1),[l,N]=a.useState(null),[j,g]=a.useState(""),[y,k]=a.useState(""),S=async()=>{!n||!j.trim()||(await x.mutateAsync({organization_id:n,name:j.trim(),description:y.trim()||void 0}),g(""),k(""),m(!1))};return l?e.jsx(xu,{pack:l,offers:d,templates:r,organizationId:n,onBack:()=>N(null)}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Coupon Packs"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(w,{variant:"outline",onClick:()=>u(!0),className:"gap-2",children:[e.jsx(wa,{className:"h-4 w-4"})," Assign Pack"]}),e.jsxs(w,{onClick:()=>m(!0),className:"gap-2",children:[e.jsx(Es,{className:"h-4 w-4"})," Create Pack"]})]})]}),t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(oe,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):i.length===0?e.jsx(re,{children:e.jsxs(xe,{className:"py-8 text-center text-muted-foreground",children:[e.jsx(va,{className:"h-10 w-10 mx-auto mb-3 opacity-50"}),e.jsx("p",{children:"No coupon packs yet. Create one to bundle coupons for riders."})]})}):e.jsx("div",{className:"grid gap-3",children:i.map(f=>e.jsx(re,{className:"cursor-pointer hover:bg-muted/30 transition-colors",onClick:()=>N(f),children:e.jsxs(xe,{className:"py-4 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(va,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:f.name}),f.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:f.description})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ie,{variant:f.is_active?"default":"secondary",children:f.is_active?"Active":"Inactive"}),e.jsx(w,{variant:"ghost",size:"icon",onClick:h=>{h.stopPropagation(),c.mutate(f.id)},children:e.jsx(ws,{className:"h-4 w-4 text-destructive"})})]})]})},f.id))}),e.jsx(ts,{open:o,onOpenChange:m,children:e.jsxs(as,{className:"sm:max-w-md",children:[e.jsx(rs,{children:e.jsx(is,{children:"Create Coupon Pack"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(v,{children:"Name"}),e.jsx(A,{value:j,onChange:f=>g(f.target.value),placeholder:"e.g. Race Day Welcome Pack"})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Description (optional)"}),e.jsx(Ns,{value:y,onChange:f=>k(f.target.value),placeholder:"What's in this pack?"})]})]}),e.jsxs(Ys,{children:[e.jsx(w,{variant:"outline",onClick:()=>m(!1),children:"Cancel"}),e.jsxs(w,{onClick:S,disabled:!j.trim()||x.isPending,children:[x.isPending?e.jsx(oe,{className:"h-4 w-4 animate-spin mr-2"}):null,"Create"]})]})]})}),e.jsx(uu,{open:p,onOpenChange:u})]})}function xu({pack:s,offers:n,templates:i,organizationId:t,onBack:d}){const{data:r=[],isLoading:x}=ci(s.id),c=Gc(),o=Yc(),m=Kc(),p=oi(),[u,l]=a.useState(!1),[N,j]=a.useState(null),[g,y]=a.useState(null),[k,S]=a.useState(""),[f,h]=a.use
210State(""),[M,T]=a.useState("amount"),[C,L]=a.useState(""),[Q,Z]=a.useState("1"),[R,E]=a.useState(""),[$,b]=a.useState(""),[I,V]=a.useState(""),H=u||!!N,Y=c.isPending||o.isPending,W=F=>{S(F.title),h(F.subtitle||""),T(F.discount_type),L(String(F.discount_value)),Z(String(F.max_uses)),E(F.expires_days?String(F.expires_days):""),b(F.template_id||""),V(F.offer_id||""),j(F)},te=async()=>{if(!k.trim()||M!=="free"&&!C)return;const F={title:k.trim(),subtitle:f.trim()||null,discount_type:M,discount_value:M==="free"?100:parseFloat(C),max_uses:parseInt(Q)||1,expires_days:R?parseInt(R):null,template_id:$||null,offer_id:I||null};N?await o.mutateAsync({id:N.id,...F}):await c.mutateAsync({pack_id:s.id,...F}),B()},B=()=>{l(!1),j(null),le()},le=()=>{S(""),h(""),T("amount"),L(""),Z("1"),E(""),b(""),V("")},Me=F=>{V(F);const ne=n.find(J=>J.id===F);ne&&(S(ne.description||ne.offer_key),T(ne.discount_type),L(String(ne.discount_value)))},_=F=>({code:"PREVIEW",title:F.title,subtitle:F.subtitle,rider_name:"Jane Rider",member_number:42,discount_type:F.discount_type,discount_value:F.discount_value,expires_at:F.expires_days?dr(new Date,F.expires_days).toISOString():null}),X=F=>F.template_id?i.find(ne=>ne.id===F.template_id)??null:null;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(w,{variant:"ghost",size:"icon",onClick:d,children:e.jsx(Wa,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:s.name}),s.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:s.description})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(v,{className:"text-sm",children:"Active"}),e.jsx(Ds,{checked:s.is_active,onCheckedChange:F=>p.mutate({id:s.id,is_active:F})})]})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("h4",{className:"text-sm font-medium text-muted-foreground uppercase tracking-wider",children:["Items in Pack (",r.length,")"]}),e.jsxs(w,{size:"sm",onClick:()=>l(!0),className:"gap-2",children:[e.jsx(Es,{className:"h-4 w-4"})," Add Item"]})]}),x?e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(oe,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):r.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No items yet. Add coupons to this pack."}):e.jsx("div",{className:"space-y-2",children:r.map(F=>e.jsx(re,{children:e.jsxs(xe,{className:"py-3 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:F.title}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[F.discount_type==="free"?"🎁 Free":F.discount_type==="percent"?`${F.discount_value}% off`:`$${F.discount_value} off`," · ",F.max_uses," use",F.max_uses!==1?"s":"",F.expires_days?` · Expires ${F.expires_days}d after assignment`:""]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(w,{variant:"ghost",size:"icon",onClick:()=>y(F),title:"Preview",children:e.jsx(Zt,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(w,{variant:"ghost",size:"icon",onClick:()=>W(F),title:"Edit",children:e.jsx(Ft,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(w,{variant:"ghost",size:"icon",onClick:()=>m.mutate(F.id),title:"Delete",children:e.jsx(ws,{className:"h-4 w-4 text-destructive"})})]})]})},F.id))}),e.jsx(ts,{open:H,onOpenChange:F=>{F||B()},children:e.jsxs(as,{className:"sm:max-w-2xl",children:[e.jsx(rs,{children:e.jsx(is,{children:N?"Edit Item":"Add Item to Pack"})}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-4",children:[!N&&n.length>0&&e.jsxs("div",{children:[e.jsx(v,{children:"Pre-fill from Offer (optional)"}),e.jsxs(Pe,{value:I,onValueChange:Me,children:[e.jsx(Ie,{children:e.jsx(qe,{placeholder:"Select an offer..."})}),e.jsx(Be,{children:n.filter(F=>F.is_active).map(F=>e.jsxs(ae,{value:F.id,children:[F.offer_key," — ",F.discount_type==="percent"?`${F.discount_value}%`:`$${F.discount_value}`]},F.id))})]})]}),i.length>0&&e.jsxs("div",{children:[e.jsx(v,{children:"Template (select to see live preview)"}),e.jsxs(Pe,{value:$,onValueChange:b,children:[e.jsx(Ie,{children:e.jsx(qe,{placeholder:"Select template..."})}),e.jsx(Be,{children:i.map(F=>e.jsx(ae,{value:F.id,children:F.template_name},F.id))})]})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Title"}),e.jsx(A,{value:k,onChange:F=>S(F.target.value),placeholder:"e.g. Free Drink"})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Subtitle (optional)"}),e.jsx(A,{value:f,onChange:F=>h(F.target.value)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(v,{children:"Discount Type"}),e.jsxs(Pe,{value:M,onValueChange:T,children:[e.jsx(Ie,{children:e.jsx(qe,{})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"amount",children:"$ Amount"}),e.jsx(ae,{value:"percent",children:"% Percent"}),e.jsx(ae,{value:"free",children:"🎁 Free (100% off)"})]})]})]}),M!=="free"&&e.jsxs("div",{children:[e.jsx(v,{children:"Discount Value"}),e.jsx(A,{type:"number",value:C,onChange:F=>L(F.target.value)})]}),M==="free"&&e.jsx("div",{className:"flex items-end",children:e.jsx("p",{className:"text-sm text-muted-foreground pb-2",children:"Full amount covered"})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(v,{children:"Max Uses"}),e.jsx(A,{type:"number",value:Q,onChange:F=>Z(F.target.value),min:"1"})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Expires (days after assignment)"}),e.jsx(A,{type:"number",value:R,onChange:F=>E(F.target.value),placeholder:"No expiry"})]})]})]}),e.jsx("div",{className:"flex flex-col items-center justify-start",children:$?e.jsxs(e.Fragment,{children:[e.jsx(oa,{coupon:{code:"PREVIEW",title:k||"COUPON",subtitle:f||null,rider_name:"Jane Rider",member_number:42,discount_type:M,discount_value:parseFloat(C)||0,expires_at:R?dr(new Date,parseInt(R)).toISOString():null},template:i.find(F=>F.id===$)??null,organizationId:t,posUrl:window.location.origin+"/pos",compact:!0}),e.jsx("p",{className:"text-xs text-muted-foreground text-center mt-2",children:"Live preview — updates as you type"})]}):e.jsx("div",{className:"flex items-center justify-center h-full text-sm text-muted-foreground text-center p-4 border border-dashed border-border rounded-lg",children:"Select a template above to see a live coupon preview"})})]}),e.jsxs(Ys,{children:[e.jsx(w,{variant:"outline",onClick:B,children:"Cancel"}),e.jsxs(w,{onClick:te,disabled:!k.trim()||!C||Y,children:[Y?e.jsx(oe,{className:"h-4 w-4 animate-spin mr-2"}):null,N?"Save Changes":"Add Item"]})]})]})}),e.jsx(ts,{open:!!g,onOpenChange:F=>{F||y(null)},children:e.jsxs(as,{className:"sm:max-w-md",children:[e.jsx(rs,{children:e.jsx(is,{children:"Coupon Preview"})}),g&&e.jsxs("div",{className:"py-4",children:[e.jsx(oa,{coupon:_(g),template:X(g),organizationId:t,posUrl:window.location.origin+"/pos",compact:!0}),e.jsx("p",{className:"text-xs text-muted-foreground text-center mt-4",children:"This is a preview with sample data. Actual coupons will show the rider's real name and a unique code."})]})]})})]})}async function pu(s,n,i={}){var t;if(!s||n.length===0)return null;try{const{data:d,error:r}=await z.functions.invoke("notify-wallet-coupon",{body:{organization_id:s,items:n,test_send:!!i.testSend,...(t=i.messageTemplate)!=null&&t.trim()?{message_template:i.messageTemplate.trim()}:{}}});return r?(console.warn("notifyWalletCoupon failed",r),null):d}catch(d){return console.warn("notifyWalletCoupon threw",d),null}}function gu(){const{currentOrganization:s}
210=Je(),n=s==null?void 0:s.id,i=Ms(),[t,d]=a.useState(null),[r,x]=a.useState(!1),[c,o]=a.useState(null),{data:m=[],isLoading:p}=ms({queryKey:["sponsors",n],queryFn:async()=>{if(!n)return[];const{data:N,error:j}=await z.from("sponsors").select("id, organization_id, name, logo_url, website_url, brand_color, redemption_notes, is_active").eq("organization_id",n).order("name");if(j)throw j;return N||[]},enabled:!!n}),u=ks({mutationFn:async N=>{const{error:j}=await z.from("sponsors").delete().eq("id",N);if(j)throw j},onSuccess:()=>{K.success("Sponsor deleted"),i.invalidateQueries({queryKey:["sponsors",n]}),d(null)},onError:N=>K.error(N.message||"Failed to delete")}),l=m.find(N=>N.id===t)||null;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("h3",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4"}),"Sponsor coupons — codes from partners like MotoSport, Holiday Oil"]}),e.jsxs(w,{size:"sm",onClick:()=>{o(null),x(!0)},children:[e.jsx(Es,{className:"h-4 w-4 mr-1"})," Add sponsor"]})]}),p?e.jsxs("p",{className:"text-sm text-muted-foreground inline-flex items-center gap-2",children:[e.jsx(oe,{className:"h-4 w-4"}),"Loading…"]}):m.length===0?e.jsx(re,{children:e.jsx(xe,{className:"py-10 text-center text-sm text-muted-foreground",children:"No sponsors yet. Add one to upload a batch of codes."})}):e.jsx("div",{className:"grid gap-2 sm:grid-cols-2 lg:grid-cols-3",children:m.map(N=>e.jsx(re,{className:`cursor-pointer transition ${t===N.id?"ring-2 ring-primary":"hover:border-primary/40"}`,onClick:()=>d(N.id),children:e.jsxs(xe,{className:"p-3 flex items-center gap-3",children:[e.jsx("div",{className:"h-12 w-12 rounded flex items-center justify-center overflow-hidden shrink-0",style:{background:N.brand_color},children:N.logo_url?e.jsx("img",{src:N.logo_url,alt:N.name,className:"max-h-12 max-w-12 object-contain"}):e.jsx(Nn,{className:"h-6 w-6 text-white"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:N.name}),N.website_url&&e.jsxs("a",{href:N.website_url,target:"_blank",rel:"noopener noreferrer",onClick:j=>j.stopPropagation(),className:"text-xs text-muted-foreground hover:text-primary truncate flex items-center gap-1",children:[e.jsx(ea,{className:"h-3 w-3"})," ",N.website_url.replace(/^https?:\/\//,"")]})]}),e.jsx(w,{size:"icon",variant:"ghost",onClick:j=>{j.stopPropagation(),o(N),x(!0)},title:"Edit",children:e.jsx(Ft,{className:"h-4 w-4"})}),e.jsx(w,{size:"icon",variant:"ghost",onClick:j=>{j.stopPropagation(),confirm(`Delete ${N.name}?`)&&u.mutate(N.id)},title:"Delete",children:e.jsx(ws,{className:"h-4 w-4 text-destructive"})})]})},N.id))}),l&&e.jsx(ju,{sponsor:l}),e.jsx(fu,{open:r,onOpenChange:x,sponsor:c,organizationId:n,onSaved:()=>i.invalidateQueries({queryKey:["sponsors",n]})})]})}function fu({open:s,onOpenChange:n,sponsor:i,organizationId:t,onSaved:d}){const[r,x]=a.useState((i==null?void 0:i.name)??""),[c,o]=a.useState((i==null?void 0:i.website_url)??""),[m,p]=a.useState((i==null?void 0:i.brand_color)??"#FF6300"),[u,l]=a.useState((i==null?void 0:i.redemption_notes)??""),[N,j]=a.useState((i==null?void 0:i.logo_url)??""),[g,y]=a.useState(!1),[k,S]=a.useState(!1),f=a.useRef(null);a.useEffect(()=>{x((i==null?void 0:i.name)??""),o((i==null?void 0:i.website_url)??""),p((i==null?void 0:i.brand_color)??"#FF6300"),l((i==null?void 0:i.redemption_notes)??""),j((i==null?void 0:i.logo_url)??"")},[i,s]);const h=async T=>{var C;if(t){y(!0);try{const L=((C=T.name.split(".").pop())==null?void 0:C.toLowerCase())||"png",Q=`${t}/${crypto.randomUUID()}.${L}`,{error:Z}=await z.storage.from("sponsor-logos").upload(Q,T,{upsert:!1});if(Z)throw Z;const{data:R}=z.storage.from("sponsor-logos").getPublicUrl(Q);j(R.publicUrl)}catch(L){K.error(L.message||"Logo upload failed")}finally{y(!1)}}},M=async()=>{if(!t||!r.trim()){K.error("Name is required");return}S(!0);try{const T={organization_id:t,name:r.trim(),website_url:c.trim()||null,brand_color:m,redemption_notes:u.trim()||null,logo_url:N||null},{error:C}=i?await z.from("sponsors").update(T).eq("id",i.id):await z.from("sponsors").insert(T);
210if(C)throw C;K.success(i?"Sponsor updated":"Sponsor created"),d(),n(!1)}catch(T){K.error(T.message||"Save failed")}finally{S(!1)}};return e.jsx(ts,{open:s,onOpenChange:n,children:e.jsxs(as,{className:"sm:max-w-md",children:[e.jsxs(rs,{children:[e.jsx(is,{children:i?"Edit sponsor":"Add sponsor"}),e.jsx(Fs,{children:"Partner brand whose coupons you'll distribute to your riders."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(v,{children:"Name"}),e.jsx(A,{value:r,onChange:T=>x(T.target.value),placeholder:"MotoSport",maxLength:120})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Website"}),e.jsx(A,{value:c,onChange:T=>o(T.target.value),placeholder:"https://motosport.com",maxLength:500})]}),e.jsxs("div",{className:"flex gap-3 items-end",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(v,{children:"Brand color"}),e.jsx(A,{value:m,onChange:T=>p(T.target.value),placeholder:"#FF6300"})]}),e.jsx("label",{className:"h-10 w-10 rounded border cursor-pointer relative overflow-hidden",style:{background:m},title:"Pick brand color",children:e.jsx("input",{type:"color",value:/^#[0-9a-fA-F]{6}$/.test(m)?m:"#FF6300",onChange:T=>p(T.target.value.toUpperCase()),className:"absolute inset-0 opacity-0 cursor-pointer"})})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Logo"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[N&&e.jsx("div",{className:"h-12 w-12 rounded border flex items-center justify-center bg-white overflow-hidden",children:e.jsx("img",{src:N,alt:"Logo",className:"max-h-12 max-w-12 object-contain"})}),e.jsxs(w,{type:"button",variant:"outline",size:"sm",onClick:()=>{var T;return(T=f.current)==null?void 0:T.click()},disabled:g,children:[g?e.jsx(oe,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(Dt,{className:"h-4 w-4 mr-1"}),N?"Replace":"Upload"," logo"]}),e.jsx("input",{ref:f,type:"file",accept:"image/png,image/jpeg,image/jpg,image/webp,image/svg+xml,image/gif,.png,.jpg,.jpeg,.webp,.svg,.gif",className:"hidden",onChange:T=>{var C;return((C=T.target.files)==null?void 0:C[0])&&h(T.target.files[0])}})]})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Redemption notes (optional)"}),e.jsx(Ns,{value:u,onChange:T=>l(T.target.value),placeholder:"Where / how to use these codes",maxLength:1e3,rows:2})]})]}),e.jsxs(Ys,{children:[e.jsx(w,{variant:"outline",onClick:()=>n(!1),disabled:k,children:"Cancel"}),e.jsxs(w,{onClick:M,disabled:k||!r.trim(),children:[k&&e.jsx(oe,{className:"h-4 w-4 animate-spin mr-1"}),i?"Save":"Create"]})]})]})})}function ju({sponsor:s}){const n=Ms(),[i,t]=a.useState(!1),[d,r]=a.useState(null),[x,c]=a.useState(null),[o,m]=a.useState(null),{data:p=[],isLoading:u}=ms({queryKey:["sponsor-batches",s.id],queryFn:async()=>{const{data:N,error:j}=await z.from("sponsor_coupon_batches").select("id, sponsor_id, name, code_mode, shared_code, discount_label, redemption_type, redemption_url, instructions, title, subtitle, fine_print, expires_at, is_active, template_id, sms_template").eq("sponsor_id",s.id).order("created_at",{ascending:!1});if(j)throw j;return N||[]}}),l=ks({mutationFn:async N=>{const{error:j}=await z.from("sponsor_coupon_batches").delete().eq("id",N);if(j)throw j},onSuccess:()=>{K.success("Batch deleted"),n.invalidateQueries({queryKey:["sponsor-batches",s.id]})},onError:N=>K.error(N.message||"Delete failed")});return e.jsxs(re,{children:[e.jsxs(ke,{className:"flex flex-row items-center justify-between gap-2",children:[e.jsxs(Ee,{className:"text-base",children:[s.name," — Batches"]}),e.jsxs(w,{size:"sm",onClick:()=>{r(null),t(!0)},children:[e.jsx(Es,{className:"h-4 w-4 mr-1"})," New batch"]})]}),e.jsx(xe,{children:u?e.jsxs("p",{className:"text-sm text-muted-foreground inline-flex items-center gap-2",children:[e.jsx(oe,{className:"h-4 w-4"}),"Loading…"]}):p.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No batches yet."}):e.jsx("ul",{className:"divide-y",children:p.map(N=>e.jsxs("li",{className:"py-3 flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium",children:N.name}),e.jsx(ie,{variant:"secondary",children:N.discount_label}),e.jsx(ie,{variant:"outline",children:N.code_mode==="shared"?"Shared code":"Unique codes"}),e.jsx(ie,{variant:"outline",children:N.redemption_type.replace("_"," ")}),!N.is_active&&e.jsx(ie,{variant:"destructive",children:"Inactive"}),N.expires_at&&new Date(N.expires_at)<new Date&&e.jsx(ie,{variant:"destructive",children:"Expired"})]}),N.code_mode==="unique"&&e.jsx(Nu,{batchId:N.id}),N.code_mode==="shared"&&N.shared_code&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Shared: ",e.jsx("span",{className:"font-mono",children:N.shared_code})]}),N.code_mode==="unique"&&e.jsx(vu,{batchId:N.id})]}),e.jsxs(w,{size:"sm",variant:"outline",onClick:()=>m(N),title:"Send a test SMS to one or more riders without consuming any codes — fire as many times as you want.",children:[e.jsx(gt,{className:"h-3.5 w-3.5 mr-1"})," Test"]}),N.code_mode==="unique"&&e.jsx(w,{size:"sm",variant:"outline",onClick:()=>c(N),children:"Assign"}),e.jsx(w,{size:"icon",variant:"ghost",onClick:()=>{r({...N,id:"",name:`${N.name} (Copy)`}),t(!0)},title:"Duplicate batch settings",children:e.jsx(Nt,{className:"h-4 w-4"})}),e.jsx(w,{size:"icon",variant:"ghost",onClick:()=>{r(N),t(!0)},title:"Edit",children:e.jsx(Ft,{className:"h-4 w-4"})}),e.jsx(w,{size:"icon",variant:"ghost",onClick:()=>confirm(`Delete batch "${N.name}" and all its codes?`)&&l.mutate(N.id),title:"Delete",children:e.jsx(ws,{className:"h-4 w-4 text-destructive"})})]},N.id))})}),e.jsx(bu,{open:i,onOpenChange:t,sponsor:s,batch:d,onSaved:()=>n.invalidateQueries({queryKey:["sponsor-batches",s.id]})}),x&&e.jsx(_r,{open:!!x,onOpenChange:N=>!N&&c(null),batch:x,organizationId:s.organization_id}),o&&e.jsx(_r,{open:!!o,onOpenChange:N=>!N&&m(null),batch:o,organizationId:s.organization_id,mode:"test"})]})}function vu({batchId:s}){const{data:n}
210=ms({queryKey:["sponsor-batch-stats",s]}),i=n;return!i||i.total===0||i.assigned>0?null:e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 italic",children:["Codes are in the pool. Click ",e.jsx("strong",{children:"Assign"})," to send to riders or ",e.jsx("strong",{children:"Test"})," to send one to yourself."]})}function Nu({batchId:s}){const{data:n}=ms({queryKey:["sponsor-batch-stats",s],queryFn:async()=>{const[i,t,d]=await Promise.all([z.from("sponsor_coupon_codes").select("id",{count:"exact",head:!0}).eq("batch_id",s),z.from("sponsor_coupon_codes").select("id",{count:"exact",head:!0}).eq("batch_id",s).not("assigned_family_member_id","is",null),z.from("sponsor_coupon_codes").select("id",{count:"exact",head:!0}).eq("batch_id",s).not("used_at","is",null)]);return{total:i.count??0,assigned:t.count??0,used:d.count??0}}});return n?e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[n.total," codes · ",n.assigned," assigned · ",n.used," used"]}):null}function bu({open:s,onOpenChange:n,sponsor:i,batch:t,onSaved:d}){const[r,x]=a.useState((t==null?void 0:t.name)??""),[c,o]=a.useState((t==null?void 0:t.code_mode)??"shared"),[m,p]=a.useState((t==null?void 0:t.shared_code)??""),[u,l]=a.useState((t==null?void 0:t.discount_label)??""),[N,j]=a.useState((t==null?void 0:t.redemption_type)??"online"),[g,y]=a.useState((t==null?void 0:t.redemption_url)??i.website_url??""),[k,S]=a.useState((t==null?void 0:t.instructions)??""),[f,h]=a.useState((t==null?void 0:t.title)??""),[M,T]=a.useState((t==null?void 0:t.subtitle)??""),[C,L]=a.useState((t==null?void 0:t.fine_print)??""),[Q,Z]=a.useState(t!=null&&t.expires_at?t.expires_at.split("T")[0]:""),[R,E]=a.useState((t==null?void 0:t.template_id)??"none"),[$,b]=a.useState((t==null?void 0:t.sms_template)??""),[I,V]=a.useState(""),[H,Y]=a.useState([]),[W,te]=a.useState(!1),B=a.useRef(null);a.useEffect(()=>{x((t==null?void 0:t.name)??""),o((t==null?void 0:t.code_mode)??"shared"),p((t==null?void 0:t.shared_code)??""),l((t==null?void 0:t.discount_label)??""),j((t==null?void 0:t.redemption_type)??"online"),y((t==null?void 0:t.redemption_url)??i.website_url??""),S((t==null?void 0:t.instructions)??""),h((t==null?void 0:t.title)??""),T((t==null?void 0:t.subtitle)??""),L((t==null?void 0:t.fine_print)??""),Z(t!=null&&t.expires_at?t.expires_at.split("T")[0]:""),E((t==null?void 0:t.template_id)??"none"),b((t==null?void 0:t.sms_template)??""),V(""),Y([])},[t,s,i.website_url]);const{data:le=[]}=ms({queryKey:["pos-coupon-templates",i.organization_id],queryFn:async()=>{const{data:F,error:ne}=await z.from("pos_coupon_templates").select("id, template_name, border_color, background_color, accent_color").eq("organization_id",i.organization_id).order("template_name");if(ne)throw ne;return F||[]},enabled:s}),Me=async F=>{try{const ne=await F.arrayBuffer(),J=no(ne,{type:"array"}),_e=J.Sheets[J.SheetNames[0]],$e=ro.sheet_to_json(_e,{header:1,blankrows:!1}).flat().map(pe=>String(pe??"").trim()).filter(pe=>pe&&!/code|coupon/i.test(pe)||pe.length>3),ee=Array.from(new Set($e.filter(pe=>pe.length>0&&pe.toLowerCase()!=="code"&&pe.toLowerCase()!=="coupon")));Y(ee),K.success(`Parsed ${ee.length} codes from ${F.name}`)}catch(ne){K.error("Failed to parse file: "+(ne.message||"unknown"))}},_=()=>{const F=I.split(/[\n,;\t]+/).map(ne=>ne.trim()).filter(Boolean);return Array.from(new Set([...H,...F]))},X=async()=>{if(!r.trim()||!u.trim()){K.error("Name and discount label are required");return}if(c==="shared"&&!m.trim()){K.error("Shared code is required");return}te(!0);try{const F={sponsor_id:i.id,organization_id:i.organization_id,name:r.trim(),code_mode:c,shared_code:c==="shared"?m.trim():null,discount_label:u.trim(),redemption_type:N,redemption_url:g.trim()||null,instructions:k.trim()||null,title:f.trim()||null,subtitle:M.trim()||null,fine_print:C.trim()||null,expires_at:Q?new Date(Q+"T23:59:59").toISOString():null,template_id:R&&R!=="none"?R:null,sms_template:$.trim()?$.trim():null};let ne=(t==null?void 0:t.id)||void 0;if(ne){const{error:J}=await z.from("sponsor_coupon_batches").update(F).eq("id",ne);if(J)throw J}else{const{data:J,error:_e}=await z.from("sponsor_coupon_batches").insert(F).select("id").single();if(_e)throw _e;ne=J.id}if(c==="unique"&&ne){const J=_();if(J.length>0){const{data:_e}=await z.from("sponsor_coupon_codes").select("code").eq("batch_id",ne),me=new Set((_e||[]).map(ee=>ee.code)),$e=J.filter(ee=>!me.has(ee)).map(ee=>({batch_id:ne,organization_id:i.organization_id,code:ee}));if($e.length>0){for(let ee=0;ee<$e.length;ee+=500){const pe=$e.slice(ee,ee+500),{error:je}=await z.from("sponsor_coupon_codes").insert(pe);if(je)throw je}K.success(`Added ${$e.length} new codes (${J.length-$e.length} duplicates skipped)`)}else K.info("No new codes to add")}}K.success(t?"Batch updated":"Batch created"),d(),n(!1)}catch(F){K.error(F.message||"Save failed")}finally{te(!1)}};return e.jsx(ts,{open:s,onOpenChange:n,children:e.jsxs(as,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(rs,{children:e.jsxs(is,{children:[t?"Edit batch":"New batch"," — ",i.name]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(v,{children:"Batch name"}),e.jsx(A,{value:r,onChange:F=>x(F.target.value),placeholder:"Spring 2026 promo",maxLength:120})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Discount label"}),e.jsx(A,{value:u,onChange:F=>l(F.target.value),placeholder:"15% off",maxLength:60})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(v,{children:"Code mode"}),e.jsxs(Pe,{value:c,onValueChange:F=>o(F),children:[e.jsx(Ie,{children:e.jsx(qe,{})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"shared",children:"Shared code (everyone uses the same)"}),e.jsx(ae,{value:"unique",children:"Unique per rider"})]})]})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Redemption"}),e.jsxs(Pe,{value:N,onValueChange:F=>j(F),children:[e.jsx(Ie,{children:e.jsx(qe,{})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"online",children:"Online checkout"}),e.jsx(ae,{value:"in_store",children:"In-store / scan"}),e.jsx(ae,{value:"both",children:"Both"})]})]})]})]}),c==="shared"&&e.jsxs("div",{children:[e.jsx(v,{children:"Shared code"}),e.jsx(A,{value:m,onChange:F=>p(F.target.value),placeholder:"BEYONDPRO15",maxLength:120,className:"font-mono"})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Redemption URL"}),e.jsx(A,{value:g,onChange:F=>y(F.target.value),placeholder:"https://motosport.com",maxLength:500})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(v,{children:"Expires"}),e.jsx(A,{type:"date",value:Q,onChange:F=>Z(F.target.value)})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Poster template"}),e.jsxs(Pe,{value:R,onValueChange:E,children:[e.jsx(Ie,{children:e.jsx(qe,{placeholder:"Default styling"})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"none",children:"Default styling"}),le.map(F=>e.jsx(ae,{value:F.id,children:F.template_name},F.id))]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"Picks the colors / logo used on the SMS landing page."})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(v,{children:"Title (optional)"}),e.jsx(A,{value:f,onChange:F=>h(F.target.value),maxLength:120,placeholder:"e.g. EXCLUSIVE OFFER"})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Subtitle (optional)"}),e.jsx(A,{value:M,onChange:F=>T(F.target.value),maxLength:160,placeholder:"Short tagline shown under title"})]})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Instructions (optional)"}),e.jsx(Ns,{value:k,onChange:F=>S(F.target.value),maxLength:1e3,rows:2,placeholder:"Enter at checkout"})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Fine print (optional)"}),e.jsx(Ns,{value:C,onChange:F=>L(F.target.value),maxLength:2e3,rows:3,placeholder:"Terms, exclusions, valid dates, etc."}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"Displayed in small text at the bottom of the coupon."})]}),e.jsxs("div",{className:"space-y-1 rounded-md border p-3",children:[e.jsx(v,{className:"text-sm font-medium",children:"SMS message (optional)"}),e.jsx(Ns,{value:$,onChange:F=>b(F.target.value),rows:3,maxLength:500,placeholder:"Hey {first_name}! You just got a new {coupon_label} in your Beyond Pro wallet. View it: {url}"}),e.jsxs("p",{className:"text-[11px] text-muted-foreground leading-snug",children:["Saved with the batch and used for the initial send and any resends. Leave blank to use the default. Placeholders: ",e.jsx("code",{className:"bg-muted px-1 rounded",children:"{first_name}"})," ",e.jsx("code",{className:"bg-muted px-1 rounded",children:"{coupon_label}"})," ",e.jsx("code",{className:"bg-muted px-1 rounded",children:"{sponsor}"})," ",e.jsx("code",{className:"bg-muted px-1 rounded",children:"{discount}"})," ",e.jsx("code",{className:"bg-muted px-1 rounded",children:"{url}"})," ",e.jsx("code",{className:"bg-muted px-1 rounded",children:"{org}"}),". The ",e.jsx("code",{className:"bg-muted px-1 rounded",children:"{url}"})," link is required."]}),$.trim()&&!$.includes("{url}")&&e.jsxs("p",{className:"text-[11px] text-amber-600",children:["⚠ Your message doesn't include ","{url}"," — recipients won't get a link to the coupon."]})]}),c==="unique"&&e.jsxs("div",{className:"space-y-2 rounded-md border p-3 bg-muted/30",children:[e.jsx(v,{className:"text-sm font-medium",children:"Add codes"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(w,{type:"button",variant:"outline",size:"sm",onClick:()=>{var F;return(F=B.current)==null?void 0:F.click()},children:[e.jsx(ao,{className:"h-4 w-4 mr-1"})," Upload CSV / XLSX"]}),e.jsx("input",{ref:B,type:"file",accept:".csv,.xlsx,.xls",className:"hidden",onChange:F=>{var ne;return((ne=F.target.files)==null?void 0:ne[0])&&Me(F.target.files[0])}}),H.length>0&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[H.length," from file"]})]}
210),e.jsx(Ns,{value:I,onChange:F=>V(F.target.value),rows:4,placeholder:"Or paste codes here, one per line",className:"font-mono text-xs"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Total queued: ",e.jsx("strong",{children:_().length})," codes (duplicates auto-skipped on save)"]})]})]}),e.jsxs(Ys,{children:[e.jsx(w,{variant:"outline",onClick:()=>n(!1),disabled:W,children:"Cancel"}),e.jsxs(w,{onClick:X,disabled:W,children:[W&&e.jsx(oe,{className:"h-4 w-4 animate-spin mr-1"}),t?"Save":"Create batch"]})]})]})})}function _r({open:s,onOpenChange:n,batch:i,organizationId:t,mode:d="bulk"}){var $e;const r=d==="test",x=Ms(),[c,o]=a.useState("rider"),[m,p]=a.useState(""),[u,l]=a.useState(new Set),[N,j]=a.useState(!1),[g,y]=a.useState(""),k="Hey {first_name}! You just got a new {coupon_label} in your Beyond Pro wallet. View it: {url}",S=(($e=i.sms_template)==null?void 0:$e.trim())||"",[f,h]=a.useState(S||k),[M,T]=a.useState(!!S);a.useEffect(()=>{var pe;const ee=((pe=i.sms_template)==null?void 0:pe.trim())||"";h(ee||k),T(!!ee)},[i.id,i.sms_template]);const[C,L]=a.useState([]),[Q,Z]=a.useState([]),[R,E]=a.useState([]),[$,b]=a.useState([]),[I,V]=a.useState([]),[H,Y]=a.useState(!1),{data:W=[]}=ms({queryKey:["sponsor-assign-search",m],queryFn:async()=>{let ee=z.from("rider_family_members").select("id, first_name, last_name, beyondpro_member_number").is("merged_into_id",null).order("last_name").limit(50);if(m.trim()){const we=m.trim();ee=ee.or(`first_name.ilike.%${we}%,last_name.ilike.%${we}%`)}const{data:pe,error:je}=await ee;if(je)throw je;return pe||[]},enabled:s}),{data:te=0,refetch:B}=ms({queryKey:["sponsor-unassigned-count",i.id],queryFn:async()=>{const{count:ee}=await z.from("sponsor_coupon_codes").select("id",{count:"exact",head:!0}).eq("batch_id",i.id).is("assigned_family_member_id",null);return ee??0},enabled:s}),le=async()=>{var ee;if(C.length===0&&Q.length===0&&R.length===0){K.error("Pick at least a year, series, or event");return}Y(!0);try{const pe=C.length>0?C:[void 0],je=Q.length>0?Q:[void 0],we=R.length>0?R:[void 0],U=$.length>0?$:[void 0],se=new Map;for(const Ue of pe)for(const de of je)for(const Le of we)for(const ye of U){const{data:Ze,error:Ls}=await z.functions.invoke("fetch-sms-recipients",{body:{organization_id:t,year:Ue,series_name:de,event_name:Le,class_name:ye}});if(Ls)throw Ls;for(const P of(Ze==null?void 0:Ze.recipients)||[])typeof P.memberNumber=="number"&&!se.has(P.memberNumber)&&se.set(P.memberNumber,{name:P.name||"",phone:P.phone||null})}const ue=[...se.keys()];if(ue.length===0){V([]),K.info("No riders match this selection");return}const ve=new Map,he=new Map;for(let Ue=0;Ue<ue.length;Ue+=500){const de=ue.slice(Ue,Ue+500),{data:Le,error:ye}=await z.from("rider_family_members").select("id, first_name, last_name, beyondpro_member_number").in("beyondpro_member_number",de).is("merged_into_id",null);if(ye)throw ye;for(const Ze of Le||[])he.set(Ze.id,{first_name:Ze.first_name||"",last_name:Ze.last_name||"",bp:Ze.beyondpro_member_number||null}),Ze.beyondpro_member_number!=null&&ve.set(Number(Ze.beyondpro_member_number),Ze.id)}const ze=[];for(const Ue of ue){const de=ve.get(Ue);if(!de)continue;const Le=he.get(de);ze.push({family_member_id:de,first_name:Le.first_name,last_name:Le.last_name,member_number:Ue,phone:((ee=se.get(Ue))==null?void 0:ee.phone)??null})}const He=new Set,Ve=ze.filter(Ue=>He.has(Ue.family_member_id)?!1:(He.add(Ue.family_member_id),!0));V(Ve),K.success(`Resolved ${Ve.length} rider${Ve.length===1?"":"s"}`)}catch(pe){K.error(pe.message||"Failed to resolve selection")}finally{Y(!1)}},Me=ee=>{if(r&&c==="rider"){const je=new Set(u);je.has(ee)?je.delete(ee):je.add(ee),l(je);return}const pe=new Set(u);pe.has(ee)?pe.delete(ee):pe.add(ee),l(pe)},_=(()=>{const ee=[],pe=new Set;for(const je of g.split(/\r?\n/)){const we=je.trim();if(!we)continue;let U="",se=we;const ue=we.indexOf(",");ue>=0&&(U=we.slice(0,ue).trim(),se=we.slice(ue+1).trim());const ve=se.replace(/[^0-9]/g,""),he=ve.length===11&&ve.startsWith("1")?ve.slice(1):ve.length===10?ve:"";if(!he){ee.push({phone:"",first_name:U,raw:we,error:"Invalid phone"});continue}if(pe.has(he))continue;pe.add(he);const ze=U.split(/\s+/)[0]||"";ee.push({phone:he,first_name:ze,raw:we})}return ee})(),X=_.filter(ee=>ee.phone),F=_.filter(ee=>!ee.phone),ne=()=>c==="selection"?I.map(ee=>ee.family_member_id):c==="manual"?[]:Array.from(u),J=async()=>{var je;const ee=ne(),pe=c==="manual"?X.length:0;if(ee.length===0&&pe===0){K.error(c==="manual"?"Paste at least one valid phone number":"Pick at least one rider");return}if(!r&&c!=="manual"&&i.code_mode==="unique"&&ee.length>te){K.error(`Only ${te} unassigned codes available`);return}j(!0);try{const{data:we}=await z.from("sponsor_coupon_batches").select("sponsor:sponsor_id(name), discount_label").eq("id",i.id).single(),U=((je=we==null?void 0:we.sponsor)==null?void 0:je.name)||i.name,se=(we==null?void 0:we.discount_label)||null;let ue=[];
210if(c==="manual"){if(!r&&i.code_mode==="unique")throw new Error('Manual phone-list sends are only supported for shared-code batches. Switch the batch to "Shared code" or use rider selection.');ue=X.map(Ve=>({kind:"sponsor",coupon_ref_id:i.id,manual_phone:Ve.phone,manual_first_name:Ve.first_name||null,label:U,sponsor_name:U,discount:se}))}else if(r)ue=ee.map(Ve=>({kind:"sponsor",coupon_ref_id:i.id,family_member_id:Ve,label:U,sponsor_name:U,discount:se}));else if(i.code_mode==="unique"){const Ve=Array.from(new Set(ee)),{data:Ue,error:de}=await z.from("sponsor_coupon_codes").select("id, assigned_family_member_id").eq("batch_id",i.id).in("assigned_family_member_id",Ve);if(de)throw de;const Le=new Map;for(const P of Ue||[])P.assigned_family_member_id&&!Le.has(P.assigned_family_member_id)&&Le.set(P.assigned_family_member_id,P.id);const ye=Ve.filter(P=>!Le.has(P));let Ze=[];if(ye.length>0){const{data:P,error:Te}=await z.from("sponsor_coupon_codes").select("id").eq("batch_id",i.id).is("assigned_family_member_id",null).limit(ye.length);if(Te)throw Te;if((P||[]).length<ye.length)throw new Error(`Only ${(P||[]).length} unassigned codes available, need ${ye.length}`);Ze=(P||[]).map((Fe,Ye)=>({id:Fe.id,family_member_id:ye[Ye]}));for(const Fe of Ze){const{error:Ye}=await z.from("sponsor_coupon_codes").update({assigned_family_member_id:Fe.family_member_id,assigned_at:new Date().toISOString()}).eq("id",Fe.id);if(Ye)throw Ye}}ue=[...Array.from(Le.entries()).map(([P,Te])=>({id:Te,family_member_id:P})),...Ze].map(P=>({kind:"sponsor",coupon_ref_id:P.id,family_member_id:P.family_member_id,label:U,sponsor_name:U,discount:se}))}else ue=ee.map(Ve=>({kind:"sponsor",coupon_ref_id:i.id,family_member_id:Ve,label:U,sponsor_name:U,discount:se}));const ve=await pu(t,ue,{testSend:r,messageTemplate:M?f:void 0}),he=(ve==null?void 0:ve.sent)??0,ze=(ve==null?void 0:ve.failed)??0,He=(ve==null?void 0:ve.skipped)??0;K.success(r?`Test sent · ${he} text${he===1?"":"s"} delivered`+(He>0?` · ${He} skipped (no phone)`:"")+(ze>0?` · ${ze} failed`:""):`Assigned ${ee.length} code${ee.length===1?"":"s"}`+(he>0?` · texted ${he} rider${he===1?"":"s"}`:"")+(He>0?` · ${He} skipped (no phone)`:"")),x.invalidateQueries({queryKey:["sponsor-batch-stats",i.id]}),x.invalidateQueries({queryKey:["sponsor-unassigned-count",i.id]}),B(),l(new Set),r||n(!1)}catch(we){K.error(we.message||"Assign failed")}finally{j(!1)}},_e=c==="manual"?X.length:c==="selection"?I.length:u.size,me=c==="selection"?I.filter(ee=>!!ee.phone).length:null;return e.jsx(ts,{open:s,onOpenChange:n,children:e.jsxs(as,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(rs,{children:[e.jsxs(is,{children:[r?"Test send":"Assign codes"," — ",i.name]}),e.jsx(Fs,{children:r?"Test sends do NOT consume codes and do NOT add anything to the rider's wallet — fire as many as you want. SMS arrives with a [TEST] prefix.":`${te} unassigned code${te===1?"":"s"} available${i.code_mode==="shared"?" · shared code batch":""}`})]}),e.jsxs("div",{className:"flex flex-wrap gap-1 rounded-md border p-1 w-fit",children:[e.jsx(w,{size:"sm",variant:c==="rider"?"default":"ghost",onClick:()=>o("rider"),type:"button",children:"By rider"}),e.jsx(w,{size:"sm",variant:c==="selection"?"default":"ghost",onClick:()=>o("selection"),type:"button",children:"By year / series / event / class"}),e.jsx(w,{size:"sm",variant:c==="manual"?"default":"ghost",onClick:()=>o("manual"),type:"button",children:"Manual phone list"})]}),c==="rider"&&e.jsxs(e.Fragment,{children:[e.jsx(A,{placeholder:"Search by name…",value:m,onChange:ee=>p(ee.target.value),autoFocus:!0}),e.jsx("div",{className:"max-h-72 overflow-y-auto rounded-md border divide-y",children:W.length===0?e.jsx("p",{className:"p-3 text-sm text-muted-foreground",children:m?"No matches":"Type to search riders"}):W.map(ee=>e.jsxs("button",{type:"button",onClick:()=>Me(ee.id),className:`w-full text-left px-3 py-2 text-sm hover:bg-muted ${u.has(ee.id)?"bg-primary/10":""}`,children:[e.jsxs("span",{className:"font-medium",children:[ee.first_name," ",ee.last_name]}),ee.beyondpro_member_number&&e.jsxs("span",{className:"text-xs text-muted-foreground ml-2",children:["#",ee.beyondpro_member_number]})]},ee.id))}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[u.size," selected",r&&u.size>1&&" — test will text each one"]})]}),c==="selection"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(Jt,{selectedYears:C,selectedSeries:
210Q,selectedEvents:R,selectedClasses:$,onYearsChange:L,onSeriesChange:Z,onEventsChange:E,onClassesChange:b}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(w,{type:"button",size:"sm",variant:"outline",onClick:le,disabled:H||C.length===0&&Q.length===0&&R.length===0,children:[H&&e.jsx(oe,{className:"h-3.5 w-3.5 animate-spin mr-1"}),"Preview riders"]}),I.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("strong",{children:I.length})," rider",I.length===1?"":"s"," match",me!==null&&` · ${me} with phone on file`,!r&&i.code_mode==="unique"&&I.length>te&&e.jsxs("span",{className:"text-destructive ml-1",children:["· only ",te," codes left, first ",te," will get one"]})]})]}),I.length>0&&e.jsxs("div",{className:"max-h-48 overflow-y-auto rounded-md border divide-y text-sm",children:[I.slice(0,200).map(ee=>e.jsxs("div",{className:"px-3 py-1.5 flex items-center justify-between",children:[e.jsxs("span",{children:[e.jsxs("span",{className:"font-medium",children:[ee.first_name," ",ee.last_name]}),ee.member_number!=null&&e.jsxs("span",{className:"text-xs text-muted-foreground ml-2",children:["#",ee.member_number]})]}),e.jsx("span",{className:`text-xs ${ee.phone?"text-muted-foreground":"text-destructive"}`,children:ee.phone?"✓ phone":"no phone"})]},ee.family_member_id)),I.length>200&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground italic",children:["…and ",I.length-200," more"]})]})]}),c==="manual"&&e.jsxs("div",{className:"space-y-2",children:[!r&&i.code_mode==="unique"&&e.jsx("p",{className:"text-xs text-destructive",children:"Manual phone-list sends only work for shared-code batches (one code blasted to everyone). This batch uses unique codes, so each rider must be picked individually."}),e.jsx(v,{className:"text-sm",children:"Paste recipients — one per line"}),e.jsxs("div",{className:"rounded-md border bg-muted/40 px-3 py-2 text-xs space-y-1",children:[e.jsxs("div",{className:"font-semibold text-foreground",children:["Format: ",e.jsx("code",{className:"bg-background px-1 rounded",children:"Name, Phone"})]}),e.jsx("div",{className:"text-muted-foreground",children:`Name comes first, then a comma, then the phone number. Name is optional — if you skip it the SMS just won't say "Hi [name]".`}),e.jsx("div",{className:"text-muted-foreground",children:"Examples:"}),e.jsx("pre",{className:"text-[11px] font-mono text-foreground leading-snug",children:`John Doe, 555-555-5555
211Jane, (555) 123-4567
212555.987.6543`})]}),e.jsx(Ns,{value:g,onChange:ee=>y(ee.target.value),placeholder:`John Doe, 555-555-5555
213Jane, 555-123-4567`,rows:8,className:"font-mono text-sm"}),e.jsx("div",{className:"text-xs space-y-1",children:e.jsxs("p",{className:"text-muted-foreground",children:[e.jsx("strong",{className:"text-foreground",children:X.length})," valid recipient",X.length===1?"":"s",".",F.length>0&&e.jsxs("span",{className:"text-destructive",children:[" ",F.length," line",F.length===1?"":"s"," couldn't be read."]})," ","Duplicates are removed automatically."]})}),X.length>0&&e.jsxs("div",{className:"max-h-40 overflow-y-auto rounded-md border divide-y text-xs",children:[X.slice(0,100).map(ee=>e.jsxs("div",{className:"px-3 py-1 flex items-center justify-between",children:[e.jsx("span",{className:"text-foreground",children:ee.first_name||e.jsx("em",{className:"text-muted-foreground",children:"(no name)"})}),e.jsx("span",{className:"font-mono text-muted-foreground",children:ee.phone.replace(/(\d{3})(\d{3})(\d{4})/,"($1) $2-$3")})]},ee.phone)),X.length>100&&e.jsxs("div",{className:"px-3 py-1 text-muted-foreground italic",children:["…and ",X.length-100," more"]})]}),F.length>0&&e.jsxs("div",{className:"rounded-md border border-destructive/40 bg-destructive/5 p-2 text-xs",children:[e.jsx("div",{className:"font-semibold text-destructive mb-1",children:"Skipped lines (need a valid 10-digit phone):"}),e.jsx("ul",{className:"space-y-0.5 max-h-24 overflow-y-auto",children:F.slice(0,20).map((ee,pe)=>e.jsx("li",{className:"font-mono text-muted-foreground truncate",children:ee.raw},pe))})]})]}),e.jsxs("div",{className:"space-y-2 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(v,{className:"text-sm",children:"SMS message"}),e.jsx(w,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>{M?(T(!1),h(k)):T(!0)},children:M?"Reset to default":"Customize message"})]}),M?e.jsxs(e.Fragment,{children:[e.jsx(Ns,{value:f,onChange:ee=>h(ee.target.value),rows:3,className:"text-sm",placeholder:k}),e.jsxs("p",{className:"text-[11px] text-muted-foreground leading-snug",children:["Placeholders: ",e.jsx("code",{className:"bg-muted px-1 rounded",children:"{first_name}"})," ",e.jsx("code",{className:"bg-muted px-1 rounded",children:"{coupon_label}"})," ",e.jsx("code",{className:"bg-muted px-1 rounded",children:"{sponsor}"})," ",e.jsx("code",{className:"bg-muted px-1 rounded",children:"{discount}"})," ",e.jsx("code",{className:"bg-muted px-1 rounded",children:"{url}"})," ",e.jsx("code",{className:"bg-muted px-1 rounded",children:"{org}"}),". The ",e.jsx("code",{className:"bg-muted px-1 rounded",children:"{url}"})," link is required so recipients can open the coupon."]}),!f.includes("{url}")&&e.jsxs("p",{className:"text-[11px] text-amber-600",children:["⚠ Your message doesn't include ","{url}"," — recipients won't get a link to the coupon."]})]}):e.jsxs("p",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:[e.jsx("span",{className:"text-foreground",children:"Default:"})," ",k]})]}),e.jsxs(Ys,{children:[e.jsx(w,{variant:"outline",onClick:()=>n(!1),disabled:N,children:r?"Done":"Cancel"}),e.jsxs(w,{onClick:J,disabled:N||_e===0||!r&&c!=="manual"&&i.code_mode==="unique"&&te===0||!r&&c==="manual"&&i.code_mode==="unique",children:[N&&e.jsx(oe,{className:"h-4 w-4 animate-spin mr-1"}),r?e.jsxs(e.Fragment,{children:[e.jsx(gt,{className:"h-4 w-4 mr-1"})," Send test to ",_e]}):c==="manual"?e.jsxs(e.Fragment,{children:[e.jsx(gt,{className:"h-4 w-4 mr-1"})," Text ",_e," number",_e===1?"":"s"]}):`Assign ${Math.min(_e,i.code_mode==="unique"?te:_e)}`]})]})]})})}function yu(){const[s,n]=a.useState("reg-coupons"),{currentOrganization:i}=Je(),{isTimingEnabled:t}=Wt(),[d,r]=a.useState(!1),[x,c]=a.useState(null),[o,m]=a.useState(0),[p,u]=a.useState(!1),[l,N]=a.useState(!1),[j,g]=a.useState(0),[y,k]=a.useState(null),S=async()=>
213{if(i!=null&&i.id){u(!0),c(null),k(null),r(!0);try{const{data:h,error:M}=await z.functions.invoke("sync-pos-coupons",{body:{organization_id:i.id,mode:"preview"}});if(M)throw M;c(h.mysql),m(h.existing_coupons||0)}catch(h){K.error("Failed to preview: "+(h.message||"Unknown error")),r(!1)}finally{u(!1)}}},f=async()=>{if(i!=null&&i.id){N(!0),g(10);try{const h=setInterval(()=>{g(C=>Math.min(C+5,90))},1e3),{data:M,error:T}=await z.functions.invoke("sync-pos-coupons",{body:{organization_id:i.id,mode:"import"}});if(clearInterval(h),T)throw T;g(100),k(M.results),K.success("Import complete!")}catch(h){K.error("Import failed: "+(h.message||"Unknown error"))}finally{N(!1)}}};return e.jsxs("div",{className:"space-y-4",children:[t&&e.jsx("div",{className:"flex justify-end",children:e.jsxs(w,{variant:"outline",size:"sm",onClick:S,className:"gap-2",children:[e.jsx($t,{className:"h-4 w-4"}),"Import from Timing System"]})}),e.jsxs(ot,{value:s,onValueChange:n,className:"w-full",children:[e.jsxs(pt,{className:"flex-wrap h-auto gap-1 p-1",children:[e.jsxs(Qe,{value:"reg-coupons",className:"gap-2",children:[e.jsx(hd,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Registration Coupons"})]}),e.jsxs(Qe,{value:"offers",className:"gap-2",children:[e.jsx(Di,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Offers"})]}),e.jsxs(Qe,{value:"coupons",className:"gap-2",children:[e.jsx(Na,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Coupons"})]}),e.jsxs(Qe,{value:"bulk",className:"gap-2",children:[e.jsx(za,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Send Coupon"})]}),e.jsxs(Qe,{value:"templates",className:"gap-2",children:[e.jsx(Fi,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Templates"})]}),e.jsxs(Qe,{value:"redemptions",className:"gap-2",children:[e.jsx(Pa,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Redemptions"})]}),e.jsxs(Qe,{value:"packs",className:"gap-2",children:[e.jsx(va,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Packs"})]}),e.jsxs(Qe,{value:"sponsors",className:"gap-2",children:[e.jsx(Nn,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Sponsors"})]})]}),e.jsx(Ae,{value:"reg-coupons",className:"mt-6",children:e.jsx(mu,{})}),e.jsx(Ae,{value:"offers",className:"mt-6",children:e.jsx(au,{})}),e.jsx(Ae,{value:"coupons",className:"mt-6",children:e.jsx(nu,{})}),e.jsx(Ae,{value:"bulk",className:"mt-6",children:e.jsx(iu,{})}),e.jsx(Ae,{value:"templates",className:"mt-6",children:e.jsx(ou,{})}),e.jsx(Ae,{value:"redemptions",className:"mt-6",children:e.jsx(du,{})}),e.jsx(Ae,{value:"packs",className:"mt-6",children:e.jsx(hu,{})}),e.jsx(Ae,{value:"sponsors",className:"mt-6",children:e.jsx(gu,{})})]}),e.jsx(ts,{open:d,onOpenChange:r,children:e.jsxs(as,{className:"sm:max-w-md",children:[e.jsxs(rs,{children:[e.jsx(is,{children:"Import Coupon Data"}),e.jsx(Fs,{children:"Import your existing coupon data from the timing system database."})]}),p&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(oe,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),x&&!y&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-lg border p-4 space-y-2 text-sm",children:[e.jsx("h4",{className:"font-medium",children:"Found in MySQL:"}),e.jsxs("div",{className:"grid grid-cols-2 gap-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"Templates:"}),e.jsx("span",{className:"font-medium",children:x.templates}),e.jsx("span",{className:"text-muted-foreground",children:"Coupons:"}),e.jsx("span",{className:"font-medium",children:x.coupons}),e.jsx("span",{className:"text-muted-foreground",children:"Redemptions:"}),e.jsx("span",{className:"font-medium",children:x.redemptions}),e.jsx("span",{className:"text-muted-foreground",children:"Staff Logins:"}),e.jsx("span",{className:"font-medium",children:x.pos_users})]}),o>0&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[o," coupons already exist and will be skipped."]})]}),l&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ka,{value:j,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Importing..."})]})]}),y&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-primary",children:[e.jsx(Yn,{className:"h-5 w-5"}),e.jsx("span",{className:"font-medium",children:"Import Complete"})]}),e.jsx("div",{className:"rounded-lg border p-4 space-y-1 text-sm",children:[{label:"Templates",data:y.templates},{label:"Offers",data:y.offers},{label:"Coupons",data:y.coupons},{label:"Staff Logins",data:y.pos_users},{label:"Redemptions",data:y.redemptions}].map(({label:h,data:M})=>e.jsxs("div",{className:"flex justify-between",children:[e.jsxs("span",{className:"text-muted-foreground",children:[h,":"]}),e.jsxs("span",{children:[e.jsxs("span",{className:"font-medium text-primary",children:[M.imported," imported"]}),M.skipped>0&&e.jsxs("span",{className:"text-muted-foreground ml-1",children:["(",M.skipped," skipped)"]})]})]},h))})]}),e.jsx(Ys,{children:y?e.jsx(w,{onClick:()=>{r(!1),k(null),c(null)},children:"Done"}):e.jsxs(e.Fragment,{children:[e.jsx(w,{variant:"outline",onClick:()=>r(!1),disabled:l,children:"Cancel"}),e.jsx(w,{onClick:f,disabled:!x||l,children:l?e.jsxs(e.Fragment,{children:[e.jsx(oe,{className:"h-4 w-4 animate-spin mr-2"})," Importing..."]}):"Start Import"})]})})]})})]})}function _u(){const{currentOrganization:s}=Je(),n=Ms();return ks({mutationFn:async({eventName:i,raceOrder:t})=>{if(!(s!=null&&s.id))throw new Error("No organization selected");const{data:d,error:r}=await z.functions.invoke("save-race-order",{body:{organization_id:s.id,event_name:i,race_order:t}});if(r)throw r;return d},onSuccess:(i,t)=>{be({title:"Race order saved",description:`Updated ${i.updated} class positions.`}),n.invalidateQueries({queryKey:["class-entries",t.eventName]}),n.invalidateQueries({queryKey:["mysql-classes"]}
213),n.invalidateQueries({queryKey:["mysql-events"]})},onError:i=>{be({title:"Error saving race order",description:i.message,variant:"destructive"})}})}const Ma=["bg-blue-100 border-blue-300 text-blue-800","bg-green-100 border-green-300 text-green-800","bg-amber-100 border-amber-300 text-amber-800","bg-purple-100 border-purple-300 text-purple-800","bg-rose-100 border-rose-300 text-rose-800"];function Ta(s,n){const[i,t]=s.split(":").map(Number),d=i*60+t+n,r=Math.floor(d/60)%24,x=d%60;return`${String(r).padStart(2,"0")}:${String(x).padStart(2,"0")}`}function Ut(s){const[n,i]=s.split(":").map(Number),t=n>=12?"PM":"AM";return`${n%12||12}:${String(i).padStart(2,"0")} ${t}`}function ha(s){var d;const n=s.crossBlockRiders.length,i=s.threeBlockViolations.length,t=((d=s.backToBackConflicts)==null?void 0:d.length)||0;return{total:n+i*5+t*2,crossBlockRiders:n,threeBlockViolations:i,backToBackConflicts:t}}function yl(s,n=[]){const i=new Set,t=[];for(const d of s){if(i.has(d.name))continue;const r=n.find(c=>c.includes(d.name)),x=r?s.filter(c=>r.includes(c.name)):[d];x.forEach(c=>i.add(c.name)),t.push(x)}return t}function Sn(s,n,i=[],t){const d=yl(n,i),r=[];for(let x=1;x<=t;x+=1)d.forEach((c,o)=>{const m=c.map(p=>p.name).join("__");r.push({id:`${s}-${x}-${o}-${m}`,moto:x,classes:c,riderCount:c.reduce((p,u)=>p+u.riderCount,0)})});return r}function wr(s,n=[],i){return s.map((t,d)=>{if(t.aiRaceSlots&&t.aiRaceSlots.length>0){const r=[],x=new Set;for(let c=0;c<t.aiRaceSlots.length;c++){if(x.has(c))continue;const o=t.aiRaceSlots[c],m=n.find(p=>p.includes(o.className));if(m){const p=[],u=t.classes.find(l=>l.name===o.className)||{name:o.className,riderCount:0,category:"Unknown"};p.push(u),x.add(c);for(let l=c+1;l<t.aiRaceSlots.length;l++){const N=t.aiRaceSlots[l];if(N.moto===o.moto&&m.includes(N.className)&&!x.has(l)){const j=t.classes.find(g=>g.name===N.className)||{name:N.className,riderCount:0,category:"Unknown"};p.push(j),x.add(l)}else break}r.push({id:`${d}-ai-${c}-${p.map(l=>l.name).join("__")}-M${o.moto}`,moto:o.moto,classes:p,riderCount:p.reduce((l,N)=>l+N.riderCount,0)})}else{const p=t.classes.find(u=>u.name===o.className)||{name:o.className,riderCount:0,category:"Unknown"};x.add(c),r.push({id:`${d}-ai-${c}-${o.className}-M${o.moto}`,moto:o.moto,classes:[p],riderCount:p.riderCount})}}return{...t,scheduleUnits:r}}return{...t,scheduleUnits:Sn(d,t.classes,n,i)}})}function Ra(s,n,i=[]){var o;const t=new Map;s.forEach((m,p)=>{m.classes.forEach(u=>t.set(u.name,p))});const d=new Map;for(const m of n){const p=t.get(m.classA),u=t.get(m.classB);if(!(p==null||u==null)&&p!==u)for(const l of m.sharedRiders)d.has(l)||d.set(l,new Set),d.get(l).add(p+1),d.get(l).add(u+1)}const r=[],x=[];d.forEach((m,p)=>{if(m.size>=2){const u={name:p,memberNumber:0,blocks:Array.from(m).sort()};r.push(u),m.size>=3&&x.push(u)}});const c=[];for(const m of s){const p=(o=m.scheduleUnits)!=null&&o.length?m.scheduleUnits.map(u=>u.classes.map(l=>l.name)):yl(m.classes,i).map(u=>u.map(l=>l.name));for(let u=0;u<p.length-1;u++){const l=p[u],N=p[u+1];for(const j of l)for(const g of N){const y=n.find(k=>k.classA===j&&k.classB===g||k.classA===g&&k.classB===j);if(y&&y.sharedCount>0)for(const k of y.sharedRiders)c.push({blockNumber:m.blockNumber,blockLabel:m.label,riderName:k,memberNumber:0,class1:j,class2:g})}}}return{crossBlockRiders:r,threeBlockViolations:x,backToBackConflicts:c}}function wu({id:s,groupClasses:n,moto:i,raceNumber:t,raceStart:d,lockState:r,onCycleLock:x,combined:c}){var f;const{attributes:o,listeners:m,setNodeRef:p,transform:u,transition:l,isDragging:N}=xo({id:s}),j={transform:po.Transform.toString(u),transition:l,opacity:N?.4:1},g=n.reduce((h,M)=>h+M.riderCount,0),y=c?`${n.length} classes`:((f=n[0])==null?void 0:f.category)||"Class",k=r==="position"?"text-amber-600":r==="block"?"text-primary":"text-muted-foreground/40",S=r==="none"?"Click to lock to this block (then again to pin exact race position)":r==="block"?"Locked to block — click to pin to this exact race position":"Pinned to exact position — click to unlock";return e.jsxs("div",{ref:p,style:j,className:`flex items-center justify-between bg-background/60 rounded px-2 py-1 text-sm ${r==="position"?"ring-1 ring-amber-400/60":""}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{...o,...m,className:"cursor-grab active:cursor-grabbing p-0.5 text-muted-foreground
213/40 hover:text-muted-foreground",children:e.jsx(Li,{className:"h-3 w-3"})}),e.jsx("button",{onClick:h=>{h.stopPropagation(),x()},className:`p-0.5 rounded hover:bg-muted ${k}`,title:S,children:r==="none"?e.jsx(Yr,{className:"h-3 w-3"}):e.jsx(ct,{className:"h-3 w-3"})}),r==="position"&&e.jsx(ie,{variant:"outline",className:"text-[10px] px-1 py-0 border-amber-400 text-amber-700 bg-amber-50",children:"PINNED"}),e.jsxs(ie,{variant:"outline",className:"min-w-12 justify-center font-mono text-xs",children:["#",t]}),e.jsxs(ie,{variant:"secondary",className:"font-mono text-xs",children:["M",i]}),d&&e.jsxs("span",{className:"text-xs text-muted-foreground font-mono w-16",children:["~",Ut(d)]}),e.jsx("span",{children:n.map(h=>h.name).join(" / ")}),c&&e.jsx(ie,{variant:"outline",className:"text-xs",children:"combined"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx(ie,{variant:"outline",className:"text-xs",children:y}),e.jsxs("span",{className:"text-muted-foreground",children:[g," riders"]})]})]})}function Su({eventName:s,onApply:n}){var ls,Bs;const i=Gt(),{currentOrganization:t}=Je(),d=_u(),[r,x]=a.useState(3),[c,o]=a.useState(!0),[m,p]=a.useState(!0),[u,l]=a.useState(2),[N,j]=a.useState("08:00"),[g,y]=a.useState([{label:"Block A",startTime:"08:00",practiceDuration:30,raceDuration:8},{label:"Block B",startTime:"",practiceDuration:30,raceDuration:8},{label:"Block C",startTime:"",practiceDuration:30,raceDuration:8}]),[k,S]=a.useState(!1),[f,h]=a.useState(null),[M,T]=a.useState(new Set),[C,L]=a.useState(!1),[Q,Z]=a.useState(!1),[R,E]=a.useState([]),[$,b]=a.useState(!0),[I,V]=a.useState(!1),[H,Y]=a.useState(!1),[W,te]=a.useState({}),[B,le]=a.useState([]),[Me,_]=a.useState({}),[X,F]=a.useState(!1),[ne,J]=a.useState(!1),[_e,me]=a.useState([]),[$e,ee]=a.useState(!1),[pe,je]=a.useState(new Set),[we,U]=a.useState([]),[se,ue]=a.useState([]),[ve,he]=a.useState([]),[ze,He]=a.useState(!1),[Ve,Ue]=a.useState(!1),[de,Le]=a.useState(null),[ye,Ze]=a.useState(!1),[Ls,P]=a.useState(""),Te=io(lo(co,{activationConstraint:{distance:5}})),Fe=async()=>{if(!(!(t!=null&&t.id)||!s||H)){V(!0);try{const{data:q,error:ge}=await z.functions.invoke("fetch-timing-classes",{body:{organization_id:t.id,event_name:s}});if(ge)throw ge;const fe=(q==null?void 0:q.classes)||[],Re=[...new Set(fe.map(Ke=>Ke.class_name))].sort();E(Re.map(Ke=>({className:Ke,priority:"none",forceBlock:null,combineWith:null}))),Y(!0)}catch(q){console.error("Failed to load classes for priorities:",q)}finally{V(!1)}}},Ye=async()=>{if(!(!(t!=null&&t.id)||!s)){J(!0);try{const{data:q,error:ge}=await z.functions.invoke("fetch-optimizer-data",{body:{organization_id:t.id,event_name:s}});if(ge)throw ge;te((q==null?void 0:q.entryCounts)||{}),le((q==null?void 0:q.conflicts)||[]),_((q==null?void 0:q.ageStats)||{})}catch(q){console.error("Failed to load optimizer data:",q)}finally{J(!1)}}},Xe=async()=>{if(!(t!=null&&t.id))return;const{data:q}=await z.from("optimization_history").select("*").eq("organization_id",t.id).order("created_at",{ascending:!1}).limit(20);he(q||[])};a.useEffect(()=>{Fe()},[t==null?void 0:t.id,s]),a.useEffect(()=>{Ye()},[t==null?void 0:t.id,s]),a.useEffect(()=>{Xe()},[t==null?void 0:t.id,s]);const bs=q=>{x(q);const ge=["Block A","Block B","Block C","Block D","Block E"],fe=[];for(let Re=0;Re<q;Re++)fe.push(g[Re]||{label:ge[Re]||`Block ${Re+1}`,startTime:"",practiceDuration:30,raceDuration:8});y(fe),h(null)},Ts=(q,ge,fe)=>{E(Re=>Re.map((Ke,Oe)=>Oe===q?{...Ke,[ge]:fe}:Ke))},Ps=(q,ge,fe)=>{y(Re=>Re.map((Ke,Oe)=>Oe===q?{...Ke,[ge]:fe}:Ke))},Rs=(q,ge=[])=>{const fe=new Set;let Re=0;for(const Ke of q){if(fe.has(Ke.name))continue;const Oe=ge.find(hs=>hs.includes(Ke.name));Oe?Oe.forEach(hs=>fe.add(hs)):fe.add(Ke.name),Re++}return Re},D=(q,ge=[])=>{let fe=N;return q.map((Re,Ke)=>{const Oe=g[Ke],hs=Ke===0?N:fe,os=Rs(Re.classes,ge),_s=(Oe==null?void 0:Oe.practiceDuration)||30,it=os*((Oe==null?void 0:Oe.raceDuration)||8),gs=Ta(hs,_s),fs=Ta(gs,it),dt=u>=2?Ta(fs,it):fs;return fe=dt,{...Re,startTime:hs,raceDuration:(Oe==null?void 0:Oe.raceDuration)||8,practiceEndTime:gs,moto1EndTime:fs,moto2EndTime:u>=2?dt:void 0,racingEndTime:dt}})},O=a.useMemo(()=>{const q=R.length||10;Object.values(W).reduce((Re,Ke)=>Re+Ke,0)||q*15;const ge=2e3+q*50+Math.min(B.length,50)*30,fe=500+q*20;return{input:ge,output:fe,total:ge+fe}},[R.length,W,B.length]),Ne=a.useMemo(()=>(O.input*15e-5+O.output*6e-4).toFixed(4),[O]),Se=a.useMemo(()=>
213{if(B.length===0)return null;const q=B.filter(fe=>fe.sharedCount>=5),ge=new Set;return B.forEach(fe=>fe.sharedRiders.forEach(Re=>ge.add(Re))),{highConflictPairs:q,totalMultiClassRiders:ge.size,totalConflictPairs:B.length}},[B]),us=()=>{Ue(!0)},ps=async()=>{if(t!=null&&t.id){Ue(!1),S(!0),h(null),Le(null);try{const q=g.map((gs,fs)=>({...gs,startTime:fs===0?N:""})),ge=new Map;f&&f.blocks.forEach((gs,fs)=>{gs.classes.forEach(dt=>{pe.has(dt.name)&&ge.set(dt.name,fs+1)})}),we.forEach(gs=>gs.classNames.forEach(fs=>ge.set(fs,gs.block))),se.forEach(gs=>{ge.has(gs.className)||ge.set(gs.className,gs.block)});const fe=R.map(gs=>{const fs=ge.get(gs.className);return fs!=null&&gs.forceBlock==null?{...gs,forceBlock:fs}:gs}),{data:Re,error:Ke}=await z.functions.invoke("optimize-race-blocks",{body:{organization_id:t.id,event_name:s,block_count:r,blocks_config:q,moto_count:u,even_blocks:c,mirror_motos:m,class_priorities:fe.filter(gs=>gs.priority!=="none"||gs.forceBlock!=null||gs.combineWith!=null),race_locks:we,practice_locks:se}});if(Ke)throw Ke;if(Re.error)throw new Error(Re.error);const Oe=wr(D(Re.blocks,Re.combinedGroups||[]),Re.combinedGroups||[],u),hs={...Re,blocks:Oe},os=Ra(Oe,B,Re.combinedGroups||[]),_s={...hs,crossBlockRiders:os.crossBlockRiders,threeBlockViolations:os.threeBlockViolations,backToBackConflicts:os.backToBackConflicts};h(_s),T(new Set(Re.blocks.map((gs,fs)=>fs))),Re.usage&&Le({prompt:Re.usage.prompt_tokens||0,completion:Re.usage.completion_tokens||0,cost:Re.usage.total_cost||0});const it=ha(_s);me(gs=>[{result:_s,score:it,timestamp:Date.now(),lockedClasses:new Set(pe)},...gs].slice(0,5)),be({title:"Block schedule generated",description:`${Re.blocks.length} blocks with ${Re.totalClasses} classes optimized. Score: ${it.total}`})}catch(q){be({title:"Optimization failed",description:q.message,variant:"destructive"})}finally{S(!1)}}},xs=async()=>{var Re;if(!f||!(t!=null&&t.id))return;const q=[];let ge=1;for(const[Ke,Oe]of f.blocks.entries()){const hs=(Re=Oe.scheduleUnits)!=null&&Re.length?Oe.scheduleUnits:Sn(Ke,Oe.classes,f.combinedGroups||[],u);for(const os of hs)q.push({slot:ge,moto:os.moto,classes:os.classes.map(_s=>_s.name),riderCount:os.riderCount}),ge++}await d.mutateAsync({eventName:s,raceOrder:q});const fe=ha(f);await z.from("optimization_history").insert({organization_id:t.id,event_name:s,block_count:r,total_classes:f.totalClasses,total_riders:f.totalRiders,cross_block_riders:fe.crossBlockRiders,three_block_violations:fe.threeBlockViolations,back_to_back_conflicts:fe.backToBackConflicts,conflict_score:fe.total,name:`Applied: ${s} - ${new Date().toLocaleDateString()}`,result_data:{blocks:f.blocks.map(Ke=>({label:Ke.label,classes:Ke.classes,totalRiders:Ke.totalRiders,aiRaceSlots:Ke.aiRaceSlots||(Ke.scheduleUnits||[]).map(Oe=>Oe.classes.map(hs=>({className:hs.name,moto:Oe.moto}))).flat()})),reasoning:f.reasoning,combinedGroups:f.combinedGroups}}),Xe(),n==null||n()},G=async()=>{if(!(!f||!(t!=null&&t.id))){Ze(!0);try{const q=ha(f),ge=Ls.trim()||`${s} - ${new Date().toLocaleString()}`;await z.from("optimization_history").insert({organization_id:t.id,event_name:s,block_count:r,total_classes:f.totalClasses,total_riders:f.totalRiders,cross_block_riders:q.crossBlockRiders,three_block_violations:q.threeBlockViolations,back_to_back_conflicts:q.backToBackConflicts,conflict_score:q.total,name:ge,result_data:{blocks:f.blocks.map(fe=>({label:fe.label,classes:fe.classes,totalRiders:fe.totalRiders,aiRaceSlots:fe.aiRaceSlots||(fe.scheduleUnits||[]).map(Re=>Re.classes.map(Ke=>({className:Ke.name,moto:Re.moto}))).flat()})),reasoning:f.reasoning,combinedGroups:f.combinedGroups,savedOnly:!0}}),await Xe(),P(""),be({title:"Schedule saved",description:`Saved as "${ge}". You can load and compare it later.`})}catch(q){be({title:"Failed to save",description:q.message,variant:"destructive"})}finally{Ze(!1)}}},De=async q=>{try{await z.from("optimization_history").delete().eq("id",q),he(ge=>ge.filter(fe=>fe.id!==q)),be({title:"Schedule deleted"})}catch(ge){be({title:"Failed to delete",description:ge.message,variant:"destructive"})}},ds=q=>{try{const ge=q.result_data;if(!(ge!=null&&ge.blocks)){be({title:"Cannot load",description:"This run does not have detailed block data.",variant:"destructive"});return}const fe=ge.blocks.map((os,_s)=>({blockNumber:_s+1,label:os.label||`Block ${String.fromCharCode(65+_s)}`,startTime:"",practiceDuration:30,raceDuration:8,classes:(os.classes||[]).map(it=>typeof it=="string"?{name:it,riderCount:W[it]||0,category:""}:it),totalRiders:os.totalRiders||0,aiRaceSlots:os.aiRaceSlots||void 0})),Re=ge.combinedGroups||[],Ke=wr(D(fe,Re),Re,u),Oe=Ra(Ke,B,Re),hs={blocks:Ke,crossBlockRiders:Oe.crossBlockRiders,threeBlockViolations:Oe.threeBlockViolations,backToBackConflicts:Oe.backToBackConflicts,combinedGroups:Re,reasoning:ge.reasoning||"",totalClasses:Ke.reduce((os,_s)=>os+_s.classes.length,0),totalRiders:Ke.reduce((os,_s)=>os+_s.totalRiders,0)};h(hs),T(new Set(Ke.map((os,_s)=>
213_s))),x(Ke.length),be({title:"Schedule loaded",description:`Loaded ${Ke.length}-block schedule from ${new Date(q.created_at).toLocaleString()}.`})}catch(ge){be({title:"Failed to load",description:ge.message,variant:"destructive"})}},Ge=q=>{if(!f)return;const{active:ge,over:fe}=q;if(!fe||ge.id===fe.id)return;const Re=String(ge.id),Ke=String(fe.id),Oe=f.blocks.findIndex(lt=>(lt.scheduleUnits||[]).some(qt=>qt.id===Re)),hs=f.blocks.findIndex(lt=>(lt.scheduleUnits||[]).some(qt=>qt.id===Ke));if(Oe===-1||hs===-1)return;if(Oe!==hs){be({title:"Move not allowed",description:"You can reorder races across motos within a block.",variant:"destructive"});return}const os=f.blocks[Oe].scheduleUnits||[],_s=os.findIndex(lt=>lt.id===Re),it=os.findIndex(lt=>lt.id===Ke);if(_s===-1||it===-1)return;const gs=f.blocks.map((lt,qt)=>qt===Oe?{...lt,scheduleUnits:go(lt.scheduleUnits||[],_s,it)}:lt),fs=Ra(gs,B,f.combinedGroups||[]),dt={...f,blocks:gs,crossBlockRiders:fs.crossBlockRiders,threeBlockViolations:fs.threeBlockViolations,backToBackConflicts:fs.backToBackConflicts};h(dt)},ss=()=>{if(!f)return;const q=Ra(f.blocks,B,f.combinedGroups||[]),ge={...f,crossBlockRiders:q.crossBlockRiders,threeBlockViolations:q.threeBlockViolations,backToBackConflicts:q.backToBackConflicts};h(ge),be({title:"Re-analyzed",description:`Score: ${ha(ge).total}`})},es=q=>{T(ge=>{const fe=new Set(ge);return fe.has(q)?fe.delete(q):fe.add(q),fe})},cs=q=>we.some(ge=>ge.classNames.some(fe=>q.includes(fe)))?"position":q.some(ge=>pe.has(ge))?"block":"none",ys=(q,ge,fe,Re)=>{const Ke=cs(q);Ke==="none"?je(Oe=>{const hs=new Set(Oe);return q.forEach(os=>hs.add(os)),hs}):Ke==="block"?(je(Oe=>{const hs=new Set(Oe);return q.forEach(os=>hs.delete(os)),hs}),U(Oe=>[...Oe.filter(hs=>!hs.classNames.some(os=>q.includes(os))),{classNames:q,block:ge,moto:fe,raceIndex:Re}])):U(Oe=>Oe.filter(hs=>!hs.classNames.some(os=>q.includes(os))))},Ce=pe.size+we.length,ft=()=>{je(new Set),U([]),ue([])},It=a.useMemo(()=>f!=null&&f.blocks.length?f.blocks[f.blocks.length-1].racingEndTime:null,[f]),Ct=a.useMemo(()=>f?ha(f):null,[f]),ce=q=>q>=5?"bg-red-100 text-red-800 border-red-300":q>=2?"bg-amber-100 text-amber-800 border-amber-300":"bg-green-100 text-green-800 border-green-300",vs=(q,ge)=>{var fe;return(fe=q.scheduleUnits)!=null&&fe.length?q.scheduleUnits:Sn(ge,q.classes,(f==null?void 0:f.combinedGroups)||[],u)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsxs(Ee,{className:"flex items-center gap-2",children:[e.jsx(aa,{className:"h-5 w-5 text-primary"}),"AI Block Scheduler"]}),e.jsxs(ns,{children:["Configure arrival blocks for ",e.jsx("span",{className:"font-semibold text-foreground",children:s}),". Each block starts with practice, then uses one numbered race list where motos can be mixed manually."]})]}),e.jsxs(xe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(v,{children:"Blocks"}),e.jsxs(Pe,{value:String(r),onValueChange:q=>bs(Number(q)),children:[e.jsx(Ie,{className:"w-28 bg-background",children:e.jsx(qe,{})}),e.jsx(Be,{className:"bg-popover border-border z-50",children:[1,2,3,4,5].map(q=>e.jsxs(ae,{value:String(q),children:[q," ",q===1?"block":"blocks"]},q))})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(v,{children:"Motos"}),e.jsxs(Pe,{value:String(u),onValueChange:q=>l(Number(q)),children:[e.jsx(Ie,{className:"w-28 bg-background",children:e.jsx(qe,{})}),e.jsx(Be,{className:"bg-popover border-border z-50",children:[1,2,3].map(q=>e.jsxs(ae,{value:String(q),children:[q," moto",q>1?"s":""]},q))})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(v,{children:"First Block Start"}),e.jsx(A,{type:"time",value:N,onChange:q=>j(q.target.value),className:"w-32 bg-background"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ds,{id:"even-blocks",checked:c,onCheckedChange:o}),e.jsx(v,{htmlFor:"even-blocks",className:"text-sm cursor-pointer",children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(fo,{className:"h-3.5 w-3.5"}),"Balance blocks evenly"]}
213)})]}),u>1&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ds,{id:"mirror-motos",checked:m,onCheckedChange:p}),e.jsx(v,{htmlFor:"mirror-motos",className:"text-sm cursor-pointer",children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(kt,{className:"h-3.5 w-3.5"}),"Mirror moto order"]})})]})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[c?"Blocks will have roughly equal class counts and rider counts (±2 classes, ±15% riders).":"Blocks can be uneven — useful for running a quick first block then the rest after.",u>1&&(m?" Moto orders will be identical — M1 and M2 run the same class sequence.":" Motos are interleaved into one continuous race order — M1 and M2 can be mixed freely.")]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("button",{onClick:()=>b(!$),className:"flex items-center gap-2 text-sm font-semibold text-foreground",children:[$?e.jsx(mt,{className:"h-4 w-4"}):e.jsx(Hs,{className:"h-4 w-4"}),"Class Priorities, Blocks & Combining"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Set early/late priority, force a class into a specific block, or combine classes to share a gate."}),$&&e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-2",children:[e.jsxs("div",{className:"grid grid-cols-[1fr_auto_auto_auto_auto] gap-2 text-xs font-semibold text-muted-foreground px-1",children:[e.jsx("span",{children:"Class"}),e.jsx("span",{className:"w-14 text-center",children:i.racers}),e.jsx("span",{className:"w-28 text-center",children:"Priority"}),e.jsx("span",{className:"w-28 text-center",children:"Force Block"}),e.jsx("span",{className:"w-36 text-center",children:"Combine With"})]}),I?e.jsx("p",{className:"text-xs text-muted-foreground py-2",children:"Loading classes..."}):R.length===0?e.jsx("p",{className:"text-xs text-muted-foreground py-2",children:"No classes found for this event."}):R.map((q,ge)=>e.jsxs("div",{className:"grid grid-cols-[1fr_auto_auto_auto_auto] gap-2 items-center",children:[e.jsx("span",{className:"text-sm font-medium truncate",title:q.className,children:q.className}),e.jsx("span",{className:"w-14 text-center text-sm",children:ne?e.jsx(oe,{className:"h-3 w-3 animate-spin mx-auto"}):e.jsxs(ie,{variant:"secondary",className:"text-xs",children:[e.jsx(Gs,{className:"h-3 w-3 mr-1"}),W[q.className]||0]})}),e.jsxs(Pe,{value:q.priority,onValueChange:fe=>Ts(ge,"priority",fe),children:[e.jsx(Ie,{className:"w-28 h-8 text-xs bg-background",children:e.jsx(qe,{})}),e.jsxs(Be,{className:"bg-popover border-border z-50",children:[e.jsx(ae,{value:"none",children:"— Not Set —"}),e.jsx(ae,{value:"early",children:"🔴 Early"}),e.jsx(ae,{value:"normal",children:"🟡 Normal"}),e.jsx(ae,{value:"late",children:"🔵 Late"})]})]}),e.jsxs(Pe,{value:q.forceBlock!=null?String(q.forceBlock):"none",onValueChange:fe=>Ts(ge,"forceBlock",fe==="none"?null:Number(fe)),children:[e.jsx(Ie,{className:"w-28 h-8 text-xs bg-background",children:e.jsx(qe,{})}),e.jsxs(Be,{className:"bg-popover border-border z-50",children:[e.jsx(ae,{value:"none",children:"— Auto —"}),Array.from({length:r},(fe,Re)=>e.jsxs(ae,{value:String(Re+1),children:["Block ",String.fromCharCode(65+Re)]},Re+1))]})]}),e.jsxs(Pe,{value:q.combineWith||"none",onValueChange:fe=>Ts(ge,"combineWith",fe==="none"?null:fe),children:[e.jsx(Ie,{className:"w-36 h-8 text-xs bg-background",children:e.jsx(qe,{})}),e.jsxs(Be,{className:"bg-popover border-border z-50",children:[e.jsx(ae,{value:"none",children:"— Solo —"}),R.filter(fe=>fe.className!==q.className).map(fe=>e.jsx(ae,{value:fe.className,children:fe.className},fe.className))]})]})]},q.className))]})]}),e.jsx(St,{}),Se&&!ne&&e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-foreground",children:[e.jsx(Is,{className:"h-4 w-4 text-amber-500"}),"Pre-Optimization Summary"]}),e.jsxs("div",{className:"flex flex-wrap gap-4 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Gs,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:[e.jsx("strong",{children:Se.totalMultiClassRiders})," riders in 2+ classes"]}
213)]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(sa,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:[e.jsx("strong",{children:Se.totalConflictPairs})," conflicting class pairs"]})]})]}),Se.highConflictPairs.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-destructive",children:"⚠ High-conflict pairs (5+ shared riders) — best kept in the same block:"}),Se.highConflictPairs.slice(0,8).map((q,ge)=>e.jsxs("div",{className:"flex items-center justify-between rounded px-2 py-1 bg-red-50 border border-red-200 text-sm",children:[e.jsxs("span",{children:[q.classA," ↔ ",q.classB]}),e.jsxs(ie,{variant:"outline",className:"text-xs border-red-300 text-red-700",children:[q.sharedCount," riders"]})]},ge)),Se.highConflictPairs.length>8&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["...and ",Se.highConflictPairs.length-8," more"]})]})]}),e.jsx(St,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("button",{onClick:()=>F(!X),className:"flex items-center gap-2 text-sm font-semibold text-foreground",children:[X?e.jsx(mt,{className:"h-4 w-4"}):e.jsx(Hs,{className:"h-4 w-4"}),e.jsx(sa,{className:"h-4 w-4"}),"Rider Conflict Matrix",B.length>0&&e.jsxs(ie,{variant:"secondary",className:"text-xs",children:[B.length," pairs"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Shows how many riders are shared between each pair of classes. High-conflict pairs should be in the same block."}),X&&e.jsx("div",{className:"rounded-lg border bg-muted/30 p-3 max-h-80 overflow-y-auto",children:ne?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-4",children:[e.jsx(oe,{className:"h-4 w-4 animate-spin"})," Loading conflict data..."]}):B.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-2",children:"No rider conflicts found."}):e.jsx("div",{className:"space-y-1",children:B.sort((q,ge)=>ge.sharedCount-q.sharedCount).map((q,ge)=>e.jsxs("div",{className:`flex items-center justify-between rounded px-3 py-1.5 border ${ce(q.sharedCount)}`,children:[e.jsxs("span",{className:"text-sm font-medium",children:[q.classA," ",e.jsx("span",{className:"opacity-50",children:"↔"})," ",q.classB]}),e.jsxs(ie,{variant:"outline",className:"text-xs font-bold",children:[q.sharedCount," shared rider",q.sharedCount!==1?"s":""]})]},ge))})})]}),e.jsx(St,{}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:g.map((q,ge)=>e.jsxs("div",{className:`rounded-lg border-2 p-3 space-y-2 ${Ma[ge]||Ma[0]}`,children:[e.jsx(A,{value:q.label,onChange:fe=>Ps(ge,"label",fe.target.value),className:"font-semibold bg-background/80"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(v,{className:"text-xs",children:"Practice (total min)"}),e.jsx(A,{type:"number",min:5,max:30,value:q.practiceDuration,onChange:fe=>Ps(ge,"practiceDuration",Number(fe.target.value)),className:"bg-background/80"})]}),e.jsxs("div",{children:[e.jsx(v,{className:"text-xs",children:"Race (min/class)"}),e.jsx(A,{type:"number",min:3,max:30,value:q.raceDuration,onChange:fe=>Ps(ge,"raceDuration",Number(fe.target.value)),className:"bg-background/80"})]})]})]},ge))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(w,{onClick:us,disabled:k,className:"flex-1 gap-2",children:k?e.jsxs(e.Fragment,{children:[e.jsx(oe,{className:"h-4 w-4 animate-spin"}),"Analyzing rider conflicts & generating blocks..."]}):e.jsxs(e.Fragment,{children:[e.jsx(aa,{className:"h-4 w-4"}),Ce>0?"Re-optimize Unlocked Classes":"Generate Block Schedule"]})}),Ce>0&&e.jsxs(w,{variant:"outline",onClick:ft,className:"gap-1",children:[e.jsx(Yr,{className:"h-4 w-4"}),"Unlock All (",Ce,")"]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Estimated: ~",(O.total/1e3).toFixed(1),"K AI tokens (~$",Ne,")"]})]})]}),Ct&&f&&e.jsxs(re,{children:[e.jsx(ke,{className:"pb-2",children:e.jsxs(Ee,{className:"text-base flex items-center gap-2",children:[e.jsx(sa,{className:"h-4 w-4"}),"Optimization Score"]})}),e.jsxs(xe,{children:[e.jsxs("div",{className:"flex flex-wrap gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:`text-2xl font-bold ${Ct.total===0?"text-green-600":Ct.total<20?"text-amber-600":"text-destructive"}`,children:Ct.total}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total Score"})]}),e.jsx(St,{orientation:"vertical",className:"h-12"}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-lg font-semibold",children:Ct.crossBlockRiders}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Multi-block riders"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-lg font-semibold",children:Ct.threeBlockViolations}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"3+ block violations"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-lg font-semibold",children:Ct.backToBackConflicts}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Back-to-back"})]}),e.jsx(St,{orientation:"vertical",className:"h-12"}),e.jsx("div",{className:"flex items-center",children:e.jsxs(w,{variant:"outline",size:"sm",onClick:ss,className:"gap-1 text-xs",children:[e.jsx(kt,{className:"h-3 w-3"}),"Re-analyze"]})})]}),de&&e.jsxs("div",{className:"mt-2 text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(za,{className:"h-3 w-3"}),"Actual usage: ",de.prompt+de.completion," tokens ($",de.cost.toFixed(4),")"]}),_e.length>1&&e.jsxs("div",{className:"mt-3",children:[e.jsxs("button",{onClick:()=>ee(!$e),className:"flex items-center gap-2 text-xs font-medium text-muted-foreground hover:text-foreground",children:[$e?e.jsx(mt,{className:"h-3 w-3"}):e.jsx(Hs,{className:"h-3 w-3"}),e.jsx(ca,{className:"h-3 w-3"}),"Compare ",_e.length," runs"]}),$e&&e.jsx("div",{className:"mt-2 space-y-1",children:_e.map((q,ge)=>e.jsxs("div",{className:`flex items-center justify-between rounded px-3 py-1.5 text-sm border ${ge===0?"bg-primary/10 border-primary/30":"bg-muted/30"}`,children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Run ",_e.length-ge," • ",new Date(q.timestamp).toLocaleTimeString()]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs",children:[e.jsxs("span",{children:["Score: ",e.jsx("strong",{children:q.score.total})]}),e.jsxs("span",{children:[q.score.crossBlockRiders," multi-block"]}),e.jsxs("span",{children:[q.score.backToBackConflicts," b2b"]}),ge>0&&e.jsx(w,{size:"sm",variant:"ghost",className:"h-6 text-xs",onClick:()=>{h(q.result),T(new Set(q.result.blocks.map((fe,Re)=>Re)))},children:"Restore"})]})]},q.timestamp))})]})]})]}),f&&e.jsx(e.Fragment,{children:e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsxs(Ee,{className:"flex items-center justify-between",children:[e.jsx("span",{children:"Generated Schedule"}),e.jsxs("div",{className:"flex items-center gap-1 text-xs font-normal text-muted-foreground",children:[e.jsx(Li,{className:"h-3 w-3"}),"Drag races to reorder across motos"]})]}),e.jsxs(ns,{children:[f.totalClasses," classes • ",f.totalRiders," total entries •"," ",f.crossBlockRiders.length," multi-block riders •"," ",(((ls=f.backToBackConflicts)==null?void 0:ls.length)||0)===0?e.jsx("span",{className:"text-green-600 font-medium",children:"0 back-to-back conflicts ✓"}):e.jsxs("span",{className:"text-destructive font-medium",children:[f.backToBackConflicts.length," back-to-back conflicts"]}),It&&e.jsxs(e.Fragment,{children:[" • Estimated day ends at ",e.jsx("span",{className:"font-semibold text-foreground",children:Ut(It)})]})]})]}),e.jsxs(xe,{className:"space-y-4",children:[f.threeBlockViolations.length>0&&e.jsxs(ht,{variant:"destructive",children:[e.jsx(Is,{className:"h-4 w-4"}),e.jsxs(xt,{children:[f.threeBlockViolations.length," rider(s) need to attend 3+ blocks. Consider adjusting manually."]})]}),Ce>0&&e.jsxs(ht,{children:[e.jsx(ct,{className:"h-4 w-4"}),e.jsxs(xt,{children:[pe.size," class(es) locked to block, ",we.length,' pinned to exact race position. Click "Re-optimize Unlocked Classes" to keep them in place and rebuild the rest around them.']})]}),f.reasoning&&e.jsx("p",{className:"text-sm text-muted-foreground italic",children:f.reasoning}),e.jsx(oo,{sensors:Te,collisionDetection:mo,onDragEnd:Ge,children:e.jsx("div",{className:"space-y-3",children:f.blocks.map((q,ge)=>{const fe=M.has(ge),Re=g[ge],Ke=vs(q,ge),Oe=Ke.length,hs=(Re==null?void 0:Re.practiceDuration)||30,os=Oe*((Re==null?void 0:Re.raceDuration)||8),_s=hs+os,it=Ke.map(fs=>fs.id),gs=f.blocks.slice(0,ge).reduce((fs,dt,lt)=>fs+vs(dt,lt).length,0);return e.jsxs("div",{className:`rounded-lg border-2 overflow-hidden ${Ma[ge]||Ma[0]}`,children:[e.jsxs("button",{onClick:()=>es(ge),className:"w-full flex items-center justify-between p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[fe?e.jsx(mt,{className:"h-4 w-4"}):e.jsx(Hs,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold",children:q.label}),q.startTime&&e.jsxs(ie,{variant:"outline",className:"gap-1",children:[e.jsx(yt,{className:"h-3 w-3"}),Ut(q.startTime)]}),q.racingEndTime&&e.jsxs(ie,{variant:"outline",className:"gap-1 opacity-70",children:["→ ",Ut(q.racingEndTime)]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ie,{variant:"secondary",className:"gap-1",children:[e.jsx(qa,{className:"h-3 w-3"}),"~",_s," min"]}),e.jsxs(ie,{variant:"secondary",className:"gap-1",children:[e.jsx(Gs,{className:"h-3 w-3"}),q.totalRiders]}),e.jsxs(ie,{variant:"secondary",children:[Oe," scheduled races (",q.classes.length," classes)"]})]})]}),fe&&e.jsxs("div",{className:"border-t px-3 pb-3 pt-2 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap gap-4 text-xs font-medium opacity-80",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(yt,{className:"h-3 w-3"}),"Practice: ",Ut(q.startTime)," – ",q.practiceEndTime&&Ut(q.practiceEndTime)," (~",hs," min)"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(qa,{className:"h-3 w-3"}),"Race window: ",q.practiceEndTime&&Ut(q.practiceEndTime)," – ",q.racingEndTime&&Ut(q.racingEndTime)]}),e.jsxs("span",{children:[Oe," total races in this block"]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-semibold mb-1 opacity-70",children:"Unified Race Order"}),e.jsx(uo,{items:it,strategy:ho,children:e.jsx("div",{className:"space-y-1",children:Ke.map((fs,dt)=>{const lt=q.practiceEndTime?Ta(q.practiceEndTime,dt*((Re==null?void 0:Re.raceDuration)||8)):"",qt=fs.classes.map(Sl=>Sl.name),wl=cs(qt);return e.jsx(wu,{id:fs.id,groupClasses:fs.classes,moto:fs.moto,raceNumber:gs+dt+1,raceStart:lt,lockState:wl,onCycleLock:()=>ys(qt,q.blockNumber,fs.moto,dt+1),combined:fs.classes.length>1},fs.id)})})})]})]})]},ge)})})}),f.crossBlockRiders.length>0&&e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>L(!C),className:"flex items-center gap-2 text-sm font-medium text-muted-foreground hover:text-foreground",children:[C?e.jsx(mt,{className:"h-4 w-4"}):e.jsx(Hs,{className:"h-4 w-4"}),e.jsx(Is,{className:"h-4 w-4 text-amber-500"}),f.crossBlockRiders.length," riders spanning multiple blocks"]}),C&&e.jsx("div",{className:"mt-2 max-h-60 overflow-y-auto rounded border bg-muted/30 p-2 space-y-1",children:f.crossBlockRiders.map((q,ge)=>e.jsxs("div",{className:"flex items-center justify-between text-sm px-2 py-1",children:[e.jsxs("span",{children:[q.name," ",q.memberNumber?`#${q.memberNumber}`:""]}),e.jsx("div",{className:"flex gap-1",children:q.blocks.map(fe=>{var Re;return e.jsx(ie,{variant:"outline",className:"text-xs",children:((Re=f.blocks[fe-1])==null?void 0:Re.label)||`Block ${fe}`},fe)})})]},ge))})]}),(((Bs=f.backToBackConflicts)==null?void 0:Bs.length)||0)>0?e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>Z(!Q),className:"flex items-center gap-2 text-sm font-medium text-destructive hover:text-destructive/80",children:[Q?e.jsx(mt,{className:"h-4 w-4"}):e.jsx(Hs,{className:"h-4 w-4"}),e.jsx(Is,{className:"h-4 w-4"}),f.backToBackConflicts.length," back-to-back conflict",f.backToBackConflicts.length!==1?"s":""]}),Q&&e.jsx("div",{className:"mt-2 max-h-60 overflow-y-auto rounded border border-destructive/30 bg-destructive/5 p-2 space-y-1",children:f.backToBackConflicts.map((q,ge)=>e.jsxs("div",{className:"flex items-center justify-between text-sm px-2 py-1",children:[e.jsxs("span",{children:[q.riderName," ",q.memberNumber?`#${q.memberNumber}`:""]}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(ie,{variant:"outline",className:"text-xs",children:q.blockLabel}),e.jsx("span",{children:q.class1}),e.jsx("span",{children:"→"}),e.jsx("span",{children:q.class2})]})]},ge))})]}):f&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-green-600",children:[e.jsx(ie,{variant:"outline",className:"border-green-500 text-green-600 text-xs",children:"✓"}),"No back-to-back conflicts — all riders have a break between races"]}),e.jsx(St,{}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex gap-2",children:e.jsxs(w,{onClick:xs,disabled:d.isPending,className:"flex-1 gap-2",children:[d.isPending?e.jsx(oe,{className:"h-4 w-4 animate-spin"}):e.jsx(Qa,{className:"h-4 w-4"}),"Apply to Race Order"]})}),e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsxs("div",{className:"flex-1 space-y-1",children:[e.jsx(v,{className:"text-xs",children:"Schedule Name"}),e.jsx(A,{placeholder:"e.g. Fast 6 + rest, Standard 3-block...",value:Ls,onChange:q=>P(q.target.value),className:"h-8 text-sm bg-background"})]}),e.jsxs(w,{variant:"outline",onClick:G,disabled:ye,className:"gap-2 h-8",children:[ye?e.jsx(oe,{className:"h-4 w-4 animate-spin"}):e.jsx(oc,{className:"h-4 w-4"}),"Save for Later"]})]})]})]})]})}),ve.length>0&&e.jsxs(re,{children:[e.jsx(ke,{className:"pb-2",children:e.jsxs("button",{onClick:()=>He(!ze),className:"flex items-center gap-2",children:[ze?e.jsx(mt,{className:"h-4 w-4"}):e.jsx(Hs,{className:"h-4 w-4"}),e.jsx(Pi,{className:"h-4 w-4"}),e.jsx(Ee,{className:"text-base",children:"Saved Schedules"}),e.jsx(ie,{variant:"secondary",className:"text-xs",children:ve.length})]})}),ze&&e.jsx(xe,{children:e.jsx("div",{className:"space-y-2",children:ve.map(q=>{var Re,Ke,Oe;const ge=((Ke=(Re=q.result_data)==null?void 0:Re.blocks)==null?void 0:Ke.length)>0,fe=(Oe=q.result_data)==null?void 0:Oe.savedOnly;return e.jsxs("div",{className:"flex items-center justify-between rounded border bg-muted/30 px-3 py-2 text-sm",children:[e.jsxs("div",{className:"flex flex-col gap-0.5",children:[q.name&&e.jsx("span",{className:"font-medium text-foreground",children:q.name}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[e.jsxs("span",{children:[new Date(q.created_at).toLocaleDateString()," ",new Date(q.created_at).toLocaleTimeString()]}),e.jsxs("span",{children:[q.block_count," blocks"]}),e.jsxs("span",{children:[q.total_classes," classes"]}
213),e.jsx("span",{children:q.event_name}),fe&&e.jsx(ie,{variant:"outline",className:"text-xs",children:"saved"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs",children:[e.jsxs(ie,{variant:q.conflict_score===0?"default":"secondary",className:"text-xs",children:["Score: ",q.conflict_score]}),e.jsxs("span",{children:[q.cross_block_riders," multi-block"]}),e.jsxs("span",{children:[q.back_to_back_conflicts," b2b"]}),ge&&e.jsxs(w,{size:"sm",variant:"outline",className:"h-6 text-xs gap-1",onClick:()=>ds(q),children:[e.jsx($t,{className:"h-3 w-3"}),"Load"]}),e.jsx(w,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 text-destructive hover:text-destructive",onClick:()=>De(q.id),children:e.jsx(ws,{className:"h-3 w-3"})})]})]},q.id)})})})]}),e.jsx(et,{open:Ve,onOpenChange:Ue,children:e.jsxs(st,{children:[e.jsxs(Et,{children:[e.jsx(tt,{children:"Run AI Optimization?"}),e.jsxs(at,{children:["This will use approximately ",e.jsxs("strong",{children:["~",(O.total/1e3).toFixed(1),"K AI tokens"]})," (~$",Ne,"). Token usage is billed to your organization."]})]}),e.jsxs(Mt,{children:[e.jsx(nt,{children:"Cancel"}),e.jsx(rt,{onClick:ps,children:"Continue"})]})]})}),de&&e.jsxs(ht,{children:[e.jsx(za,{className:"h-4 w-4"}),e.jsxs(xt,{className:"text-xs",children:["Last run used ",e.jsx("strong",{children:de.prompt+de.completion})," tokens (prompt: ",de.prompt,", completion: ",de.completion,") — cost: ",e.jsxs("strong",{children:["$",de.cost.toFixed(4)]})]})]})]})}function Cu(){Je();const{data:s=[]}=ba(),{data:n=[]}=Qt(),[i,t]=a.useState(null),[d,r]=a.useState(null),x=i?n.filter(c=>c.series_name===i):n;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsxs(Ee,{className:"flex items-center gap-2",children:[e.jsx(aa,{className:"h-5 w-5 text-primary"}),"Schedule Optimizer"]}),e.jsx(ns,{children:"Select an event to optimize its block schedule. You can save optimizations and apply them later from the Race Organization tab."})]}),e.jsx(xe,{children:e.jsxs("div",{className:"flex flex-wrap gap-4",children:[e.jsxs("div",{className:"space-y-1 min-w-[200px]",children:[e.jsx(v,{children:"Series"}),e.jsxs(Pe,{value:i||"all",onValueChange:c=>{t(c==="all"?null:c),r(null)},children:[e.jsx(Ie,{className:"bg-background",children:e.jsx(qe,{placeholder:"All series"})}),e.jsxs(Be,{className:"bg-popover border-border z-50",children:[e.jsx(ae,{value:"all",children:"All Series"}),s.map(c=>e.jsx(ae,{value:c,children:c},c))]})]})]}),e.jsxs("div",{className:"space-y-1 min-w-[250px]",children:[e.jsx(v,{children:"Event"}),e.jsxs(Pe,{value:d||"",onValueChange:c=>r(c||null),children:[e.jsx(Ie,{className:"bg-background",children:e.jsx(qe,{placeholder:"Select an event..."})}),e.jsx(Be,{className:"bg-popover border-border z-50",children:x.map(c=>e.jsx(ae,{value:c.event_name,children:c.event_name},c.event_name))})]})]})]})})]}),d&&e.jsx(Su,{eventName:d})]})}const Yt="data-[state=active]:bg-primary data-[state=active]:text-primary-foreground";function ku({unreadSmsCount:s=0,failedEmailCount:n=0}){const[i,t]=Lr(),d=Gt(),{features:r}=En(["timing_sms","timing_race_organization","timing_riders","timing_coupons"]),x=r.timing_sms,c=r.timing_race_organization,o=r.timing_riders,m=r.timing_coupons,p=i.get("section")||"communications",u=i.get("subtab")||(p==="communications"?"messaging":p==="promotions"?"offers":"race-organization"),l=N=>{t(j=>(j.set("subtab",N),j))};return e.jsx("div",{className:"space-y-6","data-tour":"timing-admin-container",children:e.jsx(wt,{children:e.jsxs(ot,{value:p,className:"w-full",children:[e.jsx(Ae,{value:"communications",className:"mt-4",children:e.jsxs(ot,{value:u,onValueChange:l,className:"w-full",children:[e.jsxs(pt,{className:"inline-flex h-10 w-auto gap-1 p-1",children:[e.jsxs(Us,{children:[e.jsx(zs,{asChild:!0,children:e.jsx("span",{children:e.jsxs(Qe,{value:"messaging",className:`gap-2 relative ${Yt}`,disabled:!x,children:[x?e.jsx(bt,{className:"h-4 w-4"}):e.jsx(ct,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"SMS"}),x&&s>0&&e.jsxs(Us,{children:[e.jsx(zs,{asChild:!0,children:e.jsx("span",{className:"absolute -top-1 -right-1 flex h-5 min-w-[1.25rem] items-center justify-center rounded-full bg-destructive px-1 text-[10px] font-bold text-destructive-foreground cursor-help",children:s})}),e.jsx(Vs,{children:e.jsxs("p",{children:[s," unread message",s===1?"":"s"]})})]})]})})}),!x&&e.jsx(Vs,{children:e.jsx("p",{children:"SMS Messaging is not enabled"})})]}),e.jsxs(Qe,{value:"email",className:`gap-2 ${Yt}`,children:[e.jsx(Ks,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Email"})]}),e.jsxs(Qe,{value:"settings",className:`gap-2 ${Yt}`,children:[e.jsx(Ua,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Settings"})]}),e.jsxs(Qe,{value:"logs",className:`gap-2 relative ${Yt}`,children:[e.jsx(jt,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Logs"}),n>0&&e.jsxs(Us,{children:[e.jsx(zs,{asChild:!0,children:e.jsx("span",{className:"absolute -top-1 -right-1 flex h-5 min-w-[1.25rem] items-center justify-center rounded-full bg-destructive px-1 text-[10px] font-bold text-destructive-foreground cursor-help",children:n})}),e.jsx(Vs,{children:e.jsxs("p",{children:[n," failed email",n===1?"":"s"]})})]})]})]}),e.jsx(Ae,{value:"messaging",className:"mt-6",children:x?e.jsx(Cm,{}):e.jsx($a,{feature:"SMS Messaging"})}),e.jsx(Ae,{value:"email",className:"mt-6",children:e.jsx(Gm,{})}),e.jsx(Ae,{value:"settings",className:"mt-6",children:e.jsx(Tm,{})}),e.jsx(Ae,{value:"logs",className:"mt-6",children:e.jsx(su,{})})]})}),e.jsx(Ae,{value:"race-management",className:"mt-4",children:e.jsxs(ot,{value:u,onValueChange:l,className:"w-full",children:[e.jsxs(pt,{className:"inline-flex h-10 w-auto gap-1 p-1",children:[e.jsxs(Us,{children:[e.jsx(zs,{asChild:!0,children:e.jsx("span",{children:e.jsxs(Qe,{value:"race-organization",className:`gap-2 ${Yt}`,disabled:!c,children:[c?e.jsx(At,{className:"h-4 w-4"}):e.jsx(ct,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Race Organization"})]})})}),!c&&e.jsx(Vs,{children:e.jsx("p",{children:"Race Organization is not enabled"})})]}),e.jsxs(Us,{children:[e.jsx(zs,{asChild:!0,children:e.jsx("span",{children:e.jsxs(Qe,{value:"riders",className:`gap-2 ${Yt}`,disabled:!o,children:[o?e.jsx(Ii,{className:"h-4 w-4"}):e.jsx(ct,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:d.racers})]})})}),!o&&e.jsx(Vs,{children:e.jsxs("p",{children:[d.racer," Management is not enabled"]})})]}),e.jsxs(Qe,{value:"optimizer",className:`gap-2 ${Yt}`,children:[e.jsx(aa,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Schedule Optimizer"})]})]}),e.jsx(Ae,{value:"race-organization",className:"mt-6",children:c?e.jsx(km,{}):e.jsx($a,{feature:"Race Organization"})}),e.jsx(Ae,{value:"riders",className:"mt-6",children:o?e.jsx(Em,{}):e.jsx($a,{feature:`${d.racer} Management`})}),e.jsx(Ae,{value:"optimizer",className:"mt-6",children:e.jsx(Cu,{})})]})}),e.jsx(Ae,{value:"promotions",className:"mt-4",children:m?e.jsx(yu,{}):e.jsx($a,{feature:"Promotions"})})]})})})}function $a({feature:s}){return e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(ct,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsxs("h3",{className:"text-lg font-semibold mb-2",children:[s," is not enabled"]}),e.jsx("p",{className:"text-muted-foreground max-w-md",children:"Contact your platform administrator to enable this feature for your organization."})]})}const Eu=s=>{const n=Ms(),i=ms({queryKey:["digest-settings",s],queryFn:async()=>
213{if(!s)return null;const{data:d,error:r}=await z.from("org_digest_settings").select("*").eq("organization_id",s).maybeSingle();if(r)throw r;return d},enabled:!!s}),t=ks({mutationFn:async d=>{if(!s)throw new Error("No org");const{data:r,error:x}=await z.from("org_digest_settings").upsert({organization_id:s,...d},{onConflict:"organization_id"}).select().single();if(x)throw x;return r},onSuccess:()=>{n.invalidateQueries({queryKey:["digest-settings",s]})}});return{settings:i.data,isLoading:i.isLoading,upsert:t}},Mu=()=>{const{currentOrganization:s}=Je(),{settings:n,isLoading:i,upsert:t}=Eu(s==null?void 0:s.id),d=(n==null?void 0:n.is_enabled)??!1,r=(n==null?void 0:n.frequency)??"daily",x=o=>{t.mutate({is_enabled:o,frequency:r},{onSuccess:()=>K.success(o?"Digest emails enabled":"Digest emails disabled"),onError:()=>K.error("Failed to update digest settings")})},c=o=>{t.mutate({is_enabled:d,frequency:o},{onSuccess:()=>K.success(`Digest frequency set to ${o}`),onError:()=>K.error("Failed to update frequency")})};return i?e.jsx(zt,{className:"h-40"}):e.jsxs(re,{className:"bg-card border-border","data-tour":"digest-settings",children:[e.jsxs(ke,{className:"pb-3",children:[e.jsxs(Ee,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ks,{className:"h-4 w-4"}),"Digest Email Reports"]}),e.jsx(ns,{children:"Receive periodic email snapshots of registrations, revenue, and usage metrics."})]}),e.jsxs(xe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(v,{htmlFor:"digest-toggle",children:"Enable digest emails"}),e.jsx(Ds,{id:"digest-toggle",checked:d,onCheckedChange:x,disabled:t.isPending})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(v,{children:"Frequency"}),e.jsxs(Pe,{value:r,onValueChange:c,disabled:!d||t.isPending,children:[e.jsx(Ie,{className:"w-36",children:e.jsx(qe,{})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"daily",children:"Daily"}),e.jsx(ae,{value:"weekly",children:"Weekly"}),e.jsx(ae,{value:"monthly",children:"Monthly"})]})]})]}),(n==null?void 0:n.last_sent_at)&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(yt,{className:"h-3 w-3"}),"Last sent: ",Js(new Date(n.last_sent_at),"MMM d, yyyy h:mm a")]})]})]})};function Tu(s,n,i){return ms({queryKey:["reconciliation-usage",s,n,i],enabled:!!s&&!!n&&!!i,staleTime:5*60*1e3,retry:1,queryFn:async()=>{const t=m=>{const[p,u,l]=m.split("-").map(Number);return new Date(p,(u||1)-1,l||1)},d=t(n),r=new Date(t(i).getTime()+24*60*60*1e3),{data:x,error:c}=await z.functions.invoke("org-reconciliation-report",{body:{organization_id:s,period_start:d.toISOString(),period_end:r.toISOString()}});if(c)return console.warn("Reconciliation usage fetch failed:",c.message),null;const o=x==null?void 0:x.totals;return o?{timing_cost:Number(o.timing_cost??0),messaging_cost:Number(o.messaging_cost??0),ai_cost:Number(o.ai_cost??0),bp_platform_fees:Number(o.bp_platform_fees??0),stripe_processing_fees:Number(o.stripe_processing_fees??0),timing_cost_breakdown:o.timing_cost_breakdown??[]}:null}})}const Ru=()=>{const{currentOrganization:s}=Je(),n=new Date,[i,t]=a.useState(Js(No(n),"yyyy-MM-dd")),[d,r]=a.useState(Js(bo(n),"yyyy-MM-dd")),{isLoading:x,getEffectivePricing:c}=Jc(s==null?void 0:s.id),{data:o,isLoading:m}=Xc((s==null?void 0:s.id)||"",i,d+"T23:59:59.999Z"),{data:p,isLoading:u}=eo((s==null?void 0:s.id)||"",i,d),{data:l,isLoading:N}=Tu((s==null?void 0:s.id)||null,i,d),j=x||m||u||N,g=c("email"),y=c("sms"),k=l?l.messaging_cost:((o==null?void 0:o.emailSent)??0)*g+((o==null?void 0:o.smsSegments)??0)*y,S=l?l.bp_platform_fees:(o==null?void 0:o.platformFeeRevenue)??0,f=l?l.stripe_processing_fees:(o==null?void 0:o.stripeFeesEst)??0,h=(o==null?void 0:o.stripeChargedCount)??0,M=l?l.timing_cost:(p==null?void 0:p.totalCost)??0,T=l?l.ai_cost:(o==null?void 0:o.aiTotalCost)??0,C=k+S+f+M+T;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(re,{className:"bg-card border-border border-l-4 border-l-amber-500",children:[e.jsxs(ke,{children:[e.jsxs(Ee,{className:"flex items-center gap-2",children:[e.jsx(jo,{className:"h-5 w-5"}),"Usage & Costs"]}),e.jsx(ns,{children:"Your organization's usage and associated costs for the selected period"})]}),e.jsxs(xe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-end gap-4","data-tour":"usage-date-range",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(v,{className:"text-xs",children:"Start Date"}),e.jsx(A,{type:"date",value:i,onChange:L=>t(L.target.value),className:"w-40"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(v,{className:"text-xs",children:"End Date"}),e.jsx(A,{type:"date",value:d,onChange:L=>r(L.target.value),className:"w-40"})]})]}),j?e.jsxs("div",{className:"grid gap-4 sm:grid-cols-6",children:[e.jsx(zt,{className:"h-24"}),e.jsx(zt,{className:"h-24"}),e.jsx(zt,{className:"h-24"}),e.jsx(zt,{className:"h-24"}),e.jsx(zt,{className:"h-24"}),e.jsx(zt,{className:"h-24"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-6","data-tour":"usage-summary",children:[e.jsx(re,{children:e.jsxs(xe,{className:"pt-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(Ks,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(o==null?void 0:o.emailSent)??0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Emails Sent"})]})]})}),e.jsx(re,{children:e.jsxs(xe,{className:"pt-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(bt,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(o==null?void 0:o.smsSegments)??0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"SMS Segments"})]})]})}),e.jsx(re,{children:e.jsxs(xe,{className:"pt-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(Kn,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(o==null?void 0:o.registrations)??0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Registrations"})]})]})}),e.jsx(re,{children:e.jsxs(xe,{className:"pt-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(qa,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(p==null?void 0:p.totalRiders)??0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Timing Riders"})]})]})}),e.jsx(re,{children:e.jsxs(xe,{className:"pt-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(vo,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(o==null?void 0:o.aiRequests)??0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"AI Requests"})]})]})}),e.jsx(re,{children:e.jsxs(xe,{className:"pt-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(_a,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-2xl font-bold",children:["$",C.toFixed(2)]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Cost"})]})]})})]}),e.jsxs(na,{"data-tour":"usage-table",children:[e.jsx(ra,{children:e.jsxs(Qs,{children:[e.jsx(Ss,{children:"Type"}),e.jsx(Ss,{className:"text-right",children:"Count"}),e.jsx(Ss,{className:"text-right",children:"Billable Units"}),e.jsx(Ss,{className:"text-right",children:"Unit Cost"}),e.jsx(Ss,{className:"text-right",children:"Total"})]})}),e.jsxs(ia,{children:[e.jsxs(Qs,{children:[e.jsx(We,{className:"font-medium",children:"Messaging (email + SMS)"}),e.jsxs(We,{className:"text-right",children:[(o==null?void 0:o.emailSent)??0," emails / ",(o==null?void 0:o.smsSent)??0," texts"]}),e.jsxs(We,{className:"text-right",children:[(o==null?void 0:o.smsSegments)??0," SMS segments"]}),e.jsxs(We,{className:"text-right",children:["$",g.toFixed(4),"/email · $",y.toFixed(4),"/seg"]}),e.jsxs(We,{className:"text-right font-medium",children:["$",k.toFixed(2)]})]}),e.jsxs(Qs,{children:[e.jsx(We,{className:"font-medium",children:"Platform Fees"}),e.jsx(We,{className:"text-right",children:(o==null?void 0:o.registrations)??0}),e.jsxs(We,{className:"text-right",children:[(o==null?void 0:o.registrations)??0," regs"]}),e.jsx(We,{className:"text-right",children:"tiered"}),e.jsxs(We,{className:"text-right font-medium",children:["$",S.toFixed(2)]})]}),e.jsxs(Qs,{children:[e.jsx(We,{className:"font-medium",children:"Live Timing"}),e.jsxs(We,{className:"text-right",children:[(p==null?void 0:p.totalRiders)??0," riders"]}),e.jsxs(We,{className:"text-right",children:[(p==null?void 0:p.totalClassEntries)??0," class-entries"]}),e.jsx(We,{className:"text-right",children:"tiered"}),e.jsxs(We,{className:"text-right font-medium",children:["$",M.toFixed(2)]})]}),e.jsxs(Qs,{children:[e.jsxs(We,{className:"font-medium flex items-center gap-2",children:[e.jsx(zr,{className:"h-4 w-4 text-muted-foreground"}),"Stripe Processing Fees (estimate)"]}),e.jsxs(We,{className:"text-right",children:[h," charges"]}),e.jsx(We,{className:"text-right",children:"est."}),e.jsx(We,{className:"text-right",children:"2.9% + $0.30"}),e.jsxs(We,{className:"text-right font-medium",children:["$",f.toFixed(2)]})]}),e.jsxs(Qs,{className:"font-bold",children:[e.jsx(We,{children:"Total"}),e.jsx(We,{}),e.jsx(We,{}),e.jsx(We,{}),e.jsxs(We,{className:"text-right",children:["$",C.toFixed(2)]})]}),e.jsxs(Qs,{children:[e.jsx(We,{className:"font-medium",children:"AI Usage"}),e.jsxs(We,{className:"text-right",children:[(o==null?void 0:o.aiRequests)??0," requests"]}),e.jsxs(We,{className:"text-right",children:[(((o==null?void 0:o.aiPromptTokens)??0)+((o==null?void 0:o.aiCompletionTokens)??0)).toLocaleStr
213ing()," tokens"]}),e.jsx(We,{className:"text-right",children:"per token"}),e.jsxs(We,{className:"text-right font-medium",children:["$",T.toFixed(2)]})]})]})]})]})]})]}),e.jsx(Mu,{})]})};function $u(s,n){return ms({queryKey:["website-analytics",s,n.from.toISOString(),n.to.toISOString()],queryFn:async()=>{if(!s)throw new Error("No org");const i=[],t=1e3;let d=0,r=!0;for(;r;){const{data:T,error:C}=await z.from("page_views").select("page_path, referrer_source, device_type, session_id, created_at").eq("organization_id",s).gte("created_at",n.from.toISOString()).lte("created_at",n.to.toISOString()).order("created_at",{ascending:!0}).range(d,d+t-1);if(C)throw C;const L=T||[];i.push(...L),r=L.length===t,d+=t}const x=i,c=x.length,m=new Set(x.map(T=>T.session_id)).size,p=m>0?Math.round(c/m*100)/100:0,u={};x.forEach(T=>{u[T.session_id]=(u[T.session_id]||0)+1});const l=Object.values(u).filter(T=>T===1).length,N=m>0?Math.round(l/m*100):0,j={};x.forEach(T=>{const C=T.created_at.substring(0,10);j[C]||(j[C]={sessions:new Set,views:0}),j[C].sessions.add(T.session_id),j[C].views++});const g=Object.entries(j).sort(([T],[C])=>T.localeCompare(C)).map(([T,C])=>({date:T,visitors:C.sessions.size,pageviews:C.views})),y={};x.forEach(T=>{y[T.page_path]=(y[T.page_path]||0)+1});const k=Object.entries(y).sort(([,T],[,C])=>C-T).slice(0,10).map(([T,C])=>({path:T,views:C})),S={};x.forEach(T=>{S[T.referrer_source]=(S[T.referrer_source]||0)+1});const f=Object.entries(S).sort(([,T],[,C])=>C-T).slice(0,10).map(([T,C])=>({source:T,count:C})),h={};x.forEach(T=>{h[T.device_type]=(h[T.device_type]||0)+1});const M=Object.entries(h).sort(([,T],[,C])=>C-T).map(([T,C])=>({type:T,count:C}));return{totalVisitors:m,totalPageviews:c,viewsPerVisit:p,bounceRate:N,dailyVisitors:g,topPages:k,topSources:f,devices:M}},enabled:!!s,staleTime:5*60*1e3,gcTime:30*60*1e3,refetchOnWindowFocus:!1,refetchOnMount:!1})}const Du=[{label:"7 days",days:7},{label:"14 days",days:14},{label:"30 days",days:30}];function Fu(){var m,p,u;const{currentOrganization:s}=Je(),[n,i]=a.useState(7),t=a.useMemo(()=>{const l=new Date,N=new Date;return N.setDate(N.getDate()-n),{from:N,to:l}},[n]),{data:d,isLoading:r}=$u(s==null?void 0:s.id,t);if(r)return e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx(oe,{className:"h-8 w-8 animate-spin text-muted-foreground"})});if(!d)return e.jsx("div",{className:"text-center py-20 text-muted-foreground",children:"No analytics data yet. Page views will appear once visitors access your organization's public pages."});const x=((m=d.topPages[0])==null?void 0:m.views)||1,c=((p=d.topSources[0])==null?void 0:p.count)||1,o=((u=d.devices[0])==null?void 0:u.count)||1;return e.jsxs("div",{className:"space-y-6","data-tour":"website-analytics-container",children:[e.jsx("div",{className:"flex items-center gap-2","data-tour":"website-date-range",children:Du.map(l=>e.jsx(w,{size:"sm",variant:n===l.days?"default":"outline",onClick:()=>i(l.days),children:l.label},l.days))}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(Da,{icon:Gs,label:"Visitors",value:d.totalVisitors}),e.jsx(Da,{icon:Zt,label:"Pageviews",value:d.totalPageviews}),e.jsx(Da,{icon:sa,label:"Views / Visit",value:d.viewsPerVisit}),e.jsx(Da,{icon:Mo,label:"Bounce Rate",value:`${d.bounceRate}%`})]}),e.jsxs(re,{children:[e.jsx(ke,{children:e.jsx(Ee,{className:"text-base",children:"Daily Visitors"})}),e.jsx(xe,{children:e.jsx("div",{className:"h-64",children:e.jsx(yo,{width:"100%",height:"100%",children:e.jsxs(_o,{data:d.dailyVisitors,children:[e.jsx(wo,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(So,{dataKey:"date",tick:{fontSize:12},className:"text-muted-foreground"}),e.jsx(Co,{tick:{fontSize:12},className:"text-muted-foreground"}),e.jsx(ko,{}),e.jsx(ur,{type:"monotone",dataKey:"visitors",stroke:"hsl(var(--primary))",strokeWidth:2,dot:!1}),e.jsx(ur,{type:"monotone",dataKey:"pageviews",stroke:"hsl(var(--muted-foreground))",strokeWidth:1,strokeDasharray:"4 4",dot:!1})]})})})})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-4",children:[e.jsxs(re,{children:[e.jsx(ke,{children:e.jsx(Ee,{className:"text-base",children:"Top Sources"})}),e.jsx(xe,{children:e.jsxs(na,{children:[e.jsx(ra,{children:e.jsxs(Qs,{children:[e.jsx(Ss,{children:"Source"}),e.jsx(Ss,{className:"text-right w-20",children:"Visits"})]})}),e.jsxs(ia,{children:[d.topSources.map(l=>e.jsxs(Qs,{children:[e.jsx(We,{children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-sm",children:l.source}),e.jsx("div",{className:"h-1.5 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-primary",style:{width:`${l.count/c*100}%`}})})]})}),e.jsx(We,{className:"text-right font-medium",children:l.count})]},l.source)),d.topSources.length===0&&e.jsx(Qs,{children:e.jsx(We,{colSpan:2,className:"text-center text-muted-foreground",children:"No data"})})]})]})})]}),e.jsxs(re,{children:[e.jsx(ke,{children:e.jsx(Ee,{className:"text-base",children:"Top Pages"})}),e.jsx(xe,{children:e.jsxs(na,{children:[e.jsx(ra,{children:e.jsxs(Qs,{children:[e.jsx(Ss,{children:"Page"}),e.jsx(Ss,{className:"text-right w-20",children:"Views"})]})}
213),e.jsxs(ia,{children:[d.topPages.map(l=>e.jsxs(Qs,{children:[e.jsx(We,{children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-sm truncate block max-w-[250px]",children:l.path}),e.jsx("div",{className:"h-1.5 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-primary",style:{width:`${l.views/x*100}%`}})})]})}),e.jsx(We,{className:"text-right font-medium",children:l.views})]},l.path)),d.topPages.length===0&&e.jsx(Qs,{children:e.jsx(We,{colSpan:2,className:"text-center text-muted-foreground",children:"No data"})})]})]})})]})]}),e.jsxs(re,{children:[e.jsx(ke,{children:e.jsx(Ee,{className:"text-base",children:"Devices"})}),e.jsx(xe,{children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:d.devices.map(l=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"capitalize",children:l.type}),e.jsx("span",{className:"font-medium",children:l.count})]}),e.jsx("div",{className:"h-2 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-primary",style:{width:`${l.count/o*100}%`}})})]},l.type))})})]})]})}function Da({icon:s,label:n,value:i}){return e.jsx(re,{children:e.jsx(xe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-lg bg-primary/10 p-2",children:e.jsx(s,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:n}),e.jsx("p",{className:"text-2xl font-bold",children:i})]})]})})})}const Sr=s=>s.replace(/<[^>]*>/g,"").trim(),Cr=(s,n)=>{if(!s)return null;if(n==="name")try{const i=JSON.parse(s);return[i.firstName,i.lastName].filter(Boolean).join(" ")}catch{return s}if(n==="address")try{const i=JSON.parse(s);return[i.street,i.city,i.state,i.zip].filter(Boolean).join(", ")}catch{return s}if(n==="waiver"||n==="signature")try{return JSON.parse(s).signed?"Signed":"Not signed"}catch{return s==="true"?"Signed":s}if(n==="class_entry")try{const i=JSON.parse(s);return`${i.className||""} #${i.bikeNumber||""}`.trim()}catch{return s}if(n==="class_selection")try{const i=JSON.parse(s);if(Array.isArray(i))return i.join(", ")}catch{return s}if(n==="checkbox")return s==="true"?"Yes":s==="false"?"No":s;if(n==="sessions")try{const i=JSON.parse(s);if(Array.isArray(i))return i.map(t=>{const d=t.label||t.value||(t.itemId?t.itemId.replace(/_/g," ").replace(/\s+/g," ").replace(/\b\w/g,x=>x.toUpperCase()).trim():""),r=t.quantity?` × ${t.quantity}`:"";return`${d}${r}`}).join(", ")}catch{return s}if(n==="merchandise")try{const i=JSON.parse(s);if(Array.isArray(i))return i.length===0?null:i.map(t=>{const r=[t.label||t.value||(t.itemId?t.itemId.replace(/_/g," ").replace(/\s+/g," ").replace(/\b\w/g,x=>x.toUpperCase()).trim():"")];return t.size&&r.push(`(${t.size})`),t.quantity&&r.push(`× ${t.quantity}`),r.join(" ")}).join(", ")}catch{return s}if((s.startsWith("{")||s.startsWith("["))&&s.length>2)try{const i=JSON.parse(s);if(typeof i=="object"&&i!==null&&!Array.isArray(i))return Object.entries(i).filter(([t,d])=>d&&t!=="signature"&&typeof d!="object").map(([,t])=>String(t)).join(", ");if(Array.isArray(i))return i.join(", ")}catch{}return s};function Au(){var je,we;const{currentOrganization:s}=Je(),{data:n}=To((s==null?void 0:s.id)||null),i=da(),{toast:t}=Ht(),d=Ms(),[r,x]=a.useState(""),[c,o]=a.useState(""),[m,p]=a.useState(null),[u,l]=a.useState(null),[N,j]=a.useState(!1),[g,y]=a.useState(null),[k,S]=a.useState("percentage"),[f,h]=a.useState("100"),[M,T]=a.useState(""),[C,L]=a.useState(null),[Q,Z]=a.useState(null),[R,E]=a.useState(null),[$,b]=a.useState(null),[I,V]=a.useState(null),{data:H=[],isLoading:Y,isFetching:W}=ms({queryKey:["admin-registration-lookup",s==null?void 0:s.id,c],queryFn:async()=>{if(!(s!=null&&s.id)||!c.trim())return[];const U=c.trim(),se=/^[A-Z0-9]{6,}$/i.test(U),{data:ue,error:ve}=await z.from("events").select("id").eq("organization_id",s.id);if(ve)throw ve;if(!ue||ue.length===0)return[];const he=ue.map(He=>He.id);let ze=[];if(se){const{data:He,error:Ve}=await z.from("registrations").select(`
214            id, confirmation_number, first_name, last_name, email, phone,
215            racing_class, bike_make, bike_model, bike_cc, status, payment_status,
216            created_at, total_amount, platform_fee, date_of_birth, checked_in, checked_in_at,
217            subtotal, add_ons_total, fees_total, stripe_payment_intent_id,
218            waiver_signed, waiver_signed_at, waiver_signature_name,
219            medical_conditions, allergies, ama_number, event_id,
220            events:event_id (id, name, event_date, location, venue_name, slug, edit_deadline)
221          `).in("event_id",he).not("is_child_registration","is",!0).ilike("confirmation_number",`%${U}%`).order("created_at",{ascending:!1}).limit(50);if(Ve)throw Ve;ze=He||[]}if(!se||ze.length===0){const He=U.split(/\s+/);let Ve=z.from("registrations").select(`
222            id, confirmation_number, first_name, last_name, email, phone,
223            racing_class, bike_make, bike_model, bike_cc, status, payment_status,
224            created_at, total_amount, platform_fee, date_of_birth, checked_in, checked_in_at,
225            subtotal, add_ons_total, fees_total, stripe_payment_intent_id,
226            waiver_signed, waiver_signed_at, waiver_signature_name,
227            medical_conditions, allergies, ama_number, event_id,
228            events:event_id (id, name, event_date, location, venue_name, slug, edit_deadline)
229          `).in("event_id",he).not("is_child_registration","is",!0).order("created_at",{ascending:!1}).limit(50);He.length>=2?Ve=Ve.ilike("first_name",`%${He[0]}%`).ilike("last_name",`%${He.slice(1).join(" ")}%`):Ve=Ve.or(`first_name.ilike.%${U}%,last_name.ilike.%${U}%`);const{data:Ue,error:de}=await Ve;if(de)throw de;const Le=new Set(ze.map(ye=>ye.id));for(const ye of Ue||[])Le.has(ye.id)||ze.push(ye)}return ze},enabled:!!(s!=null&&s.id)&&!!c.trim()}),{data:te=[]}=ms({queryKey:["admin-lookup-form-responses",m],queryFn:async()=>{if(!m)return[];const{data:U,error:se}=await z.from("form_responses").select(`
230          id, field_value,
231          form_fields (label, export_label, field_type, field_order)
232        `).eq("registration_id",m);if(se)throw se;return(U||[]).sort((ue,ve)=>{var he,ze;return(((he=ue.form_fields)==null?void 0:he.field_order)||0)-(((ze=ve.form_fields)==null?void 0:ze.field_order)||0)})},enabled:!!m}),{data:B=[]}=ms({queryKey:["admin-lookup-view-form-responses",u==null?void 0:u.id],queryFn:async()=>{if(!(u!=null&&u.id))return[];const{data:U,error:se}=await z.from("form_responses").select(`
233          id, field_value,
234          form_fields:field_id (label, export_label, field_type, field_order)
235        `).eq("registration_id",u.id);if(se)throw se;return(U||[]).sort((ue,ve)=>{var he,ze;return(((he=ue.form_fields)==null?void 0:he.field_order)||0)-(((ze=ve.form_fields)==null?void 0:ze.field_order)||0)})},enabled:!!(u!=null&&u.id)}),{data:le=[]}=ms({queryKey:["admin-lookup-addons",u==null?void 0:u.id],queryFn:async()=>{if(!(u!=null&&u.id))return[];const{data:U,error:se}=await z.from("registration_add_ons").select("id, quantity, price_at_purchase, received_count, add_ons:add_on_id (name)").eq("registration_id",u.id);if(se)throw se;return U||[]},enabled:!!(u!=null&&u.id)}),Me=ks({mutationFn:async({id:U,checked_in:se})=>{const{error:ue}=await z.from("registrations").update({checked_in:se,checked_in_at:se?new Date().toISOString():null}).eq("id",U);if(ue)throw ue},onSuccess:()=>{d.invalidateQueries({queryKey:["admin-registration-lookup"]}),t({title:"Check-in status updated"})}}),_=async(U,se="confirmation",ue)=>{V(U);try{const ve={registration_id:U,email_type:se};se==="refund"&&ue&&(ve.refund_amount=ue);const{error:he}=await z.functions.invoke("send-confirmation-email",{body:ve});if(he)throw he;t({title:se==="refund"?"Refund email sent":se==="updated"?"Updated confirmation sent":"Confirmation email resent"})}catch(ve){t({title:"Failed to send email",description:ve.message||"Unknown error",variant:"destructive"})}finally{V(null)}},X=U=>{y(U),h("100"),S("percentage"),T(""),j(!0)},F=async()=>{var U,se;if(g){if(k==="percentage"){const ue=parseInt(f);if(isNaN(ue)||ue<1||ue>100){t({title:"Invalid percentage",description:"Enter a value between 1 and 100",variant:"destructive"});return}}else{const ue=parseFloat(M);if(isNaN(ue)||ue<=0){t({title:"Invalid amount",description:"Enter a dollar amount greater than 0",variant:"destructive"});return}}L(g.id),j(!1);try{const ue=parseInt(f),ve=parseFloat(M),he={registration_id:g.id};k==="percentage"?(he.refund_type=ue===100?"full":"percentage",ue<100&&(he.percentage=ue)):(he.refund_type="amount",he.amount=ve);const ze=await z.functions.invoke("process-refund",{body:he});if(ze.error)throw ze.error;const He=parseFloat((U=ze.data)==null?void 0:U.refund_amount),Ve=isNaN(He)?k==="percentage"?(g.total_amount||0)*(parseInt(f)/100):parseFloat(M
235):He,Ue=parseFloat((se=ze.data)==null?void 0:se.withheld_fees);d.invalidateQueries({queryKey:["admin-registration-lookup"]}),t({title:`$${Ve.toFixed(2)} refund processed`,description:!isNaN(Ue)&&Ue>0?`$${Ue.toFixed(2)} in processing/platform fees withheld`:void 0}),_(g.id,"refund",Ve)}catch(ue){t({title:"Refund failed",description:ue.message||"Unable to process refund",variant:"destructive"})}finally{L(null),y(null)}}},ne=async U=>{Z(U);try{const{error:se}=await z.from("registrations").update({status:"cancelled",payment_status:"cancelled"}).eq("id",U);if(se)throw se;d.invalidateQueries({queryKey:["admin-registration-lookup"]}),t({title:"Registration cancelled"})}catch(se){t({title:"Cancel failed",description:se.message,variant:"destructive"})}finally{Z(null)}},J=async U=>{b(U.id);try{await z.from("form_responses").delete().eq("registration_id",U.id),await z.from("registration_add_ons").delete().eq("registration_id",U.id);const{error:se}=await z.from("registrations").delete().eq("id",U.id);if(se)throw se;d.invalidateQueries({queryKey:["admin-registration-lookup"]}),t({title:"Registration deleted"})}catch(se){t({title:"Delete failed",description:se.message,variant:"destructive"})}finally{b(null),E(null)}},_e=U=>{U.preventDefault(),o(r),p(null)},me=(U,se)=>se==="refunded"?e.jsx(ie,{variant:"outline",className:"border-destructive text-destructive",children:"Refunded"}):se==="partially_refunded"?e.jsx(ie,{variant:"outline",className:"border-accent text-accent-foreground",children:"Partial Refund"}):(se==="completed"||se==="paid")&&U==="confirmed"?e.jsx(ie,{className:"bg-green-500/20 text-green-400 border-green-500/30",children:"Confirmed"}):U==="cancelled"?e.jsx(ie,{className:"bg-red-500/20 text-red-400 border-red-500/30",children:"Cancelled"}):e.jsx(ie,{className:"bg-orange-500/20 text-orange-400 border-orange-500/30",children:"Pending"}),$e=U=>U.filter(se=>{var He,Ve;const ue=(He=se.field_value)==null?void 0:He.trim(),ve=ue&&ue!==""&&ue!=="[]",he=(Ve=se.form_fields)==null?void 0:Ve.field_type;return ve&&(he!=="waiver"&&he!=="add_ons"&&he!=="heading"&&he!=="paragraph"&&he!=="divider"&&he!=="image"&&he!=="spacer"&&he!=="signature"&&he!=="page_break"&&he!=="line_break"&&he!=="share_and_thank")}),ee=U=>{var He,Ve,Ue;const se=(He=U.form_fields)==null?void 0:He.field_type,ue=U.field_value;if(!ue)return null;const ve=((Ve=U.form_fields)==null?void 0:Ve.export_label)||((Ue=U.form_fields)==null?void 0:Ue.label);if(!ve||["heading","divider","image","paragraph","spacer"].includes(se))return null;const he=Sr(ve),ze=Cr(ue,se);return ze?e.jsxs("div",{className:"flex justify-between text-sm py-1",children:[e.jsx("span",{className:"text-muted-foreground",children:he}),e.jsx("span",{className:"font-medium text-right max-w-[60%]",children:ze})]},U.id):null},pe=U=>e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mt-3 pt-3 border-t border-border",children:[e.jsxs(w,{variant:"outline",size:"sm",onClick:se=>{se.stopPropagation(),l(U)},children:[e.jsx(Zt,{className:"mr-1.5 h-3.5 w-3.5"})," View"]}),e.jsxs(w,{variant:"outline",size:"sm",onClick:se=>{se.stopPropagation(),i(`/admin/registrations/${U.id}/edit`)},children:[e.jsx(hr,{className:"mr-1.5 h-3.5 w-3.5"})," Edit"]}),(U.payment_status==="paid"||U.payment_status==="completed")&&e.jsx(w,{variant:U.checked_in?"outline":"default",size:"sm",className:U.checked_in?"":"bg-green-600 hover:bg-green-700",onClick:se=>{se.stopPropagation(),Me.mutate({id:U.id,checked_in:!U.checked_in})},children:U.checked_in?e.jsxs(e.Fragment,{children:[e.jsx($o,{className:"mr-1.5 h-3.5 w-3.5"})," Undo"]}):e.jsxs(e.Fragment,{children:[e.jsx(Kn,{className:"mr-1.5 h-3.5 w-3.5"})," Check In"]})}),U.status!=="cancelled"&&e.jsxs(w,{variant:"outline",size:"sm",onClick:se=>{se.stopPropagation(),X(U)},disabled:C===U.id||U.payment_status==="refunded",children:[e.jsx(_a,{className:"mr-1.5 h-3.5 w-3.5"}),U.payment_status==="refunded"?"Refunded":"Refund"]}),(U.payment_status==="paid"||U.payment_status==="completed"||U.payment_status==="refunded"||U.payment_status==="partially_refunded")&&e.jsxs(w,{variant:"outline",size:"sm",onClick:se=>{se.stopPropagation(),_(U.id,U.payment_status==="refunded"?"refund":"confirmation")},disabled:I===U.id,children:[e.jsx(gt,{className:"mr-1.5 h-3.5 w-3.5"}),I===U.id?"Sending...":"Resend"]}
235),U.status!=="cancelled"&&e.jsxs(w,{variant:"destructive",size:"sm",onClick:se=>{se.stopPropagation(),ne(U.id)},disabled:Q===U.id,children:[e.jsx(Ai,{className:"mr-1.5 h-3.5 w-3.5"})," Cancel"]}),U.status==="cancelled"&&e.jsxs(w,{variant:"outline",size:"sm",className:"text-destructive border-destructive hover:bg-destructive/10",onClick:se=>{se.stopPropagation(),E(U)},disabled:$===U.id,children:[e.jsx(ws,{className:"mr-1.5 h-3.5 w-3.5"})," Delete"]})]});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold mb-1",children:"Registration Lookup"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Search by confirmation number or rider name across all events."})]}),e.jsxs("form",{onSubmit:_e,className:"flex gap-3 max-w-xl","data-tour":"lookup-search",children:[e.jsx(A,{placeholder:"Confirmation number or rider name...",value:r,onChange:U=>x(U.target.value),className:"flex-1"}),e.jsxs(w,{type:"submit",disabled:!r.trim()||W,children:[W?e.jsx(oe,{className:"h-4 w-4 animate-spin"}):e.jsx(Ws,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2",children:"Search"})]})]}),Y&&!W?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(oe,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):c&&H.length===0&&!W?e.jsx(re,{children:e.jsxs(xe,{className:"py-12 text-center",children:[e.jsx(Ws,{className:"h-12 w-12 mx-auto mb-4 opacity-30"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No Results Found"}),e.jsxs("p",{className:"text-muted-foreground",children:['No registrations found for "',c,'".']})]})}):H.length>0?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[H.length," registration",H.length!==1?"s":""," found"]}),H.map(U=>{var se,ue,ve;return e.jsxs(re,{className:"overflow-hidden",children:[e.jsx(ke,{className:"pb-2 cursor-pointer hover:bg-muted/30 transition-colors",onClick:()=>p(m===U.id?null:U.id),children:e.jsxs("div",{className:"flex justify-between items-start",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs(Ee,{className:"text-lg flex items-center gap-2",children:[U.first_name," ",U.last_name,U.checked_in&&e.jsx(ie,{variant:"outline",className:"border-green-500 text-green-500 text-xs",children:"Checked In"}),m===U.id?e.jsx(Ar,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(mt,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1 text-sm text-muted-foreground mt-1",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ai,{className:"h-3 w-3"}),U.confirmation_number]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(At,{className:"h-3 w-3"}),((se=U.events)==null?void 0:se.name)||"Unknown Event"]}),((ue=U.events)==null?void 0:ue.event_date)&&e.jsx("span",{children:Js(Vt(U.events.event_date),"MMM d, yyyy")}),e.jsxs("span",{title:"Net to your org after BeyondPro & Stripe fees",children:["$",nn(U,n||null).net.toFixed(2)," net"]})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:me(U.status,U.payment_status)})]})}),m===U.id&&e.jsx(xe,{className:"pt-0",children:e.jsxs("div",{className:"border-t pt-4 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Ks,{className:"h-3.5 w-3.5"}),U.email]}),U.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Rt,{className:"h-3.5 w-3.5"}),U.phone]})]}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Charged to rider"}),e.jsxs("span",{className:"font-medium",children:["$",((ve=U.total_amount)==null?void 0:ve.toFixed(2))||"0.00"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Net to your org"}),e.jsxs("span",{className:"font-medium text-primary",children:["$",nn(U,n||null).net.toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Registered"}),e.jsx("span",{children:Js(new Date(U.created_at),"MMM d, yyyy h:mm a")})]}),U.bike_make&&e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Bike"}),e.jsxs("span",{children:[U.bike_make," ",U.bike_model," ",U.bike_cc]})]})]})]}),te.length>0&&e.jsxs("div",{className:"border-t pt-3",children:[e.jsx("h4",{className:"text-sm font-semibold mb-2",children:"Registration Details"}),e.jsx("div",{className:"space-y-0.5",children:te.map(he=>ee(he))})]}),pe(U)]})})]},U.id)})]}):null,e.jsx(ts,{open:!!u,onOpenChange:()=>l(null),children:e.jsxs(as,{className:"max-w-2xl h-[90vh] bg-card border-border overflow-hidden p-0",children:[e.jsxs(rs,{className:"px-6 pt-6 pb-2",children:[e.jsx(is,{children:"Registration Details"}),e.jsx(Fs,{children:"Complete registration information"})]}),u&&e.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[e.jsx(qs,{className:"flex-1 min-h-0 px-6",children:e.jsxs("div",{className:"space-y-6 pr-4 pb-6",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsx("span",{className:"font-mono text-lg text-primary",children:u.confirmation_number}),e.jsxs("div",{className:"flex gap-2",children:[me(u.status,u.payment_status),u.checked_in&&e.jsx(ie,{variant:"outline",className:"border-green-500 text-green-500",children:"Checked In"})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-foreground mb-2",children:"Rider Information"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground block",children:"Name"}),e.jsxs("span",{className:"text-foreground",children:[u.first_name," ",u.last_name]})]}),u.date_of_birth&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground block",children:"Date of Birth"}),e.jsx("span",{className:"text-foreground",children:(()=>{const U=u.date_of_birth,se=String(U).match(/^(\d{4})-(\d{2})-(\d{2})/),ue=se?new Date(Number(se[1]),Number(se[2])-1,Number(se[3])):new Date(U);return Js(ue,"MMM d, yyyy")})()})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ks,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-foreground",children:u.email})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-foreground",children:u.phone})]})]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground text-sm",children:"Event"}),e.jsxs("p",{className:"text-foreground font-medium",children:[(je=u.events)==null?void 0:je.name,((we=u.events)==null?void 0:we.event_date)&&` — ${Js(Vt(u.events.event_date),"MMM d, yyyy")}`]})]}),$e(B).length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-semibold text-foreground mb-2 flex items-center gap-2",children:[e.jsx(Gr,{className:"h-4 w-4"}),e.jsx("span",{children:"Form Responses"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 text-sm",children:$e(B).map(U=>{var ue,ve,he;const se=Cr(U.field_value,(ue=U.form_fields)==null?void 0:ue.field_type);return e.jsxs("div",{className:"p-2 bg-muted/50 rounded",children:[e.jsx("span",{className:"text-muted-foreground block text-xs",children:Sr(((ve=U.form_fields)==null?void 0:ve.export_label)||((he=U.form_fields)==null?void 0:he.label)||"Field")}),e.jsx("span",{className:"text-foreground",children:se||"-"})]},U.id)})})]}),(u.medical_conditions||u.allergies)&&e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-foreground mb-2",children:"Medical Information"}),e.jsxs("div",{className:"space-y-2 text-sm",children:[u.medical_conditions&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground block",children:"Medical Conditions"}),e.jsx("span",{className:"text-foreground",children:u.medical_conditions})]}),u.allergies&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground block",children:"Allergies"}),e.jsx("span",{className:"text-foreground",children:u.allergies})]})]})]}),u.waiver_signed&&e.jsxs("div",{className:"p-3 rounded-md bg-green-500/10 border border-green-500/20",children:[e.jsxs("div",{className:"flex items-center gap-2 text-green-500",children:[e.jsx(Ro,{className:"h-4 w-4"}),e.jsx("span",{className:"font-semibold",children:"Waiver Signed"})]}),u.waiver_signed_at&&e.jsxs("div",{className:"text-sm text-muted-foreground mt-1",children:["Signed on ",Js(new Date(u.waiver_signed_at),"MMM d, yyyy h:mm a")]})]}),le.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-semibold text-foreground mb-2 flex items-center gap-2",children:[e.jsx(ri,{className:"h-4 w-4"}),e.jsx("span",{children:"Add-ons"})]}),e.jsx("div",{className:"space-y-2",children:le.map(U=>{var ue;const se=(U.received_count??0)>=U.quantity;return e.jsxs("div",{className:"text-sm p-2 bg-muted/50 rounded",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:`${se?"line-through opacity-60":""}`,children:[(ue=U.add_ons)==null?void 0:ue.name,e.jsxs("span",{className:"ml-1 text-xs text-muted-foreground",children:["(",U.received_count??0,"/",U.quantity,")"]})]}),e.jsxs("span",{className:"text-muted-foreground",children:["$",(U.price_at_purchase*U.quantity).toFixed(2)]})]}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-1",children:Array.from({length:U.quantity},(ve,he)=>{var He,Ve;const ze=he<(U.received_count??0);return e.jsxs("label",{className:"flex items-center gap-1 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:ze,onChange:async()=>{const Ue=U.received_count??0,de=ze?Ue-1:Ue+1;await z.from("registration_add_ons").update({received_count:de}).eq("id",U.id),d.invalidateQueries({queryKey:["admin-lookup-addons",u==null?void 0:u.id]})}
235,className:"h-4 w-4 rounded border-primary text-primary focus:ring-primary cursor-pointer"}),e.jsx("span",{className:`text-xs ${ze?"text-success line-through":"text-muted-foreground"}`,children:U.quantity>1?`${(He=U.add_ons)==null?void 0:He.name} #${he+1}`:`${(Ve=U.add_ons)==null?void 0:Ve.name} — Received`})]},he)})}),se&&e.jsx(Oa,{className:"h-4 w-4 text-success inline ml-1"})]},U.id)})})]}),e.jsxs("div",{className:"border-t border-border pt-4 bg-muted/30 -mx-6 px-6 pb-4 mt-4",children:[e.jsx("h4",{className:"font-semibold text-foreground mb-3 text-base",children:"PAYMENT SUMMARY"}),e.jsx("div",{className:"space-y-2 text-sm w-full",children:(()=>{const U=nn(u,n||null),se=Number(u.subtotal||0),ue=Number(u.add_ons_total||0),ve=Number(u.total_amount||0)||se+ue,he=Math.max(0,+(ve-U.net).toFixed(2));return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Total"}),e.jsxs("span",{className:"font-medium text-foreground",children:["$",ve.toFixed(2)]})]}),he>0&&e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"− Fees"}),e.jsxs("span",{className:"text-muted-foreground",children:["−$",he.toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between font-semibold pt-2 border-t border-border text-base",children:[e.jsx("span",{className:"text-foreground",children:"Net"}),e.jsxs("span",{className:"text-primary",children:["$",U.net.toFixed(2)]})]})]})})()})]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-1",children:[e.jsxs("div",{children:["Registered: ",Js(new Date(u.created_at),"MMM d, yyyy h:mm a")]}),u.checked_in&&u.checked_in_at&&e.jsxs("div",{children:["Checked In: ",Js(new Date(u.checked_in_at),"MMM d, yyyy h:mm a")]})]})]})}),e.jsx("div",{className:"border-t border-border p-4 bg-card shrink-0",children:e.jsxs(w,{variant:"default",onClick:()=>{const U=u.id;l(null),i(`/admin/registrations/${U}/edit`)},className:"w-full",children:[e.jsx(hr,{className:"mr-2 h-4 w-4"})," Edit Registration"]})})]})]})}),e.jsx(ts,{open:N,onOpenChange:j,children:e.jsxs(as,{className:"max-w-sm",children:[e.jsxs(rs,{children:[e.jsx(is,{children:"Process Refund"}),e.jsx(Fs,{children:"Choose refund type and amount. Card processing and platform fees are automatically withheld and not refunded."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(w,{variant:k==="percentage"?"default":"outline",size:"sm",onClick:()=>S("percentage"),children:"Percentage"}),e.jsx(w,{variant:k==="amount"?"default":"outline",size:"sm",onClick:()=>S("amount"),children:"Dollar Amount"})]}),k==="percentage"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{children:"Refund Percentage"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(A,{type:"number",min:"1",max:"100",value:f,onChange:U=>h(U.target.value),className:"w-24"}),e.jsx("span",{className:"text-muted-foreground",children:"%"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{children:"Refund Amount"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"$"}),e.jsx(A,{type:"number",min:"0.01",step:"0.01",value:M,onChange:U=>T(U.target.value),className:"w-32",placeholder:"0.00"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(w,{variant:"outline",onClick:()=>j(!1),children:"Cancel"}),e.jsx(w,{onClick:F,children:"Process Refund"})]})]})]})}),e.jsx(et,{open:!!R,onOpenChange:U=>!U&&E(null),children:e.jsxs(st,{children:[e.jsxs(Et,{children:[e.jsx(tt,{children:"Delete Registration"}),e.jsxs(at,{children:["Are you sure you want to permanently delete the registration for"," ",e.jsxs("strong",{children:[R==null?void 0:R.first_name," ",R==null?void 0:R.last_name]})," (",R==null?void 0:R.confirmation_number,")? This action cannot be undone."]})]}),e.jsxs(Mt,{children:[e.jsx(nt,{children:"Cancel"}),e.jsx(rt,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>R&&J(R),children:"Delete"})]})]})})]})}
235function Lu(s,n){if(!s||!n)return null;const[i,t,d]=s.split("-").map(Number),[r,x,c]=n.split("-").map(Number);return!i||!t||!d||!r||!x||!c?null:Math.abs(Math.floor((Date.UTC(i,t-1,d)-Date.UTC(r,x-1,c))/864e5))}function Pu(s,n,i){return!s||!n||!i?null:`${String(s).padStart(4,"0")}-${String(n).padStart(2,"0")}-${String(i).padStart(2,"0")}`}function Iu({open:s,onOpenChange:n,memberNumber:i,familyMemberId:t,initial:d,familyMember:r,onSaved:x}){const{toast:c}=Ht(),{currentOrganization:o}=Je(),m=Ms(),[p,u]=a.useState(!1),[l,N]=a.useState(""),[j,g]=a.useState(""),[y,k]=a.useState(""),[S,f]=a.useState(""),[h,M]=a.useState(!1),[T,C]=a.useState(""),[L,Q]=a.useState(""),[Z,R]=a.useState(""),[E,$]=a.useState(""),[b,I]=a.useState(""),[V,H]=a.useState(""),[Y,W]=a.useState(""),[te,B]=a.useState(""),[le,Me]=a.useState(""),[_,X]=a.useState(""),[F,ne]=a.useState(""),[J,_e]=a.useState(""),[me,$e]=a.useState(""),[ee,pe]=a.useState(""),[je,we]=a.useState("N"),[U,se]=a.useState("N"),[ue,ve]=a.useState("");a.useEffect(()=>{if(!s)return;const de=r??{};N((de.first_name??d.first_name??"").toString()),g((de.middle_initial??d.middle_initial??"").toString()),k((de.last_name??d.last_name??"").toString());const Le=de.date_of_birth??(de.birth_year?Pu(Number(de.birth_year),Number(de.birth_month),Number(de.birth_day)):null)??d.dob;f(Le??""),M(!1),C((de.phone_number??"").toString()),Q((de.email??"").toString()),R((de.address??"").toString()),$((de.city??"").toString()),I((de.state??"").toString()),H((de.zip??"").toString()),W((de.country??"").toString()),B((de.sex??"").toString()),Me(""),X((de.team??"").toString()),ne((de.sponsors??"").toString()),_e((de.ama_member_id??"").toString()),$e((de.ama_exp_date??"").toString()),pe((de.cmc_member_id??"").toString()),we(de.club_member?"Y":"N"),se(de.license_suspended?"Y":"N"),ve((de.transponder_id??"").toString())},[s,r,d.first_name,d.middle_initial,d.last_name,d.dob]);const he=Lu(d.dob,S||null),ze=S&&d.dob&&he!=null&&he>7,He=!!ze,Ve=l.trim().length>0&&y.trim().length>0&&(!He||h)&&!p,Ue=async()=>{if(o!=null&&o.id){u(!0);try{const{data:de,error:Le}=await z.functions.invoke("edit-rider-identity",{body:{organization_id:o.id,member_number:i,family_member_id:t??null,first_name:l.trim(),middle_initial:j.trim()||null,last_name:y.trim(),dob:S||null,phone:T.trim()||null,email:L.trim()||null,address:Z.trim()||null,city:E.trim()||null,state:b.trim()||null,zip:V.trim()||null,country:Y.trim()||null,sex:te||null,age:le||null,team:_.trim()||null,sponsors:F.trim()||null,ama_member_id:J.trim()||null,ama_exp_date:me.trim()||null,cmc_member_id:ee.trim()||null,club_member:je||"N",license_suspended:U||"N",transponder:ue.trim()||null}});if(Le)throw Le;
235if(de!=null&&de.error)throw new Error(de.error);m.invalidateQueries({queryKey:["rider-database-search"]}),m.invalidateQueries({queryKey:["rider-database-detail"]}),m.invalidateQueries({queryKey:["rider-family-members"]}),m.invalidateQueries({queryKey:["timing-lab-riders"]});const ye=de,Ze=((ye==null?void 0:ye.errors)??[]).length?` Warnings: ${ye.errors.join("; ")}`:"";c({title:"Rider profile updated",description:`Saved to their master profile, ${(ye==null?void 0:ye.lab_rows_updated)??0} Timing Lab roster row(s) across all orgs, and ${(ye==null?void 0:ye.registrations_updated)??0} registration(s).${Ze}`,variant:((ye==null?void 0:ye.errors)??[]).length?"destructive":void 0}),n(!1),x==null||x()}catch(de){c({title:"Save failed",description:de.message,variant:"destructive"})}finally{u(!1)}}};return e.jsx(ts,{open:s,onOpenChange:n,children:e.jsxs(as,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(rs,{children:[e.jsx(is,{children:"Edit Rider Info"}),e.jsx(Fs,{children:"Edits save to the rider's master profile and persist everywhere: name, date of birth, contact, and address fan out to every organization's Timing Lab roster and to their registrations."})]}),e.jsxs(ot,{defaultValue:"identity",children:[e.jsxs(pt,{className:"grid grid-cols-5 w-full",children:[e.jsx(Qe,{value:"identity",children:"Identity"}),e.jsx(Qe,{value:"contact",children:"Contact"}),e.jsx(Qe,{value:"address",children:"Address"}),e.jsx(Qe,{value:"demo",children:"Demographics"}),e.jsx(Qe,{value:"memberships",children:"Memberships"})]}),e.jsxs(Ae,{value:"identity",className:"space-y-3 pt-3",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(v,{children:"First name"}),e.jsx(A,{value:l,onChange:de=>N(de.target.value)})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Middle initial"}),e.jsx(A,{maxLength:4,value:j,onChange:de=>g(de.target.value)})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Last name"}),e.jsx(A,{value:y,onChange:de=>k(de.target.value)})]})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Date of birth"}),e.jsx(A,{type:"date",value:S,onChange:de=>f(de.target.value)})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Transponder (EPC)"}),e.jsx(A,{value:ue,onChange:de=>ve(de.target.value),placeholder:"Hex EPC"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Changing this will fan out to peer orgs."})]}),ze&&e.jsxs("div",{className:"flex items-start gap-2 rounded border border-destructive/40 bg-destructive/5 p-2 text-sm",children:[e.jsx(Is,{className:"h-4 w-4 mt-0.5 text-destructive shrink-0"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{children:["DOB is changing by ",e.jsxs("strong",{children:[he," days"]}),". Typos are usually ±1 day."]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(As,{checked:h,onCheckedChange:de=>M(de===!0)}),"Yes, this is a real DOB correction."]})]})]})]}),e.jsxs(Ae,{value:"contact",className:"space-y-3 pt-3",children:[e.jsxs("div",{children:[e.jsx(v,{children:"Phone"}),e.jsx(A,{value:T,onChange:de=>C(de.target.value),placeholder:"digits only"})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Email"}),e.jsx(A,{type:"email",value:L,onChange:de=>Q(de.target.value)})]})]}),e.jsxs(Ae,{value:"address",className:"space-y-3 pt-3",children:[e.jsxs("div",{children:[e.jsx(v,{children:"Street address"}),e.jsx(A,{value:Z,onChange:de=>R(de.target.value)})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx(v,{children:"City"}),e.jsx(A,{value:E,onChange:de=>$(de.target.value)})]}),e.jsxs("div",{children:[e.jsx(v,{children:"State"}),e.jsx(A,{maxLength:2,value:b,onChange:de=>I(de.target.value.toUpperCase())})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(v,{children:"ZIP"}),e.jsx(A,{value:V,onChange:de=>H(de.target.value)})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Country"}),e.jsx(A,{value:Y,onChange:de=>W(de.target.value)})]})]})]}),e.jsxs(Ae,{value:"demo",className:"space-y-3 pt-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(v,{children:"Sex"}),e.jsxs(Pe,{value:te||"unset",onValueChange:de=>B(de==="unset"?"":de),children:[e.jsx(Ie,{children:e.jsx(qe,{placeholder:"—"})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"unset",children:"—"}),e.jsx(ae,{value:"M",children:"M"}),e.jsx(ae,{value:"F",children:"F"})]})]})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Age"}),e.jsx(A,{type:"number",min:0,value:le,onChange:de=>Me(de.target.value)})]})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Team"}
235),e.jsx(A,{value:_,onChange:de=>X(de.target.value)})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Sponsors"}),e.jsx(A,{value:F,onChange:de=>ne(de.target.value)})]})]}),e.jsxs(Ae,{value:"memberships",className:"space-y-3 pt-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(v,{children:"AMA #"}),e.jsx(A,{value:J,onChange:de=>_e(de.target.value)})]}),e.jsxs("div",{children:[e.jsx(v,{children:"AMA expiration"}),e.jsx(A,{value:me,onChange:de=>$e(de.target.value),placeholder:"YYYY-MM-DD"})]})]}),e.jsxs("div",{children:[e.jsx(v,{children:"CMC #"}),e.jsx(A,{value:ee,onChange:de=>pe(de.target.value)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(v,{children:"Club member"}),e.jsxs(Pe,{value:je,onValueChange:we,children:[e.jsx(Ie,{children:e.jsx(qe,{})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"Y",children:"Yes"}),e.jsx(ae,{value:"N",children:"No"})]})]})]}),e.jsxs("div",{children:[e.jsx(v,{children:"License suspended"}),e.jsxs(Pe,{value:U,onValueChange:se,children:[e.jsx(Ie,{children:e.jsx(qe,{})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"Y",children:"Yes"}),e.jsx(ae,{value:"N",children:"No"})]})]})]})]})]})]}),e.jsxs(Ys,{children:[e.jsx(w,{variant:"outline",onClick:()=>n(!1),disabled:p,children:"Cancel"}),e.jsxs(w,{onClick:Ue,disabled:!Ve,children:[p&&e.jsx(oe,{className:"h-4 w-4 mr-1 animate-spin"}),"Save changes"]})]})]})})}function kr(s){try{return new Date(s).toLocaleString()}catch{return s}}function qu({memberNumber:s}){const{toast:n}=Ht(),{data:i,isLoading:t}=Do(s),d=Fo(),[r,x]=a.useState(null),c=i??[],o=async()=>{if(r)try{const m=await d.mutateAsync({snapshot_id:r.id});n({title:"Merge undone",description:`#${m.duplicate_member_number} is its own rider again.${m.mysql_restored?" MySQL row restored — public results will refresh on next sync.":m.mysql_error?` MySQL restore skipped: ${m.mysql_error}`:""}`}),x(null)}catch(m){n({title:"Undo failed",description:m.message,variant:"destructive"})}};return e.jsxs(e.Fragment,{children:[e.jsxs(re,{children:[e.jsx(ke,{className:"pb-2",children:e.jsxs(Ee,{className:"text-base flex items-center gap-2",children:[e.jsx(Pi,{className:"h-4 w-4"})," Merge History",e.jsxs("span",{className:"text-xs font-normal text-muted-foreground",children:["(",c.length,")"]})]})}),e.jsx(xe,{className:"space-y-2",children:t?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-2",children:[e.jsx(oe,{className:"h-4 w-4 animate-spin"})," Loading…"]}):c.length===0?e.jsx("div",{className:"text-sm text-muted-foreground italic py-2",children:"No merges recorded for this rider."}):c.map(m=>{const p=m.canonical_member_number===s,u=[m.duplicate_first_name,m.duplicate_last_name].filter(Boolean).join(" "),l=!m.undone_at&&!!m.duplicate_mysql_row;return e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded border p-2 text-sm",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"font-medium",children:["#",m.duplicate_member_number,u&&e.jsxs("span",{className:"text-muted-foreground",children:[" — ",u]})," ",e.jsx("span",{className:"text-muted-foreground",children:"merged into"})," #",m.canonical_member_number,!p&&e.jsx(ie,{variant:"outline",className:"ml-2 text-[10px]",children:"this rider was absorbed"})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:kr(m.merged_at)}),m.undone_at&&e.jsxs("div",{className:"text-xs text-muted-foreground italic",children:["Undone ",kr(m.undone_at)]})]}),m.undone_at?e.jsx(ie,{variant:"secondary",children:"Undone"}):e.jsxs(w,{size:"sm",variant:"outline",disabled:!l,title:l?"Split this duplicate back out as its own rider":"No MySQL snapshot was captured for this merge — undo not possible. Edit the canonical name instead, or contact support.",onClick:()=>x(m),children:[e.jsx(Rl,{className:"h-3.5 w-3.5 mr-1"}),"Undo merge"]})]},m.id)})})]}),e.jsx(et,{open:!!r,onOpenChange:m=>!m&&x(null),children:e.jsxs(st,{children:[e.jsxs(Et,{children:[e.jsx(tt,{children:"Undo this merge?"}),e.jsx(at,{asChild:!0,children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{children:["#",r==null?void 0:r.duplicate_member_number," will be split back out as its own rider with its original name and DOB."]}),e.jsxs("p",{className:"text-amber-700",children:[e.jsx("strong",{children:"Race results are not touched."})," Any finalized results / points / laps that were attributed to #",r==null?void 0:r.canonical_member_number," stay where they are. If specific race entries should follow the duplicate back, fix those manually after the undo."]})]})})]}),e.jsxs(Mt,{children:[e.jsx(nt,{disabled:d.isPending,children:"Cancel"}),e.jsxs(rt,{onClick:o,disabled:d.isPending,children:[d.isPending&&e.jsx(oe,{className:"h-4 w-4 mr-1 animate-spin"}),"Undo merge"]})]})]})})]})}const Xt=({label:s})=>e.jsxs(ie,{variant:"destructive",className:"gap-1",children:[e.jsx(Is,{className:"h-3 w-3"})," Missing ",s]}),$s=({label:s,value:n})=>e.jsxs("div",{className:"flex items-baseline justify-between gap-3 py-1",children:[e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:s}),e.jsx("span",{className:"text-sm font-medium text-right break-all",children:n||e.jsx("span",{className:"text-muted-foreground italic",children:"—"})})]});function Er(s){if(!s)return null;const[n,i,t]=s.split("-").map(d=>Number(d));return!n||!i||!t?s:`${i}/${t}/${n}`}
235function _l({detail:s}){var x,c,o,m,p,u,l,N,j,g;const[n,i]=a.useState(!1);if(s.error||s.org_scoped===!1)return e.jsx(re,{children:e.jsx(xe,{className:"py-10 text-center text-sm text-muted-foreground",children:s.error??"Rider not found in this organization."})});const t=s.identity,d=s.contact,r=new Set(s.missing??[]);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(re,{children:e.jsx(ke,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(Ee,{className:"text-xl",children:[t.first_name??"?"," ",t.last_name??""]}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-2",children:[t.member_number!=null?e.jsxs(ie,{variant:"secondary",children:["#",t.member_number]}):e.jsx(Xt,{label:"member #"}),t.date_of_birth?e.jsxs(ie,{variant:"outline",children:["DOB ",Er(t.date_of_birth)]}):e.jsx(Xt,{label:"DOB"}),t.sex&&e.jsx(ie,{variant:"outline",children:t.sex})]})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[r.size>0&&e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"text-xs uppercase text-muted-foreground",children:"Data gaps"}),e.jsx("div",{className:"text-2xl font-bold text-destructive",children:r.size})]}),t.member_number!=null&&e.jsxs(w,{size:"sm",variant:"outline",onClick:()=>i(!0),children:[e.jsx(Ft,{className:"h-3.5 w-3.5 mr-1"}),"Edit rider info"]})]})]})})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(re,{children:[e.jsx(ke,{className:"pb-2",children:e.jsxs(Ee,{className:"text-base flex items-center gap-2",children:[e.jsx(Rt,{className:"h-4 w-4"})," Contact"]})}),e.jsxs(xe,{className:"space-y-1",children:[e.jsx($s,{label:"Phone",value:d.phone||(r.has("phone")?e.jsx(Xt,{label:""}):null)}),e.jsx($s,{label:"Primary email",value:d.primary_email||(r.has("email")?e.jsx(Xt,{label:""}):null)}),d.linked_emails.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(St,{className:"my-2"}),e.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Linked emails"}),d.linked_emails.map((y,k)=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"break-all",children:y.email}),e.jsx(ie,{variant:y.is_verified?"secondary":"outline",className:"ml-2",children:y.is_verified?"verified":"pending"})]},k))]}),d.address&&(d.address.address||d.address.city)&&e.jsxs(e.Fragment,{children:[e.jsx(St,{className:"my-2"}),e.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Address (MySQL)"}),e.jsxs("div",{className:"text-sm",children:[d.address.address&&e.jsx("div",{children:d.address.address}),e.jsx("div",{children:[d.address.city,d.address.state,d.address.zip].filter(Boolean).join(", ")}),d.address.country&&e.jsx("div",{className:"text-muted-foreground",children:d.address.country})]})]})]})]}),e.jsxs(re,{children:[e.jsx(ke,{className:"pb-2",children:e.jsxs(Ee,{className:"text-base flex items-center gap-2",children:[e.jsx(Xs,{className:"h-4 w-4"})," Login Account"]})}),e.jsx(xe,{className:"space-y-1",children:s.account?e.jsxs(e.Fragment,{children:[e.jsx($s,{label:"Email",value:s.account.email}),e.jsx($s,{label:"Full name",value:s.account.full_name}),e.jsx($s,{label:"Created",value:s.account.created_at?new Date(s.account.created_at).toLocaleDateString():null})]}):e.jsx("div",{className:"py-4 text-sm",children:e.jsx(Xt,{label:"rider has no PG login account"})})})]}),e.jsxs(re,{children:[e.jsx(ke,{className:"pb-2",children:e.jsxs(Ee,{className:"text-base flex items-center gap-2",children:[e.jsx(la,{className:"h-4 w-4"})," Timing Lab Profile"]})}),e.jsx(xe,{className:"space-y-1",children:s.lab_rider?e.jsxs(e.Fragment,{children:[e.jsx($s,{label:"Bike #",value:s.lab_rider.primary_bike_number}),e.jsx($s,{label:"Bike make",value:s.lab_rider.bike_make}),e.jsx($s,{label:"City / State",value:[s.lab_rider.city,s.lab_rider.state].filter(Boolean).join(", ")}),e.jsx($s,{label:"Transponder",value:s.lab_rider.transponder_id}),s.lab_rider.locally_edited&&e.jsx(ie,{variant:"outline",className:"mt-1",children:"Locally edited"})]}):e.jsx("div",{className:"py-4 text-sm text-muted-foreground italic",children:"No timing lab record yet."})})]}),e.jsxs(re,{children:[e.jsx(ke,{className:"pb-2",children:e.jsxs(Ee,{className:"text-base flex items-center gap-2",children:[e.jsx(Wr,{className:"h-4 w-4"}
235)," Transponders (",(s.transponders??[]).filter(y=>y.is_active).length," active)"]})}),e.jsx(xe,{className:"space-y-2",children:(s.transponders??[]).length===0?e.jsx("div",{className:"py-2",children:e.jsx(Xt,{label:"no transponder assigned"})}):(s.transponders??[]).map((y,k)=>e.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[e.jsx("code",{className:"font-mono break-all",children:y.epc}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[y.is_primary&&e.jsx(Ur,{className:"h-3 w-3 fill-current"}),e.jsx(ie,{variant:y.is_active?"secondary":"outline",children:y.is_active?"active":"retired"})]})]},k))})]}),e.jsxs(re,{children:[e.jsx(ke,{className:"pb-2",children:e.jsxs(Ee,{className:"text-base flex items-center gap-2",children:[e.jsx(la,{className:"h-4 w-4"})," Org Activity"]})}),e.jsxs(xe,{className:"space-y-1",children:[e.jsx($s,{label:"Registrations",value:((x=s.org_activity)==null?void 0:x.registration_count)??0}),e.jsx($s,{label:"Last event",value:(c=s.org_activity)!=null&&c.last_event?`${s.org_activity.last_event.name}${s.org_activity.last_event.date?` (${Er(s.org_activity.last_event.date)})`:""}`:null}),e.jsx($s,{label:"Wallet balance",value:`$${(((o=s.org_activity)==null?void 0:o.wallet_balance)??0).toFixed(2)}`}),e.jsx($s,{label:"Wallet transactions",value:((m=s.org_activity)==null?void 0:m.wallet_transaction_count)??0}),e.jsx($s,{label:"Active coupons",value:((p=s.org_activity)==null?void 0:p.coupon_count)??0})]})]}),e.jsxs(re,{children:[e.jsx(ke,{className:"pb-2",children:e.jsxs(Ee,{className:"text-base flex items-center gap-2",children:[e.jsx(Tt,{className:"h-4 w-4"})," MySQL riderinfo"]})}),e.jsx(xe,{className:"space-y-1",children:(u=s.mysql)!=null&&u.error?e.jsx("div",{className:"text-sm text-destructive",children:s.mysql.error}):(l=s.mysql)!=null&&l.row?e.jsxs(e.Fragment,{children:[e.jsx($s,{label:"Member #",value:s.mysql.row.memberNumber}),e.jsx($s,{label:"Name",value:`${s.mysql.row.firstName??""} ${s.mysql.row.lastName??""}`.trim()}),e.jsx($s,{label:"DOB",value:s.mysql.row.birthYear?`${s.mysql.row.birthMonth}/${s.mysql.row.birthDay}/${s.mysql.row.birthYear}`:null}),e.jsx($s,{label:"Phone",value:s.mysql.row.phoneNumber}),e.jsx($s,{label:"Email",value:s.mysql.row.email}),e.jsx($s,{label:"Transponder",value:s.mysql.row.transponder_id}),e.jsx($s,{label:"AMA #",value:s.mysql.row.amaMemberId}),e.jsx($s,{label:"CMC #",value:s.mysql.row.cmcMemberId}),e.jsx($s,{label:"Team",value:s.mysql.row.team}),e.jsx($s,{label:"Sponsors",value:s.mysql.row.sponsors})]}):e.jsx("div",{className:"py-2 text-sm text-muted-foreground italic",children:"No MySQL record for this member number."})})]})]}),(((j=(N=s.org_activity)==null?void 0:N.registrations)==null?void 0:j.length)??0)>0&&e.jsxs(re,{children:[e.jsx(ke,{className:"pb-2",children:e.jsx(Ee,{className:"text-base",children:"Recent registrations"})}),e.jsx(xe,{className:"space-y-1",children:s.org_activity.registrations.slice(0,10).map(y=>e.jsxs("div",{className:"flex items-center justify-between text-sm py-1 border-b last:border-0",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:y.event_name}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[y.first_name," ",y.last_name," · ",new Date(y.created_at).toLocaleDateString()]})]}),e.jsx(ie,{variant:y.status==="confirmed"?"secondary":"outline",children:y.status})]},y.id))})]}),t.member_number!=null&&e.jsx(qu,{memberNumber:t.member_number}),t.member_number!=null&&e.jsx(Iu,{open:n,onOpenChange:i,memberNumber:t.member_number,familyMemberId:((g=s.family_member)==null?void 0:g.id)??null,initial:{first_name:t.first_name,last_name:t.last_name,dob:t.date_of_birth,middle_initial:null},familyMember:s.family_member??null})]})}function Mr({hit:s,hits:n,defaultCanonical:i,open:t,onOpenChange:d}){const{toast:r}=Ht(),x=Ao(),c=a.useMemo(()=>{if(n&&n.length>0){const y=[],k=new Set;for(const S of n){const f=[...S.member_number!=null?[S.member_number]:[],...S.duplicate_member_numbers??[]];for(const h of f)!Number.isFinite(h)||k.has(h)||(k.add(h),y.push({number:h,label:`#${h} — ${S.first_name??""} ${S.last_name??""}
235`.trim(),sub:[S.email,S.phone,S.dob].filter(Boolean).join(" · ")||void 0}))}return y}if(s){const y=[...s.member_number!=null?[s.member_number]:[],...s.duplicate_member_numbers??[]],k=`${s.first_name??""} ${s.last_name??""}`.trim();return y.map(S=>({number:S,label:`#${S}${k?` — ${k}`:""}`}))}return[]},[s,n]),[o,m]=a.useState(""),[p,u]=a.useState(!1);if(a.useEffect(()=>{if(!t)return;if(u(!1),c.length===0){m("");return}if(i!=null&&c.some(k=>k.number===i)){m(String(i));return}const y=[...c].sort((k,S)=>k.number-S.number)[0];m(String(y.number))},[t,c,i]),c.length===0)return null;const l=n&&n.length>0?`Merge ${c.length} member numbers`:`Resolve duplicates for ${(s==null?void 0:s.first_name)??""} ${(s==null?void 0:s.last_name)??""}`.trim(),N=async()=>{const y=Number(o);if(!Number.isFinite(y))return;const k=c.map(S=>S.number).filter(S=>S!==y);if(k.length===0){d(!1);return}try{await x.mutateAsync({canonical_member_number:y,duplicate_member_numbers:k}),r({title:"Merged",description:`${k.length} alternate number${k.length===1?"":"s"} now resolve to #${y}.`}),d(!1)}catch(S){r({title:"Merge failed",description:S.message,variant:"destructive"})}},j=Number(o),g=c.filter(y=>y.number!==j);return e.jsx(ts,{open:t,onOpenChange:d,children:e.jsxs(as,{children:[e.jsx(rs,{children:e.jsx(is,{children:l})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Select the record you want to ",e.jsx("strong",{children:"KEEP"}),". All others will be merged into it and aliased everywhere — results, kiosk, registrations, and timing lab. This cannot be easily undone, so double-check the spelling and history below."]}),e.jsx(ut,{value:o,onValueChange:m,className:"space-y-2",children:c.map(y=>{const k=y.number===j;return e.jsxs("div",{className:"flex items-start gap-2 rounded border p-2 transition-colors "+(k?"border-primary bg-primary/5 ring-1 ring-primary/40":"border-destructive/40 bg-destructive/5"),children:[e.jsx(js,{value:String(y.number),id:`mn-${y.number}`,className:"mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(v,{htmlFor:`mn-${y.number}`,className:"font-medium cursor-pointer",children:y.label}),k?e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide text-primary bg-primary/10 px-1.5 py-0.5 rounded",children:"Keep (canonical)"}):e.jsxs("span",{className:"text-[10px] font-semibold uppercase tracking-wide text-destructive bg-destructive/10 px-1.5 py-0.5 rounded",children:["Merge into #",j||"—"]})]}),y.sub&&e.jsx("div",{className:"text-xs text-muted-foreground",children:y.sub})]})]},y.number)})}),j>0&&g.length>0&&e.jsxs("div",{className:"rounded border border-primary/30 bg-primary/5 p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:"Summary"}),e.jsxs("div",{className:"text-muted-foreground mt-1",children:["Keeping ",e.jsxs("strong",{className:"text-foreground",children:["#",j]})," · merging"," ",e.jsx("strong",{className:"text-foreground",children:g.map(y=>`#${y.number}`).join(", ")})," ","into it."]})]}),(()=>{const y=[...n??[],...s?[s]:[]].filter(Boolean),k=new Set(y.map(L=>L.dob).filter(Boolean)),S=new Set(y.map(L=>(L.email??"").toLowerCase()).filter(Boolean)),f=new Set(y.map(L=>(L.phone??"").replace(/\D/g,"")).filter(Boolean)),h=k.size>1,M=S.size>1,T=f.size>1;return h||M||T?e.jsxs("div",{className:"flex items-start gap-2 rounded border border-destructive/40 bg-destructive/5 p-2 text-sm",children:[e.jsx(Is,{className:"h-4 w-4 mt-0.5 text-destructive shrink-0"}),e.jsxs("div",{children:["These records look like they might be ",e.jsx("strong",{children:"different people"}),":",h&&e.jsx("div",{children:"• DOB doesn't match across records"}),M&&e.jsx("div",{children:"• Email addresses don't match"}),T&&e.jsx("div",{children:"• Phone numbers don't match"}),e.jsx("div",{className:"mt-1 italic",children:"Double-check before merging."})]})]}):null})(),e.jsxs("label",{className:"flex items-center gap-2 text-sm font-medium rounded border p-2",children:[e.jsx(As,{checked:p,onCheckedChange:y=>u(y===!0)}),"I confirm these records are the same person."]})]}),e.jsxs(Ys,{children:[e.jsx(w,{variant:"outline",onClick:()=>d(!1),disabled:x.isPending,children:"Cancel"}),e.jsxs(w,{onClick:N,disabled:!o||!p||x.isPending,children:[x.isPending&&e.jsx(oe,{className:"h-4 w-4 mr-1 animate-spin"}),g.length>0?`Merge ${g.length} into #${j}`:"Merge"]})]})]})})}const Bu={name:"same name",email:"same email",phone:"same phone",dob:"same birth date"},Tr={firstName:"",middleInitial:"",lastName:"",dob:"",sex:"",phone:"",email:"",address:"",city:"",state:"",zip:"",transponder:""};function Uu({open:s,onOpenChange:n,onCreated:i}
235){const[t,d]=a.useState({...Tr}),[r,x]=a.useState(!1),[c,o]=a.useState([]),[m,p]=a.useState(!1),[u,l]=a.useState(""),N=Lo(),j=Po(),g=Io(),y=ii();a.useEffect(()=>{s&&(d({...Tr}),x(!1),o([]),p(!1),l(""))},[s]);const k=(L,Q)=>{d(Z=>({...Z,[L]:Q})),["firstName","lastName","dob","email","phone"].includes(L)&&(x(!1),o([]),p(!1),l(""))},S=t.firstName.trim().length>=1&&t.lastName.trim().length>=2&&/^\d{4}-\d{2}-\d{2}$/.test(t.dob),f=async()=>{try{const L=await N.mutateAsync({first_name:t.firstName.trim(),last_name:t.lastName.trim(),date_of_birth:t.dob||null,email:t.email.trim()||null,phone:t.phone.trim()||null});o(L.candidates??[]),p(!!L.hard_block),x(!0)}catch(L){be({title:"Duplicate check failed",description:L.message,variant:"destructive"})}},h=async L=>{try{const Q=await j.mutateAsync(L.family_member_id);be({title:"Existing racer used",description:`#${Q.member_number??"—"} ${L.first_name??""} ${L.last_name??""} is now in this organization.`}),n(!1),i(Q.member_number??null)}catch(Q){be({title:"Could not use that racer",description:Q.message,variant:"destructive"})}},M=S&&r&&!m&&(c.length===0||u.trim().length>=3),T=async()=>{const[L,Q,Z]=t.dob.split("-").map(R=>Number(R));try{c.length>0&&await g.mutateAsync({first_name:t.firstName.trim(),last_name:t.lastName.trim(),reason:u.trim()});const R=await y.mutateAsync({firstName:t.firstName.trim(),middleInitial:t.middleInitial.trim()||void 0,lastName:t.lastName.trim(),birthYear:L,birthMonth:Q,birthDay:Z,sex:t.sex||void 0,phoneNumber:t.phone.trim()||void 0,email:t.email.trim()||void 0,address:t.address.trim()||void 0,city:t.city.trim()||void 0,state:t.state.trim()||void 0,zip:t.zip.trim()||void 0,transponder_id:t.transponder.trim()||void 0});n(!1),i(R.memberNumber??null)}catch(R){be({title:"Could not add racer",description:R.message,variant:"destructive"})}},C=N.isPending||j.isPending||y.isPending;return e.jsx(ts,{open:s,onOpenChange:n,children:e.jsxs(as,{className:"max-w-2xl max-h-[90vh] overflow-y-auto z-[1100]",children:[e.jsxs(rs,{children:[e.jsxs(is,{className:"flex items-center gap-2",children:[e.jsx(wa,{className:"h-4 w-4"})," Add a racer"]}),e.jsx(Fs,{children:"Creates a racer in the database without a registration. We check the entire Beyond Pro database first — every organization — so nobody gets a second profile."})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_80px_1fr] gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(v,{children:"First name *"}),e.jsx(A,{value:t.firstName,onChange:L=>k("firstName",L.target.value)})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(v,{children:"M.I."}),e.jsx(A,{maxLength:1,value:t.middleInitial,onChange:L=>k("middleInitial",L.target.value)})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(v,{children:"Last name *"}),e.jsx(A,{value:t.lastName,onChange:L=>k("lastName",L.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(v,{children:"Date of birth *"}),e.jsx(A,{type:"date",value:t.dob,onChange:L=>k("dob",L.target.value)})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(v,{children:"Sex"}),e.jsxs(Pe,{value:t.sex,onValueChange:L=>k("sex",L),children:[e.jsx(Ie,{children:e.jsx(qe,{placeholder:"Not set"})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"M",children:"Male"}),e.jsx(ae,{value:"F",children:"Female"})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(v,{children:"Transponder (optional)"}),e.jsx(A,{value:t.transponder,onChange:L=>k("transponder",L.target.value),placeholder:"EPC"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(v,{children:"Phone"}),e.jsx(A,{value:t.phone,onChange:L=>k("phone",L.target.value)})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(v,{children:"Email"}),e.jsx(A,{value:t.email,onChange:L=>k("email",L.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[2fr_1fr_60px_100px] gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(v,{children:"Address"}),e.jsx(A,{value:t.address,onChange:L=>k("address",L.target.value)})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(v,{children:"City"}),e.jsx(A,{value:t.city,onChange:L=>k("city",L.target.value)})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(v,{children:"State"}),e.jsx(A,{maxLength:2,value:t.state,onChange:L=>k("state",L.target.value.toUpperCase())})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(v,{children:"ZIP"}),e.jsx(A,{value:t.zip,onChange:L=>k("zip",L.target.value)})]})]}),e.jsxs("div",{className:"rounded-md border p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-sm",children:r?c.length===0?e.jsxs("span",{className:"flex items-center gap-1 text-foreground",children:[e.jsx(On,{className:"h-4 w-4 text-primary"})," No existing racer matches. Safe to add."]}):e.jsxs("span",{className:"flex items-center gap-1 text-destructive font-medium",children:[e.jsx(Is,{className:"h-4 w-4"})," ",c.length," possible match",c.length>1?"es":""," already in the database"]}):e.jsx("span",{className:"text-muted-foreground",children:"Run the duplicate check before saving."})}),e.jsx(w,{type:"button",variant:"secondary",size:"sm",disabled:!S||N.isPending,onClick:f,children:N.isPending?e.jsxs(e.Fragment,{children:[e.jsx(oe,{className:"h-4 w-4 mr-1 animate-spin"})," Checking…"]}):"Check for duplicates"})]}),r&&c.length>0&&e.jsxs("div",{className:"space-y-2",children:[c.map(L=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded border bg-muted/30 p-2",children:[e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{className:"font-medium",children:[L.first_name," ",L.last_name," ",L.member_number!=null&&e.jsxs(ie,{variant:"secondary",className:"ml-1",children:["#",L.member_number]}),L.in_current_org&&e.jsx(ie,{variant:"outline",className:"ml-1",children:"already here"})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:[L.dob?`born ${L.dob}
235`:null,[L.city,L.state].filter(Boolean).join(", ")||null,L.orgs.length?L.orgs.join(" · "):null].filter(Boolean).join(" — ")}),e.jsxs("div",{className:"text-xs text-destructive",children:["matched on ",L.reasons.map(Q=>Bu[Q]??Q).join(", ")]})]}),e.jsx(w,{type:"button",size:"sm",disabled:C,onClick:()=>h(L),children:"Use this racer"})]},L.family_member_id)),m?e.jsx("p",{className:"text-xs text-destructive",children:"This is the same person as one of the rows above (same name plus the same email or phone). Use the existing racer — a second profile can't be created."}):e.jsxs("div",{className:"space-y-1",children:[e.jsx(v,{className:"text-xs",children:"Creating a new person anyway? Say why (required)"}),e.jsx(Ns,{rows:2,value:u,onChange:L=>l(L.target.value),placeholder:"e.g. brothers with the same name, confirmed different birth dates"})]})]})]})]}),e.jsxs(Ys,{children:[e.jsx(w,{variant:"ghost",onClick:()=>n(!1),disabled:C,children:"Cancel"}),e.jsx(w,{onClick:T,disabled:!M||C,children:y.isPending?e.jsxs(e.Fragment,{children:[e.jsx(oe,{className:"h-4 w-4 mr-1 animate-spin"})," Saving…"]}):"Add racer"})]})]})})}const zu=(s,n)=>`${s.source}:${s.member_number??"x"}:${s.family_member_id??""}:${s.profile_id??""}:${n}`;function Vu(){const{currentOrganization:s}=Je(),n=Gt(),[i,t]=a.useState(""),[d,r]=a.useState(""),[x,c]=a.useState(null),[o,m]=a.useState(null),[p,u]=a.useState(null),[l,N]=a.useState(null),[j,g]=a.useState({}),[y,k]=a.useState(!1),[S,f]=a.useState(!1),h=qi(d),M=Bi(),T=Object.values(j),C=(l==null?void 0:l.member_number)??null,L=Array.from(new Set(T.flatMap(b=>[...b.member_number!=null?[b.member_number]:[],...b.duplicate_member_numbers??[]]))).filter(b=>b!==C),Q=C!=null&&L.length>=1,Z=(b,I)=>{u(b),N(I),g(V=>{if(!V[b])return V;const H={...V};return delete H[b],H})},R=(b,I)=>{p===b&&(u(null),N(null)),g(V=>{const H={...V};return H[b]?delete H[b]:H[b]=I,H})},E=()=>{u(null),N(null),g({})},$=async b=>{c(null);const I=await M.mutateAsync({family_member_id:b.family_member_id??null,profile_id:b.profile_id??null,member_number:b.member_number??null});c(I)};return s!=null&&s.id?x?e.jsxs("div",{className:"space-y-4",children:[e.jsxs(w,{variant:"ghost",size:"sm",onClick:()=>c(null),children:[e.jsx(Wa,{className:"h-4 w-4 mr-1"})," Back to results"]}),e.jsx(_l,{detail:x})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs(re,{children:[e.jsxs(ke,{className:"flex flex-row items-start justify-between gap-3 space-y-0",children:[e.jsxs("div",{children:[e.jsxs(Ee,{children:[n.racer," Database Lookup"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Search by name, email, phone, member number, or transponder EPC. Scoped to"," ",e.jsx("strong",{children:s.name})," only."]})]}),e.jsxs(w,{size:"sm",variant:"secondary",onClick:()=>f(!0),children:[e.jsx(wa,{className:"h-4 w-4 mr-1"})," Add ",n.racer.toLowerCase()]})]}),e.jsx(xe,{children:e.jsxs("form",{className:"flex gap-2",onSubmit:b=>{b.preventDefault(),r(i.trim())},children:[e.jsx(A,{value:i,onChange:b=>t(b.target.value),placeholder:"e.g. Smith, 1234, [email protected], A100…",autoFocus:!0}),e.jsxs(w,{type:"submit",disabled:i.trim().length<2,children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"})," Search"]})]})})]}),M.isPending&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(oe,{className:"h-4 w-4 animate-spin"})," Loading rider…"]}),d.length>=2&&e.jsxs(re,{children:[e.jsxs(ke,{className:"pb-2 flex flex-row items-center justify-between gap-2 space-y-0",children:[e.jsxs(Ee,{className:"text-base",children:["Results",h.data&&e.jsxs("span",{className:"text-muted-foreground font-normal ml-2 text-sm",children:["(",h.data.length,")"]})]}),(l||T.length>0)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:[C!=null?e.jsxs(e.Fragment,{children:["Keeping ",e.jsxs("strong",{className:"text-foreground",children:["#",C]})]}):e.jsx("span",{className:"text-destructive",children:"Pick a Keep row"}),L.length>0&&e.jsxs(e.Fragment,{children:[" · merging ",e.jsx("strong",{className:"text-foreground",children:L.map(b=>`#${b}`).join(", ")})]})]}),e.jsx(w,{size:"sm",variant:"ghost",onClick:E,children:"Clear"}),e.jsxs(w,{size:"sm",disabled:!Q,onClick:()=>k(!0),children:[e.jsx(nr,{className:"h-3.5 w-3.5 mr-1"}),Q?`Merge ${L.length} → #${C}`:"Merge"]})]})]}),e.jsx(xe,{children:h.isLoading?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-4",children:[e.jsx(oe,{className:"h-4 w-4 animate-spin"})," Searching…"]}):h.error?e.jsx("div",{className:"text-sm text-destructive py-4",children:h.error.message}):(h.data??[]).length===0?e.jsxs("div",{className:"text-sm text-muted-foreground py-4",children:['No riders found in this organization for "',d,'".']}):e.jsxs(e.Fragment,{children:[(h.data??[]).length>1&&e.jsxs("p",{className:"text-xs text-muted-foreground mb-2",children:["Pick ",e.jsx("strong",{children:"Keep"})," on the correct row, then ",e.jsx("strong",{children:"Merge"})," on the misspelled / duplicate ones. The merge rows will be aliased to the Keep row everywhere."]}),e.jsxs("div",{className:"grid grid-cols-[auto_auto_1fr_auto] gap-x-3 gap-y-1 items-center",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground text-center",children:"Keep"}),e.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground text-center",children:"Merge"}),e.jsx("div",{}),e.jsx("div",{}),e.jsx(wt,{delayDuration:100,children:(h.data??[]).map((b,I)=>{const V=b.duplicate_member_numbers??[],H=b.sources??[b.source],Y=zu(b,I),W=b.member_number!=null||V.length>0,te=p===Y,B=!!j[Y],le=te?"bg-primary/5 ring-1 ring-primary/40":B?"bg-destructive/5 ring-1 ring-destructive/30":"hover:bg-muted/40";return e.jsxs("div",{className:"contents",children:[e.jsx("label",{className:`flex items-center justify-center py-2 cursor-pointer ${W?"":"op
235acity-30 cursor-not-allowed"}`,title:"Keep this record (canonical)",children:e.jsx("input",{type:"radio",name:"merge-keep",className:"h-4 w-4 accent-primary",checked:te,disabled:!W,onChange:()=>Z(Y,b)})}),e.jsx("label",{className:`flex items-center justify-center py-2 cursor-pointer ${W?"":"opacity-30 cursor-not-allowed"}`,title:"Merge this record into the Keep row",children:e.jsx(As,{checked:B,disabled:!W,onCheckedChange:()=>R(Y,b),className:"data-[state=checked]:bg-destructive data-[state=checked]:border-destructive"})}),e.jsxs("button",{type:"button",onClick:()=>$(b),className:`text-left py-2 px-2 rounded transition-colors ${le}`,children:[e.jsxs("div",{className:"font-medium flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{children:[b.first_name," ",b.last_name]}),te&&e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide text-primary bg-primary/10 px-1.5 py-0.5 rounded",children:"Keep"}),B&&e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide text-destructive bg-destructive/10 px-1.5 py-0.5 rounded",children:C!=null?`Merge → #${C}`:"Merge"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[b.email&&e.jsx("span",{children:b.email}),b.phone&&e.jsxs("span",{children:[b.email?" · ":"",b.phone]})]})]}),e.jsxs("div",{className:`flex items-center gap-2 py-2 px-2 rounded ${le}`,children:[b.member_number!=null&&e.jsxs(ie,{variant:"secondary",children:["#",b.member_number]}),V.length>0&&e.jsxs(Us,{children:[e.jsx(zs,{asChild:!0,children:e.jsxs(ie,{variant:"outline",className:"text-xs cursor-help",children:["+",V.length," alt"]})}),e.jsx(Vs,{className:"max-w-xs",children:e.jsxs("div",{className:"text-xs",children:["Also seen as: ",V.map(Me=>`#${Me}`).join(", ")]})})]}),e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[H.includes("family_member")&&e.jsxs(Us,{children:[e.jsx(zs,{asChild:!0,children:e.jsx(Gs,{className:"h-3.5 w-3.5"})}),e.jsx(Vs,{children:"Family member"})]}),H.includes("profile")&&e.jsxs(Us,{children:[e.jsx(zs,{asChild:!0,children:e.jsx(Xs,{className:"h-3.5 w-3.5"})}),e.jsx(Vs,{children:"Account"})]}),H.includes("lab")&&e.jsxs(Us,{children:[e.jsx(zs,{asChild:!0,children:e.jsx(Tt,{className:"h-3.5 w-3.5"})}),e.jsx(Vs,{children:"Timing lab"})]}),H.includes("transponder")&&e.jsxs(Us,{children:[e.jsx(zs,{asChild:!0,children:e.jsx(vn,{className:"h-3.5 w-3.5"})}),e.jsx(Vs,{children:"Transponder"})]})]}),V.length>0&&e.jsxs(w,{size:"sm",variant:"ghost",onClick:Me=>{Me.stopPropagation(),m(b)},children:[e.jsx(nr,{className:"h-3.5 w-3.5 mr-1"}),"Resolve"]})]})]},Y)})})]})]})})]}),e.jsx(Mr,{hit:o,open:!!o,onOpenChange:b=>{b||m(null)}}),e.jsx(Mr,{hits:l?[l,...T]:T,defaultCanonical:C,open:y,onOpenChange:b=>{k(b),b||E()}}),e.jsx(Uu,{open:S,onOpenChange:f,onCreated:async b=>{if(b==null)return;t(String(b)),r(String(b));const I=await M.mutateAsync({member_number:b});c(I)}})]}):e.jsx(re,{children:e.jsx(xe,{className:"py-10 text-center text-muted-foreground",children:"Select an organization first."})})}function Ou(){var S,f,h,M,T;const{currentOrganization:s}=Je(),n=Gt(),{settings:i}
235=di(),[t,d]=a.useState(""),[r,x]=a.useState(""),[c,o]=a.useState(null),[m,p]=a.useState([]),u=qi(r),l=Bi(),N=async C=>{const L=await l.mutateAsync({family_member_id:C.family_member_id??null,profile_id:C.profile_id??null,member_number:C.member_number??null});o({hit:C,detail:L})},j=((S=c==null?void 0:c.detail.account)==null?void 0:S.profile_id)??null,g=((f=c==null?void 0:c.detail.account)==null?void 0:f.email)??((h=c==null?void 0:c.detail.contact)==null?void 0:h.primary_email)??"",y=((M=c==null?void 0:c.detail.identity)==null?void 0:M.member_number)??null,k=(s==null?void 0:s.id)??null;if(a.useEffect(()=>{if(!j){p([]);return}z.rpc("admin_list_user_family",{_target_user:j}).then(({data:C})=>p(C||[]))},[j]),!(s!=null&&s.id))return e.jsx(re,{children:e.jsx(xe,{className:"py-10 text-center text-sm text-muted-foreground",children:"Select an organization to manage rider accounts."})});if(c){const C=c.detail.identity,L=C?`${C.first_name??""} ${C.last_name??""}`.trim():"Rider";return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(w,{variant:"ghost",size:"sm",onClick:()=>o(null),className:"gap-1",children:[e.jsx(Wa,{className:"h-4 w-4"})," Back to search"]})}),e.jsx(re,{children:e.jsxs(xe,{className:"py-4 flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-primary/10 p-2",children:e.jsx(Xs,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-base font-semibold text-foreground",children:L||"Unknown rider"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[y&&e.jsxs(ie,{variant:"secondary",children:["#",y]}),g&&e.jsx("span",{children:g})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-amber-300 bg-amber-50 px-3 py-1.5 text-xs text-amber-900",children:[e.jsx(Zr,{className:"h-4 w-4"}),"Acting on behalf of this rider — changes affect their account."]})]})}),e.jsxs(ot,{defaultValue:"identity",className:"space-y-4",children:[e.jsxs(pt,{children:[e.jsx(Qe,{value:"identity",children:"Identity"}),e.jsx(Qe,{value:"alerts",children:"Alerts"}),e.jsx(Qe,{value:"wallet",children:"Wallet & Coupons"}),e.jsx(Qe,{value:"schedule",children:"Schedule"}),e.jsx(Qe,{value:"fundraisers",children:"Fundraisers"})]}),e.jsx(Ae,{value:"identity",className:"space-y-4",children:e.jsx(_l,{detail:c.detail})}),e.jsxs(Ae,{value:"alerts",className:"grid gap-4 md:grid-cols-2",children:[e.jsx(qo,{memberNumber:y,organizationId:k,riderFirstName:(C==null?void 0:C.first_name)??"",riderLastName:(C==null?void 0:C.last_name)??"",maxAlertPhones:(i==null?void 0:i.max_alert_phones)??2}),e.jsx(Bo,{memberNumber:y,organizationId:k,maxAlertEmails:(i==null?void 0:i.max_alert_phones)??2})]}),e.jsx(Ae,{value:"wallet",className:"space-y-4",children:j&&k?e.jsxs(e.Fragment,{children:[e.jsx(Uo,{userId:j,organizationId:k}),e.jsx(zo,{userId:j,orgSlug:s.slug??void 0})]}):e.jsx(re,{children:e.jsx(xe,{className:"py-8 text-center text-sm text-muted-foreground",children:"Wallet and coupons require a registered account (no profile linked to this rider)."})})}),e.jsx(Ae,{value:"schedule",children:j?e.jsx(Vo,{userId:j,userEmail:g,organizationId:k}):e.jsx(re,{children:e.jsx(xe,{className:"py-8 text-center text-sm text-muted-foreground",children:"Schedule requires a registered account."})})}),e.jsx(Ae,{value:"fundraisers",children:j&&k&&s.slug?e.jsx(Oo,{userId:j,userEmail:g,organizationId:k,orgSlug:s.slug,familyMembers:m}):e.jsx(re,{children:e.jsx(xe,{className:"py-8 text-center text-sm text-muted-foreground",children:"Fundraisers require a registered account."})})})]})]})}return e.jsxs("div",{className:"space-y-4",children:[e.jsx(re,{children:e.jsxs(xe,{className:"py-6 space-y-4",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground",children:[n.racer," Account Manager"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Look up a ",n.racer.toLowerCase()," and manage their account — alerts, wallet, schedule, and more — as if you were signed in as them."]})]}),e.jsxs("form",{className:"flex gap-2",onSubmit:C=>{C.preventDefault(),x(t.trim())},children:[e.jsx(A,{placeholder:"Search by name, member #, email, or phone…",value:t,onChange:C=>d(C.target.value)}),e.jsxs(w,{type:"submit",disabled:t.trim().length<2,className:"gap-1",children:[e.jsx(Ws,{className:"h-4 w-4"})," Search"]})]})]})}),u.isFetching&&e.jsxs("div",{className:"flex items-center justify-center py-8 text-sm text-muted-foreground",children:[e.jsx(oe,{className:"h-4 w-4 mr-2 animate-spin"})," Searching…"]}),!u.isFetching&&r&&(((T=u.data)==null?void 0:T.length)??0)===0&&e.jsx(re,{children:e.jsxs(xe,{className:"py-8 text-center text-sm text-muted-foreground",children:["No riders found for “",r,"”."]})}),e.jsx("div",{className:"grid gap-2",children:(u.data||[]).map((C,L)=>e.jsxs("button",{onClick:()=>N(C),disabled:l.isPending,className:"text-left rounded-md border bg-card hover:bg-accent transition-colors p-3 flex items-center justify-between gap-3 disabled:opacity-60",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("div",{className:"rounded-full bg-muted p-2 flex-shrink-0",children:e.jsx(Xs,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-sm font-medium text-foreground truncate",children:[C.first_name," ",C.last_name]}),e.jsxs("div",{className:"text-xs text-muted-foreground truncate",children:[C.member_number?`#${C.member_number} · `:"",C.email||C.phone||"—"]})]})]}),e.jsx(w,{variant:"ghost",size:"sm",className:"flex-shrink-0",children:"Manage account →"})]},`${C.profile_id??C.family_member_id??C.member_number??L}-${L}`))}),l.isPending&&e.jsxs("div",{className:"flex items-center justify-center py-4 text-sm text-muted-foreground",children:[e.jsx(oe,{className:"h-4 w-4 mr-2 animate-spin"})," Loading rider…"]})]})}function Gu(){const[s,n]=a.useState(!1),[i,t]=a.useState([]),[d,r]=a.useState(0),[x,c]=a.useState(""),[o,m]=a.useState(!1),[p,u]=a.useState(null),l=async()=>{n(!0);try{const{data:g,error:y}=await z.functions.invoke("list-unlinked-registrations",{body:{include_unpaid:o,limit:300}});if(y)throw y;t(g.orphans||[]),r(g.total||0)}catch(g){K.error(`Failed to load: ${(g==null?void 0:g.message)||g}`)}finally{n(!1)}};a.useEffect(()=>{l()}
235,[o]);const N=a.useMemo(()=>{if(!x.trim())return i;const g=x.toLowerCase();return i.filter(y=>{const k=y.registration;return(k.first_name||"").toLowerCase().includes(g)||(k.last_name||"").toLowerCase().includes(g)||(k.email||"").toLowerCase().includes(g)||(k.organization_name||"").toLowerCase().includes(g)||(k.event_name||"").toLowerCase().includes(g)})},[i,x]),j=async(g,y)=>{u(g);try{const{data:k,error:S}=await z.functions.invoke("resolve-unlinked-registration",{body:{registration_id:g,...y}});if(S)throw S;if(k!=null&&k.error)throw new Error(k.error);K.success(`Linked → BP#${k.beyondpro_member_number??"?"}${k.ghosts_rewritten?` · ${k.ghosts_rewritten} ghost row(s) merged`:""}`),await l()}catch(k){K.error(`Resolve failed: ${(k==null?void 0:k.message)||k}`)}finally{u(null)}};return e.jsxs(re,{children:[e.jsxs(ke,{className:"flex flex-row items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs(Ee,{className:"flex items-center gap-2",children:[e.jsx(Is,{className:"h-5 w-5 text-amber-600"}),"Unlinked Registrations"]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["Registrations with no rider family member link. These produce ghost rows in Timing Lab. Total: ",e.jsx("b",{children:d})]})]}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs",children:[e.jsx("input",{type:"checkbox",checked:o,onChange:g=>m(g.target.checked)}),"Include unpaid"]}),e.jsx(w,{variant:"outline",size:"sm",onClick:l,disabled:s,children:s?e.jsx(oe,{className:"h-4 w-4 animate-spin"}):e.jsx(kt,{className:"h-4 w-4"})})]})]}),e.jsxs(xe,{className:"space-y-3",children:[e.jsx(A,{placeholder:"Filter by name / email / org / event…",value:x,onChange:g=>c(g.target.value)}),s&&i.length===0&&e.jsxs("p",{className:"text-sm text-muted-foreground inline-flex items-center gap-2",children:[e.jsx(oe,{className:"h-4 w-4"}),"Loading…"]}),!s&&N.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No unlinked registrations."}),e.jsx("div",{className:"space-y-3",children:N.map(g=>e.jsx(Yu,{orphan:g,busy:p===g.registration.id,onResolve:y=>j(g.registration.id,y)},g.registration.id))})]})]})}function Yu({orphan:s,busy:n,onResolve:i}){const t=s.registration,[d,r]=a.useState(!1),[x,c]=a.useState(t.first_name||""),[o,m]=a.useState(t.last_name||""),[p,u]=a.useState(t.date_of_birth||"");return e.jsxs("div",{className:"rounded-md border p-3 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{className:"font-semibold",children:[t.first_name," ",t.last_name,t.date_of_birth&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["DOB ",t.date_of_birth]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[t.organization_name||"—"," · ",t.event_name||"—"," · ",t.payment_status]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[t.email||"no email"," · ",t.phone||"no phone"," · class ",t.racing_class||"—"]}),e.jsxs("div",{className:"text-[10px] text-muted-foreground",children:["reg ",t.id.slice(0,8)," · ",new Date(t.created_at).toLocaleString()]})]}),s.ghost&&e.jsxs(ie,{variant:"destructive",className:"text-[10px]",children:["ghost lab row #",s.ghost.source_member_number," ",s.ghost.transponder_id?`· EPC ${s.ghost.transponder_id}`:"· no transponder"]})]}),s.failures.length>0&&e.jsxs("div",{className:"text-[11px] text-amber-700 bg-amber-50 rounded px-2 py-1",children:["last failure: ",e.jsx("code",{children:s.failures[0].source})," — ",s.failures[0].error_message||"(no message)"]}),s.candidates.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-muted-foreground",children:["Candidates (",s.candidates.length,"):"]}),s.candidates.slice(0,5).map(l=>{const N=l.match_reasons.includes("DOB_MISMATCH");return e.jsxs("div",{className:"flex items-center justify-between gap-2 bg-muted/40 rounded px-2 py-1 text-xs",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("b",{children:[l.first_name," ",l.last_name]})," ",l.beyondpro_member_number&&e.jsxs("span",{className:"text-muted-foreground",children:["BP#",l.beyondpro_member_number]}),e.jsxs("span",{className:"text-muted-foreground",children:[" · DOB ",l.date_of_birth||"—"," · ",l.email||"—"," · ",l.phone_number||"—"]}),e.jsx("span",{className:"ml-1",children:l.match_reasons.map(j=>e.jsx(ie,{variant:j==="DOB_MISMATCH"?"destructive":"secondary",className:"text-[9px] ml-1",children:j},j))})]}),e.jsxs(w,{size:"sm",variant:N?"outline":"default",disabled:n,onClick:()=>i({action:"link_to_existing",family_member_id:l.id}),children:[e.jsx(Za,{className:"h-3 w-3 mr-1"})," Link"]})]},l.id)})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-1",children:[e.jsxs(w,{size:"sm",variant:"secondary",disabled:n,onClick:()=>i({action:"create_new"}),children:[n?e.jsx(oe,{className:"h-3 w-3 animate-spin mr-1"}):e.jsx(wa,{className:"h-3 w-3 mr-1"}),"Create new rider + BP#"]}),e.jsxs(w,{size:"sm",variant:"outline",disabled:n,onClick:()=>r(l=>!l),children:[e.jsx(Ft,{className:"h-3 w-3 mr-1"})," ",d?"Cancel edit":"Edit & relink"]})]}),d&&e.jsxs("div",{className:"grid grid-cols-3 gap-2 pt-2 border-t",children:[e.jsxs("div",{children:[e.jsx(v,{className:"text-[10px]",children:"First"}),e.jsx(A,{value:x,onChange:l=>c(l.target.value),className:"h-7 text-xs"})]}),e.jsxs("div",{children:[e.jsx(v,{className:"text-[10px]",children:"Last"}),e.jsx(A,{value:o,onChange:l=>m(l.target.value),className:"h-7 text-xs"})]}),e.jsxs("div",{children:[e.jsx(v,{className:"text-[10px]",children:"DOB"}),e.jsx(A,{type:"date",value:p,onChange:l=>u(l.target.value),className:"h-7 text-xs"})]}),e.jsx("div",{className:"col-span-3",children:e.jsx(w,{size:"sm",disabled:n,onClick:()=>i({action:"edit_and_relink",first_name:x,last_name:o,date_of_birth:p}),children:"Save & relink"})})]})]})}function Ku(){const{currentOrganization:s}=Je(),{data:n=[],isLoading:i}
235=dc(),[t,d]=a.useState(""),[r,x]=a.useState(""),[c,o]=a.useState(5),[m,p]=a.useState(!1),[u,l]=a.useState("xlsx_single"),[N,j]=a.useState(!1),[g,y]=a.useState(!1),[k,S]=a.useState([]),[f,h]=a.useState(new Set),[M,T]=a.useState(!1),[C,L]=a.useState(""),Q=a.useMemo(()=>Array.from(new Set(n.map(W=>String(W.series_name??"").trim()).filter(Boolean))).sort((W,te)=>W.localeCompare(te)),[n]),Z=a.useMemo(()=>t?n.filter(W=>String(W.series_name??"").trim()===t).sort((W,te)=>{const B=`${W.event_date_year}-${String(W.event_date_month).padStart(2,"0")}-${String(W.event_date_day).padStart(2,"0")}`,le=`${te.event_date_year}-${String(te.event_date_month).padStart(2,"0")}-${String(te.event_date_day).padStart(2,"0")}`;return B.localeCompare(le)||W.event_name.localeCompare(te.event_name)}):[],[n,t]),R=a.useMemo(()=>{const W=n.find(te=>te.event_name===r);return(W==null?void 0:W.id)??""},[n,r]);a.useEffect(()=>{d(""),x("")},[s==null?void 0:s.id]),a.useEffect(()=>{S([]),h(new Set),L("")},[r]);const E=async()=>{if(!(!(s!=null&&s.id)||!r)&&!(C===r&&k.length>0)){T(!0);try{const{data:W,error:te}=await z.functions.invoke("export-contingency",{body:{action:"list_classes",organization_id:s.id,event_id:R,event_name:r}});if(te)throw te;if(W!=null&&W.error)throw new Error(W.error);const B=(W==null?void 0:W.classes)??[];S(B),h(new Set(B)),L(r)}catch(W){be({title:"Could not load classes",description:(W==null?void 0:W.message)??"Unknown error",variant:"destructive"})}finally{T(!1)}}},$=async()=>{await E(),y(!0)},b=(W,te)=>{h(B=>{const le=new Set(B);return te?le.add(W):le.delete(W),le})},I=k.length>0&&k.every(W=>f.has(W)),V=f.size===0,H=async()=>{if(!(s!=null&&s.id)){be({title:"No organization selected",variant:"destructive"});return}if(!r){be({title:"Select a race first",variant:"destructive"});return}j(!0);try{let W=Array.from(f);C!==r?W=[]:I&&(W=[]);const{data:te,error:B}=await z.functions.invoke("export-contingency",{body:{organization_id:s.id,event_id:R,event_name:r,top_n:m?0:c,format:u,class_names:W}});if(B)throw B;if(te!=null&&te.error)throw new Error(te.error);const{filename:le,mime_type:Me,content_b64:_,rider_count:X,class_count:F}=te,ne=atob(_),J=new Uint8Array(ne.length);for(let ee=0;ee<ne.length;ee++)J[ee]=ne.charCodeAt(ee);const _e=new Blob([J],{type:Me}),me=URL.createObjectURL(_e),$e=document.createElement("a");$e.href=me,$e.download=le,document.body.appendChild($e),$e.click(),document.body.removeChild($e),URL.revokeObjectURL(me),be({title:"Export ready",description:`Exported ${X} riders across ${F} classes.`})}catch(W){be({title:"Export failed",description:(W==null?void 0:W.message)??"Unknown error",variant:"destructive"})}finally{j(!1)}},Y=r?C!==r?"Choose classes (all by default)":f.size===0?"No classes selected":I?`All classes (${k.length})`:`${f.size} of ${k.length} classes`:"Pick a race first";return e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsxs(Ee,{className:"flex items-center gap-2",children:[e.jsx(la,{className:"h-5 w-5 text-primary"}),"Contingency Export"]}),e.jsx(ns,{children:"Export class results from a single race — Class, Finish, Rider, Town, Email and Brand — for sponsor contingency programs."})]}),e.jsxs(xe,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"series",children:"Series"}),e.jsxs(Pe,{value:t,onValueChange:W=>{d(W),x("")},disabled:i,children:[e.jsx(Ie,{id:"series",children:e.jsx(qe,{placeholder:i?"Loading…":"Choose a series"})}),e.jsx(Be,{children:Q.map(W=>e.jsx(ae,{value:W,children:W},W))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"event",children:"Race"}),e.jsxs(Pe,{value:r,onValueChange:x,disabled:!t||Z.length===0,children:[e.jsx(Ie,{id:"event",children:e.jsx(qe,{placeholder:t?Z.length===0?"No races in this series":"Choose a race":"Pick a series first"})}),e.jsx(Be,{children:Z.map(W=>e.jsxs(ae,{value:W.event_name,children:[W.event_name,` — ${W.event_date_month}/${W.event_date_day}/${W.event_date_year}`]},W.event_name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{children:"Classes"}),e.jsxs(w,{type:"button",variant:"outline",onClick:$,disabled:!r||M,className:"w-full justify-start",children:[M?e.jsx(oe,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Hn,{className:"mr-2 h-4 w-4"}),Y]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(v,{htmlFor:"top-n",children:"Riders per class"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ds,{id:"all-riders",checked:m,onCheckedChange:p}),e.jsx(v,{htmlFor:"all-riders",className:"font-normal cursor-pointer text-sm",children:"All riders"})]})]}),e.jsx(A,{id:"top-n",type:"number",min:1,max:500,value:c,onChange:W=>o(Math.max(1,Math.min(500,Number(W.target.value)||1))),className:"w-32",disabled:m}),e.jsx("p",{className:"text-xs text-muted-foreground",children:m?"Every finisher in each selected class will be included.":"Only the top N finishers per class. Default is 5."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{children:"Format"}),e.jsxs(ut,{value:u,onValueChange:W=>l(W),className:"gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(js,{id:"fmt-csv",value:"csv"}),e.jsx(v,{htmlFor:"fmt-csv",className:"font-normal cursor-pointer",children:"CSV (single file)"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(js,{id:"fmt-xlsx",value:"xlsx_single"}),e.jsx(v,{htmlFor:"fmt-xlsx",className:"font-normal cursor-pointer",children:"Excel — all classes on one sheet"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(js,{id:"fmt-xlsx-multi",value:"xlsx_multi"}),e.jsx(v,{htmlFor:"fmt-xlsx-multi",className:"font-normal cursor-pointer",children:"Excel — one sheet per class"})]})]})]}),e.jsx(w,{onClick:H,disabled:N||!r||C===r&&V,children:N?e.jsxs(e.Fragment,{children:[e.jsx(oe,{className:"mr-2 h-4 w-4 animate-spin"})," Building export…"]}):e.jsxs(e.Fragment,{children:[e.jsx($t,{className:"mr-2 h-4 w-4"})," Export"]})})]}),e.jsx(ts,{open:g,onOpenChange:y,children:e.jsxs(as,{className:"max-w-md",children:[e.jsxs(rs,{children:[e.jsx(is,{children:"Choose classes"}),e.jsx(Fs,{children:"Check the classes you want included in the report."})]}),k.length===0?e.jsx("div",{className:"text-sm text-muted-foreground py-6 text-center",children:M?"Loading classes…":"No finalized classes found for this race."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between border-b pb-2",children:[e.jsx("button",{type:"button",className:"text-sm text-primary hover:underline",onClick:()=>h(new Set(k)),children:"Select all"}),e.jsx("button",{type:"button",className:"text-sm text-primary hover:underline",onClick:()=>h(new Set),children:"Clear all"})]}),e.jsx(qs,{className:"h-72 pr-3",children:e.jsx("div",{className:"space-y-2",children:k.map(W=>{const te=`cls-${W}`;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(As,{id:te,checked:f.has(W),onCheckedChange:B=>b(W,!!B)}),e.jsx(v,{htmlFor:te,className:"font-normal cursor-pointer",children:W})]},W)})})})]}),e.jsxs(Ys,{children:[e.jsx(w,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),e.jsx(w,{onClick:()=>y(!1),disabled:V,children:"Done"})]})]})})]})}function Hu(){const{currentOrganization:s}
235=Je(),[n,i]=a.useState([]),[t,d]=a.useState(!1),[r,x]=a.useState(""),[c,o]=a.useState(10),[m,p]=a.useState(!1),[u,l]=a.useState("multi"),[N,j]=a.useState(!1),[g,y]=a.useState([]),[k,S]=a.useState(new Set),[f,h]=a.useState(!1),[M,T]=a.useState("");a.useEffect(()=>{if(x(""),i([]),y([]),S(new Set),T(""),!(s!=null&&s.id))return;let b=!1;return(async()=>{d(!0);try{const{data:I,error:V}=await z.functions.invoke("export-series-points",{body:{action:"list_series",organization_id:s.id}});if(V)throw V;if(I!=null&&I.error)throw new Error(I.error);b||i((I==null?void 0:I.series)??[])}catch(I){be({title:"Could not load series",description:(I==null?void 0:I.message)??"",variant:"destructive"})}finally{b||d(!1)}})(),()=>{b=!0}},[s==null?void 0:s.id]),a.useEffect(()=>{y([]),S(new Set),T("")},[r]);const C=async()=>{if(!(!(s!=null&&s.id)||!r)&&!(M===r&&g.length>0)){h(!0);try{const{data:b,error:I}=await z.functions.invoke("export-series-points",{body:{action:"list_classes",organization_id:s.id,series_name:r}});if(I)throw I;if(b!=null&&b.error)throw new Error(b.error);const V=(b==null?void 0:b.classes)??[];y(V),S(new Set(V)),T(r)}catch(b){be({title:"Could not load classes",description:(b==null?void 0:b.message)??"",variant:"destructive"})}finally{h(!1)}}},L=async()=>{await C(),j(!0)},Q=(b,I)=>{S(V=>{const H=new Set(V);return I?H.add(b):H.delete(b),H})},Z=g.length>0&&g.every(b=>k.has(b)),R=k.size===0,E=a.useMemo(()=>r?M!==r?"Choose classes (all by default)":k.size===0?"No classes selected":Z?`All classes (${g.length})`:`${k.size} of ${g.length} classes`:"Pick a series first",[r,M,k,Z,g.length]),$=async()=>{if(!(s!=null&&s.id)){be({title:"No organization selected",variant:"destructive"});return}if(!r){be({title:"Select a series first",variant:"destructive"});return}p(!0);try{let b=Array.from(k);(M!==r||Z)&&(b=[]);const{data:I,error:V}=await z.functions.invoke("export-series-points",{body:{organization_id:s.id,series_name:r,top_n:c,class_names:b,sheet_mode:u}});if(V)throw V;if(I!=null&&I.error)throw new Error(I.error);const{filename:H,mime_type:Y,content_b64:W,rider_count:te,class_count:B}=I,le=atob(W),Me=new Uint8Array(le.length);for(let ne=0;ne<le.length;ne++)Me[ne]=le.charCodeAt(ne);const _=new Blob([Me],{type:Y}),X=URL.createObjectURL(_),F=document.createElement("a");F.href=X,F.download=H,document.body.appendChild(F),F.click(),document.body.removeChild(F),URL.revokeObjectURL(X),be({title:"Export ready",description:`Exported ${te} riders across ${B} classes.`})}catch(b){be({title:"Export failed",description:(b==null?void 0:b.message)??"",variant:"destructive"})}finally{p(!1)}};return e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsxs(Ee,{className:"flex items-center gap-2",children:[e.jsx(Mn,{className:"h-5 w-5 text-primary"}),"Series Points Export"]}),e.jsx(ns,{children:"Export current series standings as an Excel file — one sheet per class, ordered by total points, truncated to the top N places you choose."})]}),e.jsxs(xe,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"series",children:"Series"}),e.jsxs(Pe,{value:r,onValueChange:x,disabled:t,children:[e.jsx(Ie,{id:"series",children:e.jsx(qe,{placeholder:t?"Loading…":"Choose a series"})}),e.jsx(Be,{children:n.map(b=>e.jsx(ae,{value:b,children:b},b))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{children:"Classes"}),e.jsxs(w,{type:"button",variant:"outline",onClick:L,disabled:!r||f,className:"w-full justify-start",children:[f?e.jsx(oe,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Hn,{className:"mr-2 h-4 w-4"}),E]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"top-n",children:"Places per class"}),e.jsx(A,{id:"top-n",type:"number",min:1,max:20,value:c,onChange:b=>o(Math.max(1,Math.min(20,Number(b.target.value)||1))),className:"w-32"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only the top N riders per class (by total points) will be included. Choose 1–20."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{children:"Layout"}),e.jsxs(ut,{value:u,onValueChange:b=>l(b),className:"gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(js,{id:"sp-sheet-multi",value:"multi"}),e.jsx(v,{htmlFor:"sp-sheet-multi",className:"font-normal cursor-pointer",children:"Excel — one sheet per class"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(js,{id:"sp-sheet-single",value:"single"}),e.jsx(v,{htmlFor:"sp-sheet-single",className:"font-normal cursor-pointer",children:"Excel — all classes on one sheet"})]})]})]}),e.jsx(w,{onClick:$,disabled:m||!r||M===r&&R,children:m?e.jsxs(e.Fragment,{children:[e.jsx(oe,{className:"mr-2 h-4 w-4 animate-spin"})," Building export…"]}):e.jsxs(e.Fragment,{children:[e.jsx($t,{className:"mr-2 h-4 w-4"})," Export"]})})]}),e.jsx(ts,{open:N,onOpenChange:j,children:e.jsxs(as,{className:"max-w-md",children:[e.jsxs(rs,{children:[e.jsx(is,{children:"Choose classes"}),e.jsx(Fs,{children:"Check the classes you want included in the export."})]}),g.length===0?e.jsx("div",{className:"text-sm text-muted-foreground py-6 text-center",children:f?"Loading classes…":"No classes found for this series."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between border-b pb-2",children:[e.jsx("button",{type:"button",className:"text-sm text-primary hover:underline",onClick:()=>S(new Set(g)),children:"Select all"}),e.jsx("button",{type:"button",className:"text-sm text-primary hover:underline",onClick:()=>S(new Set),children:"Clear all"})]}),e.jsx(qs,{className:"h-72 pr-3",children:e.jsx("div",{className:"space-y-2",children:g.map(b=>
235{const I=`series-cls-${b}`;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(As,{id:I,checked:k.has(b),onCheckedChange:V=>Q(b,!!V)}),e.jsx(v,{htmlFor:I,className:"font-normal cursor-pointer",children:b})]},b)})})})]}),e.jsxs(Ys,{children:[e.jsx(w,{variant:"outline",onClick:()=>j(!1),children:"Cancel"}),e.jsx(w,{onClick:()=>j(!1),disabled:R,children:"Done"})]})]})})]})}function Qu(){const{currentOrganization:s}=Je(),[n,i]=a.useState([]),[t,d]=a.useState(!1),[r,x]=a.useState(""),[c,o]=a.useState(!1),[m,p]=a.useState("multi"),[u,l]=a.useState(!1),[N,j]=a.useState([]),[g,y]=a.useState(new Set),[k,S]=a.useState(!1),[f,h]=a.useState("");a.useEffect(()=>{if(x(""),i([]),j([]),y(new Set),h(""),!(s!=null&&s.id))return;let E=!1;return(async()=>{d(!0);try{const{data:$,error:b}=await z.functions.invoke("export-race-results",{body:{action:"list_events",organization_id:s.id}});if(b)throw b;if($!=null&&$.error)throw new Error($.error);E||i(($==null?void 0:$.events)??[])}catch($){be({title:"Could not load rounds",description:($==null?void 0:$.message)??"",variant:"destructive"})}finally{E||d(!1)}})(),()=>{E=!0}},[s==null?void 0:s.id]),a.useEffect(()=>{j([]),y(new Set),h("")},[r]);const M=async()=>{if(!(!(s!=null&&s.id)||!r)&&!(f===r&&N.length>0)){S(!0);try{const{data:E,error:$}=await z.functions.invoke("export-race-results",{body:{action:"list_classes",organization_id:s.id,event_id:r}});if($)throw $;if(E!=null&&E.error)throw new Error(E.error);const b=(E==null?void 0:E.classes)??[];j(b),y(new Set(b)),h(r)}catch(E){be({title:"Could not load classes",description:(E==null?void 0:E.message)??"",variant:"destructive"})}finally{S(!1)}}},T=async()=>{await M(),l(!0)},C=(E,$)=>{y(b=>{const I=new Set(b);return $?I.add(E):I.delete(E),I})},L=N.length>0&&N.every(E=>g.has(E)),Q=g.size===0,Z=a.useMemo(()=>r?f!==r?"Choose classes (all by default)":g.size===0?"No classes selected":L?`All classes (${N.length})`:`${g.size} of ${N.length} classes`:"Pick a round first",[r,f,g,L,N.length]),R=async()=>{if(!(s!=null&&s.id)){be({title:"No organization selected",variant:"destructive"});return}if(!r){be({title:"Select a round first",variant:"destructive"});return}o(!0);try{let E=Array.from(g);(f!==r||L)&&(E=[]);const{data:$,error:b}=await z.functions.invoke("export-race-results",{body:{organization_id:s.id,event_id:r,class_names:E,sheet_mode:m}});if(b)throw b;if($!=null&&$.error)throw new Error($.error);const{filename:I,mime_type:V,content_b64:H,class_count:Y,moto_count:W}=$,te=atob(H),B=new Uint8Array(te.length);for(let X=0;X<te.length;X++)B[X]=te.charCodeAt(X);const le=new Blob([B],{type:V}),Me=URL.createObjectURL(le),_=document.createElement("a");_.href=Me,_.download=I,document.body.appendChild(_),_.click(),document.body.removeChild(_),URL.revokeObjectURL(Me),be({title:"Race results ready",description:`${Y} class sheet${Y===1?"":"s"} · ${W} moto section${W===1?"":"s"}.`})}catch(E){be({title:"Export failed",description:(E==null?void 0:E.message)??"",variant:"destructive"})}finally{o(!1)}};return e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsxs(Ee,{className:"flex items-center gap-2",children:[e.jsx(jt,{className:"h-5 w-5 text-primary"}),"Race Results Export (per round)"]}),e.jsx(ns,{children:"Download an Excel export of a single round's race results — one sheet per class or all classes on one sheet, with Moto 1, Moto 2, and Overall stacked for easy printing."})]}),e.jsxs(xe,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"race-results-event",children:"Round"}),e.jsxs(Pe,{value:r,onValueChange:x,disabled:t,children:[e.jsx(Ie,{id:"race-results-event",children:e.jsx(qe,{placeholder:t?"Loading…":"Choose a round"})}),e.jsx(Be,{children:n.map(E=>e.jsxs(ae,{value:E.id,children:[E.name,E.event_date?` · ${E.event_date}`:""]},E.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{children:"Classes"}),e.jsxs(w,{type:"button",variant:"outline",onClick:T,disabled:!r||k,className:"w-full justify-start",children:[k?e.jsx(oe,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Hn,{className:"mr-2 h-4 w-4"}),Z]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{children:"Layout"}),e.jsxs(ut,{value:m,onValueChange:E=>p(E),className:"gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(js,{id:"rr-sheet-multi",value:"multi"}),e.jsx(v,{htmlFor:"rr-sheet-multi",className:"font-normal cursor-pointer",children:"Excel — one sheet per class"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(js,{id:"rr-sheet-single",value:"single"}),e.jsx(v,{htmlFor:"rr-sheet-single",className:"font-normal cursor-pointer",children:"Excel — all classes on one sheet"})]})]})]}),e.jsx(w,{onClick:R,disabled:c||!r||f===r&&Q,children:c?e.jsxs(e.Fragment,{children:[e.jsx(oe,{className:"mr-2 h-4 w-4 animate-spin"})," Building export…"]}):e.jsxs(e.Fragment,{children:[e.jsx($t,{className:"mr-2 h-4 w-4"})," Export"]})})]}),e.jsx(ts,{open:u,onOpenChange:l,children:e.jsxs(as,{className:"max-w-md",children:[e.jsxs(rs,{children:[e.jsx(is,{children:"Choose classes"}),e.jsx(Fs,{children:"Check the classes you want included in the export."})]}),N.length===0?e.jsx("div",{className:"text-sm text-muted-foreground py-6 text-center",children:k?"Loading classes…":"No finalized race data found for this round."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between border-b pb-2",children:[e.jsx("button",{type:"button",className:"text-sm text-primary hover:underline",onClick:()=>y(new Set(N)),children:"Select all"}),e.jsx("button",{type:"button",className:"text-sm text-primary hover:underline",onClick:()=>y(new Set),children:"Clear all"})]}),e.jsx(qs,{className:"h-72 pr-3",children:e.jsx("div",{className:"space-y-2",children:N.map(E=>{const $=`race-results-cls-${E}`;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(As,{id:$,checked:g.has(E),onCheckedChange:b=>C(E,!!b)}),e.jsx(v,{htmlFor:$,className:"font-normal cursor-pointer",children:E})]},E)})})})]}),e.jsxs(Ys,{children:[e.jsx(w,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(w,{onClick:()=>l(!1),disabled:Q,children:"Done"})]})]})})]})}async function Wu(s){const{data:n,error:i}=await z.functions.invoke("fetch-timing-events",{body:{organization_id:s}});if(i)throw new Error(i.message||"Could not load timing events");return((n==null?void 0:n.events)??[]).map(d=>{const r=d.event_date_year,x=d.event_date_month,c=d.event_date_day,o=r&&x&&c?`${r}-${String(x).padStart(2,"0")}-${String(c).padStart(2,"0")}`:null;return{event_name:d.event_name,series_name:d.series_name??null,event_date:o,track_name:d.track_name??null,event_location:d.event_location??null}})}async function Zu(s){let{eventId:n,mysqlEventName:i,organizationId:t,classes:d,motos:r,timingEventNameOverride:x}=s,c,o,m,p=null;if(n){const{data:S,error:f}=await z.from("events").select("name, mysql_event_name, event_date, organization_id").eq("id",n).maybeSingle();if(f)throw f;if(!S)throw new Error("Event not found");c=S.name,o=S.mysql_event_name||S.name,m=S.organization_id,p=S.event_date}else if(i&&t){o=i,m=t,c=i;const{data:S}=await z.from("events").select("name, event_date").eq("organization_id",t).eq("mysql_event_name",i).maybeSingle();S&&(c=S.name,p=S.event_date)}else throw new Error("eventId or (mysqlEventName + organizationId) is required");x&&(o=x);const{data:u,error:l}=await z.functions.invoke("fetch-scoring-sheet-data",{body:{organization_id:m,event_name:o}});if(l)throw new Error(l.message||"Could not load race data from the timing system. Make sure the event has been synced.");const N=(u==null?void 0:u.races)??[],j=d&&d.length>0?new Set(d):null,g=r&&r.length>0?new Set(r):null,y=[];
235for(const S of N){if(j&&!j.has(S.class_name)||g&&!g.has(S.moto))continue;const f=S.riders.map(h=>({gatePick:h.gate_pick,riderNumber:h.rider_number,name:`${h.lastName}${h.lastName&&h.firstName?", ":""}${h.firstName}`.trim()||"—"}));y.push({className:S.class_name,moto:S.moto,raceNumber:S.race_number,riders:f})}const{data:k}=await z.from("organizations").select("logo_url").eq("id",m).maybeSingle();return{eventName:c,eventDate:p,races:y,organizationId:m,organizationLogoUrl:(k==null?void 0:k.logo_url)??null,timingEventName:o}}function Ju(s){if(!s)return"";const[n,i,t]=s.split("-").map(Number);return!n||!i||!t?s:`${String(i).padStart(2,"0")}/${String(t).padStart(2,"0")}/${n}`}function Rr(s){if(s.races.length===0)throw new Error("No races with riders to print.");const n=eh(s),i=window.open("","_blank","width=900,height=1100");if(!i)throw new Error("Pop-up blocked. Please allow pop-ups for this site and try again.");i.document.open(),i.document.write(n),i.document.close(),i.addEventListener("load",()=>{setTimeout(()=>i.print(),250)})}const $r=6,Xu=10;function Bt(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function eh(s){const n=Ju(s.eventDate),i=4,t=`
236            <tr class="blank-row">
237              <td class="cell-gate"></td>
238              <td class="cell-num"></td>
239              <td class="cell-name"></td>
240            </tr>`,d=Array.from({length:$r},(c,o)=>`<th>Lap ${o+1}
240</th>`).join(""),r=`<tr>${Array.from({length:$r},()=>"<td></td>").join("")}</tr>`,x=s.races.map((c,o)=>{const m=c.riders.map(N=>`
241            <tr>
242              <td class="cell-gate">${N.gatePick??""}</td>
243              <td class="cell-num">${Bt(N.riderNumber)}</td>
244              <td class="cell-name">${Bt(N.name)}</td>
245            </tr>`).join("")+Array.from({length:i},()=>t).join(""),p=Math.max(Xu,c.riders.length+2),u=Array.from({length:p},()=>r).join(""),l=c.raceNumber!=null?`Race #${c.raceNumber}`:"Race —";return`
246        <section class="sheet${o===s.races.length-1?" last":""}">
247          <header class="sheet-header">
248            <div class="event">
249              ${s.organizationLogoUrl?`<img class="org-logo" src="${Bt(s.organizationLogoUrl)}" alt="" crossorigin="anonymous" onerror="this.style.display='none'" />`:""}
250              <div class="event-text">
251                <div class="event-name">${Bt(s.eventName)}</div>
252                <div class="event-date">Date: ${Bt(n)}</div>
253              </div>
254            </div>
255            <div class="race-meta">
256              <div class="class-name">${Bt(c.className)}</div>
257              <div class="moto-line"><span class="moto-badge">Moto ${c.moto}</span><span class="race-num">${Bt(l)}</span></div>
258            </div>
259          </header>
260
261          <table class="grid">
262            <thead>
263              <tr>
264                <th class="col-gate">Gate</th>
265                <th class="col-num">#</th>
266                <th class="col-name">Rider Name</th>
267              </tr>
268            </thead>
269            <tbody>${m}</tbody>
270          </table>
271
272          <div class="finish-title">Finish Order — write bike # as each rider crosses the line (top = first across that lap)</div>
273          <table class="finish-grid">
274            <thead><tr>${d}</tr></thead>
275            <tbody>${u}</tbody>
276          </table>
277
278          <footer class="sheet-footer">
279            <div class="footer-row">
280              <span>Total laps: <span class="line short"></span></span>
281              <span>Scorer: <span class="line"></span></span>
282              <span>Start: <span class="line short"></span></span>
283              <span>End: <span class="line short"></span></span>
284            </div>
285            <div class="notes-row">
286              <span class="notes-label">Notes / DNF / DQ:</span>
287              <span class="notes-line"></span>
288            </div>
289            <div class="notes-row">
290              <span class="notes-line"></span>
291            </div>
292          </footer>
293        </section>`}).join("");return`<!doctype html>
294<html>
295<head>
296<meta charset="utf-8" />
297<title>Manual Scoring Sheets — ${Bt(s.eventName)}</title>
298<style>
299  @page { size: letter portrait; margin: 0.4in; }
300  * { box-sizing: border-box; }
301  html, body { margin: 0; padding: 0; background: #fff; color: #000;
302    font-family: Arial, Helvetica, sans-serif; font-size: 11pt; }
303  .sheet { padding: 0; page-break-after: always; }
304  .sheet.last { page-break-after: auto; }
305  .sheet-header {
306    display: flex; justify-content: space-between; align-items: flex-start;
307    border-bottom: 2px solid #000; padding-bottom: 6pt; margin-bottom: 8pt;
308  }
309  .event { display: flex; align-items: center; gap: 10pt; }
310  .org-logo { height: 44pt; width: auto; max-width: 110pt; object-fit: contain; }
311  .event-name { font-size: 16pt; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; }
312  .event-date { font-size: 10pt; margin-top: 2pt; }
313  .race-meta { text-align: right; }
314  .class-name { font-size: 14pt; font-weight: 700; }
315  .moto-line { margin-top: 3pt; display: flex; gap: 8pt; justify-content: flex-end; align-items: center; }
316  .moto-badge {
317    background: #000; color: #fff; padding: 2pt 8pt; font-weight: 700;
318    font-size: 11pt; border-radius: 3pt;
319  }
320  .race-num { font-weight: 600; }
321
322  table.grid { width: 100%; border-collapse: collapse; table-layout: fixed; }
323  table.grid th, table.grid td { border: 1px solid #000; padding: 0; text-align: center; }
324  table.grid thead th { background: #f0f0f0; font-size: 9pt; font-weight: 700; padding: 3pt 2pt; }
325
326  .col-gate { width: 12%; }
327  .col-num { width: 14%; }
328  .col-name { width: 74%; }
329
330  table.grid tbody td { height: 26pt; font-size: 11pt; font-weight: 600; }
331  td.cell-gate, td.cell-num { font-size: 12pt; font-weight: 700; }
332  td.cell-name { text-align: left; padding: 0 5pt; font-size: 10.5pt; font-weight: 600; }
333
334  .finish-title { margin-top: 10pt; margin-bottom: 4pt; font-size: 10pt; font-weight: 700; }
335  table.finish-grid { width: 100%; border-collapse: collapse; table-layout: fixed; }
336  table.finish-grid th, table.finish-grid td { border: none; border-left: 1px solid #000; border-right: 1px solid #000; text-align: center; padding: 0; }
337  table.finish-grid thead th { background: #f0f0f0; font-size: 10pt; font-weight: 700; height: 16pt; border-top: 1px solid #000; border-bottom: 1px solid #000; }
338  table.finish-grid tbody td { height: 22pt; }
339  table.finish-grid tbody tr:last-child td { border-bottom: 1px solid #000; }
340
341  .sheet-footer { margin-top: 10pt; font-size: 10pt; }
342  .footer-row { display: flex; justify-content: space-between; gap: 12pt; padding-bottom: 6pt; }
343  .footer-row > span { display: inline-flex; align-items: baseline; gap: 4pt; }
344  .line { display: inline-block; border-bottom: 1px solid #000; min-width: 110pt; height: 12pt; }
345  .line.short { min-width: 50pt; }
346  .notes-row { display: flex; align-items: baseline; gap: 6pt; padding: 4pt 0; }
347  .notes-label { font-weight: 700; white-space: nowrap; }
348  .notes-line { flex: 1; border-bottom: 1px solid #000; height: 14pt; }
349
350  @media screen {
351    body { background: #e5e5e5; padding: 20px; }
352    .sheet { background: #fff; max-width: 7.7in; margin: 0 auto 20px; padding: 0.4in; box-shadow: 0 2px 12px rgba(0,0,0,0.15); }
353  }
354</style>
355</head>
356<body>
357${x}
358</body>
359</html>`}function sh({eventId:s,mysqlEventName:n,organizationId:i,mode:t,variant:d="outline",size:r="sm",label:x="Print Scoring Sheets",className:c,disabled:o}
359){const[m,p]=a.useState(!1),[u,l]=a.useState(!1),[N,j]=a.useState(null),[g,y]=a.useState(new Set),[k,S]=a.useState(new Set),[f,h]=a.useState(!1),[M,T]=a.useState([]),[C,L]=a.useState(null),Q=!!s||!!(n&&i),Z=async V=>{const H=await Zu({eventId:s??void 0,mysqlEventName:n??void 0,organizationId:i??void 0,timingEventNameOverride:V});if(H.races.length===0){try{const Y=await Wu(H.organizationId),W=H.timingEventName.toLowerCase(),te=Y.filter(le=>le.event_name.toLowerCase().includes(W)),B=te.length>0?te:Y;if(B.length>0){B.sort((le,Me)=>(Me.event_date??"").localeCompare(le.event_date??"")),T(B),L({orgId:H.organizationId,bpName:H.eventName}),h(!0);return}}catch{}be({title:"Nothing to print",description:"No classes with riders were found in the timing system for this event yet.",variant:"destructive"});return}if(t==="raceOrder"){Rr(H);return}j(H),y(new Set(H.races.map(Y=>Y.className))),S(new Set(H.races.map(Y=>Y.moto))),l(!0)},R=async()=>{if(Q){p(!0);try{await Z()}catch(V){be({title:"Could not print scoring sheets",description:(V==null?void 0:V.message)||"Unknown error",variant:"destructive"})}finally{p(!1)}}},E=async V=>{h(!1),p(!0);try{await Z(V)}catch(H){be({title:"Could not print scoring sheets",description:(H==null?void 0:H.message)||"Unknown error",variant:"destructive"})}finally{p(!1)}},$=()=>{if(!N)return;const V={...N,races:N.races.filter(H=>g.has(H.className)&&k.has(H.moto))};if(V.races.length===0){be({title:"Nothing selected",description:"Pick at least one class and one moto.",variant:"destructive"});return}try{Rr(V),l(!1)}catch(H){be({title:"Could not open print window",description:(H==null?void 0:H.message)||"Unknown error",variant:"destructive"})}},b=N?Array.from(new Set(N.races.map(V=>V.className))).sort():[],I=N?Array.from(new Set(N.races.map(V=>V.moto))).sort((V,H)=>V-H):[];return e.jsxs(e.Fragment,{children:[e.jsxs(w,{variant:d,size:r,onClick:R,disabled:o||m||!Q,className:c,children:[m?e.jsx(oe,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ja,{className:"h-4 w-4 mr-2"}),x]}),e.jsx(ts,{open:u,onOpenChange:l,children:e.jsxs(as,{className:"max-w-md",children:[e.jsxs(rs,{children:[e.jsx(is,{children:"Print Manual Scoring Sheets"}),e.jsx(Fs,{children:"One page per race. Pick which classes and motos to include."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(v,{className:"font-semibold",children:"Motos"}),e.jsxs("div",{className:"flex gap-2 text-xs",children:[e.jsx("button",{type:"button",className:"text-primary hover:underline",onClick:()=>S(new Set(I)),children:"Select all"}),e.jsx("button",{type:"button",className:"text-muted-foreground hover:underline",onClick:()=>S(new Set),children:"None"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-3",children:I.map(V=>e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(As,{checked:k.has(V),onCheckedChange:H=>{const Y=new Set(k);H?Y.add(V):Y.delete(V),S(Y)}}),e.jsxs("span",{children:["Moto ",V]})]},V))})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(v,{className:"font-semibold",children:"Classes"}),e.jsxs("div",{className:"flex gap-2 text-xs",children:[e.jsx("button",{type:"button",className:"text-primary hover:underline",onClick:()=>y(new Set(b)),children:"Select all"}),e.jsx("button",{type:"button",className:"text-muted-foreground hover:underline",onClick:()=>y(new Set),children:"None"})]})]}),e.jsx(qs,{className:"h-64 border rounded-md p-3",children:e.jsx("div",{className:"space-y-2",children:b.map(V=>e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(As,{checked:g.has(V),onCheckedChange:H=>{const Y=new Set(g);H?Y.add(V):Y.delete(V),y(Y)}}),e.jsx("span",{className:"text-sm",children:V})]},V))})})]})]}),e.jsxs(Ys,{children:[e.jsx(w,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(w,{onClick:$,children:[e.jsx(ja,{className:"h-4 w-4 mr-2"}),"Print"]})]})]})}),e.jsx(ts,{open:f,onOpenChange:h,children:e.jsxs(as,{className:"max-w-md",children:[e.jsxs(rs,{children:[e.jsx(is,{children:"Pick a Round"}),e.jsx(Fs,{children:C!=null&&C.bpName?`“${C.bpName}” maps to multiple rounds in the timing system. Pick which round to print sheets for.`:"Pick which round to print sheets for."})]}),e.jsx(qs,{className:"max-h-80 border rounded-md",children:e.jsxs("div",{className:"divide-y",children:[M.map(V=>e.jsxs("button",{type:"button",className:"w-full text-left p-3 hover:bg-muted transition-colors",onClick:()=>E(V.event_name),children:[e.jsx("div",{className:"font-medium",children:V.event_name}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[V.event_date?V.event_date:"—",V.track_name?` · ${V.track_name}`:"",V.event_location?` · ${V.event_location}`:""]})]},V.event_name)),M.length===0&&e.jsx("div",{className:"p-4 text-sm text-muted-foreground text-center",children:"No timing events found."})]})}),e.jsx(Ys,{children:e.jsx(w,{variant:"outline",onClick:()=>h(!1),children:"Cancel"})})]})})]})}function th(){const{currentOrganization:s}=Je(),{data:n=[],isLoading:i}
359=Qt(),[t,d]=a.useState(""),[r,x]=a.useState(""),[c,o]=a.useState("");a.useEffect(()=>{d(""),x(""),o("")},[s==null?void 0:s.id]);const m=a.useMemo(()=>Array.from(new Set(n.map(l=>String(l.event_date_year??"").trim()).filter(Boolean))).sort((l,N)=>N.localeCompare(l)),[n]),p=a.useMemo(()=>t?Array.from(new Set(n.filter(l=>String(l.event_date_year??"")===t).map(l=>String(l.series_name??"").trim()).filter(Boolean))).sort((l,N)=>l.localeCompare(N)):[],[n,t]),u=a.useMemo(()=>!t||!r?[]:n.filter(l=>String(l.event_date_year??"")===t&&String(l.series_name??"").trim()===r).sort((l,N)=>{const j=`${l.event_date_year}-${String(l.event_date_month).padStart(2,"0")}-${String(l.event_date_day).padStart(2,"0")}`,g=`${N.event_date_year}-${String(N.event_date_month).padStart(2,"0")}-${String(N.event_date_day).padStart(2,"0")}`;return j.localeCompare(g)||l.event_name.localeCompare(N.event_name)}),[n,t,r]);return e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsxs(Ee,{className:"flex items-center gap-2",children:[e.jsx(ja,{className:"h-5 w-5 text-primary"}),"Print Scoring Sheets"]}),e.jsx(ns,{children:"Print manual moto scoring sheets. Pick a year, series, and race, then choose which classes and motos to include."})]}),e.jsxs(xe,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"year",children:"Year"}),e.jsxs(Pe,{value:t,onValueChange:l=>{d(l),x(""),o("")},disabled:i,children:[e.jsx(Ie,{id:"year",children:e.jsx(qe,{placeholder:i?"Loading…":"Choose a year"})}),e.jsx(Be,{children:m.map(l=>e.jsx(ae,{value:l,children:l},l))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"series",children:"Series"}),e.jsxs(Pe,{value:r,onValueChange:l=>{x(l),o("")},disabled:!t||p.length===0,children:[e.jsx(Ie,{id:"series",children:e.jsx(qe,{placeholder:t?p.length===0?"No series for this year":"Choose a series":"Pick a year first"})}),e.jsx(Be,{children:p.map(l=>e.jsx(ae,{value:l,children:l},l))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"race",children:"Race"}),e.jsxs(Pe,{value:c,onValueChange:o,disabled:!r||u.length===0,children:[e.jsx(Ie,{id:"race",children:e.jsx(qe,{placeholder:r?u.length===0?"No races in this series":"Choose a race":"Pick a series first"})}),e.jsx(Be,{children:u.map(l=>e.jsxs(ae,{value:l.event_name,children:[l.event_name,` — ${l.event_date_month}/${l.event_date_day}/${l.event_date_year}`]},l.event_name))})]})]}),e.jsx("div",{className:"pt-2",children:e.jsx(sh,{mysqlEventName:c||null,organizationId:(s==null?void 0:s.id)??null,mode:"picker",variant:"default",size:"default",label:"Cho
359ose classes & print",disabled:!c||!(s!=null&&s.id)})})]})]})}function ah({eventName:s,scheduleRows:n,label:i="Print"}){const t=()=>{if(!n||n.length===0)return;const d=window.open("","_blank","width=900,height=1100");if(!d)return;const r=j=>j.replace(/[&<>"']/g,g=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[g]),x=j=>{if(!j)return"";const g=new Date(j);return isNaN(g.getTime())?"":g.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",timeZone:"America/Denver"})},c=[];let o=null;for(const j of n){if(!o||o.kind!==j.kind||j.kind==="race"&&o.kind==="race"&&(o.moto??0)!==(j.moto??0)){const h=j.kind==="practice"?"Practices":`Moto ${j.moto??1}`,M=j.kind==="practice"?"banner practice":"banner race";c.push(`<li class="${M}">${h}</li>`)}const y=j.kind==="practice"?`<span class="tag practice">P${j.number}</span>`:`<span class="tag race">R${j.number}</span>`,k=j.riderCount!=null?`<span class="ct">${j.riderCount}</span>`:"",S=x(j.approxTimeIso),f=S?`<span class="tm">${S}</span>`:"";c.push(`<li><span class="pos">${j.position}</span>${y}<span class="cls">${r(j.classes.join(" + "))}</span>${k}${f}</li>`),o=j}const m=c.join(""),p=n.filter(j=>j.kind==="practice").length,u=n.filter(j=>j.kind==="race").length,l=`
360      <section class="copy">
361        <header>
362          <h1>${r(s)} – Full Schedule</h1>
363          <span class="meta">${p} practices · ${u} races</span>
364        </header>
365        <ol class="list">${m}</ol>
366      </section>`,N=`<!doctype html>
367<html><head><meta charset="utf-8"><title>Schedule – ${r(s)}</title>
368<style>
369  @page { size: letter portrait; margin: 0.15in; }
370  * { box-sizing: border-box; }
371  html, body { margin: 0; padding: 0; font-family: -apple-system, Arial, sans-serif; color: #000; }
372  body { font-size: 5.5pt; line-height: 1.05; }
373  .sheet { display: flex; flex-direction: row; width: 100%; height: 10.5in; }
374  .copy { flex: 1 1 0; min-width: 0; height: 100%; overflow: hidden;
375          border-right: 1px dashed #888; padding: 3px 4px; }
376  .copy:last-child { border-right: none; }
377  header { display: flex; justify-content: space-between; align-items: baseline;
378           border-bottom: 1px solid #000; padding-bottom: 1px; margin-bottom: 2px; }
379  h1 { font-size: 7pt; margin: 0; font-weight: 700; }
380  .meta { font-size: 5.5pt; color: #333; }
381  ol.list { list-style: none; margin: 0; padding: 0; }
382  ol.list li { display: flex; gap: 2px; align-items: baseline;
383               padding: 0 1px; border-bottom: 0.5px solid #ddd; }
384  .banner { display: block !important; margin: 2px 0 1px;
385            padding: 1px 3px; font-weight: 800; font-size: 6.5pt;
386            text-transform: uppercase; letter-spacing: 0.3px;
387            border-radius: 1px; text-align: center;
388            border-bottom: 0.5px solid #000; }
389  .banner.practice { background: #1d4ed8; color: #fff; }
390  .banner.race { background: #b45309; color: #fff; }
391  .pos { font-weight: 700; min-width: 12px; text-align: right;
392         font-variant-numeric: tabular-nums; color: #555; font-size: 5.5pt; }
393  .tag { font-size: 5pt; font-weight: 700; min-width: 22px;
394         padding: 0 2px; border-radius: 1px; text-align: center; }
395  .tag.practice { background: #eef3ff; color: #1d4ed8; border: 0.5px solid #94a8d9; }
396  .tag.race { background: #fff3e0; color: #b45309; border: 0.5px solid #d9b894; }
397  .cls { flex: 1; overflow-wrap: anywhere; font-size: 5.5pt; }
398  .ct { font-size: 5pt; color: #555; min-width: 12px; text-align: right; }
399  .tm { font-size: 5pt; color: #000; font-weight: 700;
400        font-variant-numeric: tabular-nums; min-width: 30px; text-align: right; }
401  .toolbar { position: fixed; top: 6px; right: 6px; }
402  .toolbar button { font-size: 11pt; padding: 4px 10px; }
403  @media print { .toolbar { display: none; } }
404</style></head>
405<body>
406  <div class="toolbar"><button onclick="window.print()">Print</button></div>
407  <div class="sheet">${l}${l}${l}</div>
408  <script>window.addEventListener('load', () => setTimeout(() => window.print(), 300));<\/script>
409</body></html>`;d.document.open(),d.document.write(N),d.document.close()};return e.jsxs(w,{variant:"outline",size:"sm",onClick:t,disabled:!(n!=null&&n.length),children:[e.jsx(ja,{className:"h-4 w-4 mr-2"}),i]})}function nh(){const{currentOrganization:s}=Je(),{data:n=[],isLoading:i}
409=Qt(),[t,d]=a.useState(""),[r,x]=a.useState(""),[c,o]=a.useState("");a.useEffect(()=>{d(""),x(""),o("")},[s==null?void 0:s.id]);const m=a.useMemo(()=>Array.from(new Set(n.map(f=>String(f.event_date_year??"").trim()).filter(Boolean))).sort((f,h)=>h.localeCompare(f)),[n]),p=a.useMemo(()=>t?Array.from(new Set(n.filter(f=>String(f.event_date_year??"")===t).map(f=>String(f.series_name??"").trim()).filter(Boolean))).sort((f,h)=>f.localeCompare(h)):[],[n,t]),u=a.useMemo(()=>!t||!r?[]:n.filter(f=>String(f.event_date_year??"")===t&&String(f.series_name??"").trim()===r).sort((f,h)=>{const M=`${f.event_date_year}-${String(f.event_date_month).padStart(2,"0")}-${String(f.event_date_day).padStart(2,"0")}`,T=`${h.event_date_year}-${String(h.event_date_month).padStart(2,"0")}-${String(h.event_date_day).padStart(2,"0")}`;return M.localeCompare(T)||f.event_name.localeCompare(h.event_name)}),[n,t,r]),l=a.useMemo(()=>u.find(f=>f.event_name===c)||null,[u,c]),N=l?`${l.event_date_year}-${String(l.event_date_month).padStart(2,"0")}-${String(l.event_date_day).padStart(2,"0")}`:null,{data:j,isLoading:g}=Go((s==null?void 0:s.slug)||void 0,c||void 0,void 0,N),y=a.useMemo(()=>((j==null?void 0:j.rows)||[]).map(h=>h.kind==="practice"?{kind:"practice",position:h.position,number:h.practice_number,moto:null,classes:h.classes||[],riderCount:h.num_riders??0,approxTimeIso:h.approx_time_iso??null}:{kind:"race",position:h.position,number:h.race_number,moto:h.moto_number??null,classes:h.classes||[],riderCount:h.num_riders??0,approxTimeIso:h.approx_time_iso??null}),[j]),k=y.filter(f=>f.kind==="practice").length,S=y.filter(f=>f.kind==="race").length;return e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsxs(Ee,{className:"flex items-center gap-2",children:[e.jsx(Gn,{className:"h-5 w-5 text-primary"}),"Print Race Order"]}),e.jsx(ns,{children:"Printer-friendly single-column schedule including practice groups and race order."})]}),e.jsxs(xe,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"year",children:"Year"}),e.jsxs(Pe,{value:t,onValueChange:f=>{d(f),x(""),o("")},disabled:i,children:[e.jsx(Ie,{id:"year",children:e.jsx(qe,{placeholder:i?"Loading…":"Choose a year"})}),e.jsx(Be,{children:m.map(f=>e.jsx(ae,{value:f,children:f},f))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"series",children:"Series"}),e.jsxs(Pe,{value:r,onValueChange:f=>{x(f),o("")},disabled:!t||p.length===0,children:[e.jsx(Ie,{id:"series",children:e.jsx(qe,{placeholder:t?p.length===0?"No series for this year":"Choose a series":"Pick a year first"})}),e.jsx(Be,{children:p.map(f=>e.jsx(ae,{value:f,children:f},f))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"race",children:"Race"}),e.jsxs(Pe,{value:c,onValueChange:o,disabled:!r||u.length===0,children:[e.jsx(Ie,{id:"race",children:e.jsx(qe,{placeholder:r?u.length===0?"No races in this series":"Choose a race":"Pick a series first"})}),e.jsx(Be,{children:u.map(f=>e.jsxs(ae,{value:f.event_name,children:[f.event_name," — ",f.event_date_month,"/",f.event_date_day,"/",f.event_date_year]},f.event_name))})]})]}),e.jsx("div",{className:"pt-2 flex items-center gap-3",children:c&&g?e.jsxs("div",{className:"flex items-center text-sm text-muted-foreground",children:[e.jsx(oe,{className:"h-4 w-4 mr-2 animate-spin"})," Loading schedule…"]}):e.jsxs(e.Fragment,{children:[e.jsx(ah,{eventName:c,scheduleRows:y,label:"Print Full Schedule"}),c&&y.length===0&&!g&&e.jsx("span",{className:"text-sm text-muted-foreground",children:"No schedule built for this event yet."}),y.length>0&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:[k," practices · ",S," races"]})]})})]})]})}function rh({organizationId:s,requiresOnboarding:n=!0,onCompleted:i}){const{account:t,isLoading:d,createAccount:r,getOnboardLink:x,getDashboardLink:c,refreshStatus:o}=Un(s);if(a.useEffect(()=>{if(!s)return;const g=new URL(window.location.href),y=g.searchParams.get("stripe_onboarding");(y==="complete"||y==="refresh")&&(o.mutate(s),g.searchParams.delete("stripe_onboarding"),window.history.replaceState({},"",g.toString()))},[s]),a.useEffect(()=>{t!=null&&t.details_submitted&&(t!=null&&t.payouts_enabled)&&(i==null||i())},[t==null?void 0:t.details_submitted,t==null?void 0:t.payouts_enabled]),!s)return null;if(!n)return e.jsx(re,{className:"mb-6 border-green-500/30 bg-green-500/5",children:e.jsxs(xe,{className:"pt-4 flex items-center gap-2 text-sm text-green-700",children:[e.jsx(Os,{className:"h-4 w-4"}),"Payout setup waived by Beyond Pro for this organization."]})});const m=async()=>
409{if(s)try{t!=null&&t.stripe_account_id||await r.mutateAsync(s);const g=await x.mutateAsync(s);g!=null&&g.url?window.location.href=g.url:K.error("Could not generate onboarding link")}catch(g){K.error(g.message||"Failed to start onboarding")}},p=async()=>{if(s)try{const g=await c.mutateAsync(s);g!=null&&g.url&&window.open(g.url,"_blank","noopener")}catch(g){K.error(g.message||"Failed to open dashboard")}},u=d||r.isPending||x.isPending||o.isPending,l=!!(t!=null&&t.details_submitted)&&!!(t!=null&&t.payouts_enabled),N=!!(t!=null&&t.stripe_account_id)&&!l,j=t!=null&&t.requirements_due?Object.values(t.requirements_due).reduce((g,y)=>g+(Array.isArray(y)?y.length:0),0):0;return e.jsxs(re,{className:"mb-6",children:[e.jsx(ke,{children:e.jsxs(Ee,{className:"text-base flex items-center gap-2",children:[e.jsx(jn,{className:"h-4 w-4"}),"Set up weekly payouts",l&&e.jsxs(ie,{className:"bg-green-600 text-white ml-auto",children:[e.jsx(Os,{className:"h-3 w-3 mr-1"})," Bank verified"]}),N&&e.jsxs(ie,{variant:"outline",className:"ml-auto border-amber-500/40 text-amber-700",children:[e.jsx(Is,{className:"h-3 w-3 mr-1"})," Action required"]})]})}),e.jsxs(xe,{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground space-y-2",children:[e.jsx("p",{children:"Beyond Pro will collect registration fees on your behalf and transfer your share to your bank account on a weekly schedule via ACH. Costs incurred (platform fee, live timing, messaging, AI) are deducted before transfer."}),e.jsx("p",{children:"We use Stripe to securely collect your bank routing and account information — we never store your bank credentials directly. You'll be redirected to a Stripe-hosted page to complete onboarding (about 5 minutes)."})]}),l?e.jsxs("div",{className:"rounded-lg border border-green-500/30 bg-green-500/5 p-3 text-sm space-y-2",children:[e.jsxs("p",{className:"flex items-center gap-2 text-green-700 font-medium",children:[e.jsx(Os,{className:"h-4 w-4"})," Your bank account is verified and ready to receive payouts."]}),e.jsxs(w,{variant:"outline",size:"sm",onClick:p,children:[e.jsx(ea,{className:"h-4 w-4 mr-2"}),"Manage in Stripe Dashboard"]})]}):N?e.jsxs("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/5 p-3 text-sm space-y-3",children:[e.jsxs("p",{className:"text-amber-800 font-medium",children:["Stripe needs more information before you can receive payouts.",j>0&&` (${j} item${j===1?"":"s"} due)`]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(w,{onClick:m,disabled:u,size:"sm",children:u?e.jsxs(e.Fragment,{children:[e.jsx(oe,{className:"h-4 w-4 mr-2 animate-spin"}),"Loading..."]}):e.jsxs(e.Fragment,{children:["Continue Stripe onboarding",e.jsx(ea,{className:"h-4 w-4 ml-2"})]})}),e.jsxs(w,{variant:"outline",size:"sm",onClick:()=>s&&o.mutate(s),disabled:o.isPending,children:[e.jsx(kt,{className:`h-4 w-4 mr-2 ${o.isPending?"animate-spin":""}`}),"Refresh status"]})]})]}):e.jsx(w,{onClick:m,disabled:u,size:"lg",children:u?e.jsxs(e.Fragment,{children:[e.jsx(oe,{className:"h-4 w-4 mr-2 animate-spin"}),"Loading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(jn,{className:"h-4 w-4 mr-2"}),"Connect bank account with Stripe",e.jsx(ea,{className:"h-4 w-4 ml-2"})]})})]})]})}function ih(){const{currentOrganization:s}=Je(),{contract:n,hasSignedCurrentVersion:i,signContract:t}=Bn(s==null?void 0:s.id),{account:d}=Un(s==null?void 0:s.id),r=!!(d!=null&&d.details_submitted)&&!!(d!=null&&d.payouts_enabled),[x,c]=a.useState(""),[o,m]=a.useState(""),[p,u]=a.useState(""),[l,N]=a.useState(""),[j,g]=a.useState(!1),[y,k]=a.useState(!1),[S,f]=a.useState(!1),[h,M]=a.useState(!1),T=a.useRef(null),C=!!x.trim()&&!!o.trim()&&!!p.trim()&&!!l&&j&&y&&S&&h&&r;a.useLayoutEffect(()=>{const R=T.current;if(!R||h)return;const E=()=>{R.scrollHeight<=R.clientHeight+80&&M(!0)};E();const $=new ResizeObserver(E);return $.observe(R),()=>$.disconnect()},[h]);const L=R=>{const E=R.currentTarget;E.scrollHeight-E.scrollTop-E.clientHeight<80&&M(!0)},Q=()=>{if(!s){K.error("Organization not loaded — please refresh and try again");return}if(!C){K.error("Please complete all required fields before signing");return}t.mutate({organization_id:s.id,signer_name:x,signer_title:o,signer_email:p,signature_data:l,agreed_to_fees:j,agreed_to_ip:y,agreed_to_terms:S})};if(i&&n)return e.jsx("section",{className:"py-8 bg-background min-h-screen",children:e.jsxs("div",{className:"container mx-auto px-4 max-w-3xl",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[e.jsx(La,{className:"h-8 w-8 text-primary"}),e.jsxs("div",{children:[e.jsx("h1",{className:"font-display text-3xl text-foreground",children:"Service Agreement Signed"}),e.jsx("p",{className:"text-muted-foreground",children:"Your organization has completed the service agreement."})]})]}),e.jsx(re,{children:e.jsxs(xe,{className:"pt-6 space-y-2",children:[e.jsxs("p",{className:"text-sm",children:["Signed by ",e.jsx("strong",{children:n.signer_name})," (",n.signer_title,")"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:n.signer_email}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Signed on ",new Date(n.signed_at).toLocaleDateString()," — version ",n.contract_version]})]})})]})});const Z=[{ok:h,label:'Read agreement (scroll to bottom or tap "Mark as read")'},{ok:j&&y&&S,label:"Check all 3 acknowledgments"},{ok:r,label:"Connect bank account for weekly payouts"},{ok:!!x.trim(),label:"Enter your full legal name"},{ok:!!o.trim(),label:"Enter your title / role"},{ok:!!p.trim(),label:"Enter your email address"},{ok:!!l,label:"Draw your signature"}];return e.jsx("section",{className:"py-8 bg-background min-h-screen",children:e.jsxs("div",{className:"container mx-auto px-4 max-w-3xl",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[e.jsx(La,{className:"h-8 w-8 text-primary"}),e.jsxs("div",{children:[e.jsx("h1",{className:"font-display text-3xl text-foreground",children:"SERVICE AGREEMENT"}),e.jsx("p",{className:"text-muted-foreground",children:"Please review and sign the following agreement to continue"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-amber-500/10 border border-amber-500/20 mb-6",children:[e.jsx(Is,{className:"h-5 w-5 text-amber-600 flex-shrink-0"}),e.jsx("p",{className:"text-sm text-amber-700",children:"You must sign this service agreement before accessing the admin dashboard. Please read the entire agreement carefully and scroll to the bottom."})]}),e.jsxs(re,{className:"mb-6",children:[e.jsx(ke,{children:e.jsxs(Ee,{className:"text-base",children:["Platform Service Agreement — ",s==null?void 0:s.name]})}),e.jsxs(xe,{children:[e.jsx("div",{ref:T,className:"h-96 overflow-y-auto border rounded-md p-4 bg-muted/20",onScroll:L,children:e.jsx(Ko,{organizationName:s==null?void 0:s.name})}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 mt-2",children:[h?e.jsxs("p",{className:"text-xs text-green-700 flex items-center gap-1",children:[e.jsx(Os,{className:"h-3.5 w-3.5"})," Agreement marked as read"]}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"↓ Scroll to the bottom, or tap the button to confirm you've read it"}),!h&&e.jsx(w,{type:"button",variant:"outline",size:"sm",onClick:()=>M(!0),children:"Mark as read"})]})]})]}),e.jsx(rh,{organizationId:s==null?void 0:s.id,requiresOnboarding:!0}),e.jsxs(re,{className:"mb-6",children:[e.jsx(ke,{children:e.jsx(Ee,{className:"text-base",children:"Acknowledgments"})}),e.jsxs(xe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(As,{id:"agree-fees",checked:j,onCheckedChange:R=>g(R===!0),disabled:!h}),e.jsxs(v,{htmlFor:"agree-fees",className:"text-sm leading-relaxed cursor-pointer",children:["I acknowledge and agree to the ",e.jsx("strong",{children:"Fee Payment Obligations"})," as outlined in Section 2, including all platform fees, subscription fees, and messaging costs."]})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(As,{id:"agree-ip",checked:y,onCheckedChange:R=>k(R===!0),disabled:!h}),e.jsxs(v,{htmlFor:"agree-ip",className:"text-sm leading-relaxed cursor-pointer",children:["I acknowledge and agree to the ",e.jsx("strong",{children:"Intellectual Property & Non-Reproduction"})," terms in Section 3. I will not copy, reverse engineer, or reproduce any part of this platform."]})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(As,{id:"agree-terms",checked:S,onCheckedChange:R=>f(R===!0),disabled:!h}),e.jsxs(v,{htmlFor:"agree-terms",className:"text-sm leading-relaxed cursor-pointer",children:["I have read, understand, and agree to the ",e.jsx("strong",{children:"entire Service Agreement"})," including all terms regarding confidentiality, indemnification, termination, and limitation of liability."]})]})]})]}),e.jsxs(re,{className:"mb-6",children:[e.jsx(ke,{children:e.jsx(Ee,{className:"text-base",children:"Signer Information"})}),e.jsxs(xe,{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["By signing below, you represent that you have the authority to bind ",e.jsx("strong",{children:s==null?void 0:s.name})," to this Agreement."]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"signer-name",children:"Full Legal Name *"}),e.jsx(A,{id:"signer-name",placeholder:"John Smith",value:x,onChange:R=>c(R.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"signer-title",children:"Title / Role *"}),e.jsx(A,{id:"signer-title",placeholder:"Owner, President, etc.",value:o,onChange:R=>m(R.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(v,{htmlFor:"signer-email",children:"Email Address *"}),e.jsx(A,{id:"signer-email",type:"email",placeholder:"[email protected]",value:p,onChange:R=>u(R.target.value)})]})]})]}),e.jsxs(re,{className:"mb-6",children:[e.jsx(ke,{children:e.jsxs(Ee,{className:"text-base flex items-center gap-2",children:[e.jsx(La,{className:"h-4 w-4"}),"Signature"]})}
409),e.jsx(xe,{children:e.jsx(Yo,{value:l,onChange:N,isLightFormColor:!0})})]}),e.jsx(w,{size:"lg",className:"w-full",disabled:!C||t.isPending,onClick:Q,children:t.isPending?"Signing...":"I Agree & Sign This Agreement"}),!C&&!t.isPending&&e.jsx(re,{className:"mt-4 border-amber-500/30 bg-amber-500/5",children:e.jsxs(xe,{className:"pt-4",children:[e.jsx("p",{className:"text-sm font-medium text-amber-800 mb-2",children:"Complete the following to enable the Sign button:"}),e.jsx("ul",{className:"space-y-1.5",children:Z.map((R,E)=>e.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[R.ok?e.jsx(Os,{className:"h-4 w-4 text-green-600 flex-shrink-0"}):e.jsx(vt,{className:"h-4 w-4 text-amber-600 flex-shrink-0"}),e.jsx("span",{className:R.ok?"text-muted-foreground line-through":"text-foreground",children:R.label})]},E))})]})}),e.jsx("p",{className:"text-xs text-muted-foreground text-center mt-4",children:"This electronic signature is legally binding under the E-SIGN Act (15 U.S.C. §7001 et seq.)"})]})})}function lh(){const{currentOrganization:s}=Je(),{data:n,isLoading:i}=tc(s==null?void 0:s.id),t=ac(),d=nc(),r=rc(),[x,c]=a.useState(!1),[o,m]=a.useState(null),[p,u]=a.useState({display_name:"",pin:"",location:"",active:!0}),l=()=>{m(null),u({display_name:"",pin:"",location:"",active:!0}),c(!0)},N=g=>{m(g),u({display_name:g.display_name,pin:"",location:g.location||"",active:g.active}),c(!0)},j=()=>
409{if(p.display_name&&!(!o&&!p.pin))if(o){const g={display_name:p.display_name,location:p.location,active:p.active};p.pin&&(g.pin_hash=p.pin),d.mutate({id:o.id,...g},{onSuccess:()=>c(!1)})}else t.mutate({display_name:p.display_name,pin_hash:p.pin,location:p.location,active:p.active,organization_id:s==null?void 0:s.id},{onSuccess:()=>c(!1)})};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Staff Logins"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage store staff who can redeem coupons"})]}),e.jsxs(w,{onClick:l,className:"gap-2",children:[e.jsx(Es,{className:"h-4 w-4"}),"Add Staff Login"]})]}),i?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(oe,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):n!=null&&n.length?e.jsx(re,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b text-left",children:[e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground",children:"Name"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground",children:"Location"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground",children:"Status"}),e.jsx("th",{className:"px-4 py-3 text-sm font-medium text-muted-foreground text-right",children:"Actions"})]})}),e.jsx("tbody",{children:n.map(g=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/50",children:[e.jsx("td",{className:"px-4 py-3 text-sm font-medium",children:g.display_name}),e.jsx("td",{className:"px-4 py-3 text-sm text-muted-foreground",children:g.location||"—"}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(ie,{variant:g.active?"default":"secondary",children:g.active?"Active":"Inactive"})}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(w,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>N(g),children:e.jsx(Ft,{className:"h-4 w-4"})}),e.jsxs(et,{children:[e.jsx(Lt,{asChild:!0,children:e.jsx(w,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",children:e.jsx(ws,{className:"h-4 w-4"})})}),e.jsxs(st,{children:[e.jsx(tt,{children:"Delete Staff Login"}),e.jsxs(at,{children:['Remove "',g.display_name,'"?']}),e.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[e.jsx(nt,{children:"Cancel"}),e.jsx(rt,{onClick:()=>r.mutate(g.id),className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})]})]})})]},g.id))})]})})}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Ii,{className:"h-12 w-12 mx-auto opacity-30 mb-2"}),e.jsx("p",{children:"No staff logins yet"})]}),e.jsx(ts,{open:x,onOpenChange:c,children:e.jsxs(as,{children:[e.jsx(rs,{children:e.jsx(is,{children:o?"Edit Staff Login":"Add Staff Login"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(v,{children:"Display Name *"}),e.jsx(A,{value:p.display_name,onChange:g=>u(y=>({...y,display_name:g.target.value})),placeholder:"Store Staff Name"})]}),e.jsxs("div",{children:[e.jsx(v,{children:o?"New PIN (leave blank to keep)":"PIN *"}),e.jsx(A,{type:"password",value:p.pin,onChange:g=>u(y=>({...y,pin:g.target.value})),placeholder:"4-6 digit PIN",maxLength:6})]}),e.jsxs("div",{children:[e.jsx(v,{children:"Location"}),e.jsx(A,{value:p.location,onChange:g=>u(y=>({...y,location:g.target.value})),placeholder:"Store location"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ds,{checked:p.active,onCheckedChange:g=>u(y=>({...y,active:g}))}),e.jsx(v,{children:"Active"})]}),e.jsxs(w,{onClick:j,disabled:!p.display_name||!o&&!p.pin||t.isPending||d.isPending,className:"w-full",children:[(t.isPending||d.isPending)&&e.jsx(oe,{className:"h-4 w-4 animate-spin mr-2"}),o?"Update":"Create"]})]})]})})]})}function Dr(s){if(!s)return null;const[n,i,t]=s.split("-").map(Number);return!n||!i||!t?null:new Date(n,i-1,t)}function ch(){const{currentOrganization:s}
409=Je(),[n,i]=a.useState("dates"),[t,d]=a.useState(""),[r,x]=a.useState(""),[c,o]=a.useState("all"),[m,p]=a.useState("all"),[u,l]=a.useState(null),{data:N,isLoading:j}=ms({queryKey:["recon-tab-events",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:h,error:M}=await z.from("events").select("id, name, event_date, parent_event_id").eq("organization_id",s.id).is("parent_event_id",null).order("event_date",{ascending:!1});if(M)throw M;return h??[]}}),{data:g,isLoading:y}=ms({queryKey:["recon-tab-rounds",c],enabled:c!=="all",queryFn:async()=>{const{data:h,error:M}=await z.from("events").select("id, name, event_date").eq("parent_event_id",c).order("event_date",{ascending:!0});if(M)throw M;return h??[]}}),k=m!=="all"?m:c,S=!!(s!=null&&s.id)&&(n==="dates"?!!t&&!!r:c!=="all"),f=ks({mutationFn:async h=>{if(!(s!=null&&s.id))throw new Error("No organization selected");let M,T;if(n==="dates"){const Q=Dr(t),Z=Dr(r);if(!Q||!Z)throw new Error("Select a date range");M=Q.toISOString(),T=new Date(Z.getTime()+24*60*60*1e3).toISOString()}else{if(c==="all")throw new Error("Select an event or series");M=new Date(2015,0,1).toISOString(),T=new Date(Date.now()+24*60*60*1e3).toISOString()}const{data:C,error:L}=await z.functions.invoke("org-reconciliation-report",{body:{organization_id:s.id,period_start:M,period_end:T,force_refresh:h===!0,...k&&k!=="all"?{event_id:k}:{}}});if(L)throw L;if(C!=null&&C.error)throw new Error(C.error);return C},onSuccess:h=>{l(h),K.success("Report generated")},onError:h=>K.error((h==null?void 0:h.message)??"Failed to generate report")});return e.jsxs("div",{className:"space-y-4 max-w-5xl",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold",children:"Reconciliation"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Generate a full money-flow reconciliation for your organization. Download the PDF or CSV to keep for your records."})]}),e.jsxs(re,{children:[e.jsxs(ke,{children:[e.jsx(Ee,{className:"text-base",children:"Report inputs"}),e.jsx(ns,{children:"Report by a date range, or by a single event / series. Dates are Mountain Time."})]}),e.jsxs(xe,{className:"space-y-3",children:[e.jsxs("div",{className:"min-w-[240px] max-w-[280px]",children:[e.jsx(v,{className:"text-xs",children:"Report by"}),e.jsxs(Pe,{value:n,onValueChange:h=>i(h),children:[e.jsx(Ie,{children:e.jsx(qe,{})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"dates",children:"Date range"}),e.jsx(ae,{value:"event",children:"Event / series"})]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-3 items-end",children:[n==="event"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"min-w-[240px]",children:[e.jsx(v,{className:"text-xs",children:"Event / series"}),e.jsxs(Pe,{value:c,onValueChange:h=>{o(h),p("all")},children:[e.jsx(Ie,{children:e.jsx(qe,{placeholder:j?"Loading…":"Select event or series"})}),e.jsx(Be,{children:(N??[]).map(h=>e.jsxs(ae,{value:h.id,children:[h.name,h.event_date?` · ${String(h.event_date).slice(0,10)}`:""]},h.id))})]})]}),c!=="all"&&(g??[]).length>0&&e.jsxs("div",{className:"min-w-[240px]",children:[e.jsx(v,{className:"text-xs",children:"Round"}),e.jsxs(Pe,{value:m,onValueChange:p,children:[e.jsx(Ie,{children:e.jsx(qe,{placeholder:y?"Loading…":"Whole series"})}),e.jsxs(Be,{children:[e.jsx(ae,{value:"all",children:"Whole series (all rounds)"}),(g??[]).map(h=>e.jsxs(ae,{value:h.id,children:[h.name,h.event_date?` · ${String(h.event_date).slice(0,10)}`:""]},h.id))]})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(v,{className:"text-xs",htmlFor:"rec-from",children:"From"}),e.jsx(A,{id:"rec-from",type:"date",value:t,onChange:h=>d(h.target.value),className:"w-44"})]}),e.jsxs("div",{children:[e.jsx(v,{className:"text-xs",htmlFor:"rec-to",children:"To"}),e.jsx(A,{id:"rec-to",type:"date",value:r,onChange:h=>x(h.target.value),className:"w-44"})]})]}),e.jsxs(w,{onClick:()=>f.mutate(!1),disabled:f.isPending||!S,children:[f.isPending?e.jsx(oe,{className:"mr-2 h-4 w-4 animate-spin"}):null,"Generate report"]}),e.jsx(w,{variant:"outline",onClick:()=>f.mutate(!0),disabled:f.isPending||!S,title:"Re-check every charge against Stripe live. Slower, but guaranteed current.",children:"Re-verify with Stripe"})]}),f.isPending&&e.jsx(Ho,{active:!0,expectedSeconds:f.variables===!0?70:45,label:f.variables===!0?"Re-checking every charge against Stripe live…":"Building the report — registrations, fees, and costs…"})]})]}),u&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(w,{variant:"outline",onClick:()=>Qo(u),children:[e.jsx(jt,{className:"mr-2 h-4 w-4"})," Download PDF"]}),e.jsxs(w,{variant:"outline",onClick:()=>Wo(u),children:[e.jsx($t,{className:"mr-2 h-4 w-4"})," Download CSV"]})]}),e.jsx(Zo,{data:u})]})]})}function oh({severity:s}){return s==="blocker"?e.jsxs(ie,{className:"bg-destructive text-destructive-foreground gap-1",children:[e.jsx(Ui,{className:"h-3 w-3"})," Blocker"]}):s==="warning"?e.jsxs(ie,{className:"bg-amber-500 text-white gap-1",children:[e.jsx(Is,{className:"h-3 w-3"})," Warning"]}):e.jsxs(ie,{variant:"secondary",className:"gap-1",children:[e.jsx(Rn,{className:"h-3 w-3"})," Info"]})}function dh(){const s=da(),{currentOrganization:n}
409=Je(),i=(n==null?void 0:n.id)??null,[t,d]=a.useState(null),{data:r}=ms({queryKey:["org-readiness-events",i],enabled:!!i,queryFn:async()=>{const{data:f,error:h}=await z.from("events").select("id, name, end_date, is_published").eq("organization_id",i).order("end_date",{ascending:!0,nullsFirst:!1});if(h)throw h;return f??[]}}),{data:x,isFetching:c,refetch:o}=Jo(i,t),m=Xo(i,t),{data:p=[],isLoading:u}=ms({queryKey:["org-readiness-rider-match-reviews",t],enabled:!!t,queryFn:async()=>{const{data:f,error:h}=await z.from("rider_match_reviews").select("id, status, registration_id, candidate_member_number, match_score, registration_details, candidate_details, created_at, review_kind").eq("event_id",t).order("created_at",{ascending:!1}).limit(500);if(h)throw h;return f??[]}}),l=p.filter(f=>f.status==="pending"),{data:N=[],isLoading:j}=ms({queryKey:["org-readiness-unlinked-registrations",t],enabled:!!t,queryFn:async()=>{const{data:f}=await z.from("events").select("id").eq("parent_event_id",t),h=Array.from(new Set([t,...(f??[]).map(C=>C.id)])),{data:M,error:T}=await z.from("registrations").select("id, first_name, last_name, email, event_id, family_member_id, beyondpro_member_number, status, created_at").in("event_id",h).eq("status","confirmed").or("family_member_id.is.null,beyondpro_member_number.is.null").order("created_at",{ascending:!1}).limit(500);if(T)throw T;return M??[]}});function g(f,h,M){if(h==="open_dedupe"||h==="open_merge"||h==="enqueue_merge"){t&&s(`/admin/events/${t}/registrations?rmrTab=review`);return}if(h==="open_registrations"||h==="open_rider"){t&&s(`/admin/events/${t}/registrations`);return}if(h==="open_transponders"){s("/admin?tab=transponders");return}m.mutate({action_kind:h,payload:M,issue_key:f.issue_key},{onSuccess:()=>K.success(`Applied: ${f.title}`),onError:T=>K.error(`Failed: ${(T==null?void 0:T.message)??"unknown error"}`)})}function y(f){m.mutate({action_kind:"dismiss",issue_key:f.issue_key},{onSuccess:()=>K.success("Dismissed"),onError:h=>K.error(`Failed: ${(h==null?void 0:h.message)??"unknown error"}`)})}const k=(x==null?void 0:x.summary.score)??0,S=k>=90?"text-emerald-600":k>=70?"text-amber-600":"text-destructive";return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(On,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"font-display text-xl md:text-2xl",children:"Race Readiness"}),e.jsxs("p",{className:"text-muted-foreground text-sm",children:["Pre-race data quality for ",(n==null?void 0:n.name)??"your organization"," — duplicates, ghost rows, missing data, transponders, sync drift."]})]})]}),e.jsx(re,{children:e.jsxs(xe,{className:"pt-6 flex flex-col md:flex-row gap-3 md:items-end",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Round / Event"}),e.jsxs(Pe,{value:t??"",onValueChange:d,disabled:!i,children:[e.jsx(Ie,{children:e.jsx(qe,{placeholder:"Select a round or event"})}),e.jsx(Be,{children:(r??[]).map(f=>e.jsxs(ae,{value:f.id,children:[f.name," ",f.end_date?`· ${Vt(f.end_date).toLocaleDateString()}`:""," ",f.is_published?"":"· (draft)"]},f.id))})]})]}),e.jsxs(w,{onClick:()=>o(),disabled:!t||c,variant:"outline",children:[c?e.jsx(oe,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(kt,{className:"h-4 w-4 mr-2"}),"Re-run"]})]})}),!t&&e.jsx(re,{children:e.jsx(xe,{className:"py-16 text-center text-muted-foreground",children:"Pick a round or event to run readiness checks."})}),t&&c&&!x&&e.jsx(re,{children:e.jsx(xe,{className:"py-16 text-center",children:e.jsx(oe,{className:"h-6 w-6 animate-spin mx-auto"})})}),x&&e.jsxs(e.Fragment,{children:[e.jsxs(re,{children:[e.jsx(ke,{children:e.jsxs(Ee,{className:"flex items-center justify-between",children:[e.jsx("span",{children:"Readiness"}),e.jsxs("span",{className:`text-4xl font-bold ${S}`,children:[k,e.jsx("span",{className:"text-base text-muted-foreground",children:"/100"})]})]})}),e.jsxs(xe,{className:"flex flex-wrap gap-6 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ui,{className:"h-4 w-4 text-destructive"})," ",e.jsx("strong",{children:x.summary.blocker})," blockers"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Is,{className:"h-4 w-4 text-amber-500"})," ",e.jsx("strong",{children:x.summary.warning})," warnings"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rn,{className:"h-4 w-4 text-muted-foreground"})," ",e.jsx("strong",{children:x.summary.info})," info"]}),e.jsxs("div",{className:"ml-auto text-muted-foreground",children:[x.registration_count," active registrations"]})]})]}),e.jsxs(re,{children:[e.jsx(ke,{children:e.jsxs(Ee,{className:"flex items-center gap-2 justify-between flex-wrap",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Kn,{className:"h-5 w-5 text-primary"}),"Rider Match Review",l.length>0&&e.jsxs(ie,{className:"bg-destructive text-destructive-foreground ml-1",children:[l.length," pending"]}),N.length>0&&e.jsxs(ie,{className:"bg-amber-500 text-white ml-1",children:[N.length," unlinked"]})]}),e.jsxs(w,{size:"sm",variant:"outline",onClick:()=>s(`/admin/events/${t}/registrations?rmrTab=review`),children:["Open Full Review Tool",e.jsx($l,{className:"h-4 w-4 ml-1"})]})]})}),e.jsx(xe,{children:u||j?e.jsxs("div",{className:"py-6 flex items-center justify-center text-muted-foreground",children:[e.jsx(oe,{className:"h-5 w-5 animate-spin mr-2"})," Loading..."]}):l.length===0&&N.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-2",children:"No pending rider matches. All registrations are linked."}):e.jsxs("div",{className:"divide-y",children:[l.slice(0,10).map(f=>{const h=f.registration_details||{},M=f.candidate_details||{}
409,T=[h.first_name,h.last_name].filter(Boolean).join(" ")||"Unknown rider",C=[M.firstName,M.lastName].filter(Boolean).join(" ");return e.jsxs("div",{className:"flex items-center gap-3 py-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(ie,{variant:"destructive",className:"text-xs",children:"Pending review"}),e.jsx("span",{className:"font-medium",children:T}),h.email&&e.jsx("span",{className:"text-xs text-muted-foreground",children:h.email})]}),C&&e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:["Suggested match: ",C,f.match_score!=null?` · score ${f.match_score}`:""]})]}),e.jsx(w,{size:"sm",variant:"outline",onClick:()=>s(`/admin/events/${t}/registrations?rmrTab=review`),children:"Review"})]},f.id)}),N.slice(0,20).map(f=>{const h=[f.first_name,f.last_name].filter(Boolean).join(" ")||"Unknown rider",M=[];return f.family_member_id||M.push("no family link"),f.beyondpro_member_number||M.push("no BP#"),e.jsxs("div",{className:"flex items-center gap-3 py-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(ie,{className:"bg-amber-500 text-white text-xs",children:"Unlinked"}),e.jsx("span",{className:"font-medium",children:h}),f.email&&e.jsx("span",{className:"text-xs text-muted-foreground",children:f.email})]}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:M.join(" · ")})]}),e.jsx(w,{size:"sm",variant:"outline",onClick:()=>s(`/admin/registrations/${f.id}/edit`),children:"Fix Registration"})]},f.id)})]})})]}),e.jsx(ed,{type:"multiple",defaultValue:x.categories.filter(f=>f.issues.some(h=>h.severity!=="info")).map(f=>f.key),children:x.categories.map(f=>{const h=f.issues.filter(C=>C.severity==="blocker").length,M=f.issues.filter(C=>C.severity==="warning").length,T=f.issues.filter(C=>C.severity==="info").length;return e.jsxs(sd,{value:f.key,children:[e.jsx(td,{children:e.jsxs("div",{className:"flex items-center gap-3 w-full",children:[e.jsx("span",{className:"font-semibold",children:f.label}),e.jsxs("div",{className:"flex gap-2 ml-auto mr-3 text-xs",children:[h>0&&e.jsx(ie,{className:"bg-destructive text-destructive-foreground",children:h}),M>0&&e.jsx(ie,{className:"bg-amber-500 text-white",children:M}),T>0&&e.jsx(ie,{variant:"secondary",children:T}),f.issues.length===0&&e.jsx(ie,{variant:"outline",className:"text-emerald-600 border-emerald-600",children:"Clean"})]})]})}),e.jsx(ad,{children:f.issues.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-2",children:"No issues found."}):f.issues.map(C=>e.jsxs("div",{className:"flex items-start justify-between gap-4 py-3 border-b last:border-b-0",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(oh,{severity:C.severity}),e.jsx("span",{className:"font-medium",children:C.title})]}),C.detail&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 break-words",children:C.detail})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[C.actions.map(L=>e.jsx(w,{size:"sm",variant:"outline",disabled:m.isPending,onClick:()=>g(C,L.kind,L.payload),children:L.label},L.kind+L.label)),e.jsx(w,{size:"sm",variant:"ghost",disabled:m.isPending,onClick:()=>y(C),children:"Dismiss"})]})]},C.id))})]},f.key)})})]})]})}const Hg=()=>{const{signOut:s,isSuperAdmin:n}=kn(),i=da(),[t,d]=Lr(),[r,x]=a.useState(!1),[c,o]=a.useState(!1),[m,p]=a.useState(!1),u=a.useRef(null),{currentOrganization:l}=Je(),{count:N,total:j}=nd(),{reviewCountsByEvent:g,abandonedCountsByEvent:y,unreadSmsCount:k,failedEmailCount:S}=Kr();En(["page_builder"]);const{isTimingEnabled:f}=Wt(),{isCommunicationsEnabled:h}=$c(),{hasSignedCurrentVersion:M}=Bn(l==null?void 0:l.id),T=t.get("tab")||"registration",C=t.get("action"),L=C==="create-event";a.useEffect(()=>{C&&d(E=>(E.delete("action"),E),{replace:!0})},[C,d]),a.useEffect(()=>{const E=localStorage.getItem("beyondpro_getting_started_dismissed")==="true",$=N>=j&&j>0;!E&&!$&&x(!0)},[N,j]);const Q=E=>{d($=>($.set("tab",E),$))},Z=()=>{m&&localStorage.setItem("beyondpro_getting_started_dismissed","true"),x(!1),i("/admin/getting-started")},R=()=>{m&&localStorage.setItem("beyondpro_getting_started_dismissed","true"),x(!1),setTimeout(()=>{o(!0),setTimeout(()=>
409o(!1),6e3)},400)};return e.jsx(e.Fragment,{children:e.jsxs("section",{className:"py-6 bg-background min-h-full",children:[e.jsx("div",{className:"container mx-auto px-4 relative z-20",children:e.jsxs(ot,{value:T,onValueChange:Q,className:"w-full",children:[e.jsxs("div",{className:"flex flex-col gap-3 mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3","data-tour":"dashboard-title",children:[e.jsx(rd,{className:"h-7 w-7 text-primary flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("h1",{className:"font-display text-2xl md:text-3xl text-foreground",children:"ADMIN DASHBOARD"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage events, registrations, and timing"})]})]}),c&&e.jsxs(Ti,{open:c,onOpenChange:o,children:[e.jsx(Ri,{asChild:!0,children:e.jsx("span",{ref:u})}),e.jsx($i,{side:"bottom",className:"w-64 p-3",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(aa,{className:"h-4 w-4 text-primary mt-0.5 flex-shrink-0"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Tip:"})," Find Getting Started in the sidebar under Tools."]})]})})]})]}),!M&&!n&&e.jsxs("div",{className:"mb-4 rounded-lg border border-amber-500/50 bg-amber-500/10 p-3 flex items-center gap-3",children:[e.jsx(La,{className:"h-5 w-5 text-amber-600 flex-shrink-0"}),e.jsx("p",{className:"text-sm text-amber-800 dark:text-amber-200",children:"Your service agreement has not been signed. Some features are restricted until the agreement is completed."}),e.jsx(w,{variant:"outline",size:"sm",className:"ml-auto flex-shrink-0",onClick:()=>Q("service-agreement"),children:"Sign Agreement"})]}),(l==null?void 0:l.id)&&e.jsx(Kd,{organizationId:l.id}),(l==null?void 0:l.id)&&e.jsx(Fc,{organizationId:l.id}),(l==null?void 0:l.id)&&e.jsx(Yd,{organizationId:l.id}),e.jsx(Ae,{value:"shareable-links",children:e.jsx("div",{"data-tour":"shareable-links",children:e.jsx(qd,{defaultOpen:!0})})}),e.jsx(Ae,{value:"registration",children:e.jsx(Pd,{autoOpenCreateEvent:L,reviewCountsByEvent:g,abandonedCountsByEvent:y})}),(f||h)&&e.jsx(Ae,{value:"timing",children:e.jsx(ku,{unreadSmsCount:k,failedEmailCount:S})}),e.jsx(Ae,{value:"usage",children:e.jsx(Ru,{})}),e.jsx(Ae,{value:"analytics",children:e.jsx(Eo,{orgMode:!0})}),e.jsx(Ae,{value:"website",children:e.jsx(Fu,{})}),e.jsx(Ae,{value:"race-readiness",children:e.jsx(dh,{})}),e.jsx(Ae,{value:"reconciliation",children:e.jsx(ch,{})}),e.jsx(Ae,{value:"lookup",children:e.jsx(Au,{})}),e.jsx(Ae,{value:"contingency",children:e.jsx(Ku,{})}),e.jsx(Ae,{value:"series-points-export",children:e.jsx(Hu,{})}),e.jsx(Ae,{value:"race-results-export",children:e.jsx(Qu,{})}),e.jsx(Ae,{value:"scoring-sheets",children:e.jsx(th,{})}),e.jsx(Ae,{value:"race-order-print",children:e.jsx(nh,{})}),e.jsx(Ae,{value:"service-agreement",children:e.jsx(ih,{})}),e.jsx(Ae,{value:"rider-lookup",children:e.jsx(Vu,{})}),e.jsx(Ae,{value:"rider-manager",children:e.jsx(Ou,{})}),e.jsx(Ae,{value:"pos-users",children:e.jsx(lh,{})}),e.jsx(Ae,{value:"unlinked-registrations",children:e.jsx(Gu,{})})]})}),e.jsx(ts,{open:r,onOpenChange:E=>{E||R()},children:e.jsxs(as,{className:"max-w-md",children:[e.jsxs(rs,{children:[e.jsxs(is,{className:"flex items-center gap-2 text-xl",children:[e.jsx("div",{className:"rounded-lg bg-primary/10 p-2",children:e.jsx(xr,{className:"h-6 w-6 text-primary"})}),"Welcome to Your Dashboard!"]}),e.jsx(Fs,{className:"pt-3 text-sm leading-relaxed text-muted-foreground",children:N>0&&N<j?e.jsxs(e.Fragment,{children:["You've completed ",e.jsxs("span",{className:"font-medium text-foreground",children:[N," of ",j]})," sections. Keep going — open the guide to finish setting up!"]}):e.jsxs(e.Fragment,{children:["We have a ",e.jsx("span",{className:"font-medium text-foreground",children:"Getting Started Guide"})," that walks you through everything — from branding and fees to creating events and building registration forms."]})})]}),e.jsxs("div",{className:"space-y-4 pt-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"It only takes a few minutes and will help you hit the ground running."}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(As,{id:"dont-show-again",checked:m,onCheckedChange:E=>p(E===!0)}),e.jsx("label",{htmlFor:"dont-show-again",className:"text-sm text-muted-foreground cursor-pointer select-none",children:"Don't show this on login"})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(w,{variant:"outline",onClick:R,children:"I'll explore on my own"}),e.jsxs(w,{onClick:Z,children:[e.jsx(xr,{className:"mr-2 h-4 w-4"}),"Open Getting Started"]})]})]})]})})]})})};export{Hg as default};

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.