1import{$ as Et,r as l,a8 as we,a9 as Vt,j as t,aa as Vn,g as ce,ab as Bs,B as K,X as Un,s as Q,q as O,T as Vs,p as Se,I as Ge,D as Ut,h as Wt,_ as Ht,i as Gt,t as et,v as tt,O as st,w as nt,y as Ne,a1 as wt,C as hn,K as Er,a as Dr,L as Tr,Z as gn,a5 as $r,R as xn,a0 as As,a6 as Mr}from"./index-DnLpPdJu.js";import{T as Ar,a as Pr,b as Ft,c as Bt}from"./tabs-6oruROEX.js";import{T as Wn}from"./textarea-BGHgl9MJ.js";import{I as Hn}from"./info-DLwT-bFw.js";import{i as Us,s as us,p as Lr}from"./matchScore-C9pe5mlo.js";import{S as kt}from"./save-yZ18sOqh.js";import{C as vn}from"./checkbox-U8QRCI9x.js";import{L as Ie}from"./loader-circle-p4PmW0Hd.js";import{C as bn}from"./clock-I4IgI4BL.js";import{C as Or}from"./circle-check-CAnLWdwS.js";import{M as Ir}from"./mail-v2fqe1pM.js";import{E as jn}from"./eye-DKo7S9wJ.js";import{S as fs}from"./send-DeHfzYDf.js";import{a as zr,u as qr,d as Fr}from"./podium-B1GFD2BB.js";import{C as Ws}from"./camera-CnKtd2yN.js";import{T as ms}from"./trash-2-9vLPNF96.js";import{B as Br}from"./badge-Ci6bMlns.js";import{C as yn}from"./chevron-left-Bty14ADU.js";import{A as Vr}from"./arrow-left-Br53sykA.js";import{D as Ur}from"./download-BSPmfIif.js";import{R as Wr}from"./rotate-ccw-BClUz8C0.js";import{U as Hr}from"./users-BdNpofaM.js";import{S as Gr}from"./scale--t5cMFVs.js";/** 2 * @license lucide-react v0.462.0 - ISC 3 * 4 * This source code is licensed under the ISC license. 5 * See the LICENSE file in the root directory of this source tree. 6 */const Xr=Et("BookmarkPlus",[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}],["line",{x1:"12",x2:"12",y1:"7",y2:"13",key:"1cppfj"}],["line",{x1:"15",x2:"9",y1:"10",y2:"10",key:"1gty7f"}]]);/** 7 * @license lucide-react v0.462.0 - ISC 8 * 9 * This source code is licensed under the ISC license. 10 * See the LICENSE file in the root directory of this source tree. 11 */const Dt=Et("GripVertical",[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]]);/** 12 * @license lucide-react v0.462.0 - ISC 13 * 14 * This source code is licensed under the ISC license. 15 * See the LICENSE file in the root directory of this source tree. 16 */const Kr=Et("ImagePlus",[["path",{d:"M16 5h6",key:"1vod17"}],["path",{d:"M19 2v6",key:"4bpg5p"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5",key:"1ue2ih"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}]]);/** 17 * @license lucide-react v0.462.0 - ISC 18 * 19 * This source code is licensed under the ISC license. 20 * See the LICENSE file in the root directory of this source tree. 21 */const Yr=Et("RotateCw",[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]]);/** 22 * @license lucide-react v0.462.0 - ISC 23 * 24 * This source code is licensed under the ISC license. 25 * See the LICENSE file in the root directory of this source tree. 26 */const Ps=Et("Shuffle",[["path",{d:"m18 14 4 4-4 4",key:"10pe0f"}],["path",{d:"m18 2 4 4-4 4",key:"pucp1d"}],["path",{d:"M2 18h1.973a4 4 0 0 0 3.3-1.7l5.454-8.6a4 4 0 0 1 3.3-1.7H22",key:"1ailkh"}],["path",{d:"M2 6h1.972a4 4 0 0 1 3.6 2.2",key:"km57vx"}],["path",{d:"M22 18h-6.041a4 4 0 0 1-3.3-1.8l-.359-.45",key:"os18l9"}]]);/** 27 * @license lucide-react v0.462.0 - ISC 28 * 29 * This source code is licensed under the ISC license. 30 * See the LICENSE file in the root directory of this source tree. 31 */const Xt=Et("WandSparkles",[["path",{d:"m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72",key:"ul74o6"}],["path",{d:"m14 7 3 3",key:"1r5n42"}],["path",{d:"M5 6v4",key:"ilb8ba"}],["path",{d:"M19 14v4",key:"blhpug"}],["path",{d:"M10 2v2",key:"7u0qdc"}],["path",{d:"M7 8H3",key:"zfb6yr"}],["path",{d:"M21 16h-4",key:"1cnmox"}],["path",{d:"M11 3H9",key:"1obp7u"}]]),_s=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function Tt(e){const s=Object.prototype.toString.call(e);return s==="[object Window]"||s==="[object global]"}function Ys(e){return"nodeType"in e}function ze(e){var s,n;return e?Tt(e)?e:Ys(e)&&(s=(n=e.ownerDocument)==null?void 0:n.defaultView)!=null?s:window:window}function Js(e){const{Document:s}=ze(e);return e instanceof s}function ts(e){return Tt(e)?!1:e instanceof ze(e).HTMLElement}function Gn(e){return e instanceof ze(e).SVGElement}function $t(e){return e?Tt(e)?e.document:Ys(e)?Js(e)?e:ts(e)||Gn(e)?e.ownerDocument:document:document:document}const pt=_s?l.useLayoutEffect:l.useEffect;function ws(e){const s=l.useRef(e);return pt(()=>{s.current=e}),l.useCallback(function(){for(var n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];return s.current==null?void 0:s.current(...r)},[])}function Jr(){const e=l.useRef(null),s=l.useCallback((r,o)=>{e.current=setInterval(r,o)},[]),n=l.useCallback(()=>{e.current!==null&&(clearInterval(e.current),e.current=null)},[]);return[s,n]}function Qt(e,s){s===void 0&&(s=[e]);const n=l.useRef(e);return pt(()=>{n.current!==e&&(n.current=e)},s),n}function ss(e,s){const n=l.useRef();return l.useMemo(()=>{const r=e(n.current);return n.current=r,r},[...s])}function ps(e){const s=ws(e),n=l.useRef(null),r=l.useCallback(o=>{o!==n.current&&(s==null||s(o,n.current)),n.current=o},[]);return[n,r]}function hs(e){const s=l.useRef();return l.useEffect(()=>{s.current=e},[e]),s.current}let Ls={};function Ns(e,s){return l.useMemo(()=>
31{if(s)return s;const n=Ls[e]==null?0:Ls[e]+1;return Ls[e]=n,e+"-"+n},[e,s])}function Xn(e){return function(s){for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return r.reduce((i,d)=>{const c=Object.entries(d);for(const[u,h]of c){const y=i[u];y!=null&&(i[u]=y+e*h)}return i},{...s})}}const Rt=Xn(1),gs=Xn(-1);function Qr(e){return"clientX"in e&&"clientY"in e}function Qs(e){if(!e)return!1;const{KeyboardEvent:s}=ze(e.target);return s&&e instanceof s}function Zr(e){if(!e)return!1;const{TouchEvent:s}=ze(e.target);return s&&e instanceof s}function xs(e){if(Zr(e)){if(e.touches&&e.touches.length){const{clientX:s,clientY:n}=e.touches[0];return{x:s,y:n}}else if(e.changedTouches&&e.changedTouches.length){const{clientX:s,clientY:n}=e.changedTouches[0];return{x:s,y:n}}}return Qr(e)?{x:e.clientX,y:e.clientY}:null}const Zt=Object.freeze({Translate:{toString(e){if(!e)return;const{x:s,y:n}=e;return"translate3d("+(s?Math.round(s):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;const{scaleX:s,scaleY:n}=e;return"scaleX("+s+") scaleY("+n+")"}},Transform:{toString(e){if(e)return[Zt.Translate.toString(e),Zt.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:s,duration:n,easing:r}=e;return s+" "+n+"ms "+r}}}),_n="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function ea(e){return e.matches(_n)?e:e.querySelector(_n)}const ta={display:"none"};function sa(e){let{id:s,value:n}=e;return we.createElement("div",{id:s,style:ta},n)}function na(e){let{id:s,announcement:n,ariaLiveType:r="assertive"}=e;const o={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return we.createElement("div",{id:s,style:o,role:"status","aria-live":r,"aria-atomic":!0},n)}function ra(){const[e,s]=l.useState("");return{announce:l.useCallback(r=>{r!=null&&s(r)},[]),announcement:e}}const Kn=l.createContext(null);function aa(e){const s=l.useContext(Kn);l.useEffect(()=>{if(!s)throw new Error("useDndMonitor must be used within a children of <DndContext>");return s(e)},[e,s])}function ia(){const[e]=l.useState(()=>new Set),s=l.useCallback(r=>(e.add(r),()=>e.delete(r)),[e]);return[l.useCallback(r=>{let{type:o,event:i}=r;e.forEach(d=>{var c;return(c=d[o])==null?void 0:c.call(d,i)})},[e]),s]}const oa={draggable:` 32 To pick up a draggable item, press the space bar. 33 While dragging, use the arrow keys to move the item. 34 Press space again to drop the item in its new position, or press escape to cancel. 35 `},la={onDragStart(e){let{active:s}=e;return"Picked up draggable item "+s.id+"."},onDragOver(e){let{active:s,over:n}=e;return n?"Draggable item "+s.id+" was moved over droppable area "+n.id+".":"Draggable item "+s.id+" is no longer over a droppable area."},onDragEnd(e){let{active:s,over:n}=e;return n?"Draggable item "+s.id+" was dropped over droppable area "+n.id:"Draggable item "+s.id+" was dropped."},onDragCancel(e){let{active:s}=e;return"Dragging was cancelled. Draggable item "+s.id+" was dropped."}};function ca(e){let{announcements:s=la,container:n,hiddenTextDescribedById:r,screenReaderInstructions:o=oa}=e;const{announce:i,announcement:d}=ra(),c=Ns("DndLiveRegion"),[u,h]=l.useState(!1);if(l.useEffect(()=>{h(!0)},[]),aa(l.useMemo(()=>({onDragStart(m){let{active:b}=m;i(s.onDragStart({active:b}))},onDragMove(m){let{active:b,over:N}=m;s.onDragMove&&i(s.onDragMove({active:b,over:N}))},onDragOver(m){let{active:b,over:N}=m;i(s.onDragOver({active:b,over:N}))},onDragEnd(m){let{active:b,over:N}=m;i(s.onDragEnd({active:b,over:N}))},onDragCancel(m){let{active:b,over:N}=m;i(s.onDragCancel({active:b,over:N}))}}),[i,s])),!u)return null;const y=we.createElement(we.Fragment,null,we.createElement(sa,{id:r,value:o.draggable}),we.createElement(na,{id:c,announcement:d}));return n?Vt.createPortal(y,n):y}var ke;(function(e){e.DragStart="dragStart",e.DragMove="dragMove",e.DragEnd="dragEnd",e.DragCancel="dragCancel",e.DragOver="dragOver",e.RegisterDroppable="registerDroppable",e.SetDroppableDisabled="setDroppableDisabled",e.UnregisterDroppable="unregisterDroppable"})(ke||(ke={}));function vs(){}function bs(e,s){return l.useMemo(()=>({sensor:e,options:s??{}}),[e,s])}function Yn(){for(var e=arguments.length,s=new Array(e),n=0;n<e;n++)s[n]=arguments[n];return l.useMemo(()=>[...s].filter(r=>r!=null),[...s])}const rt=Object.freeze({x:0,y:0});function Jn(e,s){return Math.sqrt(Math.pow(e.x-s.x,2)+Math.pow(e.y-s.y,2))}function da(e,s){const n=xs(e);if(!n)return"0 0";const r={x:(n.x-s.left)/s.width*100,y:(n.y-s.top)/s.height*100};return r.x+"% "+r.y+"%"}function Qn(e,s){let{data:{value:n}}=e,{data:{value:r}}=s;return n-r}function ua(e,s){let{data:{value:n}}=e,{data:{value:r}}=s;return r-n}function fa(e){let{left:s,top:n,height:r,width:o}=e;return[{x:s,y:n},{x:s+o,y:n},{x:s,y:n+r},{x:s+o,y:n+r}]}function ma(e,s){if(!e||e.length===0)return null;const[n]=e;return n[s]}function wn(e,s,n){return s===void 0&&(s=e.left),n===void 0&&(n=e.top),{x:s+e.width*.5,y:n+e.height*.5}}const Zn=e=>{let{collisionRect:s,droppableRects:n,droppableContainers:r}=e;const o=wn(s,s.left,s.top),i=[];for(const d of r){const{id:c}=d,u=n.get(c);if(u){const h=Jn(wn(u),o);i.push({id:c,data:{droppableContainer:d,value:h}})}}return i.sort(Qn)};function pa(e,s){const n=Math.max(s.top,e.top),r=Math.max(s.left,e.left),o=Math.min(s.left+s.width,e.left+e.width),i=Math.min(s.top+s.height,e.top+e.height),d=o-r,c=i-n;if(r<o&&n<i){const u=s.width*s.height,h=e.width*e.height,y=d*c,m=y/(u+h-y);return Number(m.toFixed(4))}return 0}
35const Zs=e=>{let{collisionRect:s,droppableRects:n,droppableContainers:r}=e;const o=[];for(const i of r){const{id:d}=i,c=n.get(d);if(c){const u=pa(c,s);u>0&&o.push({id:d,data:{droppableContainer:i,value:u}})}}return o.sort(ua)};function ha(e,s){const{top:n,left:r,bottom:o,right:i}=s;return n<=e.y&&e.y<=o&&r<=e.x&&e.x<=i}const er=e=>{let{droppableContainers:s,droppableRects:n,pointerCoordinates:r}=e;if(!r)return[];const o=[];for(const i of s){const{id:d}=i,c=n.get(d);if(c&&ha(r,c)){const h=fa(c).reduce((m,b)=>m+Jn(r,b),0),y=Number((h/4).toFixed(4));o.push({id:d,data:{droppableContainer:i,value:y}})}}return o.sort(Qn)};function ga(e,s,n){return{...e,scaleX:s&&n?s.width/n.width:1,scaleY:s&&n?s.height/n.height:1}}function tr(e,s){return e&&s?{x:e.left-s.left,y:e.top-s.top}:rt}function xa(e){return function(n){for(var r=arguments.length,o=new Array(r>1?r-1:0),i=1;i<r;i++)o[i-1]=arguments[i];return o.reduce((d,c)=>({...d,top:d.top+e*c.y,bottom:d.bottom+e*c.y,left:d.left+e*c.x,right:d.right+e*c.x}),{...n})}}const va=xa(1);function sr(e){if(e.startsWith("matrix3d(")){const s=e.slice(9,-1).split(/, /);return{x:+s[12],y:+s[13],scaleX:+s[0],scaleY:+s[5]}}else if(e.startsWith("matrix(")){const s=e.slice(7,-1).split(/, /);return{x:+s[4],y:+s[5],scaleX:+s[0],scaleY:+s[3]}}return null}function ba(e,s,n){const r=sr(s);if(!r)return e;const{scaleX:o,scaleY:i,x:d,y:c}=r,u=e.left-d-(1-o)*parseFloat(n),h=e.top-c-(1-i)*parseFloat(n.slice(n.indexOf(" ")+1)),y=o?e.width/o:e.width,m=i?e.height/i:e.height;return{width:y,height:m,top:h,right:u+y,bottom:h+m,left:u}}const ja={ignoreTransform:!1};function ns(e,s){s===void 0&&(s=ja);let n=e.getBoundingClientRect();if(s.ignoreTransform){const{transform:h,transformOrigin:y}=ze(e).getComputedStyle(e);h&&(n=ba(n,h,y))}const{top:r,left:o,width:i,height:d,bottom:c,right:u}=n;return{top:r,left:o,width:i,height:d,bottom:c,right:u}}function Nn(e){return ns(e,{ignoreTransform:!0})}function ya(e){const s=e.innerWidth,n=e.innerHeight;return{top:0,left:0,right:s,bottom:n,width:s,height:n}}function _a(e,s){return s===void 0&&(s=ze(e).getComputedStyle(e)),s.position==="fixed"}function wa(e,s){s===void 0&&(s=ze(e).getComputedStyle(e));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(o=>{const i=s[o];return typeof i=="string"?n.test(i):!1})}function en(e,s){const n=[];function r(o){if(s!=null&&n.length>=s||!o)return n;if(Js(o)&&o.scrollingElement!=null&&!n.includes(o.scrollingElement))return n.push(o.scrollingElement),n;if(!ts(o)||Gn(o)||n.includes(o))return n;const i=ze(e).getComputedStyle(o);return o!==e&&wa(o,i)&&n.push(o),_a(o,i)?n:r(o.parentNode)}return e?r(e):n}function nr(e){const[s]=en(e,1);return s??null}function Os(e){return!_s||!e?null:Tt(e)?e:Ys(e)?Js(e)||e===$t(e).scrollingElement?window:ts(e)?e:null:null}function rr(e){return Tt(e)?e.scrollX:e.scrollLeft}function ar(e){return Tt(e)?e.scrollY:e.scrollTop}function Hs(e){return{x:rr(e),y:ar(e)}}var De;(function(e){e[e.Forward=1]="Forward",e[e.Backward=-1]="Backward"})(De||(De={}));function ir(e){return!_s||!e?!1:e===document.scrollingElement}function or(e){const s={x:0,y:0},n=ir(e)?{height:window.innerHeight,width:window.innerWidth}:{height:e.clientHeight,width:e.clientWidth},r={x:e.scrollWidth-n.width,y:e.scrollHeight-n.height},o=e.scrollTop<=s.y,i=e.scrollLeft<=s.x,d=e.scrollTop>=r.y,c=e.scrollLeft>=r.x;return{isTop:o,isLeft:i,isBottom:d,isRight:c,maxScroll:r,minScroll:s}}const Na={x:.2,y:.2};function Sa(e,s,n,r,o){let{top:i,left:d,right:c,bottom:u}=n;r===void 0&&(r=10),o===void 0&&(o=Na);const{isTop:h,isBottom:y,isLeft:m,isRight:b}=or(e),N={x:0,y:0},G={x:0,y:0},T={height:s.height*o.y,width:s.width*o.x};return!h&&i<=s.top+T.height?(N.y=De.Backward,G.y=r*Math.abs((s.top+T.height-i)/T.height)):!y&&u>=s.bottom-T.height&&(N.y=De.Forward,G.y=r*Math.abs((s.bottom-T.height-u)/T.height)),!b&&c>=s.right-T.width?(N.x=De.Forward,G.x=r*Math.abs((s.right-T.width-c)/T.width)):!m&&d<=s.left+T.width&&(N.x=De.Backward,G.x=r*Math.abs((s.left+T.width-d)/T.width)),{direction:N,speed:G}}function Ca(e){if(e===document.scrollingElement){const{innerWidth:i,innerHeight:d}=window;return{top:0,left:0,right:i,bottom:d,width:i,height:d}}const{top:s,left:n,right:r,bottom:o}=e.getBoundingClientRect();return{top:s,left:n,right:r,bottom:o,width:e.clientWidth,height:e.clientHeight}}function lr(e){return e.reduce((s,n)=>Rt(s,Hs(n)),rt)}function ka(e){return e.reduce((s,n)=>s+rr(n),0)}function Ra(e){return e.reduce((s,n)=>s+ar(n),0)}function cr(e,s){if(s===void 0&&(s=ns),!e)return;const{top:n,left:r,bottom:o,right:i}=s(e);
35nr(e)&&(o<=0||i<=0||n>=window.innerHeight||r>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}const Ea=[["x",["left","right"],ka],["y",["top","bottom"],Ra]];class tn{constructor(s,n){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const r=en(n),o=lr(r);this.rect={...s},this.width=s.width,this.height=s.height;for(const[i,d,c]of Ea)for(const u of d)Object.defineProperty(this,u,{get:()=>{const h=c(r),y=o[i]-h;return this.rect[u]+y},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class Kt{constructor(s){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var r;return(r=this.target)==null?void 0:r.removeEventListener(...n)})},this.target=s}add(s,n,r){var o;(o=this.target)==null||o.addEventListener(s,n,r),this.listeners.push([s,n,r])}}function Da(e){const{EventTarget:s}=ze(e);return e instanceof s?e:$t(e)}function Is(e,s){const n=Math.abs(e.x),r=Math.abs(e.y);return typeof s=="number"?Math.sqrt(n**2+r**2)>s:"x"in s&&"y"in s?n>s.x&&r>s.y:"x"in s?n>s.x:"y"in s?r>s.y:!1}var Ye;(function(e){e.Click="click",e.DragStart="dragstart",e.Keydown="keydown",e.ContextMenu="contextmenu",e.Resize="resize",e.SelectionChange="selectionchange",e.VisibilityChange="visibilitychange"})(Ye||(Ye={}));function Sn(e){e.preventDefault()}function Ta(e){e.stopPropagation()}var ge;(function(e){e.Space="Space",e.Down="ArrowDown",e.Right="ArrowRight",e.Left="ArrowLeft",e.Up="ArrowUp",e.Esc="Escape",e.Enter="Enter",e.Tab="Tab"})(ge||(ge={}));const dr={start:[ge.Space,ge.Enter],cancel:[ge.Esc],end:[ge.Space,ge.Enter,ge.Tab]},$a=(e,s)=>{let{currentCoordinates:n}=s;switch(e.code){case ge.Right:return{...n,x:n.x+25};case ge.Left:return{...n,x:n.x-25};case ge.Down:return{...n,y:n.y+25};case ge.Up:return{...n,y:n.y-25}}};class ur{constructor(s){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=s;const{event:{target:n}}=s;this.props=s,this.listeners=new Kt($t(n)),this.windowListeners=new Kt(ze(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Ye.Resize,this.handleCancel),this.windowListeners.add(Ye.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Ye.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:s,onStart:n}=this.props,r=s.node.current;r&&cr(r),n(rt)}handleKeyDown(s){if(Qs(s)){const{active:n,context:r,options:o}=this.props,{keyboardCodes:i=dr,coordinateGetter:d=$a,scrollBehavior:c="smooth"}=o,{code:u}=s;if(i.end.includes(u)){this.handleEnd(s);return}if(i.cancel.includes(u)){this.handleCancel(s);return}const{collisionRect:h}=r.current,y=h?{x:h.left,y:h.top}:rt;this.referenceCoordinates||(this.referenceCoordinates=y);const m=d(s,{active:n,context:r.current,currentCoordinates:y});if(m){const b=gs(m,y),N={x:0,y:0},{scrollableAncestors:G}=r.current;for(const T of G){const I=s.code,{isTop:E,isRight:$,isLeft:B,isBottom:Y,maxScroll:q,minScroll:g}=or(T),v=Ca(T),C={x:Math.min(I===ge.Right?v.right-v.width/2:v.right,Math.max(I===ge.Right?v.left:v.left+v.width/2,m.x)),y:Math.min(I===ge.Down?v.bottom-v.height/2:v.bottom,Math.max(I===ge.Down?v.top:v.top+v.height/2,m.y))},F=I===ge.Right&&!$||I===ge.Left&&!B,z=I===ge.Down&&!Y||I===ge.Up&&!E;if(F&&C.x!==m.x){const L=T.scrollLeft+b.x,f=I===ge.Right&&L<=q.x||I===ge.Left&&L>=g.x;if(f&&!b.y){T.scrollTo({left:L,behavior:c});return}f?N.x=T.scrollLeft-L:N.x=I===ge.Right?T.scrollLeft-q.x:T.scrollLeft-g.x,N.x&&T.scrollBy({left:-N.x,behavior:c});break}else if(z&&C.y!==m.y){const L=T.scrollTop+b.y,f=I===ge.Down&&L<=q.y||I===ge.Up&&L>=g.y;if(f&&!b.x){T.scrollTo({top:L,behavior:c});return}f?N.y=T.scrollTop-L:N.y=I===ge.Down?T.scrollTop-q.y:T.scrollTop-g.y,N.y&&T.scrollBy({top:-N.y,behavior:c});break}}this.handleMove(s,Rt(gs(m,this.referenceCoordinates),N))}}}handleMove(s,n){const{onMove:r}=this.props;s.preventDefault(),r(n)}handleEnd(s){const{onEnd:n}=this.props;s.preventDefault(),this.detach(),n()}handleCancel(s){const{onCancel:n}=this.props;s.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}ur.activators=[{eventName:"onKeyDown",handler:(e,s,n)=>{let{keyboardCodes:r=dr,onActivation:o}=s,{active:i}=n;const{code:d}=e.nativeEvent;if(r.start.includes(d)){const c=i.activatorNode.current;return c&&e.target!==c?!1:(e.preventDefault(),o==null||o({event:e.nativeEvent}),!0)}return!1}}];function Cn(e){return!!(e&&"distance"in e)}function kn(e){return!!(e&&"delay"in e)}class sn{constructor(s,n,r){var o;r===void 0&&(r=Da(s.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=s,this.events=n;const{event:i}=s,{target:d}=i;this.props=s,this.events=n,this.document=$t(d),this.documentListeners=new Kt(this.document),this.listeners=new Kt(r),this.windowListeners=new Kt(ze(d)),this.initialCoordinates=(o=xs(i))!=null?o:rt,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:s,props:{options:{activationConstraint:n,bypassActivationConstraint:r}}}=this;if(this.listeners.add(s.move.name,this.handleMove,{passive:!1}),this.listeners.add(s.end.name,this.handleEnd),s.cancel&&this.listeners.add(s.cancel.name,this.handleCancel),this.windowListeners.add(Ye.Resize,this.handleCancel),this.windowListeners.add(Ye.DragStart,Sn),this.windowListeners.add(Ye.VisibilityChange,this.handleCancel),this.windowListeners.add(Ye.ContextMenu,Sn),this.documentListeners.add(Ye.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(kn(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(Cn(n)){this.handlePending(n);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(s,n){const{active:r,onPending:o}=this.props;o(r,s,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:s}=this,{onStart:n}=this.props;s&&(this.activated=!0,this.documentListeners.add(Ye.Click,Ta,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Ye.SelectionChange,this.removeTextSelection),n(s))}handleMove(s){var n;const{activated:r,initialCoordinates:o,props:i}=this,{onMove:d,options:{activationConstraint:c}}=i;if(!o)return;const u=(n=xs(s))!=null?n:rt,h=gs(o,u);
35if(!r&&c){if(Cn(c)){if(c.tolerance!=null&&Is(h,c.tolerance))return this.handleCancel();if(Is(h,c.distance))return this.handleStart()}if(kn(c)&&Is(h,c.tolerance))return this.handleCancel();this.handlePending(c,h);return}s.cancelable&&s.preventDefault(),d(u)}handleEnd(){const{onAbort:s,onEnd:n}=this.props;this.detach(),this.activated||s(this.props.active),n()}handleCancel(){const{onAbort:s,onCancel:n}=this.props;this.detach(),this.activated||s(this.props.active),n()}handleKeydown(s){s.code===ge.Esc&&this.handleCancel()}removeTextSelection(){var s;(s=this.document.getSelection())==null||s.removeAllRanges()}}const Ma={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class Ss extends sn{constructor(s){const{event:n}=s,r=$t(n.target);super(s,Ma,r)}}Ss.activators=[{eventName:"onPointerDown",handler:(e,s)=>{let{nativeEvent:n}=e,{onActivation:r}=s;return!n.isPrimary||n.button!==0?!1:(r==null||r({event:n}),!0)}}];const Aa={move:{name:"mousemove"},end:{name:"mouseup"}};var Gs;(function(e){e[e.RightClick=2]="RightClick"})(Gs||(Gs={}));class Pa extends sn{constructor(s){super(s,Aa,$t(s.event.target))}}Pa.activators=[{eventName:"onMouseDown",handler:(e,s)=>{let{nativeEvent:n}=e,{onActivation:r}=s;return n.button===Gs.RightClick?!1:(r==null||r({event:n}),!0)}}];const zs={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class nn extends sn{constructor(s){super(s,zs)}static setup(){return window.addEventListener(zs.move.name,s,{capture:!1,passive:!1}),function(){window.removeEventListener(zs.move.name,s)};function s(){}}}nn.activators=[{eventName:"onTouchStart",handler:(e,s)=>{let{nativeEvent:n}=e,{onActivation:r}=s;const{touches:o}=n;return o.length>1?!1:(r==null||r({event:n}),!0)}}];var Yt;(function(e){e[e.Pointer=0]="Pointer",e[e.DraggableRect=1]="DraggableRect"})(Yt||(Yt={}));var js;(function(e){e[e.TreeOrder=0]="TreeOrder",e[e.ReversedTreeOrder=1]="ReversedTreeOrder"})(js||(js={}));function La(e){let{acceleration:s,activator:n=Yt.Pointer,canScroll:r,draggingRect:o,enabled:i,interval:d=5,order:c=js.TreeOrder,pointerCoordinates:u,scrollableAncestors:h,scrollableAncestorRects:y,delta:m,threshold:b}=e;const N=Ia({delta:m,disabled:!i}),[G,T]=Jr(),I=l.useRef({x:0,y:0}),E=l.useRef({x:0,y:0}),$=l.useMemo(()=>{switch(n){case Yt.Pointer:return u?{top:u.y,bottom:u.y,left:u.x,right:u.x}:null;case Yt.DraggableRect:return o}},[n,o,u]),B=l.useRef(null),Y=l.useCallback(()=>{const g=B.current;if(!g)return;const v=I.current.x*E.current.x,C=I.current.y*E.current.y;g.scrollBy(v,C)},[]),q=l.useMemo(()=>c===js.TreeOrder?[...h].reverse():h,[c,h]);l.useEffect(()=>{if(!i||!h.length||!$){T();return}for(const g of q){if((r==null?void 0:r(g))===!1)continue;const v=h.indexOf(g),C=y[v];if(!C)continue;const{direction:F,speed:z}=Sa(g,C,$,s,b);for(const L of["x","y"])N[L][F[L]]||(z[L]=0,F[L]=0);if(z.x>0||z.y>0){T(),B.current=g,G(Y,d),I.current=z,E.current=F;return}}I.current={x:0,y:0},E.current={x:0,y:0},T()}
35,[s,Y,r,T,i,d,JSON.stringify($),JSON.stringify(N),G,h,q,y,JSON.stringify(b)])}const Oa={x:{[De.Backward]:!1,[De.Forward]:!1},y:{[De.Backward]:!1,[De.Forward]:!1}};function Ia(e){let{delta:s,disabled:n}=e;const r=hs(s);return ss(o=>{if(n||!r||!o)return Oa;const i={x:Math.sign(s.x-r.x),y:Math.sign(s.y-r.y)};return{x:{[De.Backward]:o.x[De.Backward]||i.x===-1,[De.Forward]:o.x[De.Forward]||i.x===1},y:{[De.Backward]:o.y[De.Backward]||i.y===-1,[De.Forward]:o.y[De.Forward]||i.y===1}}},[n,s,r])}function za(e,s){const n=s!=null?e.get(s):void 0,r=n?n.node.current:null;return ss(o=>{var i;return s==null?null:(i=r??o)!=null?i:null},[r,s])}function qa(e,s){return l.useMemo(()=>e.reduce((n,r)=>{const{sensor:o}=r,i=o.activators.map(d=>({eventName:d.eventName,handler:s(d.handler,r)}));return[...n,...i]},[]),[e,s])}var es;(function(e){e[e.Always=0]="Always",e[e.BeforeDragging=1]="BeforeDragging",e[e.WhileDragging=2]="WhileDragging"})(es||(es={}));var Xs;(function(e){e.Optimized="optimized"})(Xs||(Xs={}));const Rn=new Map;function Fa(e,s){let{dragging:n,dependencies:r,config:o}=s;const[i,d]=l.useState(null),{frequency:c,measure:u,strategy:h}=o,y=l.useRef(e),m=I(),b=Qt(m),N=l.useCallback(function(E){E===void 0&&(E=[]),!b.current&&d($=>$===null?E:$.concat(E.filter(B=>!$.includes(B))))},[b]),G=l.useRef(null),T=ss(E=>{if(m&&!n)return Rn;if(!E||E===Rn||y.current!==e||i!=null){const $=new Map;for(let B of e){if(!B)continue;if(i&&i.length>0&&!i.includes(B.id)&&B.rect.current){$.set(B.id,B.rect.current);continue}const Y=B.node.current,q=Y?new tn(u(Y),Y):null;B.rect.current=q,q&&$.set(B.id,q)}return $}return E},[e,i,n,m,u]);return l.useEffect(()=>{y.current=e},[e]),l.useEffect(()=>{m||N()},[n,m]),l.useEffect(()=>{i&&i.length>0&&d(null)},[JSON.stringify(i)]),l.useEffect(()=>{m||typeof c!="number"||G.current!==null||(G.current=setTimeout(()=>{N(),G.current=null},c))},[c,m,N,...r]),{droppableRects:T,measureDroppableContainers:N,measuringScheduled:i!=null};function I(){switch(h){case es.Always:return!1;case es.BeforeDragging:return n;default:return!n}}}function rn(e,s){return ss(n=>e?n||(typeof s=="function"?s(e):e):null,[s,e])}function Ba(e,s){return rn(e,s)}function Va(e){let{callback:s,disabled:n}=e;const r=ws(s),o=l.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:i}=window;return new i(r)},[r,n]);return l.useEffect(()=>()=>o==null?void 0:o.disconnect(),[o]),o}function Cs(e){let{callback:s,disabled:n}=e;const r=ws(s),o=l.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:i}=window;return new i(r)},[n]);return l.useEffect(()=>()=>o==null?void 0:o.disconnect(),[o]),o}function Ua(e){return new tn(ns(e),e)}function En(e,s,n){s===void 0&&(s=Ua);const[r,o]=l.useState(null);function i(){o(u=>{if(!e)return null;if(e.isConnected===!1){var h;return(h=u??n)!=null?h:null}const y=s(e);return JSON.stringify(u)===JSON.stringify(y)?u:y})}const d=Va({callback(u){if(e)for(const h of u){const{type:y,target:m}=h;if(y==="childList"&&m instanceof HTMLElement&&m.contains(e)){i();break}}}}),c=Cs({callback:i});return pt(()=>{i(),e?(c==null||c.observe(e),d==null||d.observe(document.body,{childList:!0,subtree:!0})):(c==null||c.disconnect(),d==null||d.disconnect())},[e]),r}function Wa(e){const s=rn(e);return tr(e,s)}const Dn=[];function Ha(e){const s=l.useRef(e),n=ss(r=>e?r&&r!==Dn&&e&&s.current&&e.parentNode===s.current.parentNode?r:en(e):Dn,[e]);return l.useEffect(()=>{s.current=e},[e]),n}function Ga(e){const[s,n]=l.useState(null),r=l.useRef(e),o=l.useCallback(i=>{const d=Os(i.target);d&&n(c=>c?(c.set(d,Hs(d)),new Map(c)):null)},[]);return l.useEffect(()=>{const i=r.current;if(e!==i){d(i);const c=e.map(u=>{const h=Os(u);return h?(h.addEventListener("scroll",o,{passive:!0}),[h,Hs(h)]):null}).filter(u=>u!=null);n(c.length?new Map(c):null),r.current=e}return()=>{d(e),d(i)};function d(c){c.forEach(u=>{const h=Os(u);h==null||h.removeEventListener("scroll",o)})}},[o,e]),l.useMemo(()=>e.length?s?Array.from(s.values()).reduce((i,d)=>Rt(i,d),rt):lr(e):rt,[e,s])}function Tn(e,s){s===void 0&&(s=[]);const n=l.useRef(null);return l.useEffect(()=>{n.current=null},s),l.useEffect(()=>{const r=e!==rt;r&&!n.current&&(n.current=e),!r&&n.current&&(n.current=null)},[e]),n.current?gs(e,n.current):rt}function Xa(e){l.useEffect(()=>{if(!_s)return;const s=e.map(n=>{let{sensor:r}=n;return r.setup==null?void 0:r.setup()});return()=>{for(const n of s)n==null||n()}},e.map(s=>{let{sensor:n}=s;return n}))}function Ka(e,s){return l.useMemo(()=>e.reduce((n,r)=>{let{eventName:o,handler:i}=r;return n[o]=d=>{i(d,s)},n},{}),[e,s])}function fr(e){return l.useMemo(()=>e?ya(e):null,[e])}const $n=[];function Ya(e,s){s===void 0&&(s=ns);const[n]=e,r=fr(n?ze(n):null),[o,i]=l.useState($n);function d(){i(()=>e.length?e.map(u=>ir(u)?r:new tn(s(u),u)):$n)}const c=Cs({callback:d});return pt(()=>{c==null||c.disconnect(),d(),e.forEach(u=>c==null?void 0:c.observe(u))},[e]),o}function mr(e){if(!e)return null;if(e.children.length>1)return e;const s=e.children[0];return ts(s)?s:e}function Ja(e){let{measure:s}=e;const[n,r]=l.useState(null),o=l.useCallback(h=>{for(const{target:y}of h)if(ts(y)){r(m=>{const b=s(y);
35return m?{...m,width:b.width,height:b.height}:b});break}},[s]),i=Cs({callback:o}),d=l.useCallback(h=>{const y=mr(h);i==null||i.disconnect(),y&&(i==null||i.observe(y)),r(y?s(y):null)},[s,i]),[c,u]=ps(d);return l.useMemo(()=>({nodeRef:c,rect:n,setRef:u}),[n,c,u])}const Qa=[{sensor:Ss,options:{}},{sensor:ur,options:{}}],Za={current:{}},ds={draggable:{measure:Nn},droppable:{measure:Nn,strategy:es.WhileDragging,frequency:Xs.Optimized},dragOverlay:{measure:ns}};class Jt extends Map{get(s){var n;return s!=null&&(n=super.get(s))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(s=>{let{disabled:n}=s;return!n})}getNodeFor(s){var n,r;return(n=(r=this.get(s))==null?void 0:r.node.current)!=null?n:void 0}}const ei={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Jt,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:vs},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:ds,measureDroppableContainers:vs,windowRect:null,measuringScheduled:!1},pr={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:vs,draggableNodes:new Map,over:null,measureDroppableContainers:vs},rs=l.createContext(pr),hr=l.createContext(ei);function ti(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Jt}}}function si(e,s){switch(s.type){case ke.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:s.initialCoordinates,active:s.active}};case ke.DragMove:return e.draggable.active==null?e:{...e,draggable:{...e.draggable,translate:{x:s.coordinates.x-e.draggable.initialCoordinates.x,y:s.coordinates.y-e.draggable.initialCoordinates.y}}};case ke.DragEnd:case ke.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case ke.RegisterDroppable:{const{element:n}=s,{id:r}=n,o=new Jt(e.droppable.containers);return o.set(r,n),{...e,droppable:{...e.droppable,containers:o}}}case ke.SetDroppableDisabled:{const{id:n,key:r,disabled:o}=s,i=e.droppable.containers.get(n);if(!i||r!==i.key)return e;const d=new Jt(e.droppable.containers);return d.set(n,{...i,disabled:o}),{...e,droppable:{...e.droppable,containers:d}}}case ke.UnregisterDroppable:{const{id:n,key:r}=s,o=e.droppable.containers.get(n);if(!o||r!==o.key)return e;const i=new Jt(e.droppable.containers);return i.delete(n),{...e,droppable:{...e.droppable,containers:i}}}default:return e}}function ni(e){let{disabled:s}=e;const{active:n,activatorEvent:r,draggableNodes:o}=l.useContext(rs),i=hs(r),d=hs(n==null?void 0:n.id);return l.useEffect(()=>{if(!s&&!r&&i&&d!=null){if(!Qs(i)||document.activeElement===i.target)return;const c=o.get(d);if(!c)return;const{activatorNode:u,node:h}=c;if(!u.current&&!h.current)return;requestAnimationFrame(()=>{for(const y of[u.current,h.current]){if(!y)continue;const m=ea(y);if(m){m.focus();break}}})}},[r,s,o,d,i]),null}function gr(e,s){let{transform:n,...r}=s;return e!=null&&e.length?e.reduce((o,i)=>i({transform:o,...r}),n):n}function ri(e){return l.useMemo(()=>({draggable:{...ds.draggable,...e==null?void 0:e.draggable},droppable:{...ds.droppable,...e==null?void 0:e.droppable},dragOverlay:{...ds.dragOverlay,...e==null?void 0:e.dragOverlay}}),[e==null?void 0:e.draggable,e==null?void 0:e.droppable,e==null?void 0:e.dragOverlay])}function ai(e){let{activeNode:s,measure:n,initialRect:r,config:o=!0}=e;const i=l.useRef(!1),{x:d,y:c}=typeof o=="boolean"?{x:o,y:o}:o;pt(()=>{if(!d&&!c||!s){i.current=!1;return}if(i.current||!r)return;const h=s==null?void 0:s.node.current;if(!h||h.isConnected===!1)return;const y=n(h),m=tr(y,r);if(d||(m.x=0),c||(m.y=0),i.current=!0,Math.abs(m.x)>0||Math.abs(m.y)>0){const b=nr(h);b&&b.scrollBy({top:m.y,left:m.x})}},[s,d,c,r,n])}const ks=l.createContext({...rt,scaleX:1,scaleY:1});var vt;(function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initializing=1]="Initializing",e[e.Initialized=2]="Initialized"})(vt||(vt={}));const xr=l.memo(function(s){var n,r,o,i;let{id:d,accessibility:c,autoScroll:u=!0,children:h,sensors:y=Qa,collisionDetection:m=Zs,measuring:b,modifiers:N,...G}=s;const T=l.useReducer(si,void 0,ti),[I,E]=T,[$,B]=ia(),[Y,q]=l.useState(vt.Uninitialized),g=Y===vt.Initialized,{draggable:{active:v,nodes:C,translate:F},droppable:{containers:z}}=I,L=v!=null?C.get(v):null,f=l.useRef({initial:null,translated:null}),A=l.useMemo(()=>{var Re;return v!=null?{id:v,data:(Re=L==null?void 0:L.data)!=null?Re:Za,rect:f}:null},[v,L]),p=l.useRef(null),[_,W]=l.useState(null),[X,V]=l.useState(null),J=Qt(G,Object.values(G)),de=Ns("DndDescribedBy",d),se=l.useMemo(()=>z.getEnabled(),[z]),oe=ri(b),{droppableRects:me,measureDroppableContainers:le,measuringScheduled:D}=Fa(se,{dragging:g,dependencies:[F.x,F.y],config:oe.droppable}),P=za(C,v),H=l.useMemo(()=>X?xs(X):null,[X]),ee=Es(),xe=Ba(P,oe.draggable.measure);ai({activeNode:v!=null?C.get(v):null,config:ee.layoutShiftCompensation,initialRect:xe,measure:oe.draggable.measure});const ie=En(P,oe.draggable.measure,xe),ae=En(P?P.parentElement:null),be=l.useRef({activatorEvent:null,active:null,activeNode:P,collisionRect:null,collisions:null,droppableRects:me,draggableNodes:C,draggingNode:null,draggingNodeRect:null,droppableContainers:z,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),ve=z.getNodeFor((n=be.current.over)==null?void 0:n.id),ye=Ja({measure:oe.dragOverlay.measure}),ue=(r=ye.nodeRef.current)!=null?r:P,$e=g?(o=ye.rect)!=null?o:ie:null,Ae=!!(ye.nodeRef.current&&ye.rect),x=Wa(Ae?null:ie),w=fr(ue?ze(ue):null),R=
35Ha(g?ve??P:null),M=Ya(R),te=gr(N,{transform:{x:F.x-x.x,y:F.y-x.y,scaleX:1,scaleY:1},activatorEvent:X,active:A,activeNodeRect:ie,containerNodeRect:ae,draggingNodeRect:$e,over:be.current.over,overlayNodeRect:ye.rect,scrollableAncestors:R,scrollableAncestorRects:M,windowRect:w}),re=H?Rt(H,F):null,je=Ga(R),_e=Tn(je),Mt=Tn(je,[ie]),Je=Rt(te,_e),at=$e?va($e,te):null,ht=A&&at?m({active:A,collisionRect:at,droppableRects:me,droppableContainers:se,pointerCoordinates:re}):null,At=ma(ht,"id"),[it,gt]=l.useState(null),Pt=Ae?te:Rt(te,Mt),qe=ga(Pt,(i=it==null?void 0:it.rect)!=null?i:null,ie),ft=l.useRef(null),Lt=l.useCallback((Re,Pe)=>{let{sensor:Me,options:Ve}=Pe;if(p.current==null)return;const Ee=C.get(p.current);if(!Ee)return;const Le=Re.nativeEvent,Ke=new Me({active:p.current,activeNode:Ee,event:Le,options:Ve,context:be,onAbort(Ce){if(!C.get(Ce))return;const{onDragAbort:Oe}=J.current,Ue={id:Ce};Oe==null||Oe(Ue),$({type:"onDragAbort",event:Ue})},onPending(Ce,ot,Oe,Ue){if(!C.get(Ce))return;const{onDragPending:yt}=J.current,lt={id:Ce,constraint:ot,initialCoordinates:Oe,offset:Ue};yt==null||yt(lt),$({type:"onDragPending",event:lt})},onStart(Ce){const ot=p.current;if(ot==null)return;const Oe=C.get(ot);if(!Oe)return;const{onDragStart:Ue}=J.current,jt={activatorEvent:Le,active:{id:ot,data:Oe.data,rect:f}};Vt.unstable_batchedUpdates(()=>{Ue==null||Ue(jt),q(vt.Initializing),E({type:ke.DragStart,initialCoordinates:Ce,active:ot}),$({type:"onDragStart",event:jt}),W(ft.current),V(Le)})},onMove(Ce){E({type:ke.DragMove,coordinates:Ce})},onEnd:xt(ke.DragEnd),onCancel:xt(ke.DragCancel)});ft.current=Ke;function xt(Ce){return async function(){const{active:Oe,collisions:Ue,over:jt,scrollAdjustedTranslate:yt}=be.current;let lt=null;if(Oe&&yt){const{cancelDrop:_t}=J.current;lt={activatorEvent:Le,active:Oe,collisions:Ue,delta:yt,over:jt},Ce===ke.DragEnd&&typeof _t=="function"&&await Promise.resolve(_t(lt))&&(Ce=ke.DragCancel)}p.current=null,Vt.unstable_batchedUpdates(()=>{E({type:Ce}),q(vt.Uninitialized),gt(null),W(null),V(null),ft.current=null;const _t=Ce===ke.DragEnd?"onDragEnd":"onDragCancel";if(lt){const We=J.current[_t];We==null||We(lt),$({type:_t,event:lt})}})}}},[C]),Ot=l.useCallback((Re,Pe)=>(Me,Ve)=>{const Ee=Me.nativeEvent,Le=C.get(Ve);if(p.current!==null||!Le||Ee.dndKit||Ee.defaultPrevented)return;const Ke={active:Le};Re(Me,Pe.options,Ke)===!0&&(Ee.dndKit={capturedBy:Pe.sensor},p.current=Ve,Lt(Me,Pe))}
35,[C,Lt]),bt=qa(y,Ot);Xa(y),pt(()=>{ie&&Y===vt.Initializing&&q(vt.Initialized)},[ie,Y]),l.useEffect(()=>{const{onDragMove:Re}=J.current,{active:Pe,activatorEvent:Me,collisions:Ve,over:Ee}=be.current;if(!Pe||!Me)return;const Le={active:Pe,activatorEvent:Me,collisions:Ve,delta:{x:Je.x,y:Je.y},over:Ee};Vt.unstable_batchedUpdates(()=>{Re==null||Re(Le),$({type:"onDragMove",event:Le})})},[Je.x,Je.y]),l.useEffect(()=>{const{active:Re,activatorEvent:Pe,collisions:Me,droppableContainers:Ve,scrollAdjustedTranslate:Ee}=be.current;if(!Re||p.current==null||!Pe||!Ee)return;const{onDragOver:Le}=J.current,Ke=Ve.get(At),xt=Ke&&Ke.rect.current?{id:Ke.id,rect:Ke.rect.current,data:Ke.data,disabled:Ke.disabled}:null,Ce={active:Re,activatorEvent:Pe,collisions:Me,delta:{x:Ee.x,y:Ee.y},over:xt};Vt.unstable_batchedUpdates(()=>{gt(xt),Le==null||Le(Ce),$({type:"onDragOver",event:Ce})})},[At]),pt(()=>{be.current={activatorEvent:X,active:A,activeNode:P,collisionRect:at,collisions:ht,droppableRects:me,draggableNodes:C,draggingNode:ue,draggingNodeRect:$e,droppableContainers:z,over:it,scrollableAncestors:R,scrollAdjustedTranslate:Je},f.current={initial:$e,translated:at}},[A,P,ht,at,C,ue,$e,me,z,it,R,Je]),La({...ee,delta:F,draggingRect:at,pointerCoordinates:re,scrollableAncestors:R,scrollableAncestorRects:M});const It=l.useMemo(()=>({active:A,activeNode:P,activeNodeRect:ie,activatorEvent:X,collisions:ht,containerNodeRect:ae,dragOverlay:ye,draggableNodes:C,droppableContainers:z,droppableRects:me,over:it,measureDroppableContainers:le,scrollableAncestors:R,scrollableAncestorRects:M,measuringConfiguration:oe,measuringScheduled:D,windowRect:w}),[A,P,ie,X,ht,ae,ye,C,z,me,it,le,R,M,oe,D,w]),Qe=l.useMemo(()=>({activatorEvent:X,activators:bt,active:A,activeNodeRect:ie,ariaDescribedById:{draggable:de},dispatch:E,draggableNodes:C,over:it,measureDroppableContainers:le}),[X,bt,A,ie,E,de,C,it,le]);return we.createElement(Kn.Provider,{value:B},we.createElement(rs.Provider,{value:Qe},we.createElement(hr.Provider,{value:It},we.createElement(ks.Provider,{value:qe},h)),we.createElement(ni,{disabled:(c==null?void 0:c.restoreFocus)===!1})),we.createElement(ca,{...c,hiddenTextDescribedById:de}));function Es(){const Re=(_==null?void 0:_.autoScrollEnabled)===!1,Pe=typeof u=="object"?u.enabled===!1:u===!1,Me=g&&!Re&&!Pe;return typeof u=="object"?{...u,enabled:Me}:{enabled:Me}}}),ii=l.createContext(null),Mn="button",oi="Draggable";function Rs(e){let{id:s,data:n,disabled:r=!1,attributes:o}=e;const i=Ns(oi),{activators:d,activatorEvent:c,active:u,activeNodeRect:h,ariaDescribedById:y,draggableNodes:m,over:b}=l.useContext(rs),{role:N=Mn,roleDescription:G="draggable",tabIndex:T=0}=o??{},I=(u==null?void 0:u.id)===s,E=l.useContext(I?ks:ii),[$,B]=ps(),[Y,q]=ps(),g=Ka(d,s),v=Qt(n);pt(()=>(m.set(s,{id:s,key:i,node:$,activatorNode:Y,data:v}),()=>{const F=m.get(s);F&&F.key===i&&m.delete(s)}),[m,s]);const C=l.useMemo(()=>({role:N,tabIndex:T,"aria-disabled":r,"aria-pressed":I&&N===Mn?!0:void 0,"aria-roledescription":G,"aria-describedby":y.draggable}),[r,N,T,I,G,y.draggable]);return{active:u,activatorEvent:c,activeNodeRect:h,attributes:C,isDragging:I,listeners:r?void 0:g,node:$,over:b,setNodeRef:B,setActivatorNodeRef:q,transform:E}}function li(){return l.useContext(hr)}const ci="Droppable",di={timeout:25};function vr(e){let{data:s,disabled:n=!1,id:r,resizeObserverConfig:o}=e;const i=Ns(ci),{active:d,dispatch:c,over:u,measureDroppableContainers:h}=l.useContext(rs),y=l.useRef({disabled:n}),m=l.useRef(!1),b=l.useRef(null),N=l.useRef(null),{disabled:G,updateMeasurementsFor:T,timeout:I}={...di,...o},E=Qt(T??r),$=l.useCallback(()=>{if(!m.current){m.current=!0;return}N.current!=null&&clearTimeout(N.current),N.current=setTimeout(()=>{h(Array.isArray(E.current)?E.current:[E.current]),N.current=null},I)},[I]),B=Cs({callback:$,disabled:G||!d}),Y=l.useCallback((C,F)=>{B&&(F&&(B.unobserve(F),m.current=!1),C&&B.observe(C))},[B]),[q,g]=ps(Y),v=Qt(s);return l.useEffect(()=>{!B||!q.current||(B.disconnect(),m.current=!1,B.observe(q.current))},[q,B]),l.useEffect(()=>(c({type:ke.RegisterDroppable,element:{id:r,key:i,disabled:n,node:q,rect:b,data:v}}),()=>c({type:ke.UnregisterDroppable,key:i,id:r})),[r]),l.useEffect(()=>{n!==y.current.disabled&&(c({type:ke.SetDroppableDisabled,id:r,key:i,disabled:n}),y.current.disabled=n)},[r,i,n,c]),{active:d,rect:b,isOver:(u==null?void 0:u.id)===r,node:q,over:u,setNodeRef:g}}function ui(e){let{animation:s,children:n}=e;const[r,o]=l.useState(null),[i,d]=l.useState(null),c=hs(n);return!n&&!r&&c&&o(c),pt(()=>{if(!i)return;const u=r==null?void 0:r.key,h=r==null?void 0:r.props.id;if(u==null||h==null){o(null);return}Promise.resolve(s(h,i)).then(()=>{o(null)})},[s,r,i]),we.createElement(we.Fragment,null,n,r?l.cloneElement(r,{ref:d}):null)}const fi={x:0,y:0,scaleX:1,scaleY:1};function mi(e){let{children:s}=e;return we.createElement(rs.Provider,{value:pr},we.createElement(ks.Provider,{value:fi},s))}const pi={position:"fixed",touchAction:"none"}
35,hi=e=>Qs(e)?"transform 250ms ease":void 0,gi=l.forwardRef((e,s)=>{let{as:n,activatorEvent:r,adjustScale:o,children:i,className:d,rect:c,style:u,transform:h,transition:y=hi}=e;if(!c)return null;const m=o?h:{...h,scaleX:1,scaleY:1},b={...pi,width:c.width,height:c.height,top:c.top,left:c.left,transform:Zt.Transform.toString(m),transformOrigin:o&&r?da(r,c):void 0,transition:typeof y=="function"?y(r):y,...u};return we.createElement(n,{className:d,style:b,ref:s},i)}),xi=e=>s=>{let{active:n,dragOverlay:r}=s;const o={},{styles:i,className:d}=e;if(i!=null&&i.active)for(const[c,u]of Object.entries(i.active))u!==void 0&&(o[c]=n.node.style.getPropertyValue(c),n.node.style.setProperty(c,u));if(i!=null&&i.dragOverlay)for(const[c,u]of Object.entries(i.dragOverlay))u!==void 0&&r.node.style.setProperty(c,u);return d!=null&&d.active&&n.node.classList.add(d.active),d!=null&&d.dragOverlay&&r.node.classList.add(d.dragOverlay),function(){for(const[u,h]of Object.entries(o))n.node.style.setProperty(u,h);d!=null&&d.active&&n.node.classList.remove(d.active)}},vi=e=>{let{transform:{initial:s,final:n}}=e;return[{transform:Zt.Transform.toString(s)},{transform:Zt.Transform.toString(n)}]},bi={duration:250,easing:"ease",keyframes:vi,sideEffects:xi({styles:{active:{opacity:"0"}}})};function ji(e){let{config:s,draggableNodes:n,droppableContainers:r,measuringConfiguration:o}=e;return ws((i,d)=>{if(s===null)return;const c=n.get(i);if(!c)return;const u=c.node.current;if(!u)return;const h=mr(d);if(!h)return;const{transform:y}=ze(d).getComputedStyle(d),m=sr(y);if(!m)return;const b=typeof s=="function"?s:yi(s);return cr(u,o.draggable.measure),b({active:{id:i,data:c.data,node:u,rect:o.draggable.measure(u)},draggableNodes:n,dragOverlay:{node:d,rect:o.dragOverlay.measure(h)},droppableContainers:r,measuringConfiguration:o,transform:m})})}function yi(e){const{duration:s,easing:n,sideEffects:r,keyframes:o}={...bi,...e};return i=>{let{active:d,dragOverlay:c,transform:u,...h}=i;if(!s)return;const y={x:c.rect.left-d.rect.left,y:c.rect.top-d.rect.top},m={scaleX:u.scaleX!==1?d.rect.width*u.scaleX/c.rect.width:1,scaleY:u.scaleY!==1?d.rect.height*u.scaleY/c.rect.height:1},b={x:u.x-y.x,y:u.y-y.y,...m},N=o({...h,active:d,dragOverlay:c,transform:{initial:u,final:b}}),[G]=N,T=N[N.length-1];if(JSON.stringify(G)===JSON.stringify(T))return;const I=r==null?void 0:r({active:d,dragOverlay:c,...h}),E=c.node.animate(N,{duration:s,easing:n,fill:"forwards"});return new Promise($=>{E.onfinish=()=>{I==null||I(),$()}})}}let An=0;function _i(e){return l.useMemo(()=>{if(e!=null)return An++,An},[e])}const br=we.memo(e=>
35{let{adjustScale:s=!1,children:n,dropAnimation:r,style:o,transition:i,modifiers:d,wrapperElement:c="div",className:u,zIndex:h=999}=e;const{activatorEvent:y,active:m,activeNodeRect:b,containerNodeRect:N,draggableNodes:G,droppableContainers:T,dragOverlay:I,over:E,measuringConfiguration:$,scrollableAncestors:B,scrollableAncestorRects:Y,windowRect:q}=li(),g=l.useContext(ks),v=_i(m==null?void 0:m.id),C=gr(d,{activatorEvent:y,active:m,activeNodeRect:b,containerNodeRect:N,draggingNodeRect:I.rect,over:E,overlayNodeRect:I.rect,scrollableAncestors:B,scrollableAncestorRects:Y,transform:g,windowRect:q}),F=rn(b),z=ji({config:r,draggableNodes:G,droppableContainers:T,measuringConfiguration:$}),L=F?I.setRef:void 0;return we.createElement(mi,null,we.createElement(ui,{animation:z},m&&v?we.createElement(gi,{key:v,id:m.id,ref:L,as:c,activatorEvent:y,adjustScale:s,className:u,transition:i,rect:F,style:{zIndex:h,...o},transform:C},n):null))}),Ct=e=>e?`${(e.player_last_name??"").toUpperCase()} / ${(e.partner_last_name??"").toUpperCase()}`:"â",qs=["bg-court/15 text-court","bg-amber-500/15 text-amber-700","bg-sky-500/15 text-sky-700","bg-violet-500/15 text-violet-700","bg-rose-500/15 text-rose-700","bg-emerald-500/15 text-emerald-700"];function Pn({regId:e,label:s,poolName:n,poolBadge:r}){const{attributes:o,listeners:i,setNodeRef:d,isDragging:c}=Rs({id:`palette:${e}`});return t.jsxs("div",{ref:d,...i,...o,className:`flex items-center gap-2 rounded-lg border bg-card px-2.5 py-2 text-sm shadow-sm select-none touch-none cursor-grab active:cursor-grabbing ${c?"opacity-40":""}`,children:[t.jsx(Dt,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),t.jsx("span",{className:`shrink-0 rounded px-1.5 py-0.5 text-[10px] font-bold ${r}`,children:n}),t.jsx("span",{className:"truncate flex-1",children:s})]})}
35function Ln({matchId:e,slot:s,reg:n,sourceLabel:r,poolName:o,poolBadge:i,onClear:d,games:c,tiebreak:u,isWinner:h,isDragActive:y}){const{isOver:m,setNodeRef:b}=vr({id:`slot:${e}:${s}`}),N=n?t.jsx(wi,{matchId:e,slot:s,regId:n.id,label:Ct(n),poolName:o??"TS",poolBadge:i??"bg-primary/15 text-primary",onClear:d}):t.jsxs("span",{className:"italic text-muted-foreground text-xs",children:["Déposez une paire (",r??"â",")"]}),G=c!=null;return t.jsxs("div",{ref:b,className:`relative min-h-[58px] rounded-lg border-2 px-3 py-2.5 flex items-center gap-2 transition-all duration-150 ${m?"border-solid border-court bg-court/15 ring-2 ring-court ring-offset-1 shadow-md scale-[1.02]":n?"border-transparent bg-muted/40":`border-dashed ${y?"border-court/50 bg-court/5":"border-muted-foreground/25"}`}`,children:[t.jsx("div",{className:"flex-1 min-w-0",children:N}),G&&t.jsxs("span",{className:`shrink-0 tabular-nums text-sm ${h?"font-bold text-court":"text-muted-foreground"}`,children:[c,u!=null&&t.jsx("sup",{className:"text-[0.65em] ml-0.5",children:u})]}),m&&t.jsx("span",{className:"absolute inset-0 z-10 flex items-center justify-center rounded-lg bg-court/90 text-xs font-bold uppercase tracking-wide text-white pointer-events-none",children:n?"â Remplacer ici":"ï¼ Déposer ici"})]})}function wi({matchId:e,slot:s,regId:n,label:r,poolName:o,poolBadge:i,onClear:d}){const{attributes:c,listeners:u,setNodeRef:h,isDragging:y}=Rs({id:`placed:${n}:${e}:${s}`});return t.jsxs("div",{className:`flex items-center gap-2 w-full text-sm ${y?"opacity-40":""}`,children:[t.jsxs("span",{ref:h,...u,...c,className:"flex items-center gap-2 flex-1 min-w-0 select-none touch-none cursor-grab active:cursor-grabbing",children:[t.jsx(Dt,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),t.jsx("span",{className:`shrink-0 rounded px-1.5 py-0.5 text-[10px] font-bold ${i}`,children:o}),t.jsx("span",{className:"truncate flex-1",children:r})]}),t.jsx("button",{onClick:d,className:"shrink-0 rounded p-1 hover:bg-destructive/10 text-muted-foreground hover:text-destructive","aria-label":"Retirer",children:t.jsx(Un,{className:"h-3.5 w-3.5"})})]})}function Ni({matches:e,pools:s,assigns:n,regs:r,qualifiedIds:o,eliminatedIds:i,onReload:d,onOpenScore:c}){const[u,h]=l.useState(null),[y,m]=l.useState(!1),b=Yn(bs(Ss,{activationConstraint:{distance:5}}),bs(nn,{activationConstraint:{delay:150,tolerance:8}})),N=f=>{const A=er(f);if(A.length>0)return A;const p=Zs(f);return p.length>0?p:Zn(f)},G=l.useMemo(()=>{const f={};return n.forEach(A=>{A.pool_id&&(f[A.registration_id]=A.pool_id)}),f},[n]),T=l.useMemo(()=>{const f={};return s.forEach((A,p)=>{f[A.id]={name:A.name,badge:qs[p%qs.length]}}),f},[s]),I=f=>!!(o!=null&&o.has(f))&&!(i!=null&&i.has(f)),E=l.useMemo(()=>s.map(f=>({pool:f,regs:n.filter(A=>A.pool_id===f.id&&!I(A.registration_id)&&r[A.registration_id]).map(A=>A.registration_id)})).filter(f=>f.regs.length>0),[s,n,r,o,i]),$=l.useMemo(()=>{const f=new Set(n.filter(A=>A.pool_id).map(A=>A.registration_id));return Array.from(i??[]).filter(A=>!f.has(A)&&r[A]).sort((A,p)=>Ct(r[A]).localeCompare(Ct(r[p])))},[n,r,i]),B=f=>{f.games_a=null,f.games_b=null,f.tiebreak_a=null,f.tiebreak_b=null,f.winner_id=null,f.status="pending"},Y=async f=>{m(!0);try{for(const[A,p]of Object.entries(f)){const{error:_}=await Q.from("matches").update(p).eq("id",A);if(_)return O.error(_.message),!1}return!0}finally{m(!1)}},q=async(f,A,p)=>{const _=e.find(se=>se.id===A);if(!_)return;if(I(f)){O.error("Cette paire est encore qualifiée pour la phase finale : elle ne peut pas jouer un match de classement.");return}if(((p==="a"?"b":"a")==="a"?_.pair_a_id:_.pair_b_id)===f){O.error("Une paire ne peut pas s'affronter elle-même.");return}if((p==="a"?_.pair_a_id:_.pair_b_id)===f)return;const J={};J[p==="a"?"pair_a_id":"pair_b_id"]=f,B(J),await Y({[A]:J})&&d()},g=async(f,A)=>{const p={};p[A==="a"?"pair_a_id":"pair_b_id"]=null,B(p),await Y({[f]:p})&&d()},v=f=>f.startsWith("palette:")?f.slice(8):f.startsWith("placed:")?f.split(":")[1]:null,C=f=>{const A=v(String(f.active.id));A&&h(A)},F=f=>{h(null);const{active:A,over:p}=f;if(!p)return;const _=String(p.id);if(!_.startsWith("slot:"))return;const W=v(String(A.id));if(!W)return;const[,X,V]=_.split(":");q(W,X,V)},z=u?r[u]:void 0,L=u?G[u]:void 0;return t.jsxs(xr,{sensors:b,collisionDetection:N,onDragStart:C,onDragEnd:F,children:[t.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 mb-3 flex items-start gap-2 text-xs text-muted-foreground",children:[t.jsx(Hn,{className:"h-4 w-4 shrink-0 mt-0.5"}),t.jsx("span",{children:"Glissez-déposez les paires qui ont terminé leur poule vers un match de classement â pas besoin d'attendre que les 4 poules soient finies. Les têtes de série éliminées en phase finale (ex. défaite directe en 1/4) sont aussi disponibles."})]}),t.jsxs("div",{className:"grid gap-4 lg:grid-cols-[280px_1fr]",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-semibold mb-2",children:"Paires disponibles"}),E.length===0&&$.length===0?t.jsx("p",{className:"text-xs text-muted-foreground",children:"Toutes les paires disponibles s
35ont placées."}):t.jsxs("div",{className:"space-y-3",children:[E.map(({pool:f,regs:A})=>{const p=T[f.id];return t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground mb-1",children:Vn(f.name)}),t.jsx("div",{className:"space-y-1.5",children:A.map(_=>t.jsx(Pn,{regId:_,label:Ct(r[_]),poolName:(p==null?void 0:p.name)??"?",poolBadge:(p==null?void 0:p.badge)??qs[0]},_))})]},f.id)}),$.length>0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground mb-1",children:"Têtes de série éliminées"}),t.jsx("div",{className:"space-y-1.5",children:$.map(f=>t.jsx(Pn,{regId:f,label:Ct(r[f]),poolName:"TS",poolBadge:"bg-primary/15 text-primary"},f))})]})]})]}),t.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:e.slice().sort((f,A)=>f.position-A.position).map(f=>{const A=f.pair_a_id?r[f.pair_a_id]:void 0,p=f.pair_b_id?r[f.pair_b_id]:void 0,_=f.pair_a_id?T[G[f.pair_a_id]]:void 0,W=f.pair_b_id?T[G[f.pair_b_id]]:void 0,X=f.status==="completed",V=f.pair_a_id&&f.pair_b_id;return t.jsxs(ce,{className:"p-3 text-sm",children:[t.jsxs("div",{className:"text-xs text-muted-foreground mb-2 flex items-center justify-between",children:[t.jsx("span",{children:Bs(f.label)}),X&&t.jsx("span",{className:"text-success font-semibold",children:"Terminé"})]}),t.jsxs("div",{className:"space-y-1.5",children:[t.jsx(Ln,{matchId:f.id,slot:"a",reg:A,sourceLabel:f.pair_a_source,poolName:_==null?void 0:_.name,poolBadge:_==null?void 0:_.badge,onClear:()=>g(f.id,"a"),games:f.games_a,tiebreak:f.tiebreak_a,isWinner:!!f.winner_id&&f.winner_id===f.pair_a_id,isDragActive:!!u}),t.jsx(Ln,{matchId:f.id,slot:"b",reg:p,sourceLabel:f.pair_b_source,poolName:W==null?void 0:W.name,poolBadge:W==null?void 0:W.badge,onClear:()=>g(f.id,"b"),games:f.games_b,tiebreak:f.tiebreak_b,isWinner:!!f.winner_id&&f.winner_id===f.pair_b_id,isDragActive:!!u})]}),V&&t.jsx(K,{size:"sm",variant:X?"outline":"default",className:"mt-2 w-full h-7 text-xs",disabled:y,onClick:()=>c(f),children:X?"Modifier le score":"Saisir le score"})]},f.id)})})]}),t.jsx(br,{children:z?t.jsxs("div",{className:"flex items-center gap-2 rounded-lg border bg-card px-2.5 py-2 text-sm shadow-lg",children:[t.jsx(Dt,{className:"h-4 w-4 text-muted-foreground"}),L&&T[L]&&t.jsx("span",{className:`rounded px-1.5 py-0.5 text-[10px] font-bold ${T[L].badge}`,children:T[L].name}),t.jsx("span",{children:Ct(z)})]}):null})]})}const Ks=e=>e?`${(e.player_last_name??"").toUpperCase()} / ${(e.partner_last_name??"").toUpperCase()}`:"â",On=e=>{if(e.startsWith("bpalette:"))return{type:"palette",regId:e.slice(9)};if(e.startsWith("bslotpair:")){const[,s,n,r]=e.split(":");if((n==="a"||n==="b")&&s&&r)return{type:"slot",matchId:s,slot:n,regId:r}}return null};
35function Si({matchId:e,slot:s,regId:n,label:r,onClear:o}){const{attributes:i,listeners:d,setNodeRef:c,isDragging:u}=Rs({id:`bslotpair:${e}:${s}:${n}`});return t.jsxs("div",{className:`flex items-center gap-2 w-full text-sm ${u?"opacity-40":""}`,children:[t.jsxs("span",{ref:c,...d,...i,className:"flex items-center gap-2 flex-1 min-w-0 select-none touch-none cursor-grab active:cursor-grabbing",children:[t.jsx(Dt,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),t.jsx("span",{className:"truncate flex-1",children:r})]}),t.jsx("button",{onClick:o,className:"shrink-0 rounded p-1 hover:bg-destructive/10 text-muted-foreground hover:text-destructive","aria-label":"Retirer",children:t.jsx(Un,{className:"h-3.5 w-3.5"})})]})}function Ci({regId:e,label:s,dragging:n}){const{attributes:r,listeners:o,setNodeRef:i,isDragging:d}=Rs({id:`bpalette:${e}`});return t.jsxs("div",{ref:i,...o,...r,className:`flex items-center gap-2 rounded-lg border bg-card px-2.5 py-2 text-sm shadow-sm select-none touch-none cursor-grab active:cursor-grabbing ${d||n?"opacity-40":""}`,children:[t.jsx(Dt,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),t.jsx("span",{className:"truncate flex-1",children:s})]})}function In({matchId:e,slot:s,reg:n,sourceLabel:r,onClear:o,games:i,tiebreak:d,setScores:c,isWinner:u,isDragActive:h}){const{isOver:y,setNodeRef:m}=vr({id:`bslot:${e}:${s}`}),b=n?t.jsx(Si,{matchId:e,slot:s,regId:n.id,label:Ks(n),onClear:o}):t.jsx("span",{className:"italic text-muted-foreground text-xs",children:r??"â"}),N=c&&c.length>0,G=i!=null;return t.jsxs("div",{ref:m,className:`relative min-h-[54px] rounded-md border-2 px-3 py-2.5 flex items-center gap-2 transition-all duration-150 ${y?"border-solid border-court bg-court/15 ring-2 ring-court ring-offset-1 shadow-md scale-[1.02]":n?"border-transparent bg-muted/40":`border-dashed ${h?"border-court/50 bg-court/5":"border-muted-foreground/25"}`}`,children:[t.jsx("div",{className:"flex-1 min-w-0",children:b}),N?t.jsx("span",{className:`shrink-0 tabular-nums text-sm flex gap-1.5 ${u?"font-bold text-court":"text-muted-foreground"}`,children:c.map((T,I)=>t.jsx("span",{children:T},I))}):G&&t.jsxs("span",{className:`shrink-0 tabular-nums text-sm ${u?"font-bold text-court":"text-muted-foreground"}`,children:[i,d!=null&&t.jsx("sup",{className:"text-[0.65em] ml-0.5",children:d})]}),y&&t.jsx("span",{className:"absolute inset-0 z-10 flex items-center justify-center rounded-md bg-court/90 text-xs font-bold uppercase tracking-wide text-white pointer-events-none",children:n?"â Remplacer ici":"ï¼ Déposer ici"})]})}const ki={r16:"1/8 de finale",quarter:"1/4 de finale",semi:"1/2 finales",final:"Finale",third_place:"3e place"},Ri=["r16","quarter","semi","final","third_place"],Ei={1:"lg:grid-cols-1",2:"lg:grid-cols-2",3:"lg:grid-cols-3",4:"lg:grid-cols-4"};function Di({matches:e,regs:s,availableIds:n,onReload:r,onOpenScore:o}){const[i,d]=l.useState(null),[c,u]=l.useState(!1),h=Yn(bs(Ss,{activationConstraint:{distance:5}}),bs(nn,{activationConstraint:{delay:150,tolerance:8}})),y=g=>{const v=er(g);if(v.length>0)return v;const C=Zs(g);return C.length>0?C:Zn(g)},m=l.useMemo(()=>{const g={};return e.forEach(v=>{var C,F;v.pair_a_id&&(g[C=v.pair_a_id]??(g[C]=[])).push({matchId:v.id,slot:"a",stage:v.stage}),v.pair_b_id&&(g[F=v.pair_b_id]??(g[F]=[])).push({matchId:v.id,slot:"b",stage:v.stage})}),g},[e]),b=l.useMemo(()=>n?Array.from(n).filter(g=>s[g]):[],[n,s]),N=Ri.filter(g=>e.some(v=>v.stage===g)),G=g=>{g.games_a=null,g.games_b=null,g.tiebreak_a=null,g.tiebreak_b=null,g.sets=null,g.match_format="single9",g.winner_id=null,g.status="pending"},T=(g,v,C=new Set)=>{if(C.has(g))return;C.add(g);const F=e.find(L=>L.id===g);if(!F)return;const z=(L,f)=>{if(!L||f!=="a"&&f!=="b")return;const A=v[L]??(v[L]={});A[f==="a"?"pair_a_id":"pair_b_id"]=null,G(A),T(L,v,C)};z(F.next_match_id,F.next_slot),z(F.loser_match_id,F.loser_slot)},I=async g=>{u(!0);try{for(const[v,C]of Object.entries(g)){const{error:F}=await Q.from("matches").update(C).eq("id",v);if(F)return O.error(F.message),!1}return!0}finally{u(!1)}},E=async(g,v,C,F)=>{var X;const z=e.find(V=>V.id===v);if(!z)return;const L=C==="a"?z.pair_a_id:z.pair_b_id;if(L===g)return;const f={},A=V=>f[V]??(f[V]={}),p=(V,J,de)=>{const se=A(V);se[J==="a"?"pair_a_id":"pair_b_id"]=de,G(se),T(V,f)},_=F.type==="slot"?e.find(V=>V.id===F.matchId):void 0;if(F.type==="slot"&&F.matchId!==v&&(_==null?void 0:_.stage)===z.stage)p(F.matchId,F.slot,L??null);else if(F.type==="slot"&&F.matchId===v)p(F.matchId,F.slot,L??null);else{const V=(X=m[g])==null?void 0:X.find(J=>
35J.stage===z.stage&&!(J.matchId===v&&J.slot===C));V&&p(V.matchId,V.slot,L??null)}p(v,C,g),await I(f)&&r()},$=async(g,v)=>{const C={};C[v==="a"?"pair_a_id":"pair_b_id"]=null,G(C);const F={[g]:C};T(g,F),await I(F)&&r()},B=g=>{const v=String(g.active.id),C=On(v);C&&d(C.regId)},Y=g=>{d(null);const{active:v,over:C}=g;if(!C)return;const F=String(v.id),z=String(C.id),L=On(F);if(!L||!z.startsWith("bslot:"))return;const[,f,A]=z.split(":");E(L.regId,f,A,L)},q=i?s[i]:void 0;return t.jsxs(xr,{sensors:h,collisionDetection:y,onDragStart:B,onDragEnd:Y,children:[t.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 mb-3 flex items-start gap-2 text-xs text-muted-foreground",children:[t.jsx(Hn,{className:"h-4 w-4 shrink-0 mt-0.5"}),t.jsx("span",{children:"Glissez-déposez les paires pour corriger le tableau. D'un tour à l'autre, une paire est copiée sans vider son match précédent ; dans un même tour, elle est déplacée/échangée. Modifier une paire réinitialise le score du match concerné."})]}),b.length>0&&t.jsxs("div",{className:"mb-4",children:[t.jsx("div",{className:"text-sm font-semibold mb-2",children:"Paires disponibles"}),t.jsx("div",{className:"grid gap-1.5 sm:grid-cols-2 lg:grid-cols-3",children:b.map(g=>t.jsx(Ci,{regId:g,label:Ks(s[g]),dragging:i===g},g))})]}),t.jsx("div",{className:`grid gap-4 md:grid-cols-2 ${Ei[Math.min(N.length,4)]}`,children:N.map(g=>t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-semibold mb-2",children:ki[g]??g}),t.jsx("div",{className:"space-y-2",children:e.filter(v=>v.stage===g).sort((v,C)=>v.position-C.position).map(v=>{const C=v.pair_a_id?s[v.pair_a_id]:void 0,F=v.pair_b_id?s[v.pair_b_id]:void 0,z=v.status==="completed",L=v.pair_a_id&&v.pair_b_id;return t.jsxs(ce,{className:"p-3 text-sm",children:[t.jsxs("div",{className:"text-xs text-muted-foreground mb-2 flex items-center justify-between",children:[t.jsx("span",{children:v.label}),z&&t.jsx("span",{className:"text-success font-semibold",children:"Terminé"})]}),t.jsxs("div",{className:"space-y-1.5",children:[t.jsx(In,{matchId:v.id,slot:"a",reg:C,sourceLabel:v.pair_a_source,onClear:()=>$(v.id,"a"),games:v.games_a,tiebreak:v.tiebreak_a,setScores:Us(v)?us(v,"a"):void 0,isWinner:!!v.winner_id&&v.winner_id===v.pair_a_id,isDragActive:!!i}),t.jsx(In,{matchId:v.id,slot:"b",reg:F,sourceLabel:v.pair_b_source,onClear:()=>$(v.id,"b"),games:v.games_b,tiebreak:v.tiebreak_b,setScores:Us(v)?us(v,"b"):void 0,isWinner:!!v.winner_id&&v.winner_id===v.pair_b_id,isDragActive:!!i})]}),L&&t.jsx(K,{size:"sm",variant:z?"outline":"default",className:"mt-2 w-full h-7 text-xs",disabled:c,onClick:()=>o(v),children:z?"Modifier le score":"Saisir le score"})]},v.id)})})]},g))}),t.jsx(br,{children:q?t.jsxs("div",{className:"flex items-center gap-2 rounded-lg border bg-card px-2.5 py-2 text-sm shadow-lg",children:[t.jsx(Dt,{className:"h-4 w-4 text-muted-foreground"}),t.jsx("span",{children:Ks(q)})]}):null})]})}const Ti=({tournamentId:e,category:s,confirmedRegs:n,onSaved:r})=>{const[o,i]=l.useState({}),[d,c]=l.useState({}),[u,h]=l.useState({}),[y,m]=l.useState(!1),b=n.length,N=async()=>{const[{data:E},{data:$}]=await Promise.all([Q.from("tournament_results").select("registration_id,final_rank").eq("tournament_id",e),Q.from("points_scale").select("rank,points,min_pairs,max_pairs").eq("category",s).lte("min_pairs",b).gte("max_pairs",b).order("rank")]),B={},Y={};
35E==null||E.forEach(g=>{B[g.registration_id]=g.final_rank,Y[g.registration_id]=g.final_rank}),i(B),c(Y);const q={};$==null||$.forEach(g=>{q[g.rank]=g.points}),h(q)};l.useEffect(()=>{N()},[e,s,b]);const G=(E,$)=>{const B=$===""?"":parseInt($,10);i(Y=>({...Y,[E]:B}))},T=async()=>{m(!0);const E=Object.entries(o).filter(([,q])=>q!==""&&q!=null).map(([q,g])=>({tournament_id:e,registration_id:q,final_rank:g})),$=E.map(q=>q.registration_id),{data:B}=await Q.from("tournament_results").select("id,registration_id").eq("tournament_id",e),Y=(B==null?void 0:B.filter(q=>!$.includes(q.registration_id)).map(q=>q.id))??[];if(Y.length){const{error:q}=await Q.from("tournament_results").delete().in("id",Y);if(q)return m(!1),O.error(q.message)}if(E.length){const{error:q}=await Q.from("tournament_results").upsert(E,{onConflict:"tournament_id,registration_id"});if(q)return m(!1),O.error(q.message)}m(!1),O.success("Résultats enregistrés"),r==null||r(),N()};if(n.length===0)return t.jsx(ce,{className:"p-6 text-center text-muted-foreground",children:"Aucune paire confirmée à classer."});const I=[...n].map((E,$)=>({r:E,i:$})).sort((E,$)=>{const B=d[E.r.id]||99,Y=d[$.r.id]||99;return B!==Y?B-Y:E.i-$.i}).map(({r:E})=>E);return t.jsxs("div",{className:"space-y-4",children:[t.jsx(ce,{className:"p-4 bg-muted/30",children:t.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[t.jsx(Vs,{className:"h-4 w-4 text-court mt-0.5"}),t.jsxs("div",{children:[t.jsxs("p",{className:"font-medium",children:["Saisie des résultats â catégorie ",s," · ",b," paire",b>1?"s":""]}),t.jsx("p",{className:"text-muted-foreground text-xs mt-1",children:"Attribuez à chaque paire son rang final (1 = vainqueur, 2 = finaliste, 3-4 = demi-finalistesâ¦). Vous pouvez donner le même rang à plusieurs paires (ex-æquo) si des matchs de classement n'ont pas pu être joués. Les points sont calculés automatiquement selon le barème officiel FFT, en fonction du nombre de paires engagées."})]})]})}),t.jsx("div",{className:"space-y-2",children:I.map(E=>{const $=o[E.id],B=typeof $=="number"?u[$]??0:0;return t.jsxs(ce,{className:"p-3 flex flex-wrap items-center gap-3",children:[t.jsxs("div",{className:"flex-1 min-w-[240px]",children:[t.jsxs("div",{className:"font-medium text-sm",children:[E.player_first_name," ",E.player_last_name," / ",E.partner_first_name," ",E.partner_last_name]}),t.jsxs("div",{className:"text-xs text-muted-foreground",children:[E.player_license," · ",E.partner_license]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Se,{className:"text-xs",children:"Rang"}),t.jsx(Ge,{type:"number",min:1,max:64,className:"w-20",value:$??"",onChange:Y=>G(E.id,Y.target.value)}),t.jsx("span",{className:"text-xs text-muted-foreground w-16 text-right",children:B>0?`${B} pts`:"â"})]})]},E.id)})}),t.jsxs(K,{onClick:T,disabled:y,className:"bg-court",children:[t.jsx(kt,{className:"h-4 w-4 mr-2"}),y?"Enregistrementâ¦":"Enregistrer les résultats"]})]})},jr=`Bonjour à tous, 36 37Voici les informations concernant le tournoi {{titre}} qui aura lieu le {{date}} ! 38 39Il y aura {{nb_paires}} paires engagées ð¥ 40Je compte sur votre PONCTUALITà pour la bonne organisation du tournoi. 41 42MERCI DE CONFIRMER VOTRE PRÃSENCE en cliquant sur le bouton en bas de cet e-mail. 43 44LE CENTRE 45Padel AC â 58 rue de la belle étoile, 95700 Roissy-en-France 46GPS / WAZE : Padel AC 4710 pistes indoor panoramiques â 1 piste single. 48Parking, vestiaires hommes/femmes séparés et douches, salon/bar pour se restaurer. 49 50FORMAT 511 set de 9 jeux, pas d'avantages, tie-break à 7 points à 8/8. D'autres formats pourront être utilisés si nécessaire. 52 53INFORMATION IMPORTANTE : les temps de repos entre les matchs peuvent être courts. En confirmant votre présence, vous acceptez cette possibilité. 54 55EN CAS DE RETARD, DES PÃNALITÃS DE JEUX SERONT APPLIQUÃES. 56 57Le règlement du tournoi pourra s'effectuer en CB ou en espèces sur place. 58 59à très vite en forme ð¥ 60Sportivement, 61L'équipe Padel AC`;function Nt(e){return(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function ys(e){if(!e)return"â";const s=String(e).match(/^(\d{1,2})[:h](\d{2})/);return s?`${s[1].padStart(2,"0")}h${s[2]}`:String(e)}function $i(e){const s=new Map,n=[],r=e.slice().sort((i,d)=>(i.time??"~").localeCompare(d.time??"~"));for(const i of r){const d=ys(i.time);s.has(d)||(s.set(d,[]),n.push(d)),s.get(d).push(i.name)}return`<div style="border:1px solid #e5e7eb;border-radius:10px;padding:14px 16px;background:#fafafa">${n.map(i=>{const d=s.get(i).map(c=>`<div style="padding:2px 0;
61color:#1a1a1a">${Nt(c)}</div>`).join("");return`<div style="margin:10px 0"> 62 <div style="font-weight:700;color:#0b1220;margin-bottom:4px">${Nt(i)}</div> 63 ${d} 64 </div>`}).join("")}</div>`}function Mi(e){return Nt(e).split(/\n{2,}/).map(s=>`<p style="margin:0 0 14px;white-space:pre-wrap">${s.replace(/\n/g,"<br/>")}</p>`).join("")}function Ai(e){const s=ys(e.pairTime),n=$i(e.listItems),r=(e.template||jr).replace(/\{\{\s*titre\s*\}\}/gi,e.title).replace(/\{\{\s*date\s*\}\}/gi,e.dateLabel).replace(/\{\{\s*nb_paires\s*\}\}/gi,String(e.pairCount)).replace(/\{\{\s*heure_paire\s*\}\}/gi,s).replace(/\{\{\s*nom_paire\s*\}\}/gi,e.pairName),o=/\{\{\s*liste_convocations\s*\}\}/i.test(r);let i=Mi(r.replace(/\{\{\s*liste_convocations\s*\}\}/gi,"@@LISTE@@"));i=o?i.replace("@@LISTE@@",n):i+'<h3 style="font-size:15px;color:#0b1220;margin:18px 0 8px">Convocations</h3>'+n;const d=` 65 <div style="border-radius:12px;padding:16px 18px;background:#0b1220;color:#ffffff;margin:0 0 18px"> 66 <div style="font-size:12px;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Votre convocation</div> 67 <div style="font-size:20px;font-weight:800;margin-top:4px">${Nt(e.pairName)}</div> 68 <div style="font-size:16px;margin-top:2px">Présentez-vous à <strong>${Nt(s)}</strong></div> 69 </div>`,c=e.alreadyConfirmed?'<div style="text-align:center;margin:24px 0;color:#15803d;font-weight:700">â Présence déjà confirmée â merci !</div>':`<div style="text-align:center;margin:26px 0"> 70 <a href="${e.confirmUrl}" style="display:inline-block;background:#2563eb;color:#ffffff;text-decoration:none;font-weight:700;padding:14px 28px;border-radius:10px;font-size:16px">Je confirme ma présence â </a> 71 <div style="font-size:12px;color:#6b7280;margin-top:10px">Merci de confirmer obligatoirement la bonne réception de cette c
71onvocation.</div> 72 </div>`;return`<div style="max-width:600px;margin:0 auto;padding:24px 22px;font-family:Arial,Helvetica,sans-serif;font-size:15px;line-height:1.6;color:#1a1a1a;background:#ffffff"> 73 <div style="font-size:22px;font-weight:800;color:#0b1220;margin-bottom:4px">${Nt(e.title)}</div> 74 <div style="color:#6b7280;margin-bottom:18px">${Nt(e.dateLabel)}</div> 75 ${d} 76 ${i} 77 ${c} 78 </div>`}const ls=e=>{if(!e)return"";const s=String(e).match(/^(\d{1,2}):(\d{2})/);return s?`${s[1].padStart(2,"0")}:${s[2]}`:""},zn=e=>e?`${e}:00`:null,Pi=(e,s)=>{const n=e.match(/^(\d{1,2}):(\d{2})/);if(!n)return e;let r=parseInt(n[1],10)*60+parseInt(n[2],10)+s;r=(r%1440+1440)%1440;const o=Math.floor(r/60),i=r%60;return`${String(o).padStart(2,"0")}:${String(i).padStart(2,"0")}`},cs=e=>`${(e.player_last_name??"").toUpperCase()} / ${(e.partner_last_name??"").toUpperCase()}`,Li=e=>{if(!e)return"";try{return new Date(e+"T00:00:00").toLocaleDateString("fr-FR",{weekday:"long",day:"2-digit",month:"long",year:"numeric"})}catch{return e??""}},qn=e=>{const s=parseInt((e||"").replace(/[^\d]/g,""),10);return Number.isFinite(s)&&s>0?s:null},Oi=({tournament:e})=>{const s=e.id,[n,r]=l.useState([]),[o,i]=l.useState([]),[d,c]=l.useState({}),[u,h]=l.useState(new Set),[y,m]=l.useState(""),[b,N]=l.useState(""),[G,T]=l.useState(""),[I,E]=l.useState(!0),[$,B]=l.useState(!1),[Y,q]=l.useState(!1),[g,v]=l.useState(!1),[C,F]=l.useState(!1),z=async()=>{var x,w;E(!0);const[{data:D},{data:P},{data:H},{data:ee},{data:xe},{data:ie}]=await Promise.all([Q.from("registrations").select("id,player_first_name,player_last_name,player_email,partner_first_name,partner_last_name,partner_email,player_ranking,partner_ranking,convocation_time,status,forfeit").eq("tournament_id",s).eq("status","confirmed"),Q.from("convocation_recipients").select("id,registration_id,role,email,name,sent_at,confirmed_at").eq("tournament_id",s),Q.from("app_settings").select("convocation").limit(1).maybeSingle(),Q.from("tournaments").select("convocation_message").eq("id",s).maybeSingle(),Q.from("matches").select("pair_a_id,pair_b_id,scheduled_time").eq("tournament_id",s),Q.from("pool_assignments").select("registration_id,is_top_seed").eq("tournament_id",s)]),ae=e.gender==="hommes"?"H":e.gender==="femmes"?"F":null,{data:be}=await Q.rpc("fft_player_count",{_gender:ae}),ve=typeof be=="number"?be:null,ye=R=>{const M=qn(R.player_ranking)??ve,te=qn(R.partner_ranking)??ve;return M!=null&&te!=null?M+te:null},ue=(D??[]).filter(R=>!R.forfeit).sort((R,M)=>{const te=ye(R),re=ye(M);return te==null&&re==null?0:te==null?1:re==null?-1:te-re});r(ue),i(P??[]);const $e=(x=H==null?void 0:H.convocation)==null?void 0:x.template;T(($e??"").trim()),N(((w=ee==null?void 0:ee.convocation_message)==null?void 0:w.trim())||($e==null?void 0:$e.trim())||jr);const Ae={};ue.forEach(R=>{Ae[R.id]=ls(R.convocation_time)}),c(Ae),z._matches=xe??[],z._assigns=ie??[],E(!1)};l.useEffect(()=>{z()},[s]);const L=()=>{const D=z._matches??[],P=z._assigns??[],H=new Set(P.filter(ae=>ae.is_top_seed).map(ae=>ae.registration_id)),ee={};for(const ae of D){if(!ae.scheduled_time)continue;const be=ls(ae.scheduled_time);for(const ve of[ae.pair_a_id,ae.pair_b_id])ve&&(!ee[ve]||be<ee[ve])&&(ee[ve]=be)}const xe=ls(e.start_time)||"08:30",ie={};n.forEach(ae=>{ee[ae.id]?ie[ae.id]=ee[ae.id]:H.has(ae.id)?ie[ae.id]=Pi(xe,210):ie[ae.id]=xe}),c(ie),O.success("Heures déduites â vérifie puis enregistre.")},f=async()=>{B(!0);try{const D=n.filter(P=>ls(P.convocation_time)!==(d[P.id]??""));for(const P of D){const{error:H}=await Q.from("registrations").update({convocation_time:zn(d[P.id]??"")}).eq("id",P.id);if(H)throw H}r(P=>P.map(H=>({...H,convocation_time:zn(d[H.id]??"")}))),O.success("Heures de convocation enregistrées.")}catch(D){O.error((D==null?void 0:D.message)??"Ãchec de l'enregistrement.")}B(!1)},A=()=>{if(!y)return O.error("Choisis une heure.");if(!u.size)return O.error("Sélectionne au moins une paire.");c(D=>{const P={...D};return u.forEach(H=>{P[H]=y}),P}),O.success(`${u.size} paire(s) convoquée(s) à ${ys(y)}.`)},p=D=>h(P=>{const H=new Set(P);return H.has(D)?H.delete(D):H.add(D),H}),_=()=>h(D=>D.size===n.length?new Set:new Set(n.map(P=>P.id))),W=async()=>{q(!0);const{error:D}=await Q.from("tournaments").update({convocation_message:b}).eq("id",s);if(q(!1),D)return O.error(D.message);O.success("Message enregistré pour ce tournoi.")},X=async()=>{const{error:D}=await Q.from("app_settings").update({convocation:{template:b}}).eq("id",!0);if(D)return O.error(D.message);T(b.trim()),O.success("Modèle par défaut du club mis à jour.")},V=async(D,P=!1)=>
78{if(!n.filter(ee=>d[ee.id]).length)return O.error("Renseigne au moins une heure de convocation.");if(P&&!u.size)return O.error("Sélectionne au moins une paire.");v(!0);try{await f(),await Q.from("tournaments").update({convocation_message:b}).eq("id",s);const{data:ee,error:xe}=await Q.functions.invoke("send-convocations",{body:{tournament_id:s,only_unconfirmed:D,...P?{registration_ids:Array.from(u)}:{}}});if(xe)throw xe;if(ee!=null&&ee.error)throw new Error(typeof ee.error=="string"?ee.error:"Erreur d'envoi.");const ie=ee;O.success(`${ie.sent} e-mail(s) envoyé(s)${ie.failed?`, ${ie.failed} échec(s)`:""}.`),await z()}catch(ee){O.error((ee==null?void 0:ee.message)??"Ãchec de l'envoi.")}v(!1)},J=l.useMemo(()=>{const D={};return o.forEach(P=>{var H;(D[H=P.registration_id]??(D[H]=[])).push(P)}),D},[o]),de=o.filter(D=>D.confirmed_at).length,se=o.filter(D=>D.sent_at).length,oe=n.map(D=>({name:cs(D),time:d[D.id]||null})),me=l.useMemo(()=>{const D=n[0];return Ai({template:b,title:`${e.title}${e.category?" â "+e.category:""}`,dateLabel:Li(e.tournament_date),pairCount:n.length,pairName:D?cs(D):"VOTRE / PAIRE",pairTime:D&&d[D.id]||null,listItems:oe,confirmUrl:"#"})},[b,n,d,e]);if(I)return t.jsx(ce,{className:"p-8 text-center",children:t.jsx(Ie,{className:"h-6 w-6 animate-spin mx-auto text-muted-foreground"})});if(!n.length)return t.jsx(ce,{className:"p-8 text-center text-muted-foreground",children:"Aucune paire confirmée à convoquer."});const le=se>0;return t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[t.jsxs(ce,{className:"p-4",children:[t.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Paires"}),t.jsx("div",{className:"font-display text-2xl tabular-nums",children:n.length})]}),t.jsxs(ce,{className:"p-4",children:[t.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"E-mails envoyés"}),t.jsx("div",{className:"font-display text-2xl tabular-nums",children:se})]}),t.jsxs(ce,{className:"p-4",children:[t.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Présences confirmées"}),t.jsxs("div",{className:"font-display text-2xl tabular-nums",children:[de,t.jsxs("span",{className:"text-base text-muted-foreground",children:["/",se||n.length*2]})]})]})]}),t.jsxs(ce,{className:"p-4 space-y-3",children:[t.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[t.jsxs("h3",{className:"font-semibold flex items-center gap-2",children:[t.jsx(bn,{className:"h-4 w-4"})," Heures de convocation"]}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsxs(K,{size:"sm",variant:"outline",onClick:L,children:[t.jsx(Xt,{className:"h-4 w-4 mr-1.5"})," Déduire les heures"]}),t.jsxs(K,{size:"sm",onClick:f,disabled:$,className:"bg-court",children:[$?t.jsx(Ie,{className:"h-4 w-4 mr-1.5 animate-spin"}):t.jsx(kt,{className:"h-4 w-4 mr-1.5"})," Enregistrer les heures"]})]})]}),t.jsxs("div",{className:"flex flex-wrap items-center gap-2 rounded-md bg-muted/50 p-2",children:[t.jsx(vn,{checked:u.size===n.length&&n.length>0,onCheckedChange:_,id:"all"}),t.jsx(Se,{htmlFor:"all",className:"text-sm",children:"Tout"}),t.jsxs("span",{className:"text-sm text-muted-foreground",children:["· ",u.size," sélectionnée(s)"]}),t.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[t.jsx(Ge,{type:"time",value:y,onChange:D=>m(D.target.value),className:"w-32 h-9"}),t.jsx(K,{size:"sm",variant:"secondary",onClick:A,children:"Convoquer à cette heure"})]})]}),t.jsx("div",{className:"divide-y",children:n.map(D=>{const P=J[D.id]??[];return t.jsxs("div",{className:"flex flex-wrap items-center gap-3 py-2",children:[t.jsx(vn,{checked:u.has(D.id),onCheckedChange:()=>p(D.id)}),t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"font-medium truncate",children:cs(D)}),t.jsxs("div",{className:"text-xs text-muted-foreground flex flex-wrap gap-2",children:[P.length===0&&t.jsx("span",{children:"Pas encore envoyé"}),P.map(H=>t.jsxs("span",{className:"inline-flex items-center gap-1",children:[H.confirmed_at?t.jsx(Or,{className:"h-3 w-3 text-court"}):H.sent_at?t.jsx(bn,{className:"h-3 w-3 text-amber-500"}):t.jsx(Ir,{className:"h-3 w-3"}),H.role==="player"?D.player_first_name:D.partner_first_name]}
78,H.id))]})]}),t.jsx(Ge,{type:"time",value:d[D.id]??"",onChange:H=>c(ee=>({...ee,[D.id]:H.target.value})),className:"w-28 h-9"})]},D.id)})})]}),t.jsxs(ce,{className:"p-4 space-y-3",children:[t.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[t.jsx("h3",{className:"font-semibold",children:"Message de convocation"}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsxs(K,{size:"sm",variant:"ghost",onClick:()=>F(D=>!D),children:[t.jsx(jn,{className:"h-4 w-4 mr-1.5"})," ",C?"Masquer":"Aperçu"]}),t.jsxs(K,{size:"sm",variant:"outline",onClick:W,disabled:Y,children:[Y?t.jsx(Ie,{className:"h-4 w-4 mr-1.5 animate-spin"}):t.jsx(kt,{className:"h-4 w-4 mr-1.5"})," Enregistrer"]}),t.jsxs(K,{size:"sm",variant:"outline",onClick:X,children:[t.jsx(Xr,{className:"h-4 w-4 mr-1.5"})," Modèle par défaut"]})]})]}),t.jsx(Wn,{value:b,onChange:D=>N(D.target.value),rows:12,className:"font-mono text-sm"}),t.jsxs("p",{className:"text-xs text-muted-foreground",children:["Variables : ",t.jsx("code",{children:"{{titre}}"})," ",t.jsx("code",{children:"{{date}}"})," ",t.jsx("code",{children:"{{nb_paires}}"})," ",t.jsx("code",{children:"{{nom_paire}}"})," ",t.jsx("code",{children:"{{heure_paire}}"})," ",t.jsx("code",{children:"{{liste_convocations}}"}),". L'heure personnelle et le bouton de confirmation sont ajoutés automatiquement."]}),C&&t.jsxs("div",{className:"rounded-lg border overflow-hidden",children:[t.jsx("div",{className:"bg-muted px-3 py-1.5 text-xs text-muted-foreground",children:"Aperçu (exemple avec la 1ʳᵠpaire)"}),t.jsx("div",{dangerouslySetInnerHTML:{__html:me}})]})]}),t.jsxs(ce,{className:"p-4 space-y-3",children:[t.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[t.jsxs("h3",{className:"font-semibold flex items-center gap-2",children:[t.jsx(jn,{className:"h-4 w-4"})," Prévisualisation complète du mail"]}),t.jsxs("p",{className:"text-xs text-muted-foreground",children:["Exemple envoyé à ",t.jsx("span",{className:"font-medium text-foreground",children:n[0]?cs(n[0]):"la 1ʳᵠpaire"}),n[0]&&d[n[0].id]?` · convoquée à ${ys(d[n[0].id])}`:""]})]}),t.jsxs("div",{className:"rounded-lg border bg-white overflow-hidden",children:[t.jsxs("div",{className:"flex flex-col gap-0.5 border-b bg-muted/60 px-4 py-3 text-sm",children:[t.jsxs("div",{children:[t.jsx("span",{className:"text-muted-foreground",children:"De :"})," Padel AC <[email protected]>"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-muted-foreground",children:"Objet :"})," ",t.jsxs("span",{className:"font-medium",children:["Convocation â ",e.title,e.category?" "+e.category:""]})]})]}),t.jsx("div",{className:"max-h-[600px] overflow-auto p-2 sm:p-4",children:t.jsx("div",{dangerouslySetInnerHTML:{__html:me}})})]})]}),t.jsxs(ce,{className:"p-4 flex flex-wrap items-center justify-between gap-3",children:[t.jsx("p",{className:"text-sm text-muted-foreground",children:"Chaque joueur reçoit sa convocation par e-mail avec un bouton de confirmation en 1 clic. Coche des paires ci-dessus pour ne renvoyer qu'à celles-ci (utile si un horaire change)."}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[u.size>0&&t.jsxs(K,{variant:"secondary",onClick:()=>V(!1,!0),disabled:g,children:[g?t.jsx(Ie,{className:"h-4 w-4 mr-1.5 animate-spin"}):t.jsx(fs,{className:"h-4 w-4 mr-1.5"}),"Renvoyer à la sélection (",u.size,")"]}),le&&t.jsxs(K,{variant:"outline",onClick:()=>V(!0),disabled:g,children:[g?t.jsx(Ie,{className:"h-4 w-4 mr-1.5 animate-spin"}):t.jsx(Yr,{className:"h-4 w-4 mr-1.5"})," Relancer les non-confirmés"]}),t.jsxs(K,{onClick:()=>V(!1),disabled:g,className:"bg-court",children:[g?t.jsx(Ie,{className:"h-4 w-4 mr-1.5 animate-spin"}):t.jsx(fs,{className:"h-4 w-4 mr-1.5"}),le?"Renvoyer à tous":"Envoyer les convocations"]})]})]})]})};function Ii({tournamentId:e,path:s,title:n,onChanged:r}){const o=l.useRef(null),[i,d]=l.useState(null),[c,u]=l.useState(!1);l.useEffect(()=>{let m=!0;return d(null),zr(s).then(b=>{m&&d(b)}),()=>{m=!1}},[s]);const h=async m=>{if(!m.type.startsWith("image/")){O.error("Merci de choisir une image (JPEG, PNGâ¦).");return}if(m.size>10*1024*1024){O.error("Image trop lourde (max 10 Mo).");return}u(!0);try{await qr(e,m),O.success("Photo du podium enregistrée ð"),r==null||r()}catch(b){O.error(b.message||"Ãchec de l'envoi de la photo.")}finally{u(!1),o.current&&(o.current.value="")}},y=async()=>
78{if(s){u(!0);try{await Fr(e,s),O.success("Photo du podium supprimée."),r==null||r()}catch(m){O.error(m.message||"Ãchec de la suppression.")}finally{u(!1)}}};return t.jsxs(ce,{className:"mb-6 p-4",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[t.jsx(Ws,{className:"h-4 w-4 text-accent"}),t.jsx("span",{className:"text-xs uppercase tracking-[0.2em] font-extrabold text-accent",children:"Photo du podium"})]}),t.jsx("input",{ref:o,type:"file",accept:"image/*",className:"hidden",onChange:m=>{var N;const b=(N=m.target.files)==null?void 0:N[0];b&&h(b)}}),s?t.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[t.jsx("div",{className:"w-full sm:w-56 shrink-0 overflow-hidden rounded-xl border border-border bg-muted",children:i?t.jsx("img",{src:i,alt:n?`Podium du tournoi ${n}`:"Photo du podium",className:"w-full h-auto object-cover"}):t.jsx("div",{className:"aspect-video w-full animate-pulse bg-muted"})}),t.jsxs("div",{className:"flex flex-col justify-center gap-2",children:[t.jsx("p",{className:"text-sm text-muted-foreground",children:"Cette photo est visible par tous sur la fiche du tournoi, la page live et l'accueil."}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsxs(K,{variant:"outline",disabled:c,onClick:()=>{var m;return(m=o.current)==null?void 0:m.click()},children:[c?t.jsx(Ie,{className:"h-4 w-4 mr-2 animate-spin"}):t.jsx(Kr,{className:"h-4 w-4 mr-2"}),"Remplacer"]}),t.jsxs(K,{variant:"outline",className:"text-destructive hover:text-destructive",disabled:c,onClick:y,children:[t.jsx(ms,{className:"h-4 w-4 mr-2"}),"Supprimer"]})]})]})]}):t.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-3",children:[t.jsx("p",{className:"text-sm text-muted-foreground flex-1",children:"Ajoutez la photo du podium prise au club : elle sera visible par les joueurs sur la fiche du tournoi, la page live et l'accueil."}),t.jsxs(K,{className:"bg-court",disabled:c,onClick:()=>{var m;return(m=o.current)==null?void 0:m.click()},children:[c?t.jsx(Ie,{className:"h-4 w-4 mr-2 animate-spin"}):t.jsx(Ws,{className:"h-4 w-4 mr-2"}),"Ajouter la photo"]})]})]})}const zi=["A","B","C","D","E","F","G","H"];function qi(e,s){const n=s.map(i=>Array.from({length:i},()=>null)),r=s.reduce((i,d)=>Math.max(i,d),0),o=[...e];for(let i=0;i<r;i++){const d=s.map((c,u)=>u);i%2===1&&d.reverse();for(const c of d){if(i>=s[c])continue;const u=o.shift();if(!u)return n;n[c][i]=u}}return n}const ut=["r16","quarter","semi","final"],Fs={r16:16,quarter:8,semi:4,final:2},yr={r16:"r16",quarter:"quarter",semi:"semi",final:"final"},Xe={r16:"1/8 Finale",quarter:"1/4 Finale",semi:"1/2 Finale",final:"Finale"},mt=["1er","2e","3e"];function Fn(e){var A;const{pools:s,topSeeds:n,byeSeeds:r,qualifiersPerPool:o,bestRunnersUp:i,startRound:d,thirdPlace:c,classifSources:u}=e,h=[],y=Math.max(0,Math.min(r,n)),m=ut.indexOf(d),b=ut.slice(m),N={},G=p=>{if(p<=1)return[1];const _=G(p/2),W=[];return _.forEach((X,V)=>{const J=[X,p+1-X];V%2===1&&J.reverse(),W.push(J[0],J[1])}),W},T=Fs[d],I=G(T).reverse(),E=new Array(T).fill(null);for(let p=1;p<=y;p++){const _=I.indexOf(p);if(_<0)continue;E[_]=`TS${p}`;const W=_%2===0?_+1:_-1;E[W]="BYE"}const $=[];for(let p=y+1;p<=n;p++)$.push(`TS${p}`);const B=p=>Math.min(p.qualifiers??o,p.size),Y=s.reduce((p,_)=>Math.max(p,B(_)),0);for(let p=1;p<=Y;p++)s.forEach(_=>{B(_)<p||$.push(`${mt[p-1]??`${p}e`} Poule ${_.name}`)});if(i>0){const p=o+1,_=mt[p-1]??`${p}e`;for(let W=1;W<=i;W++)$.push(i===1?`Meilleur ${_}`:`Meilleur ${_} n°${W}`)}let q=0;for(let p=1;p<=T;p++){const _=I.indexOf(p);_<0||E[_]!=null||(E[_]=$[q++]??"BYE")}for(let p=0;p<b.length;p++){const _=b[p],W=Fs[_]/2,X=[];for(let V=0;V<W;V++){let J,de;if(p===0)J=E[2*V]??"BYE",de=E[2*V+1]??"BYE";else{const oe=b[p-1];J=`Vainqueur ${Xe[oe]} ${V*2+1}`,de=`Vainqueur ${Xe[oe]} ${V*2+2}`}const se=_==="final";X.push({key:se?"final":`${_}-${V+1}`,stage:yr[_],label:se?"Finale":`${Xe[_]} ${V+1}`,position:V+1,pair_a_source:J,pair_b_source:de})}N[_]=X,h.push(...X)}for(let p=0;p<b.length-1;p++){const _=N[b[p]],W=N[b[p+1]];_.forEach((X,V)=>{X.next_key=W[Math.floor(V/2)].key,X.next_slot=V%2===0?"a":"b"})}if(b.length>=2){const p=b[0],_=b[1],W=N[p],X=N[_],V=new Set;if(W.forEach((J,de)=>{const se=J.pair_a_source==="BYE",oe=J.pair_b_source==="BYE",me=/^TS\d+$/.test(J.pair_a_source),le=/^TS\d+$/.test(J.pair_b_source);if(se&&le||oe&&me){const D=me?J.pair_a_source:J.pair_b_source,P=X[Math.floor(de/2)];(de%2===0?"a":"b")==="a"?P.pair_a_source=D:P.pair_b_source=D,V.add(J.key)}}),V.size>0){const J=new Map;W.forEach((se,oe)=>J.set(se.key,oe)),N[p]=W.filter(se=>!V.has(se.key));for(let se=h.length-1;se>=0;se--)V.has(h[se].key)&&h.splice(se,1);const de=Xe[p];
78N[p].forEach((se,oe)=>{const me=se.key,le=J.get(me)??oe,D=X[Math.floor(le/2)],P=le%2===0?"a":"b";se.position=oe+1,se.label=`${Xe[p]} ${oe+1}`;const H=p==="final"?"final":`${p}-${oe+1}`;if(H!==me&&(h.forEach(ee=>{ee.next_key===me&&(ee.next_key=H),ee.loser_key===me&&(ee.loser_key=H)}),se.key=H),D){se.next_key=D.key,se.next_slot=P;const ee=`Vainqueur ${de} ${se.position}`;P==="a"?D.pair_a_source=ee:D.pair_b_source=ee}})}}if(c&&N.semi){const p=N.semi;h.push({key:"third",stage:"third_place",label:"Match pour la 3e place",position:1,pair_a_source:"Perdant 1/2 Finale 1",pair_b_source:"Perdant 1/2 Finale 2"}),p.forEach((_,W)=>{_.loser_key="third",_.loser_slot=W===0?"a":"b"})}const g=s.reduce((p,_)=>Math.max(p,_.size),0),v=Fs[d],C=(p,_)=>_<=1?`${p}e place`:`places ${p}-${p+_-1}`,F=p=>`${p}e / ${p+1}e place`;let z=v+1;const L={};for(let p=o+1;p<=g;p++){if(!u.includes(`pool-${p}`))continue;const _=s.filter(W=>W.size>=p).length;L[p]=z,z+=_}let f=1;for(const p of u)if(p.startsWith("pool-")){const _=Number(p.split("-")[1]);if(!_||_<=o||_>g)continue;const W=mt[_-1]??`${_}e`,X=s.filter(le=>le.size>=_).map(le=>le.name),V=L[_]??z,J=X.length,de=Math.floor(J/2),se=V+de-1,oe=V+J-1,me=de>1?`${se}e / ${oe}e place`:F(V);for(let le=0;le<X.length;le+=2){const D=X[le],P=X[le+1];!D||!P||(h.push({key:`cl-p${_}-${f}`,stage:"classification",label:`${W} de poule · ${me}`,position:f,pair_a_source:`${W} Poule ${D}`,pair_b_source:`${W} Poule ${P}`}),f++)}}else if(p.startsWith("losers-")){const _=p.split("-")[1],W=N[_];if(!W||W.length<2)continue;const X=Xe[_],V=W.length,J=ut.indexOf(_),de=ut[J+1],oe=(de?(((A=N[de])==null?void 0:A.length)??0)*2:V)+1,me=W.map(P=>({source:`Perdant ${X} ${P.position}`,parentKey:P.key,parentIsWinner:!1})),le=(P,H,ee)=>{if(!P.parentKey)return;const xe=h.find(ie=>ie.key===P.parentKey);xe&&(P.parentIsWinner?(xe.next_key=H,xe.next_slot=ee):(xe.loser_key=H,xe.loser_slot=ee))},D=(P,H)=>{if(P.length<2)return;if(P.length===2){const ae=`cl-l${_}-${f}`;h.push({key:ae,stage:"classification",label:`Perdants ${X} · ${F(H)}`,position:f,pair_a_source:P[0].source,pair_b_source:P[1].source}),le(P[0],ae,"a"),le(P[1],ae,"b"),f++;return}const ee=P.length/2,xe=[],ie=[];for(let ae=0;ae<P.length;ae+=2){const be=P[ae],ve=P[ae+1];if(!be||!ve)continue;const ye=`cl-l${_}-${f}`,ue=`Perdants ${X} · tour de classement (${C(H,P.length)})`;h.push({key:ye,stage:"classification",label:ue,position:f,pair_a_source:be.source,pair_b_source:ve.source}),le(be,ye,"a"),le(ve,ye,"b"),xe.push({source:`Vainqueur match ${f}`,parentKey:ye,parentIsWinner:!0}),ie.push({source:`Perdant match ${f}`,parentKey:ye,parentIsWinner:!1}),f++}D(xe,H),D(ie,H+ee)};D(me,oe)}return h}function Fi({open:e,onClose:s,tournamentId:n,pairs:r,onSaved:o,hasExistingBracket:i}){const[d,c]=l.useState(1),[u,h]=l.useState(4),[y,m]=l.useState(4),[b,N]=l.useState(0),[G,T]=l.useState(0),[I,E]=l.useState([]),[$,B]=l.useState(null),[Y,q]=l.useState([]),[g,v]=l.useState(1),[C,F]=l.useState(0),[z,L]=l.useState("quarter"),[f,A]=l.useState(!0),[p,_]=l.useState([]),[W,X]=l.useState([]),[V,J]=l.useState(!1),de=l.useMemo(()=>[...r].sort((x,w)=>{const R=x.weight??Number.MAX_SAFE_INTEGER,M=w.weight??Number.MAX_SAFE_INTEGER;return R-M}),[r]);l.useEffect(()=>{_(x=>{const w=ut.indexOf(z),R=ut.slice(w,-1).filter(_e=>!(_e==="semi"&&f)).map(_e=>`losers-${_e}`),M=[];for(let _e=g+1;_e<=y;_e++)M.push(`pool-${_e}`);const te=[...M,...R],re=x.filter(_e=>te.includes(_e)),je=Array.from(new Set([...re,...te]));return je.length===x.length&&je.every((_e,Mt)=>_e===x[Mt])?x:je})},[y,g,z,f]);const se=l.useMemo(()=>{const x=new Set;return I.forEach(w=>w.assignments.forEach(R=>R&&x.add(R))),Y.forEach(w=>w&&x.add(w)),x},[I,Y]),oe=de.filter(x=>!se.has(x.id)),me=()=>{const w=($??Array.from({length:u},()=>({size:y,qualifiers:void 0}))).map((R,M)=>({name:zi[M]??String(M+1),size:R.size,qualifiers:R.qualifiers,assignments:Array.from({length:R.size},()=>null)}));E(w),q(Array.from({length:b},()=>null))},le=()=>{me(),c(2)},D=()=>{X(Fn({pools:I,topSeeds:b,byeSeeds:G,qualifiersPerPool:g,bestRunnersUp:C,startRound:z,thirdPlace:f,classifSources:p})),c(3)},P=()=>{const x=de.map(te=>te.id),w=x.slice(0,b),R=x.slice(b),M=qi(R,I.map(te=>te.size));E(te=>te.map((re,je)=>({...re,assignments:M[je]??re.assignments}))),q(w.concat(Array(Math.max(0,b-w.length)).fill(null))),O.success("Pré-remplissage serpentin appliqué")},H=()=>{E(x=>x.map(w=>({...w,assignments:w.assignments.map(()=>null)}))),q(x=>x.map(()=>null))},ee=(x,w,R)=>{E(M=>M.map((te,re)=>{if(re!==x)return te;const je=[...te.assignments];return je[w]=R,{...te,assignments:je}}))},xe=(x,w)=>{q(R=>{const M=[...R];return M[x]=w,M})},ie=()=>{const x=yr[z],w=W.filter(re=>re.stage===x);if(w.length<2)return O.error("Aucun tour de barrage à tirer au sort.");const R=w.flatMap(re=>[re.pair_a_source,re.pair_b_source]);for(let re=R.length-1;re>0;re--){const je=Math.floor(Math.random()*(re+1));[R[re],R[je]]=[R[je],R[re]]}let M=0;const te=new Map;
78w.forEach(re=>{te.set(re.key,{a:R[M++],b:R[M++]})}),X(re=>re.map(je=>{const _e=te.get(je.key);return _e?{...je,pair_a_source:_e.a,pair_b_source:_e.b}:je})),O.success("Tirage au sort effectué")},ae=()=>{X(Fn({pools:I,topSeeds:b,byeSeeds:G,qualifiersPerPool:g,bestRunnersUp:C,startRound:z,thirdPlace:f,classifSources:p})),O.success("Tableau final régénéré")},be=l.useMemo(()=>{const x=[];for(let w=1;w<=b;w++)x.push(`TS${w}`);if(I.forEach(w=>{for(let R=1;R<=w.size;R++){const M=mt[R-1]??`${R}e`;x.push(`${M} Poule ${w.name}`)}}),C>0){const w=g+1,R=mt[w-1]??`${w}e`;for(let M=1;M<=C;M++)x.push(C===1?`Meilleur ${R}`:`Meilleur ${R} n°${M}`)}return["r16","quarter","semi"].forEach(w=>{W.filter(M=>M.stage===w).forEach(M=>{x.push(`Vainqueur ${Xe[w]} ${M.position}`),x.push(`Perdant ${Xe[w]} ${M.position}`)})}),Array.from(new Set(x))},[b,I,W,C,g]),ve=(x,w,R)=>{X(M=>M.map(te=>te.key===x?{...te,[w==="a"?"pair_a_source":"pair_b_source"]:R}:te))},ye=async()=>{J(!0);try{const x={pools:I.map((M,te)=>({name:M.name,size:M.size,position:te,assignments:M.assignments.filter(re=>!!re)})),top_seeds:Y.filter(M=>!!M),matches:W},{data:w,error:R}=await Q.rpc("save_manual_bracket",{_tournament_id:n,_payload:x});if(R)return O.error(R.message);O.success(`Tableau créé : ${(w==null?void 0:w.matches)??0} matchs`),o(),s()}finally{J(!1)}},ue=$?$.reduce((x,w)=>x+w.size,0):u*y,$e=$?$.map(x=>`${x.size}`).join(" + "):`${u} à ${y}`,Ae=ue+b;return t.jsx(Ut,{open:e,onOpenChange:x=>!x&&s(),children:t.jsxs(Wt,{className:"max-w-5xl max-h-[92vh] overflow-y-auto",children:[t.jsx(Ht,{children:t.jsxs(Gt,{className:"flex items-center gap-2",children:[t.jsx(Xt,{className:"h-5 w-5"})," Construire le tableau â étape ",d,"/3"]})}),i&&t.jsxs("div",{className:"rounded-md border border-warning/40 bg-warning/10 text-warning-foreground text-xs p-3",children:["Un tableau existe déjà . Enregistrer ici ",t.jsx("b",{children:"l'écrase"})," (seulement possible si aucun score n'a été saisi)."]}),d===1&&t.jsxs("div",{className:"space-y-4",children:[t.jsxs("p",{className:"text-sm text-muted-foreground",children:["Choisissez la structure des poules. ",r.length," paires confirmées disponibles."]}),$&&t.jsxs("div",{className:"text-xs text-muted-foreground",children:["Structure sur-mesure active : poules de ",$.map(x=>x.size).join(", "),". Modifier les menus ci-dessous la désactive."]}),t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[t.jsxs("div",{children:[t.jsx(Se,{children:"Nombre de poules"}),t.jsxs(et,{value:String(u),onValueChange:x=>{B(null),h(Number(x))},children:[t.jsx(tt,{children:t.jsx(st,{})}),t.jsx(nt,{children:Array.from({length:13},(x,w)=>w).map(x=>t.jsx(Ne,{value:String(x),children:x===0?"Aucune poule":`${x} poule${x>1?"s":""}`},x))})]})]}),t.jsxs("div",{children:[t.jsx(Se,{children:"Taille de chaque poule"}),t.jsxs(et,{value:String(y),onValueChange:x=>{B(null),m(Number(x))},children:[t.jsx(tt,{children:t.jsx(st,{})}),t.jsx(nt,{children:[2,3,4,5,6].map(x=>t.jsxs(Ne,{value:String(x),children:[x," paires"]},x))})]})]}),t.jsxs("div",{children:[t.jsx(Se,{children:"Têtes de série (bypass)"}),t.jsxs(et,{value:String(b),onValueChange:x=>{const w=Number(x);N(w),G>w&&T(w)},children:[t.jsx(tt,{children:t.jsx(st,{})}),t.jsx(nt,{children:Array.from({length:17},(x,w)=>w).map(x=>t.jsx(Ne,{value:String(x),children:x===0?"Aucune TS":`${x} TS`},x))})]})]})]}),b>0&&z!=="final"&&t.jsxs("div",{children:[t.jsx(Se,{children:"Entrée des têtes de série"}),t.jsxs(et,{value:String(G),onValueChange:x=>T(Number(x)),children:[t.jsx(tt,{children:t.jsx(st,{})}),t.jsx(nt,{children:Array.from({length:b+1},(x,w)=>w).map(x=>{const w=ut[ut.indexOf(z)+1],R=w?Xe[w]:"";return x===0?t.jsxs(Ne,{value:"0",children:["Toutes en ",Xe[z]]},x):x===b?t.jsxs(Ne,{value:String(x),children:["Toutes en ",R," (bye)"]},x):t.jsxs(Ne,{value:String(x),children:["TS1â¦TS",x," en ",R," (bye) · TS",x+1,"â¦TS",b," en ",Xe[z]]},x)})})]}),t.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:['Les TS "bye" gagnent automatiquement leur match du 1',t.jsx("sup",{children:"er"})," tour et n'entrent réellement qu'au tour suivant."]})]}),t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[t.jsxs("div",{children:[t.jsx(Se,{children:"Qualifiés par poule (phases finales)"}),t.jsxs(et,{value:String(g),onValueChange:x=>v(Number(x)),children:[t.jsx(tt,{children:t.jsx(st,{})}),t.jsxs(nt,{children:[t.jsx(Ne,{value:"1",children:"Le 1er de chaque poule"}),t.jsx(Ne,{value:"2",children:"Les 2 premiers de chaque poule"}),t.jsx(Ne,{value:"3",children:"Les 3 premiers de chaque poule"})]})]})]}),t.jsxs("div",{children:[t.jsx(Se,{children:"Début des phases finales"}),t.jsxs(et,{value:z,onValueChange:x=>L(x),children:[t.jsx(tt,{children:t.jsx(st,{})}),t.jsxs(nt,{children:[t.jsx(Ne,{value:"r16",children:"1/8 de finale (16 paires)"}),t.jsx(Ne,{value:"quarter",children:"1/4 de finale (8 paires)"}),t.jsx(Ne,{value:"semi",children:"1/2 finales (4 paires)"}),t.jsx(Ne,{value:"final",children:"Finale seule (2 paires)"})]})]})]})]}),t.jsxs("div",{children:[t.jsxs(Se,{children:["Places supplémentaires (meilleurs ",mt[g]??`${g+1}e`,")"]}),t.jsxs(et,{value:String(C),onValueChange:x=>F(Number(x)),children:[t.jsx(tt,{children:t.jsx(st,{})}),t.jsxs(nt,{children:[t.jsx(Ne,{value:"0",children:"Aucune"}),Array.from({length:Math.max(1,u)},(x,w)=>w+1).map(x=>t.jsx(Ne,{value:String(x),children:x===1?`+ Le meilleur ${mt[g]??`${g+1}e`}`:`+ Les ${x} meilleurs ${mt[g]??`${g+1}e`}`},x))]})]}),t.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Ajoute ",C||0," paire(s) supplémentaire(s) au tableau final (à départager manuellement par le JA)."]})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(Se,{children:"Matchs de classement (facultatifs)"}),t.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 rounded-md border p-3 bg-muted/20",children:(()=>{const x=[];for(let M=g+1;M<=y;M++){const te=mt[M-1]??`${M}e`;x.push({key:`pool-${M}`,label:`${te} de chaque poule (perdants)`})}const w=ut.indexOf(z),R=ut.slice(w,-1);for(const M of R)M==="semi"&&f||x.push({key:`losers-${M}`,label:`Perdants ${Xe[M]}`});return x.length===0?t.jsx("div",{className:"text-xs text-muted-foreground",children:"Aucune source disponible pour cette structure."}):x.map(M=>t.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[t.jsx("input",{type:"checkbox",checked:p.includes(M.key),onChange:te=>{_(re=>te.target.checked?[...re,M.key]:re.filter(je=>je!==M.key))}}),M.label]},M.key))})()}),t.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[t.jsx("input",{type:"checkbox",id:"thirdPlace",checked:f,onChange:x=>A(x.target.checked)}),t.jsx("label",{htmlFor:"thirdPlace",children:"Match pour la 3e place (perdants des 1/2)"})]})]}),t.jsxs(ce,{className:"p-3 bg-muted/30 text-sm",children:[t.jsxs("div",{children:["Capacité totale : ",t.jsxs("b",{children:[Ae," paires"]})," (",$e," + ",b," TS)"]}),Ae!==r.length&&t.jsx("div",{className:`mt-1 text-xs ${Ae<r.length?"text-destructive":"text-warning-foreground"}`,children:Ae<r.length?`â ï¸ ${r.length-Ae} paire(s) confirmées ne rentreront pas dans la structure.`:`${Ae-r.length} slot(s) vides seront laissés (bye).`})]}),t.jsxs(wt,{children:[t.jsx(K,{variant:"outline",onClick:s,children:"Annuler"}
78),t.jsxs(K,{onClick:le,disabled:u===0&&b===0,children:["Suivant ",t.jsx(hn,{className:"h-4 w-4 ml-1"})]})]})]}),d===2&&t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsxs(K,{variant:"outline",size:"sm",onClick:P,children:[t.jsx(Ps,{className:"h-4 w-4 mr-1"})," Pré-remplir en serpentin"]}),t.jsxs(K,{variant:"outline",size:"sm",onClick:H,children:[t.jsx(ms,{className:"h-4 w-4 mr-1"})," Vider tout"]}),t.jsxs("div",{className:"text-xs text-muted-foreground self-center ml-auto",children:[oe.length," paire(s) non placée(s)"]})]}),b>0&&t.jsxs(ce,{className:"p-3",children:[t.jsx("div",{className:"font-semibold text-sm mb-2",children:"ð Têtes de série"}),t.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:Y.map((x,w)=>t.jsx(Bn,{label:`TS${w+1}`,value:x,onChange:R=>xe(w,R),allPairs:r,available:oe},`ts-${w}`))})]}),t.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:I.map((x,w)=>t.jsxs(ce,{className:"p-3",children:[t.jsxs("div",{className:"font-semibold text-sm mb-2",children:["Poule ",x.name]}),t.jsx("div",{className:"space-y-2",children:x.assignments.map((R,M)=>t.jsx(Bn,{label:`${M+1}.`,value:R,onChange:te=>ee(w,M,te),allPairs:r,available:oe},`p${w}-s${M}`))})]},w))}),t.jsxs(wt,{children:[t.jsxs(K,{variant:"outline",onClick:()=>c(1),children:[t.jsx(yn,{className:"h-4 w-4 mr-1"})," Retour"]}),t.jsxs(K,{onClick:D,children:["Suivant ",t.jsx(hn,{className:"h-4 w-4 ml-1"})]})]})]}),d===3&&t.jsxs("div",{className:"space-y-4",children:[t.jsxs(ce,{className:"p-3 space-y-3",children:[t.jsxs("div",{className:"text-xs text-muted-foreground",children:["Le format (",Xe[z]," · ",g," qualifié",g>1?"s":"","/poule) a été choisi à l'étape 1. Vous pouvez encore ajuster ci-dessous."]}),t.jsx("div",{className:"text-xs text-muted-foreground",children:"Options des matchs de classement et 3e place définies à l'étape 1. Retournez à l'étape 1 pour modifier."}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsxs(K,{variant:"outline",size:"sm",onClick:ae,children:[t.jsx(Ps,{className:"h-4 w-4 mr-1"})," Regénérer le tableau"]}),t.jsxs(K,{variant:"outline",size:"sm",onClick:ie,children:[t.jsx(Ps,{className:"h-4 w-4 mr-1"})," Tirage au sort des barrages"]})]})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx("div",{className:"text-xs text-muted-foreground",children:"Chaque match ci-dessous est éditable : modifiez les sources (paires ou qualifiés) via les menus."}),["r16","quarter","semi","final","third_place","classification"].filter(x=>W.some(w=>w.stage===x)).map(x=>t.jsxs(ce,{className:"p-3",children:[t.jsx("div",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:t.jsx(Br,{variant:"outline",children:Bi(x)})}),t.jsx("div",{className:"space-y-2",children:W.filter(w=>w.stage===x).map(w=>t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[120px_1fr_auto_1fr] gap-2 items-center text-sm",children:[t.jsx("div",{className:"font-mono text-xs text-muted-foreground",children:w.label}),t.jsxs(et,{value:w.pair_a_source,onValueChange:R=>ve(w.key,"a",R),children:[t.jsx(tt,{className:"h-8",children:t.jsx(st,{placeholder:"Source A"})}),t.jsx(nt,{children:be.map(R=>t.jsx(Ne,{value:R,children:R},R))})]}),t.jsx("span",{className:"text-center text-muted-foreground",children:"vs"}),t.jsxs(et,{value:w.pair_b_source,onValueChange:R=>ve(w.key,"b",R),children:[t.jsx(tt,{className:"h-8",children:t.jsx(st,{placeholder:"Source B"})}),t.jsx(nt,{children:be.map(R=>t.jsx(Ne,{value:R,children:R},R))})]})]},w.key))})]},x))]}),t.jsxs(wt,{children:[t.jsxs(K,{variant:"outline",onClick:()=>c(2),children:[t.jsx(yn,{className:"h-4 w-4 mr-1"})," Retour"]}),t.jsxs(K,{onClick:ye,disabled:V,className:"bg-court",children:[V?t.jsx(Ie,{className:"h-4 w-4 mr-1 animate-spin"}):null,"Enregistrer le tableau"]})]})]})]})})}const Bi=e=>({r16:"1/8 de finale",quarter:"1/4 de finale",semi:"1/2 finales",final:"Finale",third_place:"3e place",classification:"Classement"})[e]??e;function Bn({label:e,value:s,onChange:n,allPairs:r,available:o}){const i=s?r.find(c=>c.id===s):null,d=i?[i,...o.filter(c=>c.id!==i.id)]:o;return t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-xs font-mono w-6 shrink-0",children:e}),t.jsxs(et,{value:s??"__none__",onValueChange:c=>n(c==="__none__"?null:c),children:[t.jsx(tt,{className:"h-8 text-xs",children:t.jsx(st,{placeholder:"â vide â"})}),t.jsxs(nt,{children:[t.jsx(Ne,{value:"__none__",children:"â vide â"}),d.map(c=>t.jsxs(Ne,{value:c.id,children:[c.label,c.weight!=null?` · ${c.weight}`:""]},c.id))]})]})]})}const dt=e=>e?`${(e.player_last_name??"").toUpperCase()} / ${(e.partner_last_name??"").toUpperCase()}`:"â",Vi=["r16","quarter","semi","final","third_place","classification"],Ui={r16:"1/8 de finale",quarter:"1/4 de finale",semi:"1/2 finales",final:"Finale",third_place:"3e place",classification:"Classement"},Wi={1:"lg:grid-cols-1",2:"lg:grid-cols-2",3:"lg:grid-cols-3",4:"lg:grid-cols-4"},go=()=>{const{id:e}=Er(),{isReferee:s,user:n}=Dr(),[r,o]=l.useState(null),[i,d]=l.useState(0),[c,u]=l.useState([]),[h,y]=l.useState([]),[m,b]=l.useState([]),[N,G]=l.useState({}),[T,I]=l.useState(null),[E,$]=l.useState(new Set),[B,Y]=l.useState(!0),[q,g]=l.useState(!1),[v,C]=l.useState(!1),[F,z]=l.useState(!1),[L,f]=l.useState(null),[A,p]=l.useState(!1),[_,W]=l.useState(!1),[X,V]=l.useState(""),[J,de]=l.useState(""),[se,oe]=l.useState(""),[me,le]=l.useState(""),[D,P]=l.useState(""),[H,ee]=l.useState("single9"),[xe,ie]=l.useState([{a:"",b:""},{a:"",b:""},{a:"",b:""}]),[ae,be]=l.useState(!1),[ve,ye]=l.useState(""),[ue,$e]=l.useState(!1),[Ae,x]=l.useState(!1),[w,R]=l.useState([]),[M,te]=l.useState(""),[re,je]=l.useState(!1),[_e,Mt]=l.useState(!1),[Je,at]=l.useState([]),[ht,At]=l.useState(!1),[it,gt]=l.useState(!1);l.useRef(!1);const Pt=l.useRef(!1),[qe,ft]=l.useState(null),[Lt,Ot]=l.useState(""),[bt,It]=l.useState(!1),Qe=async()=>
78{if(!e)return;Y(!0);const[{data:a},{data:j},{data:S},{data:k},{data:U}]=await Promise.all([Q.from("tournaments").select("id,title,category,gender,tournament_date,start_time,end_time,referee_id,referee_name,created_by,max_pairs,num_courts,price_cents,description,status,created_at,updated_at,twitch_channel_court1,twitch_channel_court2,payment_enabled,onsite_payment_allowed,podium_photo_path,live_started_at,closed_at,recaps_sent_at").eq("id",e).maybeSingle(),Q.from("registrations").select("id,player_first_name,player_last_name,partner_first_name,partner_last_name,player_ranking,partner_ranking,player_license,partner_license,status,forfeit").eq("tournament_id",e),Q.from("pools").select("*").eq("tournament_id",e).order("position"),Q.from("pool_assignments").select("*").eq("tournament_id",e).order("seed_global"),Q.from("matches").select("*").eq("tournament_id",e).order("position")]),Z={};(j??[]).forEach(he=>{Z[he.id]=he}),o(a),G(Z),d((j??[]).filter(he=>he.status==="confirmed").length),u(S??[]),y(k??[]),b(U??[]),Y(!1);const pe=(a==null?void 0:a.gender)==="hommes"?"H":(a==null?void 0:a.gender)==="femmes"?"F":null;Q.rpc("fft_player_count",{_gender:pe}).then(({data:he})=>{I(typeof he=="number"?he:null)});const fe=Array.from(new Set((j??[]).flatMap(he=>[he.player_license,he.partner_license]).filter(Boolean)));fe.length?Q.rpc("approximate_licenses",{_licenses:fe}).then(({data:he})=>{$(new Set((he??[]).map(Be=>String(Be.fft_license))))}):$(new Set)};l.useEffect(()=>{Qe()},[e]);const Es=async(a,j)=>{const S=j.trim()||null;u(U=>U.map(Z=>Z.id===a?{...Z,court:S}:Z));const{error:k}=await Q.from("pools").update({court:S}).eq("id",a);k&&O.error("Terrain non enregistré")},Re=async(a,j)=>{const S=j.trim()||null;b(U=>U.map(Z=>Z.id===a?{...Z,court:S}:Z));const{error:k}=await Q.from("matches").update({court:S}).eq("id",a);k&&O.error("Terrain non enregistré")},Pe=async a=>{const j=a.status==="in_progress"?"ready":"in_progress";b(k=>k.map(U=>U.id===a.id?{...U,status:j}:U));const{error:S}=await Q.from("matches").update({status:j}).eq("id",a.id);S&&(O.error("Statut non enregistré"),b(k=>k.map(U=>U.id===a.id?{...U,status:a.status}:U)))},Me=async()=>{if(!qe)return;const a=Lt.trim(),j=a===""?null:parseInt(a.replace(/[^\d]/g,""),10);if(a!==""&&(!Number.isFinite(j)||j<=0))return O.error("Classement invalide : saisis un numéro de rang (ex. 850).");It(!0);const S=qe.field==="player"?"player_ranking":"partner_ranking",k=j==null?null:String(j),{error:U}=await Q.from("registrations").update({[S]:k}).eq("id",qe.regId);if(U)return It(!1),O.error(U.message);G(Z=>({...Z,[qe.regId]:{...Z[qe.regId],[S]:k}})),qe.license&&($(Z=>{const pe=new Set(Z);return pe.delete(String(qe.license)),pe}),k!=null&&await Q.rpc("referee_set_profile_ranking",{_license:String(qe.license),_ranking:k})),It(!1),ft(null),O.success("Classement mis à jour")},Ve=async()=>{if(!e)return;const{data:a}=await Q.from("matches").select("*").eq("tournament_id",e).order("position");a&&b(a)},Ee=(r==null?void 0:r.referee_id)??(r==null?void 0:r.created_by)??(n==null?void 0:n.id)??null,Le=async()=>{if(!Ee)return;const{data:a}=await Q.from("bracket_prompt_templates").select("id,name,prompt").eq("user_id",Ee).order("created_at",{ascending:!0});R(a??[])};l.useEffect(()=>{Le()},[Ee]);const Ke=a=>{te(a);const j=w.find(S=>S.id===a);j&&ye(j.prompt)},xt=async()=>{var S;if(!Ee)return;const a=ve.trim();if(!a){O.error("Ãcrivez d'abord un prompt à enregistrer.");return}const j=(S=window.prompt("Nom du modèle :",""))==null?void 0:S.trim();if(j){je(!0);try{const{data:k,error:U}=await Q.from("bracket_prompt_templates").insert({user_id:Ee,name:j,prompt:a}).select("id,name,prompt").single();if(U){O.error(U.message);return}R(Z=>[...Z,k]),te(k.id),O.success("Modèle enregistré â")}finally{je(!1)}}},Ce=async a=>{var U;const j=w.find(Z=>Z.id===a);if(!j)return;const S=(U=window.prompt("Renommer le modèle :",j.name))==null?void 0:U.trim();if(!S||S===j.name)return;const{error:k}=await Q.from("bracket_prompt_templates").update({name:S}).eq("id",a);if(k){O.error(k.message);return}R(Z=>Z.map(pe=>pe.id===a?{...pe,name:S}:pe)),O.success("Modèle renommé â")},ot=async a=>{const j=w.find(k=>k.id===a);if(!j||!confirm(`Supprimer le modèle « ${j.name} » ?`))return;const{error:S}=await Q.from("bracket_prompt_templates").delete().eq("id",a);if(S){O.error(S.message);return}R(k=>k.filter(U=>U.id!==a)),M===a&&te(""),O.success("Modèle supprimé â")};if(!s)return t.jsx("div",{className:"container py-20 text-center text-muted-foreground",children:"Réservé aux juges-arbitres."});if(B)return t.jsx("div",{className:"container py-20 text-center text-muted-foreground",children:"Chargementâ¦"});const Oe=async(a=!1,j=!1)=>{var U;if(Pt.current||ue||Ae)return;const S=!a&&m.length>0,k=ve.trim();if(!(!k&&S)){Pt.current=!0,$e(!0);try{const{data:Z,error:pe}=await Q.functions.invoke("generate-bracket-ai",{body:{tournament_id:e,prompt:ve,refine:S,history:S?Je:[],preserveScores:j}});if(pe){const he=pe.context;let Be=pe.message;try{const Ze=await((U=he==null?void 0:he.json)==null?void 0:U.call(he));Ze!=null&&Ze.error&&(Be=Ze.error)}catch{}O.error(Be);return}if(Z!=null&&Z.error)return O.error(Z.error);const fe=(Z==null?void 0:Z.summary)??"Tableau mis à jour â¨";O.success(fe),at(he=>S?[...he,{role:"user",content:k||"Génère un format équilibré et classique."},{role:"assistant",content:fe}]:[{role:"assistant",content:fe}]),ye(""),te(""),Qe()}catch(Z){O.error((Z==null?void 0:Z.message)??"Erreur lors de la génération")}finally{Pt.current=!1,$e(!1)}}},Ue=a=>{var k,U,Z,pe;f(a);const j=a.match_format==="two_sets";ee(j?"two_sets":"single9"),V(((k=a.games_a)==null?void 0:k.toString())??""),de(((U=a.games_b)==null?void 0:U.toString())??""),oe(((Z=a.tiebreak_a)==null?void 0:Z.toString())??""),le(((pe=a.tiebreak_b)==null?void 0:pe.toString())??""),P(a.court??"");
78const S=Lr(a.sets);ie([0,1,2].map(fe=>({a:S[fe]?String(S[fe][0]):"",b:S[fe]?String(S[fe][1]):""})))},jt=async()=>{if(!(!L||A)){p(!0);try{let a;if(H==="two_sets"){const S=xe.filter(k=>k.a!==""&&k.b!=="").map(k=>[parseInt(k.a),parseInt(k.b)]);if(S.length<2){O.error("Renseignez au moins 2 sets.");return}({error:a}=await Q.rpc("record_match_result_sets",{_match_id:L.id,_sets:S}))}else({error:a}=await Q.rpc("record_match_result",{_match_id:L.id,_games_a:parseInt(X),_games_b:parseInt(J),_tb_a:se?parseInt(se):null,_tb_b:me?parseInt(me):null}));if(a){O.error(a.message);return}const j=D.trim()||null;j!==(L.court??null)&&await Q.from("matches").update({court:j}).eq("id",L.id),f(null),O.success("Score enregistré â"),await Ve()}finally{p(!1)}}},yt=async()=>{if(!(!L||_)&&confirm("Effacer le score de ce match ? Le match repassera à « à jouer ».")){W(!0);try{const{error:a}=await Q.rpc("clear_match_result",{_match_id:L.id});if(a){O.error(a.message);return}f(null),O.success("Score effacé â"),await Ve()}finally{W(!1)}}},lt=a=>m.filter(j=>j.stage===a).sort((j,S)=>j.position-S.position),_t=a=>m.filter(j=>j.pool_id===a).sort((j,S)=>j.position-S.position),We=a=>{const j=parseInt((a||"").replace(/[^\d]/g,""),10);return Number.isFinite(j)&&j>0?j:null},zt=a=>{const j=We(a.player_ranking)??T,S=We(a.partner_ranking)??T;return j!=null&&S!=null?j+S:null},St=Object.values(N).filter(a=>a.status==="confirmed"),as=St.slice().sort((a,j)=>{const S=zt(a),k=zt(j);return S==null&&k==null?0:S==null?1:k==null?-1:S-k}),Ds=as.map(zt).filter(a=>a!=null),an=Ds.length?Math.round(Ds.reduce((a,j)=>a+j,0)/Ds.length):null,_r=St.filter(a=>We(a.player_ranking)==null||We(a.partner_ranking)==null).length,wr=async()=>{var a;if(r){if(!St.length)return O.error("Aucune paire confirmée à exporter.");g(!0);try{const{data:j}=await Q.from("registrations").select("id,player_first_name,player_last_name,player_license,player_email,player_phone,player_ranking,partner_first_name,partner_last_name,partner_license,partner_email,partner_phone,partner_ranking,status").eq("tournament_id",e).eq("status","confirmed"),S=j??[];if(!S.length)return O.error("Aucune paire confirmée à exporter.");const k=Array.from(new Set(S.flatMap(ne=>[ne.player_license,ne.partner_license]).filter(Boolean).map(ne=>ne.trim()))),U={};if(k.length){const[{data:ne},{data:ct}]=await Promise.all([Q.from("fft_rankings").select("license, club").in("license",k),Q.from("players_cache").select("license, club, birth_year").in("license",k)]);for(const Te of ne??[]){const He=(Te.license||"").trim();He&&(U[He]={club:Te.club})}for(const Te of ct??[]){const He=(Te.license||"").trim();He&&(U[He]={club:Te.club??((a=U[He])==null?void 0:a.club)??null,birth:Te.birth_year?String(Te.birth_year):null})}}const Z=ne=>!!ne&&E.has(String(ne).trim()),pe=(ne,ct)=>({value:We(ne),approx:Z(ct)}),fe=ne=>{const ct=We(ne.player_ranking)??T,Te=We(ne.partner_ranking)??T;return ct!=null&&Te!=null?ct+Te:null},he=S.slice().sort((ne,ct)=>{const Te=fe(ne),He=fe(ct);return Te==null&&He==null?0:Te==null?1:He==null?-1:Te-He}),Be=ne=>ne.value==null?"":ne.approx?`${ne.value} (estimé)`:ne.value,Ze=["Nom de l'épreuve","Catégorie de l'épreuve","Position de la paire","Nom joueur 1","Prénom joueur 1","Date de naissance joueur 1","Licence joueur 1","Club joueur 1","Classement joueur 1","Mail joueur 1","Téléphone joueur 1","Nom joueur 2","Prénom joueur 2","Date de naissance joueur 2","Licence joueur 2","Club joueur 2","Classement joueur 2","Mail joueur 2","Téléphone joueur 2","Poids paire","Classement à vérifier"],kr=he.map((ne,ct)=>{const Te=U[(ne.player_license||"").trim()]??{},He=U[(ne.partner_license||"").trim()]??{},mn=pe(ne.player_ranking,ne.player_license),pn=pe(ne.partner_ranking,ne.partner_license),Rr=[mn.approx?"Joueur 1":null,pn.approx?"Joueur 2":null].filter(Boolean).join(", ");return[r.title,r.category,ct+1,(ne.player_last_name||"").toUpperCase(),ne.player_first_name||"",Te.birth??"",ne.player_license||"",Te.club??"",Be(mn),ne.player_email||"",ne.player_phone||"",(ne.partner_last_name||"").toUpperCase(),ne.partner_first_name||"",He.birth??"",ne.partner_license||"",He.club??"",Be(pn),ne.partner_email||"",ne.partner_phone||"",fe(ne)??"",Rr]}
78),os=await Mr(()=>import("./xlsx-B6sNpj_1.js"),[]),un=os.utils.aoa_to_sheet([Ze,...kr]);un["!cols"]=Ze.map(ne=>({wch:Math.max(12,ne.length)}));const fn=os.utils.book_new();os.utils.book_append_sheet(fn,un,"Paires"),os.writeFile(fn,`Paires_${(r.title||"tournoi").replace(/\s+/g,"_")}.xlsx`)}catch(j){O.error((j==null?void 0:j.message)??"Export impossible")}finally{g(!1)}}},Ts=a=>{const j=h.filter(k=>k.pool_id===a),S=m.filter(k=>k.pool_id===a);return j.map(k=>{let U=0,Z=0,pe=0;return S.forEach(fe=>{fe.status==="completed"&&(fe.pair_a_id===k.registration_id?(pe++,Z+=(fe.games_a??0)-(fe.games_b??0),fe.winner_id===k.registration_id&&U++):fe.pair_b_id===k.registration_id&&(pe++,Z+=(fe.games_b??0)-(fe.games_a??0),fe.winner_id===k.registration_id&&U++))}),{...k,wins:U,gd:Z,played:pe}}).sort((k,U)=>U.wins-k.wins||U.gd-k.gd)},on=({m:a})=>{const j=a.pair_a_id?N[a.pair_a_id]:void 0,S=a.pair_b_id?N[a.pair_b_id]:void 0,k=a.status==="completed",U=k&&a.winner_id===a.pair_a_id,Z=k&&a.winner_id===a.pair_b_id,pe=a.pair_a_id&&a.pair_b_id,fe=Us(a),he=a.status==="in_progress";return t.jsxs("div",{className:`rounded-lg border bg-card p-3 text-sm ${he?"border-red-500/60 ring-1 ring-red-500/30":""}`,children:[t.jsxs("div",{className:"text-xs text-muted-foreground mb-2 flex items-center justify-between gap-2",children:[t.jsx("span",{children:Bs(a.label)}),k?t.jsx("span",{className:"text-success font-semibold",children:"Terminé"}):he?t.jsxs("span",{className:"inline-flex items-center gap-1 text-red-500 font-bold uppercase tracking-wider text-[10px]",children:[t.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-red-500 animate-pulse"})," En cours"]}):null]}),t.jsxs("div",{className:`flex items-center justify-between py-1 ${U?"font-bold":""}`,children:[t.jsx("span",{className:"truncate flex-1",children:j?dt(j):t.jsx("span",{className:"italic text-muted-foreground",children:a.pair_a_source??"â"})}),k&&(fe?t.jsx("span",{className:"ml-2 tabular-nums flex gap-1.5",children:us(a,"a").map((Be,Ze)=>t.jsx("span",{children:Be},Ze))}):t.jsxs("span",{className:"ml-2 tabular-nums",children:[a.games_a,a.tiebreak_a!==null&&t.jsx("sup",{className:"text-xs",children:a.tiebreak_a})]}))]}),t.jsxs("div",{className:`flex items-center justify-between py-1 ${Z?"font-bold":""}`,children:[t.jsx("span",{className:"truncate flex-1",children:S?dt(S):t.jsx("span",{className:"italic text-muted-foreground",children:a.pair_b_source??"â"})}),k&&(fe?t.jsx("span",{className:"ml-2 tabular-nums flex gap-1.5",children:us(a,"b").map((Be,Ze)=>t.jsx("span",{children:Be},Ze))}):t.jsxs("span",{className:"ml-2 tabular-nums",children:[a.games_b,a.tiebreak_b!==null&&t.jsx("sup",{className:"text-xs",children:a.tiebreak_b})]}))]}),pe&&t.jsxs("div",{className:"mt-2 flex gap-2",children:[!k&&t.jsx(K,{size:"sm",variant:he?"destructive":"secondary",className:"h-7 text-xs flex-1",onClick:()=>Pe(a),children:he?"Arrêter":"Match en cours"}),t.jsx(K,{size:"sm",variant:k?"outline":"default",className:"h-7 text-xs flex-1",onClick:()=>Ue(a),children:k?"Modifier le score":"Saisir le score"})]}),t.jsxs("div",{className:"mt-2 pt-2 border-t border-border/60",children:[t.jsx(Se,{htmlFor:`mcourt-${a.id}`,className:"text-[11px] text-muted-foreground",children:"Terrain (facultatif · affiché sur l'écran TV)"}),t.jsx(Ge,{id:`mcourt-${a.id}`,defaultValue:a.court??"",placeholder:"ex. Piste 3",className:"h-8 mt-1",onBlur:Be=>{(Be.target.value.trim()||null)!==(a.court??null)&&Re(a.id,Be.target.value)}})]})]})},ln=async a=>{if(!e)return;C(!0);const{error:j}=await Q.from("tournaments").update({live_started_at:a?new Date().toISOString():null}).eq("id",e);if(C(!1),j)return O.error(j.message);O.success(a?"Tournoi lancé : la liste est dévoilée au public ð¾":"Tournoi masqué : la liste n'est plus visible"),Qe()},cn=()=>{const a=(r==null?void 0:r.tournament_date)<=new Date().toISOString().slice(0,10);if(r!=null&&r.live_started_at){confirm("Masquer le live ? La liste des participants, têtes de série et poids de paire sera de nouveau masquée du public.")&&ln(!1);return}if(!a){O.error("Vous ne pouvez pas lancer un tournoi avant le jour du tournoi.");return}confirm("Lancer le tournoi ? La liste des participants, têtes de série et poids de paire seront dévoilés au public en temps réel.")&&ln(!0)},Nr=()=>{confirm(`Clôturer le tournoi ? Le classement final des ${i} paires sera figé et les points FFT attribués. La clôture reste réversible.`)&&(C(!0),Q.rpc("close_tournament",{p_tournament_id:e}).then(({error:a})=>{if(C(!1),a)return O.error(a.message);O.success("Tournoi clôturé : classement et points figés ð"),Qe()}))},Sr=()=>{confirm("Rouvrir le tournoi ? Il repassera en mode live pour corriger des résultats.")&&(C(!0),Q.rpc("reopen_tournament",{p_tournament_id:e}).then(({error:a})=>{if(C(!1),a)return O.error(a.message);O.success("Tournoi rouvert"),Qe()}))},Cr=async()=>{const a=!!(r!=null&&r.recaps_sent_at);if(!confirm(a?"Renvoyer les récaps aux joueurs ?":`Envoyer les récaps aux ${i} paires ? Chaque joueur recevra son bilan (classement, points, podium, parcours) par e-mail et notification.`))return;z(!0);const{data:j,error:S}=await Q.functions.invoke("send-tournament-recaps",{body:{tournament_id:e,force:a}});if(z(!1),S)return O.error(S.message);if(j!=null&&j.error)return O.error(j.error);O.success(`Récaps envoyés : ${(j==null?void 0:j.emails_sent)??0} e-mails, ${(j==null?void 0:j.in_app_sent)??0} notifications ð¾`),Qe()},Fe=m.length>0,is=Vi.filter(a=>a!=="classification"&&m.some(j=>j.stage===a)),dn=m.filter(a=>a.stage==="classification"),qt=new Set;m.forEach(a=>{a.stage==="classification"||a.pool_id||(a.pair_a_id&&qt.add(a.pair_a_id),a.pair_b_id&&qt.add(a.pair_b_id))}
78),c.forEach(a=>{const j=m.filter(U=>U.pool_id===a.id);if(!(j.length>0&&j.every(U=>U.status==="completed")))return;const k=Ts(a.id);k[0]&&qt.add(k[0].registration_id)});const $s=new Set;m.forEach(a=>{a.stage==="classification"||a.pool_id||a.status!=="completed"||!a.winner_id||(a.pair_a_id&&a.pair_a_id!==a.winner_id&&$s.add(a.pair_a_id),a.pair_b_id&&a.pair_b_id!==a.winner_id&&$s.add(a.pair_b_id))});const Ms=new Set(qt);return c.forEach(a=>{Ts(a.id).forEach(j=>Ms.add(j.registration_id))}),h.forEach(a=>{a.is_top_seed&&Ms.add(a.registration_id)}),t.jsxs("div",{className:"container py-8",children:[t.jsxs(Tr,{to:`/ja/tournoi/${e}`,className:"inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground mb-4",children:[t.jsx(Vr,{className:"h-4 w-4"})," Retour au tournoi"]}),t.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3 mb-6",children:[t.jsxs("div",{children:[t.jsxs("h1",{className:"font-display text-3xl",children:["Tableau â ",r==null?void 0:r.title]}),(r==null?void 0:r.tournament_date)&&t.jsx("p",{className:"text-muted-foreground capitalize",children:new Date(r.tournament_date).toLocaleDateString("fr-FR",{weekday:"long",day:"numeric",month:"long",year:"numeric"})}),(r==null?void 0:r.referee_name)&&t.jsxs("p",{className:"text-sm text-muted-foreground",children:["JA : ",r.referee_name]}),t.jsxs("p",{className:"text-muted-foreground",children:[i," paires confirmées"]})]}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsxs(K,{variant:"outline",onClick:wr,disabled:q,children:[q?t.jsx(Ie,{className:"h-4 w-4 mr-2 animate-spin"}):t.jsx(Ur,{className:"h-4 w-4 mr-2"}),"Exporter les paires"]}),t.jsxs(K,{onClick:()=>At(!0),className:"bg-court",disabled:Ae||ue,children:[t.jsx(gn,{className:"h-4 w-4 mr-2"}),Fe?"Régénérer le tableau":"Générer le tableau"]}),s&&Fe&&!["completed","cancelled"].includes(r==null?void 0:r.status)&&(r!=null&&r.closed_at?t.jsxs(t.Fragment,{children:[t.jsxs(K,{className:"bg-court",onClick:Cr,disabled:F,children:[F?t.jsx(Ie,{className:"h-4 w-4 mr-2 animate-spin"}):t.jsx(fs,{className:"h-4 w-4 mr-2"}),r!=null&&r.recaps_sent_at?"Renvoyer les récaps":"Envoyer les récaps"]}),t.jsxs(K,{variant:"outline",onClick:Sr,disabled:v,children:[t.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Rouvrir le tournoi"]})]}):r!=null&&r.live_started_at?t.jsxs(t.Fragment,{children:[t.jsxs(K,{className:"bg-court",onClick:Nr,disabled:v,children:[t.jsx($r,{className:"h-4 w-4 mr-2"}),"Clôturer le tournoi"]}),t.jsxs(K,{variant:"outline",onClick:cn,disabled:v,children:[t.jsx(xn,{className:"h-4 w-4 mr-2 text-red-500"}),"Masquer le live"]})]}):t.jsxs(K,{className:"bg-red-500 hover:bg-red-600 text-white",onClick:cn,disabled:v,children:[t.jsx(xn,{className:"h-4 w-4 mr-2"}),"Lancer le tournoi"]}))]})]}),ht&&t.jsx(Fi,{open:ht,onClose:()=>At(!1),tournamentId:e,hasExistingBracket:Fe,pairs:as.map(a=>({id:a.id,label:dt(a),weight:zt(a)})),onSaved:Qe}),t.jsxs(Ar,{defaultValue:Fe?"bracket":"seeding",children:[t.jsxs(Pr,{className:"flex h-auto w-full flex-wrap justify-start gap-1",children:[t.jsxs(Ft,{value:"seeding",className:"gap-1.5",children:[t.jsx(Hr,{className:"h-3.5 w-3.5"})," Analyse des paires",i?` (${i})`:""]}),t.jsxs(Ft,{value:"bracket",className:"gap-1.5",children:[t.jsx(Vs,{className:"h-3.5 w-3.5"})," Tableau & scores"]}),t.jsxs(Ft,{value:"results",className:"gap-1.5",children:[t.jsx(kt,{className:"h-3.5 w-3.5"})," Résultats"]}),t.jsxs(Ft,{value:"photos",className:"gap-1.5",children:[t.jsx(Ws,{className:"h-3.5 w-3.5"})," Photos"]}),t.jsxs(Ft,{value:"convocations",className:"gap-1.5",children:[t.jsx(fs,{className:"h-3.5 w-3.5"})," Convocations"]})]}),t.jsx(Bt,{value:"seeding",className:"mt-4 space-y-4",children:St.length===0?t.jsx(ce,{className:"p-8 text-center text-muted-foreground",children:"Aucune paire confirmée pour l'instant."}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[t.jsxs(ce,{className:"p-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Paires confirmées"}),t.jsx("div",{className:"font-display text-2xl tabular-nums",children:St.length})]}),t.jsxs(ce,{className:"p-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Tête de série n°1"}),t.jsx("div",{className:"font-medium text-sm truncate mt-1",children:dt(as[0])})]}),t.jsxs(ce,{className:"p-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Poids moyen"}),t.jsx("div",{className:"font-display text-2xl tabular-nums",children:an!=null?an.toLocaleStr
78ing("fr-FR"):"â"})]}),t.jsxs(ce,{className:"p-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Paires NC"}),t.jsx("div",{className:"font-display text-2xl tabular-nums",children:_r})]})]}),t.jsx(ce,{className:"p-4 bg-muted/30",children:t.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[t.jsx(Gr,{className:"h-4 w-4 text-court mt-0.5 shrink-0"}),t.jsxs("p",{className:"text-muted-foreground text-xs",children:["Paires classées par ",t.jsx("b",{children:"poids de paire"})," (somme des deux classements FFT). Plus le poids est faible, plus la paire est forte : la n°1 est en tête. Un joueur ",t.jsx("b",{children:"NC"})," compte automatiquement comme le",t.jsx("b",{children:" pire classement"})," (",T!=null?T.toLocaleString("fr-FR"):"â¦",t.jsx("sup",{children:"e"}),", soit le nombre total de licenciés FFT du dernier relevé, mis à jour chaque mois). Cette vue vous aide à définir têtes de série, poules et format avant la génération du tableau."]})]})}),t.jsx(ce,{className:"divide-y",children:as.map((a,j)=>{const S=We(a.player_ranking),k=We(a.partner_ranking),U=!!a.player_license&&E.has(String(a.player_license)),Z=!!a.partner_license&&E.has(String(a.partner_license)),pe=zt(a);return t.jsxs("div",{className:"flex items-center gap-4 p-3",children:[t.jsx("div",{className:"w-8 h-8 rounded-full bg-muted flex items-center justify-center text-sm font-bold shrink-0",children:j+1}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsxs("div",{className:"flex items-baseline gap-2 text-sm",children:[U&&s?t.jsx("button",{type:"button",onClick:()=>{ft({regId:a.id,field:"player",name:`${a.player_first_name} ${a.player_last_name}`,license:a.player_license??null}),Ot(S!=null?String(S):"")},className:"text-court font-mono text-xs tabular-nums shrink-0 underline decoration-dotted underline-offset-2 hover:text-court/80",title:"Classement estimé â cliquer pour corriger",children:S!=null?`~#${S}`:"NC"}):t.jsx("span",{className:"text-court font-mono text-xs tabular-nums shrink-0",title:U?"Classement estimé":void 0,children:S!=null?`${U?"~":""}#${S}`:"NC"}),t.jsxs("span",{className:"font-medium truncate",children:[a.player_first_name," ",a.player_last_name]}),a.forfeit&&t.jsx("span",{className:"ml-1 shrink-0 rounded px-1.5 py-0.5 text-[10px] font-bold bg-destructive/15 text-destructive",children:"FORFAIT"})]}),t.jsxs("div",{className:"flex items-baseline gap-2 text-sm",children:[Z&&s?t.jsx("button",{type:"button",onClick:()=>{ft({regId:a.id,field:"partner",name:`${a.partner_first_name} ${a.partner_last_name}`,license:a.partner_license??null}),Ot(k!=null?String(k):"")},className:"text-court font-mono text-xs tabular-nums shrink-0 underline decoration-dotted underline-offset-2 hover:text-court/80",title:"Classement estimé â cliquer pour corriger",children:k!=null?`~#${k}`:"NC"}):t.jsx("span",{className:"text-court font-mono text-xs tabular-nums shrink-0",title:Z?"Classement estimé":void 0,children:k!=null?`${Z?"~":""}#${k}`:"NC"}),t.jsxs("span",{className:"font-medium truncate",children:[a.partner_first_name," ",a.partner_last_name]})]})]}),t.jsxs("div",{className:"text-right shrink-0",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Poids paire"}),t.jsx("div",{className:"font-mono text-sm font-semibold tabular-nums",children:pe!=null?pe.toLocaleString("fr-FR"):"â"})]})]},a.id)})})]})}),t.jsxs(Bt,{value:"bracket",className:"mt-4 space-y-0",children:[!Fe&&t.jsxs(ce,{className:"p-8 text-center",children:[t.jsx(Vs,{className:"h-12 w-12 mx-auto text-muted-foreground mb-3"}),t.jsx("p",{className:"text-muted-foreground mb-1",children:"Aucun tableau généré."}),t.jsxs("p",{className:"text-xs text-muted-foreground",children:["Clique sur ",t.jsx("b",{children:"« Générer le tableau »"})," pour construire ton tableau à la main, étape par étape : choix du nombre de poules, placement des paires (pré-remplissage serpentin ou drag & drop), puis format des phases finales (1/4, 1/2, finale, 3e place, matchs de classement). Paires confirmées : ",t.jsx("b",{children:i}),"."]}),t.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Besoin d'aide pour un format inhabituel ? Utilise ",t.jsx("b",{children:"Format flexible (IA)"})," et décris ce que tu veux (nombre de poules, élimination directe, etc.) â tu pourras ensuite ajuster manuellement."]}),t.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Format de match : ",t.jsx("b",{children:"9 jeux gagnants"}),", point décisif à 40-40, tie-break à 8-8 (premier à 7 avec 2 d'écart)."]})]}),Fe&&t.jsxs(t.Fragment,{children:[c.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("h2",{className:"font-display text-xl mb-3",children:"Phase de poules"}),t.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4 mb-8",children:c.map(a=>{const j=Ts(a.id);return t.jsxs(ce,{className:"p-4",children:[t.jsx("div",{className:"font-semibold mb-2",children:Vn(a.name)}),t.jsxs("div",{className:"mb-3",children:[t.jsx(Se,{htmlFor:`court-${a.id}`,className:"text-[11px] text-muted-foreground",children:"Terrain (facultatif · affiché sur l'écran TV)"}),t.jsx(Ge,{id:`court-${a.id}`,defaultValue:a.court??"",placeholder:"ex : Terrain 3",className:"h-8 mt-1 text-sm",onBlur:S=>{(S.target.value.trim()||null)!==(a.court??null)&&Es(a.id,S.target.value)}})]}),t.jsx("div",{className:"space-y-1 mb-3 text-xs",children:j.map((S,k)=>t.jsxs("div",{className:`flex justify-between ${k===0&&S.played>0?"font-bold text-success":""}`,children:[t.jsxs("span",{className:"truncate",children:[k+1,". ",dt(N[S.registration_id])]}),t.jsxs("span",{className:"tabular-nums ml-2",children:[S.wins,"V · ",S.gd>0?"+":"",S.gd]})]},S.id))}),t.jsx("div",{className:"space-y-2",children:_t(a.id).map(S=>t.jsx(on,{m:S},S.id))})]},a.id)})})]}),h.some(a=>a.is_top_seed)&&t.jsxs(ce,{className:"p-4 mb-8",children:[t.jsx("div",{className:"font-semibold mb-2",children:"ð Têtes de série (entrée directe en phase finale)"}),t.jsx("div",{className:"grid gap-2 sm:grid-cols-2 md:grid-cols-4 text-sm",children:h.filter(a=>a.is_top_seed).map((a,j)=>t.jsxs("div",{className:"rounded border p-2 bg-amber-50",children:[t.jsxs("span",{className:"text-xs text-muted-foreground",children:["TS",j+1," ·"]})," ",dt(N[a.registration_id])]},a.id))})]}),is.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex items-center justify-between mb-3",children:[t.jsx("h2",{className:"font-display text-xl",children:"Tableau final"}),t.jsx(K,{size:"sm",variant:_e?"default":"outline",onClick:()=>Mt(a=>!a),children:_e?"Terminer l'ajustement":"Ajuster (glisser-déposer)"})]}),_e?t.jsx("div",{className:"mb-6",children:t.jsx(Di,{matches:m.filter(a=>is.includes(a.stage)),regs:N,availableIds:Ms,onReload:Ve,onOpenScore:a=>Ue(a)})}):t.jsx("div",{className:`grid gap-4 mb-6 md:grid-cols-2 ${Wi[Math.min(is.length,4)]}`,children:is.map(a=>t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-semibold mb-2",children:Ui[a]??a}),t.jsx("div",{className:"space-y-2",children:lt(a).map(j=>t.jsx(on,{m:j},j.id))})]},a))})]}),dn.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("h2",{className:"font-display text-xl mb-3",children:"Matchs de classement"}),t.jsx("div",{className:"mb-6",children:t.jsx(Ni,{matches:dn,pools:c,assigns:h,regs:N,qualifiedIds:qt,eliminatedIds:$s,onReload:Ve,onOpenScore:a=>Ue(a)})})]})]})]}),t.jsx(Bt,{value:"results",className:"mt-4",children:t.jsx(Ti,{tournamentId:e,category:r.category,confirmedRegs:St,onSaved:Qe})}),t.jsx(Bt,{value:"photos",className:"mt-4",children:t.jsx(Ii,{tournamentId:r.id,path:r.podium_photo_path,title:r.title,onChanged:Qe})}),t.jsx(Bt,{value:"convocations",className:"mt-4",children:t.jsx(Oi,{tournament:{id:r.id,title:r.title,category:r.category,tournament_date:r.tournament_date,start_time:r.start_time,gender:r.gender}})})]}),t.jsx(Ut,{open:!!L,onOpenChange:a=>!a&&f(null),children:t.jsxs(Wt,{children:[t.jsx(Ht,{children:t.jsx(Gt,{children:Bs(L==null?void 0:L.label)})}),L&&t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[t.jsx("button",{type:"button",onClick:()=>ee("single9"),className:`rounded-md border px-3 py-2 text-xs font-medium transition-colors ${H==="single9"?"border-court bg-court/10 text-court":"text-muted-foreground hover:bg-muted"}`,children:"1 set en 9 jeux"}),t.jsx("button",{type:"button",onClick:()=>ee("two_sets"),className:`rounded-md border px-3 py-2 text-xs font-medium transition-colors ${H==="two_sets"?"border-court bg-court/10 text-court":"text-muted-foreground hover:bg-muted"}`,children:"2 sets gagnants de 6"})]}),H==="single9"?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"text-sm text-muted-foreground",children:"9 jeux gagnants · Point décisif à 40-40 · Tie-break à 8-8 (7 pts, 2 d'écart)"}),t.jsxs("div",{className:"grid grid-cols-[1fr_auto_auto] gap-3 items-center",children:[t.jsx("div",{className:"font-medium",children:dt(N[L.pair_a_id])}),t.jsxs("div",{children:[t.jsx(Se,{className:"text-xs",children:"Jeux"}),t.jsx(Ge,{type:"number",min:0,max:9,value:X,onChange:a=>V(a.target.value),className:"w-20"})]}),t.jsxs("div",{children:[t.jsx(Se,{className:"text-xs",children:"TB"}),t.jsx(Ge,{type:"number",min:0,value:se,onChange:a=>oe(a.target.value),className:"w-20",placeholder:"â"})]}),t.jsx("div",{className:"font-medium",children:dt(N[L.pair_b_id])}),t.jsx(Ge,{type:"number",min:0,max:9,value:J,onChange:a=>de(a.target.value),className:"w-20"}),t.jsx(Ge,{type:"number",min:0,value:me,onChange:a=>le(a.target.value),className:"w-20",placeholder:"â"})]}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"Le tie
78-break n'est requis qu'à 8-8."})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"text-sm text-muted-foreground",children:"2 sets gagnants de 6 jeux · 3e set = super tie-break à 10 (2 pts d'écart)"}),t.jsxs("div",{className:"grid grid-cols-[1fr_auto_auto_auto] gap-3 items-center",children:[t.jsx("div",{className:"text-xs text-muted-foreground"}),t.jsx(Se,{className:"text-xs text-center",children:"Set 1"}),t.jsx(Se,{className:"text-xs text-center",children:"Set 2"}),t.jsx(Se,{className:"text-xs text-center",children:"Set 3"}),t.jsx("div",{className:"font-medium",children:dt(N[L.pair_a_id])}),[0,1,2].map(a=>t.jsx(Ge,{type:"number",min:0,value:xe[a].a,onChange:j=>ie(S=>S.map((k,U)=>U===a?{...k,a:j.target.value}:k)),className:"w-16",placeholder:a===2?"TB":"â"},`a${a}`)),t.jsx("div",{className:"font-medium",children:dt(N[L.pair_b_id])}),[0,1,2].map(a=>t.jsx(Ge,{type:"number",min:0,value:xe[a].b,onChange:j=>ie(S=>S.map((k,U)=>U===a?{...k,b:j.target.value}:k)),className:"w-16",placeholder:a===2?"TB":"â"},`b${a}`))]}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"Set 3 à remplir uniquement en cas d'égalité à 1 set partout (super tie-break à 10)."})]}),t.jsxs("div",{children:[t.jsx(Se,{htmlFor:"score-court",className:"text-xs",children:"Terrain (facultatif · affiché sur l'écran TV)"}),t.jsx(Ge,{id:"score-court",value:D,onChange:a=>P(a.target.value),placeholder:"ex. Piste 3",className:"mt-1"})]})]}),t.jsxs(wt,{className:"flex-col-reverse gap-2 sm:flex-row sm:justify-between",children:[L&&(L.status==="completed"||L.winner_id)?t.jsx(K,{variant:"ghost",onClick:yt,disabled:A||_,className:"text-destructive hover:text-destructive hover:bg-destructive/10 sm:mr-auto",children:_?t.jsxs(t.Fragment,{children:[t.jsx(Ie,{className:"h-4 w-4 mr-2 animate-spin"})," Suppressionâ¦"]}):t.jsxs(t.Fragment,{children:[t.jsx(ms,{className:"h-4 w-4 mr-2"})," Effacer le score"]})}):t.jsx("span",{}),t.jsxs("div",{className:"flex gap-2 justify-end",children:[t.jsx(K,{variant:"outline",onClick:()=>f(null),disabled:A||_,children:"Annuler"}),t.jsx(K,{onClick:jt,className:"bg-court",disabled:A||_,children:A?t.jsxs(t.Fragment,{children:[t.jsx(Ie,{className:"h-4 w-4 mr-2 animate-spin"})," Enregistrementâ¦"]}):"Valider"})]})]})]})}),t.jsx(Ut,{open:!!qe,onOpenChange:a=>!a&&!bt&&ft(null),children:t.jsxs(Wt,{className:"max-w-sm",children:[t.jsxs(Ht,{children:[t.jsx(Gt,{children:"Corriger le classement"}),t.jsxs(As,{children:[qe==null?void 0:qe.name," â classement FFT estimé. Saisis le vrai numéro de rang pour ajuster le poids de paire."]})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(Se,{htmlFor:"rank-edit",className:"text-xs",children:"Classement (n° de rang)"}),t.jsx(Ge,{id:"rank-edit",type:"number",min:1,inputMode:"numeric",placeholder:"ex. 850",value:Lt,onChange:a=>Ot(a.target.value),onKeyDown:a=>{a.key==="Enter"&&Me()}}),t.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Laisse vide pour repasser le joueur en NC."})]}),t.jsxs(wt,{children:[t.jsx(K,{variant:"outline",onClick:()=>ft(null),disabled:bt,children:"Annuler"}),t.jsxs(K,{onClick:Me,disabled:bt,className:"bg-court",children:[bt?t.jsx(Ie,{className:"h-4 w-4 mr-2 animate-spin"}):t.jsx(kt,{className:"h-4 w-4 mr-2"}),"Enregistrer"]})]})]})}),t.jsx(Ut,{open:ae,onOpenChange:a=>!ue&&be(a),children:t.jsxs(Wt,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[t.jsxs(Ht,{children:[t.jsxs(Gt,{className:"flex items-center gap-2",children:[t.jsx(Xt,{className:"h-5 w-5 text-court"})," Format flexible (IA)"]}),t.jsx(As,{children:Fe?"Un tableau existe déjà . Demandez une modification en langage naturel â l'IA ajuste le tableau existant sans repartir de zéro. Vous pouvez itérer autant de fois que nécessaire.":`Décrivez en langage naturel le format souhaité pour ce tournoi (${i} paires confirmées). L'IA construit poules et phase finale automatiquement.`})]}),t.jsxs("div",{className:"space-y-3 min-w-0",children:[Je.length>0&&t.jsx("div",{className:"space-y-2 max-h-52 overflow-y-auto rounded-lg border bg-muted/30 p-3",children:Je.map((a,j)=>t.jsx("div",{className:a.role==="user"?"text-right":"text-left",children:t.jsx("span",{className:`inline-block rounded-lg px-2.5 py-1.5 text-xs max-w-[85%] ${a.role==="user"?"bg-court text-white":"bg-card border"}`,children:a.content})},j))}),w.length>0&&t.jsxs("div",{className:"space-y-1.5",children:[t.jsx(Se,{className:"text-xs text-muted-foreground",children:"Mes modèles"}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs(et,{value:M,onValueChange:Ke,children:[t.jsx(tt,{className:"flex-1",disabled:ue,children:t.jsx(st,{placeholder:"Réutiliser un modèle enregistréâ¦"})}),t.jsx(nt,{children:w.map(a=>t.jsx(Ne,{value:a.id,children:a.name},a.id))})]}),t.jsx(K,{type:"button",variant:"outline",size:"icon",disabled:!M||ue,onClick:()=>Ce(M),title:"Renommer le modèle",children:t.jsx(Xt,{className:"h-4 w-4"})}),t.jsx(K,{type:"button",variant:"outline",size:"icon",disabled:!M||ue,onClick:()=>ot(M),title:"Supprimer le modèle",children:t.jsx(ms,{className:"h-4 w-4 text-destructive"})})]})]}),t.jsx(Wn,{value:ve,onChange:a=>{ye(a.target.value),te("")},rows:4,placeholder:Fe?"Ex : mets la paire DUPONT/MARTIN dans la poule B · inverse TS3 et TS4 · évite que les 2 sortants de la poule A se recroisent en 1/4.":"Ex : 12 paires, 3 poules de 4, les 2 premiers de chaque poule + 2 meilleurs 3e en 1/4 de finale, puis 1/2, finale et petite finale.",disabled:ue}),t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.jsxs(K,{type:"button",variant:"outline",size:"sm",disabled:re||ue||!ve.trim(),onClick:xt,children:[t.jsx(kt,{className:"h-4 w-4 mr-2"})," Enregistrer comme modèle"]}),Je.length>0&&t.jsx(K,{type:"button",variant:"ghost",size:"sm",disabled:ue,onClick:()=>at([]),children:"Effacer la conversation"})]}),t.jsx("p",{className:"text-xs text-muted-foreground",children:Fe?"⨠Mode itératif : le tableau existant est modifié, pas écrasé. Si des scores sont déjà saisis, on te demandera si tu veux les conserver. Utilise « Repartir de zéro » pour tout écraser et reconstruire.":"â ï¸ La génération crée le tableau à partir de zéro."})]}),t.jsxs(wt,{className:"flex-col sm:flex-row sm:flex-wrap gap-2 min-w-0",children:[t.jsx(K,{variant:"outline",onClick:()=>
78be(!1),disabled:ue,className:"w-full sm:w-auto sm:mr-auto",children:"Fermer"}),Fe&&t.jsxs(K,{variant:"destructive",onClick:()=>{window.confirm("Repartir de zéro écrase le tableau actuel (poules, têtes de série, matchs et scores). Continuer ?")&&(at([]),Oe(!0))},disabled:ue,className:"w-full sm:w-auto",children:[t.jsx(Xt,{className:"h-4 w-4 mr-2"})," Repartir de zéro"]}),t.jsx(K,{onClick:()=>{const a=m.some(j=>j.games_a!=null&&j.games_b!=null);Fe&&a?gt(!0):Oe(!1,!1)},className:"w-full sm:w-auto bg-court",disabled:ue||Fe&&!ve.trim(),children:ue?t.jsxs(t.Fragment,{children:[t.jsx(Ie,{className:"h-4 w-4 mr-2 animate-spin"})," ",Fe?"Traitementâ¦":"Générationâ¦"]}):t.jsxs(t.Fragment,{children:[t.jsx(gn,{className:"h-4 w-4 mr-2"})," ",Fe?"Appliquer la modification":"Générer le tableau"]})})]})]})}),t.jsx(Ut,{open:it,onOpenChange:gt,children:t.jsxs(Wt,{className:"max-w-md",children:[t.jsxs(Ht,{children:[t.jsx(Gt,{children:"Des scores sont déjà saisis"}),t.jsx(As,{children:"Ce tableau contient déjà des scores de matchs. Veux-tu les conserver lors de la modification ? Les scores des matchs qui opposent toujours les deux mêmes paires seront reportés automatiquement."})]}),t.jsxs(wt,{className:"flex-col sm:flex-row gap-2",children:[t.jsx(K,{variant:"outline",className:"w-full sm:w-auto sm:mr-auto",onClick:()=>gt(!1),disabled:ue,children:"Annuler"}),t.jsx(K,{variant:"destructive",className:"w-full sm:w-auto",onClick:()=>{gt(!1),Oe(!1,!1)},disabled:ue,children:"Réinitialiser les scores"}),t.jsx(K,{className:"w-full sm:w-auto bg-court",onClick:()=>{gt(!1),Oe(!1,!0)},disabled:ue,children:"Conserver les scores"})]})]})})]})};export{go as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.