1import{r as o,j as e}from"./react-vendor-Q2BSRknM.js";import{c as Z,cE as Pe,s as C,Q as w,R as P,aZ as te,B as N,ax as _e,ay as ye,az as je,h as J,U as M,V as X,dB as Fe,ab as ge,cR as ze,dk as Ke,dV as Ue,cS as $e,J as Q,K as O,L as W,N as I,O as A,cF as Qe,C as Oe,t as de,dW as We,aR as Ie,dX as Je,dY as Ge}from"./index-CuraQpvj.js";import{a as G,u as Y}from"./query-BLOP9k_M.js";import{X as fe,aE as ie,bq as be,w as Te,L as K,br as Ae,a5 as Ve,bs as He,o as Ne,a as we,a0 as Ye,c as Ze,a4 as Xe,a6 as ea,aj as aa,W as sa,ae as ke,af as Ce,bt as ta,T as la,t as na,U as Me,g as le,b as Re,aT as qe,aD as ne,Q as ra,e as Be,y as De,bu as ia,a9 as oa,n as Se,bv as ca,aa as pe,aQ as Le}from"./lucide-DhlFjs1-.js";import{A as H,a as ve,P as da}from"./Admin-XbDVNFMU.js";import"./scroll-area-G9RincEy.js";import"./capacitor-DSpR9wll.js";import{S as me}from"./StatCard-ne8HtqGK.js";import{u as ma}from"./useTeamAvatarCache-DnynuOLF.js";import{I as ua}from"./ImageCropper-DRRbELg7.js";import"./ui-radix-DzQ_orwq.js";import"./supabase-DoZmW4Yf.js";import"./date-utils-DaNoSKVa.js";import"./slider-DKSeILo7.js";function ha({onFileSelect:a,accept:s="image/jpeg,image/jpg,image/png,image/webp",maxSize:r=5*1024*1024,disabled:t=!1,previewUrl:n,onClear:c}){const[i,p]=o.useState(!1),[m,u]=o.useState(null),l=o.useRef(null),d=v=>{const b=s.split(",").map(E=>E.trim());return b.includes(v.type)?v.size>r?`File too large. Maximum size: ${Math.round(r/1024/1024)}MB`:null:`Invalid file type. Accepted: ${b.join(", ")}`},f=o.useCallback(v=>{u(null);const b=d(v);if(b){u(b);return}a(v)},[a,s,r]),S=o.useCallback(v=>{v.preventDefault(),v.stopPropagation(),t||p(!0)},[t]),y=o.useCallback(v=>{v.preventDefault(),v.stopPropagation(),p(!1)},[]),g=o.useCallback(v=>{if(v.preventDefault(),v.stopPropagation(),p(!1),t)return;const b=v.dataTransfer.files;b.length>0&&f(b[0])},[f,t]),j=()=>{!t&&l.current&&l.current.click()},x=v=>{var E;const b=(E=v.target.files)==null?void 0:E[0];b&&f(b),l.current&&(l.current.value="")};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{onClick:j,onDragOver:S,onDragLeave:y,onDrop:g,className:Z("relative border-2 border-dashed rounded-lg p-6 transition-all cursor-pointer","flex flex-col items-center justify-center min-h-[120px]",i&&"border-primary bg-primary/5",!i&&!t&&"hover:border-primary/50 hover:bg-muted/50",t&&"opacity-50 cursor-not-allowed",m&&"border-destructive"),children:[e.jsx("input",{ref:l,type:"file",accept:s,onChange:x,className:"hidden",disabled:t}),n?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:n,alt:"Preview",className:"w-24 h-24 rounded-full object-cover border-2 border-border"}),c&&e.jsx("button",{onClick:v=>{v.stopPropagation(),c()},className:"absolute -top-2 -right-2 p-1 bg-destructive text-destructive-foreground rounded-full opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(fe,{className:"h-4 w-4"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(ie,{className:Z("h-8 w-8 mb-2",i?"text-primary":"text-muted-foreground")}),e.jsx("p",{className:"text-sm font-medium text-center",children:i?"Drop image here":"Drop image or click to upload"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 text-center",children:["JPEG, PNG, WebP up to ",Math.round(r/1024/1024),"MB"]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"400Ã400px recommended"})]})]}),m&&e.jsx("p",{className:"text-xs text-destructive",children:m})]})}function pa(){const a=G(),{allPlayers:s}=Pe({defer:!1}),[r,t]=o.useState(""),[n,c]=o.useState(null),[i,p]=o.useState(""),[m,u]=o.useState(!1),[l,d]=o.useState(null),[f,S]=o.useState(null),[y,g]=o.useState(""),[j,x]=o.useState(null),{data:v=[],refetch:b}=Y({queryKey:["admin-player-user-links"],queryFn:async()=>{const{data:_,error:F}=await C.from("player_user_links").select("id, player_name, user_id, created_at, photo_locked, admin_override_avatar_url").order("created_at",{ascending:!1});if(F)throw F;if(!(_!=null&&_.length))return[];const h=_.map(R=>
1R.user_id),{data:L}=await C.from("profiles_public").select("id, display_name, avatar_url, email_fallback").in("id",h),B=new Map((L||[]).map(R=>[R.id,R]));return _.map(R=>{const U=B.get(R.user_id);return{id:R.id,player_name:R.player_name,user_id:R.user_id,display_name:(U==null?void 0:U.display_name)??null,avatar_url:(U==null?void 0:U.avatar_url)??null,email:(U==null?void 0:U.email_fallback)??null,photo_locked:!!R.photo_locked,admin_override_avatar_url:R.admin_override_avatar_url??null}})},staleTime:3e4}),E=o.useMemo(()=>new Set(v.map(_=>_.player_name.toLowerCase().trim())),[v]),D=o.useMemo(()=>{if(r.length<2)return[];const _=r.toLowerCase();return s.filter(F=>F.toLowerCase().includes(_)&&!E.has(F.toLowerCase().trim())).slice(0,15)},[r,s,E]),{data:z=[],isFetching:k}=Y({queryKey:["admin-link-user-search",i],queryFn:async()=>{const _=i.trim();if(_.length<2)return[];const{data:F,error:h}=await C.from("profiles_public").select("id, display_name, avatar_url, email_fallback").or(`display_name.ilike.%${_}%,email_fallback.ilike.%${_}%`).limit(15);if(h)throw h;return F||[]},enabled:!!n&&i.trim().length>=2,staleTime:1e4}),T=o.useCallback(async _=>{if(n){u(!0);try{const{error:F}=await C.rpc("link_player_to_user",{_player_name:n,_user_id:_});if(F)throw F;w({title:"Player linked",description:`${n} is now linked to that user account.`}),c(null),t(""),p(""),await b(),a.invalidateQueries({queryKey:["user-follows"],exact:!1}),a.invalidateQueries({queryKey:["follow-list"],exact:!1}),a.invalidateQueries({queryKey:["follow-counts"],exact:!1}),a.invalidateQueries({queryKey:["verified-users"],exact:!1})}catch(F){w({title:"Link failed",description:F.message||"Unable to link player",variant:"destructive"})}finally{u(!1)}}},[n,b,a]),q=o.useCallback(async _=>{d(_.id);try{const{error:F}=await C.rpc("unlink_player",{_player_name:_.player_name});if(F)throw F;w({title:"Unlinked",description:`${_.player_name} is no longer linked to a user account.`}),await b(),a.invalidateQueries({queryKey:["user-follows"],exact:!1}),a.invalidateQueries({queryKey:["follow-list"],exact:!1}),a.invalidateQueries({queryKey:["follow-counts"],exact:!1}),a.invalidateQueries({queryKey:["verified-users"],exact:!1})}catch(F){w({title:"Unlink failed",description:F.message||"Unable to unlink",variant:"destructive"})}finally{d(null)}},[b,a]),$=o.useCallback(async(_,F,h)=>{x(_.id);try{const L=(h||"").trim()||null,{error:B}=await C.from("player_user_links").update({photo_locked:F,admin_override_avatar_url:L}).eq("id",_.id);if(B)throw B;w({title:F?"Photo locked":"Photo unlocked",description:F?`${_.player_name}'s photo is locked${L?" to admin URL":""}.`:`${_.player_name} can change their own photo again.`}),S(null),g(""),await b(),a.invalidateQueries({queryKey:["user-linked-player"],exact:!1})}catch(L){w({title:"Save failed",description:L.message||"Unable to update photo settings",variant:"destructive"})}finally{x(null)}},[b,a]);return e.jsxs(H,{title:"Player â Account Links",icon:be,collapsible:!0,defaultOpen:!1,children:[e.jsxs("p",{className:"text-sm text-muted-foreground mb-4",children:["Link a professional player name to a registered user account. Followers and follows automatically sync across both systems once linked, and the user is automatically marked as ",e.jsx("span",{className:"font-medium text-foreground",children:"verified"}),"."]}),e.jsxs("div",{className:"space-y-3 mb-6",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground mb-1 block",children:"1. Select a player"}),e.jsx(P,{value:r,onChange:_=>{t(_.target.value),c(null)},placeholder:"Search player name...",className:"max-w-md",disabled:!!n}),!n&&r.length>=2&&e.jsx("div",{className:"border rounded-lg max-h-[180px] overflow-y-auto mt-2 max-w-md",children:D.length===0?e.jsx("div",{className:"p-3 text-center text-sm text-muted-foreground",children:"No unlinked players match"}):e.jsx("div",{className:"divide-y",children:D.map(_=>e.jsxs("button",{onClick:()=>{c(_),t(_)},className:"w-full p-2 text-left hover:bg-muted flex items-center gap-2 text-sm",children:[e.jsx(te,{name:_,className:"h-6 w-6"}),e.jsx("span",{className:"flex-1 truncate",children:_})]},_))})})]}),n&&e.jsxs("div",{className:"p-3 bg-muted rounded-lg flex items-center gap-3 max-w-md",children:[e.jsx(te,{name:n,className:"h-10 w-10"}),e.jsx("div",{className:"flex-1 font-medium",children:n}),e.jsx(N,{variant:"ghost",size:"sm",onClick:()=>{c(null),t(""),p("")},children:"Clear"})]}),n&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground mb-1 block",children:"2. Search a user account by email or username"}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(Te,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(P,{value:i,onChange:_=>p(_.target.value),placeholder:"email or display name...",className:"pl-8",autoFocus:!0})]}),i.trim().length>=2&&e.jsx("div",{className:"border rounded-lg max-h-[240px] overflow-y-auto mt-2 max-w-md",children:k?e.jsx("div",{className:"p-3 text-center",children:e.jsx(K,{className:"h-4 w-4 animate-spin mx-auto"})}):z.length===0?e.jsx("div",{className:"p-3 text-center text-sm text-muted-foreground",children:"No users found"}):e.jsx("div",{className:"divide-y",children:z.map(_=>e.jsxs("button",{onClick:()=>T(_.id),disabled:m,className:Z("w-full p-2 text-left hover:bg-muted flex items-center gap-2 text-sm transition-colors",m&&"opacity-50"),children:[e.jsxs(_e,{className:"h-8 w-8",children:[e.jsx(ye,{src:_.avatar_url||void 0}),e.jsx(je,{className:"text-xs",children:(_.display_name||_.email_fallback||"?").substring(0,2).toUpperCase()})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:_.display_name||"(no display name)"}),_.email_fallback&&e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:_.email_fallback})]}),m?e.jsx(K,{className:"h-4 w-4 animate-spin"}):e.jsx(be,{className:"h-4 w-4 text-primary"})]},_.id))})})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"text-sm font-semibold",children:"Existing links"}),e.jsx(J,{variant:"outline",children:v.length})]}),v.length===0?e.jsx("div",{className:"text-sm text-muted-foreground p-4 text-center border rounded-lg",children:"No players linked yet."}):e.jsx("div",{className:"border rounded-lg divide-y max-h-[400px] overflow-y-auto",children:v.map(_=>{const F=f===_.id;return e.jsxs("div",{className:"p-3 hover:bg-muted/30 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(te,{name:_.player_name,className:"h-9 w-9"}),e.jsx("div",{className:"font-medium text-sm flex-1 min-w-0 truncate",children:_.player_name}),e.jsx(Ae,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(_e,{className:"h-9 w-9",children:[e.jsx(ye,{src:_.admin_override_avatar_url||_.avatar_url||void 0}),e.jsx(je,{className:"text-xs",children:(_.display_name||_.email||"?").substring(0,2).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:_.display_name||"(no display name)"}),_.email&&e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:_.email})]}),e.jsx(N,{variant:"ghost",size:"sm",onClick:()=>{F?S(null):(S(_.id),g(_.admin_override_avatar_url||""))},title:"Photo lock",children:e.jsx(Ve,{className:Z("h-4 w-4",_.photo_locked?"text-amber-500":"text-muted-foreground")})}),e.jsx(N,{variant:"ghost",size:"sm",onClick:()=>q(_),disabled:l===_.id,className:"text-destructive hover:text-destructive",children:l===_.id?e.jsx(K,{className:"h-4 w-4 animate-spin"}):e.jsx(He,{className:"h-4 w-4"})})]}),F&&e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(M,{htmlFor:`lock-${_.id}`,className:"text-xs",children:"Lock photo (user can't change it)"}),e.jsx(X,{id:`lock-${_.id}`,checked:_.photo_locked,disabled:j===_.id,onCheckedChange:h=>$(_,h,y||_.admin_override_avatar_url)})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(M,{className:"text-xs text-muted-foreground",children:"Admin override photo URL (optional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(P,{value:y,onChange:h=>g(h.target.value),placeholder:"https://...",className:"text-xs h-8"}),e.jsx(N,{size:"sm",onClick:()=>$(_,_.photo_locked,y),disabled:j===_.id,children:j===_.id?e.jsx(K,{className:"h-3 w-3 animate-spin"}):"Save"})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Precedence: admin lock URL â user upload â player photo â default."})]})]})]},_.id)})})]})]})}const xa=[{name:"Aanik Lohani",email:"[email protected]"},{name:"Abbigal Hatton",email:"[email protected]"},{name:"Adam Harvey",email:"[email protected]"},{name:"Aditya Ruhela",email:"[email protected]"},{name:"Aiko Yoshitomi",email:"[email protected]"},{name:"AJ Koller",email:"[email protected]"},{name:"Alex Crum",email:"[email protected]"},{name:"Alex Walker",email:"[email protected]"},{name:"Alexa Schull",email:"[email protected]"},{name:"Alix Truong",email:"[email protected]"},{name:"Alli Phillips",email:"[email protected]"},{name:"Allyce Jones",email:"[email protected]"},{name:"Altaf Merchant",email:"[email protected]"},{name:"Anderson Scarpa",email:"[email protected]"},{name:"Andre Mercado",email:"[email protected]"},{name:"Andrei Daescu",email:"[email protected]"},{name:"Andrew Caldarella",email:"[email protected]"},{name:"Angie Walker",email:"[email protected]"},{name:"Anna Bright",email:"[email protected]"},{name:"Anna Leigh Waters",email:"[email protected]"},{name:"Armaan Bhatia",email:"[email protected]"},{name:"Aryaan Bhatia",email:"[email protected]"},{name:"Ashley Griffith",email:"[email protected]"},{name:"Audrey Brown",email:"[email protected]"},{name:"Augustus Ge",email:"[email protected]"},{name:"Austin Bricker",email:"[email protected]"},{name:"Ava Cavataio",email:"[email protected]"},{name:"Ava Ignatowich",email:"[email protected]"},{name:"Ben Johns",email:"[email protected]"},{name:"Blaine Hovenier",email:"[email protected]"},{name:"Braden Jacobson",email:"[email protected]"},{name:"Brandon French",email:"[email protected]"},{name:"Brooke Buckner",email:"[email protected]"},{name:"Brooke Caruso",email:"[email protected]"},{name:"Caden Nemoff",email:"[email protected]"},{name:"Cailyn Campbell",email:"[email protected]"},{name:"Callie Smith",email:"[email protected]"},{name:"Camden Chaffin",email:"[email protected]"},{name:"Camila Zilveti",email:"[email protected]"},{name:"Carlos Di Laura",email:"[email protected]"},{name:"Cason Campbell",email:"[email protected]"},{name:"Catherine Parenteau",email:"[email protected]"},{name:"Chao Yi Wang",email:"[email protected]"},{name:"Chloe Igleski",email:"[email protected]"},{name:"Christopher Crouch",email:"[email protected]"},{name:"Chris Haworth",email:"[email protected]"},{name:"Christa Gecheva",email:"[email protected]"},{name:"Christian Alshon",email:"[email protected]"},{name:"Christine Trifunovic",email:"[email protected]"},{name:"Chuck Taylor",email:"[email protected]"},{name:"CJ Klinger",email:"[email protected]"},{name:"Collin Johns",email:"[email protected]"},{name:"Connor Allen Mogle",email:"[email protected]"},{name:"Connor Garnett",email:"[email protected]"},{name:"Craig Johnson",email:"[email protected]"},{name:"Danni-Elle Townsend",email:"[email protected]"},{name:"Danny Phillips",email:"[email protected]"},{name:"Daria Walczak",email:"[email protected]"},{name:"Darrian Young",email:"[email protected]"},{name:"Dekel Bar",email:"[email protected]"},{name:"Donald Young",email:"[email protected]"},{name:"Dylan Frazier",email:"[email protected]"},{name:"Ed Perez",email:"[email protected]"},{name:"Ella Cosma",email:"[email protected]"},{name:"Ella Yeh",email:"[email protected]"},{name:"Elsie Hendershot",email:"[email protected]"},{name:"Emma Nelson",email:"[email protected]"},{name:"Eric Oncins",email:"[email protected]"},{name:"Estée Widdershoven",email:"[email protected]"},{name:"Etta Tuionetoa",email:"[email protected]"},{name:"Federico Staksrud",email:"[email protected]"},{name:"Gabriel Joseph",email:"[email protected]"},{name:"Gabriel Tardio",email:"[email protected]"},{name:"Genie Bouchard",email:"[email protected]"},{name:"Genie Erokhina",email:"[email protected]"},{name:"George Rangelov",email:"[email protected]"},{name:"George Wall",email:"[email protected]"},{name:"Giovanna Morelli",email:"[email protected]"},{name:"Grayson Goldin",email:"[email protected]"},{name:"Greg Dow",email:"[email protected]"},{name:"Hannah Blatt",email:"[email protected]"},{name:"Hayden Patriquin",email:"[email protected]"},{name:"Hsiang Wen-Huang",email:"[email protected]"},{name:"Hunter Johnson",email:"[email protected]"},{name:"Indigo Dagnall",email:"[email protected]"},{name:"Irina Tereschenko",email:"[email protected]"},{name:"Isabella Dunlap",email:"[email protected]"},{name:"Ivan Jakovljevic",email:"[email protected]"},{name:"Jace Morris",email:"[email protected]"}
1,{name:"Jack Sock",email:"[email protected]"},{name:"Jackie Kawamoto",email:"[email protected]"},{name:"Jade Kawamoto",email:"[email protected]"},{name:"Jade Rau",email:"[email protected]"},{name:"Jaeda Minniefield",email:"[email protected]"},{name:"Jalina Ingram",email:"[email protected]"},{name:"James Delgado",email:"[email protected]"},{name:"Jaume Martinez Vich",email:"[email protected]"},{name:"Jay Devilliers",email:"[email protected]"},{name:"Jessie Irvine",email:"[email protected]"},{name:"John Cincola",email:"[email protected]"},{name:"John Lucian Goins",email:"[email protected]"},{name:"Jonathan Truong",email:"[email protected]"},{name:"Jorja Johnson",email:"[email protected]"},{name:"Juan Benitez",email:"[email protected]"},{name:"Judit Castillo",email:"[email protected]"},{name:"JW Johnson",email:"[email protected]"},{name:"Kaitlyn Christian",email:"[email protected]"},{name:"Kate Fahey",email:"[email protected]"},{name:"Kenta Miyoshi",email:"[email protected]"},{name:"Kiora Kunimoto",email:"[email protected]"},{name:"Lacy Schneemann",email:"[email protected]"},{name:"Layne Sleeth",email:"[email protected]"},{name:"Lea Jansen",email:"[email protected]"},{name:"Len Yang",email:"[email protected]"},{name:"Lina Padegimaite",email:"[email protected]"},{name:"Lindsey Newman",email:"[email protected]"},{name:"Lingwei Kong",email:"[email protected]"},{name:"Liz Truluck",email:"[email protected]"},{name:"Luana Stanciu",email:"[email protected]"},{name:"Luc Pham",email:"[email protected]"},{name:"Luca Mack",email:"[email protected]"},{name:"Lucas Pascoe",email:"[email protected]"},{name:"Luke Wasson",email:"[email protected]"},{name:"Marcela Hones",email:"[email protected]"},{name:"Mariana Humberg",email:"[email protected]"},{name:"Martin Emmrich",email:"[email protected]"},{name:"Martina Frantova",email:"[email protected]"},{name:"Max Freeman",email:"[email protected]"},{name:"Meghan Dizon",email:"[email protected]"},{name:"Mehvish Safdar",email:"[email protected]"},{name:"Michael Loyd",email:"[email protected]"},{name:"Milan Rane",email:"[email protected]"},{name:"Mitch Hargreaves",email:"[email protected]"},{name:"Mo Alhouni",email:"[email protected]"},{name:"Mohamed Anouar Braham",email:"[email protected]"},{name:"Monica Paolicelli",email:"[email protected]"},{name:"Mota Alhouni",email:"[email protected]"},{name:"Mya Bui",email:"[email protected]"},{name:"Naomi Phuong Nguyen",email:"[email protected]"},{name:"Nicole Conard",email:"[email protected]"},{name:"Noe Khlif",email:"[email protected]"},{name:"Olivia McMillan",email:"[email protected]"},{name:"Pablo Tellez",email:"[email protected]"},{name:"Parris Todd",email:"[email protected]"},{name:"Pat Smith",email:"[email protected]"},{name:"Paula Rives Palau",email:"[email protected]"},{name:"Pesa Teoni",email:"[email protected]"},{name:"Pierina Imparato",email:"[email protected]"},{name:"Polina Libo",email:"[email protected]"},{name:"Purav Raja",email:"[email protected]"},{name:"Rachel Rettger",email:"[email protected]"},{name:"Rachel Rohrabacher",email:"[email protected]"},{name:"Rafa Hewett",email:"[email protected]"},{name:"Rafa Lenhard",email:"[email protected]"},{name:"Riley Newman",email:"[email protected]"},{name:"Roscoe Bellamy",email:"[email protected]"},{name:"Ross Whittaker",email:"[email protected]"},{name:"Ryan Sherry",email:"[email protected]"},{name:"Sahra Dennehy",email:"[email protected]"},{name:"Samantha Parker",email:"[email protected]"},{name:"Sofia Sewing",email:"[email protected]"},{name:"Spartak Rahachou",email:"[email protected]"},{name:"Stefan Auvergne",email:"[email protected]"},{name:"Stephen Madonia",email:"[email protected]"},{name:"Steve Deakin",email:"[email protected]"},{name:"Tam Trinh",email:"[email protected]"},{name:"Tama Shimabukuro",email:"[email protected]"}
1,{name:"Tamaryn Emmrich",email:"[email protected]"},{name:"Tatiana Ruhl",email:"[email protected]"},{name:"Thomas Wilson",email:"[email protected]"},{name:"Tina Pisnik",email:"[email protected]"},{name:"Ting Chieh Wei",email:"[email protected]"},{name:"Tom Protzek",email:"[email protected]"},{name:"Travis Rettenmaier",email:"[email protected]"},{name:"Tyler Loong",email:"[email protected]"},{name:"Tyra Black",email:"[email protected]"},{name:"Tyson McGuffin",email:"[email protected]"},{name:"Valerie Simon",email:"[email protected]"},{name:"Victoria Di Muzio",email:"[email protected]"},{name:"Victoria Simon",email:"[email protected]"},{name:"Wes Burrows",email:"[email protected]"},{name:"Wil Shaffer",email:"[email protected]"},{name:"Will Howells",email:"[email protected]"},{name:"Will MacKinnon",email:"[email protected]"},{name:"Wyatt Stone",email:"[email protected]"},{name:"Xiao Yi Wang-Beckvall",email:"[email protected]"},{name:"Yates Johnson",email:"[email protected]"},{name:"Yuta Funemizu",email:"[email protected]"},{name:"Zane Ford",email:"[email protected]"},{name:"Zane Navratil",email:"[email protected]"},{name:"Zoey Weil",email:"[email protected]"},{name:"Zoeya Khan",email:"[email protected]"}];function ga(){const[a,s]=o.useState(""),[r,t]=o.useState("all"),{data:n=new Set}=Y({queryKey:["admin-pro-roster-linked"],queryFn:async()=>{const{data:l}=await C.from("player_user_links").select("player_name"),d=new Set;return(l||[]).forEach(f=>d.add(String(f.player_name).toLowerCase().trim())),d},staleTime:3e4}),c=o.useMemo(()=>xa.map(l=>({...l,linked:n.has(l.name.toLowerCase().trim())})),[n]),i=o.useMemo(()=>{let l=c;if(r==="linked"?l=l.filter(d=>d.linked):r==="unlinked"&&(l=l.filter(d=>!d.linked)),a.trim()){const d=a.toLowerCase();l=l.filter(f=>f.name.toLowerCase().includes(d)||f.email.toLowerCase().includes(d))}return l},[c,r,a]),p=c.filter(l=>l.linked).length,m=c.length-p,u=l=>{const d=c.filter(S=>!S.linked),f=d.map(S=>S.email).join(", ");navigator.clipboard.writeText(f),w({title:`Copied ${d.length} emails`})};return e.jsxs(H,{title:"Pro Player Roster",icon:Ne,collapsible:!0,defaultOpen:!1,headerAction:e.jsxs(J,{variant:"outline",className:"text-xs",children:[p," / ",c.length," linked"]}),children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Canonical roster of pro players with contact emails. Linked players have an account on the site connected to their pro identity (verified â + photo locked)."}),e.jsxs("div",{className:"grid gap-3 grid-cols-3 mb-4",children:[e.jsx(me,{label:"Total Pros",value:c.length,icon:Ne,variant:"blue"}),e.jsx(me,{label:"Linked",value:p,icon:we,variant:"green"}),e.jsx(me,{label:"Not Linked",value:m,icon:Ye,variant:"amber"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-3",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-sm",children:[e.jsx(Te,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(P,{value:a,onChange:l=>s(l.target.value),placeholder:"Search name or email...",className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(N,{size:"sm",variant:r==="all"?"default":"outline",onClick:()=>t("all"),children:"All"}),e.jsx(N,{size:"sm",variant:r==="linked"?"default":"outline",onClick:()=>t("linked"),children:"Linked"}),e.jsx(N,{size:"sm",variant:r==="unlinked"?"default":"outline",onClick:()=>t("unlinked"),children:"Not Linked"})]}),e.jsxs(N,{size:"sm",variant:"outline",onClick:()=>u(),title:"Copy all unlinked emails",children:[e.jsx(Ze,{className:"h-3.5 w-3.5 mr-1"}),"Copy unlinked emails"]})]}),e.jsx("div",{className:"border rounded-lg divide-y max-h-[500px] overflow-y-auto",children:i.length===0?e.jsx("div",{className:"p-6 text-center text-sm text-muted-foreground",children:"No players match"}):i.map(l=>e.jsxs("div",{className:"p-2.5 flex items-center gap-3 hover:bg-muted/30",children:[e.jsx(te,{name:l.name,className:"h-8 w-8 shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"text-sm font-medium truncate flex items-center gap-1.5",children:[l.name,l.linked&&e.jsx(we,{className:"h-3.5 w-3.5 text-green-600 shrink-0"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground truncate flex items-center gap-1",children:[e.jsx(Xe,{className:"h-3 w-3"}),l.email]})]}),l.linked?e.jsx(J,{variant:"outline",className:"text-green-600 border-green-600/50 text-xs shrink-0",children:"Linked"}):e.jsx(J,{variant:"outline",className:"text-amber-600 border-amber-600/50 text-xs shrink-0",children:"Not Linked"})]},l.email))}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-3",children:["Showing ",i.length," of ",c.length,' pros. To link a "Not Linked" player, scroll down to ',e.jsx("span",{className:"font-medium",children:"Player â Account Links"})," after the user has signed up with their email."]})]})}const fa=[{value:"hidden",label:"Hidden",icon:ea,desc:"Not visible to anyone"},{value:"admin_only",label:"Admin Only",icon:aa,desc:"Only admins can see"},{value:"public",label:"Public",icon:sa,desc:"Visible to all users"}],va=()=>{const{visibility:a,tournament:s}=Fe(),[r,t]=o.useState(!1),n=G(),{toast:c}=ge(),i=async p=>{if(!(p===a||r)){t(!0);try{const{error:m}=await C.from("app_settings").update({value:p,updated_at:new Date().toISOString()}).eq("key","event_guide_visibility");if(m)throw m;n.invalidateQueries({queryKey:["event_guide_visibility"]}),c({title:"Event Guide visibility updated",description:`Set to ${p}`})}catch{c({title:"Failed to update",variant:"destructive"})}finally{t(!1)}}};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-scalable-sm font-semibold text-foreground",children:"Event Guide Visibility"}),s&&e.jsxs("span",{className:"text-scalable-xs text-muted-foreground",children:["Staged for: ",s.display_name||s.name]})]}),e.jsx("div",{className:"flex gap-2",children:fa.map(p=>{const m=p.icon,u=a===p.value;return e.jsxs("button",{onClick:()=>i(p.value),disabled:r,className:Z("flex-1 flex flex-col items-center gap-1 py-2.5 px-2 rounded-lg border text-scalable-xs font-medium transition-all",u?"border-primary bg-primary/10 text-primary":"border-border/30 text-muted-foreground hover:border-border/60"),children:[e.jsx(m,{className:"w-4 h-4"}),p.label]},p.value)})})]})},xe=[{mode:"mlpTeams",label:"Teams (MLP)"},{mode:"mlpPlayers",label:"Players (MLP)"},{mode:"ppaRank",label:"Tour (PPA)"},{mode:"overall",label:"Power"},{mode:"winRate",label:"Win %"},{mode:"clutch",label:"Clutch"}],ue=xe.map(a=>a.mode),Ee=[{key:"ppa",label:"PPA Stats (Pwr Rank / Pt Diff / Pts Won)"},{key:"mlp",label:"MLP Stats (Player Rank / Record / Pt Diff)"}],he=Ee.map(a=>a.key),_a=()=>{const a=G(),{toast:s}
1=ge(),[r,t]=o.useState("PPA"),[n,c]=o.useState(!1),[i,p]=o.useState(!1),[m,u]=o.useState(ue),[l,d]=o.useState(!1),[f,S]=o.useState(""),[y,g]=o.useState(!1),[j,x]=o.useState(he),[v,b]=o.useState(!1);o.useEffect(()=>{(async()=>{const{data:h}=await C.from("app_settings").select("key,value").in("key",["event_calendar_brand","leaderboard_tabs_order","player_stats_sections_order","leaderboard_default_tab"]),L=new Map((h||[]).map(U=>[U.key,U.value])),B=(L.get("event_calendar_brand")||"PPA").toString().toUpperCase().slice(0,3);t(B||"PPA"),p(!0),S((L.get("leaderboard_default_tab")||"").toString());const R=(U,V)=>{if(!U)return V;try{const ee=JSON.parse(U);if(!Array.isArray(ee))return V;const ae=new Set(V),oe=new Set,ce=[];for(const se of ee)ae.has(se)&&!oe.has(se)&&(ce.push(se),oe.add(se));for(const se of V)oe.has(se)||ce.push(se);return ce}catch{return V}};u(R(L.get("leaderboard_tabs_order"),ue)),x(R(L.get("player_stats_sections_order"),he))})()},[]);const E=async()=>{const h=r.trim().toUpperCase().slice(0,3);if(!h){s({title:"Enter 1â3 letters",variant:"destructive"});return}c(!0);try{const{error:L}=await C.from("app_settings").upsert({key:"event_calendar_brand",value:h,updated_at:new Date().toISOString()},{onConflict:"key"});if(L)throw L;t(h),a.invalidateQueries({queryKey:["app_settings","event_calendar_brand"]}),s({title:"Calendar icon updated",description:`Now showing "${h}"`})}catch(L){s({title:"Failed to update",description:L==null?void 0:L.message,variant:"destructive"})}finally{c(!1)}},D=(h,L)=>{const B=[...m],R=h+L;R<0||R>=B.length||([B[h],B[R]]=[B[R],B[h]],u(B))},z=async()=>{d(!0);try{const{error:h}=await C.from("app_settings").upsert({key:"leaderboard_tabs_order",value:JSON.stringify(m),updated_at:new Date().toISOString()},{onConflict:"key"});if(h)throw h;a.invalidateQueries({queryKey:["app_settings","leaderboard_tabs_order"]}),s({title:"Leaderboard tab order saved"})}catch(h){s({title:"Failed to save order",description:h==null?void 0:h.message,variant:"destructive"})}finally{d(!1)}},k=()=>u(ue),T=async h=>{S(h),g(!0);try{const{error:L}=await C.from("app_settings").upsert({key:"leaderboard_default_tab",value:h,updated_at:new Date().toISOString()},{onConflict:"key"});if(L)throw L;a.invalidateQueries({queryKey:["app_settings","leaderboard_default_tab"]}),s({title:"Default leaderboard tab saved"})}catch(L){s({title:"Failed to save",description:L==null?void 0:L.message,variant:"destructive"})}finally{g(!1)}},q=async()=>{S(""),g(!0);try{const{error:h}=await C.from("app_settings").upsert({key:"leaderboard_default_tab",value:"",updated_at:new Date().toISOString()},{onConflict:"key"});if(h)throw h;a.invalidateQueries({queryKey:["app_settings","leaderboard_default_tab"]}),s({title:"Default tab cleared",description:"Will use first tab in order."})}catch(h){s({title:"Failed to clear",description:h==null?void 0:h.message,variant:"destructive"})}finally{g(!1)}},$=(h,L)=>{const B=[...j],R=h+L;R<0||R>=B.length||([B[h],B[R]]=[B[R],B[h]],x(B))},_=async()=>{b(!0);try{const{error:h}=await C.from("app_settings").upsert({key:"player_stats_sections_order",value:JSON.stringify(j),updated_at:new Date().toISOString()},{onConflict:"key"});if(h)throw h;a.invalidateQueries({queryKey:["app_settings","player_stats_sections_order"]}),s({title:"Player stats section order saved"})}catch(h){s({title:"Failed to save",description:h==null?void 0:h.message,variant:"destructive"})}finally{b(!1)}},F=()=>x(he);return e.jsx(H,{title:"Nav Display",className:"mt-6",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(M,{htmlFor:"cal-brand",className:"text-scalable-sm font-semibold",children:"Event Calendar Icon Label"}),e.jsxs("p",{className:"text-scalable-xs text-muted-foreground",children:["3-letter label inside the calendar nav icon. Flip to ",e.jsx("code",{children:"MLP"})," when the season starts; revert to ",e.jsx("code",{children:"PPA"})," after."]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(P,{id:"cal-brand",value:r,onChange:h=>t(h.target.value.toUpperCase().slice(0,3)),maxLength:3,className:"w-24 uppercase tracking-wider font-mono",disabled:!i||n}),e.jsxs(N,{onClick:E,disabled:!i||n,children:[n&&e.jsx(K,{className:"w-4 h-4 mr-1 animate-spin"}),"Save"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(M,{className:"text-scalable-sm font-semibold",children:"Leaderboard Tab Order"}),e.jsx("p",{className:"text-scalable-xs text-muted-foreground",children:"Reorder the Stats leaderboard tabs. Top of the list = first tab."}),e.jsx("div",{className:"space-y-1.5",children:m.map((h,L)=>{const B=xe.find(R=>R.mode===h);return B?e.jsxs("div",{className:Z("flex items-center gap-2 rounded-lg border border-border/40 bg-muted/20 px-3 py-2"),children:[e.jsxs("span",{className:"text-scalable-xs text-muted-foreground w-5",children:[L+1,"."]}),e.jsx("span",{className:"flex-1 text-scalable-sm font-medium",children:B.label}
1),e.jsx("span",{className:"text-[10px] text-muted-foreground/60 font-mono",children:h}),e.jsx(N,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>D(L,-1),disabled:L===0,"aria-label":"Move up",children:e.jsx(ke,{className:"w-4 h-4"})}),e.jsx(N,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>D(L,1),disabled:L===m.length-1,"aria-label":"Move down",children:e.jsx(Ce,{className:"w-4 h-4"})})]},h):null})}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsxs(N,{onClick:z,disabled:l,children:[l&&e.jsx(K,{className:"w-4 h-4 mr-1 animate-spin"}),"Save Order"]}),e.jsx(N,{variant:"outline",onClick:k,disabled:l,children:"Reset to Default"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(M,{className:"text-scalable-sm font-semibold",children:"Default Leaderboard Tab"}),e.jsx("p",{className:"text-scalable-xs text-muted-foreground",children:"Which tab loads first when users open the Stats page. Independent of tab order â clear to fall back to the first tab in the order above."}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[xe.map(h=>{const L=f===h.mode;return e.jsx(N,{size:"sm",variant:L?"default":"outline",disabled:y,onClick:()=>T(h.mode),children:h.label},h.mode)}),e.jsx(N,{size:"sm",variant:"ghost",disabled:y||!f,onClick:q,children:"Clear"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(M,{className:"text-scalable-sm font-semibold",children:"Player Profile Stat Sections"}),e.jsx("p",{className:"text-scalable-xs text-muted-foreground",children:"Reorder the PPA Stats and MLP Stats blocks shown on player profiles. Put MLP first when the MLP season starts."}),e.jsx("div",{className:"space-y-1.5",children:j.map((h,L)=>{const B=Ee.find(R=>R.key===h);return B?e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-border/40 bg-muted/20 px-3 py-2",children:[e.jsxs("span",{className:"text-scalable-xs text-muted-foreground w-5",children:[L+1,"."]}),e.jsx("span",{className:"flex-1 text-scalable-sm font-medium",children:B.label}),e.jsx("span",{className:"text-[10px] text-muted-foreground/60 font-mono",children:h}),e.jsx(N,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>$(L,-1),disabled:L===0,"aria-label":"Move up",children:e.jsx(ke,{className:"w-4 h-4"})}),e.jsx(N,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>$(L,1),disabled:L===j.length-1,"aria-label":"Move down",children:e.jsx(Ce,{className:"w-4 h-4"})})]},h):null})}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsxs(N,{onClick:_,disabled:v,children:[v&&e.jsx(K,{className:"w-4 h-4 mr-1 animate-spin"}),"Save Order"]}),e.jsx(N,{variant:"outline",onClick:F,disabled:v,children:"Reset to Default"})]})]})]})})},ya=[{value:"2025",label:"2025 Regular Season"},{value:"2025_cup",label:"2025 MLP Cup"},{value:"2026",label:"2026 Regular Season",requires2026:!0},{value:"2026_one_level",label:"2026 One Level",requires2026:!0}],ja=[{value:"premier",label:"Premier"},{value:"challenger",label:"Challenger"}];function ba(){const a=G(),{data:s,isLoading:r,refetch:t}=ze({includeFull:!0}),[n,c]=o.useState("prod"),[i,p]=o.useState("2025"),[m,u]=o.useState("premier"),[l,d]=o.useState(!1),[f,S]=o.useState(!1);o.useEffect(()=>{s&&(c(s.env),p(s.active_season),u(s.active_level),d(!!s.two_thousand_twenty_six_enabled))},[s]);const y=!!s&&(n!==s.env||i!==s.active_season||m!==s.active_level||l!==!!s.two_thousand_twenty_six_enabled),g=async()=>{S(!0);try{const x=[{key:"mlp_env",value:n},{key:"mlp_active_season",value:i},{key:"mlp_active_level",value:m},{key:"mlp_2026_enabled",value:l?"true":"false"}],{error:v}=await C.from("app_settings").upsert(x,{onConflict:"key"});if(v)throw v;w.success("MLP config saved"),await Promise.all([t(),a.invalidateQueries({queryKey:["mlp-team-league-standings"]}),a.invalidateQueries({queryKey:["mlp-active-config"]})])}catch(x){w.error(`Failed to save: ${(x==null?void 0:x.message)||x}`)}finally{S(!1)}},j=(i==="2026"||i==="2026_one_level")&&!l;return e.jsx(H,{title:"MLP Team League",icon:ta,children:r&&!s?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(K,{className:"h-4 w-4 animate-spin"})," Loading configâ¦"]}):e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Controls which MLP Team League IDs the app uses. PROD targets live data; DEV targets the staging environment (no 2026 setup yet). 2026 paths are gated until the kill-switch below is enabled."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(M,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Environment"}),e.jsx("div",{className:"flex gap-2",children:["prod","dev"].map(x=>e.jsx(N,{variant:n===x?"default":"outline",size:"sm",onClick:()=>c(x),children:x.toUpperCase()},x))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(M,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Active Season"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:ya.map(x=>{const v=!!x.requires2026&&!l;return e.jsxs(N,{variant:i===x.value?"default":"outline",size:"sm",disabled:v,onClick:()=>
1p(x.value),children:[x.label,x.requires2026&&e.jsx(J,{variant:"secondary",className:"ml-2 text-[10px]",children:"2026"})]},x.value)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(M,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Default Level"}),e.jsx("div",{className:"flex gap-2",children:ja.map(x=>e.jsx(N,{variant:m===x.value?"default":"outline",size:"sm",onClick:()=>u(x.value),children:x.label},x.value))}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"UI shows both with a toggle; this sets which loads first."})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3",children:[e.jsxs("div",{children:[e.jsx(M,{className:"text-sm",children:"Enable 2026 paths"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Off by default. Turn on once 2026 is configured in the chosen environment."})]}),e.jsx(X,{checked:l,onCheckedChange:d})]}),j&&e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-amber-500/40 bg-amber-500/10 p-2 text-xs text-amber-200",children:[e.jsx(la,{className:"h-4 w-4 flex-shrink-0 mt-0.5"}),e.jsx("span",{children:"Selected a 2026 season but the 2026 flag is off â data calls will be blocked until you enable it."})]}),(s==null?void 0:s.resolved_season_division_uuid)&&e.jsxs("div",{className:"rounded-md bg-muted/30 p-2 font-mono text-[10px] text-muted-foreground break-all",children:["Resolved season-division UUID: ",s.resolved_season_division_uuid]}),e.jsxs(N,{onClick:g,disabled:!y||f,size:"sm",children:[f?e.jsx(K,{className:"h-4 w-4 mr-1 animate-spin"}):null,"Save MLP Config"]}),e.jsx(Na,{queryClient:a})]})})}function Na({queryClient:a}){const[s,r]=o.useState(()=>Ke()),t=c=>{const i=c?"dev":null;Ue(i),r(i),a.invalidateQueries({queryKey:["mlp-active-config"]}),a.invalidateQueries({queryKey:["mlp-team-league-standings"]}),a.invalidateQueries({queryKey:["mlp-team-roster"]}),a.invalidateQueries({queryKey:["mlp-event-bracket-api"]}),w.success(c?"Now viewing MLP DEV data (this device only)":"Reverted to global MLP env")},n=s==="dev";return e.jsxs("div",{className:"mt-3 rounded-md border border-purple-500/30 bg-purple-500/5 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(na,{className:"h-4 w-4 mt-0.5 text-purple-300"}),e.jsxs("div",{children:[e.jsx(M,{className:"text-sm font-medium",children:"Preview MLP DEV API"}),e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-0.5",children:["This device only. Hits api.pickleballdev.net so you can test dev tournaments without affecting other users. Tip: append ",e.jsx("code",{children:"?mlpEnv=dev"})," to any URL for a one-off."]})]})]}),e.jsx(X,{checked:n,onCheckedChange:t})]}),n&&e.jsx(J,{variant:"outline",className:"mt-2 border-purple-400/50 text-purple-200 text-[10px]",children:"DEV preview active"})]})}function wa(){const a=G(),{teamStandings:s,configured:r}=$e(),[t,n]=o.useState("2025"),[c,i]=o.useState("all"),{data:p}=Y({queryKey:["mlp-exhibition-teams-roster-dropdown"],queryFn:async()=>{const{data:y}=await C.from("mlp_team_meta").select("team_uuid, display_name").eq("is_exhibition",!0).order("display_name");return(y||[]).map(g=>({team_uuid:g.team_uuid,team_title:g.display_name||"Untitled exhibition team",is_exhibition:!0}))}}),m=o.useMemo(()=>[...s,...p||[]],[s,p]),{data:u,isLoading:l}=Y({queryKey:["mlp-rosters-admin",t],queryFn:async()=>{const{data:y,error:g}=await C.from("mlp_team_rosters").select("id, team_uuid, team_title, season, player_name, player_first_name, player_last_name, role, jersey_number, is_active").eq("season",t).order("team_title").order("player_last_name");if(g)throw g;return y||[]}}),d=o.useMemo(()=>u?c==="all"?u:u.filter(y=>y.team_uuid===c):[],[u,c]),f=o.useMemo(()=>{const y=new Map;for(const g of d){const j=g.team_uuid;y.has(j)||y.set(j,[]),y.get(j).push(g)}return Array.from(y.entries()).map(([g,j])=>{var x,v;return{uuid:g,title:((x=j[0])==null?void 0:x.team_title)||((v=m.find(b=>b.team_uuid===g))==null?void 0:v.team_title)||g,rows:j}})},[d,m]),S=async y=>{const{error:g}=await C.from("mlp_team_rosters").delete().eq("id",y);g?w({title:"Delete failed",description:g.message,variant:"destructive"}):(w({title:"Removed"}),a.invalidateQueries({queryKey:["mlp-rosters-admin",t]}),a.invalidateQueries({queryKey:["mlp-team-roster"]}),a.invalidateQueries({queryKey:["mlp-player-current-team"]}))};return e.jsx(H,{title:"MLP Team Rosters",icon:Me,description:"Hand-curated roster fallback (used while upstream API roster is unavailable)",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(M,{className:"text-xs",children:"Season"}),e.jsxs(Q,{value:t,onValueChange:n,children:[e.jsx(O,{className:"h-8 w-32",children:e.jsx(W,{})}),e.jsxs(I,{children:[e.jsx(A,{value:"2025",children:"2025"}),e.jsx(A,{value:"2026",children:"2026"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(M,{className:"text-xs",children:"Team"}),e.jsxs(Q,{value:c,onValueChange:i,children:[e.jsx(O,{className:"h-8 w-44",children:e.jsx(W,{})}),e.jsxs(I,{children:[e.jsx(A,{value:"all",children:"All teams"}),m.map(y=>e.jsx(A,{value:y.team_uuid,children:y.team_title},y.team_uuid))]})]})]}),e.jsxs(J,{variant:"outline",className:"text-[10px]",children:[(u==null?void 0:u.length)||0," entries"]})]}),e.jsx(Ca,{season:t,teamStandings:m,configured:r}),e.jsx(ka,{season:t,teamStandings:m}),l?e.jsx("div",{className:"flex items-center justify-center py-8 text-muted-foreground",children:e.jsx(K,{className:"h-4 w-4 animate-spin"})}):f.length===0?e.jsx("div",{className:"text-center py-6 text-xs text-muted-foreground",children:"No roster entries yet. Use the bulk paste below."}):e.jsx("div",{className:"space-y-3 max-h-[500px] overflow-y-auto",children:f.map(y=>e.jsxs("div",{className:"rounded-lg border border-border/60 p-2",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5 px-1",children:[e.jsx("p",{className:"font-score text-sm",children:y.title}),e.jsx(J,{variant:"secondary",className:"text-[9px] h-4 px-1.5",children:y.rows.length})]}),e.jsx("div",{className:"space-y-1",children:y.rows.map(g=>e.jsx(Sa,{row:g,season:t,teamStandings:m,onChanged:()=>{a.invalidateQueries({queryKey:["mlp-rosters-admin",t]}),a.invalidateQueries({queryKey:["mlp-team-roster"]}),a.invalidateQueries({queryKey:["mlp-player-current-team"]})},onDelete:()=>S(g.id)},g.id))})]},y.uuid))})]})})}function ka({season:a,teamStandings:s}){const r=G(),[t,n]=o.useState(""),[c,i]=o.useState(""),[p,m]=o.useState("player"),[u,l]=o.useState(!1),d=async()=>
1{if(!t||!c.trim())return;l(!0);const f=s.find(j=>j.team_uuid===t),S=c.trim(),y=S.split(/\s+/),{error:g}=await C.from("mlp_team_rosters").insert({team_uuid:t,team_title:f==null?void 0:f.team_title,season:a,player_name:S,player_first_name:y.slice(0,-1).join(" ")||null,player_last_name:y.length>1?y[y.length-1]:null,role:p,is_exhibition:!!(f!=null&&f.is_exhibition)});l(!1),g?w({title:"Add failed",description:g.message,variant:"destructive"}):(w({title:"Added"}),i(""),r.invalidateQueries({queryKey:["mlp-rosters-admin",a]}),r.invalidateQueries({queryKey:["mlp-team-roster"]}),r.invalidateQueries({queryKey:["mlp-player-current-team"]}))};return e.jsxs("div",{className:"rounded-lg border border-border/60 p-3 space-y-2",children:[e.jsx("p",{className:"text-xs font-score uppercase tracking-wide text-muted-foreground",children:"Add single player"}),e.jsxs("div",{className:"grid grid-cols-12 gap-2",children:[e.jsxs(Q,{value:t,onValueChange:n,children:[e.jsx(O,{className:"h-8 col-span-5",children:e.jsx(W,{placeholder:"Team"})}),e.jsx(I,{children:s.map(f=>e.jsxs(A,{value:f.team_uuid,children:[f.team_title,f.is_exhibition?" (Exhibition)":""]},f.team_uuid))})]}),e.jsx(P,{className:"h-8 col-span-4",placeholder:"Player name",value:c,onChange:f=>i(f.target.value)}),e.jsxs(Q,{value:p,onValueChange:m,children:[e.jsx(O,{className:"h-8 col-span-2",children:e.jsx(W,{})}),e.jsxs(I,{children:[e.jsx(A,{value:"player",children:"Player"}),e.jsx(A,{value:"captain",children:"Captain"}),e.jsx(A,{value:"co_captain",children:"Co-Captain"})]})]}),e.jsx(N,{size:"sm",className:"h-8 col-span-1 px-0",onClick:d,disabled:u||!t||!c.trim(),children:e.jsx(le,{className:"h-3.5 w-3.5"})})]})]})}function Ca({season:a,teamStandings:s,configured:r}){const t=G(),[n,c]=o.useState(""),[i,p]=o.useState(!1),[m,u]=o.useState(null),l=o.useMemo(()=>{const g=new Map;for(const j of s)g.set(j.team_title.toLowerCase(),{uuid:j.team_uuid,title:j.team_title}),j.team_abbreviation&&g.set(j.team_abbreviation.toLowerCase(),{uuid:j.team_uuid,title:j.team_title}),j.team_slug&&g.set(j.team_slug.toLowerCase(),{uuid:j.team_uuid,title:j.team_title});return g},[s]),d=g=>{const j=g.split(/\r?\n/).map(D=>D.trim()).filter(Boolean),x=[],v=[];let b=0;const E=(j[0]||"").toLowerCase();E.includes("team")&&E.includes("player")&&(b=1);for(let D=b;D<j.length;D++){const k=j[D].split(/[,\t]/).map(R=>R.trim().replace(/^["']|["']$/g,""));if(k.length<2){v.push(`Line ${D+1}: needs at least Team, Player`);continue}const[T,q,$="player",_=""]=k,F=l.get(T.toLowerCase());if(!F){v.push(`Line ${D+1}: unknown team "${T}"`);continue}const h=q.trim();if(!h){v.push(`Line ${D+1}: missing player name`);continue}const L=h.split(/\s+/),B=["player","captain","co_captain","co-captain"].includes($.toLowerCase().replace(/\s+/g,"_"))?$.toLowerCase().replace(/[\s-]+/g,"_").replace("co_captain","co_captain"):"player";x.push({team_uuid:F.uuid,team_title:F.title,player_name:h,first:L.slice(0,-1).join(" ")||"",last:L.length>1?L[L.length-1]:"",role:B,jersey:_||null,lineNo:D+1})}return{rows:x,errors:v}},f=()=>{const{rows:g,errors:j}=d(n);u({valid:g.length,invalid:j.length,errors:j.slice(0,10)})},S=async()=>{const{rows:g,errors:j}=d(n);if(g.length===0){w({title:"Nothing to import",description:j.join(` 2`)||"Empty input",variant:"destructive"});return}p(!0);let x=0,v=0;const b=[];for(let E=0;E<g.length;E+=100){const D=g.slice(E,E+100).map(T=>({team_uuid:T.team_uuid,team_title:T.team_title,season:a,player_name:T.player_name,player_first_name:T.first||null,player_last_name:T.last||null,role:T.role,jersey_number:T.jersey})),{error:z,count:k}=await C.from("mlp_team_rosters").upsert(D,{onConflict:"team_uuid,season,player_name",ignoreDuplicates:!1,count:"exact"});if(z)for(const T of D){const{error:q}=await C.from("mlp_team_rosters").insert(T);q&&q.code!=="23505"?(v+=1,b.length<5&&b.push(`${T.player_name}: ${q.message}`)):x+=1}else x+=k||D.length}p(!1),c(""),u(null),t.invalidateQueries({queryKey:["mlp-rosters-admin",a]}),t.invalidateQueries({queryKey:["mlp-team-roster"]}),t.invalidateQueries({queryKey:["mlp-player-current-team"]}),w({title:`Imported ${x} entries`,description:v>0?`${v} failed. ${b.join("; ")}`:`Season: ${a}${j.length?` ⢠${j.length} skipped lines`:""}`})},y=async()=>
2{if(!confirm(`Delete ALL ${a} roster entries? This cannot be undone.`))return;const{error:g}=await C.from("mlp_team_rosters").delete().eq("season",a);g?w({title:"Clear failed",description:g.message,variant:"destructive"}):(w({title:`Cleared ${a} rosters`}),t.invalidateQueries({queryKey:["mlp-rosters-admin",a]}),t.invalidateQueries({queryKey:["mlp-team-roster"]}))};return e.jsxs("div",{className:"rounded-lg border border-border/60 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs font-score uppercase tracking-wide text-muted-foreground flex items-center gap-1.5",children:[e.jsx(ie,{className:"h-3 w-3"})," Bulk paste from spreadsheet"]}),e.jsxs(N,{variant:"ghost",size:"sm",className:"h-6 text-[10px] text-destructive",onClick:y,children:["Clear ",a]})]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground leading-snug",children:["Paste CSV or tab-separated. Columns: ",e.jsx("code",{className:"bg-muted/50 px-1 rounded",children:"Team, Player, Role, Jersey"}),". Team can be full name, abbreviation, or slug. Role is optional (player/captain/co_captain). Header row OK.",!r&&e.jsx("span",{className:"text-amber-500",children:" â Standings not loaded â team matching may fail."})]}),e.jsx(ve,{rows:6,value:n,onChange:g=>c(g.target.value),placeholder:`Team,Player,Role,Jersey 3St. Louis Shock,Andrei Daescu,player,7 4Dallas Flash,Anna Bright,captain,1`,className:"text-xs font-mono"}),m&&e.jsxs("div",{className:"text-[10px] text-muted-foreground bg-muted/30 rounded p-2",children:["Preview: ",e.jsxs("span",{className:"text-primary font-score",children:[m.valid," valid"]}),", ",e.jsxs("span",{className:"text-destructive font-score",children:[m.invalid," invalid"]}),m.errors.length>0&&e.jsx("ul",{className:"mt-1 space-y-0.5",children:m.errors.map((g,j)=>e.jsxs("li",{children:["⢠",g]},j))})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(N,{size:"sm",variant:"outline",className:"h-7",onClick:f,disabled:!n.trim(),children:"Preview"}),e.jsxs(N,{size:"sm",className:"h-7",onClick:S,disabled:i||!n.trim(),children:[i&&e.jsx(K,{className:"h-3 w-3 animate-spin mr-1"}),"Import"]})]})]})}function Sa({row:a,season:s,teamStandings:r,onChanged:t,onDelete:n}){const[c,i]=o.useState(!1),[p,m]=o.useState(a.player_name),[u,l]=o.useState(a.team_uuid),[d,f]=o.useState(a.role||"player"),[S,y]=o.useState(a.jersey_number||""),[g,j]=o.useState(!1),x=async()=>{const b=p.trim();if(!b||!u)return;j(!0);const E=r.find(k=>k.team_uuid===u),D=b.split(/\s+/),{error:z}=await C.from("mlp_team_rosters").update({player_name:b,player_first_name:D.slice(0,-1).join(" ")||null,player_last_name:D.length>1?D[D.length-1]:null,team_uuid:u,team_title:(E==null?void 0:E.team_title)||a.team_title,role:d,jersey_number:S.trim()||null}).eq("id",a.id);j(!1),z?w({title:"Save failed",description:z.code==="23505"?`Duplicate: "${b}" is already on this team for ${s}.`:z.message,variant:"destructive"}):(w({title:"Updated"}),i(!1),t())},v=()=>{i(!1),m(a.player_name),l(a.team_uuid),f(a.role||"player"),y(a.jersey_number||"")};return c?e.jsxs("div",{className:"rounded bg-muted/40 border border-border/60 p-2 space-y-1.5",children:[e.jsxs("div",{className:"grid grid-cols-12 gap-1.5",children:[e.jsx(P,{className:"h-7 text-xs col-span-12",value:p,onChange:b=>m(b.target.value),placeholder:"Player name"}),e.jsxs(Q,{value:u,onValueChange:l,children:[e.jsx(O,{className:"h-7 text-xs col-span-7",children:e.jsx(W,{placeholder:"Team"})}),e.jsx(I,{children:r.map(b=>e.jsx(A,{value:b.team_uuid,children:b.team_title},b.team_uuid))})]}),e.jsxs(Q,{value:d,onValueChange:f,children:[e.jsx(O,{className:"h-7 text-xs col-span-3",children:e.jsx(W,{})}),e.jsxs(I,{children:[e.jsx(A,{value:"player",children:"Player"}),e.jsx(A,{value:"captain",children:"Captain"}),e.jsx(A,{value:"co_captain",children:"Co-Captain"})]})]}),e.jsx(P,{className:"h-7 text-xs col-span-2",value:S,onChange:b=>y(b.target.value),placeholder:"#"})]}),e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(N,{size:"sm",variant:"ghost",className:"h-6 px-2",onClick:v,children:e.jsx(fe,{className:"h-3 w-3"})}),e.jsx(N,{size:"sm",className:"h-6 px-2",onClick:x,disabled:g||!p.trim()||!u,children:g?e.jsx(K,{className:"h-3 w-3 animate-spin"}):e.jsx(Re,{className:"h-3 w-3"})})]})]}):e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 rounded bg-muted/30",children:[e.jsx("span",{className:"flex-1 text-xs truncate",children:a.player_name}),a.role!=="player"&&e.jsx(J,{variant:"outline",className:"text-[9px] h-4 px-1",children:a.role}),a.jersey_number&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["#",a.jersey_number]}),e.jsx(N,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:()=>i(!0),children:e.jsx(qe,{className:"h-3 w-3"})}),e.jsx(N,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:n,children:e.jsx(ne,{className:"h-3 w-3"})})]})}function La(a){return a.toLowerCase().trim().replace(/['â`]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Pa(){const a=G(),{data:s,isLoading:r}=Y({queryKey:["mlp-exhibition-teams"],queryFn:async()=>{const{data:n,error:c}=await C.from("mlp_team_meta").select("*").eq("is_exhibition",!0).order("display_name");if(c)throw c;return n||[]}}),t=()=>{a.invalidateQueries({queryKey:["mlp-exhibition-teams"]}),a.invalidateQueries({queryKey:["team-avatar-urls"]}),a.invalidateQueries({queryKey:["mlp-rosters-admin"]})};return e.jsx(H,{title:"MLP Exhibition Teams",icon:ra,description:"Non-league teams (college, international, etc.) that appear on team pages but are excluded from MLP stats and leaderboards.",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx(Ta,{onAdded:t}),r?e.jsx("div",{className:"flex items-center justify-center py-6 text-muted-foreground",children:e.jsx(K,{className:"h-4 w-4 animate-spin"})}):!s||s.length===0?e.jsx("div",{className:"text-center py-4 text-xs text-muted-foreground",children:"No exhibition teams yet. Add one above."}):e.jsx("div",{className:"space-y-1.5",children:s.map(n=>e.jsx(Aa,{team:n,onChanged:t},n.team_uuid))})]})})}function Ta({onAdded:a}){const[s,r]=o.useState(""),[t,n]=o.useState(""),[c,i]=o.useState(null),[p,m]=o.useState(!1),u=async()=>{const l=s.trim();if(l){m(!0);try{const d=La(l);let f=null;if(c){const g=(c.name.split(".").pop()||"jpg").toLowerCase(),j=`${d}.${g}`,{error:x}=await C.storage.from("team-avatars").upload(j,c,{upsert:!0,contentType:c.type});if(x)throw x;const{data:v}=C.storage.from("team-avatars").getPublicUrl(j);f=v.publicUrl||null}const S=crypto.randomUUID(),{error:y}=await C.from("mlp_team_meta").insert({team_uuid:S,display_name:l,avatar_url:f,is_exhibition:!0,exclude_from_stats:!0,notes:t.trim()||null});if(y)throw y;w({title:"Exhibition team added",description:l}),r(""),n(""),i(null),a()}catch(d){w({title:"Add failed",description:d.message,variant:"destructive"})}finally{m(!1)}}};return e.jsxs("div",{className:"rounded-lg border border-dashed border-border/60 p-3 space-y-2",children:[e.jsxs("p",{className:"text-xs font-score uppercase tracking-wide text-muted-foreground flex items-center gap-1.5",children:[e.jsx(le,{className:"h-3 w-3"})," Add exhibition team"]}),e.jsxs("div",{className:"grid grid-cols-12 gap-2",children:[e.jsxs("div",{className:"col-span-6",children:[e.jsx(M,{className:"text-[10px] text-muted-foreground",children:"Team name"}),e.jsx(P,{className:"h-8",value:s,onChange:l=>r(l.target.value),placeholder:"e.g. Team Australia, College All-Stars"})]}),e.jsxs("div",{className:"col-span-6",children:[e.jsxs(M,{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[e.jsx(ie,{className:"h-2.5 w-2.5"})," Avatar (JPG / PNG / WEBP)"]}),e.jsx(P,{type:"file",accept:"image/jpeg,image/png,image/webp",className:"h-8 text-xs file:text-xs",onChange:l=>{var d;return i(((d=l.target.files)==null?void 0:d[0])||null)}})]}),e.jsxs("div",{className:"col-span-12",children:[e.jsx(M,{className:"text-[10px] text-muted-foreground",children:"Notes (optional)"}),e.jsx(ve,{rows:2,value:t,onChange:l=>n(l.target.value),placeholder:"Origin, captain, season, etc.",className:"text-xs"})]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(N,{size:"sm",className:"h-7",onClick:u,disabled:p||!s.trim(),children:[p&&e.jsx(K,{className:"h-3 w-3 animate-spin mr-1"}),"Add team"]})})]})}function Aa({team:a,onChanged:s}){const[r,t]=o.useState(!1),n=async()=>
4{if(!confirm(`Delete exhibition team "${a.display_name}"? Any roster players linked to it will become orphaned (not deleted).`))return;t(!0);const{error:c}=await C.from("mlp_team_meta").delete().eq("team_uuid",a.team_uuid);t(!1),c?w({title:"Delete failed",description:c.message,variant:"destructive"}):(w({title:"Removed"}),s())};return e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded bg-muted/30 border border-border/40",children:[a.avatar_url?e.jsx("img",{src:a.avatar_url,alt:a.display_name||"team",className:"h-7 w-7 rounded object-cover bg-muted"}):e.jsx("div",{className:"h-7 w-7 rounded bg-muted flex items-center justify-center text-[9px] text-muted-foreground",children:"â"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs font-score truncate",children:a.display_name||a.team_uuid}),a.notes&&e.jsx("p",{className:"text-[10px] text-muted-foreground truncate",children:a.notes})]}),e.jsx(J,{variant:"outline",className:"text-[9px] h-4 px-1.5 border-amber-500/40 text-amber-600 dark:text-amber-400",children:"Exhibition"}),e.jsx("code",{className:"text-[9px] text-muted-foreground hidden sm:inline",children:a.team_uuid.slice(0,8)}),e.jsx(N,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:n,disabled:r,children:e.jsx(ne,{className:"h-3 w-3"})})]})}function Ma(){const a=[];for(let s=1;s<=8;s++)a.push({bracket:"WB",round_number:1,round_label:"WB Round 1",match_code:`WB-R1-M${s}`,feeder_winner_code:null,feeder_loser_code:null});for(let s=1;s<=8;s++)a.push({bracket:"WB",round_number:2,round_label:"WB Round 2",match_code:`WB-R2-M${s}`,feeder_winner_code:`WB-R1-M${s}`,feeder_loser_code:null});for(let s=1;s<=4;s++)a.push({bracket:"WB",round_number:3,round_label:"WB Quarterfinals",match_code:`WB-QF-M${s}`,feeder_winner_code:`WB-R2-M${2*s-1}`,feeder_loser_code:`WB-R2-M${2*s}`});for(let s=1;s<=2;s++)a.push({bracket:"WB",round_number:4,round_label:"WB Semifinals",match_code:`WB-SF-M${s}`,feeder_winner_code:`WB-QF-M${2*s-1}`,feeder_loser_code:`WB-QF-M${2*s}`});a.push({bracket:"WB",round_number:5,round_label:"WB Final",match_code:"WB-F",feeder_winner_code:"WB-SF-M1",feeder_loser_code:"WB-SF-M2"});for(let s=1;s<=4;s++)a.push({bracket:"LB",round_number:1,round_label:"LB Round 1",match_code:`LB-R1-M${s}`,feeder_winner_code:`WB-R1-M${2*s-1}`,feeder_loser_code:`WB-R1-M${2*s}`});for(let s=1;s<=8;s++)a.push({bracket:"LB",round_number:2,round_label:"LB Round 2",match_code:`LB-R2-M${s}`,feeder_winner_code:`WB-R2-M${s}`,feeder_loser_code:s%2===1?`LB-R1-M${Math.ceil(s/2)}`:null});for(let s=1;s<=4;s++)a.push({bracket:"LB",round_number:3,round_label:"LB Round 3",match_code:`LB-R3-M${s}`,feeder_winner_code:`LB-R2-M${2*s-1}`,feeder_loser_code:`LB-R2-M${2*s}`});for(let s=1;s<=4;s++)a.push({bracket:"LB",round_number:4,round_label:"LB Round 4",match_code:`LB-R4-M${s}`,feeder_winner_code:`WB-QF-M${s}`,feeder_loser_code:`LB-R3-M${s}`});for(let s=1;s<=2;s++)a.push({bracket:"LB",round_number:5,round_label:"LB Round 5",match_code:`LB-R5-M${s}`,feeder_winner_code:`LB-R4-M${2*s-1}`,feeder_loser_code:`LB-R4-M${2*s}`});for(let s=1;s<=2;s++)a.push({bracket:"LB",round_number:6,round_label:"LB Round 6",match_code:`LB-R6-M${s}`,feeder_winner_code:`WB-SF-M${s}`,feeder_loser_code:`LB-R5-M${s}`});return a.push({bracket:"LB",round_number:7,round_label:"LB Semifinal",match_code:"LB-SF",feeder_winner_code:"LB-R6-M1",feeder_loser_code:"LB-R6-M2"}),a.push({bracket:"LB",round_number:8,round_label:"LB Final",match_code:"LB-F",feeder_winner_code:"WB-F",feeder_loser_code:"LB-SF"}),a.push({bracket:"GF",round_number:1,round_label:"Grand Final",match_code:"GF1",feeder_winner_code:"WB-F",feeder_loser_code:"LB-F"}),a.push({bracket:"GF",round_number:2,round_label:"Bracket Reset",match_code:"GF2",feeder_winner_code:"GF1",feeder_loser_code:"GF1",if_necessary:!0}),a}function Ra({tournamentId:a,bracketConfig:s,onConfigSave:r}){const t=G(),[n,c]=o.useState(!0),[i,p]=o.useState(JSON.stringify(s||{},null,2)),{data:m,isLoading:u}=Y({queryKey:["mlp-de-matchups",a],queryFn:async()=>{const{data:x,error:v}=await C.from("mlp_event_matchups").select("id, tournament_id, stage, bracket, round_number, round_label, match_order, match_code, feeder_winner_code, feeder_loser_code, if_necessary, manual_override, team1_uuid, team2_uuid, team1_name, team2_name, team1_seed, team2_seed, team1_score, team2_score, status, scheduled_at, court").eq("tournament_id",a).eq("stage","double_elim").order("bracket",{ascending:!0,nullsFirst:!1}).order("round_number",{ascending:!0,nullsFirst:!1}).order("match_order",{ascending:!0});if(v)throw v;return x||[]}}),l=()=>{t.invalidateQueries({queryKey:["mlp-de-matchups",a]}),t.invalidateQueries({queryKey:["mlp-event-matchups-curated",a]})},d=async(x,v)=>{const{error:b}=await C.from("mlp_event_matchups").update({...v,manual_override:!0}).eq("id",x);if(b){w({title:"Update failed",description:b.message,variant:"destructive"});return}l()},f=async x=>{if(!confirm("Delete this matchup?"))return;const{error:v}=await C.from("mlp_event_matchups").delete().eq("id",x);if(v){w({title:"Delete failed",description:v.message,variant:"destructive"});return}l()},S=async()=>{const x=(m==null?void 0:m.length)||0,{error:v}=await C.from("mlp_event_matchups").insert({tournament_id:a,stage:"double_elim",bracket:"WB",round_number:1,match_order:x,match_code:`WB-R1-M${x+1}`,status:"upcoming",manual_override:!0});if(v){w({title:"Insert failed",description:v.message,variant:"destructive"});return}l()},y=async()=>{const x=Number(s==null?void 0:s.field_size)||24;if(!confirm(`Generate the empty ${x}-team double-elimination template? Existing matchups in this bracket will be cleared first (use this on a fresh event only).`))return;const v=Ma(),{error:b}=await C.from("mlp_event_matchups").delete().eq("tournament_id",a).eq("stage","double_elim");if(b){w({title:"Template regen failed",description:b.message,variant:"destructive"});return}const E=v.map((z,k)=>({tournament_id:a,stage:"double_elim",bracket:z.bracket,round_number:z.round_number,round_label:z.round_label,match_order:k,match_code:z.match_code,feeder_winner_code:z.feeder_winner_code,feeder_loser_code:z.feeder_loser_code,if_necessary:z.if_necessary||!1,status:"upcoming",manual_override:!1})),{error:D}=await C.from("mlp_event_matchups").insert(E);if(D){w({title:"Template regen failed",description:D.message,variant:"destructive"});return}w({title:`Inserted ${E.length} template matches`}),l()},g=async()=>
4{if(!m)return;const x=new Map;for(const b of m)b.match_code&&x.set(b.match_code,b);let v=0;for(const b of m){const E={},D=b.feeder_winner_code?x.get(b.feeder_winner_code):null,z=b.feeder_loser_code?x.get(b.feeder_loser_code):null;if((D==null?void 0:D.status)==="completed"&&!b.team1_name){const k=Ba(D);k&&(E.team1_name=k)}if((z==null?void 0:z.status)==="completed"&&!b.team2_name){const k=Da(z);k&&(E.team2_name=k)}if(Object.keys(E).length>0){const{error:k}=await C.from("mlp_event_matchups").update(E).eq("id",b.id);k||v++}}w({title:`Propagated ${v} team slot(s)`}),l()},j=()=>{try{const x=JSON.parse(i||"{}");r(x),w({title:"Config saved"})}catch(x){w({title:"Invalid JSON",description:x.message,variant:"destructive"})}};return e.jsxs("div",{className:"rounded-lg border border-border/60 p-3 space-y-3 bg-card",children:[e.jsxs("button",{type:"button",onClick:()=>c(x=>!x),className:"w-full flex items-center gap-2 text-left",children:[n?e.jsx(Be,{className:"h-4 w-4"}):e.jsx(De,{className:"h-4 w-4"}),e.jsx("span",{className:"font-semibold text-sm",children:"Double-Elimination Bracket Editor"}),e.jsxs(J,{variant:"outline",className:"text-[10px]",children:[(m==null?void 0:m.length)||0," matches"]})]}),n&&e.jsxs(e.Fragment,{children:[e.jsx(Fa,{bracketConfig:s,onPatch:x=>{const v={...s||{},...x};p(JSON.stringify(v,null,2)),r(v)}}),e.jsxs("div",{children:[e.jsxs(M,{className:"text-xs",children:["Bracket config JSON",e.jsx("span",{className:"text-muted-foreground font-normal ml-2",children:"(advanced â bronze_rule, tiebreaker_rule, standings_bonuses, exhibition_team_uuidsâ¦)"})]}),e.jsx(ve,{className:"font-mono text-xs h-32",value:i,onChange:x=>p(x.target.value)}),e.jsx("div",{className:"flex justify-end mt-1",children:e.jsx(N,{size:"sm",variant:"outline",onClick:j,children:"Save config"})})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(N,{size:"sm",variant:"outline",onClick:y,children:[e.jsx(ia,{className:"h-3 w-3 mr-1"})," Generate 24-team template"]}),e.jsx(N,{size:"sm",variant:"outline",onClick:g,children:"Propagate winners â empty slots"}),e.jsxs(N,{size:"sm",onClick:S,children:[e.jsx(le,{className:"h-3 w-3 mr-1"})," Add match"]})]}),u?e.jsxs("div",{className:"flex items-center gap-2 py-4 text-sm text-muted-foreground",children:[e.jsx(K,{className:"h-4 w-4 animate-spin"})," Loadingâ¦"]}):e.jsxs("div",{className:"space-y-1 max-h-[600px] overflow-y-auto",children:[(m||[]).map(x=>e.jsx(qa,{row:x,onChange:v=>d(x.id,v),onDelete:()=>f(x.id)},x.id)),(m||[]).length===0&&e.jsx("div",{className:"text-xs text-muted-foreground py-4 text-center",children:'No DE matches yet. Use "Generate 24-team template" or "Add match".'})]})]})]})}function qa({row:a,onChange:s,onDelete:r}){const[t,n]=o.useState(a),{data:c}=Qe();o.useEffect(()=>{n(a)},[a.id]);const i=Object.keys(t).filter(l=>t[l]!==a[l]),p=i.length>0,m=()=>{const l={};for(const d of i)l[d]=t[d];s(l)},u=(l,d)=>{const f=(c||[]).find(S=>S.team_uuid===d);f&&n(l===1?{...t,team1_uuid:f.team_uuid,team1_name:f.team_title}:{...t,team2_uuid:f.team_uuid,team2_name:f.team_title})};return e.jsxs("div",{className:"rounded border border-border/40 bg-background/50 p-2 space-y-1",children:[e.jsxs("div",{className:"grid grid-cols-12 gap-1 items-center text-xs",children:[e.jsxs(Q,{value:t.bracket||"",onValueChange:l=>n({...t,bracket:l}),children:[e.jsx(O,{className:"h-7 col-span-1",children:e.jsx(W,{placeholder:"â"})}),e.jsxs(I,{children:[e.jsx(A,{value:"WB",children:"WB"}),e.jsx(A,{value:"LB",children:"LB"}),e.jsx(A,{value:"GF",children:"GF"})]})]}),e.jsx(P,{className:"h-7 col-span-1",type:"number",placeholder:"R#",value:t.round_number??"",onChange:l=>n({...t,round_number:l.target.value===""?null:Number(l.target.value)})}),e.jsx(P,{className:"h-7 col-span-2 font-mono",placeholder:"match_code",value:t.match_code||"",onChange:l=>n({...t,match_code:l.target.value||null})}),e.jsx(P,{className:"h-7 col-span-2",placeholder:"round_label",value:t.round_label||"",onChange:l=>n({...t,round_label:l.target.value||null})}),e.jsx(P,{className:"h-7 col-span-2 font-mono",placeholder:"feeder_winner",value:t.feeder_winner_code||"",onChange:l=>n({...t,feeder_winner_code:l.target.value||null})}
4),e.jsx(P,{className:"h-7 col-span-2 font-mono",placeholder:"feeder_loser",value:t.feeder_loser_code||"",onChange:l=>n({...t,feeder_loser_code:l.target.value||null})}),e.jsxs("label",{className:"flex items-center gap-1 col-span-2 justify-end",children:[e.jsx(X,{checked:t.if_necessary,onCheckedChange:l=>n({...t,if_necessary:l})}),e.jsx("span",{className:"text-[10px]",children:"if-nec"})]})]}),e.jsxs("div",{className:"grid grid-cols-12 gap-1 items-center text-xs",children:[e.jsxs(Q,{value:t.team1_uuid||"",onValueChange:l=>u(1,l),children:[e.jsx(O,{className:"h-7 col-span-4",children:e.jsx(W,{placeholder:"Team 1 (pick)"})}),e.jsx(I,{className:"max-h-72",children:(c||[]).map(l=>e.jsx(A,{value:l.team_uuid,children:l.team_title},l.team_uuid))})]}),e.jsx(P,{className:"h-7 col-span-3",placeholder:"Team 1 name override",value:t.team1_name||"",onChange:l=>n({...t,team1_name:l.target.value||null})}),e.jsx(P,{className:"h-7 col-span-1",type:"number",placeholder:"seed",value:t.team1_seed??"",onChange:l=>n({...t,team1_seed:l.target.value===""?null:Number(l.target.value)})}),e.jsx(P,{className:"h-7 col-span-1",type:"number",placeholder:"s1",value:t.team1_score??"",onChange:l=>n({...t,team1_score:l.target.value===""?null:Number(l.target.value)})}),e.jsx(N,{size:"sm",variant:"ghost",className:"h-7 col-span-1 text-[10px]",onClick:()=>n({...t,team1_uuid:null,team1_name:null,team1_seed:null,team1_score:null}),children:"clear"}),e.jsxs(Q,{value:t.status,onValueChange:l=>n({...t,status:l}),children:[e.jsx(O,{className:"h-7 col-span-2",children:e.jsx(W,{})}),e.jsxs(I,{children:[e.jsx(A,{value:"upcoming",children:"upcoming"}),e.jsx(A,{value:"in_progress",children:"in_progress"}),e.jsx(A,{value:"completed",children:"completed"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-12 gap-1 items-center text-xs",children:[e.jsxs(Q,{value:t.team2_uuid||"",onValueChange:l=>u(2,l),children:[e.jsx(O,{className:"h-7 col-span-4",children:e.jsx(W,{placeholder:"Team 2 (pick)"})}),e.jsx(I,{className:"max-h-72",children:(c||[]).map(l=>e.jsx(A,{value:l.team_uuid,children:l.team_title},l.team_uuid))})]}),e.jsx(P,{className:"h-7 col-span-3",placeholder:"Team 2 name override",value:t.team2_name||"",onChange:l=>n({...t,team2_name:l.target.value||null})}),e.jsx(P,{className:"h-7 col-span-1",type:"number",placeholder:"seed",value:t.team2_seed??"",onChange:l=>n({...t,team2_seed:l.target.value===""?null:Number(l.target.value)})}),e.jsx(P,{className:"h-7 col-span-1",type:"number",placeholder:"s2",value:t.team2_score??"",onChange:l=>n({...t,team2_score:l.target.value===""?null:Number(l.target.value)})}),e.jsx(N,{size:"sm",variant:"ghost",className:"h-7 col-span-1 text-[10px]",onClick:()=>n({...t,team2_uuid:null,team2_name:null,team2_seed:null,team2_score:null}),children:"clear"}),e.jsx(P,{className:"h-7 col-span-2",placeholder:"court",value:t.court||"",onChange:l=>n({...t,court:l.target.value||null})})]}),e.jsxs("div",{className:"grid grid-cols-12 gap-1 items-center text-xs",children:[e.jsx(P,{className:"h-7 col-span-4",type:"datetime-local",value:t.scheduled_at?Ea(t.scheduled_at):"",onChange:l=>n({...t,scheduled_at:l.target.value?new Date(l.target.value).toISOString():null})}),e.jsx("div",{className:"col-span-6 text-[10px] text-muted-foreground truncate",children:a.manual_override?"ð manual_override â protected from sync":"auto (sync may overwrite)"}),e.jsxs("div",{className:"col-span-2 flex justify-end gap-1",children:[p&&e.jsx(N,{size:"sm",className:"h-7 px-2",onClick:m,children:"Save"}),e.jsx(N,{size:"sm",variant:"ghost",className:"h-7 px-1 text-destructive",onClick:r,children:e.jsx(ne,{className:"h-3 w-3"})})]})]})]})}function Ba(a){return!a.team1_score||!a.team2_score?null:a.team1_score>a.team2_score?a.team1_name:a.team2_name}function Da(a){return!a.team1_score||!a.team2_score?null:a.team1_score>a.team2_score?a.team2_name:a.team1_name}function Ea(a){try{const s=new Date(a),r=t=>String(t).padStart(2,"0");return`${s.getFullYear()}-${r(s.getMonth()+1)}-${r(s.getDate())}T${r(s.getHours())}:${r(s.getMinutes())}`}catch{return""}}function Fa({bracketConfig:a,onPatch:s}){const r=a||{},t=r.standings_bonuses||{gold:10,silver:6,bronze:4};return e.jsxs("div",{className:"rounded-md border border-border/50 bg-muted/20 p-3 space-y-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide font-semibold text-muted-foreground",children:"Qu
4ick config"}),e.jsxs("div",{className:"grid grid-cols-12 gap-2 items-end",children:[e.jsxs("div",{className:"col-span-3",children:[e.jsx(M,{className:"text-[10px]",children:"Field size"}),e.jsxs(Q,{value:String(r.field_size||24),onValueChange:n=>s({field_size:Number(n)}),children:[e.jsx(O,{className:"h-8",children:e.jsx(W,{})}),e.jsxs(I,{children:[e.jsx(A,{value:"16",children:"16"}),e.jsx(A,{value:"24",children:"24"})]})]})]}),e.jsxs("div",{className:"col-span-5",children:[e.jsx(M,{className:"text-[10px]",children:"Bronze rule"}),e.jsxs(Q,{value:r.bronze_rule||"lb_final_winner",onValueChange:n=>s({bronze_rule:n}),children:[e.jsx(O,{className:"h-8",children:e.jsx(W,{})}),e.jsxs(I,{children:[e.jsx(A,{value:"lb_final_winner",children:"LB Final winner (standard DE)"}),e.jsx(A,{value:"lb_final_loser",children:"LB Final loser (2025 BCO)"}),e.jsx(A,{value:"third_place_match",children:"Dedicated 3rd-place match"}),e.jsx(A,{value:"tiebreaker_points",children:"Tiebreaker â points for"}),e.jsx(A,{value:"tiebreaker_games",children:"Tiebreaker â game diff"})]})]})]}),e.jsxs("div",{className:"col-span-4",children:[e.jsx(M,{className:"text-[10px]",children:"Tiebreaker"}),e.jsxs(Q,{value:r.tiebreaker_rule||"none",onValueChange:n=>s({tiebreaker_rule:n==="none"?null:n}),children:[e.jsx(O,{className:"h-8",children:e.jsx(W,{})}),e.jsxs(I,{children:[e.jsx(A,{value:"none",children:"None"}),e.jsx(A,{value:"points_for",children:"Points for"}),e.jsx(A,{value:"game_diff",children:"Game differential"}),e.jsx(A,{value:"head_to_head",children:"Head-to-head"})]})]})]}),e.jsxs("div",{className:"col-span-12",children:[e.jsx(M,{className:"text-[10px]",children:"Standings point bonuses (Gold / Silver / Bronze)"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:["gold","silver","bronze"].map(n=>e.jsx(P,{type:"number",className:"h-8",value:t[n]??"",onChange:c=>s({standings_bonuses:{...t,[n]:Number(c.target.value)||0}})},n))})]}),e.jsxs("label",{className:"col-span-6 flex items-center gap-2",children:[e.jsx(X,{checked:!!r.third_place_match_enabled,onCheckedChange:n=>s({third_place_match_enabled:n})}),e.jsx("span",{className:"text-[11px]",children:"3rd-place match enabled"})]}),e.jsxs("label",{className:"col-span-6 flex items-center gap-2",children:[e.jsx(X,{checked:r.if_necessary_visible!==!1,onCheckedChange:n=>s({if_necessary_visible:n})}),e.jsx("span",{className:"text-[11px]",children:'Show "if necessary" matches'})]}),e.jsxs("div",{className:"col-span-12",children:[e.jsx(M,{className:"text-[10px]",children:"Pick'em label"}),e.jsx(P,{className:"h-8",value:r.pickem_label||"",onChange:n=>s({pickem_label:n.target.value}),placeholder:"Playoff Picks"})]})]})]})}function za({tournamentId:a,bracketFormat:s,bracketConfig:r,onConfigSave:t}){const n=s==="playoff_advance_4",[c,i]=o.useState([]),[p,m]=o.useState({}),[u,l]=o.useState({}),[d,f]=o.useState(!1),[S,y]=o.useState(!1);o.useEffect(()=>{i(Array.isArray(r.playoff_field)?r.playoff_field:[]),m(r.result||{}),l(r.scoring||{})},[a]);const g=n?8:4,j=()=>{i(k=>[...k,{seed:k.length+1,team_uuid:"",team_name:"",regular_season_points:0}])},x=k=>i(T=>T.filter((q,$)=>$!==k)),v=(k,T)=>{i(q=>q.map(($,_)=>_===k?{...$,...T}:$))},b=o.useMemo(()=>new Set((p.advancing_uuids??[]).map(String)),[p.advancing_uuids]),E=k=>{m(T=>{const q=new Set((T.advancing_uuids??[]).map(String));return q.has(k)?q.delete(k):q.add(k),{...T,advancing_uuids:Array.from(q)}})},D=async()=>{f(!0);try{const k=c.filter(q=>q.team_uuid&&q.team_name).map((q,$)=>({seed:Number(q.seed)||$+1,team_uuid:q.team_uuid,team_name:q.team_name,regular_season_points:Number(q.regular_season_points)||0,eliminated:!!q.eliminated})),T={...r,playoff_field:k,result:p,scoring:u};t(T),de.success("Playoff config saved")}finally{f(!1)}},z=async()=>{var k;y(!0);try{const T=n?"score-mlp-playoff-advance-picks":"score-mlp-playoff-podium-picks",{data:q,error:$}=await C.functions.invoke(T,{body:{tournament_id:a}});if($)throw $;de.success(`Scoring triggered: ${JSON.stringify(((k=q==null?void 0:q.results)==null?void 0:k[0])??q)}`)}catch(T){de.error(`Scoring failed: ${String(T)}`)}finally{y(!1)}};return e.jsxs(Oe,{className:"p-4 space-y-4 border-primary/30",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-sm",children:n?"Playoff â Advance-4 Editor":"Playoff â Podium-3 Editor"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Seed ",g," teams for the field, set winners, tune points."]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(N,{size:"sm",variant:"outline",onClick:z,disabled:S,children:S?"Scoringâ¦":"Score now"}),e.jsxs(N,{size:"sm",onClick:D,disabled:d,children:[e.jsx(oa,{className:"w-3.5 h-3.5 mr-1"})," ",d?"Savingâ¦":"Save"]})]})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:n?e.jsxs("div",{children:[e.jsx(M,{className:"text-xs",children:"Points per correct advance"}),e.jsx(P,{type:"number",value:u.advance_per_correct??"",onChange:k=>l({advance_per_correct:Number(k.target.value)||0}),placeholder:"250",className:"h-8"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(M,{className:"text-xs",children:"Champion pts"}),e.jsx(P,{type:"number",className:"h-8",value:u.champion_points??"",onChange:k=>l(T=>({...T,champion_points:Number(k.target.value)||0}))})]}),e.jsxs("div",{children:[e.jsx(M,{className:"text-xs",children:"Runner-up pts"}),e.jsx(P,{type:"number",className:"h-8",value:u.runner_up_points??"",onChange:k=>l(T=>({...T,runner_up_points:Number(k.target.value)||0}))})]}),e.jsxs("div",{children:[e.jsx(M,{className:"text-xs",children:"Third pts"}),e.jsx(P,{type:"number",className:"h-8",value:u.third_points??"",onChange:k=>l(T=>({...T,third_points:Number(k.target.value)||0}))})]})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(M,{className:"text-xs uppercase tracking-wide",children:["Playoff Field (",c.length,"/",g,")"]}),e.jsxs(N,{size:"sm",variant:"ghost",onClick:j,children:[e.jsx(le,{className:"w-3.5 h-3.5 mr-1"})," Add team"]})]}),c.map((k,T)=>e.jsxs("div",{className:"grid grid-cols-12 gap-1 items-center",children:[e.jsx(P,{type:"number",className:"h-8 col-span-1",value:k.seed,onChange:q=>v(T,{seed:Number(q.target.value)||0}),placeholder:"Seed"}),e.jsx(P,{className:"h-8 col-span-4",value:k.team_name,onChange:q=>v(T,{team_name:q.target.value}),placeholder:"Team name (e.g. St. Louis Shock)"}),e.jsx(P,{className:"h-8 col-span-5 font-mono text-xs",value:k.team_uuid,onChange:q=>v(T,{team_uuid:q.target.value}),placeholder:"team_uuid"}),n?e.jsxs("label",{className:"col-span-1 flex items-center gap-1 text-xs",children:[e.jsx("input",{type:"checkbox",checked:b.has(k.team_uuid),onChange:()=>E(k.team_uuid)}),"Adv"]}):e.jsx("div",{className:"col-span-1"}),e.jsx(N,{size:"icon",variant:"ghost",onClick:()=>x(T),className:"col-span-1 h-8 w-8",children:e.jsx(ne,{className:"w-3.5 h-3.5"})})]},T))]}),!n&&e.jsxs("div",{className:"space-y-2 pt-2 border-t border-border/50",children:[e.jsx(M,{className:"text-xs uppercase tracking-wide",children:"Championship Result"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(M,{className:"text-[10px]",children:"Champion uuid"}),e.jsx(P,{className:"h-8 font-mono text-xs",value:p.champion_uuid||"",onChange:k=>m(T=>({...T,champion_uuid:k.target.value||null}))})]}),e.jsxs("div",{children:[e.jsx(M,{className:"text-[10px]",children:"Runner-up uuid"}),e.jsx(P,{className:"h-8 font-mono text-xs",value:p.runner_up_uuid||"",onChange:k=>m(T=>({...T,runner_up_uuid:k.target.value||null}))})]}),e.jsxs("div",{children:[e.jsx(M,{className:"text-[10px]",children:"Third (SF loser A)"}),e.jsx(P,{className:"h-8 font-mono text-xs",value:p.third_uuid||"",onChange:k=>m(T=>({...T,third_uuid:k.target.value||null}))})]}),e.jsxs("div",{children:[e.jsx(M,{className:"text-[10px]",children:"Third alt (SF loser B)"}),e.jsx(P,{className:"h-8 font-mono text-xs",value:p.third_alt_uuid||"",onChange:k=>m(T=>({...T,third_alt_uuid:k.target.value||null}))})]})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"MLP does not play a 3rd-place match â either losing semifinalist counts for third-place credit."})]})]})}function Ka(){const a=G(),[s,r]=o.useState(null),{data:t,isLoading:n}=Y({queryKey:["mlp-event-meta-admin"],queryFn:async()=>{const{data:i,error:p}=await C.from("mlp_event_meta").select("tournament_id, format, data_source, is_visible, mlp_tournament_uuid, season, notes, playoff_label, broadcast_url, broadcast_provider, bracket_format, bracket_config, tournaments!inner(id, name, start_date)").order("season",{ascending:!1});if(p)throw p;return(i||[]).sort((m,u)=>{var f,S;const l=((f=m.tournaments)==null?void 0:f.start_date)||"";return(((S=u.tournaments)==null?void 0:S.start_date)||"").localeCompare(l)})}}),c=async(i,p)=>{const{error:m}=await C.from("mlp_event_meta").update(p).eq("tournament_id",i);if(m){w({title:"Update failed",description:m.message,variant:"destructive"});return}w({title:"Saved"}),a.invalidateQueries({queryKey:["mlp-event-meta-admin"]}),a.invalidateQueries({queryKey:["tournaments-with-brackets"]}),a.invalidateQueries({queryKey:["mlp-event-meta",i]})};return e.jsxs(H,{title:"MLP Event Setup",className:"mt-6",children:[e.jsxs("p",{className:"text-xs text-muted-foreground mb-3",children:["Controls which MLP events appear in the Brackets dropdown and how their bracket data is sourced. Set ",e.jsx("strong",{children:"data source"})," to ",e.jsx("em",{children:"auto"})," to prefer the live MLP API when an upstream UUID is provided, falling back to curated matchups. Use ",e.jsx("em",{children:"curated"})," to lock to admin-entered data only."]}),n?e.jsxs("div",{className:"flex items-center gap-2 py-4 text-sm text-muted-foreground",children:[e.jsx(K,{className:"h-4 w-4 animate-spin"})," Loadingâ¦"]}):e.jsxs("div",{className:"space-y-2",children:[(t||[]).map(i=>{var m;const p=s===i.tournament_id;return e.jsxs("div",{className:"rounded-lg border border-border/60",children:[e.jsxs("button",{type:"button",onClick:()=>r(p?null:i.tournament_id),className:"w-full flex items-center gap-2 px-3 py-2 text-left hover:bg-accent/40",children:[p?e.jsx(Be,{className:"h-4 w-4"}):e.jsx(De,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-sm flex-1 truncate",children:((m=i.tournaments)==null?void 0:m.name)||i.tournament_id}),e.jsx(J,{variant:"outline",className:"text-[10px] uppercase",children:i.format}),e.jsx(J,{variant:i.is_visible?"default":"secondary",className:"text-[10px]",children:i.is_visible?"visible":"hidden"}),i.mlp_tournament_uuid&&e.jsx(J,{variant:"outline",className:"text-[10px]",children:"api-linked"})]}),p&&e.jsxs("div",{className:"border-t border-border/60 p-3 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(M,{className:"text-xs",children:"Format"}),e.jsxs(Q,{value:i.format,onValueChange:u=>c(i.tournament_id,{format:u}),children:[e.jsx(O,{className:"h-8",children:e.jsx(W,{})}),e.jsxs(I,{children:[e.jsx(A,{value:"regular",children:"Regular (matchup list)"}),e.jsx(A,{value:"playoff",children:"Playoff (single-elim bracket)"}),e.jsx(A,{value:"hybrid",children:"Hybrid (pool + playoff)"})]})]})]}),e.jsxs("div",{children:[e.jsx(M,{className:"text-xs",children:"Data source"}),e.jsxs(Q,{value:i.data_source,onValueChange:u=>c(i.tournament_id,{data_source:u}),children:[e.jsx(O,{className:"h-8",children:e.jsx(W,{})}),e.jsxs(I,{children:[e.jsx(A,{value:"auto",children:"Auto (API â curated)"}),e.jsx(A,{value:"api",children:"API only"}),e.jsx(A,{value:"curated",children:"Curated only"})]})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(M,{className:"text-xs",children:"Upstream MLP tournament UUID / bracket link"}),e.jsx(Ua,{initial:i.mlp_tournament_uuid||"",onSave:u=>c(i.tournament_id,{mlp_tournament_uuid:u||null})}),e.jsx($a,{tournamentId:i.tournament_id,mlpTournamentUuid:i.mlp_tournament_uuid})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(X,{checked:i.is_visible,onCheckedChange:u=>c(i.tournament_id,{is_visible:u})}),e.jsx(M,{className:"text-xs",children:"Visible in Brackets dropdown"})]}),e.jsxs("div",{children:[e.jsx(M,{className:"text-xs",children:"Playoff label override"}),e.jsx(re,{initial:i.playoff_label||"",placeholder:"e.g. Super Sunday, Championship",onSave:u=>c(i.tournament_id,{playoff_label:u||null})})]}),e.jsxs("div",{children:[e.jsx(M,{className:"text-xs",children:"Broadcast provider"}),e.jsx(re,{initial:i.broadcast_provider||"",placeholder:"e.g. Tennis Channel, YouTube",onSave:u=>c(i.tournament_id,{broadcast_provider:u||null})})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(M,{className:"text-xs",children:"Broadcast URL"}),e.jsx(re,{initial:i.broadcast_url||"",placeholder:"https://â¦",onSave:u=>c(i.tournament_id,{broadcast_url:u||null})})]}),e.jsxs("div",{children:[e.jsx(M,{className:"text-xs",children:"Bracket layout"}),e.jsxs(Q,{value:i.bracket_format||"team_pool",onValueChange:u=>c(i.tournament_id,{bracket_format:u}),children:[e.jsx(O,{className:"h-8",children:e.jsx(W,{})}),e.jsxs(I,{children:[e.jsx(A,{value:"team_pool",children:"Pool / Super-Sunday (default)"}),e.jsx(A,{value:"team_de",children:"Double Elimination (24-team MST)"}),e.jsx(A,{value:"team_playoff",children:"Playoff only"}),e.jsx(A,{value:"playoff_advance_4",children:"2026 Playoff â Advance 4
4(Dallas / Newport)"}),e.jsx(A,{value:"playoff_podium_3",children:"2026 Playoff â Podium 3 (New York)"})]})]})]})]}),e.jsx(Oa,{tournamentId:i.tournament_id}),(i.bracket_format||"team_pool")==="team_de"&&e.jsx(Ra,{tournamentId:i.tournament_id,bracketConfig:i.bracket_config||{},onConfigSave:u=>c(i.tournament_id,{bracket_config:u})}),(i.bracket_format==="playoff_advance_4"||i.bracket_format==="playoff_podium_3")&&e.jsx(za,{tournamentId:i.tournament_id,bracketFormat:i.bracket_format,bracketConfig:i.bracket_config||{},onConfigSave:u=>c(i.tournament_id,{bracket_config:u})}),e.jsx(Qa,{tournamentId:i.tournament_id,format:i.format})]})]},i.tournament_id)}),(t||[]).length===0&&e.jsx("div",{className:"text-sm text-muted-foreground py-4",children:"No MLP events configured."})]})]})}function Ua({initial:a,onSave:s}){const[r,t]=o.useState(a),n=r.trim()!==a.trim();return e.jsxs("div",{className:"flex gap-2",children:[e.jsx(P,{className:"h-8 font-mono text-xs",placeholder:"00000000-0000-0000-0000-000000000000",value:r,onChange:c=>t(c.target.value)}),e.jsx(N,{size:"sm",variant:n?"default":"outline",disabled:!n,onClick:()=>s(r.trim()),children:"Save"})]})}function $a({tournamentId:a,mlpTournamentUuid:s}){const r=G(),[t,n]=o.useState(""),[c,i]=o.useState(!1),p=async()=>{i(!0);try{const m={tournament_id:a};if(t.trim())m.link=t.trim();else if(s)m.mlp_tournament_uuid=s;else{w({title:"Need a UUID or link",variant:"destructive"}),i(!1);return}const{data:u,error:l}=await C.functions.invoke("sync-mlp-event-matchups",{body:m});if(l)throw l;const d=u;if(!(d!=null&&d.ok))throw new Error((d==null?void 0:d.error)||"sync failed");w({title:"Pulled from PBLFG",description:`${d.pools} pools · ${d.inserted} new · ${d.updated} updated · ${d.matchups_seen} seen`}),n(""),r.invalidateQueries({queryKey:["mlp-matchups-admin",a]}),r.invalidateQueries({queryKey:["mlp-event-matchups-curated",a]}),r.invalidateQueries({queryKey:["tournaments-with-brackets"]}),r.invalidateQueries({queryKey:["mlp-event-meta-admin"]})}catch(m){w({title:"Pull failed",description:(m==null?void 0:m.message)||String(m),variant:"destructive"})}finally{i(!1)}};return e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsx(P,{className:"h-8 text-xs",placeholder:"Paste bracket link (or leave empty to use saved UUID)",value:t,onChange:m=>n(m.target.value)}),e.jsx(N,{size:"sm",onClick:p,disabled:c,children:c?e.jsx(K,{className:"h-3 w-3 animate-spin"}):"Pull from PBLFG"})]})}function Qa({tournamentId:a,format:s}){const r=G(),[t,n]=o.useState({stage:s==="playoff"?"playoff":"regular",pool_label:"",round_label:"",team1_name:"",team2_name:"",team1_score:"",team2_score:""}),{data:c,isLoading:i}=Y({queryKey:["mlp-matchups-admin",a],queryFn:async()=>{const{data:d,error:f}=await C.from("mlp_event_matchups").select("id, tournament_id, stage, pool_label, round_label, match_order, team1_name, team2_name, team1_score, team2_score, status, tier_label, lineup_matchup_uuid").eq("tournament_id",a).order("stage").order("match_order");if(f)throw f;return d||[]}}),p=async()=>{if(!t.team1_name||!t.team2_name){w({title:"Both teams required",variant:"destructive"});return}const d=(c||[]).filter(S=>S.stage===t.stage).length,{error:f}=await C.from("mlp_event_matchups").insert({tournament_id:a,stage:t.stage,pool_label:t.pool_label||null,round_label:t.round_label||null,match_order:d,team1_name:t.team1_name,team2_name:t.team2_name,team1_score:t.team1_score?Number(t.team1_score):null,team2_score:t.team2_score?Number(t.team2_score):null,status:t.team1_score&&t.team2_score?"completed":"upcoming"});if(f){w({title:"Insert failed",description:f.message,variant:"destructive"});return}n({...t,team1_name:"",team2_name:"",team1_score:"",team2_score:""}),r.invalidateQueries({queryKey:["mlp-matchups-admin",a]}),r.invalidateQueries({queryKey:["mlp-event-matchups-curated",a]}),r.invalidateQueries({queryKey:["tournaments-with-brackets"]})},m=async d=>{const{error:f}=await C.from("mlp_event_matchups").delete().eq("id",d);if(f){w({title:"Delete failed",description:f.message,variant:"destructive"});return}r.invalidateQueries({queryKey:["mlp-matchups-admin",a]}),r.invalidateQueries({queryKey:["mlp-event-matchups-curated",a]})},u=async(d,f)=>{const S=f.trim(),{error:y}=await C.from("mlp_event_matchups").update({tier_label:S||null}).eq("id",d);if(y){w({title:"Tier save failed",description:y.message,variant:"destructive"});return}w({title:S?`Tier set to "${S}"`:"Tier cleared"}),r.invalidateQueries({queryKey:["mlp-matchups-admin",a]}),r.invalidateQueries({queryKey:["mlp-event-matchups-curated",a]})},l=async(d,f)=>{const S=f.trim(),{error:y}=await C.from("mlp_event_matchups").update({lineup_matchup_uuid:S||null}).eq("id",d);if(y){w({title:"Lineup link save failed",description:y.message,variant:"destructive"});return}w({title:S?"Lineup link saved":"Lineup link cleared"}),r.invalidateQueries({queryKey:["mlp-matchups-admin",a]}),r.invalidateQueries({queryKey:["mlp-event-matchups-curated",a]})};return e.jsxs("div",{className:"space-y-2 pt-2 border-t border-border/60",children:[e.jsxs("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:["Curated matchups (",(c==null?void 0:c.length)||0,")"]}),i?e.jsx(K,{className:"h-4 w-4 animate-spin"}):e.jsx("div",{className:"space-y-1",children:(c||[]).map(d=>e.jsxs("div",{className:Z("flex items-center gap-2 text-xs px-2 py-1 rounded bg-muted/40"),children:[e.jsx(J,{variant:"outline",className:"text-[9px] uppercase",children:d.stage}),d.pool_label&&e.jsx(J,{variant:"outline",className:"text-[9px]",children:d.pool_label}),d.round_label&&e.jsx(J,{variant:"outline",className:"text-[9px]",children:d.roun
4d_label}),e.jsxs("span",{className:"flex-1 truncate",children:[d.team1_name," ",e.jsx("span",{className:"font-mono",children:d.team1_score??"â"})," vs ",d.team2_name," ",e.jsx("span",{className:"font-mono",children:d.team2_score??"â"})]}),d.stage==="playoff"&&e.jsx(re,{initial:d.tier_label||"",placeholder:"Tier (e.g. Tier 2)",onSave:f=>u(d.id,f)}),e.jsx(re,{initial:d.lineup_matchup_uuid||"",placeholder:"Lineup matchup_uuid",onSave:f=>l(d.id,f)}),e.jsx(N,{size:"icon",variant:"ghost",onClick:()=>m(d.id),className:"h-6 w-6",children:e.jsx(ne,{className:"h-3 w-3"})})]},d.id))}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-6 gap-2 pt-2",children:[e.jsxs(Q,{value:t.stage,onValueChange:d=>n({...t,stage:d}),children:[e.jsx(O,{className:"h-8 col-span-2 md:col-span-1",children:e.jsx(W,{})}),e.jsxs(I,{children:[e.jsx(A,{value:"regular",children:"regular"}),e.jsx(A,{value:"pool",children:"pool"}),e.jsx(A,{value:"playoff",children:"playoff"})]})]}),e.jsx(P,{className:"h-8",placeholder:"Pool",value:t.pool_label,onChange:d=>n({...t,pool_label:d.target.value})}),e.jsx(P,{className:"h-8",placeholder:"Round",value:t.round_label,onChange:d=>n({...t,round_label:d.target.value})}),e.jsx(P,{className:"h-8",placeholder:"Team 1",value:t.team1_name,onChange:d=>n({...t,team1_name:d.target.value})}),e.jsx(P,{className:"h-8",placeholder:"Team 2",value:t.team2_name,onChange:d=>n({...t,team2_name:d.target.value})}),e.jsxs("div",{className:"flex gap-1 col-span-2 md:col-span-1",children:[e.jsx(P,{className:"h-8 w-12",placeholder:"S1",value:t.team1_score,onChange:d=>n({...t,team1_score:d.target.value})}),e.jsx(P,{className:"h-8 w-12",placeholder:"S2",value:t.team2_score,onChange:d=>n({...t,team2_score:d.target.value})}),e.jsx(N,{size:"icon",className:"h-8 w-8 shrink-0",onClick:p,children:e.jsx(le,{className:"h-4 w-4"})})]})]})]})}function re({initial:a,placeholder:s,onSave:r}){const[t,n]=o.useState(a),c=t.trim()!==(a||"").trim();return e.jsxs("div",{className:"flex gap-2",children:[e.jsx(P,{className:"h-8 text-xs",placeholder:s,value:t,onChange:i=>n(i.target.value)}),e.jsx(N,{size:"sm",variant:c?"default":"outline",disabled:!c,onClick:()=>r(t.trim()),children:"Save"})]})}function Oa({tournamentId:a}){var y;const s=G(),{data:r}=Y({queryKey:["app_settings","mlp_court_sponsors"],queryFn:async()=>{const{data:g}=await C.from("app_settings").select("value").eq("key","mlp_court_sponsors").maybeSingle();if(!(g!=null&&g.value))return{default:{},by_event:{}};try{return JSON.parse(g.value)}catch{return{default:{},by_event:{}}}},staleTime:5*60*1e3}),t=((y=r==null?void 0:r.by_event)==null?void 0:y[a])||{},[n,c]=o.useState(t.championship||""),[i,p]=o.useState(t.grandstand||""),[m,u]=o.useState(!1);o.useEffect(()=>{c(t.championship||""),p(t.grandstand||"")},[r,a]);const l=(n||"")!==(t.championship||"")||(i||"")!==(t.grandstand||""),d=async()=>{u(!0);const g={default:(r==null?void 0:r.default)||{},by_event:{...(r==null?void 0:r.by_event)||{}}},j=n.trim(),x=i.trim();!j&&!x?delete g.by_event[a]:g.by_event[a]={championship:j||null,grandstand:x||null};const{error:v}=await C.from("app_settings").upsert({key:"mlp_court_sponsors",value:JSON.stringify(g)},{onConflict:"key"});if(u(!1),v){w({title:"Save failed",description:v.message,variant:"destructive"});return}w({title:"Court sponsor override saved"}),s.invalidateQueries({queryKey:["app_settings","mlp_court_sponsors"]})},f=async()=>{c(""),p("");const g={default:(r==null?void 0:r.default)||{},by_event:{...(r==null?void 0:r.by_event)||{}}};delete g.by_event[a];const{error:j}=await C.from("app_settings").upsert({key:"mlp_court_sponsors",value:JSON.stringify(g)},{onConflict:"key"});if(j){w({title:"Clear failed",description:j.message,variant:"destructive"});return}w({title:"Override cleared"}),s.invalidateQueries({queryKey:["app_settings","mlp_court_sponsors"]})},S=!!(t.championship||t.grandstand);return e.jsxs("div",{className:"space-y-2 pt-2 border-t border-border/60",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Court sponsor override (this event)"}),S&&e.jsx(N,{size:"sm",variant:"ghost",onClick:f,className:"h-6 text-[10px]",children:"Clear override"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:[e.jsx(P,{className:"h-8 text-xs",placeholder:"Championship court (defaults if blank)",value:n,onChange:g=>c(g.target.value)}),e.jsx(P,{className:"h-8 text-xs",placeholder:"Grandstand court (defaults if blank)",value:i,onChange:g=>p(g.target.value)})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx(N,{size:"sm",disabled:!l||m,onClick:d,children:m?"Savingâ¦":"Save override"})})]})}function Wa(){const a=G(),{config:s}=We(),[r,t]=o.useState(s),[n,c]=o.useState(!1);o.useEffect(()=>{t(s)},[s.default_mode,s.allow_user_switch,s.teams_enabled_when,s.user_choice_epoch]);const i=r.default_mode!==s.default_mode||r.allow_user_switch!==s.allow_user_switch||r.teams_enabled_when!==s.teams_enabled_when,p=async(l,d)=>{c(!0);const f={...l,defaultMode:l.default_mode,allowUserToggle:l.allow_user_switch,visibility:l.teams_enabled_when},{error:S}=await C.from("app_settings").upsert({key:"top_ticker_config",value:JSON.stringify(f)},{onConflict:"key"});if(c(!1),S){w({title:"Save failed",description:S.message,variant:"destructive"});return}w({title:d}),a.invalidateQueries({queryKey:["app_settings","top_ticker_config"]})},m=()=>p(r,"Top ticker config saved"),u=()=>p({...r,user_choice_epoch:(s.user_choice_epoch||0)+1},"All devices reset to the default ticker");return e.jsxs(H,{title:"Top Ticker Config",className:"mt-6",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Controls the homepage scrolling ticker. Choose whether it defaults to player rankings or MLP team standings, and when the Teams option is exposed to users."}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(M,{className:"text-xs",children:"Default mode"}),e.jsxs(Q,{value:r.default_mode,onValueChange:l=>t({...r,default_mode:l}),children:[e.jsx(O,{className:"h-8",children:e.jsx(W,{})}),e.jsxs(I,{children:[e.jsx(A,{value:"auto",children:"Auto (teams during MLP season, else players)"}),e.jsx(A,{value:"players",children:"Players"}),e.jsx(A,{value:"teams",children:"Teams"})]})]})]}),e.jsxs("div",{children:[e.jsx(M,{className:"text-xs",children:"Teams ticker available when"}),e.jsxs(Q,{value:r.teams_enabled_when,onValueChange:l=>t({...r,teams_enabled_when:l}),children:[e.jsx(O,{className:"h-8",children:e.jsx(W,{})}),e.jsxs(I,{children:[e.jsx(A,{value:"mlp_season",children:"MLP season only (admins always)"}),e.jsx(A,{value:"always",children:"Always"}),e.jsx(A,{value:"never",children:"Never (admins still see)"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 md:col-span-2",children:[e.jsx(X,{checked:r.allow_user_switch,onCheckedChange:l=>t({...r,allow_user_switch:l})}),e.jsx(M,{className:"text-xs",children:"Allow users to toggle PL / TM"})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 mt-3",children:[e.jsx(N,{size:"sm",variant:"outline",disabled:n,onClick:u,children:"Reset all devices to default"}),e.jsx(N,{size:"sm",disabled:!i||n,onClick:m,children:n?"Savingâ¦":"Save"})]})]})}function Ia(){const a=G(),s=Ie(),[r,t]=o.useState(s.default.championship||""),[n,c]=o.useState(s.default.grandstand||""),[i,p]=o.use
4State(!1);o.useEffect(()=>{t(s.default.championship||""),c(s.default.grandstand||"")},[s.default.championship,s.default.grandstand]);const m=(r||"")!==(s.default.championship||"")||(n||"")!==(s.default.grandstand||""),u=async()=>{p(!0);const l={...s,default:{championship:r.trim()||null,grandstand:n.trim()||null}},{error:d}=await C.from("app_settings").upsert({key:"mlp_court_sponsors",value:JSON.stringify(l)},{onConflict:"key"});if(p(!1),d){w({title:"Save failed",description:d.message,variant:"destructive"});return}w({title:"Default court sponsors saved"}),a.invalidateQueries({queryKey:["app_settings","mlp_court_sponsors"]})};return e.jsxs(H,{title:"MLP Court Sponsors (Defaults)",className:"mt-6",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Default labels shown in match cards for the Championship and Grandstand courts at MLP events. Per-event overrides are set on each MLP Event row below."}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(M,{className:"text-xs",children:"Championship court"}),e.jsx(P,{className:"h-8",placeholder:"e.g. Toray CC",value:r,onChange:l=>t(l.target.value)})]}),e.jsxs("div",{children:[e.jsx(M,{className:"text-xs",children:"Grandstand court"}),e.jsx(P,{className:"h-8",placeholder:"e.g. (sponsor name or blank)",value:n,onChange:l=>c(l.target.value)})]})]}),e.jsx("div",{className:"flex justify-end mt-3",children:e.jsx(N,{size:"sm",disabled:!m||i,onClick:u,children:i?"Savingâ¦":"Save"})})]})}function Ja(){const[a,s]=o.useState(!1),{toast:r}=ge(),t=async()=>{s(!0);try{const{data:{user:n}}=await C.auth.getUser();if(!n){r({title:"Not signed in",variant:"destructive"});return}const{error:c}=await C.functions.invoke("mlp-team-notifications",{body:{test:!0,user_id:n.id,team_title:"New Jersey 5s"}});if(c)throw c;r({title:"Test push sent",description:"Should arrive within a few seconds."})}catch(n){r({title:"Failed",description:String((n==null?void 0:n.message)||n),variant:"destructive"})}finally{s(!1)}};return e.jsxs(H,{title:"MLP Push Notifications",icon:Se,className:"mt-6",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Send a sample MLP team-follow alert to your own devices. Use this to verify push delivery before relying on live cron events."}),e.jsxs(N,{onClick:t,disabled:a,size:"sm",children:[a?e.jsx(K,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Se,{className:"h-4 w-4 mr-1"}),"Send Test Push"]})]})}function Ga(){const a=G(),[s,r]=o.useState(""),{data:t,isLoading:n}=Y({queryKey:["player-name-aliases-admin"],queryFn:async()=>{const{data:m,error:u}=await C.from("player_name_aliases").select("id, alt_name, canonical_name, notes, updated_at").order("alt_name");if(u)throw u;return m||[]}}),c=o.useMemo(()=>{const m=s.trim().toLowerCase();return m?(t||[]).filter(u=>u.alt_name.toLowerCase().includes(m)||u.canonical_name.toLowerCase().includes(m)):t||[]},[t,s]),i=()=>{a.invalidateQueries({queryKey:["player-name-aliases-admin"]}),a.invalidateQueries({queryKey:["player-name-aliases"]}),a.invalidateQueries({queryKey:["mlp-team-roster"]})},p=async m=>{const{error:u}=await C.from("player_name_aliases").delete().eq("id",m);u?w({title:"Delete failed",description:u.message,variant:"destructive"}):(w({title:"Alias removed"}),i())};return e.jsx(H,{title:"Player Name Aliases",icon:ca,description:"Map roster/API names (left) to the canonical player name in our DB (right). Used for display and lookup â does not affect Pick'em scoring.",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ha,{onAdded:i}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(P,{placeholder:"Filter aliasesâ¦",value:s,onChange:m=>r(m.target.value),className:"h-8 text-xs"}),e.jsxs(J,{variant:"outline",className:"text-[10px] whitespace-nowrap",children:[(t==null?void 0:t.length)||0," total"]})]}),n?e.jsx("div",{className:"flex items-center justify-center py-8 text-muted-foreground",children:e.jsx(K,{className:"h-4 w-4 animate-spin"})}):c.length===0?e.jsx("div",{className:"text-center py-6 text-xs text-muted-foreground",children:t!=null&&t.length?"No matches.":"No aliases yet. Add one above."}):e.jsx("div",{className:"space-y-1 max-h-[500px] overflow-y-auto",children:c.map(m=>e.jsx(Va,{row:m,onChanged:i,onDelete:()=>p(m.id)},m.id))})]})})}function Va({row:a,onChanged:s,onDelete:r}){const[t,n]=o.useState(!1),[c,i]=o.useState(a.alt_name),[p,m]=o.useState(a.canonical_name),[u,l]=o.useState(a.notes||""),[d,f]=o.useState(!1),S=async()=>
4{if(!c.trim()||!p.trim())return;f(!0);const{error:y}=await C.from("player_name_aliases").update({alt_name:c.trim(),canonical_name:p.trim(),notes:u.trim()||null}).eq("id",a.id);f(!1),y?w({title:"Save failed",description:y.message,variant:"destructive"}):(w({title:"Updated"}),n(!1),s())};return t?e.jsxs("div",{className:"rounded-md border border-border/60 bg-muted/20 p-2 space-y-1.5",children:[e.jsxs("div",{className:"grid grid-cols-12 gap-1.5",children:[e.jsx(P,{className:"h-7 text-xs col-span-5",value:c,onChange:y=>i(y.target.value),placeholder:"Alt name"}),e.jsx("div",{className:"col-span-1 flex items-center justify-center text-muted-foreground",children:e.jsx(pe,{className:"h-3 w-3"})}),e.jsx(P,{className:"h-7 text-xs col-span-6",value:p,onChange:y=>m(y.target.value),placeholder:"Canonical name"})]}),e.jsx(P,{className:"h-7 text-xs",value:u,onChange:y=>l(y.target.value),placeholder:"Notes (optional)"}),e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(N,{size:"sm",variant:"ghost",className:"h-6 px-2",onClick:()=>{n(!1),i(a.alt_name),m(a.canonical_name),l(a.notes||"")},children:e.jsx(fe,{className:"h-3 w-3"})}),e.jsx(N,{size:"sm",className:"h-6 px-2",onClick:S,disabled:d||!c.trim()||!p.trim(),children:d?e.jsx(K,{className:"h-3 w-3 animate-spin"}):e.jsx(Re,{className:"h-3 w-3"})})]})]}):e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded bg-muted/30",children:[e.jsxs("span",{className:"text-xs flex-1 min-w-0 truncate",children:[e.jsx("span",{className:"text-muted-foreground",children:a.alt_name}),e.jsx(pe,{className:"inline h-3 w-3 mx-1.5 text-muted-foreground/60"}),e.jsx("span",{className:"font-score",children:a.canonical_name}),a.notes&&e.jsxs("span",{className:"text-[10px] text-muted-foreground ml-1.5",children:["· ",a.notes]})]}),e.jsx(N,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:()=>n(!0),children:e.jsx(qe,{className:"h-3 w-3"})}),e.jsx(N,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:r,children:e.jsx(ne,{className:"h-3 w-3"})})]})}function Ha({onAdded:a}){const[s,r]=o.useState(""),[t,n]=o.useState(""),[c,i]=o.useState(""),[p,m]=o.useState(!1),u=async()=>{if(!s.trim()||!t.trim())return;m(!0);const{error:l}=await C.from("player_name_aliases").insert({alt_name:s.trim(),canonical_name:t.trim(),notes:c.trim()||null});m(!1),l?w({title:"Add failed",description:l.code==="23505"?`Alias "${s.trim()}" already exists.`:l.message,variant:"destructive"}):(w({title:"Alias added"}),r(""),n(""),i(""),a())};return e.jsxs("div",{className:"rounded-lg border border-border/60 p-3 space-y-2",children:[e.jsx(M,{className:"text-xs font-score uppercase tracking-wide text-muted-foreground",children:"Add alias"}),e.jsxs("div",{className:"grid grid-cols-12 gap-1.5",children:[e.jsx(P,{className:"h-8 text-xs col-span-5",placeholder:"Alt name (e.g., Rafa Lenhard)",value:s,onChange:l=>r(l.target.value)}),e.jsx("div",{className:"col-span-1 flex items-center justify-center text-muted-foreground",children:e.jsx(pe,{className:"h-3 w-3"})}),e.jsx(P,{className:"h-8 text-xs col-span-5",placeholder:"Canonical (e.g., Rafael Lenhard)",value:t,onChange:l=>n(l.target.value)}),e.jsx(N,{size:"sm",className:"h-8 col-span-1 px-0",onClick:u,disabled:p||!s.trim()||!t.trim(),children:p?e.jsx(K,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(le,{className:"h-3.5 w-3.5"})})]}),e.jsx(P,{className:"h-7 text-xs",placeholder:"Notes (optional)",value:c,onChange:l=>i(l.target.value)})]})}const ms=o.memo(function(){const s=G(),[r,t]=o.useState("player"),[n,c]=o.useState(""),[i,p]=o.useState(null),[m,u]=o.useState(null),[l,d]=o.useState(!1),[f,S]=o.useState(!1),[y,g]=o.useState(null),[j,x]=o.useState(""),[v,b]=o.useState(!1),{allPlayers:E,loading:D}=Pe({defer:!1}),{getAvatarUrl:z}=Je(),{getTeamAvatarUrl:k}=ma(),T=o.useMemo(()=>{const h=j.toLowerCase(),L=E.filter(R=>R.toLowerCase().includes(h)).map(R=>({name:R,type:"player",hasAvatar:!!z(R)})),B=Ge.filter(R=>R.toLowerCase().includes(h)).map(R=>({name:R,type:"team",hasAvatar:!!k(R)}));return[...L.slice(0,50),...B.slice(0,20)]},[E,j,z,k]);o.useEffect(()=>{p(null),u(null),g(null)},[n,r]);const q=o.useCallback(h=>{const L=URL.createObjectURL(h);g(L),S(!0)},[]),$=o.useCallback(h=>{const L=new File([h],"cropped-avatar.jpg",{type:"image/jpeg"});p(L),u(URL.createObjectURL(h)),S(!1),y&&URL.revokeObjectURL(y)},[y]),_=async()=>
4{if(!i||!n.trim()){w.error("Please select a name and an image");return}d(!0);try{const h=n.toLowerCase().trim().replace(/\s+/g,"-"),B=`${h}.jpeg`,R=r==="player"?"player-avatars":"team-avatars";if(r==="player"){const{data:V}=await C.storage.from(R).list();if(V){const ee=V.filter(ae=>ae.name.toLowerCase().split(".")[0]===h).map(ae=>ae.name);ee.length>0&&(await C.storage.from(R).remove(ee),await new Promise(ae=>setTimeout(ae,500)))}}const{error:U}=await C.storage.from(R).upload(B,i,{upsert:!0,cacheControl:"0"});if(U)throw U;w.success(`${r==="player"?"Player":"Team"} avatar uploaded successfully!`);try{await C.from("app_settings").upsert({key:"avatar_cache_version",value:String(Date.now()),updated_at:new Date().toISOString()},{onConflict:"key"})}catch(V){console.warn("[ManageTab] Failed to bump avatar_cache_version",V)}r==="player"?(s.invalidateQueries({queryKey:["avatar-bucket-urls"]}),s.invalidateQueries({queryKey:["player-avatar"]}),s.invalidateQueries({queryKey:["all-avatars"]})):(s.invalidateQueries({queryKey:["team-avatar-urls"]}),s.invalidateQueries({queryKey:["all-avatars"]})),c(""),p(null),u(null),x("")}catch(h){w.error(h.message||"Failed to upload avatar")}finally{d(!1)}},F=async()=>{b(!0);try{const h="https://grwhdhnlafqrcmiuqhhi.supabase.co",{data:{session:L}}=await C.auth.getSession();if(!L)throw new Error("Not authenticated");const B=await fetch(`${h}/functions/v1/export-avatars-for-xcode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${L.access_token}`}});if(!B.ok){const ee=await B.json().catch(()=>({}));throw new Error(ee.error||`Export failed: ${B.statusText}`)}const R=await B.blob(),U=window.URL.createObjectURL(R),V=document.createElement("a");V.href=U,V.download=`avatars-for-xcode-${Date.now()}.zip`,document.body.appendChild(V),V.click(),window.URL.revokeObjectURL(U),document.body.removeChild(V),w.success("Avatar package downloaded! Extract and import into Xcode Assets.")}catch(h){w.error(h.message||"Failed to export avatars")}finally{b(!1)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(H,{title:"Avatar Upload",icon:ie,children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs(M,{className:"flex items-center gap-2 mb-2",children:[e.jsx(Me,{className:"h-4 w-4"}),"Search Players & Teams"]}),e.jsx(P,{value:j,onChange:h=>x(h.target.value),placeholder:"Start typing to search...",className:"max-w-md"}),j.length>=2&&e.jsx("div",{className:"border rounded-lg max-h-[200px] overflow-y-auto mt-2",children:D?e.jsx("div",{className:"p-4 text-center text-muted-foreground",children:e.jsx(K,{className:"h-4 w-4 animate-spin mx-auto"})}):T.length===0?e.jsx("div",{className:"p-4 text-center text-muted-foreground",children:"No results found"}):e.jsx("div",{className:"divide-y",children:T.slice(0,20).map(h=>e.jsxs("button",{onClick:()=>{c(h.name),t(h.type),x("")},className:Z("w-full p-2 text-left hover:bg-muted flex items-center gap-2 transition-colors text-sm",n===h.name&&r===h.type&&"bg-primary/10"),children:[h.type==="player"?e.jsx(te,{name:h.name,className:"h-6 w-6"}):e.jsx("div",{className:"w-6 h-6 rounded-full bg-muted flex items-center justify-center text-xs font-bold",children:h.name.charAt(0)}),e.jsx("span",{className:"flex-1 truncate",children:h.name}),e.jsx(J,{variant:"outline",className:"text-[10px]",children:h.type}),h.hasAvatar&&e.jsx(Ae,{className:"h-3 w-3 text-green-500"})]},`${h.type}-${h.name}`))})})]}),n&&e.jsxs("div",{className:"p-3 bg-muted rounded-lg flex items-center gap-3",children:[e.jsx(te,{name:n,className:"h-10 w-10"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium",children:n}),e.jsx("div",{className:"text-xs text-muted-foreground capitalize",children:r})]}),e.jsx(N,{variant:"ghost",size:"sm",onClick:()=>c(""),children:"Clear"})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(ha,{onFileSelect:q,disabled:!n,previewUrl:m,onClear:()=>{p(null),u(null)}}),e.jsx(N,{onClick:_,disabled:l||!i||!n,className:"w-full",children:l?e.jsxs(e.Fragment,{children:[e.jsx(K,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ie,{className:"h-4 w-4 mr-2"}),"Upload Avatar"]})})]})]})}),e.jsx(da,{}),e.jsx(ga,{}),e.jsx(pa,{}),e.jsxs(H,{title:"Avatar Export",icon:Le,children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Export all player avatars as a ZIP for Xcode Asset import."}),e.jsxs(N,{onClick:F,disabled:v,variant:"outline",size:"sm",children:[v?e.jsx(K,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Le,{className:"h-4 w-4 mr-1"}),"Export Avatars"]})]}),y&&e.jsx(ua,{open:f,onClose:()=>{S(!1),y&&URL.revokeObjectURL(y),g(null)},imageSrc:y,onCropComplete:$}),e.jsx(H,{title:"Event Guide",className:"mt-6",children:e.jsx(va,{})}),e.jsx(_a,{}),e.jsx(ba,{}),e.jsx(wa,{}),e.jsx(Pa,{}),e.jsx(Ga,{}),e.jsx(Ka,{}),e.jsx(Wa,{}),e.jsx(Ia,{}),e.jsx(Ja,{})]})});export{ms as ManageTab};
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.