1import{r as F,Z as ks,l as J,a6 as _s,s as S,u as be,j as e,E as Ve,F as We,G as He,H as Ye,R as js,ac as At,ad as Mt,B as k,ae as zt,af as Dt,I as Qe,b as pe,X as Ls,O as ts,D as Lt,J as Is,_ as Me,aa as ht,P as Os,d as Js,a as De,i as Bs,m as qe,n as ns,o as Ks,p as Us,q as pt,v as D,S as Pt,w as Tt,x as It,y as Ot,z as Oe,t as Bt,Y as Kt,M as Ps,ab as Zs,K as Ut,h as Qt}from"./index-Ct8eLu1I.js";import{T as ft,a as xt,b as Ke,c as Ue}from"./tabs-BxjRtXE_.js";import{c as Vt}from"./orgNetRevenue-Bfw6BRxN.js";import{a as Wt,u as Ht}from"./useEventAnalytics-CAAWlxxZ.js";import{u as Yt}from"./usePlatformServiceFees-Dia1sN9c.js";import{S as gt}from"./scroll-area-XBOZYw_N.js";import{A as Gt,b as Jt,c as Zt,d as Xt,e as en,f as sn,g as tn,h as nn}from"./alert-dialog-C_VGpbHe.js";import{C as Ae}from"./checkbox-s2xEAdOA.js";import{P as Xs,a as et,b as st}from"./popover-Dz6tNqoF.js";import{C as tt}from"./calendar-DxDCzZX-.js";import{C as bs,a as vs,b as Ns}from"./collapsible-CE2zbKIJ.js";import{F as an}from"./folder-open-BTqxP00f.js";import{T as yt}from"./trash-2-LxvlgA12.js";import{S as rn}from"./save-BTwFz6YM.js";import{C as nt}from"./calendar-CbKSfKX5.js";import{e as ln,f as on}from"./formatDistanceToNow-nzxXZqmT.js";import{f as ke,s as dn}from"./format-ybceeo2k.js";import{d as at,s as rt}from"./signupLabel-CoOzVGDj.js";import{C as it}from"./copy-BLDCcnKG.js";import{D as Ts}from"./dollar-sign-4EtnXuIa.js";import{E as cn}from"./external-link-Jsfrs_aE.js";import{R as ws}from"./refresh-cw-B5_EXY-e.js";import{S as Qs}from"./search-BsvfnwMH.js";import{M as Vs}from"./mail-BgXQiqCk.js";import{P as mn}from"./phone-CEN_vm4h.js";import{B as un}from"./bike-BIqava6h.js";import{F as hn}from"./file-check-D7f7QP0i.js";import{S as _t}from"./shopping-bag-CTD0jp3M.js";import{P as lt}from"./pen-cK6y1lt9.js";import{E as pn}from"./eye-BX6Kc3UM.js";import{U as fn}from"./user-x-Df6xAmC1.js";import{U as Ws}from"./user-check-BwC8fXcP.js";import{S as as}from"./send-BmfKE8XA.js";import{C as ss}from"./circle-x-DAvesdV7.js";import{T as jt,a as bt,b as Ge,c as Ee,d as vt,e as Se}from"./table--nl4fhep.js";import{R as Nt,a as wt}from"./radio-group-C9ucw0LR.js";import{u as xn}from"./useRidersForOrg-HvJYLxMM.js";import{C as gn}from"./circle-check-big-B2qMybdU.js";import{H as yn}from"./history-BS_575gd.js";import{U as kt}from"./user-plus-BtybScnH.js";import{T as St}from"./triangle-alert-DJpcx1Nd.js";import{C as _n}from"./clock-B75jo-2Q.js";import{u as jn}from"./useSendSMS-CjXzQ05F.js";import{c as bn,E as vn}from"./EmailBlastWizard-RF981D9G.js";import{T as Nn}from"./textarea-ZX0L5GAv.js";import{U as wn}from"./users-YMaWm21U.js";import{M as kn}from"./message-square-DX3LWn6G.js";import{P as Sn}from"./package-BIcii-RO.js";import{G as Cn}from"./gift-C-KFjWTZ.js";import{a as Fn,A as $n}from"./AIFloatingButton-DzuTziAn.js";import{O as En}from"./OrganizationBadge-5pjWJhs2.js";import{a as qn}from"./KioskAdapterContext-D-dkJDI6.js";import{A as Rn}from"./arrow-left-xu1INuH2.js";import{L as An}from"./layers-DmHX825Z.js";import"./resolveClassName-DvVkNNVP.js";import"./en-US-CGO0aXMi.js";import"./startOfMonth-B1VOnNUT.js";import"./endOfMonth--R-WtYph.js";import"./differenceInCalendarMonths-D2gXU8RP.js";import"./chevron-left-m_yK3qef.js";import"./index-0rGuXlz0.js";import"./differenceInMilliseconds-CVPzdaho.js";import"./useTimingEnabled-Cvj4NnkE.js";import"./SetupWizard-IaKRIBAl.js";import"./progress-CZ_7l-CT.js";import"./sanitized-html-D_hDi9wu.js";import"./purify.es-C5KSVp3G.js";import"./switch-BivgU5Jr.js";import"./megaphone-EgNztnZk.js";import"./useTimingClassesForOrg-B1awIF23.js";import"./skeleton-Bbz92LbC.js";import"./ExtrasRecipientPicker-C02xnSlF.js";import"./alert-lZXLZ_nC.js";import"./map-pin-DUB0IYFr.js";import"./shirt-yZVtQS9T.js";import"./index-DvDyV3_k.js";import"./index-CJLyLLo7.js";import"./index-Dh4i1-J3.js";import"./index-ouk_GpjY.js";import"./database-COmqmgFs.js";import"./square-pen-CMzwsyoA.js";import"./code-B3uDdoMW.js";import"./underline-DzSBTR4Z.js";import"./list-ordered-D8sNfrla.js";import"./link-BavsN2MW.js";import"./image-B91W3doo.js";import"./ImageLightbox-DzJkaBWN.js";import"./bot-D2DTHCn_.js";import"./minus-CoO45ah2.js";import"./zap-DvDo5oFM.js";import"./sparkles-BqYnitDi.js";import"./thumbs-up-CrpZt3t6.js";import"./thumbs-down-ChN-DmeG.js";import"./crosshair-gUHo1kGG.js";import"./building-2-BSn65gGt.js";const zs=[{key:"first_name",label:"First Name"},{key:"last_name",label:"Last Name"},{key:"confirmation_number",label:"Confirmation Number"},{key:"status",label:"Status"},{key:"payment_status",label:"Payment Status"},{key:"checked_in",label:"Checked In"},{key:"checked_in_at",label:"Checked In At"},{key:"subtotal",label:"Subtotal"},{key:"add_ons_total",label:"Add-ons Total"},{key:"fees_total",label:"Fees Total"},{key:"total_amount",label:"Total Amount"},{key:"created_at",label:"Registration Date"}],Ds=t=>(t||"Field").replace(/<[^>]*>/g,"").trim(),Mn=[{key:"street",label:"Street"},{key:"street2",label:"Street 2"},{key:"city",label:"City"},{key:"state",label:"State"},{key:"zip",label:"Zip"},{key:"zipCode",label:"Zip Code"},{key:"country",label:"Country"}],zn=[{key:"className",label:"Class"},{key:"bikeNumber",label:"Bike #"},{key:"bikeMake",label:"Bike Make"}],ot=[{key:"month",label:"Month"},{key:"day",label:"Day"},{key:"year",label:"Year"},{key:"full",label:"Full Date"}],Dn=[{key:"firstName",label:"First Name"},{key:"lastName",label:"Last Name"}],Ln=[{key:"quantity_by_size",label:"Qty by Size"},{key:"total_quantity",label:"Total Qty"},{key:"price",label:"Price"}],Pn=[{key:"size",label:"Size"},{key:"quantity",label:"Quantity"}],Tn=[{key:"type",label:"Type"},{key:"event_count",label:"Event Count"},{key:"events",label:"Events"},{key:"divisions",label:"Divisions"},{key:"classes",label:"Classes"}],$e={name:Dn,address:Mn,class_entry:zn,date:ot,dob:ot,merchandise:Ln,tshirt_size:Pn,season_registration:Tn},es=t=>{if(!t)return null;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{return null}return null},dt=t=>t?t.toLowerCase()==="true"?"Yes":t.toLowerCase()==="false"?"No":t:"";function In({eventId:t,open:x,onOpenChange:n}){const[i,h]=F.useState(["first_name","last_name","confirmation_number","status","checked_in","total_amount"]),[l,m]=F.useState({}),[j,_]=F.useState([]),[r,B]=F.useState(!1),[M,g]=F.useState(void 0),[b,A]=F.useState(void 0),[v,L]=F.useState(!0),[$,O]=F.useState(""),[q,K]=F.useState(!1),le=ks(),{data:V=[]}
1=J({queryKey:["export-presets",t],queryFn:async()=>{const{data:c,error:f}=await S.from("export_presets").select("*").eq("event_id",t).order("created_at",{ascending:!1});if(f)throw f;return c||[]},enabled:x}),H=_s({mutationFn:async c=>{const f={...l,__meta__:{onlyRowsWithData:v}},{error:R}=await S.from("export_presets").insert({event_id:t,name:c,selected_standard_fields:i,field_selections:f});if(R)throw R},onSuccess:()=>{le.invalidateQueries({queryKey:["export-presets",t]}),O(""),K(!1),be.success("Preset saved")},onError:c=>{console.error("Failed to save preset:",c),be.error("Failed to save preset")}}),te=_s({mutationFn:async c=>{const{error:f}=await S.from("export_presets").delete().eq("id",c);if(f)throw f},onSuccess:()=>{le.invalidateQueries({queryKey:["export-presets",t]}),be.success("Preset deleted")},onError:c=>{console.error("Failed to delete preset:",c),be.error("Failed to delete preset")}}),{data:Z}=J({queryKey:["export-source-event",t],queryFn:async()=>{const{data:c}=await S.from("events").select("id, parent_event_id").eq("id",t).maybeSingle(),f=(c==null?void 0:c.parent_event_id)??null,{count:R}=await S.from("form_fields").select("id",{count:"exact",head:!0}).eq("event_id",t),Q=(R??0)>0||!f?t:f;return{parentEventId:f,formEventId:Q}},enabled:x&&!!t}),me=(Z==null?void 0:Z.formEventId)??t;Z==null||Z.parentEventId;const fe=!!Z&&Z.formEventId!==t,{data:xe=[]}=J({queryKey:["export-add-ons",t,me],queryFn:async()=>{const c=Array.from(new Set([t,me].filter(Boolean))),{data:f,error:R}=await S.from("add_ons").select("id, name, price, event_id").in("event_id",c).order("name",{ascending:!0});if(R)throw R;return f||[]},enabled:x&&!!Z}),[oe,U]=F.useState([]),re=c=>U(f=>f.includes(c)?f.filter(R=>R!==c):[...f,c]),{data:ue=[]}=J({queryKey:["export-form-fields",me],queryFn:async()=>{const{data:c,error:f}=await S.from("form_fields").select("id, label, field_type, field_order, options, export_label").eq("event_id",me).order("field_order",{ascending:!0});if(f)throw f;const R=["waiver","heading","paragraph","divider","image","page_break","line_break","share_and_thank","banner","button_link","facebook_plugins","video","image_gallery","schedule","speakers","location","raw_html","widget","grouprev_signup","usat_membership"];return(c||[]).filter(Q=>!R.includes(Q.field_type))},enabled:x&&!!Z});F.useEffect(()=>{if(ue.length>0&&Object.keys(l).length===0){const c={};ue.forEach(f=>{const R=!!$e[f.field_type],Q=$e[f.field_type]||[];c[f.id]={fieldId:f.id,subFields:R?Q.map(ne=>ne.key):["__all__"],isExpandable:R,fieldType:f.field_type}}),m(c)}},[ue]);const Ce=c=>{h(f=>f.includes(c)?f.filter(R=>R!==c):[...f,c])},Je=c=>{m(f=>{const R=f[c];if(!R)return f;if(R.isExpandable?R.subFields.length>0:R.subFields.includes("__all__"))return{...f,[c]:{...R,subFields:[]}};{const ne=$e[R.fieldType]||[];return{...f,[c]:{...R,subFields:R.isExpandable?ne.map(G=>G.key):["__all__"]}}}})},rs=(c,f)=>{m(R=>{const Q=R[c];if(!Q)return R;const G=Q.subFields.includes(f)?Q.subFields.filter(ce=>ce!==f):[...Q.subFields,f];return{...R,[c]:{...Q,subFields:G}}})},is=c=>{const f=l[c];return f?f.isExpandable?f.subFields.length>0:f.subFields.includes("__all__"):!1},Ze=(c,f)=>{const R=l[c];return(R==null?void 0:R.subFields.includes(f))??!1},ls=c=>{_(f=>f.includes(c)?f.filter(R=>R!==c):[...f,c])},os=()=>{h(zs.map(c=>c.key))},ds=()=>{h([])},cs=()=>{const c={};ue.forEach(f=>{const R=!!$e[f.field_type],Q=$e[f.field_type]||[];c[f.id]={fieldId:f.id,subFields:R?Q.map(ne=>ne.key):["__all__"],isExpandable:R,fieldType:f.field_type}}),m(c)},Ss=()=>{const c={};ue.forEach(f=>{const R=!!$e[f.field_type];c[f.id]={fieldId:f.id,subFields:[],isExpandable:R,fieldType:f.field_type}}),m(c)},ye=()=>{if(!$.trim()){be.error("Please enter a preset name");return}H.mutate($.trim())},ms=c=>{h(c.selected_standard_fields||[]);const f={},R=c.field_selections||{},Q=R.__meta__||{};typeof Q.onlyRowsWithData=="boolean"&&L(Q.onlyRowsWithData);const ne=Object.fromEntries(Object.entries(R).filter(([G])=>G!=="__meta__"));ue.forEach(G=>{const ce=ne[G.id];if(ce)f[G.id]=ce;else{const ee=!!$e[G.field_type];f[G.id]={fieldId:G.id,subFields:[],isExpandable:ee,fieldType:G.field_type}}}),m(f),be.success(`Loaded preset "${c.name}"`)},us=c=>{te.mutate(c)},Xe=F.useMemo(()=>Object.values(l).filter(c=>c.subFields.length>0||!c.isExpandable&&c.subFields.includes("__all__")).length,[l]),hs=async()=>{const c=Object.values(l).some(f=>f.subFields.length>0);if(!(i.length===0&&!c&&oe.length===0)){B(!0);try{const R=[];for(let p=0;;p+=1e3){let u=S.from("registrations").select("*").eq("event_id",t).order("created_at",{ascending:!1}).order("id",{ascending:!0}).range(p,p+1e3-1);M&&(u=u.gte("created_at",dn(M).toISOString())),b&&(u=u.lte("created_at",ln(b).toISOString()));const{data:T,error:w}=await u;if(w)throw w;const z=T||[];if(R.push(...z),z.length<1e3)break}const Q={};R.forEach(p=>{Q[p.id]=p.parent_registration_id??null});const ne=Array.from(new Set([...R.map(p=>p.id),...R.map(p=>
1p.parent_registration_id).filter(Boolean)])),G=(p,u)=>{const T=[];for(let w=0;w<p.length;w+=u)T.push(p.slice(w,w+u));return T},ce=Object.entries(l).filter(([p,u])=>u.subFields.length>0).map(([p])=>p);let ee={};if(ce.length>0&&ne.length>0)for(const p of G(ne,200)){const{data:u,error:T}=await S.from("form_responses").select("registration_id, field_id, field_value").in("registration_id",p).in("field_id",ce);if(T)throw T;(u||[]).forEach(w=>{ee[w.registration_id]||(ee[w.registration_id]={}),ee[w.registration_id][w.field_id]=w.field_value})}const Cs=p=>{const u=ee[p]||{},T=Q[p];return T?{...ee[T]||{},...u}:u},_e={};if(oe.length>0&&ne.length>0)for(const p of G(ne,200)){const{data:u,error:T}=await S.from("registration_add_ons").select("registration_id, add_on_id, quantity").in("registration_id",p).in("add_on_id",oe);if(T)throw T;(u||[]).forEach(w=>{_e[w.registration_id]||(_e[w.registration_id]={}),_e[w.registration_id][w.add_on_id]=(_e[w.registration_id][w.add_on_id]||0)+(w.quantity||0)})}const Fs=(p,u)=>{var z,Y;const T=(z=_e[p])==null?void 0:z[u];if(T)return T;const w=Q[p];return w&&((Y=_e[w])==null?void 0:Y[u])||0},X=[],he=[];i.forEach(p=>{const u=zs.find(T=>T.key===p);u&&(X.push(u.label),he.push({type:"standard",key:p}))}),ue.forEach(p=>{const u=l[p.id];if(!u||u.subFields.length===0)return;const T=p.export_label||Ds(p.label);if(u.isExpandable){const w=$e[u.fieldType]||[];if(u.fieldType==="class_entry"){let z=1;for(const Y in ee){const se=ee[Y][p.id],C=es(se);Array.isArray(C)&&(z=Math.max(z,C.length))}for(let Y=0;Y<z;Y++)u.subFields.forEach(se=>{const C=w.find(I=>I.key===se);if(C){const I=z>1?`${T} ${Y+1} ${C.label}`:`${T} ${C.label}`;X.push(I),he.push({type:"form",key:`${p.id}__${Y}__${se}`,fieldId:p.id,subField:`${Y}__${se}`})}})}else if(u.fieldType==="merchandise"){const z=p.options||[];z.forEach((Y,se)=>{var W,ae;const C=Y.label||`Item ${se+1}`;Y.isClothing&&(((W=Y.sizes)==null?void 0:W.length)||((ae=Y.youthSizes)==null?void 0:ae.length))&&u.subFields.includes("quantity_by_size")&&[...Y.sizes||[],...Y.youthSizes||[]].forEach(Ne=>{X.push(`${T} - ${C} (${Ne})`),he.push({type:"form",key:`${p.id}__merch__${se}__size__${Ne}`,fieldId:p.id,subField:`merch__${se}__size__${Ne}`,fieldType:u.fieldType,merchOptions:z,merchItemIndex:se})}),u.subFields.includes("total_quantity")&&(X.push(`${T} - ${C} Total Qty`),he.push({type:"form",key:`${p.id}__merch__${se}__total_quantity`,fieldId:p.id,subField:`merch__${se}__total_quantity`,fieldType:u.fieldType,merchOptions:z,merchItemIndex:se})),u.subFields.includes("price")&&(X.push(`${T} - ${C} Price`),he.push({type:"form",key:`${p.id}__merch__${se}__price`,fieldId:p.id,subField:`merch__${se}__price`,fieldType:u.fieldType,merchOptions:z,merchItemIndex:se}))})}else if(u.fieldType==="tshirt_size"){const z=p.options||[];z.length>0?z.forEach((Y,se)=>{u.subFields.forEach(C=>{w.find(W=>W.key===C)&&C==="quantity"&&(X.push(`${T} - ${Y.label||Y.value}`),he.push({type:"form",key:`${p.id}__tshirt__${se}__${C}`,fieldId:p.id,subField:`tshirt__${se}__${Y.value}`,fieldType:u.fieldType}))})}):(X.push(T),he.push({type:"form",key:p.id,fieldId:p.id,fieldType:u.fieldType}))}else u.subFields.forEach(z=>{const Y=w.find(se=>se.key===z);Y&&(X.push(`${T} ${Y.label}`),he.push({type:"form",key:`${p.id}__${z}`,fieldId:p.id,subField:z,fieldType:u.fieldType}))})}else X.push(T),he.push({type:"form",key:p.id,fieldId:p.id})}),oe.forEach(p=>{const u=xe.find(T=>T.id===p);u&&(X.push(`${u.name} (Qty)`),he.push({type:"addon",key:`addon__${p}`,addOnId:p}))});const Le=[],ps=he.map((p,u)=>p.type==="form"||p.type==="addon"?u:-1).filter(p=>p>=0),Fe=ps.length>0,$s=p=>{const u=(p||"").trim();return!u||u==="$0.00"||u==="$0"||u==="0"},fs=p=>{if(p.family_member_id)return`fm:${p.family_member_id}`;const u=`${p.first_name??""} ${p.last_name??""}`.toLowerCase().replace(/[^a-z0-9]/g,""),T=String(p.email??p.rider_email??p.date_of_birth??"").toLowerCase().trim();return`n:${u}|${T}`},ze=new Map;for(const p of R||[]){const u=fs(p);ze.has(u)||ze.set(u,p)}if([...ze.values()].forEach(p=>{const u=[],T=Cs(p.id);he.forEach(w=>{var z,Y,se;if(w.type==="addon"&&w.addOnId){const C=Fs(p.id,w.addOnId);u.push(C>0?String(C):"")}else if(w.type==="standard"){let C=p[w.key];w.key==="created_at"||w.key==="checked_in_at"?C=C?ke(new Date(C),"yyyy-MM-dd HH:mm"):"":w.key==="checked_in"?C=C?"Yes":"No":typeof C=="number"?C=C.toString():C==null&&(C=""),u.push(String(C))}else if(w.type==="form"&&w.fieldId){const C=T[w.fieldId]??null;if(w.subField)if(w.fieldType==="date"||w.fieldType==="dob"){const I=C;if(I)try{const W=new Date(I);
1if(isNaN(W.getTime()))u.push("");else switch(w.subField){case"month":u.push(String(W.getMonth()+1));break;case"day":u.push(String(W.getDate()));break;case"year":u.push(String(W.getFullYear()));break;case"full":u.push(ke(W,"yyyy-MM-dd"));break;default:u.push("")}}catch{u.push("")}else u.push("")}else if(w.fieldType==="merchandise"){const I=es(C),W=((z=w.subField)==null?void 0:z.split("__"))||[];if(W.length>=3&&W[0]==="merch"){const ae=parseInt(W[1],10),Ne=(w.merchOptions||[])[ae];if(Ne&&Array.isArray(I)){const Ie=I.filter(je=>je.itemId===Ne.value);if(W[2]==="size"&&W.length===4){const je=W[3],ge=Ie.find(we=>we.size===je);u.push(ge?String(ge.quantity||1):"")}else if(W[2]==="total_quantity"){const je=Ie.reduce((ge,we)=>ge+(we.quantity||0),0);u.push(je>0?String(je):"")}else if(W[2]==="price"){const je=Ie.reduce((we,qs)=>we+(qs.quantity||0),0),ge=Ne.price||0;u.push(je>0?`$${(je*ge).toFixed(2)}`:"")}else u.push("")}else u.push("")}else u.push("")}else if(w.fieldType==="tshirt_size"){const I=((Y=w.subField)==null?void 0:Y.split("__"))||[];if(I.length===3&&I[0]==="tshirt"){const W=I[2],ae=es(C);if(ae&&typeof ae=="object")if(ae.size===W)u.push(String(ae.quantity||1));else if(Array.isArray(ae.sizes)){const ie=ae.sizes.find(Ne=>Ne.size===W);u.push(ie?String(ie.quantity||1):"")}else u.push("");else C===W?u.push("1"):u.push("")}else u.push(dt(C))}else if(w.fieldType==="season_registration"){const I=es(C),W=w.subField;if(I&&typeof I=="object")switch(W){case"type":u.push(I.registrationType==="season"?"Season Pass":I.registrationType==="multi_event"?"Select Events":I.registrationType||"");break;case"event_count":u.push(String(Array.isArray(I.selectedEvents)?I.selectedEvents.length:0));break;case"events":{const ae=Array.isArray(I.selectedEvents)?I.selectedEvents.map(ie=>typeof ie=="object"?ie.event_name||ie.name||"":String(ie)):[];u.push(ae.join(", "));break}case"divisions":u.push(String(I.classCount||0));break;case"classes":{const ae=Array.isArray(I.classes)?I.classes.filter(ie=>ie==null?void 0:ie.className).map(ie=>[ie.className,ie.bikeNumber?`#${ie.bikeNumber}`:"",ie.bikeMake].filter(Boolean).join(" | ")):[];u.push(ae.join("; "));break}default:u.push("")}else u.push("")}else{const I=es(C),W=((se=w.subField)==null?void 0:se.split("__"))||[];if(W.length===2){const ae=parseInt(W[0],10),ie=W[1];Array.isArray(I)&&I[ae]&&I[ae][ie]!==void 0?u.push(String(I[ae][ie])):u.push("")}else if(W.length===1){const ae=w.subField;I&&typeof I=="object"&&I[ae]!==void 0?u.push(String(I[ae])):u.push("")}else u.push("")}else u.push(dt(C))}}),!(v&&Fe&&!ps.some(z=>!$s(u[z])))&&Le.push(u)}),Le.length===0){be.error("No registrations matched the selected form-field values."),B(!1);return}const Pe=p=>p.includes(",")||p.includes('"')||p.includes(` 2`)?`"${p.replace(/"/g,'""')}"`:p,Es=[X.map(Pe).join(","),...Le.map(p=>p.map(Pe).join(","))].join(` 3`),Te=new Blob(["\uFEFF"+Es],{type:"text/csv;charset=utf-8;"}),xs=URL.createObjectURL(Te),ve=document.createElement("a");ve.href=xs,ve.download=`registrations-export-${ke(new Date,"yyyy-MM-dd")}.csv`,document.body.appendChild(ve),ve.click(),document.body.removeChild(ve),URL.revokeObjectURL(xs),n(!1)}catch(f){console.error("Export error:",f)}finally{B(!1)}}};return e.jsx(Ve,{open:x,onOpenChange:n,children:e.jsxs(We,{className:"max-w-2xl max-h-[90vh] bg-card border-border overflow-hidden p-0",children:[e.jsx(He,{className:"px-6 pt-6 pb-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(Ye,{className:"font-display",children:"Export Registrations"}),e.jsx(js,{children:"Select the fields you want to include in your export"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[V.length>0&&e.jsxs(At,{children:[e.jsx(Mt,{asChild:!0,children:e.jsxs(k,{variant:"outline",size:"sm",children:[e.jsx(an,{className:"h-4 w-4 mr-2"}),"Load Preset"]})}),e.jsx(zt,{align:"end",className:"w-56",children:V.map(c=>e.jsxs(Dt,{className:"flex items-center justify-between cursor-pointer",children:[e.jsx("span",{className:"flex-1 truncate",onClick:()=>ms(c),children:c.name}),e.jsx(k,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-2 hover:bg-destructive/10 hover:text-destructive",onClick:f=>{f.stopPropagation(),us(c.id)},children:e.jsx(yt,{className:"h-3 w-3"})})]},c.id))})]}),q?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qe,{placeholder:"Preset name...",value:$,onChange:c=>O(c.target.value),className:"h-8 w-40",onKeyDown:c=>{c.key==="Enter"&&ye(),c.key==="Escape"&&K(!1)},autoFocus:!0}),e.jsx(k,{size:"sm",onClick:ye,children:"Save"}),e.jsx(k,{size:"sm",variant:"ghost",onClick:()=>K(!1),children:"Cancel"})]}):e.jsxs(k,{variant:"outline",size:"sm",onClick:()=>K(!0),disabled:i.length===0&&Xe===0&&oe.length===0,children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Save Preset"]})]})]})}),e.jsx(gt,{className:"flex-1 max-h-[60vh] px-6",children:e.jsxs("div",{className:"space-y-6 pb-6",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-foreground mb-3",children:"Filter by Date"}),e.jsxs("div",{className:"flex flex-wrap gap-4",children:[e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(pe,{className:"text-sm text-muted-foreground",children:"Start Date"}),e.jsxs(Xs,{children:[e.jsx(et,{asChild:!0,children:e.jsxs(k,{variant:"outline",className:Ls("w-[180px] justify-start text-left font-normal",!M&&"text-muted-foreground"),children:[e.jsx(nt,{className:"mr-2 h-4 w-4"}),M?ke(M,"MMM d, yyyy"):"All dates"]})}),e.jsxs(st,{className:"w-auto p-0",align:"start",children:[e.jsx(tt,{mode:"single",selected:M,onSelect:g,initialFocus:!0}),M&&e.jsx("div",{className:"p-2 border-t",children:e.jsx(k,{variant:"ghost",size:"sm",className:"w-full",onClick:()=>g(void 0),children:"Clear"})})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(pe,{className:"text-sm text-muted-foreground",children:"End Date"}),e.jsxs(Xs,{children:[e.jsx(et,{asChild:!0,children:e.jsxs(k,{variant:"outline",className:Ls("w-[180px] justify-start text-left font-normal",!b&&"text-muted-foreground"),children:[e.jsx(nt,{className:"mr-2 h-4 w-4"}),b?ke(b,"MMM d, yyyy"):"All dates"]})}),e.jsxs(st,{className:"w-auto p-0",align:"start",children:[e.jsx(tt,{mode:"single",selected:b,onSelect:A,initialFocus:!0}),b&&e.jsx("div",{className:"p-2 border-t",children:e.jsx(k,{variant:"ghost",size:"sm",className:"w-full",onClick:()=>A(void 0),children:"Clear"})})]})]})]})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h4",{className:"font-semibold text-foreground",children:"Registration Fields"}),e.jsxs("div",{className:"flex gap-2 text-sm",children:[e.jsx(k,{variant:"ghost",size:"sm",onClick:os,children:"Select All"}),e.jsx(k,{variant:"ghost",size:"sm",onClick:ds,children:"Select None"})]})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:zs.map(c=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ae,{id:`std-${c.key}`,checked:i.includes(c.key),onCheckedChange:()=>Ce(c.key)}),e.jsx(pe,{htmlFor:`std-${c.key}`,className:"text-sm cursor-pointer",children:c.label})]},c.key))})]}),xe.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h4",{className:"font-semibold text-foreground",children:"Add-ons"}),e.jsxs("div",{className:"flex gap-2 text-sm",children:[e.jsx(k,{variant:"ghost",size:"sm",onClick:()=>U(xe.map(c=>c.id)),children:"Select All"}),e.jsx(k,{variant:"ghost",size:"sm",onClick:()=>U([]),children:"Select None"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Purchased quantities (camping, practice, pit passes) for the riders in this round."}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:xe.map(c=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ae,{id:`addon-${c.id}`,checked:oe.includes(c.id),onCheckedChange:()=>re(c.id)}
3),e.jsx(pe,{htmlFor:`addon-${c.id}`,className:"text-sm cursor-pointer",children:c.name})]},c.id))})]}),fe&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"This round uses the series signup form â its questions and add-ons are listed here and pulled from each rider's series order, scoped to this round's entries."}),ue.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h4",{className:"font-semibold text-foreground",children:"Form Fields"}),e.jsxs("div",{className:"flex gap-2 text-sm",children:[e.jsx(k,{variant:"ghost",size:"sm",onClick:cs,children:"Select All"}),e.jsx(k,{variant:"ghost",size:"sm",onClick:Ss,children:"Select None"})]})]}),e.jsxs("div",{className:"flex items-start space-x-2 mb-3 p-3 rounded-md border border-border bg-muted/30",children:[e.jsx(Ae,{id:"only-rows-with-data",checked:v,onCheckedChange:c=>L(!!c),className:"mt-0.5"}),e.jsxs(pe,{htmlFor:"only-rows-with-data",className:"text-sm cursor-pointer leading-snug",children:[e.jsx("span",{className:"font-medium",children:"Only include rows with data in selected form fields"}),e.jsx("span",{className:"block text-xs text-muted-foreground mt-0.5",children:"Hides registrations that didn't pick any of the merch, sizes, or items you selected below."})]})]}),e.jsx("div",{className:"space-y-2",children:ue.map(c=>{const f=l[c.id],R=(f==null?void 0:f.isExpandable)??!1,Q=is(c.id),ne=j.includes(c.id),G=$e[c.field_type]||[];return R?e.jsxs(bs,{open:ne,onOpenChange:()=>ls(c.id),children:[e.jsxs("div",{className:"flex items-center gap-2 py-1",children:[e.jsx(Ae,{id:`form-${c.id}`,checked:Q,onCheckedChange:()=>Je(c.id)}),e.jsx(vs,{asChild:!0,children:e.jsx(k,{variant:"ghost",size:"sm",className:"h-auto p-1 hover:bg-muted",children:ne?e.jsx(ts,{className:"h-4 w-4"}):e.jsx(Lt,{className:"h-4 w-4"})})}),e.jsxs(pe,{htmlFor:`form-${c.id}`,className:"text-sm cursor-pointer flex-1",children:[Ds(c.label),e.jsxs("span",{className:"text-muted-foreground ml-2 text-xs",children:["(",(f==null?void 0:f.subFields.length)||0,"/",G.length," fields)"]})]})]}),e.jsx(Ns,{children:e.jsx("div",{className:"ml-12 mt-1 mb-2 pl-3 border-l-2 border-muted space-y-1",children:G.map(ce=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ae,{id:`form-${c.id}-${ce.key}`,checked:Ze(c.id,ce.key),onCheckedChange:()=>rs(c.id,ce.key)}),e.jsx(pe,{htmlFor:`form-${c.id}-${ce.key}`,className:"text-sm cursor-pointer text-muted-foreground",children:ce.label})]},ce.key))})})]},c.id):e.jsxs("div",{className:"flex items-center space-x-2 py-1",children:[e.jsx(Ae,{id:`form-${c.id}`,checked:Q,onCheckedChange:()=>Je(c.id)}),e.jsx(pe,{htmlFor:`form-${c.id}`,className:"text-sm cursor-pointer",children:Ds(c.label)})]},c.id)})})]})]})}),e.jsxs(Is,{className:"border-t border-border p-4 bg-card",children:[e.jsx(k,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(k,{onClick:hs,disabled:r||i.length===0&&Xe===0&&oe.length===0,children:r?e.jsxs(e.Fragment,{children:[e.jsx(Me,{className:"mr-2 h-4 w-4 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ht,{className:"mr-2 h-4 w-4"}),"Export to CSV"]})})]})]})})}const Be=t=>`$${(t/100).toFixed(2)}`;function On({open:t,onOpenChange:x,registrationId:n,onCollected:i}){const{toast:h}=Os(),[l,m]=F.useState(!1),[j,_]=F.useState(!1),[r,B]=F.useState(null),[M,g]=F.useState(""),[b,A]=F.useState(!0),[v,L]=F.useState(!1),[$,O]=F.useState(null),[q,K]=F.useState(null);F.useEffect(()=>{!t||!n||(B(null),O(null),K(null),m(!0),S.functions.invoke("admin-collect-payment",{body:{action:"quote",registration_id:n}}).then(({data:V,error:H})=>{if(H||V!=null&&V.error)throw new Error((H==null?void 0:H.message)||(V==null?void 0:V.error));B(V.quote),K(V.last_link??null),g((V.quote.amountDueCents/100).toFixed(2)),V.last_link&&(A(!1),L(!1))}).catch(V=>h({title:"Could not price this registration",description:V.message,variant:"destructive"})).finally(()=>m(!1)))},[t,n,h]);const le=async()=>{var V;if(n){_(!0);try{const H=Math.round(parseFloat(M||"0")*100),{data:te,error:Z}=await S.functions.invoke("admin-collect-payment",{body:{action:"create_link",registration_id:n,amount_cents:H,send_email:b,send_sms:v}});if(Z||te!=null&&te.error)throw new Error((Z==null?void 0:Z.message)||(te==null?void 0:te.error));O(te.url),K(te.last_link??null);const me=[b&&!te.emailed?`Email failed: ${te.email_error||"unknown error"}`:null,v&&!te.texted?`Text failed: ${te.sms_error||"unknown error"}
3`:null].filter(Boolean),fe=[te.emailed?`Emailed to ${r==null?void 0:r.email}`:null,te.texted?`Texted to ${((V=te.last_link)==null?void 0:V.texted_to)||(r==null?void 0:r.phone)}`:null].filter(Boolean);me.length?h({title:"Link created, but sending failed",description:[...fe,...me].join(" · "),variant:"destructive"}):h({title:"Payment link ready",description:fe.join(" · ")||"Copy the link below to send it manually."}),i==null||i()}catch(H){h({title:"Could not create payment link",description:H.message,variant:"destructive"})}finally{_(!1)}}};return e.jsx(Ve,{open:t,onOpenChange:x,children:e.jsxs(We,{className:"max-w-lg",children:[e.jsxs(He,{children:[e.jsx(Ye,{children:"Take a payment"}),e.jsx(js,{children:"Prices are recalculated from the event's current pricing. The rider stays off the Timing Lab roster until the balance is paid."})]}),l&&e.jsx("div",{className:"flex items-center justify-center py-10 text-muted-foreground",children:e.jsx(Js,{className:"h-5 w-5 animate-spin"})}),r&&!l&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-md border p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:r.riderName}),e.jsxs("div",{className:"text-muted-foreground",children:[r.eventName," · ",r.confirmationNumber]})]}),q&&e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-warning/40 bg-warning/10 p-3 text-sm",children:[e.jsx(De,{className:"mt-0.5 h-4 w-4 shrink-0 text-warning"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:"A payment link was already sent"}),e.jsxs("div",{className:"text-muted-foreground",children:[new Date(q.created_at).toLocaleString()," ·"," ",[q.emailed?`emailed to ${q.emailed_to||r.email}`:null,q.texted?`texted to ${q.texted_to||r.phone}`:null].filter(Boolean).join(" · ")||"link created, not sent",q.expires_at&&e.jsxs(e.Fragment,{children:[" · ",new Date(q.expires_at)>new Date?`expires ${new Date(q.expires_at).toLocaleString()}`:"expired"]})]}),q.checkout_url&&e.jsxs(k,{size:"sm",variant:"outline",className:"mt-2",onClick:()=>{navigator.clipboard.writeText(q.checkout_url),h({title:"Previous link copied"})},children:[e.jsx(it,{className:"mr-1 h-3 w-3"})," Copy previous link"]})]})]}),e.jsxs("div",{className:"space-y-1 text-sm",children:[r.lineItems.length===0&&e.jsx("p",{className:"text-muted-foreground",children:"No priced items found on this registration's form answers."}),r.lineItems.map((V,H)=>e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:V.name}),e.jsx("span",{children:Be(V.amountCents)})]},H)),r.feesCents>0&&e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Service fees"}),e.jsx("span",{children:Be(r.feesCents)})]}),r.platformFeeCents>0&&e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Platform fee"}),e.jsx("span",{children:Be(r.platformFeeCents)})]}),e.jsxs("div",{className:"flex justify-between border-t pt-1 font-medium",children:[e.jsx("span",{children:"Total today"}),e.jsx("span",{children:Be(r.totalCents)})]}),r.alreadyPaidCents>0&&e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Already paid"}),e.jsxs("span",{children:["â",Be(r.alreadyPaidCents)]})]}),e.jsxs("div",{className:"flex justify-between text-base font-semibold",children:[e.jsx("span",{children:"Balance due"}),e.jsx("span",{children:Be(r.amountDueCents)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(pe,{htmlFor:"collect-amount",children:"Amount to charge"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ts,{className:"absolute left-2 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(Qe,{id:"collect-amount",className:"pl-7",value:M,onChange:V=>g(V.target.value),inputMode:"decimal"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ae,{id:"collect-email",checked:b,onCheckedChange:V=>A(!!V)}),e.jsxs(pe,{htmlFor:"collect-email",className:"font-normal",children:["Email the payment link to ",r.email]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ae,{id:"collect-sms",checked:v,disabled:!r.phone,onCheckedChange:V=>L(!!V)}),e.jsx(pe,{htmlFor:"collect-sms",className:"font-normal",children:r.phone?`Text the payment link to ${r.phone}`:"No phone number on this registration"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Payment links stay valid for 24 hours (Stripe's maximum)."}),$&&e.jsxs("div",{className:"space-y-2 rounded-md border bg-muted/40 p-3",children:[e.jsx("div",{className:"break-all text-xs",children:$}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(k,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText($),h({title:"Link copied"})},children:[e.jsx(it,{className:"mr-1 h-3 w-3"})," Copy link"]}),e.jsxs(k,{size:"sm",variant:"outline",onClick:()=>window.open($,"_blank"),children:[e.jsx(cn,{className:"mr-1 h-3 w-3"})," Open"]})]})]})]}),e.jsxs(Is,{children:[e.jsx(k,{variant:"outline",onClick:()=>x(!1),children:"Close"}),e.jsxs(k,{onClick:le,disabled:j||l||!r,children:[j&&e.jsx(Js,{className:"mr-2 h-4 w-4 animate-spin"}),$||q?"Create new link":"Create payment link"]})]})]})})}const Bn=t=>{if(t.length<=1)return t.join(", ");let x=t[0];for(let i=1;i<t.length;i++)for(;x.length>0&&!t[i].startsWith(x);)x=x.slice(0,-1);const n=x.lastIndexOf(" ");if(n>3&&x.length>5){x=x.slice(0,n+1);const i=t.map(h=>
3h.slice(x.length)).filter(Boolean);if(i.length===t.length)return`${x.trim()}: ${i.join(", ")}`}return t.join(", ")},Kn=t=>t.replace(/_/g," ").replace(/\s+/g," ").replace(/\b\w/g,x=>x.toUpperCase()).trim(),Un=(t,x)=>{if(!t)return"-";if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{const n=JSON.parse(t);if(typeof n=="object"&&n!==null&&!Array.isArray(n)){if("className"in n||"bikeNumber"in n||"bikeMake"in n){const l=[];return n.className&&l.push(n.className),n.bikeNumber&&l.push(`#${n.bikeNumber}`),n.bikeMake&&l.push(n.bikeMake),l.length>0?l.join(" | "):t}if("street"in n||"address"in n||"city"in n||"state"in n||"zip"in n||"country"in n){const l=[];(n.street||n.address)&&l.push(n.street||n.address),(n.street2||n.address2)&&l.push(n.street2||n.address2);const m=[];return n.city&&m.push(n.city),n.state&&m.push(n.state),(n.zip||n.zipCode||n.postalCode)&&m.push(n.zip||n.zipCode||n.postalCode),m.length>0&&l.push(m.join(", ")),n.country&&l.push(n.country),l.length>0?l.join(" ⢠"):t}if("label"in n||"size"in n||"quantity"in n||"variant"in n){const l=[];return n.label&&l.push(n.label),n.variant&&l.push(n.variant),n.size&&l.push(`Size: ${n.size}`),n.quantity&&n.quantity>1&&l.push(`Qty: ${n.quantity}`),n.color&&l.push(`Color: ${n.color}`),l.length>0?l.join(" ⢠"):t}if("registrationType"in n||"selectedEvents"in n||"classes"in n){if(n.summary){const j=Array.isArray(n.selectedEvents)?n.selectedEvents.map(_=>typeof _=="object"?_.event_name||_.name||"":String(_)).filter(Boolean):[];return j.length>0&&!j.some(_=>n.summary.includes(_))?`${n.summary} [${j.join(", ")}]`:n.summary}const l=[],m=n.registrationType==="season"?"Season Pass":n.registrationType==="multi_event"?"Select Events":n.registrationType==="season_pass"?"Season Pass":"Registration";if(Array.isArray(n.selectedEvents)){const j=n.selectedEvents.map(r=>typeof r=="object"?r.event_name||r.name||"":String(r)),_=Bn(j);l.push(`${m} - ${j.length} Race${j.length!==1?"s":""}`),l.push(`Events: ${_}`)}else l.push(m);return Array.isArray(n.classes)&&n.classes.forEach((j,_)=>{if(typeof j=="object"&&j.className){const r=[j.className];j.bikeNumber&&r.push(`#${j.bikeNumber}`),j.bikeMake&&r.push(j.bikeMake),l.push(`Division ${_+1}: ${r.join(" | ")}`)}}),l.join(` 4`)}const i=l=>l==null?"":Array.isArray(l)?l.map(i).join(", "):typeof l=="object"?Object.entries(l).filter(([j,_])=>_!=null&&_!=="").map(([j,_])=>`${j}: ${i(_)}`).join(", "):String(l),h=Object.entries(n).filter(([l,m])=>m!=null&&m!=="").map(([l,m])=>`${l}: ${i(m)}`);return h.length>0?h.join(", "):t}return Array.isArray(n)?n.length===0?"-":n.map(i=>
4{if(typeof i=="object"&&i!==null){if("label"in i||"itemId"in i||"size"in i||"quantity"in i){const h=[],l=i.label||(i.itemId?Kn(i.itemId):"");return l&&h.push(l),i.variant&&h.push(i.variant),i.size&&h.push(`Size: ${i.size}`),i.quantity&&i.quantity>1&&h.push(`Qty: ${i.quantity}`),i.color&&h.push(`Color: ${i.color}`),h.join(" ⢠")}if("className"in i||"bikeNumber"in i){const h=[];return i.className&&h.push(i.className),i.bikeNumber&&h.push(`#${i.bikeNumber}`),i.bikeMake&&h.push(i.bikeMake),h.join(" | ")}return JSON.stringify(i)}return String(i)}).join("; "):String(n)}catch{return t}return t.toLowerCase()==="true"?"Yes":t.toLowerCase()==="false"?"No":t},Qn=(t,x)=>(t||x||"Field").replace(/<[^>]*>/g,"").trim();function ct({eventId:t,eventIds:x}){const{toast:n}=Os(),i=Bs(),h=ks(),[l,m]=F.useState(""),[j,_]=F.useState("all"),[r,B]=F.useState(null),[M,g]=F.useState(null),[b,A]=F.useState(!1),[v,L]=F.useState(null),[$,O]=F.useState(null),[q,K]=F.useState(!1),[le,V]=F.useState(null),[H,te]=F.useState("100"),[Z,me]=F.useState("percentage"),[fe,xe]=F.useState(""),[oe,U]=F.useState("stripe"),[re,ue]=F.useState(null),[Ce,Je]=F.useState(null),[rs,is]=F.useState(null),[Ze,ls]=F.useState(null),[os,ds]=F.useState(!1),[cs,Ss]=F.useState(!1),[ye,ms]=F.useState([]),[us,Xe]=F.useState(!1),hs=async(s=!1)=>{s?Xe(!0):ds(!0);try{const{data:a,error:o}=await S.functions.invoke("list-registrations-missing-mirror",{body:{event_ids:ne,resync_all:s}});if(o)throw o;if(a!=null&&a.error)throw new Error(a.error);const d=(a==null?void 0:a.missing)??[];if(ms(d),Ss(!0),s){const y=(a==null?void 0:a.resynced)??0,N=(a==null?void 0:a.errors)??[];n({title:N.length?"Resync completed with warnings":"Resync complete",description:`${y} lab row(s) written${N.length?`, ${N.length} error(s)`:""}.`,variant:N.length?"destructive":void 0});const{data:E}=await S.functions.invoke("list-registrations-missing-mirror",{body:{event_ids:ne}});ms((E==null?void 0:E.missing)??[]),h.invalidateQueries({queryKey:["event-registrations"]})}else n({title:"Sync check complete",description:`${d.length} registration(s) missing from Timing Lab.`})}catch(a){n({title:"Sync check failed",description:(a==null?void 0:a.message)??"Unknown error",variant:"destructive"})}finally{ds(!1),Xe(!1)}},c=async s=>{ls(s);try{const{data:a,error:o}=await S.functions.invoke("resync-registration",{body:{registration_id:s}});if(o)throw o;if(a!=null&&a.error)throw new Error(a.error);const d=(a==null?void 0:a.fanout_created)??0,y=(a==null?void 0:a.mirrored)??0,N=(a==null?void 0:a.errors)??[];N.length>0?n({title:"Resync completed with warnings",description:N.slice(0,2).join("; "),variant:"destructive"}):n(d===0&&y===0?{title:"Already in sync",description:"No changes were needed."}:{title:"Resynced to Timing Lab",description:`${d} round(s) added, ${y} lab row(s) written.`}),h.invalidateQueries({queryKey:["event-registrations"]})}catch(a){console.error("resync-registration failed",a),n({title:"Resync failed",description:(a==null?void 0:a.message)??"Unknown error",variant:"destructive"})}finally{ls(null)}},[f,R]=F.useState({}),Q=Array.isArray(x),ne=Q?x??[]:t?[t]:[],G=ne.slice().sort().join(","),ce=t??ne[0]??"",{data:ee=[],isLoading:Cs}=J({queryKey:["event-registrations",G],queryFn:async()=>{if(ne.length===0)return[];const s=1e3,a=[];for(let o=0;;o+=s){const{data:d,error:y}=await S.from("registrations").select("*").in("event_id",ne).order("created_at",{ascending:!1}).order("id",{ascending:!0}).range(o,o+s-1);if(y)throw y;const N=d||[];if(a.push(...N),N.length<s)break}return a},enabled:ne.length>0}),{data:_e}=J({queryKey:["event-signup-meta",ce],queryFn:async()=>{const{data:s,error:a}=await S.from("events").select("id, name, mysql_event_name, mysql_series_name, organization_id").eq("id",ce).maybeSingle();if(a)throw a;return s},enabled:!!ce}),{data:Fs}=Yt((_e==null?void 0:_e.organization_id)||null),X=ee.map(s=>s.id),{data:he={}}=J({queryKey:["event-signup-responses",G,X.length],queryFn:async()=>{if(X.length===0)return{};const s={},a=200;for(let o=0;o<X.length;o+=a){const d=X.slice(o,o+a),{data:y,error:N}=await S.from("form_responses").select("registration_id, field_value, form_fields!inner(field_type)").in("registration_id",d).eq("form_fields.field_type","season_registration");if(N)throw N;for(const E of y||[])E.registration_id&&E.field_value&&!s[E.registration_id]&&(s[E.registration_id]=E.field_value)}return s},enabled:X.length>0}),{data:Le={}}=J({queryKey:["event-signup-child-counts",G,X.length],queryFn:async()=>
4{if(X.length===0)return{};const s={},a=200;for(let o=0;o<X.length;o+=a){const d=X.slice(o,o+a),{data:y,error:N}=await S.from("registrations").select("parent_registration_id").in("parent_registration_id",d);if(N)throw N;for(const E of y||[]){const P=E.parent_registration_id;P&&(s[P]=(s[P]||0)+1)}}return s},enabled:X.length>0}),{data:ps={}}=J({queryKey:["registration-payment-links",G,X.length],queryFn:async()=>{const s={};if(X.length===0)return s;const a=200;for(let o=0;o<X.length;o+=a){const d=X.slice(o,o+a),{data:y,error:N}=await S.from("registration_payment_links").select("registration_id, created_at, emailed, texted, expires_at").in("registration_id",d).order("created_at",{ascending:!1});if(N)throw N;for(const E of y||[])s[E.registration_id]||(s[E.registration_id]={created_at:E.created_at,emailed:!!E.emailed,texted:!!E.texted,expires_at:E.expires_at})}return s},enabled:X.length>0}),Fe=Array.from(new Set(ee.filter(s=>s.is_child_registration&&s.parent_registration_id).map(s=>s.parent_registration_id))),$s=Fe.sort().join(","),{data:fs={}}=J({queryKey:["event-child-parent-info",$s],queryFn:async()=>{const s={};if(Fe.length===0)return s;const a=200;for(let d=0;d<Fe.length;d+=a){const y=Fe.slice(d,d+a),{data:N,error:E}=await S.from("registrations").select("id, total_amount, subtotal, platform_fee, fees_total, stripe_payment_intent_id").in("id",y);if(E)throw E;for(const P of N||[]){const de=P.id;s[de]={total_amount:Number(P.total_amount||0),child_count:0,round_count:0,subtotal:Number(P.subtotal||0),platform_fee:Number(P.platform_fee||0),fees_total:Number(P.fees_total||0),stripe_payment_intent_id:P.stripe_payment_intent_id??null}}}const o={};for(let d=0;d<Fe.length;d+=a){const y=Fe.slice(d,d+a),{data:N,error:E}=await S.from("registrations").select("parent_registration_id, event_id").in("parent_registration_id",y);if(E)throw E;for(const P of N||[]){const de=P.parent_registration_id;de&&(s[de]||(s[de]={total_amount:0,child_count:0,round_count:0,subtotal:0,platform_fee:0,fees_total:0,stripe_payment_intent_id:null}),s[de].child_count+=1,(o[de]||(o[de]=new Set)).add(String(P.event_id||"")))}}for(const[d,y]of Object.entries(o))s[d]&&(s[d].round_count=y.size);return s},enabled:Fe.length>0}),ze=Array.from(new Set([...ee.map(s=>s.stripe_payment_intent_id),...Object.values(fs).map(s=>s.stripe_payment_intent_id)].filter(Boolean))),Hs=[...ze].sort().join(","),{data:Pe}=J({queryKey:["event-reg-stripe-actuals",Hs],queryFn:()=>Wt(ze),enabled:ze.length>0,staleTime:5*60*1e3}),Es=s=>(s.stripe_payment_intent_id?Pe==null?void 0:Pe.get(s.stripe_payment_intent_id):null)??null,Te=s=>Vt(s,Fs||null,Es(s)),xs=new Set(ee.map(s=>s.id)),ve=Array.from(new Set(ee.map(s=>s.parent_registration_id).filter(s=>!!s&&!xs.has(s)))),{data:p=[]}=J({queryKey:["event-rollup-parents",G,ve.sort().join(",")],queryFn:async()=>{if(!Q||ve.length===0)return[];const s=[],a=200;for(let o=0;o<ve.length;o+=a){const d=ve.slice(o,o+a),{data:y,error:N}=await S.from("registrations").select("*").in("id",d);if(N)throw N;s.push(...y||[])}return s},enabled:Q&&ve.length>0}),u=Array.from(new Set([...ee.map(s=>s.event_id),...p.map(s=>s.event_id)].filter(Boolean))),{data:T={}}=J({queryKey:["event-rollup-event-names",u.sort().join(",")],queryFn:async()=>{if(u.length===0)return{};const s={},{data:a,error:o}=await S.from("events").select("id, name, event_date").in("id",u);if(o)throw o;for(const d of a||[])s[d.id]={name:d.name,event_date:d.event_date};return s},enabled:u.length>0}),w=r!=null&&r.is_child_registration&&(r!=null&&r.parent_registration_id)?r.parent_registration_id:r==null?void 0:r.id,{data:z}=J({queryKey:["registration-parent",r==null?void 0:r.parent_registration_id],queryFn:async()=>{if(!(r!=null&&r.is_child_registration)||!(r!=null&&r.parent_registration_id))return null;const{data:s,error:a}=await S.from("registrations").select("id, confirmation_number, medical_conditions, allergies, ama_number, waiver_signed, waiver_signed_at, waiver_signature_name, subtotal, add_ons_total, fees_total, total_amount, platform_fee, stripe_payment_intent_id, created_at").eq("id",r.parent_registration_id).maybeSingle();if(a)throw a;return s},enabled:!!(r!=null&&r.is_child_registration&&(r!=null&&r.parent_registration_id))}),{data:Y=[]}=J({queryKey:["registration-addons",w],queryFn:async()=>
4{if(!w)return[];const{data:s,error:a}=await S.from("registration_add_ons").select(` 5 id, 6 quantity, 7 price_at_purchase, 8 received_count, 9 add_ons:add_on_id (name) 10 `).eq("registration_id",w);if(a)throw a;return s},enabled:!!w}),{data:se=[]}=J({queryKey:["registration-form-responses",w],queryFn:async()=>{if(!w)return[];const{data:s,error:a}=await S.from("form_responses").select(` 11 id, 12 field_value, 13 form_fields:field_id (label, export_label, field_type, field_order) 14 `).eq("registration_id",w);if(a)throw a;return(s||[]).sort((d,y)=>{var N,E;return(((N=d.form_fields)==null?void 0:N.field_order)||0)-(((E=y.form_fields)==null?void 0:E.field_order)||0)})},enabled:!!w}),C=r?r.is_child_registration&&z?{...r,medical_conditions:r.medical_conditions??z.medical_conditions,allergies:r.allergies??z.allergies,ama_number:r.ama_number??z.ama_number,waiver_signed:r.waiver_signed||z.waiver_signed,waiver_signed_at:r.waiver_signed_at??z.waiver_signed_at,waiver_signature_name:r.waiver_signature_name??z.waiver_signature_name,subtotal:Number(r.subtotal||0)||Number(z.subtotal||0),add_ons_total:Number(r.add_ons_total||0)||Number(z.add_ons_total||0),fees_total:Number(r.fees_total||0)||Number(z.fees_total||0),total_amount:Number(r.total_amount||0)||Number(z.total_amount||0),platform_fee:Number(r.platform_fee||0)||Number(z.platform_fee||0),stripe_payment_intent_id:r.stripe_payment_intent_id??z.stripe_payment_intent_id}:r:null,I=_s({mutationFn:async({id:s,checked_in:a})=>{const{error:o}=await S.from("registrations").update({checked_in:a,checked_in_at:a?new Date().toISOString():null}).eq("id",s);if(o)throw o},onSuccess:()=>{h.invalidateQueries({queryKey:["event-registrations",G]}),n({title:"Check-in status updated"})}}),W=s=>{V(s),te("100"),me("percentage"),xe(""),U("stripe"),K(!0)},ae=async()=>{var s,a;if(le){if(Z==="percentage"){const o=parseInt(H);if(isNaN(o)||o<1||o>100){n({title:"Invalid percentage",description:"Enter a value between 1 and 100",variant:"destructive"});return}}else{const o=parseFloat(fe);if(isNaN(o)||o<=0){n({title:"Invalid amount",description:"Enter a dollar amount greater than 0",variant:"destructive"});return}}L(le),K(!1);try{const{data:{session:o}}=await S.auth.getSession();if(!o){n({title:"Error",description:"Not authenticated",variant:"destructive"});return}const d=parseInt(H),y=parseFloat(fe),N={registration_id:le,destination:oe};Z==="percentage"?(N.refund_type=d===100?"full":"percentage",d<100&&(N.percentage=d)):(N.refund_type="amount",N.amount=y);const E=await S.functions.invoke("process-refund",{body:N});if(E.error)throw E.error;const P=ee.find(Rt=>Rt.id===le),de=parseFloat((s=E.data)==null?void 0:s.refund_amount),Re=isNaN(de)?Z==="percentage"?((P==null?void 0:P.total_amount)||0)*(parseInt(H)/100):parseFloat(fe):de,Ms=parseFloat((a=E.data)==null?void 0:a.withheld_fees);h.invalidateQueries({queryKey:["event-registrations",G]}),n({title:oe==="wallet"?`$${Re.toFixed(2)} added as account credit`:`$${Re.toFixed(2)} refund processed`,description:oe==="wallet"?"No money left Stripe â the credit is on their account balance":!isNaN(Ms)&&Ms>0?`$${Ms.toFixed(2)} in processing/platform fees withheld`:void 0}),le&&Ie(le,"refund",Re)}catch(o){n({title:"Refund failed",description:o.message||"Unable to process refund",variant:"destructive"})}finally{L(null),V(null)}}},ie=async s=>{O(s);try{const{error:a}=await S.from("registrations").update({status:"cancelled",payment_status:"cancelled"}).eq("id",s);if(a)throw a;try{await S.functions.invoke("remove-registration-from-timing-lab",{body:{registration_id:s}})}catch(o){console.error("remove-registration-from-timing-lab (cancel) failed",o)}h.invalidateQueries({queryKey:["event-registrations",G]}),n({title:"Registration cancelled"})}catch(a){n({title:"Cancel failed",description:a.message,variant:"destructive"})}finally{O(null)}},Ne=async s=>{Je(s.id);try{try{await S.functions.invoke("remove-registration-from-timing-lab",{body:{registration_id:s.id}})}catch(o){console.error("remove-registration-from-timing-lab (delete) failed",o)}await S.from("form_responses").delete().eq("registration_id",s.id),await S.from("registration_add_ons").delete().eq("registration_id",s.id);const{error:a}=await S.from("registrations").delete().eq("id",s.id);if(a)throw a;h.invalidateQueries({queryKey:["event-registrations",G]}),n({title:"Registration deleted"})}catch(a){n({title:"Delete failed",description:a.message,variant:"destructive"})}finally{Je(null),ue(null)}},Ie=async(s,a="confirmation",o)=>{is(s);try{const d={registration_id:s,email_type:a};a==="refund"&&o&&(d.refund_amount=o);const{error:y}=await S.functions.invoke("send-confirmation-email",{body:d});if(y)throw y;n({title:a==="refund"?"Refund email sent":a==="updated"?"Updated confirmation sent":"Confirmation email resent"})}catch(d){n({title:"Failed to send email",description:d.message||"Unknown error",variant:"destructive"})}finally{is(null)}},je=(s,a)=>a==="refunded"?e.jsx(D,{variant:"outline",className:"border-destructive text-destructive",children:"Refunded"}):a==="partially_refunded"?e.jsx(D,{variant:"outline",className:"border-accent text-accent-foreground",children:"Partial Refund"}):(a==="paid"||a==="completed")&&s==="confirmed"?e.jsx(D,{className:"bg-success text-success-foreground",children:"Confirmed"}):s==="cancelled"?e.jsx(D,{variant:"destructive",children:"Cancelled"}):s==="abandoned"?e.jsx(D,{variant:"outline",className:"border-muted-foreground text-muted-foreground",children:"Abandoned"}):e.jsx(D,{variant:"secondary",children:"Pending"}),ge=(s,a,o)=>{const d=a.toLowerCase(),y=!d||s.confirmation_number.toLowerCase().includes(d)||s.first_name.toLowerCase().includes(d)||s.last_name.toLowerCase().includes(d)||s.email.toLowerCase().includes(d),N=o==="all"||s.status===o;return y&&N},we=Q?[]:Array.from(new Set(ee.filter(s=>s.is_child_registration&&s.parent_registration_id).map(s=>s.parent_registration_id).filter(s=>!ee.some(a=>a.id===s)))),qs=we.slice().sort().join(","),{data:Ct=[]}=J({queryKey:["event-registrations-nonrollup-parents",G,qs],queryFn:async()=>
14{if(we.length===0)return[];const s=[],a=200;for(let o=0;o<we.length;o+=a){const d=we.slice(o,o+a),{data:y,error:N}=await S.from("registrations").select("*").in("id",d);if(N)throw N;s.push(...y||[])}return s},enabled:!Q&&we.length>0}),Ft=new Set,Rs=(()=>{if(Q)return ee;const s=new Map;for(const d of ee)s.set(d.id,d);for(const d of Ct)s.set(d.id,d);const a=new Set,o=[];for(const d of ee){const y=d.is_child_registration&&d.parent_registration_id?d.parent_registration_id:d.id;a.has(y)||(a.add(y),y!==d.id&&Ft.add(y),o.push(s.get(y)||d))}return o})(),gs=Rs.filter(s=>ge(s,l,j)),As=(()=>{if(!Q)return[];const s=new Map,a=new Map;for(const d of p)a.set(d.id,d);for(const d of ee)a.set(d.id,d);for(const d of ee){const y=d.parent_registration_id||d.id;let N=s.get(y);if(!N){const E=a.get(y)||d;N={key:y,parent:E,children:[]},s.set(y,N)}N.children.push(d)}const o=Array.from(s.values());for(const d of o)d.children.sort((y,N)=>{var de,Re;const E=((de=T[y.event_id])==null?void 0:de.event_date)||"",P=((Re=T[N.event_id])==null?void 0:Re.event_date)||"";return E&&P&&E!==P?E<P?-1:1:(y.created_at||"")<(N.created_at||"")?-1:1});return o.sort((d,y)=>d.parent.created_at<y.parent.created_at?1:-1),o})(),ys=As.filter(s=>{if(ge(s.parent,l,"all")&&j==="all")return ge(s.parent,l,"all")||s.children.some(d=>ge(d,l,"all"));const a=ge(s.parent,l,"all")||s.children.some(d=>ge(d,l,"all")),o=j==="all"||s.children.some(d=>d.status===j)||s.parent.status===j;return a&&o}),$t=s=>{const a=s.children;return a.every(o=>o.payment_status==="refunded")?e.jsx(D,{variant:"outline",className:"border-destructive text-destructive",children:"Refunded"}):a.some(o=>o.payment_status==="partially_refunded"||o.payment_status==="refunded")&&!a.every(o=>o.payment_status==="refunded")?e.jsx(D,{variant:"outline",className:"border-accent text-accent-foreground",children:"Partial Refund"}):a.every(o=>(o.payment_status==="paid"||o.payment_status==="completed")&&o.status==="confirmed")?e.jsx(D,{className:"bg-success text-success-foreground",children:"Confirmed"}):a.every(o=>o.status==="cancelled")?e.jsx(D,{variant:"destructive",children:"Cancelled"}):a.some(o=>o.status==="cancelled")?e.jsx(D,{variant:"outline",className:"border-destructive text-destructive",children:"Partial Cancel"}):e.jsx(D,{variant:"secondary",children:"Pending"})},Ys=()=>se.filter(s=>{var N,E;const a=(N=s.field_value)==null?void 0:N.trim(),o=a&&a!==""&&a!=="[]",d=(E=s.form_fields)==null?void 0:E.field_type;return o&&(d!=="waiver"&&d!=="add_ons"&&d!=="heading"&&d!=="paragraph"&&d!=="divider"&&d!=="image"&&d!=="spacer"&&d!=="signature"&&d!=="page_break"&&d!=="line_break"&&d!=="share_and_thank")}),Gs=s=>e.jsxs("div",{className:"flex items-start gap-1.5 shrink-0 self-start",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-1.5 md:w-[210px]",children:[e.jsxs(k,{variant:"outline",size:"sm",className:"w-full px-2","data-guide":"registrations-view",onClick:()=>B(s),children:[e.jsx(pn,{className:"mr-1.5 h-4 w-4"})," View"]}),e.jsxs(k,{variant:"outline",size:"sm",className:"w-full px-2","data-guide":"registrations-edit",onClick:()=>i(`/admin/registrations/${s.is_child_registration&&s.parent_registration_id?s.parent_registration_id:s.id}/edit`),children:[e.jsx(lt,{className:"mr-1.5 h-4 w-4"})," Edit"]}),(s.payment_status==="paid"||s.payment_status==="completed")&&e.jsx(k,{variant:s.checked_in?"outline":"default",size:"sm","data-guide":"registrations-check-in",onClick:()=>I.mutate({id:s.id,checked_in:!s.checked_in}),className:`w-full px-2${s.checked_in?"":" bg-success hover:bg-success/90"}`,children:s.checked_in?e.jsxs(e.Fragment,{children:[e.jsx(fn,{className:"mr-1.5 h-4 w-4"})," Undo"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ws,{className:"mr-1.5 h-4 w-4"})," Check In"]})}),s.status!=="cancelled"&&e.jsxs(k,{variant:"outline",size:"sm",className:"w-full px-2","data-guide":"registrations-refund",onClick:()=>W(s.id),disabled:v===s.id||s.payment_status==="refunded",children:[e.jsx(Ts,{className:"mr-1.5 h-4 w-4"}),s.payment_status==="refunded"?"Refunded":"Refund"]}),s.status!=="cancelled"&&!["paid","completed","refunded","partially_refunded"].includes(s.payment_status)&&(()=>{const a=ps[s.id],o=a?[a.emailed?"email":null,a.texted?"text":null].filter(
14Boolean).join(" + "):"";return e.jsx(k,{variant:a?"outline":"default",size:"sm",className:`w-full px-2${a?" border-warning text-warning hover:bg-warning/10":""}`,"data-guide":"registrations-take-payment",onClick:()=>g(s.id),title:a?`Payment link sent ${o?`by ${o} `:""}on ${new Date(a.created_at).toLocaleString()} â click to review or resend`:"Recalculate this registration at current prices and send a payment link",children:a?e.jsxs(e.Fragment,{children:[e.jsx(as,{className:"mr-1.5 h-4 w-4"})," Link Sent"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ts,{className:"mr-1.5 h-4 w-4"})," Take Payment"]})})})(),(s.payment_status==="paid"||s.payment_status==="completed"||s.payment_status==="refunded"||s.payment_status==="partially_refunded")&&e.jsxs(k,{variant:"outline",size:"sm",className:"w-full px-2","data-guide":"registrations-resend",onClick:()=>Ie(s.id,s.payment_status==="refunded"?"refund":"confirmation"),disabled:rs===s.id,children:[e.jsx(as,{className:"mr-1.5 h-4 w-4"}),rs===s.id?"Sending...":"Resend"]}),(s.payment_status==="paid"||s.payment_status==="completed")&&e.jsxs(k,{variant:"outline",size:"sm",className:"w-full px-2","data-guide":"registrations-resync",onClick:()=>c(s.id),disabled:Ze===s.id,title:"Re-run the season-pass fan-out and Timing Lab mirror for this registration. Idempotent.",children:[e.jsx(ws,{className:`mr-1.5 h-4 w-4 ${Ze===s.id?"animate-spin":""}`}),Ze===s.id?"Resyncingâ¦":"Resync"]}),s.status==="cancelled"&&e.jsxs("div",{className:"col-span-2 flex items-center justify-between gap-2",children:[e.jsx(D,{variant:"destructive",children:"Cancelled"}),e.jsxs(k,{variant:"outline",size:"sm",className:"flex-1 px-2 text-destructive border-destructive hover:bg-destructive/10",onClick:()=>ue(s),disabled:Ce===s.id,children:[e.jsx(yt,{className:"mr-1.5 h-4 w-4"})," Delete"]})]})]}),s.status!=="cancelled"&&e.jsxs(k,{variant:"destructive",size:"sm",className:"w-[96px] px-2","data-guide":"registrations-cancel",onClick:()=>ie(s.id),disabled:$===s.id,children:[e.jsx(ss,{className:"mr-1 h-4 w-4"})," Cancel"]})]}),Et=s=>{const a=at(s,he[s.id],_e||null,Le[s.id]||0);return e.jsx("div",{className:"p-4 border border-border rounded-lg bg-background",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:[e.jsx("span",{className:"font-mono text-sm text-primary",children:s.confirmation_number}),je(s.status,s.payment_status),s.checked_in&&e.jsx(D,{variant:"outline",className:"border-success text-success",children:"Checked In"}
14),s.source==="kiosk"?e.jsx(D,{variant:"outline",className:"border-amber-500 text-amber-700",children:"Kiosk"}):e.jsx(D,{variant:"outline",className:"border-blue-500 text-blue-700",children:"Online"})]}),e.jsxs("h3",{className:"font-display text-foreground",children:[s.first_name," ",s.last_name]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs mt-1",children:[e.jsx(D,{variant:"outline",className:rt(a.variant),children:a.badge}),e.jsx("span",{className:"text-foreground",children:a.text}),e.jsxs("span",{className:"text-muted-foreground",title:"When this signup happened, shown in your device's time zone",children:["Signed up ",s.created_at?ke(new Date(s.created_at),"MMM d, yyyy h:mm a"):"â"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-4 text-sm text-muted-foreground mt-1",children:[e.jsx("span",{children:s.email}),(()=>{if(s.is_child_registration&&s.parent_registration_id){const o=fs[s.parent_registration_id];if(o&&o.child_count>1)return e.jsx("span",{className:"italic",children:"Season Pass â see series registration"});const d=Te(o?{...s,total_amount:o.total_amount,subtotal:o.subtotal,platform_fee:o.platform_fee,fees_total:o.fees_total,stripe_payment_intent_id:o.stripe_payment_intent_id}:s);return e.jsxs("span",{title:"Net to your org",children:["$",d.net.toFixed(2)," ",e.jsx("span",{className:"text-xs",children:"net"})]})}return e.jsxs("span",{title:"Net to your org after BeyondPro & Stripe fees",children:["$",Te(s).net.toFixed(2)," ",e.jsx("span",{className:"text-xs",children:"net"})]})})()]}),(s.phone||s.bike_make||s.bike_model||s.ama_number||s.waiver_signed!==void 0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-0.5 text-xs text-muted-foreground mt-0.5",children:[s.phone&&e.jsx("span",{title:"Rider phone",children:s.phone}),(s.bike_make||s.bike_model)&&e.jsx("span",{title:"Bike",children:[s.bike_make,s.bike_model,s.bike_cc?`${s.bike_cc}cc`:null].filter(o=>o&&!/^unknown$/i.test(o)).join(" ")}),s.ama_number&&e.jsxs("span",{title:"AMA membership number",children:["AMA #",s.ama_
14number]}),s.waiver_signed?e.jsx("span",{className:"text-success",children:"Waiver signed"}):e.jsx("span",{className:"text-warning",children:"Waiver missing"})]})]}),Gs(s)]})},s.id)},qt=s=>{var o;const a=s.children.filter(d=>d.id!==s.parent.id);if(a.length>0){const d=new Set,y=[];for(const N of a)d.has(N.event_id)||(d.add(N.event_id),y.push(N));return y.map(N=>{var E;return{name:((E=T[N.event_id])==null?void 0:E.name)||"Round",reg:N,key:N.id,showConfirmation:!0}})}try{const d=he[s.parent.id];if(d){const y=JSON.parse(d),E=(Array.isArray(y==null?void 0:y.selectedEvents)?y.selectedEvents:[]).map(P=>typeof P=="object"?(P==null?void 0:P.event_name)||(P==null?void 0:P.name)||"":String(P||"")).filter(Boolean);if(E.length>0)return E.map((P,de)=>({name:P,reg:s.parent,key:`${s.parent.id}-${de}-${P}`,showConfirmation:!1}))}}catch{}return[{name:((o=T[s.parent.event_id])==null?void 0:o.name)||"Registration",reg:s.parent,key:s.parent.id,showConfirmation:!0}]};return Cs?e.jsx(qe,{className:"bg-card border-border",children:e.jsx(ns,{className:"py-8 text-center text-muted-foreground",children:"Loading registrations..."})}):e.jsxs(qe,{className:"bg-card border-border","data-tour":"registrations-container",children:[e.jsxs(Ks,{children:[e.jsx(Us,{children:"Registrations"}),e.jsx(pt,{children:Q?`${As.length} rider${As.length!==1?"s":""} across ${ee.length} round entr${ee.length===1?"y":"ies"}`:`${Rs.length} registration${Rs.length!==1?"s":""} for this event`})]}),e.jsxs(ns,{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-md border border-border bg-muted/40 p-3 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(ws,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:"Timing Lab sync check"}),cs&&e.jsx(D,{variant:ye.length===0?"secondary":"destructive",children:ye.length===0?"All in sync":`${ye.length} missing`}),e.jsxs("div",{className:"ml-auto flex gap-2",children:[e.jsx(k,{size:"sm",variant:"outline",onClick:()=>hs(!1),disabled:os||ne.length===0,children:os?"Checkingâ¦":"Check now"}),ye.length>0&&e.jsx(k,{size:"sm",onClick:()=>hs(!0),disabled:us,children:us?"Resyncingâ¦":`Resync ${ye.length} missing`})]})]}),cs&&ye.length>0&&e.jsxs("div",{className:"text-xs text-muted-foreground max-h-32 overflow-y-auto",children:[ye.slice(0,20).map(s=>e.jsxs("div",{className:"flex justify-between py-0.5",children:[e.jsxs("span",{children:[s.first_name," ",s.last_name," ",e.jsxs("span",{className:"opacity-60",children:["· BP#",s.bp_number]})]}),e.jsx("span",{className:"opacity-60",children:s.event_name})]},s.registration_id)),ye.length>20&&e.jsxs("div",{className:"opacity-60 pt-1",children:["â¦and ",ye.length-20," more"]})]})]}),e.jsxs("div",{className:"flex flex-col md:flex-row gap-4","data-tour":"registrations-search-filter",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Qs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Qe,{"data-guide":"registrations-search",placeholder:"Search by name, email, or confirmation #",value:l,onChange:s=>m(s.target.value),className:"pl-10"})]}),e.jsxs(Pt,{value:j,onValueChange:_,children:[e.jsx(Tt,{className:"w-[180px]","data-guide":"registrations-status-filter",children:e.jsx(It,{placeholder:"Filter by status"})}),e.jsxs(Ot,{children:[e.jsx(Oe,{value:"all",children:"All Status"}),e.jsx(Oe,{value:"confirmed",children:"Confirmed"}),e.jsx(Oe,{value:"pending",children:"Pending"}),e.jsx(Oe,{value:"cancelled",children:"Cancelled"}),e.jsx(Oe,{value:"abandoned",children:"Abandoned"}),e.jsx(Oe,{value:"refunded",children:"Refunded"})]})]}),e.jsxs(k,{variant:"outline",onClick:()=>A(!0),"data-tour":"registrations-export","data-guide":"registrations-export",children:[e.jsx(ht,{className:"mr-2 h-4 w-4"}),"Export"]})]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Q?`${ys.length} rider${ys.length!==1?"s":""} found`:`${gs.length} registration${gs.length!==1?"s":""} found`}),Q?ys.length===0?e.jsx("div",{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No registrations foun
14d"})}):e.jsx("div",{className:"space-y-3",children:ys.map(s=>{f[s.key];const a=qt(s),d=[s.parent,...s.children].filter((E,P,de)=>de.findIndex(Re=>Re.id===E.id)===P).reduce((E,P)=>E+Te(P).net,0),y=at(s.parent,he[s.parent.id],_e||null,Le[s.parent.id]||a.length),N=a.length<=1;return e.jsx("div",{className:"p-4 border border-border rounded-lg bg-background",children:e.jsxs("div",{className:"flex flex-col md:flex-row md:items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-mono text-sm text-primary",children:s.parent.confirmation_number}),$t(s),e.jsxs(D,{variant:"outline",className:"border-muted-foreground text-muted-foreground",children:[a.length," round",a.length!==1?"s":""]})]}),e.jsxs("h3",{className:"font-display text-foreground",children:[s.parent.first_name," ",s.parent.last_name]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs mt-1",children:[e.jsx(D,{variant:"outline",className:rt(y.variant),children:y.badge}),e.jsx("span",{className:"text-foreground",children:y.text}),e.jsxs("span",{className:"text-muted-foreground",title:"When this signup happened, shown in your device's time zone",children:["Signed up ",s.parent.created_at?ke(new Date(s.parent.created_at),"MMM d, yyyy h:mm a"):"â"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-4 text-sm text-muted-foreground mt-1",children:[e.jsx("span",{children:s.parent.email}),e.jsxs("span",{children:["$",d.toFixed(2)]})]})]}),Gs(N?a[0].reg:s.parent)]})},s.key)})}):gs.length===0?e.jsx("div",{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No registrations found"})}):e.jsx("div",{className:"space-y-3",children:gs.map(s=>Et(s))})]}),e.jsx(Ve,{open:!!r,onOpenChange:()=>B(null),children:e.jsxs(We,{className:"max-w-2xl h-[90vh] bg-card border-border overflow-hidden p-0",children:[e.jsxs(He,{className:"px-6 pt-6 pb-2",children:[e.jsx(Ye,{className:"font-display",children:"Registration Details"}),e.jsx(js,{children:"Complete registration information"})]}),r&&e.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[e.jsx(gt,{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:r.confirmation_number}),e.jsxs("div",{className:"flex gap-2",children:[je(r.status,r.payment_status),r.checked_in&&e.jsx(D,{variant:"outline",className:"border-success text-success",children:"Checked In"})]})]}),r.is_child_registration&&r.parent_registration_id&&e.jsxs("div",{className:"p-3 rounded-md bg-muted/60 border border-border text-sm",children:[e.jsx("div",{className:"font-medium text-foreground",children:"Round-level entry"}),e.jsxs("div",{className:"text-muted-foreground mt-1",children:["This row represents the rider's entry into this specific round. Form responses, add-ons, medical info, waiver, and payment live on the parent registration",(z==null?void 0:z.confirmation_number)&&e.jsxs(e.Fragment,{children:[" ",e.jsx("span",{className:"font-mono text-primary",children:z.confirmation_number})]}),"."]})]}),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:[r.first_name," ",r.last_name]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground block",children:"Date of Birth"}),e.jsx("span",{className:"text-foreground",children:ke(Bt(r.date_of_birth),"MMM d, yyyy")})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vs,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-foreground",children:r.email})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-foreground",children:r.phone})]}),C.ama_number&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground block",children:"AMA Number"}),e.jsx("span",{className:"text-foreground",children:C.ama_number})]})]})]}),Ys().length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-semibold text-foreground mb-2 flex items-center gap-2",children:[e.jsx(un,{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:Ys().map(s=>{var o,d,y;const a=Un(s.field_value,(o=s.form_fields)==null?void 0:o.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:Qn((d=s.form_fields)==null?void 0:d.export_label,(y=s.form_fields)==null?void 0:y.label)}),e.jsx("span",{className:"text-foreground",children:a})]},s.id)})})]}),(C.medical_conditions||C.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:[C.medical_conditions&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground block",children:"Medical Conditions"}),e.jsx("span",{className:"text-foreground",children:C.medical_conditions})]}),C.allergies&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground block",children:"Allergies"}),e.jsx("span",{className:"text-foreground",children:C.allergies})]})]})]}),C.waiver_signed&&e.jsxs("div",{className:"p-3 rounded-md bg-success/10 border border-success/20",children:[e.jsxs("div",{className:"flex items-center gap-2 text-success",children:[e.jsx(hn,{className:"h-4 w-4"}),e.jsx("span",{className:"font-semibold",children:"Waiver Signed"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-1",children:["Signed by:"," ",C.waiver_signature_name?C.waiver_signature_name.startsWith("data:image")?"Signature captured":C.waiver_signature_name:"Unknown",C.waiver_signed_at&&e.jsxs("span",{children:[" on ",ke(new Date(C.waiver_signed_at),"MMM d, yyyy h:mm a")]})]})]}),Y.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-semibold text-foreground mb-2 flex items-center gap-2",children:[e.jsx(_t,{className:"h-4 w-4"}),e.jsx("span",{children:"Add-ons Purchased"})]}),e.jsx("div",{className:"space-y-2",children:Y.map(s=>{var o;const a=s.received_count>=s.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:`text-foreground ${a?"line-through opacity-60":""}`,children:[(o=s.add_ons)==null?void 0:o.name,e.jsxs("span",{className:"ml-1 text-xs text-muted-foreground",children:["(",s.received_count,"/",s.quantity,")"]})]}),e.jsxs("span",{className:"text-muted-foreground",children:["$",(s.price_at_purchase*s.quantity).toFixed(2)]})]}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-1",children:Array.from({length:s.quantity},(d,y)=>{var E,P;const N=y<s.received_count;return e.jsxs("label",{className:"flex items-center gap-1 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:N,onChange:async()=>{const de=N?s.received_count-1:s.received_count+1;await S.from("registration_add_ons").update({received_count:de}).eq("id",s.id),h.invalidateQueries({queryKey:["registration-addons",w]})}
14,className:"h-4 w-4 rounded border-primary text-primary focus:ring-primary cursor-pointer"}),e.jsx("span",{className:`text-xs ${N?"text-success line-through":"text-muted-foreground"}`,children:s.quantity>1?`${(E=s.add_ons)==null?void 0:E.name} #${y+1}`:`${(P=s.add_ons)==null?void 0:P.name} â Received`})]},y)})}),a&&e.jsx(De,{className:"h-4 w-4 text-success inline ml-1"})]},s.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 s=Te(C),a=Number(C.subtotal||0),o=Number(C.add_ons_total||0),d=s.isActual?s.gross:Number(C.total_amount||0)||a+o,y=Math.max(0,+(d-s.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:["$",d.toFixed(2)]})]}),y>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:["â$",y.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:["$",s.net.toFixed(2)]})]})]})})()})]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-1",children:[e.jsxs("div",{children:["Registered: ",ke(new Date(r.created_at),"MMM d, yyyy h:mm a")]}),r.checked_in&&r.checked_in_at&&e.jsxs("div",{children:["Checked In: ",ke(new Date(r.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(k,{variant:"default",onClick:()=>{const s=r.is_child_registration&&r.parent_registration_id?r.parent_registration_id:r.id;B(null),i(`/admin/registrations/${s}/edit`)},className:"w-full",children:[e.jsx(lt,{className:"mr-2 h-4 w-4"}),"Edit Registration"]})})]})]})}),e.jsx(On,{open:!!M,onOpenChange:s=>!s&&g(null),registrationId:M,onCollected:()=>{h.invalidateQueries({queryKey:["event-registrations"]}),h.invalidateQueries({queryKey:["registration-payment-links"]})}}),e.jsx(In,{eventId:ce,open:b,onOpenChange:A}),e.jsx(Ve,{open:q,onOpenChange:K,children:e.jsxs(We,{className:"max-w-sm",children:[e.jsxs(He,{children:[e.jsx(Ye,{children:"Process Refund"}),e.jsx(js,{children:oe==="wallet"?"Adds credit to the rider's account balance at this track. No money leaves Stripe and no fees are withheld.":"Money goes back to the card. Card processing and platform fees are automatically withheld and not refunded."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(pe,{children:"Refund to"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(k,{variant:oe==="stripe"?"default":"outline",size:"sm",onClick:()=>U("stripe"),children:"Card (Stripe)"}),e.jsx(k,{variant:oe==="wallet"?"default":"outline",size:"sm",onClick:()=>U("wallet"),children:"Account Credit"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(k,{variant:Z==="percentage"?"default":"outline",size:"sm",onClick:()=>me("percentage"),children:"Percentage"}),e.jsx(k,{variant:Z==="amount"?"default":"outline",size:"sm",onClick:()=>me("amount"),children:"Dollar Amount"})]}),Z==="percentage"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(pe,{children:"Refund Percentage"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qe,{type:"number",min:"1",max:"100",value:H,onChange:s=>te(s.target.value),className:"w-24"}),e.jsx("span",{className:"text-muted-foreground",children:"%"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(pe,{children:"Refund Amount"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"$"}),e.jsx(Qe,{type:"number",min:"0.01",step:"0.01",value:fe,onChange:s=>xe(s.target.value),className:"w-32",placeholder:"0.00"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(k,{variant:"outline",onClick:()=>K(!1),children:"Cancel"}),e.jsx(k,{onClick:ae,children:oe==="wallet"?"Add Account Credit":"Process Refund"})]})]})]})}),e.jsx(Gt,{open:!!re,onOpenChange:s=>!s&&ue(null),children:e.jsxs(Jt,{children:[e.jsxs(Zt,{children:[e.jsx(Xt,{children:"Delete Registration"}),e.jsxs(en,{children:["Are you sure you want to permanently delete the registration for"," ",e.jsxs("strong",{children:[re==null?void 0:re.first_name," ",re==null?void 0:re.last_name]})," (",re==null?void 0:re.confirmation_number,")? This action cannot be undone."]})]}),e.jsxs(sn,{children:[e.jsx(tn,{children:"Cancel"}),e.jsx(nn,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>re&&Ne(re),children:"Delete"})]})]})})]})}const Vn=[{key:"firstName",label:"First Name"},{key:"middleInitial",label:"Middle Initial"},{key:"lastName",label:"Last Name"},{key:"address",label:"Address"},{key:"city",label:"City"},{key:"state",label:"State"},{key:"zip",label:"Zip"},{key:"birthMonth",label:"Birth Month"},{key:"birthDay",label:"Birth Day"},{key:"birthYear",label:"Birth Year"},{key:"phoneNumber",label:"Phone"},{key:"sponsors",label:"Sponsors"},{key:"email",label:"Email"},{key:"amaMemberId",label:"AMA Member ID"}];function mt(t){return t==null||t===""?"":String(t).trim()}function Wn({label:t,regValue:x,masterValue:n}){const i=mt(x),h=mt(n),l=i!==""&&h!==""&&i.toLowerCase()!==h.toLowerCase();return e.jsxs("div",{className:`grid grid-cols-3 gap-2 text-sm py-1.5 px-2 rounded ${l?"bg-destructive/10":""}`,children:[e.jsx("span",{className:"text-muted-foreground font-medium text-xs",children:t}),e.jsx("span",{className:l?"text-destructive font-semibold":"text-foreground",children:i||"â"}),e.jsx("span",{className:l?"text-destructive font-semibold":"text-foreground",children:h||"â"})]})}function Hn(t,x){return J({queryKey:["registration-full-data",t],queryFn:async()=>{const[n,i]=await Promise.all([S.from("registrations").select("*").eq("id",t).maybeSingle(),S.from("form_responses").select("field_value, form_fields!inner(field_type, label)").eq("registration_id",t)]),h=n.data,l=i.data||[],m={};if(h){if(m.firstName=h.first_name||"",m.lastName=h.last_name||"",m.email=h.email||"",m.phoneNumber=h.phone||"",h.date_of_birth){const _=h.date_of_birth.split(/[-\/]/);if(_.length===3){const r=_[0].length===4;m.birthYear=r?_[0]:_[2],m.birthMonth=r?_[1]:_[0],m.birthDay=r?_[2]:_[1],m.birthMonth=String(parseInt(m.birthMonth)||""),m.birthDay=String(parseInt(m.birthDay)||"")}}
14m.amaMemberId=h.ama_number||""}const j=_=>(_||"").replace(/<[^>]*>/g,"").trim().toLowerCase();for(const _ of l){const r=_.form_fields;if(!r||!_.field_value)continue;const B=r.field_type||"",M=j(r.label||"");if(B==="address")try{const g=JSON.parse(_.field_value);g.street&&!m.address&&(m.address=g.street),g.city&&!m.city&&(m.city=g.city),g.state&&!m.state&&(m.state=g.state),g.zip&&!m.zip&&(m.zip=g.zip)}catch{m.address||(m.address=_.field_value)}M.includes("sponsor")&&!m.sponsors&&(m.sponsors=_.field_value),M.includes("middle")&&M.includes("initial")&&!m.middleInitial&&(m.middleInitial=_.field_value),(M.includes("ama")&&M.includes("number")||M.includes("ama")&&M.includes("member"))&&(m.amaMemberId||(m.amaMemberId=_.field_value))}return m},enabled:!!t})}function Yn({memberNumber:t,registrationId:x,eventId:n,organizationId:i}){const{data:h,isLoading:l,isError:m}=J({queryKey:["rider-compare-pg",i,t],queryFn:async()=>{const{data:g}=await S.from("rider_family_members").select("first_name, middle_initial, last_name, address, city, state, zip, date_of_birth, phone_number, email, ama_member_id, sponsors").eq("beyondpro_member_number",t).maybeSingle();if(!g)return{master:null};const b=g,A=b.date_of_birth?String(b.date_of_birth).match(/^(\d{4})-(\d{2})-(\d{2})/):null;return{master:{firstName:b.first_name??"",middleInitial:b.middle_initial??"",lastName:b.last_name??"",address:b.address??"",city:b.city??"",state:b.state??"",zip:b.zip??"",birthYear:A?Number(A[1]):"",birthMonth:A?Number(A[2]):"",birthDay:A?Number(A[3]):"",phoneNumber:b.phone_number??"",email:b.email??"",sponsors:b.sponsors??"",amaMemberId:b.ama_member_id??""},staging:null}},enabled:!!i&&t>0}),{data:j,isLoading:_}=Hn(x);if(l||_)return e.jsxs("div",{className:"flex items-center gap-2 py-4 text-muted-foreground text-sm",children:[e.jsx(Me,{className:"h-4 w-4 animate-spin"})," Loading comparison dataâ¦"]});if(m)return e.jsx("div",{className:"text-sm text-destructive py-2",children:"Failed to load rider data."});const B=(h==null?void 0:h.master)||{},M=j||{};return e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 space-y-1",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-xs font-semibold text-muted-foreground pb-2 border-b border-border mb-1",children:[e.jsx("span",{children:"Field"}),e.jsx("span",{children:"Registration"}),e.jsx("span",{children:"Existing Rider"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground pb-1",children:["Member #",t,!(h!=null&&h.master)&&e.jsx(D,{variant:"outline",className:"ml-2 text-xs",children:"No existing rider found"})]}),Vn.map(g=>e.jsx(Wn,{label:g.label,regValue:String(M[g.key]??""),masterValue:String(B[g.key]??"")},g.key))]})}function Gn({candidates:t,selectedMember:x,onSelect:n}){return e.jsx(Nt,{value:(x==null?void 0:x.toString())||"",onValueChange:i=>n(parseInt(i)),className:"space-y-2",children:t.map(i=>e.jsxs("div",{className:"flex items-start gap-3 p-2 rounded-md border border-border hover:bg-muted/50",children:[e.jsx(wt,{value:i.memberNumber.toString(),id:`candidate-${i.memberNumber}`,className:"mt-1"}),e.jsxs(pe,{htmlFor:`candidate-${i.memberNumber}`,className:"flex-1 cursor-pointer",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"font-medium",children:[i.firstName," ",i.lastName]}),e.jsxs(D,{variant:"outline",className:"text-xs",children:["#",i.memberNumber]}),e.jsx(D,{variant:"secondary",className:"text-xs",children:i.source}),e.jsxs(D,{variant:"secondary",className:"text-xs",children:["Score: ",i.score]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1 flex gap-3 flex-wrap",children:[i.email&&e.jsxs("span",{children:["Email: ",i.email]}),i.dob&&e.jsxs("span",{children:["DOB: ",i.dob]}),i.phone&&e.jsxs("span",{children:["Phone: ",i.phone]})]}),e.jsxs("div",{className:"flex gap-2 mt-1",children:[i.email_match&&e.jsx(D,{className:"text-xs bg-green-600",children:"Email â"}),i.dob_match&&e.jsx(D,{className:"text-xs bg-green-600",children:"DOB â"}),i.phone_match&&e.jsx(D,{className:"text-xs bg-green-600",children:"Phone â"}),!i.email_match&&!i.dob_match&&!i.phone_match&&e.jsx(D,{variant:"outline",className:"text-xs",children:"Name only"})]})]})]},i.memberNumber))})}function Jn({review:t,onDismiss:x,isResolving:n}){const i=t.registration_details||{},h=t.match_details||{},l=h.selected_child_events||[],m=t.registration_id;return e.jsxs(qe,{className:"p-4 space-y-3 border-amber-300 dark:border-amber-700",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"font-semibold",children:[i.first_name||i.firstName," ",i.last_name||i.lastName]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Season pass fan-out couldn't put this rider in Timing Lab â no class was selected on their registration."})]}),e.jsx(D,{variant:"outline",className:"border-amber-500 text-amber-700 dark:text-amber-300",children:"Class missing"})]}),e.jsxs("div",{className:"text-xs grid grid-cols-2 gap-2 p-2 bg-muted/30 rounded",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Email:"})," ",i.email||"â"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"DOB:"})," ",i.date_of_birth||"â"]}
14),e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"BP#:"})," ",i.beyondpro_member_number||"â"]})]}),l.length>0&&e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"text-muted-foreground mb-1",children:"Affected rounds:"}),e.jsx("ul",{className:"list-disc list-inside space-y-0.5",children:l.map(j=>e.jsx("li",{children:j.name},j.id))})]}),h.reason&&e.jsxs("p",{className:"text-xs text-muted-foreground italic",children:["Reason: ",h.reason]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsx(k,{asChild:!0,size:"sm",children:e.jsx("a",{href:`/admin/registrations/${m}/edit`,children:"Open registration to assign class"})}),e.jsx(k,{size:"sm",variant:"outline",onClick:()=>x(t.id),disabled:n,children:"Dismiss review"})]})]})}function Zn({defaultQuery:t,onPick:x}){const[n,i]=F.useState(t||""),{data:h=[],isLoading:l}=xn(n,!0);return e.jsxs("div",{className:"space-y-2 border border-dashed border-border rounded-md p-3 bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qs,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("p",{className:"text-sm font-medium",children:"Search existing riders to merge into"})]}),e.jsx(Qe,{placeholder:"Search by name, member #, emailâ¦",value:n,onChange:m=>i(m.target.value)}),n.length<2?e.jsx("p",{className:"text-xs text-muted-foreground",children:"Type at least 2 characters to search."}):l?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-2",children:[e.jsx(Me,{className:"h-4 w-4 animate-spin"})," Searchingâ¦"]}):h.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No riders matched."}):e.jsx("div",{className:"max-h-56 overflow-y-auto divide-y divide-border rounded border border-border bg-background",children:h.slice(0,25).map(m=>{const j=`${m.firstName} ${m.lastName}`.trim(),_=m.birthYear&&m.birthMonth&&m.birthDay?`${m.birthYear}-${String(m.birthMonth).padStart(2,"0")}-${String(m.birthDay).padStart(2,"0")}`:"";return e.jsxs("button",{type:"button",onClick:()=>x(m.memberNumber,j),className:"w-full text-left px-2 py-1.5 hover:bg-muted text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium",children:j||"(no name)"}),e.jsxs(D,{variant:"outline",className:"text-xs",children:["#",m.memberNumber]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[m.email||"â"," · ",m.phoneNumber||"â"," · DOB ",_||"â"]})]},m.memberNumber)})})]})}function Xn({review:t,eventId:x,organizationId:n,onResolve:i,isResolving:h}){var A,v,L,$,O;const l=((A=t.match_details)==null?void 0:A.all_candidates)||[],m=l.length>1,j=l.length>0||!!t.candidate_member_number,[_,r]=F.useState(l.length>0?l[0].memberNumber:t.candidate_member_number),[B,M]=F.useState(!j),g=_||t.candidate_member_number,b=`${((v=t.registration_details)==null?void 0:v.firstName)||""} ${((L=t.registration_details)==null?void 0:L.lastName)||""}`.trim();return e.jsxs(qe,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"font-semibold",children:[($=t.registration_details)==null?void 0:$.firstName," ",(O=t.registration_details)==null?void 0:O.lastName]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l.length>0?`${l.length} potential match${l.length>1?"es":""} found`:`Match Score: ${t.match_score} · Candidate #${t.candidate_member_number}`})]}),e.jsx(D,{variant:"outline",children:"Pending"})]}),m&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Select which existing rider to merge into:"}),e.jsx(Gn,{candidates:l,selectedMember:_,onSelect:r})]}),g&&n?e.jsx(Yn,{memberNumber:g,registrationId:t.registration_id,eventId:x,organizationId:n}):e.jsx("div",{className:"text-sm text-muted-foreground",children:"No candidate auto-found. Search below for an existing rider to merge into, or create a new rider."}),(B||!j)&&e.jsx(Zn,{defaultQuery:b,onPick:q=>{r(q),M(!1)}}),j&&!B&&e.jsxs(k,{size:"sm",variant:"ghost",onClick:()=>M(!0),className:"w-fit",children:[e.jsx(Qs,{className:"h-4 w-4 mr-1"})," Pick a different existing rider"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(k,{size:"sm",onClick:()=>i(t.id,"approve",_||void 0),disabled:h||!g,children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"}),"Approve Match ",g?`(#${g})`:""]}),e.jsxs(k,{size:"sm",variant:"outline",onClick:()=>i(t.id,"create_new"),disabled:h,children:[e.jsx(kt,{className:"h-4 w-4 mr-1"}),"Create New Rider"]})]})]})}function ea({review:t,onResolve:x,isResolving:n}){var _;const i=t.pg_candidate_family_member_ids||[],h=t.submission_identity||t.registration_details||{},[l,m]=F.useState(i[0]||null),{data:j=[]}=J({queryKey:["near-match-candidates",t.id],queryFn:async()=>
14{if(i.length===0)return[];const{data:r,error:B}=await S.from("rider_family_members").select("id, first_name, last_name, email, phone_number, date_of_birth, beyondpro_member_number").in("id",i);if(B)throw B;return r||[]},enabled:i.length>0});return e.jsxs(qe,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"font-semibold",children:[h.firstName," ",h.lastName]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Near match â registered as new rider, but ",i.length," existing profile",i.length===1?"":"s"," overlap. Pick the right person to merge into, or keep as a new rider."]})]}),e.jsx(D,{variant:"outline",children:"Near match"})]}),e.jsxs("div",{className:"text-xs grid grid-cols-2 gap-2 p-2 bg-muted/30 rounded",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Submitted email:"})," ",h.email||"â"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Submitted phone:"})," ",h.phone||"â"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Submitted DOB:"})," ",h.dateOfBirth||h.dob||"â"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"New BP#:"})," ",((_=t.match_details)==null?void 0:_.created_bp_number)||"â"]})]}),j.length>0&&e.jsx(Nt,{value:l||"",onValueChange:m,className:"space-y-1",children:j.map(r=>e.jsxs(pe,{htmlFor:`near-${r.id}`,className:`flex items-start gap-2 p-2 border rounded cursor-pointer hover:bg-muted/50 ${l===r.id?"border-primary bg-primary/5":""}`,children:[e.jsx(wt,{value:r.id,id:`near-${r.id}`,className:"mt-1"}),e.jsxs("div",{className:"text-sm flex-1",children:[e.jsxs("div",{className:"font-medium",children:[r.first_name," ",r.last_name," ",r.beyondpro_member_number?e.jsxs("span",{className:"text-muted-foreground font-normal",children:["· BP#",r.beyondpro_member_number]}):null]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[r.email||"â"," · ",r.phone_number||"â"," · DOB ",r.date_of_birth||"â"]}
14)]})]},r.id))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(k,{size:"sm",onClick:()=>x(t.id,"approve",l||void 0),disabled:n||!l,children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"}),"Merge into selected"]}),e.jsxs(k,{size:"sm",variant:"outline",onClick:()=>x(t.id,"create_new"),disabled:n,children:[e.jsx(kt,{className:"h-4 w-4 mr-1"}),"Keep as new rider"]})]})]})}function sa({registration:t,onFix:x}){const n=[t.first_name,t.last_name].filter(Boolean).join(" ")||"Unknown rider",i=[];return t.family_member_id||i.push("No family link"),t.beyondpro_member_number||i.push("No BP#"),e.jsxs(qe,{className:"p-4 space-y-3 border-amber-300",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"font-semibold",children:n}),e.jsx(D,{variant:"secondary",children:"Needs link"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"This registration is confirmed, but Race Readiness cannot verify it against a linked rider profile."})]}),e.jsx(D,{variant:"outline",children:"Unlinked"})]}),e.jsxs("div",{className:"text-xs grid grid-cols-1 sm:grid-cols-3 gap-2 p-2 bg-muted/30 rounded",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Email:"})," ",t.email||"â"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Family link:"})," ",t.family_member_id?"Linked":"Missing"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"BP#:"})," ",t.beyondpro_member_number||"Missing"]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:i.join(" · ")}),e.jsx(k,{size:"sm",variant:"outline",onClick:()=>x(t.id),children:"Fix Registration"})]})]})}function ut({eventId:t,eventIds:x}){const n=Bs(),i=ks(),{currentOrganization:h}=Kt(),[l,m]=F.useState(!1),j=x&&x.length>0?x:[t],{data:_=[],isLoading:r}=J({queryKey:["rider-match-reviews",j.join(",")],queryFn:async()=>{const{data:v,error:L}=await S.from("rider_match_reviews").select("id, registration_id, candidate_member_number, match_score, match_details, candidate_details, registration_details, status, resolved_member_number, resolved_by, resolved_at, created_at, review_kind, submission_identity, pg_candidate_family_member_ids, new_family_member_id").in("event_id",j).order("created_at",{ascending:!1});if(L)throw L;return v||[]}}),{data:B=[],isLoading:M}=J({queryKey:["rider-match-review-unlinked-registrations",j.join(",")],queryFn:async()=>{const{data:v,error:L}=await S.from("registrations").select("id, first_name, last_name, email, event_id, family_member_id, beyondpro_member_number, status, created_at").in("event_id",j).eq("status","confirmed").or("family_member_id.is.null,beyondpro_member_number.is.null").order("created_at",{ascending:!1}).limit(500);if(L)throw L;return v||[]},enabled:j.length>0}),g=_s({mutationFn:async({reviewId:v,action:L,selectedMember:$})=>{const{data:O,error:q}=await S.functions.invoke("resolve-rider-match",{body:{review_id:v,action:L,selected_member_number:$}});if(q)throw q;return O},onSuccess:(v,L)=>{be.success(L.action==="approve"?"Match approved â rider linked":"New rider profile created"),i.invalidateQueries({queryKey:["rider-match-reviews",j.join(",")]})},onError:v=>{be.error(`Failed to resolve: ${v.message}`)}}),b=_.filter(v=>v.status==="pending"),A=_.filter(v=>v.status!=="pending");return r||M?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Me,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):b.length===0&&A.length===0&&B.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(gn,{className:"h-10 w-10 mx-auto mb-3 text-primary"}),e.jsx("p",{className:"text-lg font-medium",children:"No issues to review"}),e.jsx("p",{className:"text-sm",children:"All registrations matched successfully."})]}):e.jsxs("div",{className:"space-y-6",children:[b.length>0&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center gap-2",children:["Pending Reviews",e.jsx(D,{variant:"destructive",children:b.length})]}),b.map(v=>v.review_kind==="near_match"?e.jsx(ea,{review:v,onResolve:(L,$,O)=>g.mutate({reviewId:L,action:$,selectedMember:O}),isResolving:g.isPending},v.id):v.review_kind==="season_pass_fanout_unresolved"?e.jsx(Jn,{review:v,onDismiss:L=>g.mutate({reviewId:L,action:"create_new"}),isResolving:g.isPending},v.id):e.jsx(Xn,{review:v,eventId:t,organizationId:(h==null?void 0:h.id)||"",onResolve:(L,$,O)=>g.mutate({reviewId:L,action:$,selectedMember:O}),isResolving:g.isPending},v.id))]}),B.length>0&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center gap-2",children:["Unlinked Confirmed Registrations",e.
14jsx(D,{variant:"secondary",children:B.length})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"These are the same rider-link gaps Race Readiness is flagging. They have confirmed registrations, but the registration is missing a family profile link or BP#."}),B.map(v=>e.jsx(sa,{registration:v,onFix:L=>n(`/admin/registrations/${L}/edit`)},v.id))]}),A.length>0&&e.jsxs(bs,{open:l,onOpenChange:m,children:[e.jsx(vs,{asChild:!0,children:e.jsxs(k,{variant:"ghost",className:"flex items-center gap-2",children:[e.jsx(yn,{className:"h-4 w-4"}),"Resolved (",A.length,")",e.jsx(ts,{className:`h-4 w-4 transition-transform ${l?"rotate-180":""}`})]})}),e.jsx(Ns,{children:e.jsxs(jt,{children:[e.jsx(bt,{children:e.jsxs(Ge,{children:[e.jsx(Ee,{children:"Name"}),e.jsx(Ee,{children:"Status"}),e.jsx(Ee,{children:"Member #"}),e.jsx(Ee,{children:"Resolved"})]})}),e.jsx(vt,{children:A.map(v=>{var L,$;return e.jsxs(Ge,{children:[e.jsxs(Se,{children:[(L=v.registration_details)==null?void 0:L.firstName," ",($=v.registration_details)==null?void 0:$.lastName]}),e.jsx(Se,{children:e.jsx(D,{variant:v.status==="approved"?"default":"secondary",children:v.status==="approved"?"Matched":"New Rider"})}),e.jsxs(Se,{children:["#",v.resolved_member_number]}),e.jsx(Se,{className:"text-sm text-muted-foreground",children:v.resolved_at?new Date(v.resolved_at).toLocaleDateString():"â"})]},v.id)})})]})})]})]})}function ta({eventId:t}){const{toast:x}=Os();ks();const[n,i]=F.useState(new Set),[h,l]=F.useState(!1),{data:m=[],isLoading:j,refetch:_}=J({queryKey:["abandoned-registrations",t],queryFn:async()=>{const{data:{session:g}}=await S.auth.getSession();if(!g)return[];const b=await fetch("https://hhkjvpdlkhxblpqzugic.supabase.co/functions/v1/send-abandoned-followup",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${g.access_token}`},body:JSON.stringify({event_id:t,mode:"preview"})});if(!b.ok)throw new Error("Failed to fetch abandoned registrations");return(await b.json()).abandoned||[]},enabled:!!t}),r=async g=>{const{data:{session:b}}=await S.auth.getSession();if(!b)throw new Error("Not authenticated");const A=await fetch("https://hhkjvpdlkhxblpqzugic.supabase.co/functions/v1/send-abandoned-followup",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${b.access_token}`},body:JSON.stringify({event_id:t,record_ids:g,mode:"send"})});if(!A.ok)throw new Error("Failed to send follow-up emails");return A.json()},B=async g=>{var A;const b=`${g.type}|${g.id}`;i(v=>new Set(v).add(b));try{const v=await r([{id:g.id,type:g.type}]);x({title:v.sent>0?"Follow-up sent":"Failed to send",description:v.sent>0?`Email sent to ${g.email}`:((A=v.errors)==null?void 0:A[0])||"Unknown error",variant:v.sent>0?"default":"destructive"}),_()}catch(v){x({title:"Error",description:v.message,variant:"destructive"})}finally{i(v=>{const L=new Set(v);return L.delete(b),L})}},M=async()=>{var g;if(m.length!==0){l(!0);try{const b=m.map(v=>({id:v.id,type:v.type})),A=await r(b);x({title:`${A.sent} follow-up email${A.sent!==1?"s":""} sent`,description:(g=A.errors)!=null&&g.length?`${A.errors.length} failed`:void 0}),_()}catch(b){x({title:"Error",description:b.message,variant:"destructive"})}finally{l(!1)}}};return j?e.jsx(qe,{children:e.jsx(ns,{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):e.jsxs(qe,{children:[e.jsx(Ks,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Us,{className:"flex items-center gap-2",children:[e.jsx(St,{className:"h-5 w-5 text-amber-500"}),"Abandoned Registrations"]}),e.jsx(pt,{children:"People who started registering but didn't complete. Send a friendly follow-up to encourage them to finish."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(k,{variant:"outline",size:"sm",onClick:()=>_(),children:[e.jsx(ws,{className:"h-4 w-4 mr-1"}),"Refresh"]}),m.length>0&&e.jsxs(k,{size:"sm",onClick:M,disabled:h,children:[e.jsx(as,{className:"h-4 w-4 mr-1"}),h?"Sending...":`Send All (${m.length})`]})]})]})}),e.jsx(ns,{children:m.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Vs,{className:"h-10 w-10 mx-auto mb-3 opacity-40"}),e.jsx("p",{className:"font-medium",children:"No abandoned registrations foun
14d"}),e.jsx("p",{className:"text-sm mt-1",children:"Records appear here 2 hours after someone starts but doesn't complete registration"})]}):e.jsx("div",{className:"space-y-2",children:m.map(g=>{const b=`${g.type}|${g.id}`,A=n.has(b);return e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border border-border bg-card hover:bg-muted/50 transition-colors",children:[e.jsx("div",{className:"flex items-center gap-3 min-w-0",children:e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-sm truncate",children:g.name||g.email}),e.jsx(D,{variant:"outline",className:"text-xs shrink-0",children:g.type==="pending_checkout"?"Checkout":"Draft"})]}),g.name&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:g.email}),e.jsxs("div",{className:"flex items-center gap-1 mt-0.5 text-xs text-muted-foreground",children:[e.jsx(_n,{className:"h-3 w-3"}),"Started ",on(new Date(g.created_at),{addSuffix:!0})]})]})}),e.jsxs(k,{variant:"outline",size:"sm",onClick:()=>B(g),disabled:A,children:[e.jsx(as,{className:"h-3.5 w-3.5 mr-1"}),A?"Sending...":"Send Follow-up"]})]},b)})})})]})}function na({registrationId:t,eventId:x}){const{data:n,isLoading:i}=J({queryKey:["rider-fulfillment",t],queryFn:async()=>{const[l,m,j,_,r,B]=await Promise.all([S.from("event_checkin_items").select("id, name, sort_order").eq("event_id",x).eq("is_active",!0).order("sort_order"),S.from("registration_checkin_fulfillment").select("checkin_item_id, received").eq("registration_id",t),S.from("registration_add_ons").select("add_on_id, quantity, received_count").eq("registration_id",t),S.from("form_fields").select("id, label").eq("event_id",x).eq("field_type","merchandise"),S.from("merch_fulfillment").select("field_id, item_index, received").eq("registration_id",t),S.from("form_responses").select("field_id, field_value").eq("registration_id",t)]),M=(l.data||[]).map(q=>{const K=(m.data||[]).find(le=>le.checkin_item_id===q.id);return{name:q.name,received:(K==null?void 0:K.received)??!1}}),g=(j.data||[]).map(q=>q.add_on_id);let b={};if(g.length>0){const{data:q}=await S.from("add_ons").select("id, name").in("id",g);b=Object.fromEntries((q||[]).map(K=>[K.id,K.name]))}const A=(j.data||[]).map(q=>({name:b[q.add_on_id]||"Unknown",quantity:q.quantity,receivedCount:q.received_count||0})),v=_.data||[],L=r.data||[],$=B.data||[],O=[];return v.forEach(q=>{const K=$.find(le=>le.field_id===q.id);if(K!=null&&K.field_value)try{const le=JSON.parse(K.field_value);(Array.isArray(le)?le:[le]).forEach((H,te)=>{const Z=H.quantity||1;for(let me=0;me<Z;me++){const fe=te*100+me,xe=L.find(U=>U.field_id===q.id&&U.item_index===fe),oe=H.itemId?H.itemId.replace(/_/g," ").replace(/\b\w/g,U=>U.toUpperCase()):q.label||"Merch";O.push({name:H.size?`${oe} (${H.size})`:oe,size:H.size,received:(xe==null?void 0:xe.received)??!1})}})}catch{}}),{packetItems:M,addOns:A,merchItems:O}}});return i?e.jsxs("div",{className:"p-3 flex items-center gap-2 text-muted-foreground text-xs",children:[e.jsx(Me,{className:"h-3 w-3 animate-spin"})," Loading..."]}):n?n.packetItems.length>0||n.addOns.length>0||n.merchItems.length>0?e.jsxs("div",{className:"p-3 space-y-3 bg-muted/30 border-t border-border",children:[n.packetItems.length>0&&e.jsxs("div",{children:[e.jsxs("p",{className:"text-xs font-medium text-muted-foreground mb-1 flex items-center gap-1",children:[e.jsx(Sn,{className:"h-3 w-3"})," Packet Items"]}),e.jsx("div",{className:"space-y-0.5",children:n.packetItems.map((l,m)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[l.received?e.jsx(De,{className:"h-3 w-3 text-green-600 shrink-0"}):e.jsx(ss,{className:"h-3 w-3 text-muted-foreground shrink-0"}),e.jsx("span",{className:l.received?"text-foreground":"text-muted-foreground",children:l.name})]},m))})]}),n.addOns.length>0&&e.jsxs("div",{children:[e.jsxs("p",{className:"text-xs font-medium text-muted-foreground mb-1 flex items-center gap-1",children:[e.jsx(_t,{className:"h-3 w-3"})," Add-Ons"]}),e.jsx("div",{className:"space-y-0.5",children:n.addOns.map((l,m)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[l.receivedCount>=l.quantity?e.jsx(De,{className:"h-3 w-3 text-green-600 shrink-0"}):e.jsx(ss,{className:"h-3 w-3 text-muted-foreground shrink-0"}),e.jsxs("span",{className:l.receivedCount>=l.quantity?"text-foreground":"text-muted-foreground",children:[l.name," (",l.receivedCount,"/",l.quantity,")"]})]},m))})]}),n.merchItems.length>0&&e.jsxs("div",{children:[e.jsxs("p",{className:"text-xs font-medium text-muted-foreground mb-1 flex items-center gap-1",children:[e.jsx(Cn,{className:"h-3 w-3"})," Merchandise"]}),e.jsx("div",{className:"space-y-0.5",children:n.merchItems.map((l,m)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[l.received?e.jsx(De,{className:"h-3 w-3 text-green-600 shrink-0"}):e.jsx(ss,{className:"h-3 w-3 text-muted-foreground shrink-0"}),e.jsxs("span",{className:l.received?"text-foreground":"text-muted-foreground",children:[l.name,l.size?` (${l.size})`:""]})]},m))})]})]}):e.jsx("div",{className:"p-3 text-xs text-muted-foreground",children:"No items to track"}):null}function aa({rider:t,eventId:x}){const[n,i]=F.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(Ge,{className:"cursor-pointer",onClick:()=>i(!n),children:[e.jsx(Se,{className:"w-8 px-2",children:n?e.jsx(Ps,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(ts,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsx(Se,{className:"font-medium",children:t.name}),e.jsx(Se,{className:"text-muted-foreground",children:t.phone||"â"}),e.jsx(Se,{children:t.racingClass||"â"}),e.jsx(Se,{className:"font-mono text-xs",children:t.confirmationNumber})]}),n&&e.jsx(Ge,{children:e.jsx(Se,{colSpan:5,className:"p-0",children:e.jsx(na,{registrationId:t.registrationId,eventId:x})})})]})}function ra({eventId:t}){const{data:x,isLoading:n,error:i}=Ht(t),[h,l]=F.useState(!1),[m,j]=F.useState(!1),[_,r]=F.useState(""),[B,M]=F.useState(!1),[g,b]=F.useState(!1),A=jn(),{sendEmail:v,isSe
14nding:L}=bn(),{data:$}=J({queryKey:["event-name",t],queryFn:async()=>{const{data:U}=await S.from("events").select("name").eq("id",t).maybeSingle();return U},enabled:!!t});if(n)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Me,{className:"h-8 w-8 animate-spin text-primary"})});if(i||!x)return e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Failed to load check-in data"});const O=x.checkedInCount+x.notCheckedInCount,q=x.notCheckedInList.filter(U=>U.phone),K=x.notCheckedInList.filter(U=>U.email),le=160,V=153,H=_.length,te=H<=le?1:Math.ceil(H/V),Z=te>1,me=H>320,fe=()=>{if(!_.trim()||q.length===0)return;const U=q.map(re=>({phone:re.phone,name:re.name}));A.mutate({recipients:U,message:_,eventName:$==null?void 0:$.name,source:"check_in_status"},{onSuccess:()=>{l(!1),r("")}})},xe=U=>{const re=new Set(K.map(Ce=>Ce.email.toLowerCase())),ue=U.recipients.filter(Ce=>re.has(Ce.email.toLowerCase()));v({subject:U.subject,message_body:U.messageBody,recipients:ue,source:"check_in_status"},{onSuccess:()=>j(!1)})},oe=(U,re)=>e.jsxs(jt,{children:[e.jsx(bt,{children:e.jsxs(Ge,{children:[e.jsx(Ee,{className:"w-8"}),e.jsx(Ee,{children:"Name"}),e.jsx(Ee,{children:"Phone"}),e.jsx(Ee,{children:"Class"}),e.jsx(Ee,{children:"Confirmation"})]})}),e.jsx(vt,{children:U.length===0?e.jsx(Ge,{children:e.jsx(Se,{colSpan:5,className:"text-center text-muted-foreground",children:re})}):U.map((ue,Ce)=>e.jsx(aa,{rider:ue,eventId:t},Ce))})]});return e.jsxs(qe,{className:"bg-card border-border",children:[e.jsx(Ks,{className:"pb-3",children:e.jsxs(Us,{className:"text-foreground flex items-center gap-2",children:[e.jsx(De,{className:"h-4 w-4"})," Check-In Status"]})}),e.jsxs(ns,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs(D,{variant:"outline",className:"text-sm px-3 py-1",children:[e.jsx(wn,{className:"mr-1.5 h-3.5 w-3.5"})," ",O," Confirmed"]}),e.jsxs(D,{className:"bg-green-600 hover:bg-green-600 text-sm px-3 py-1",children:[e.jsx(De,{className:"mr-1.5 h-3.5 w-3.5"})," ",x.checkedInCount," Checked In"]}),e.jsxs(D,{className:"bg-amber-600 hover:bg-amber-600 text-sm px-3 py-1",children:[e.jsx(ss,{className:"mr-1.5 h-3.5 w-3.5"})," ",x.notCheckedInCount," Remaining"]})]}),e.jsxs(ft,{defaultValue:"not-checked-in",children:[e.jsxs(xt,{children:[e.jsxs(Ke,{value:"checked-in",children:["Checked In (",x.checkedInCount,")"]}),e.jsxs(Ke,{value:"not-checked-in",children:["Not Checked In (",x.notCheckedInCount,")"]})]}),e.jsx(Ue,{value:"checked-in",children:e.jsxs(bs,{open:B,onOpenChange:M,children:[e.jsx(vs,{asChild:!0,children:e.jsxs(k,{variant:"ghost",size:"sm",className:"w-full justify-center gap-2 text-muted-foreground",children:[B?e.jsx(Ps,{className:"h-4 w-4"}):e.jsx(ts,{className:"h-4 w-4"}),B?"Hide list":`Show all ${x.checkedInList.length} riders`]})}),e.jsx(Ns,{children:oe(x.checkedInList,"No one checked in yet")})]})}),e.jsx(Ue,{value:"not-checked-in",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[q.length," with phone · ",K.length," with email"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ve,{open:h,onOpenChange:l,children:[e.jsx(Zs,{asChild:!0,children:e.jsxs(k,{size:"sm",variant:"outline",disabled:q.length===0,children:[e.jsx(kn,{className:"mr-2 h-4 w-4"})," Send SMS"]})}),e.jsxs(We,{children:[e.jsx(He,{children:e.jsxs(Ye,{children:["Send SMS to ",q.length," Rider",q.length!==1?"s":""]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Message"}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[Z&&e.jsxs("span",{className:"text-amber-600 flex items-center gap-1",children:[e.jsx(St,{className:"h-3 w-3"}),te," segments"]}),e.jsxs("span",{className:Ls("tabular-nums",me?"text-destructive":H>le?"text-amber-600":"text-muted-foreground"),children:[H,"/320"]})]})]}
14),e.jsx(Nn,{value:_,onChange:U=>r(U.target.value),placeholder:"Type your message here...",rows:4,className:"resize-none",disabled:A.isPending}),Z&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Messages over 160 characters are sent as multiple segments and may cost more."})]}),e.jsxs("div",{className:"rounded-md border bg-muted/30 p-2 max-h-48 overflow-y-auto",children:[e.jsxs("p",{className:"text-xs font-medium text-foreground mb-1",children:["Recipients (",q.length,") â only riders not checked in for this event:"]}),e.jsx("ul",{className:"text-xs text-muted-foreground space-y-0.5",children:q.map((U,re)=>e.jsxs("li",{className:"flex justify-between gap-2",children:[e.jsx("span",{className:"truncate",children:U.name}),e.jsx("span",{className:"font-mono shrink-0",children:U.phone})]},re))})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["This will text only the ",q.length," riders listed above",$!=null&&$.name?` for ${$.name}`:"","."]}),e.jsxs(Is,{children:[e.jsx(k,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(k,{onClick:fe,disabled:!_.trim()||me||A.isPending,children:[A.isPending?e.jsx(Me,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(as,{className:"mr-2 h-4 w-4"}),"Send"]})]})]})]}),e.jsxs(Ve,{open:m,onOpenChange:j,children:[e.jsx(Zs,{asChild:!0,children:e.jsxs(k,{size:"sm",variant:"outline",disabled:K.length===0,children:[e.jsx(Vs,{className:"mr-2 h-4 w-4"})," Send Email"]})}),e.jsxs(We,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(He,{children:e.jsxs(Ye,{children:["Email ",K.length," Rider",K.length!==1?"s":""," Not Checked In"]})}),e.jsx(vn,{onSend:xe,isSending:L,onCancel:()=>j(!1),initialSubject:"",initialBody:"",initialRecipients:K.map(U=>({email:U.email,name:U.name}))})]})]})]})]}),e.jsxs(bs,{open:g,onOpenChange:b,children:[e.jsx(vs,{asChild:!0,children:e.jsxs(k,{variant:"ghost",size:"sm",className:"w-full justify-center gap-2 text-muted-foreground",children:[g?e.jsx(Ps,{className:"h-4 w-4"}):e.jsx(ts,{className:"h-4 w-4"}),g?"Hide list":`Show all ${x.notCheckedInList.length} riders`]})}),e.jsx(Ns,{children:oe(x.notCheckedInList,"Everyone is checked in!")})]})]})})]})]})]})}function Wr(){const{eventId:t}=Ut(),[x]=Qt(),n=Bs(),[i,h]=F.useState(!1),[l,m]=F.useState(!1),j=x.get("scope"),_=async()=>{if(t){m(!0);try{const{data:$,error:O}=await S.functions.invoke("sync-season-pass-classes",{body:{event_id:t}});if(O)throw O;if($!=null&&$.error)throw new Error($.error);const q=($==null?void 0:$.added)??0,K=($==null?void 0:$.prev_round)??"previous round";q===0?be.success(`Season pass classes already match ${K}. No changes.`):be.success(`Added ${q} class assignment${q===1?"":"s"} from ${K}.`)}catch($){console.error("sync-season-pass-classes failed",$),be.error(($==null?void 0:$.message)||"Failed to sync season pass classes")}finally{m(!1)}}},{data:r,isLoading:B}=J({queryKey:["event",t],queryFn:async()=>{const{data:$,error:O}=await S.from("events").select("*").eq("id",t).maybeSingle();if(O)throw O;return $},enabled:!!t}),M=j==="series"&&!!r&&qn(r),{data:g=[]}=J({queryKey:["series-round-ids",t],queryFn:async()=>{const{data:$,error:O}=await S.from("events").select("id").eq("parent_event_id",t);if(O)throw O;return($||[]).map(q=>q.id)},enabled:!!t&&M}),b=M?Array.from(new Set([t,...g])):t?[t]:[],{data:A=0}=J({queryKey:["rider-match-reviews-count",t,M,b.length],queryFn:async()=>{if(b.length===0)return 0;const{count:$,error:O}=await S.from("rider_match_reviews").select("*",{count:"exact",head:!0}).in("event_id",b).eq("status","pending");if(O)throw O;return $||0},enabled:b.length>0}),{data:v=0}=J({queryKey:["unlinked-registrations-count",t,M,b.length],queryFn:async()=>{if(b.length===0)return 0;const{count:$,error:O}=await S.from("registrations").select("id",{count:"exact",head:!0}).in("event_id",b).eq("status","confirmed").or("family_member_id.is.null,beyondpro_member_number.is.null");if(O)throw O;return $||0},enabled:b.length>0}),L=A+v;return B?e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})}):r?e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b border-border bg-card",children:e.jsxs("div",{className:"container mx-auto px-4 py-4 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(k,{variant:"ghost",size:"icon",onClick:()=>n("/admin"),children:e.jsx(Rn,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("h1",{className:"text-xl font-bold",children:[r.name,M?" â All Rounds":""," - Registrations"]}),M&&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(An,{className:"h-3 w-3"}),"Series rollup · ",g.length," round",g.length===1?"":"s"]}),e.jsx(En,{})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:M?"All registrations across every round in this series":"View and manage event registrations"})]})]}),!M&&(r==null?void 0:r.parent_event_id)&&e.jsxs(k,{variant:"outline",size:"sm",onClick:_,disabled:l,title:"Additively copy each season pass rider's timing lab class assignments from the previous round into this round. Never removes classes.",children:[l?e.jsx(Me,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ws,{className:"h-4 w-4 mr-2"}),"Sync season pass classes from previous round"]}
14)]})}),e.jsx("main",{className:`container mx-auto px-4 py-6 transition-all duration-300 ${i?"mr-80":""}`,children:e.jsxs(ft,{defaultValue:x.get("rmrTab")==="review"?"review":"registrations",children:[e.jsxs(xt,{"data-guide":"registrations-tabs",children:[e.jsx(Ke,{value:"registrations","data-guide":"registrations-tab-list",children:"Registrations"}),e.jsx(Ke,{value:"checkin-status","data-guide":"registrations-tab-checkin",children:"Check-In Status"}),e.jsx(Ke,{value:"abandoned","data-guide":"registrations-tab-abandoned",children:"Abandoned"}),e.jsxs(Ke,{value:"review",className:"flex items-center gap-2","data-guide":"registrations-tab-review",children:["Review Issues",L>0&&e.jsx(D,{variant:"destructive",className:"ml-1 h-5 min-w-5 px-1.5 text-xs",children:L})]})]}),e.jsx(Ue,{value:"registrations",children:M?e.jsx(ct,{eventIds:b}):e.jsx(ct,{eventId:t})}),e.jsx(Ue,{value:"checkin-status",children:M?e.jsx("div",{className:"text-sm text-muted-foreground p-6 border rounded-md",children:"Check-In Status is per-round. Open a specific round from the series page to view check-in data."}):e.jsx(ra,{eventId:t})}),e.jsx(Ue,{value:"abandoned",children:e.jsx(ta,{eventId:t})}),e.jsx(Ue,{value:"review",children:M?e.jsx(ut,{eventId:t,eventIds:b}):e.jsx(ut,{eventId:t})})]})}),!i&&e.jsx(Fn,{onClick:()=>h(!0)}),e.jsx($n,{pageContext:"admin-registrations",isOpen:i,onClose:()=>h(!1),className:"fixed right-0 top-0 w-80 h-screen z-50"})]}):e.jsxs("div",{className:"min-h-screen flex flex-col items-center justify-center bg-background gap-4",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Event Not Found"}),e.jsx(k,{onClick:()=>n("/admin"),children:"Back to Dashboard"})]})}export{Wr 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.