PageSourceSearch

https://twinforgefit.ai/assets/TrainingPage-DJd49C-6.js

js twinforgefit.ai collected 2026-10-05 14:31:23 UTC 255,816 bytes, 57 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TrainingTwinTab-DdoXBLxh.js","assets/motion-CghpQXKE.js","assets/router-epi9CWfp.js","assets/index-_-9kgWZ5.js","assets/supabase-CTBn71hm.js","assets/index-DgO36s-g.css","assets/heat-zone-adapter-C2YVEJFC.js","assets/InfoTooltip-DShv0ozk.js","assets/ForgeIcon-PBV6eFDW.js","assets/useBodyScanTwin-CjDga_ah.js","assets/useRuntimeFeatureFlag-Q8wV5kQ1.js","assets/productEvents-DItVKoUy.js","assets/camera-C5hhbOmw.js","assets/refrigerator-0UrXF6wH.js","assets/chef-hat-DMAlDOEJ.js","assets/calendar-days-Z8c114VT.js","assets/fr-text-BT4IBObw.js","assets/TwinPreviewStage-e7NNtZpZ.js","assets/TwinBoundary-DDPI3cVE.js","assets/TwinStage-SXvS1dQ4.js","assets/morph-normals-CfRh6rQ9.js","assets/measures-DMn_ZQvM.js","assets/viewer-registry-DLIcBGr7.js","assets/twin-preview-sex-Bx9ptNuF.js","assets/useTrainingHeatCoverage-BYHlRqmC.js","assets/SurfaceHeading-D49e6FSi.js","assets/CardHeading-CcXctmQj.js","assets/resolved-daily-health-Dvckn8ID.js","assets/training-split-CEjh7ZOD.js","assets/calendar-window-CDqSTSNk.js","assets/WeekAgenda-DJlgrsi7.js","assets/calendar-read-state-3flPBvWF.js","assets/chevron-up-J_GnXi8C.js","assets/calendar-clock-BSDaZIsa.js","assets/utensils-crossed-8gPnwRDO.js","assets/SectionBoundary-BkSrDADb.js","assets/chevron-right-WmA4jE3-.js","assets/exercise-illustration-url-DY2CwbL8.js","assets/person-standing-CbQIQ0U1.js","assets/arrow-up-C3EWNZgG.js","assets/ForgeGalleryPreview-BK7B2XNv.js","assets/forge-card-share-dN1B8nV0.js","assets/gift-D-9FN6p5.js","assets/share-2-BXojvhlh.js","assets/download-B5AFaDgs.js","assets/addDays-aYYkHh1o.js","assets/Chip-CIa43c9D.js","assets/shield-alert-B5Y3tq6p.js","assets/trending-down-Cd0TvuSZ.js","assets/bar-chart-3-BJ1hMGNU.js","assets/charts-BVCHgq9e.js","assets/play-BIPsOZyJ.js","assets/trees-C-OYtWOr.js","assets/plus-DSuB3LTj.js","assets/message-square-quote-O_oYtgMg.js","assets/calendar-DrNo2-T3.js","assets/scan-line-BYBAHEUu.js","assets/useGamingTeam-D9_qqgYA.js","assets/useSocialRefresh-BNPqaImu.js","assets/TeamInviteModal-B1OmX-z3.js","assets/EditorFrame-BlN4Ei9q.js","assets/SettingsPrimitives-L3DIo8jg.js","assets/clipboard-iQ7AojFJ.js","assets/copy-BPVsxxGn.js","assets/user-plus-BrfxM2bh.js","assets/book-open-DsRVbYI6.js","assets/arrow-up-right-C6rE6Mgk.js","assets/external-link-c8SLAmAp.js","assets/sliders-horizontal-CpIHb-6m.js","assets/isPast-vTq5mRlk.js","assets/filter-BIVb9EmY.js"])))=>i.map(i=>d[i]);
2import{j as e,A as Oe,m as te}from"./motion-CghpQXKE.js";import{r as o,b as Es,a as xr,L as mn,e as pr}from"./router-epi9CWfp.js";import{c as ve,d5 as sa,c$ as fr,s as $,bm as nt,r as be,ch as pt,V as hr,R as gr,a7 as br,d6 as Rs,Y as As,l as ze,f as Ds,c8 as Le,G as Q,K as Je,aA as Mt,Z as Ms,N as ue,az as Bt,k as Ie,bL as ke,ak as Lt,B as P,cr as Ls,cn as Ze,z as Xe,bK as Ut,d7 as yr,br as na,O as ft,cj as jr,c7 as vr,_ as _r,ay as V,d8 as he,aK as We,au as ge,bs as oe,cO as ye,m as Te,d9 as qt,a3 as aa,da as ra,u as _e,S as ht,E as Be,aT as Nr,am as qs,db as wr,bQ as ia,aC as la,M as $s,ck as zt,at as kr,I as Sr,A as $t,U as Fs,cP as Ps,cl as fe,b$ as Cr,J as Os,H as Tr,X as xt,a9 as xn,b7 as Bs,aJ as Er,bO as Rr,ac as oa,bM as ca,bu as Ar,dc as Dr,al as Mr,aa as Lr,aS as mt,cK as qr,T as $r,dd as da,de as ua,cA as Fr,cE as Pr,df as Or,bq as ma,dg as as,ag as Us,bN as xa,n as hs,dh as Br,b8 as Ur,cB as zr,cD as pn,cz as Ir,di as Wr}from"./index-_-9kgWZ5.js";import{i as pa,u as Hr,E as Vr,S as Gr}from"./SurfaceHeading-D49e6FSi.js";import{f as Yr,t as Kr,d as Jr,P as Zr}from"./resolved-daily-health-Dvckn8ID.js";import{w as rs,j as Qr,n as Xr,r as fa,S as re,a as ei,u as ti,W as si,v as ha,f as ni,d as ai,k as ri,l as ii,m as li,h as oi,g as ci,o as di,s as ui}from"./training-split-CEjh7ZOD.js";import{s as mi,u as xi,g as pi,b as fi,d as fn,n as hi,f as gi,h as bi,C as zs,W as yi,w as ji,j as ga,k as vi,l as ba}from"./WeekAgenda-DJlgrsi7.js";import{B as _i,A as Ni,T as ya,M as wi,a as ja,b as ki}from"./exercise-illustration-url-DY2CwbL8.js";import{P as Si}from"./person-standing-CbQIQ0U1.js";import{A as Ci}from"./arrow-up-C3EWNZgG.js";import{W as Ti,E as Ei,P as Ri,A as Ai,H as Di,I as Mi,a as Li,F as qi}from"./ForgeGalleryPreview-BK7B2XNv.js";import{S as Ue,a as st,B as me,I as Ke}from"./InfoTooltip-DShv0ozk.js";import{s as gs,f as je,M as It,D as $i}from"./CardHeading-CcXctmQj.js";import{a as bs}from"./addDays-aYYkHh1o.js";import{C as va}from"./calendar-days-Z8c114VT.js";import{S as Me}from"./SectionBoundary-BkSrDADb.js";import{A as Wt,t as Rt}from"./productEvents-DItVKoUy.js";import{T as Fi}from"./TwinBoundary-DDPI3cVE.js";import{C as Pi}from"./Chip-CIa43c9D.js";import{F as xe}from"./ForgeIcon-PBV6eFDW.js";import{S as Is}from"./shield-alert-B5Y3tq6p.js";import{C as Ht}from"./chevron-right-WmA4jE3-.js";import{T as gt}from"./trending-down-Cd0TvuSZ.js";import{B as _a}from"./bar-chart-3-BJ1hMGNU.js";import{R as Oi,A as Bi,a as Ui}from"./charts-BVCHgq9e.js";import{C as et}from"./chevron-up-J_GnXi8C.js";import{C as Ft}from"./camera-C5hhbOmw.js";import{P as zi}from"./play-BIPsOZyJ.js";import{B as Ii,T as hn}from"./trees-C-OYtWOr.js";import{P as Wi}from"./plus-DSuB3LTj.js";import{M as Hi}from"./message-square-quote-O_oYtgMg.js";import{C as Vi}from"./calendar-DrNo2-T3.js";import{S as Gi}from"./scan-line-BYBAHEUu.js";import{u as Yi}from"./useGamingTeam-D9_qqgYA.js";import{u as is}from"./useRuntimeFeatureFlag-Q8wV5kQ1.js";import{L as Na,a as ys,T as Ki}from"./TeamInviteModal-B1OmX-z3.js";import{U as wa}from"./user-plus-BrfxM2bh.js";import{B as Ji}from"./book-open-DsRVbYI6.js";import{A as Zi}from"./arrow-up-right-C6rE6Mgk.js";import{E as Qi}from"./external-link-c8SLAmAp.js";import{S as Xi}from"./sliders-horizontal-CpIHb-6m.js";import{C as el}from"./calendar-clock-BSDaZIsa.js";import{i as gn}from"./isPast-vTq5mRlk.js";import{F as bn}from"./filter-BIVb9EmY.js";(function(){try{var t=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{};t.SENTRY_RELEASE={id:"19ca80bcc68db376b793c8a886be03b6d5ea8a5c"};var s=new t.Error().stack;s&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[s]="917fa1c2-e76b-4013-8a1a-3bcc8c5916f3",t._sentryDebugIdIdentifier="sentry-dbid-917fa1c2-e76b-4013-8a1a-3bcc8c5916f3")}catch{}})();/**
3 * @license lucide-react v0.344.0 - ISC
4 *
5 * This source code is licensed under the ISC license.
6 * See the LICENSE file in the root directory of this source tree.
7 */const tl=ve("ArrowDownRight",[["path",{d:"m7 7 10 10",key:"1fmybs"}],["path",{d:"M17 7v10H7",key:"6fjiku"}]]);/**
8 * @license lucide-react v0.344.0 - ISC
9 *
10 * This source code is licensed under the ISC license.
11 * See the LICENSE file in the root directory of this source tree.
12 */const ka=ve("Circle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/**
13 * @license lucide-react v0.344.0 - ISC
14 *
15 * This source code is licensed under the ISC license.
16 * See the LICENSE file in the root directory of this source tree.
17 */const Ws=ve("Hourglass",[["path",{d:"M5 22h14",key:"ehvnwv"}],["path",{d:"M5 2h14",key:"pdyrp9"}],["path",{d:"M17 22v-4.172a2 2 0 0 0-.586-1.414L12 12l-4.414 4.414A2 2 0 0 0 7 17.828V22",key:"1d314k"}],["path",{d:"M7 2v4.172a2 2 0 0 0 .586 1.414L12 12l4.414-4.414A2 2 0 0 0 17 6.172V2",key:"1vvvr6"}]]);/**
18 * @license lucide-react v0.344.0 - ISC
19 *
20 * This source code is licensed under the ISC license.
21 * See the LICENSE file in the root directory of this source tree.
22 */const sl=ve("Maximize2",[["polyline",{points:"15 3 21 3 21 9",key:"mznyad"}],["polyline",{points:"9 21 3 21 3 15",key:"1avn1i"}],["line",{x1:"21",x2:"14",y1:"3",y2:"10",key:"ota7mn"}],["line",{x1:"3",x2:"10",y1:"21",y2:"14",key:"1atl0r"}]]);/**
23 * @license lucide-react v0.344.0 - ISC
24 *
25 * This source code is licensed under the ISC license.
26 * See the LICENSE file in the root directory of this source tree.
27 */const Hs=ve("Repeat",[["path",{d:"m17 2 4 4-4 4",key:"nntrym"}],["path",{d:"M3 11v-1a4 4 0 0 1 4-4h14",key:"84bu3i"}],["path",{d:"m7 22-4-4 4-4",key:"1wqhfi"}],["path",{d:"M21 13v1a4 4 0 0 1-4 4H3",key:"1rx37r"}]]);/**
28 * @license lucide-react v0.344.0 - ISC
29 *
30 * This source code is licensed under the ISC license.
31 * See the LICENSE file in the root directory of this source tree.
32 */const nl=ve("StretchHorizontal",[["rect",{width:"20",height:"6",x:"2",y:"4",rx:"2",key:"qdearl"}],["rect",{width:"20",height:"6",x:"2",y:"14",rx:"2",key:"1xrn6j"}]]);/**
33 * @license lucide-react v0.344.0 - ISC
34 *
35 * This source code is licensed under the ISC license.
36 * See the LICENSE file in the root directory of this source tree.
37 */const al=ve("ThumbsDown",[["path",{d:"M17 14V2",key:"8ymqnk"}],["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22h0a3.13 3.13 0 0 1-3-3.88Z",key:"s6e0r"}]]);/**
38 * @license lucide-react v0.344.0 - ISC
39 *
40 * This source code is licensed under the ISC license.
41 * See the LICENSE file in the root directory of this source tree.
42 */const Vs=ve("Timer",[["line",{x1:"10",x2:"14",y1:"2",y2:"2",key:"14vaq8"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11",key:"17fdiu"}],["circle",{cx:"12",cy:"14",r:"8",key:"1e1u0o"}]]);/**
43 * @license lucide-react v0.344.0 - ISC
44 *
45 * This source code is licensed under the ISC license.
46 * See the LICENSE file in the root directory of this source tree.
47 */const rl=ve("UserCog",[["circle",{cx:"18",cy:"15",r:"3",key:"gjjjvw"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M10 15H6a4 4 0 0 0-4 4v2",key:"1nfge6"}],["path",{d:"m21.7 16.4-.9-.3",key:"12j9ji"}],["path",{d:"m15.2 13.9-.9-.3",key:"1fdjdi"}],["path",{d:"m16.6 18.7.3-.9",key:"heedtr"}],["path",{d:"m19.1 12.2.3-.9",key:"1af3ki"}],["path",{d:"m19.6 18.7-.4-1",key:"1x9vze"}],["path",{d:"m16.8 12.3-.4-1",key:"vqeiwj"}],["path",{d:"m14.3 16.6 1-.4",key:"1qlj63"}],["path",{d:"m20.7 13.8 1-.4",key:"1v5t8k"}]]);/**
48 * @license lucide-react v0.344.0 - ISC
49 *
50 * This source code is licensed under the ISC license.
51 * See the LICENSE file in the root directory of this source tree.
52 */const il=ve("Waves",[["path",{d:"M2 6c.6.5 1.2 1 2.5 1C7 7 7 5 9.5 5c2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1",key:"knzxuh"}],["path",{d:"M2 12c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1",key:"2jd2cc"}],["path",{d:"M2 18c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1",key:"rd2r6e"}]]);/**
53 * @license lucide-react v0.344.0 - ISC
54 *
55 * This source code is licensed under the ISC license.
56 * See the LICENSE file in the root directory of this source tree.
57 */const ll=ve("Youtube",[["path",{d:"M2.5 17a24.12 24.12 0 0 1 0-10 2 2 0 0 1 1.4-1.4 49.56 49.56 0 0 1 16.2 0A2 2 0 0 1 21.5 7a24.12 24.12 0 0 1 0 10 2 2 0 0 1-1.4 1.4 49.55 49.55 0 0 1-16.2 0A2 2 0 0 1 2.5 17",key:"1q2vi4"}],["path",{d:"m10 15 5-3-5-3z",key:"1jp15x"}]]);function js(t,s){return pa(fr(t,t),sa(t))}function ol(t,s){return pa(t,bs(sa(t),1),s)}function cl(t,s){const[n,a]=o.useState(null),[r,l]=o.useState([]),[i,c]=o.useState(!!(t&&s)),[m,u]=o.useState(null),[x,d]=o.useState(void 0),[g,b]=o.useState(void 0),f=o.useRef(!0),h=o.useRef(0),v=o.useRef(t),w=o.useRef(s??null);v.current=t,w.current=s??null,o.useEffect(()=>(f.current=!0,()=>{f.current=!1}),[]);const _=o.useRef(new Set),T=o.useCallback(async()=>{const k=s??null;if(!f.current||v.current!==t||w.current!==k)return!1;const p=++h.current,S=()=>f.current&&p===h.current&&v.current===t&&w.current===k;if(d(t),b(k),a(null),l([]),c(!!(t&&k)),u(null),!t||!k)return S()&&c(!1),!0;try{if(!_.current.has(t)){_.current.add(t);try{await $.functions.invoke("ai-training",{body:{action:"sync_week"}})}catch{}if(!S())return!1}const[j,C]=await Promise.all([$.from("training_programs").select("id, week_start, week_end, program, split_type, sessions_per_week, deload_tracking").eq("user_id",t).eq("is_active",!0).order("created_at",{ascending:!1}).limit(1).maybeSingle(),$.from("training_sessions").select("id, session_type, scheduled_at, session_local_date, performed_local_date, completed_at, created_at, status, exercises, warmup, cooldown, duration_min, calories_burned, adherence_pct, difficulty_rating, user_feedback").eq("user_id",t).eq("training_plan_id",k).order("scheduled_at",{ascending:!1,nullsFirst:!1}).limit(50)]);return S()?j.error?(a(null),l([]),u(j.error.message),!1):C.error?(a(null),l([]),u(C.error.message),!1):(a(j.data??null),l(C.data??[]),!0):!1}catch(j){return S()&&(a(null),l([]),u(j instanceof Error?j.message:"Erreur inattendue")),!1}finally{S()&&c(!1)}},[t,s]);o.useEffect(()=>{T()},[T]),nt({table:"training_sessions",userId:t,events:["INSERT","UPDATE"],onAny:()=>{s&&T()}});const N=o.useCallback(()=>{T()},[T]);return x===t&&g===(s??null)?{program:n,sessions:r,loading:i,error:m,refresh:N,refetch:T}:{program:null,sessions:[],loading:!!(t&&s),error:null,refresh:N,refetch:T}}function dl(t){const[s,n]=o.useState(null),[a,r]=o.useState([]),[l,i]=o.useState(!!t),[c,m]=o.useState(null),[u,x]=o.use
57State(void 0),d=o.useRef(!0),g=o.useRef(0),b=o.useRef(t);b.current=t,o.useEffect(()=>(d.current=!0,()=>{d.current=!1}),[]);const f=o.useRef(new Set),h=o.useCallback(async()=>{if(!d.current||b.current!==t)return!1;const k=++g.current,p=()=>d.current&&k===g.current&&b.current===t;if(x(t),n(null),r([]),i(!!t),m(null),!t)return p()&&i(!1),!0;try{if(!f.current.has(t)){f.current.add(t);const{data:R,error:B}=await $.from("training_plans").select("id").eq("user_id",t).eq("is_active",!0).limit(1).maybeSingle();if(!p())return!1;if(B)be("training","training_plan_sync_skipped",{error:B.message});else if(R){try{const{error:O}=await $.functions.invoke("ai-training",{body:{action:"sync_week"}});O&&be("training","training_plan_sync_failed",{error:O.message})}catch(O){be("training","training_plan_sync_failed",{error:O instanceof Error?O.message:"unknown"})}if(!p())return!1}}let S=null,j=null;const{data:C,error:A}=await $.from("training_plans").select("*").eq("user_id",t).eq("is_active",!0).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(!p())return!1;if(A)throw A;if(C){const R=C;S=R.id,R.end_date&&new Date(R.end_date)<new Date(new Date().toISOString().split("T")[0])?j={...R,status:"completed",is_active:!1}:j=R}else{const{data:R,error:B}=await $.from("training_plans").select("*").eq("user_id",t).eq("status","draft").eq("is_active",!1).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(!p())return!1;if(B)throw B;if(R){const O=R;S=O.id,j=O}else{const{data:O,error:G}=await $.from("training_plans").select("*").eq("user_id",t).in("status",["completed","active","cancelled","abandoned"]).eq("is_active",!1).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(!p())return!1;if(G)throw G;if(O){const z=O;S=z.id,z.status==="active"?j={...z,status:"completed"}:j=z}}}const{data:D,error:E}=await $.from("training_plans").select("*").eq("user_id",t).neq("is_active",!0).order("created_at",{ascending:!1}).limit(10);if(!p())return!1;if(E)throw E;const L=D??[],q=S?L.filter(R=>R.id!==S):L;return n(j),r(q),!0}catch(S){return p()&&(n(null),r([]),m(S instanceof Error?S.message:"Erreur inattendue")),!1}finally{p()&&i(!1)}},[t]);o.useEffect(()=>{h()},[h]),nt({table:"training_plans",userId:t,events:["INSERT","UPDATE"],onAny:()=>{h()}});const v=h,w=u===t,_=w?s:null,T=o.useCallback(async k=>{if(!t||!_||b.current!==t)return;const p=t,S=_;n(j=>j?.id===S.id?{...j,plan_data:k}:j);try{const{error:j}=await $.from("training_plans").update({plan_data:k,updated_at:new Date().toISOString()}).eq("id",S.id).eq("user_id",p);if(!d.current||b.current!==p||u!==p)return;j&&(n(C=>C?.id===S.id?{...C,plan_data:S.plan_data}:C),m(j.message))}catch(j){d.current&&b.current===p&&u===p&&(n(C=>C?.id===S.id?{...C,plan_data:S.plan_data}:C),m(j instanceof Error?j.message:"Erreur de sauvegarde"))}},[_,u,t]),N=_?_.status==="completed"||_.status==="cancelled"||_.end_date!=null&&new Date(_.end_date)<new Date(new Date().toISOString().split("T")[0]):!1,y=_?.end_date?Math.ceil((new Date(_.end_date).getTime()-new Date(new Date().toISOString().split("T")[0]).getTime())/864e5):null;return w?{plan:_,pastPlans:a,loading:l,error:c,refetch:v,updatePlanData:T,isExpired:N,daysUntilExpiry:y}:{plan:null,pastPlans:[],loading:!!t,error:null,refetch:v,updatePlanData:T,isExpired:!1,daysUntilExpiry:null}}function Vt(t,s){if(t.performed_local_date)return t.performed_local_date;const n=t.completed_at??t.performed_at;return n&&Number.isFinite(Date.parse(n))?pt(n,s):null}function at(t){if(!t)return"Date non renseignée";const s=new Date(`${t}T12:00:00Z`);return Number.isFinite(s.getTime())?new Intl.DateTimeFormat("fr-FR",{timeZone:"UTC",weekday:"long",day:"numeric",month:"short"}).format(s):"Date non renseignée"}function ul(t,s,n){const a=pt(t.toISOString(),n),r=pt(s.toISOString(),n),l=`and(completed_at.gte.${t.toISOString()},completed_at.lt.${s.toISOString()}),and(completed_at.is.null,performed_at.gte.${t.toISOString()},performed_at.lt.${s.toISOString()}),and(completed_at.is.null,performed_at.is.null,created_at.gte.${t.toISOString()},created_at.lt.${s.toISOString()})`;return`and(performed_local_date.gte.${a},performed_local_date.lt.${r}),and(performed_local_date.is.null,or(${l}))`}function ml(t,s){const n=at(t);if(!t)return n;const a=Date.parse(`${s}T12:00:00Z`),r=Date.parse(`${t}T12:00:00Z`);return!Number.isFinite(a)||!Number.isFinite(r)?n:Math.round((r-a)/864e5)===1?`demain · ${n}`:n}function xl(t){const s=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",weekday:"short"}).formatToParts(new Date),n=r=>s.find(l=>l.type===r)?.value??"",a={Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6,Sun:7};return{y:Number(n("year")),m:Number(n("month")),d:Number(n("day")),isoDow:a[n("weekday")]??1}}function yn(t,s,n,a){const r=new Date(Date.UTC(t,s-1,n,0,0,0)),l=new Date(r.toLocaleStr
57ing("en-US",{timeZone:a})),c=new Date(r.toLocaleString("en-US",{timeZone:"UTC"})).getTime()-l.getTime();return new Date(r.getTime()+c)}function pl(t){if(!t){const s=gs(new Date,{weekStartsOn:1});return{start:s,end:bs(s,7)}}try{const{y:s,m:n,d:a,isoDow:r}=xl(t),l=new Date(Date.UTC(s,n-1,a,12,0,0)),i=new Date(l);i.setUTCDate(i.getUTCDate()-(r-1));const c=yn(i.getUTCFullYear(),i.getUTCMonth()+1,i.getUTCDate(),t),m=new Date(i);m.setUTCDate(m.getUTCDate()+7);const u=yn(m.getUTCFullYear(),m.getUTCMonth()+1,m.getUTCDate(),t);return{start:c,end:u}}catch{const s=gs(new Date,{weekStartsOn:1});return{start:s,end:bs(s,7)}}}function ls(){return gs(new Date,{weekStartsOn:1})}function fl(t,s){const[n,a]=o.useState(0),[r,l]=o.useState(0),[i,c]=o.useState(null),[m,u]=o.useState(null),[x,d]=o.useState(!1),[g,b]=o.useState(!!t),[f,h]=o.useState(null),[v,w]=o.useState(void 0),[_,T]=o.useState(ls),N=o.useRef(!0),y=o.useRef(0),k=o.useRef(t);k.current=t;const p=!!s,S=s?.gender??null,j=s?.objective??null,C=s?.training_objective??null,A=s?.training_frequency_week??null,D=s?.timezone??null;o.useEffect(()=>(N.current=!0,()=>{N.current=!1}),[]);const E=o.useCallback(async()=>{if(!N.current||k.current!==t)return;const L=++y.current,q=()=>N.current&&L===y.current&&k.current===t;if(w(t),a(0),l(0),c(null),u(null),d(!1),T(ls()),b(!!t),h(null),!t){q()&&b(!1);return}try{let R=p?{gender:S,objective:j,training_objective:C,training_frequency_week:A,timezone:D}:null;if(!R){const K=await rs($.from("user_profiles").select("gender, objective, training_objective, training_frequency_week, timezone").eq("user_id",t).maybeSingle(),"profil de la semaine");if(!q())return;if(K.error){h(K.error.message);return}R=K.data}const{start:B,end:O}=pl(R?.timezone??null),[G,z]=await Promise.all([rs($.from("training_sessions").select("id").eq("user_id",t).eq("status","completed").or(ul(B,O,R?.timezone)),"séances de la semaine"),rs($.from("training_plans").select("sessions_per_week").eq("user_id",t).eq("is_active",!0).order("created_at",{ascending:!1}).limit(1).maybeSingle(),"cible hebdomadaire")]);if(!q())return;if(G.error){h(G.error.message);return}if(z.error){h(z.error.message);return}T(B),a((G.data??[]).length);const X=z.data?.sessions_per_week??0,ae=R?.training_frequency_week??0;l(ae>0?ae:Math.max(0,X));const I=R?.training_objective,M=hr(I)?I:null,F=M??gr(R?.objective);u(F),d(M!==null),c(F?br(F,R?.gender):null)}catch(R){q()&&h(R instanceof Error?R.message:"Erreur inattendue")}finally{q()&&b(!1)}},[t,p,S,j,C,A,D]);return o.useEffect(()=>{E()},[E]),nt({table:"training_sessions",userId:t,events:["INSERT","UPDATE"],onAny:()=>{E()}}),v!==t?{sessionsDone:0,sessionsTarget:0,objectiveLabel:null,trainingObjective:null,objectiveDeclared:!1,weekStart:ls(),loading:!!t,error:null,refetch:E}:{sessionsDone:n,sessionsTarget:r,objectiveLabel:i,trainingObjective:m,objectiveDeclared:x,weekStart:_,loading:g,error:f,refetch:E}}function hl(t){const[s,n]=o.useState([]),[a,r]=o.useState(!!t),[l,i]=o.useState(null),[c,m]=o.useState(void 0),u=o.useRef(!0),x=o.useRef(0),d=o.useRef(t);d.current=t,o.useEffect(()=>(u.current=!0,()=>{u.current=!1}),[]);const g=o.useCallback(async()=>{if(!u.current||d.current!==t)return;const b=++x.current,f=()=>u.current&&b===x.current&&d.current===t;if(m(t),n([]),r(!!t),i(null),!t){f()&&r(!1);return}try{const{data:h,error:v}=await $.from("training_sessions").select("id, session_type, scheduled_at, session_local_date, performed_local_date, completed_at, performed_at, created_at, status, exercises, warmup, cooldown, duration_min, calories_burned, adherence_pct, difficulty_rating, user_feedback, trajectory_focus").eq("user_id",t).eq("status","completed").order("completed_at",{ascending:!1,nullsFirst:!1}).order("created_at",{ascending:!1}).limit(100);if(!f())return;if(v)throw v;n(h??[])}catch(h){f()&&(n([]),i(h instanceof Error?h.message:"Historique Training indisponible"))}finally{f()&&r(!1)}},[t]);return o.useEffect(()=>{g()},[g]),nt({table:"training_sessions",userId:t,events:["INSERT","UPDATE"],onAny:()=>void g()}),c!==t?{sessions:[],loading:!!t,error:null,refetch:g}:{sessions:s,loading:a,error:l,refetch:g}}function Gs(t){const[s,n]=o.useState({}),[a,r]=o.useState(!0),[l,i]=o.useState(null),c=o.useRef(!0);o.useEffect(()=>(c.current=!0,()=>{c.current=!1}),[]);const m=t.join(","),u=o.useCallback(async()=>
57{if(t.length===0){r(!1);return}i(null);try{const x=[...new Set(t.filter(b=>b&&b.trim()))],{data:d,error:g}=await $.rpc("get_exercise_images_batch",{p_names:x});if(!c.current)return;if(g){i(g.message);return}if(d&&typeof d=="object"){const b=Array.isArray(d)?d.reduce((f,h)=>{const v=h;return v.name&&v.image_url&&(f[v.name]=v.image_url),f},{}):d;n(b)}}catch(x){c.current&&i(x instanceof Error?x.message:"Erreur inattendue")}finally{c.current&&r(!1)}},[m]);return o.useEffect(()=>{u()},[u]),{images:s,loading:a,error:l,refetch:u}}const gl=200,dt=new Map;function bl(t){const[s,n]=o.useState(null),[a,r]=o.useState(!1);return o.useEffect(()=>{if(!t){n(null);return}const l=dt.get(t.toLowerCase().trim());if(l){n(l);return}let i=!1;return r(!0),(async()=>{const{data:c,error:m}=await $.rpc("get_exercise_detail",{p_name:t});if(i)return;if(m||!c){n(null),r(!1);return}const u=c,x=t.toLowerCase().trim();if(dt.size>=gl){const d=dt.keys().next().value;d&&dt.delete(d)}dt.set(x,u),n(u),r(!1)})(),()=>{i=!0}},[t]),{detail:s,loading:a}}function yl(t){if(t.length<2)return"stable";const s=t.slice(0,Math.min(3,t.length)),n=t.slice(Math.min(3,t.length));if(n.length===0)return"stable";const a=s.reduce((i,c)=>i+c.score,0)/s.length,r=n.reduce((i,c)=>i+c.score,0)/n.length,l=a-r;return l>5?"improving":l<-5?"declining":"stable"}function os(t){return Rs(t)}function jl(t){const[s,n]=o.useState([]),[a,r]=o.useState(!!t),[l,i]=o.useState(null),[c,m]=o.useState(void 0),u=o.useRef(!0),x=o.useRef(0),d=o.useRef(t);d.current=t,o.useEffect(()=>(u.current=!0,()=>{u.current=!1,x.current+=1}),[]);const g=o.useCallback(async()=>{const b=t,f=++x.current,h=()=>u.current&&f===x.current&&d.current===b;if(m(b),n([]),r(!!b),i(null),!b){r(!1);return}try{const[v,w]=await Promise.all([$.from("video_references").select("exercise_name, exercise_id, form_score, score_history, recorded_at").eq("user_id",b).order("recorded_at",{ascending:!1}),$.from("video_analyses").select("analysis_result, exercise_matched_id, created_at").eq("user_id",b).eq("processing_status","completed").in("analysis_type",["exercise_form","live_form_check"]).order("created_at",{ascending:!1}).limit(100)]);if(!h())return;if(v.error)throw v.error;if(w.error)throw w.error;const _=v.data,T=w.data,N=new Map;for(const k of _||[]){const p=k,S=p.exercise_name||"";if(!S)continue;const j=N.get(S)||{exercise_id:p.exercise_id,scores:[]};j.scores.push({score:os(Number(p.form_score)||0),date:p.recorded_at});const C=p.score_history;if(C&&Array.isArray(C))for(const A of C)j.scores.push({score:os(A.score),date:A.date});N.set(S,j)}for(const k of T||[]){const p=k,S=p.analysis_result;if(!S?.exercise_identified||S.form_score==null)continue;const j=S.exercise_identified,C=N.get(j)||{exercise_id:p.exercise_matched_id,scores:[]};C.scores.push({score:os(S.form_score),date:p.created_at}),N.set(j,C)}const y=[];for(const[k,p]of N.entries()){const S=p.scores.filter(A=>A.score>0).sort((A,D)=>new Date(D.date).getTime()-new Date(A.date).getTime());if(S.length===0)continue;const j=[],C=new Set;for(const A of S){const D=A.date.slice(0,10);C.has(D)||(C.add(D),j.push(A))}y.push({exercise_name:k,exercise_id:p.exercise_id,latest_score:j[0].score,previous_score:j.length>1?j[1].score:null,score_history:j.slice(0,10).reverse(),analysis_count:S.length,trend:yl(j)})}y.sort((k,p)=>p.analysis_count-k.analysis_count),n(y)}catch(v){h()&&(n([]),i(v instanceof Error?v.message:"Impossible de charger la progression"))}finally{h()&&r(!1)}},[t]);return o.useEffect(()=>{g()},[g]),c!==t?{items:[],loading:!!t,error:null,refetch:g}:{items:s,loading:a,error:l,refetch:g}}const vl={knee_valgus:"Genoux",knee_cave:"Genoux",knee:"Genoux",hip_shift:"Hanches",hip_hike:"Hanches",hip:"Hanches",anterior_pelvic_tilt:"Bassin",posterior_pelvic_tilt:"Bassin",pelvi:"Bassin",shoulder_elevation:"Épaules",shoulder_protraction:"Épaules",shoulder_impingement:"Épaules",shoulder:"Épaules",spinal_flexion:"Colonne",lumbar_rounding:"Colonne",back_rounding:"Colonne",thoracic_kyphosis:"Colonne",spine:"Colonne",neck_forward:"Cou",head_forward:"Cou",ankle_collapse:"Chevilles",ankle:"Chevilles",wrist:"Poignets",elbow_flare:"Coudes",core_stability:"Tronc",balance:"Équilibre"};function _l(t){const s=t.toLowerCase().replace(/\s+/g,"_");for(const[n,a]of Object.entries(vl))if(s.includes(n))return a;return"Autre"}const Nl={Genoux:["Étirements quadriceps","Foam rolling IT band","Renforcement VMO"],Hanches:["Mobilité de hanche 9
570/90","Étirements des fléchisseurs de hanche","Pigeon stretch"],Bassin:["Bascule du bassin au sol","Cat-Cow","Mobilité pelvienne"],Épaules:["Dislocations à la bande","Stretch pectoraux porte","Wall slides"],Colonne:["Thoracic extensions sur foam roller","Jefferson curl léger","Cat-Cow"],Cou:["Chin tucks","Stretch du trapèze supérieur","Mobilité cervicale"],Chevilles:["Mobilité de cheville au mur","Stretch du mollet en dégressif","Cercles de cheville"],Tronc:["Dead bug","Planche latérale","Pallof press"],Équilibre:["Appui unilatéral","Marche talon-pointe","Exercices proprioceptifs"]};function wl(t){const[s,n]=o.useState({recurring:[],improving:[]}),[a,r]=o.useState(!!t),[l,i]=o.useState(null),[c,m]=o.useState(void 0),u=o.useRef(!0),x=o.useRef(0),d=o.useRef(t);d.current=t,o.useEffect(()=>(u.current=!0,()=>{u.current=!1,x.current+=1}),[]);const g=o.useCallback(async()=>{const f=t,h=++x.current,v=()=>u.current&&h===x.current&&d.current===f;if(m(f),n({recurring:[],improving:[]}),r(!!f),i(null),!f){r(!1);return}try{const w=new Date;w.setDate(w.getDate()-14);const{data:_,error:T}=await $.from("video_analyses").select("analysis_type, analysis_result, exercise_matched_id, created_at").eq("user_id",f).eq("processing_status","completed").in("analysis_type",["exercise_form","injury_risk","stretching","posture","mobility_assessment","live_form_check"]).gte("created_at",w.toISOString()).order("created_at",{ascending:!1}).limit(30);if(!v())return;if(T)throw T;const N=_||[];if(N.length===0){n({recurring:[],improving:[]});return}const y=new Map;for(const j of N){const C=j.analysis_result;if(!C?.errors)continue;const A=C.exercise_identified||"inconnu";for(const D of C.errors){if(D.severity==="minor")continue;const E=_l(D.type),L=`${E}::${D.type}`,q=y.get(L);q?(q.count++,q.exercises.add(A),j.created_at>q.last_seen&&(q.last_seen=j.created_at)):y.set(L,{zone:E,count:1,last_seen:j.created_at,exercises:new Set([A])})}}const k=[],p=[],S=new Date;S.setDate(S.getDate()-7);for(const[j,C]of y.entries()){const[A,D]=j.split("::");C.count>=2&&k.push({zone:A,error_type:D,count:C.count,last_seen:C.last_seen,exercises_affected:[...C.exercises]}),C.count>=2&&new Date(C.last_seen)<S&&p.push({zone:A,error_type:D,improved_since:C.last_seen,previous_count:C.count})}k.sort((j,C)=>C.count-j.count),n({recurring:k,improving:p})}catch(w){v()&&(n({recurring:[],improving:[]}),i(w instanceof Error?w.message:"Impossible de charger les points faibles"))}finally{v()&&r(!1)}},[t]);o.useEffect(()=>{g()},[g]);const b=f=>Nl[f]||[];return c!==t?{recurring:[],improving:[],loading:!!t,error:null,refetch:g,getStretchRecommendations:b}:{...s,loading:a,error:l,refetch:g,getStretchRecommendations:b}}const Pt=7.5;function vs(t){const s=t?.total_duration_min;return s!=null&&Number.isFinite(Number(s))&&Number(s)>0}function kl(t){const s=new Map;let n=0;for(const a of t??[]){const r=a?.sleep_date??`__sans_date_${n++}`,l=s.get(r);if(!l){s.set(r,a);continue}const i=vs(l),c=vs(a);(!i&&c||i&&c&&Number(a.total_duration_min)>Number(l.total_duration_min))&&s.set(r,a)}return[...s.values()]}function Sl(t){return t<=1?"none":t<=3?"mild":t<=5?"moderate":"severe"}function Cl(t,s=Pt){const n=Number.isFinite(s)&&s>0?s:Pt,a=kl(t??[]),r=a.filter(vs),l=r.length,i=a.length-l;if(l===0)return{debtHours:null,nightsTimed:0,nightsUntimed:i,avgHours:null,isMeasured:!1,severity:"unknown"};const c=r.reduce((u,x)=>u+Number(x.total_duration_min),0)/l/60,m=Math.max(0,Math.round((n-c)*7*10)/10);return{debtHours:m,nightsTimed:l,nightsUntimed:i,avgHours:Math.round(c*10)/10,isMeasured:!0,severity:Sl(m)}}const jn=7,St={debtHours:null,nightsTimed:0,nightsUntimed:0,avgHours:null,isMeasured:!1,severity:"unknown",nights:[],targetHours:Pt,trend:null};function Tl(t){const[s,n]=o.useState(St),[a,r]=o.useState(!!t),[l,i]=o.useState(null),[c,m]=o.useState(void 0),u=o.useRef(!0),x=o.useRef(0),d=o.useRef(t);d.current=t,o.useEffect(()=>(u.current=!0,()=>{u.current=!1}),[]);const g=o.useCallback(async()=>{if(!u.current||d.current!==t)return;const f=++x.current,h=()=>u.current&&f===x.current&&d.current===t;if(m(t),n(St),r(!!t),i(null),!t){if(!h())return;r(!1);return}try{const v=new Date().toISOString().split("T")[0],w=new Date;w.setUTCDate(w.getUTCDate()-(jn*2-1));const _=w.toISOString().split("T")[0],[T,N]=await Promise.all([$.from("user_profiles").select("target_sleep_hours").eq("user_id",t).maybeSingle(),Yr(_,v)]);if(!h())return;if(T.error)throw T.error;const y=Number(T.data?.target_sleep_hours)||Pt,k=Kr(N),p=Cl(k,y),S=new Map;for(const C of k){const A=S.get(C.sleep_date),D=C.total_duration_min!==null&&C.total_duration_min>0?C.total_duration_min:null;(A===void 0||A===null&&D!==null||A!==null&&D!==null&&D>A)&&S.set(C.sleep_date,D)}
57const j=[...S.entries()].sort((C,A)=>A[0].localeCompare(C[0])).slice(0,jn).reverse().map(([C,A])=>({date:C,actual_hours:A===null?null:Math.round(A/60*100)/100,target_hours:y}));n({...p,nights:j,targetHours:y,trend:El(j)})}catch(v){h()&&(n(St),i(v instanceof Error?v.message:"Erreur inattendue"))}finally{h()&&r(!1)}},[t]);return o.useEffect(()=>{g()},[g]),c===t?{...s,loading:a,error:l,refetch:g}:{...St,loading:!!t,error:null,refetch:g}}function El(t){const s=t.filter(i=>i.actual_hours!==null);if(s.length<4)return null;const n=Math.floor(s.length/2),a=i=>i.reduce((c,m)=>c+(m.target_hours-m.actual_hours),0)/i.length,r=a(s.slice(0,n)),l=a(s.slice(n));return l<r-.3?"improving":l>r+.3?"worsening":"stable"}const _s=28,Ct={acwr:null,zone:null,acuteLoad:null,chronicLoad:null,weeklyVolumes:[],sessionsLogged:0};function Rl(t){return t>1.5?"danger":t>1.3?"high":t>=.8?"optimal":"low"}function Al(t){const[s,n]=o.useState(Ct),[a,r]=o.useState(!!t),[l,i]=o.useState(null),[c,m]=o.useState(void 0),u=o.useRef(!0),x=o.useRef(0),d=o.useRef(t);d.current=t,o.useEffect(()=>(u.current=!0,()=>{u.current=!1}),[]);const g=o.useCallback(async()=>{if(!u.current||d.current!==t)return;const f=++x.current,h=()=>u.current&&f===x.current&&d.current===t;if(m(t),n(Ct),r(!!t),i(null),!t){if(!h())return;r(!1);return}try{const v=new Date;v.setDate(v.getDate()-_s);const w=v.toISOString().slice(0,10),[_,T]=await Promise.all([$.from("training_load_log").select("log_date, session_load").eq("user_id",t).gte("log_date",w).order("log_date",{ascending:!0}),$.from("daily_readiness").select("score_date, acwr_ratio, acute_load, chronic_load").eq("user_id",t).not("acwr_ratio","is",null).order("score_date",{ascending:!1}).limit(1).maybeSingle()]);if(!h())return;if(_.error)throw _.error;if(T.error)throw T.error;const N=_.data??[],y=T.data,k=y?.acwr_ratio,p=k==null?null:Number(k),S=new Map;for(const j of N)S.set(_n(j.log_date),(S.get(_n(j.log_date))??0)+Number(j.session_load??0));n({acwr:p,zone:p===null||!Number.isFinite(p)?null:Rl(p),acuteLoad:vn(y?.acute_load),chronicLoad:vn(y?.chronic_load),weeklyVolumes:[...S.entries()].map(([j,C])=>({week_start:j,total_load:C})).sort((j,C)=>j.week_start.localeCompare(C.week_start)),sessionsLogged:N.length})}catch(v){h()&&(n(Ct),i(v instanceof Error?v.message:"Erreur inattendue"))}finally{h()&&r(!1)}},[t]);return o.useEffect(()=>{g()},[g]),c===t?{...s,loading:a,error:l,refetch:g}:{...Ct,loading:!!t,error:null,refetch:g}}function vn(t){if(t==null)return null;const s=Number(t);return Number.isFinite(s)?s:null}function _n(t){const[s,n,a]=t.split("-").map(Number),r=new Date(Date.UTC(s,n-1,a)),l=r.getUTCDay();return r.setUTCDate(r.getUTCDate()-(l===0?6:l-1)),r.toISOString().slice(0,10)}function Gt(t){if(!t||typeof t!="object")return!1;const s=t;return s.name==="AbortError"||s.status==="unknown"||s.status==="context_unknown"||s.reason==="team_adaptation_unknown"}function Dl(t){const[s,n]=o.useState(null),[a,r]=o.useState(!!t),[l,i]=o.useState(null),[c,m]=o.useState(void 0),u=o.useRef(!0),x=o.useRef(null),d=o.useRef(0),g=o.useRef(t);g.current=t,o.useEffect(()=>(u.current=!0,()=>{u.current=!1}),[]);const b=o.useCallback(async()=>{if(!u.current||g.current!==t)return;const f=++d.current,h=()=>u.current&&f===d.current&&g.current===t;x.current?.abort();const v=new AbortController;if(x.current=v,m(t),n(null),r(!!t),i(null),!t){h()&&r(!1);return}try{const w=await As("calendar-context-engine",{method:"POST",body:{action:"get_today_profile",user_id:t},params:{action:"get_today_profile"},signal:v.signal,retry:!0});if(v.signal.aborted||!h())return;n(w.profile||null)}catch(w){if(v.signal.aborted||!h())return;n(null),i(w instanceof Error?w.message:"Erreur profil du jour")}finally{h()&&!v.signal.aborted&&r(!1)}},[t]);return o.useEffect(()=>(b(),()=>{x.current?.abort()}),[b]),c!==t?{profile:null,trusted:!1,loading:!!t,error:null,refetch:b}:{profile:s,trusted:Qr(s),loading:a,error:l,refetch:b}}const Ml=["distance_km","avg_pace_sec_per_km","avg_hr","max_hr","elevation_gain_m","laps","avg_power_w","avg_cadence_rpm","avg_split_sec_per_500m"];function J(t){const s=Number(t);return Number.isFinite(s)&&s>0?s:null}function Ll(t){return(Number.isInteger(t)?String(t):t.toFixed(1)).replace(".",",")}function Sa(t){const s=J(t);if(s===null)return null;if(s<60)return`${Math.round(s)} s`;const n=Math.round(s/60);if(n<60)return`${n} min`;const a=Math.floor(n/60),r=n%60;return r===0?`${a} h`:`${a} h ${String(r).padStart(2,"0")}`}function Ca(t){const s=Math.floor(t/60),n=Math.round(t%60);return n===60?{min:s+1,sec:0}:{min:s,sec:n}}function ql(t){const s=J(t);if(s===null)return null;const n=Ca(s);return`${n.min}'${String(n.sec).padStart(2,"0")}"/km`}function $l(t){const s=J(t);if(s===null)return null;const n=Ca(s);return`${n.min}'${String(n.sec).padStart(2,"0")}"/500m`}function Fl(t){const s=J(t?.distance_km),n=J(t?.duration_sec);return s===null||n===null?null:Math.round(n/s)}function Pl(t){const s=J(t?.laps),n=J(t?.pool_length_m);return s===null||n===null?null:Math.round(s*n/1e3*100)/100}function Ol(t){if(!t)return null;const s=[],n=J(t.distance_km)??Pl(t);n!==null&&s.push(n<1?`${Math.round(n*1e3)} m`:`${Ll(n)} km`);const a=Sa(t.duration_sec);a!==null&&s.push(a);const r=ql(J(t.avg_pace_sec_per_km)??Fl(t));r!==null&&s.push(r);const l=$l(t.avg_split_sec_per_500m);l!==null&&s.push(l);const i=J(t.laps);i!==null&&s.push(`${i} longueurs`);const c=J(t.elevation_gain_m);c!==null&&s.push(`${Math.round(c)} m D+`);const m=J(t.avg_power_w);m!==null&&s.push(`${Math.round(m)} W moy`);const u=J(t.avg_cadence_rpm);u!==null&&s.push(`${Math.round(u)} rpm`);const x=J(t.avg_hr);x!==null&&s.push(`${Math.round(x)} bpm moy`);const d=J(t.max_hr);return d!==null&&s.push(`${Math.round(d)} bpm max`),s.length>0?s.join(" · "):null}function Bl(t){return t?Ml.some(s=>J(t[s])!==null):!1}
57const Z={to_failure:"échec",dropset:"dégressif",warmup_set:"échauffement",bodyweight:"poids du corps",per_side:"par côté",unilateral_left:"côté gauche",unilateral_right:"côté droit",assisted:"assisté",superset:"superset"};function At(t){const s=Number(t);return Number.isFinite(s)&&s>0?s:null}function Ta(t){return(Number.isInteger(t)?String(t):t.toFixed(1).replace(/\.0$/,"")).replace(".",",")}function Ul(t){return t?.warmup_set!==!0}function Ea(t){return typeof t?.dropset_of=="number"&&Number.isFinite(t.dropset_of)}function zl(t){if(!t)return[];const s=[];t.warmup_set===!0&&s.push(Z.warmup_set),Ea(t)&&s.push(Z.dropset),t.to_failure===!0&&s.push(Z.to_failure);const n=At(t.rpe);n!==null&&n<=10&&s.push(`RPE ${Math.round(n)}`),t.unilateral==="left"?s.push(Z.unilateral_left):t.unilateral==="right"?s.push(Z.unilateral_right):t.unilateral==="both"&&t.per_side!==!0&&s.push(Z.per_side);const a=At(t.assisted_kg);return a!==null&&At(t.weight_kg)!==null&&s.push(`${Z.assisted} −${Ta(a)} kg`),typeof t.note=="string"&&t.note.trim()&&s.push(t.note.trim()),s}function Il(t){const s=Array.isArray(t)?t:[],n=s.filter(i=>Ea(i));if(n.length===0)return null;const a=n[0]?.dropset_of,l=[typeof a=="number"?s[a]:void 0,...n].map(i=>At(i?.weight_kg)).filter(i=>i!==null);return l.length<2?Z.dropset:`${Z.dropset} ${l.map(Ta).join("/")}`}function Nn(t){const s=typeof t=="string"?t.trim():"";if(!s)return null;const n=Z.superset;return`${n.charAt(0).toUpperCase()}${n.slice(1)} ${s}`}function Wl(t){const s=t.name||t.exercise||t.title||(typeof t=="string"?t:"")||"Exercice";let n=t.weight_kg,a,r,l=!1,i=!1,c,m,u=!1,x=!1,d=0,g=!1,b=[];if(Array.isArray(t.sets)){const f=t.sets;a=f.length;const h=f.map(y=>y.reps).filter(y=>y!=null);if(h.length>0)r=h.every(k=>String(k)===String(h[0]))?String(h[0]):h.map(String).join(", ");else{const y=f.find(p=>Bl(p)),k=y?Ol(y):null;if(k)r=k,g=!0;else{const p=f.map(S=>S.duration_sec).filter(S=>S!=null);r=p.length>0?Sa(p[0])??"":""}}const v=f.filter(y=>Ul(y)),w=v.length>0?v:f;if(d=f.length-v.length,n==null){const y=w.map(k=>k.weight_kg).filter(k=>k!=null&&k>0);y.length>0&&(n=Math.max(...y))}l=f.some(y=>y.to_failure===!0),i=f.some(y=>typeof y.dropset_of=="number");const _=f.map(y=>Number(y.rpe)).filter(y=>Number.isFinite(y)&&y>0&&y<=10);_.length>0&&(c=Math.round(Math.max(..._))),m=f.find(y=>y.unilateral)?.unilateral,u=w.some(y=>y.bodyweight===!0),x=w.some(y=>y.per_side===!0);const T=w.find(y=>(y.weight_kg??0)===(n??0)&&(y.weight_kg??0)>0)??w[0],N=Il(f);b=[...zl(T).filter(y=>y!==Z.dropset),...N?[N]:[]]}else a=t.sets||0,r=t.reps||t.duration||"";if(n==null&&t.weight_suggestion){const f=parseFloat(t.weight_suggestion);isNaN(f)||(n=f)}return{name:s,...typeof t.name_fr=="string"&&t.name_fr.trim()&&t.name_fr_of===t.name&&t.name===s?{name_fr:t.name_fr.trim(),name_fr_of:s}:{},sets:a,reps:r,rest_seconds:t.rest_seconds||0,weight_kg:n,previous_weight_kg:t.previous_weight_kg,notes:t.notes,image_url:t.image_url,muscle_groups:t.muscle_groups||t.muscle_targets,target_rpe:t.target_rpe,...l?{to_failure:!0}:{},...i?{is_dropset:!0}:{},...c!=null?{actual_rpe:c}:{},...m?{unilateral:m}:{},...u?{bodyweight:!0}:{},...x?{per_side:!0}:{},...d>0?{warmup_sets:d}:{},...g?{is_endurance:!0}:{},...b.length>0?{qualifiers:b}:{},...t.superset_group?{superset_group:t.superset_group}:{}}}function tt(t){const s=Array.isArray(t)?t:t&&typeof t=="object"?[t]:[];return s.length===0?[]:s.map(Wl)}async function Ys(t,s,n){const{data:a,error:r}=await t.from("training_sessions").select("id,status,completed_at,session_local_date").eq("id",n).eq("user_id",s).maybeSingle();if(r)throw r;if(!a)throw new Error("Séance introuvable. Actualise Training.");return a}async function Hl(t,s,n,a,r=new Date().toISOString(),l={}){const i=await Ys(t,s,n);if(i.status===a)return i;if(["completed","cancelled","skipped"].includes(i.status??""))throw new Error(i.status==="skipped"?"Une séance passée ne se rouvre pas.":"Cette séance est déjà clôturée. Actualise Training.");const c=t.from("training_sessions").update({status:a,...a==="completed"?{completed_at:i.completed_at??r}:{}}).eq("id",n).eq("user_id",s).eq("status",i.status),{data:m,error:u}=await c.select("id,status,completed_at").maybeSingle();if(u)throw u;if(!m||m.status!==a)throw new Error("Mise à jour non confirmée. Actualise Training.");return m}async function Vl(t,s,n,a={}){let r,l;const i=typeof n=="number"&&Number.isFinite(n)&&n>0?Math.round(n*60):null;try{r=await As("post-session-recap",{method:"POST",expectedUserId:t,body:{user_id:t,training_session_id:s,session_type:"training",completion_source:"manual_completion",...i?{duration_seconds:i,duration_source:"planned"}:{},...a.background?{effects_mode:"background"}:{}},retry:!1,timeoutMs:6e4})}catch(x){l=x}if((await Ys($,t,s)).status!=="completed")throw l??new Error("La clôture reste à confirmer. Réessaie dans un instant.");const m=r?.completion,u=m?.training_session_id===s&&m.session_status==="completed"?m.effects_status:"unknown";return{sessionId:s,effects:u}}async function Gl(t){const{error:s}=await $.rpc("infer_my_performed_muscle_load_for_completed_session",{p_session_id:t});return s?(ze.error("[training.completion] manual heat inference failed",s,{reason:"heat_inference_failed",sessionId:t}),!1):!0}async function Yl(t,s){let n,a;try{n=await As("training-session-skip",{method:"POST",expectedUserId:t,body:{training_session_id:s},retry:!1,timeoutMs:3e4})}catch(l){a=l}if((await Ys($,t,s)).status!=="skipped")throw a??new Error("La séance n'a pas pu être passée. Réessaie dans un instant.");return{sessionId:s,delivery:n?.success===!0?n.message_delivery??"failed":"failed",reason:n?.message_reason??null}}const Kl={markDone:null,video:null,skip:null},Yt="Le bilan se prépare. Réessaie dans un instant.";function Ra({session:t,todayLocal:s,timezone:n,completionFlagLoading:a}){if(!t)return Kl;const r=Jl(t,s,n);return r?{markDone:r,video:null,skip:r}:{markDone:a?Yt:null,video:null,skip:null}}function Jl(t,s,n){if(t.status==="completed"){const a=Vt(t,n);return a?a===s?"Séance déjà faite aujourd’hui.":`Séance déjà faite : ${at(a)}`:"Séance déjà faite."}return t.status==="skipped"?"Séance passée : elle ne se rouvre pas.":t.status==="cancelled"?"Séance annulée : elle ne se rouvre pas.":null}function cs(t){return Array.isArray(t)?t:t&&typeof t=="object"?[t]:[]}function Zl(t){return t==="pending"||t==="in_progress"?"scheduled":t}function Ql(t){return{...t,status:Zl(t.status),exercises:tt(t.exercises),warmup:tt(t.warmup||[]),cooldown:tt(t.cooldown||[]),user_feedback:t.user_feedback??void 0,difficulty_rating:t.difficulty_rating??void 0,adherence_pct:t.adherence_pct??void 0}}function Xl(t,s,n=!1,a=!1,r=[]){const{program:l,sessions:i,loading:c,error:m,refresh:u,refetch:x}=cl(t,s),d=Ds(),[g,b]=o.useState({}),f=o.useRef(new Set),h=o.useMemo(()=>{const N=new Set,y=k=>
57{tt(cs(k.exercises)).forEach(p=>N.add(p.name)),tt(cs(k.warmup)).forEach(p=>N.add(p.name)),tt(cs(k.cooldown)).forEach(p=>N.add(p.name))};return i.forEach(k=>y(k)),r.forEach(y),N.delete(""),Array.from(N)},[i,r]),{images:v,loading:w}=Gs(h),_=async(N,y,k)=>{if(!t||f.current.has(N))return!1;f.current.add(N);try{if(y==="completed"&&a)return ze.warn("[training.tab.session.update] completion refused while the flag loads",{reason:"completion_flag_loading",sessionId:N}),d.warning(Yt),!1;if(y==="completed"&&(n||k?.raid)){const p=await Vl(t,N,i.find(S=>S.id===N)?.duration_min??null,{background:k?.background});return b(S=>({...S,[N]:p.effects})),p.effects==="complete"?d.success("Séance et bilan enregistrés."):k?.background&&p.effects==="pending"||d.warning("Séance enregistrée. Le bilan et les récompenses restent à vérifier."),k?.background||u(),!0}return y==="skipped"?((await Yl(t,N)).delivery==="sent"?d.success("Séance passée. Alloy te propose la suite dans son message."):d.warning("Séance passée. Le message d’Alloy reste à confirmer."),u(),!0):(await Hl($,t,N,y,void 0,{reopenSkippedOn:k?.todayLocal}),y==="completed"&&!k?.background&&d.success("Séance marquée comme terminée !"),k?.background||u(),!0)}catch(p){return ze.error("[training.tab.session.update] threw",p,{sessionId:N,newStatus:y}),d.error("Mise à jour non confirmée. Actualise puis réessaie."),!1}finally{f.current.delete(N)}},T=i.find(N=>N.scheduled_at&&js(new Date(N.scheduled_at))||!N.scheduled_at&&N.status!=="completed"&&N.status!=="cancelled");return{program:l,sessions:i,loading:c,error:m,refresh:u,refetch:x,exerciseImages:v,imagesLoading:w,handleStatusChange:_,completionEffects:g,todaySession:T,transformSession:Ql}}const eo={healthkit:"Apple Santé",fitbit:"Fitbit",withings:"Withings"},to={running:"Course",run:"Course",walking:"Marche",walk:"Marche",cycling:"Vélo",cycle:"Vélo",swimming:"Natation",swim:"Natation",strength:"Renforcement",training:"Entraînement"};function so({userId:t,timezone:s}){const{data:n,error:a,refresh:r}=Hr(t,s),l=Jr(n.flatMap(i=>i.workouts??[]));return a?e.jsxs("div",{className:"text-sm text-white/60",role:"status",children:[a," ",e.jsx(Le,{onRetry:()=>void r(),className:"ml-1"})]}):l.length?e.jsxs("section",{className:"space-y-3","aria-label":"Séances de tes appareils",children:[e.jsx("h3",{className:"text-base font-semibold",children:"Séances de tes appareils"}),e.jsx("p",{className:"text-sm text-white/60",children:"Alloï en tient compte dans ton coaching et ta récupération."}),e.jsx("ul",{className:"space-y-2",children:l.slice(0,10).map(i=>e.jsxs("li",{className:"rounded-2xl border border-white/10 bg-white/5 px-4 py-3",children:[e.jsxs("div",{className:"flex justify-between gap-3",children:[e.jsx("span",{children:to[i.activity_type]??"Séance importée"}),e.jsxs("span",{children:[Math.round(i.duration_min)," min"]})]}),e.jsxs("p",{className:"mt-1 text-xs text-white/60",children:[eo[i.source]??"Appareil connecté"," ·"," ",new Date(i.end_at).toLocaleString("fr-FR",{timeZone:s??void 0,day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"})]})]},`${i.source}:${i.external_id}`))})]}):null}function no(t){const s=Xr(t);if(/\b(hypertrophie|hypertrophy|volume)\b/.test(s))return"hypertrophy_full_body";if(/\b(recuperation|recovery|repos|rest)\b/.test(s))return"recovery";const n=fa(t);return n==="mobility"?"mobility":n==="recovery"||n==="rest"?"recovery":n==="hiit"||n==="cardio"||n==="running"||n==="cycling"||n==="swimming"||n==="walking"?"conditioning":"strength_full_body"}const wn={push:{label:re.push,icon:Ci,forgeTheme:"ember"},pull:{label:re.pull,icon:Ni,forgeTheme:"verdant"},legs:{label:re.legs,icon:Je,forgeTheme:"flame"},upper:{label:re.upper,icon:Q,forgeTheme:"aqua"},lower:{label:re.lower,icon:Je,forgeTheme:"rose"},full_body:{label:re.full_body,icon:Q,forgeTheme:"ember"},cardio:{label:"Cardio",icon:Mt,forgeTheme:"flame"},hiit:{label:"HIIT",icon:Ms,forgeTheme:"gold"},mobility:{label:"Mobilité",icon:nl,forgeTheme:"verdant"},rest:{label:"Repos",icon:ka,forgeTheme:"charcoal"},strength:{label:re.strength,icon:Q,forgeTheme:"ember"},running:{label:re.running,icon:Si,forgeTheme:"flame"},cycling:{label:re.cycling,icon:_i,forgeTheme:"aqua"},swimming:{label:re.swimming,icon:il,forgeTheme:"aqua"},walking:{label:re.walking,icon:Je,forgeTheme:"verdant"},recovery:{label:re.recovery,icon:Mt,forgeTheme:"rose"},jambes:{label:re.legs,icon:Je,forgeTheme:"flame"},"haut du corps":{label:"Haut du corps",icon:Q,forgeTheme:"aqua"},musculation:{label:"Musculation",icon:Q,forgeTheme:"ember"}};function qe(t){const s=t?wn[t]:void 0;if(s)return s;const n=fa(t),a=n?wn[n]:void 0;return{label:mi(t)??ei(t),icon:a?.icon??ue,forgeTheme:a?.forgeTheme??"steel"}}const kn={scheduled:{label:"À faire",icon:ka,forgeTheme:"steel",bgColor:"bg-slate-500/20"},completed:{label:"Faite",icon:Ie,forgeTheme:"verdant",bgColor:"bg-success/20"},skipped:{label:"Passée",icon:Bt,forgeTheme:"flame",bgColor:"bg-error/20"}},Sn={gym:"ember",home:"verdant",outdoor:"aqua",park:"verdant",hotel:"gold",other:"steel"},ao={barbell:"ember",dumbbell:"ember",machine:"aqua",cable:"aqua",cardio:"flame",bodyweight:"verdant",band:"rose",kettlebell:"gold",accessory:"steel"},le={leaderOnlyInvite:"Seul le chef actuel peut créer et partager le lien de l’escouade.",raidAlreadyRunning:"Un raid est déjà en cours dans ton escouade.",inviteFirst:"Invite au moins une personne avant de lancer un raid.",noShareableExercise:"Cette séance ne contient aucun exercice partageable.",noTeam:"Crée ou rejoins d’abord une escouade.",noSessionYet:"Génère ou planifie une séance : la proposition s’ouvrira lorsqu’elle sera enregistrée.",sessionNoLongerScheduled:"La séance du jour n’est plus simplement planifiée et ne peut pas être proposée."},ro={strength_full_body:{label:"Force",description:"Même ordre d’exercices, avec une adaptation personnelle des charges et répétitions."},hypertrophy_full_body:{label:"Renforcement",description:"Même trame pour le groupe, avec un volume adapté séparément à chacun."},conditioning:{label:"Conditionnement",description:"Circuit ou cardio commun, avec durée et intensité individuelles."},mobility:{label:"Mobilité",description:"Mêmes mouvements de mobilité, avec des amplitudes et variantes personnelles."},recovery:{label:"Récupération",description:"Séance douce partagée, sans imposer le même niveau d’effort."}};function io({open:t,onClose:s,team:n,source:a,activeProposal:r,onConfirm:l,onRefresh:i,onViewRaid:c}){const[m,u]=o.useState(!1),x=o.useRef(!1),[d,g]=o.useState(!1),b=o.useRef(null),[f,h]=o.use
57State(!1),[v,w]=o.useState(null),_=a?.id,T=a?.sessionType,N=no(T??""),y=N==="conditioning",k=!!(a&&a.exerciseNames.length===0&&!y);o.useEffect(()=>{!t||!_||!T||(x.current=!1,u(!1),g(b.current===_),h(!1),w(null))},[t,_,T]);const p=()=>{x.current||s()},S=async()=>{if(!(!a||x.current||d||r)){if(a.status!=="scheduled"){w("Cette séance n’est plus planifiée et ne peut pas être proposée.");return}if(a.exerciseNames.length===0&&!y){w(le.noShareableExercise);return}x.current=!0,u(!0),w(null);try{await l(a.id,N),h(!0)}catch(E){if(Gt(E)){b.current=a.id,g(!0);let L=!1;try{L=await i()}catch{L=!1}L&&(b.current=null),g(!L),w(L?"Le résultat n’était pas confirmé. L’état de l’escouade a été actualisé : vérifie la proposition avant de recommencer.":"Le résultat n’est pas confirmé et l’escouade n’a pas pu être actualisée. N’envoie pas une seconde proposition pour le moment.")}else w(E instanceof Error?E.message:"La proposition n’a pas été confirmée.")}finally{x.current=!1,u(!1)}}},j=f||r,C=Math.max(n.member_count,n.members.length),A=qe(a?.sessionType).label,D=ro[N];return e.jsx(ke,{open:t,onClose:p,title:"Proposer ce training",eyebrow:n.name,maxWidthClassName:"sm:max-w-md",footer
57:j?e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsx(P,{type:"button",onClick:p,variant:"secondary",children:"Fermer"}),e.jsx(P,{type:"button",onClick:c,variant:"primary",children:"Voir le raid"})]}):e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsx(P,{type:"button",disabled:m,onClick:p,variant:"secondary",children:"Annuler"}),e.jsx(P,{type:"button",disabled:m||d||!a||a.status!=="scheduled"||C<2||k,onClick:()=>void S(),variant:"primary",children:m?"Publication…":"Lancer le raid"})]}),children:e.jsxs("div",{className:"space-y-5 p-4",children:[e.jsxs("div",{className:"flex items-start gap-3 rounded-2xl border border-cyan-300/15 bg-cyan-300/[0.05] p-4",children:[e.jsx(Q,{className:"mt-0.5 h-5 w-5 flex-none text-cyan-300","aria-hidden":"true"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"font-bold text-text-primary",children:A}),e.jsxs("p",{className:"font-mono-numbers mt-1 text-sm text-text-secondary",children:[a?.exerciseNames.length===0&&y?"Trame cardio commune":`${a?.exerciseNames.length??0} exercice${(a?.exerciseNames.length??0)>1?"s":""}`,a?.durationMinutes?` · ${a.durationMinutes} min`:""]})]})]}),a&&a.exerciseNames.length>0&&e.jsx("ol",{className:"space-y-2","aria-label":"Exercices partagés dans l’ordre",children:a.exerciseNames.map((E,L)=>e.jsxs("li",{className:"flex min-h-11 items-center gap-3 rounded-xl border border-white/[0.08] bg-white/[0.03] px-3 py-2 text-sm",children:[e.jsx("span",{className:"font-mono-numbers flex h-7 w-7 flex-none items-center justify-center rounded-full bg-white/[0.08] text-xs font-bold text-cyan-200","aria-hidden":"true",children:L+1}),e.jsx("span",{children:E})]},`${L}-${E}`))}),!j&&e.jsxs("section",{"aria-labelledby":"team-training-derived-style",className:"rounded-2xl border border-white/[0.08] bg-white/[0.03] p-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.12em] text-text-tertiary",children:"Style déduit de ta séance"}),e.jsx("h3",{id:"team-training-derived-style",className:"mt-1 font-bold text-text-primary",children:D.label}),e.jsxs("p",{className:"mt-1 text-xs leading-relaxed text-text-secondary",children:[D.description," Le serveur vérifie le type et les exercices réellement enregistrés avant publication."]})]}),C<2&&e.jsx("p",{role:"alert",className:"text-sm text-error",children:le.inviteFirst}),k&&e.jsx("p",{role:"alert",className:"text-sm text-error",children:le.noShareableExercise}),j&&e.jsx("div",{role:"status",className:"rounded-2xl border border-success/20 bg-success/10 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Lt,{className:"mt-0.5 h-5 w-5 flex-none text-success","aria-hidden":"true"}),e.jsx("p",{className:"text-sm leading-relaxed text-text-secondary",children:"Le raid est lancé pour ton escouade. Les notifications éventuelles sont gérées séparément selon les préférences de chaque membre."})]})}),v&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{role:"alert",className:"text-sm leading-relaxed text-error",children:v}),d&&e.jsx(P,{type:"button",disabled:m,onClick:()=>{x.current||(x.current=!0,u(!0),(async()=>{try{const E=await i();E&&(b.current=null),g(!E),w(E?"L’état de l’escouade a été actualisé. Vérifie-le avant de continuer.":"L’escouade n’a pas pu être actualisée. Aucune nouvelle proposition n’est autorisée pour le moment.")}catch{g(!0),w("L’escouade n’a pas pu être actualisée. Aucune nouvelle proposition n’est autorisée pour le moment.")}finally{x.current=!1,u(!1)}})())},variant:"secondary",children:"Actualiser l’escouade"})]})]})})}function lo({userId:t,profile:s,onDefineTarget:n,qualitative:a=!1,refreshToken:r}){const{sessionsDone:l,sessionsTarget:i,objectiveLabel:c,loading:m,error:u,refetch:x}=fl(t,s),d=xi(t),g=d.refetch,b=o.useRef(r);o.useEffect(()=>{b.current!==r&&(b.current=r,x(),g())},[r,x,g]);const f=Es(),h=i>0,v=pi(d.week?.items??[],Ls(d.timezone)),w=h&&l>=i,_=Math.max(0,i-l),T=d.enabled&&!!d.week,N=ti(T?t:void 0,d.timezone,d.window),y=d.window?.dates,k=d.window?.startDate,p=o.useMemo(()=>fi({hasPreparedPlan:!!d.week,dates:y??[],timezone:d.timezone,items:d.week?.items,training:d.training,profiles:N.days,pastFrom
57:k}),[y,k,d.timezone,d.week,d.training,N.days]),[S,j]=o.useState(!1),[C,A]=o.useState(null),[D,E]=o.useState(null),L=o.useMemo(()=>N.days.find(M=>M.date===D)??null,[N.days,D]),q=o.useMemo(()=>d.week?.items.find(M=>M.local_date===D&&M.kind==="training"&&M.status==="planned")??null,[d.week,D]),R=o.useCallback(async M=>{if(!q)return;await d.mutate({action:"change",item_id:q.id,expected_version:q.version,target_time:M.start})&&E(null)},[q,d]),B=o.useCallback(async()=>{if(!q)return;await d.mutate({action:"change",item_id:q.id,expected_version:q.version,operation:"remove"})&&E(null)},[q,d]),O=o.useCallback((M,F)=>{!M.training||d.saving||M.training.itemId===null||M.training.version===null||d.mutate({action:"change",item_id:M.training.itemId,expected_version:M.training.version,option_key:F})},[d]),G=o.useCallback(M=>{const{name:F,num:K}=fn(M.date);f(Ze(`Prépare ma séance du ${F.toLowerCase()} ${K}${M.training?.focus?` : ${M.training.focus.label.toLowerCase()}`:""}`))},[f]),z=o.useCallback(M=>f(Ze(M)),[f]),Y=p.days.filter(M=>M.training&&M.training.status!=="cancelled"),X=o.useMemo(()=>hi(p.days),[p.days]),ae=d.enabled&&d.week?gi(y):null,I=d.enabled&&e.jsxs("div",{className:"mt-3 flex flex-col gap-2.5 border-t border-white/[0.08] pt-3","aria-label":"Créneaux sportifs prévus",children:[d.week?e.jsxs(e.Fragment,{children:[!S&&Y.length>0&&e.jsx("ul",{role:"list","aria-label":"Tes séances de la semaine",className:"flex flex-wrap gap-1.5",children:Y.map(M=>e.jsxs("li",{className:"inline-flex flex-none items-center gap-1.5 whitespace-nowrap rounded-full border border-white/10 bg-black/20 px-2.5 py-[5px] text-[11px] font-semibold text-text-primary",children:[e.jsxs("span",{className:"font-mono-numbers text-amber-300",children:[fn(M.date).name.slice(0,3).toLowerCase(),M.training?.startTime?` ${M.training.startTime}`:""]}),M.training?.focus?.label??"Séance"]},M.date))}),X&&e.jsx(bi,{day:X,theme:"training",qualitative:a,onOpen:M=>{A(M.date),j(!0)}}),e.jsx(zs,{summary:"Voir mes séances de la semaine",label:"mes séances de la semaine",accent:"text-amber-300",open:S,onToggle:j,footer:e.jsx(P,{type:"button",variant:"secondary",size:"sm",className:"flex-1",onClick:()=>z("Pour ma semaine, je veux : "),icon:e.jsx(Xe,{"aria-hidden":"true",className:"h-4 w-4 flex-none"}),children:"Modifier avec Alloy"}),children:e.jsx(yi,{calendarHealth:d.calendarHealth,reviewIssues:d.reviewIssues,theme:"training",state:N.loading&&d.loading?"loading":d.week.status==="partial"?"partial":"ready",days:p.days,pastDays:p.pastDays,selected:C,onSelect:A,qualitative:a,notice:null,saving:d.saving,settings:d.settings,suggestions:d.week.suggestions,isNextWeek:d.window?.isNextWeek??!1,actions:{onReview:()=>{d.review(!0)},onChooseFocus:O,onPrepareSession:G,onPickSlot:d.calendarConnected?E:void 0,onAlloy:z,onResolveSuggestion:(M,F)=>{d.mutate({action:"resolve",suggestion_id:M,decision:F})}}})})]}):d.calendarConnected===!1?e.jsxs("div",{className:"space-y-2",children:[e.jsx(P,{type:"button",variant:"primary",fullWidth:!0,onClick:()=>f(Ze("Organise ma semaine avec mes séances")),icon:e.jsx(Xe,{"aria-hidden":"true",className:"h-4 w-4 flex-none"}),children:"Préparer ma semaine"}),e.jsx(P,{type:"button",variant:"secondary",fullWidth:!0,onClick:()=>f("/settings/integrations/calendar"),icon:e.jsx(va,{"aria-hidden":"true",className:"h-4 w-4 flex-none"}),children:"Connecter mon agenda"})]}):e.jsx(P,{type:"button",variant:"primary",fullWidth:!0,onClick:()=>f(Ze("Organise ma semaine avec mes séances")),icon:e.jsx(Xe,{"aria-hidden":"true",className:"h-4 w-4 flex-none"}),children:"Préparer ma semaine"}),d.notice&&e.jsx("p",{role:"status",className:"text-sm text-text-secondary",children:d.notice}),d.error&&e.jsx("p",{role:"alert",className:"text-sm text-error",children:d.error}),e.jsx(si,{open:L!==null,onClose:()=>E(null),day:L,timezone:d.timezone,saving:d.saving,error:d.error,neededMin:q?.duration_min??d.settings?.duration_min??null,onChooseSlot:R,onChooseRest:B})]});return e.jsxs(Ue,{loading:m,error:u,loadingFallback:e.jsx(yr,{}),onRetry:x,errorTitle:"Rythme hebdomadaire indisponible",errorMessage:"Impossible de charger ton rythme de semaine pour le moment.",children:[h?e.jsx(Ti,{domain:"training",eyebrow:ji({hasPlan:d.enabled&&!!d.week,partial:d.week?.status==="partial",isNextWeek:d.window?.isNextWeek,qualitative:a,goalReached:w,peri
57od:ae}),title:a?"Ton rythme de semaine":`${i} séances`,current:l,target:i,planned:v,unit:`coup${l>1?"s":""} porté${l>1?"s":""}`,helper:a?"Tes séances s’adaptent à ta semaine.":w?"Tout ce qui suit est du bonus.":v>l?`Il te reste ${_} coup${_>1?"s":""}, dont ${v-l} déjà calé${v-l>1?"s":""}.`:`Il te reste ${_} coup${_>1?"s":""}.`,rewardLabel:c??"→ ta carte du dimanche",onEdit:n,qualitative:a,qualitativeLabel:"Ta régularité se construit à ton rythme.",children:I}):e.jsx(st,{density:"inline",state:"contextual_empty",icon:Ut,theme:"gold",title:"Choisis ton rythme de semaine",description:l>0?"Tes séances sont bien enregistrées. Définis simplement le rythme qui te convient.":"Définis une fréquence réaliste pour suivre ta semaine sans pression.",action:n?e.jsx("button",{type:"button",onClick:n,className:"inline-flex min-h-11 items-center rounded-lg px-3 py-2 text-sm font-semibold text-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent",children:"Choisir"}):void 0}),!h&&I]})}function oo(t,s){const[n,a]=o.useState([]),[r,l]=o.useState(!!t),[i,c]=o.useState(null),[m,u]=o.useState(void 0),x=o.useRef(!0),d=o.useRef(0),g=o.useRef(t);g.current=t,o.useEffect(()=>(x.current=!0,()=>{x.current=!1}),[]);const b=o.useCallback(async()=>{if(!x.current||g.current!==t)return;const f=++d.current,h=()=>x.current&&f===d.current&&g.current===t;if(u(t),a([]),l(!!t),c(null),!t){h()&&l(!1);return}const v=new Date(Date.now()-60*864e5).toISOString(),w=s??"00000000-0000-0000-0000-000000000000";try{const{data:_,error:T}=await $.from("training_sessions").select("id, session_type, scheduled_at, session_local_date, performed_local_date, completed_at, performed_at, created_at, status, duration_min, calories_burned, exercises, warmup, cooldown, user_feedback, difficulty_rating, trajectory_focus").eq("user_id",t).or(`completed_at.gte.${v},and(completed_at.is.null,scheduled_at.gte.${v}),and(completed_at.is.null,scheduled_at.is.null,created_at.gte.${v})`).or(`training_plan_id.is.null,training_plan_id.neq.${w}`).order("completed_at",{ascending:!1,nullsFirst:!1}).limit(50);if(!h())return;if(T){a([]),c(T.message);return}a(_??[])}catch(_){h()&&(a([]),c(_ instanceof Error?_.message:"Erreur inattendue"))}finally{h()&&l(!1)}},[t,s]);return o.useEffect(()=>{b()},[b]),nt({table:"training_sessions",userId:t,events:["INSERT","UPDATE"],onAny:()=>{b()}}),m!==t?{sessions:[],loading:!!t,error:null,refetch:b}:{sessions:n,loading:r,error:i,refetch:b}}const co="id, session_type, scheduled_at, session_local_date, performed_local_date, completed_at, performed_at, created_at, status, duration_min, calories_burned, exercises, warmup, cooldown, user_feedback, difficulty_rating, trajectory_focus";function uo(t,s){const[n,a]=o.useState(null),[r,l]=o.useState(!!t),[i,c]=o.useState(null),[m,u]=o.useState(void 0),x=t?`${t}:${s}`:void 0,d=o.useRef(!0),g=o.useRef(0),b=o.useRef(x);b.current=x,o.useEffect(()=>(d.current=!0,()=>{d.current=!1}),[]);const f=o.useCallback(async()=>{if(!d.current||b.current!==x)return!1;const h=++g.current,v=()=>d.current&&h===g.current&&b.current===x;if(u(x),l(!!t),c(null),!t)return v()&&(a(null),l(!1)),!0;const{data:w,error:_}=await $.from("training_sessions").select(co).eq("user_id",t).eq("status","scheduled").gt("session_local_date",s).order("session_local_date",{ascending:!0}).order("scheduled_at",{ascending:!0,nullsFirst:!1}).limit(1).maybeSingle();return v()?(l(!1),_?(a(null),c(_.message),ze.warn("[training.next] prochaine séance illisible",{reason:"next_session_unreadable",error:_.message}),!1):(a(w??null),!0)):!1},[x,t,s]);return o.useEffect(()=>{f()},[f]),nt({table:"training_sessions",userId:t,events:["INSERT","UPDATE"],onAny:()=>{f()}}),m!==x?{session:null,loading:!!t,error:null,refetch:f}:{session:n,loading:r,error:i,refetch:f}}function Kt({label:t,message:s,icon:n="training",variant:a="secondary"}){return e.jsx(Wt,{label:t,message:s,icon:n,variant:a,className:"w-full"})}function Aa(t){return t>=80?"Excellente récupération":t>=65?"Bonne récupération":t>=50?"Récupération correcte":t>=40?"Récupération incomplète":"Repos recommandé"}function mo({userId:t,readiness:s,sleep:n,load:a,onDetails:r}){const l=s.today??s.latest,i=ha(s.signals),c=i.filter(u=>u.status==="measured").length,m=n.nights[n.nights.length-1];return e.jsxs("div",{className:"space-y-4 px-4 pb-5 pt-2",children:[e.jsx(Me,{label:"Récupération",resetKeys:[t],children:e.jsxs("div",{className:"flex items-center gap-3 border-y border-white/[0.08] py-4","aria-label":"Récupération",children:[e.jsxs("div",{className:"relative flex h-16 w-16 flex-none items-center justify-center",children:[e.jsxs("svg",{className:"absolute inset-0 h-full w-full -rotate-90",viewBox:"0 0 64 64","aria-hidden":"true",children:[e.jsx("circle",{cx:"32",cy:"32",r:"28",fill:"none",stroke:"currentColor",strokeWidth:"4",className:"text-white/10"}),l&&c>0&&!s.error&&e.jsx("circle",{cx:"32",cy:"32",r:"28",fill:"none",stroke:"currentColor",strokeWidth:"4",strokeLinecap:"round",strokeDasharray:`${Math.min(100,Math.max(0,l.score))*1.76} 176`,className:"text-amber-300"})]}),l&&c>0&&!s.error?e.jsxs("span",{className:"text-lg font-bold font-mono-numbers text-amber-200",children:[Math.round(l.score),e.jsx("span",{className:"sr-only",children:" sur 100"})]}):e.jsx(na,{className:"h-6 w-6 text-text-secondary","aria-hidden":"true"})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.12em] text-text-secondary",children:"Récupération"}),e.jsx("p",{className:"mt-1 text-sm font-semibold",children:s.loading?"Lecture de ton état…":s.error?"Lecture indisponible":l&&c>0?Aa(l.score):"À construire avec ton ressenti"}),!s.loading&&!s.error&&e.jsxs("p",{className:"mt-1 text-xs text-text-secondary",children:[l?`${s.today?"Aujourd’hui":`Dernière mesure : ${l.date}`} · `:"",c," ",c>1?"signaux":"signal"," renseigné",c>1?"s":""," ","sur ",i.length]}),s.error&&e.jsx(Le,{onRetry:()=>void s.refetch(),className:"mt-1"})]})]})}),e.jsxs("div",{className:"grid grid-cols-2 divide-x divide-white/[0.08]",children:[e.jsx(Me,{label:"Sommeil",resetKeys:[t],children:e.jsxs("div",{className:"pr-3",children:[e.jsxs("p",{className:"flex items-center gap-2 text-xs text-text-secondary",children:[e.jsx(ft,{className:"h-4 w-4 text-sky-200","aria-hidden":"true"}),"Sommeil"]}),e.jsx("p",{className:"mt-2 text-sm font-semibold",children:n.loading?"Lecture…":n.error?"Indisponible":m?.actual_hours!=null?`${m.actual_hours.toLocaleStr
57ing("fr-FR",{maximumFractionDigits:1})} h`:m?"Nuit notée sans durée":"Aucune nuit renseignée"}),m&&!n.error&&e.jsxs("p",{className:"mt-1 text-[11px] text-text-secondary",children:["Nuit du ",m.date]}),n.error&&e.jsx(Le,{onRetry:()=>void n.refetch(),className:"mt-1"})]})}),e.jsx(Me,{label:"Charge",resetKeys:[t],children:e.jsxs("div",{className:"pl-3",children:[e.jsxs("p",{className:"flex items-center gap-2 text-xs text-text-secondary",children:[e.jsx(ue,{className:"h-4 w-4 text-amber-200","aria-hidden":"true"}),"Charge"]}),e.jsx("p",{className:"mt-2 text-sm font-semibold",children:a.loading?"Lecture…":a.error?"Indisponible":a.acwr===null?"Pas assez de mesures":`Ratio ${a.acwr.toLocaleString("fr-FR",{maximumFractionDigits:2})}`}),e.jsx("p",{className:"mt-1 text-[11px] text-text-secondary",children:"Comparaison 7 / 28 jours"}),a.error&&e.jsx(Le,{onRetry:()=>void a.refetch(),className:"mt-1"})]})})]}),e.jsx(P,{type:"button",variant:"secondary",fullWidth:!0,onClick:u=>{u.currentTarget.focus(),r()},children:"Comprendre mon état"}),!s.loading&&!s.error&&c===0&&e.jsx(Kt,{variant:"primary",label:"Faire mon check-in",icon:"checkin",message:"Je veux faire mon check-in du jour."})]})}async function xo(){return{default:(await _r(()=>import("./TrainingTwinTab-DdoXBLxh.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70]))).TrainingTwinTab}}const po=jr(xo,{reload:()=>{}}),fo=({className:t})=>e.jsx(vr,{className:`h-[448px] ${t??""}`}),ho=({className:t,onRetry:s})=>e.jsxs("div",{className:`flex min-h-[28rem] flex-col items-center justify-center gap-3 rounded-[22px] border border-error/25 bg-error/5 px-6 text-center ${t??""}`,role:"alert",children:[e.jsx("p",{className:"font-display text-base font-semibold text-text-primary",children:"Twin indisponible"}),e.jsx("p",{className:"max-w-xs text-sm leading-relaxed text-text-secondary",children:"Le module 3D n’a pas pu charger. Réessaie sans renvoyer de scan."}),e.jsx(Le,{onRetry:s})]});function go({userId:t,className:s,afterStage:n}){return e.jsx(Fi,{resetKeys:[t],fallback:e.jsxs(e.Fragment,{children:[e.jsx(ho,{className:s,onRetry:()=>window.location.reload()}),n]}),children:e.jsx(o.Suspense,{fallback:e.jsxs(e.Fragment,{children:[e.jsx(fo,{className:s}),n]}),children:e.jsx(po,{userId:t,className:s,afterStage:n})})})}function Da({icon:t,title:s,eyebrow:n,action:a}){return e.jsx(Ei,{icon:t,title:s,eyebrow:n,action:a})}var Cn;(function(t){t.DragStart="dragStart",t.DragMove="dragMove",t.DragEnd="dragEnd",t.DragCancel="dragCancel",t.DragOver="dragOver",t.RegisterDroppable="registerDroppable",t.SetDroppableDisabled="setDroppableDisabled",t.UnregisterDroppable="unregisterDroppable"})(Cn||(Cn={}));const bo=Object.freeze({x:0,y:0});var Qe;(function(t){t[t.Forward=1]="Forward",t[t.Backward=-1]="Backward"})(Qe||(Qe={}));var Tn;(function(t){t.Click="click",t.DragStart="dragstart",t.Keydown="keydown",t.ContextMenu="contextmenu",t.Resize="resize",t.SelectionChange="selectionchange",t.VisibilityChange="visibilitychange"})(Tn||(Tn={}));var de;(function(t){t.Space="Space",t.Down="ArrowDown",t.Right="ArrowRight",t.Left="ArrowLeft",t.Up="ArrowUp",t.Esc="Escape",t.Enter="Enter",t.Tab="Tab"})(de||(de={}));de.Space,de.Enter,de.Esc,de.Space,de.Enter,de.Tab;var En;(function(t){t[t.RightClick=2]="RightClick"})(En||(En={}));var Rn;(function(t){t[t.Pointer=0]="Pointer",t[t.DraggableRect=1]="DraggableRect"})(Rn||(Rn={}));var An;(function(t){t[t.TreeOrder=0]="TreeOrder",t[t.ReversedTreeOrder=1]="ReversedTreeOrder"})(An||(An={}));Qe.Backward+"",Qe.Forward+"",Qe.Backward+"",Qe.Forward+"";var Ns;(function(t){t[t.Always=0]="Always",t[t.BeforeDragging=1]="BeforeDragging",t[t.WhileDragging=2]="WhileDragging"})(Ns||(Ns={}));var ws;(function(t){t.Optimized="optimized"})(ws||(ws={}));Ns.WhileDragging,ws.Optimized;({...bo});var Dn;(function(t){t[t.Uninitialized=0]="Uninitialized",t[t.Initializing=1]="Initializing",t[t.Initialized=2]="Initialized"})(Dn||(Dn={}));de.Down,de.Right,de.Up,de.Left;const yo=[{value:"all",label:"Tout"},{value:"exercise_form",label:"Forme"},{value:"injury_risk",label:"Risque"},{value:"progression",label:"Suivi"}],Mn={exercise_form:{label:"Forme",theme:"aqua",icon:ge},injury_risk:{label:"Risque",theme:"flame",icon:Is},progression_comparison:{label:"Progression",theme:"verdant",icon:oe},mobility_assessment:{label:"Mobilité",theme:"gold",icon:ue},posture:{label:"Posture",theme:"rose",icon:ge},posture_workstation:{label:"Posture",theme:"rose",icon:ge},stretching:{label:"Étirement",theme:"verdant",icon:oe},stretching_validation:{label:"Étirement",theme:"verdant",icon:oe},initial_assessment:{label:"Évaluation",theme:"aqua",icon:ge},body_video_journal:{label:"Journal",theme:"gold",icon:We},general_video:{label:"Aperçu",theme:"aqua",icon:We}};function jo(t){if(!t||t.length===0)return null;const s=t.some(a=>a.severity==="critical"||a.severity==="high"),n=t.some(a=>a.severity==="major"||a.severity==="moderate"||a.severity==="medium");return s?{label:"Critique",tone:"error"}:n?{label:"Moyen",tone:"warning"}
57:{label:"Mineur",tone:"success"}}function vo({analysis:t}){return e.jsx(V,{padding:"md",className:"border-accent/20 bg-accent/5",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-accent/10 flex items-center justify-center flex-shrink-0",children:e.jsx(aa,{className:"h-5 w-5 animate-spin text-accent motion-reduce:animate-none"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium text-text-primary",children:"Analyse en cours"}),e.jsxs("p",{className:"text-xs text-text-tertiary mt-0.5",children:[je(new Date(t.created_at),"'reçue à' HH:mm",{locale:ye})," — l'IA traite ta vidéo"]})]})]})})}function _o({analysis:t,onSelect:s}){return e.jsx("button",{onClick:()=>s(t),className:"w-full text-left",children:e.jsx(V,{padding:"md",className:"border-error/20 bg-error/5 hover:bg-error/10 transition-colors motion-reduce:transition-none",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-error/10 flex items-center justify-center flex-shrink-0",children:e.jsx(Bt,{className:"w-5 h-5 text-error"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium text-text-primary",children:"Analyse échouée"}),e.jsx("p",{className:"text-xs text-text-tertiary mt-0.5 truncate",children:t.error_message||"Réessaie avec une vidéo plus claire"})]}),e.jsx(Ht,{className:"w-4 h-4 text-text-tertiary flex-shrink-0"})]})})})}function No({analyses:t,loading:s,error:n,filter:a,onFilterChange:r,onSelect:l,onRetry:i}){return n?e.jsx(Vr,{compact:!0,message:n,onRetry:i}):e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex items-center gap-1 bg-surface rounded-lg p-1",children:yo.map(c=>e.jsx(Pi,{label:c.label,selected:a===c.value,onClick:()=>r(c.value),className:"flex-1"},c.value))}),s&&e.jsx("div",{className:"space-y-3",children:[0,1,2].map(c=>e.jsx(V,{padding:"md",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(he,{className:"w-10 h-10 rounded-xl"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(he,{className:"h-4 w-2/3"}),e.jsx(he,{className:"h-3 w-1/3"})]}),e.jsx(he,{className:"w-12 h-8 rounded-lg"})]})},c))}),!s&&t.length===0&&e.jsx(st,{density:"inline",state:"filtered_empty",icon:We,theme:"steel",title:"Aucune analyse dans cette catégorie",action:a!=="all"?e.jsx("button",{type:"button",onClick:()=>r("all"),className:"inline-flex min-h-11 items-center rounded-lg px-3 py-2 text-sm font-semibold text-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent",children:"Voir tout"}):void 0}),!s&&t.map(c=>{if(c.processing_status==="processing")return e.jsx(vo,{analysis:c},c.id);if(c.processing_status==="failed")return e.jsx(_o,{analysis:c,onSelect:l},c.id);const m=Mn[c.analysis_type]||Mn.exercise_form,u=c.analysis_result,x=u?.general_video,d=c.analysis_type==="general_video",g=d?x?.exercise_name||(x?.person_exercising?"Exercice détecté":"Aperçu vidéo"):u?.exercise_identified||u?.catalog_exercise_name||"Exercice",b=d?void 0:u?.form_score,f=u?.errors||[],h=f.length,v=jo(f),w=!!(u?.partial||u?.parse_failed||x?.partial||x?.parse_failed),_=d?x?.rep_count_estimate:null;return e.jsx("button",{onClick:()=>l(c),className:"w-full text-left",children:e.jsx(V,{padding:"md",className:"hover:border-accent/30 transition-colors motion-reduce:transition-none",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(xe,{icon:m.icon,theme:m.theme,size:"md"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"text-sm font-medium text-text-primary truncate capitalize",children:g})}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5 flex-wrap",children:[e.jsx("span",{className:"text-xs text-text-tertiary",children:je(new Date(c.created_at),"d MMM yyyy",{locale:ye})}),e.jsx(me,{tone:"neutral",children:m.label}),h>0&&v&&e.jsxs(me,{tone:v.tone,className:"font-mono-numbers",children:[h," erreur",h>1?"s":""]}),w&&e.jsx(me,{icon:Te,tone:"warning",children:"Partielle"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[b!=null&&Number.isFinite(b)&&e.jsx("span",{className:`text-lg font-bold font-mono-numbers ${qt(b)}`,children:Rs(b)}),b==null&&_!=null&&Number.isFinite(_)&&e.jsxs("span",{className:"text-sm font-bold font-mono-numbers text-text-secondary",children:["~",_,e.jsx("span",{className:"text-[10px] text-text-tertiary ml-0.5",children:"reps"})]}),e.jsx(Ht,{className:"w-4 h-4 text-text-tertiary"})]})]})})},c.id)})]})}function wo({current:t,previous:s,higherIsBetter:n=!0,format:a="percent",compact:r=!1}){if(s===0&&t===0)return null;const l=t-s,i=s!==0?Math.round(l/s*100):t>0?100:0,c=a==="percent"?2:1,m=Math.abs(l)<c,u=l>0,x=m?null:n?u:!u,d=m?It:u?oe:gt,g=m?"text-text-tertiary":x?"text-success":"text-error",b=m?"bg-surface-elevated":x?"bg-success/10":"bg-error/10",f=a==="percent"?`${i>0?"+":""}${i}%`:`${l>0?"+":""}${l}`;return r?e.jsxs("span",{className:`inline-flex items-center gap-0.5 ${g}`,children:[e.jsx(d,{className:"w-3 h-3"}),e.jsx("span",{className:"text-[10px] font-medium",children:f})]}):e.jsxs("span",{className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded ${b} ${g}`,children:[e.jsx(d,{className:"w-3 h-3"}),e.jsx("span",{className:"text-[10px] font-medium",children:f})]})}const Ln={improving:{icon:oe,color:"text-success",label:"Amelioration"},stable:{icon:It,color:"text-text-tertiary",label:"Stable"},declining:{icon:gt,color:"text-error",label:"Regression"}};function ko({data:t,toneClass:s}
57){const[n,a]=o.useState(!1);return o.useEffect(()=>{const r=requestAnimationFrame(()=>a(!0));return()=>cancelAnimationFrame(r)},[]),!n||t.length<2?e.jsx("div",{className:"w-20 h-8"}):e.jsx("div",{className:`w-20 h-8 ${s}`,children:e.jsx(Oi,{width:"100%",height:"100%",children:e.jsx(Bi,{data:t,children:e.jsx(Ui,{type:"monotone",dataKey:"value",stroke:"currentColor",fill:"currentColor",fillOpacity:.12,strokeWidth:1.5,dot:!1,isAnimationActive:!1})})})})}function So({items:t,loading:s,onSelectExercise:n}){const a=o.useMemo(()=>t.slice(0,3),[t]),r=o.useMemo(()=>t.slice(3),[t]);return s?e.jsx("div",{className:"space-y-3",children:[0,1,2].map(l=>e.jsx(V,{padding:"md",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(he,{className:"w-10 h-10 rounded-xl"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(he,{className:"h-4 w-1/2"}),e.jsx(he,{className:"h-3 w-1/4"})]}),e.jsx(he,{className:"w-20 h-8 rounded"})]})},l))}):t.length===0?e.jsxs(V,{padding:"lg",className:"text-center",children:[e.jsx(xe,{icon:_a,theme:"steel",size:"md",className:"mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-text-secondary",children:"Pas encore de données de progression"}),e.jsx("p",{className:"mt-1 text-sm text-text-tertiary",children:"Envoie des vidéos d’exercices pour suivre ta progression"})]}):e.jsxs("div",{className:"space-y-4",children:[a.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 px-1",children:[e.jsx(ra,{className:"w-4 h-4 text-accent"}),e.jsx("h3",{className:"text-sm font-medium text-text-secondary",children:"Top exercices analysés"})]}),e.jsx("div",{className:"space-y-2",children:a.map((l,i)=>{const c=Ln[l.trend],m=c.icon,u=l.score_history.map(d=>({value:d.score})),x=qt(l.latest_score);return e.jsx("button",{onClick:()=>n(l.exercise_name),className:"w-full text-left",children:e.jsx(V,{padding:"md",className:"hover:border-accent/30 transition-colors motion-reduce:transition-none",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex-shrink-0 w-8 h-8 rounded-lg bg-accent/10 flex items-center justify-center",children:e.jsxs("span",{className:"text-sm font-bold font-mono-numbers text-accent",children:["#",i+1]})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium text-text-primary truncate block",children:l.exercise_name}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsxs("span",{className:"text-xs text-text-tertiary",children:[e.jsx("span",{className:"font-mono-numbers",children:l.analysis_count})," analyse",l.analysis_count>1?"s":""]}),e.jsxs("span",{className:`flex items-center gap-0.5 text-[10px] font-medium ${c.color}`,children:[e.jsx(m,{className:"w-3 h-3"}),c.label]})]})]}),e.jsx(ko,{data:u,toneClass:x}),e.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[e.jsx("span",{className:`text-lg font-bold font-mono-numbers ${x}`,children:Math.round(l.latest_score)}),l.previous_score!=null&&e.jsx(wo,{current:l.latest_score,previous:l.previous_score,compact:!0})]})]})})},l.exercise_name)})})]}),r.length>0&&e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-medium text-text-secondary mb-2 px-1",children:"Autres exercices"}),e.jsx("div",{className:"space-y-2",children:r.map(l=>{const i=Ln[l.trend],c=i.icon;return e.jsx("button",{onClick:()=>n(l.exercise_name),className:"w-full text-left",children:e.jsx(V,{padding:"sm",className:"hover:border-accent/30 transition-colors motion-reduce:transition-none",children:e.jsxs("div",{className:"flex items-center gap-3 px-1",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx("span",{className:"text-sm text-text-primary truncate block",children:l.exercise_name})}),e.jsx("span",{className:`flex items-center gap-0.5 text-[10px] ${i.color}`,children:e.jsx(c,{className:"w-3 h-3"})}),e.jsx("span",{className:`text-sm font-bold font-mono-numbers ${qt(l.latest_score)}`,children:Math.round(l.latest_score)}),e.jsx(Ht,{className:"w-4 h-4 text-text-tertiary flex-shrink-0"})]})})},l.exercise_name)})})]})]})}const Co={Genoux:Ut,Hanches:ue,Bassin:ue,Epaules:ue,Colonne:ue,Tronc:ht};function To(t){return t>=5?"bg-error/15 text-error":t>=3?"bg-warning/15 text-warning":"bg-accent/15 text-accent"}function Eo({point:t,recommendations:s}
57){const[n,a]=o.useState(!1),r=_e(),l=Co[t.zone]||Te;return e.jsxs(V,{padding:"md",children:[e.jsx("button",{type:"button",onClick:()=>a(!n),className:"w-full text-left","aria-expanded":n,children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(xe,{icon:l,theme:"flame",size:"sm"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-text-primary",children:t.zone}),e.jsxs("span",{className:`text-[10px] font-semibold font-mono-numbers px-1.5 py-0.5 rounded-full ${To(t.count)}`,children:[t.count,"x"]})]}),e.jsx("p",{className:"text-xs text-text-tertiary mt-0.5 truncate",children:t.error_type.replace(/_/g," ")})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsxs("span",{className:"text-xs font-mono-numbers text-text-tertiary",children:[t.exercises_affected.length," ex."]}),n?e.jsx(et,{className:"w-4 h-4 text-text-tertiary"}):e.jsx(Be,{className:"w-4 h-4 text-text-tertiary"})]})]})}),e.jsx(Oe,{initial:!r,children:n&&e.jsx(te.div,{initial:r?!1:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:r?void 0:{height:0,opacity:0},transition:r?{duration:0,delay:0}:{duration:.2},className:"overflow-hidden",children:e.jsxs("div",{className:"mt-3 pt-3 border-t border-border space-y-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium text-text-secondary mb-1.5",children:"Exercices concernes"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.exercises_affected.map(i=>e.jsx("span",{className:"text-[11px] px-2 py-0.5 rounded-full bg-surface-elevated text-text-secondary",children:i},i))})]}),s.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium text-text-secondary mb-1.5",children:"Mobilité recommandée"}),e.jsx("div",{className:"space-y-1",children:s.map(i=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-1 h-1 rounded-full bg-accent flex-shrink-0"}),e.jsx("span",{className:"text-xs text-text-secondary",children:i})]},i))})]}),e.jsxs("p",{className:"text-[10px] text-text-tertiary",children:["Dernière occurrence :"," ",je(new Date(t.last_seen),"d MMM yyyy",{locale:ye})]})]})})})]})}function Ro({recurring:t,improving:s,loading:n,getStretchRecommendations:a}){return n?e.jsx("div",{className:"space-y-3",children:[0,1,2].map(r=>e.jsx(V,{padding:"md",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(he,{className:"w-8 h-8 rounded-lg"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(he,{className:"h-4 w-1/3"}),e.jsx(he,{className:"h-3 w-2/3"})]})]})},r))}):t.length===0&&s.length===0?e.jsxs(V,{padding:"lg",className:"text-center",children:[e.jsx(xe,{icon:Xe,theme:"verdant",size:"md",className:"mx-auto mb-2"}),e.jsx("p",{className:"text-sm font-medium text-text-primary",children:"Aucun point faible détecté"}),e.jsx("p",{className:"mt-1 text-sm text-text-tertiary",children:"Continue à envoyer des vidéos pour que l’IA détecte tes axes d’amélioration"})]}):e.jsxs("div",{className:"space-y-4",children:[t.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 px-1",children:[e.jsx(Te,{className:"w-4 h-4 text-warning"}),e.jsx("h3",{className:"text-sm font-medium text-text-secondary",children:"Erreurs récurrentes"})]}),e.jsx("div",{className:"space-y-2",children:t.slice(0,8).map(r=>e.jsx(Eo,{point:r,recommendations:a(r.zone)},`${r.zone}-${r.error_type}`))})]}),s.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 px-1",children:[e.jsx(oe,{className:"w-4 h-4 text-success"}),e.jsx("h3",{className:"text-sm font-medium text-text-secondary",children:"En amélioration"})]}),e.jsx("div",{className:"space-y-2",children:s.map(r=>e.jsx(V,{padding:"md",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-success/15 flex items-center justify-center flex-shrink-0",children:e.jsx(oe,{className:"w-4 h-4 text-success"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium text-text-primary",children:r.zone}),e.jsxs("p",{className:"text-xs text-text-tertiary mt-0.5",children:[r.error_type.replace(/_/g," ")," — plus détecté depuis le"," ",je(ne
57w Date(r.improved_since),"d MMM",{locale:ye})]})]}),e.jsx(me,{tone:"success",children:"Corrige"})]})},`${r.zone}-${r.error_type}`))})]})]})}const qn=Nr("safe-supabase");async function Ao(t,s){try{const{data:n,error:a}=await t();return a?(qn.error(s.op,{code:a.code,message:a.message,details:a.details,hint:a.hint,userId:s.userId,...s.extra}),{data:null,error:new Error(a.message)}):{data:n,error:null}}catch(n){const a=n instanceof Error?n:new Error("Unknown error");return qn.error(`${s.op}:throw`,{error:a.message,stack:a.stack,userId:s.userId,...s.extra}),{data:null,error:a}}}function Do(t){try{return je(new Date(t),"d MMMM yyyy 'à' HH:mm",{locale:ye})}catch{return t}}function Mo({exerciseName:t,score:s,createdAt:n,videoUrl:a,typeLabel:r,typeToneClass:l,typeSurfaceClass:i,typeWashClass:c,typeIcon:m,isPartial:u}){const x=m,d=s!=null&&Number.isFinite(s),g=d?Rs(s):null,b=d?qt(s):"text-text-tertiary",f=d?wr(s):null;return e.jsx("div",{className:"relative",children:e.jsxs("div",{className:`p-5 pb-4 bg-gradient-to-br to-transparent ${l} ${c}`,children:[e.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[e.jsx("div",{className:`w-12 h-12 rounded-2xl flex items-center justify-center flex-shrink-0 ${i}`,children:e.jsx(x,{className:"w-6 h-6"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h2",{className:"font-display font-bold text-text-primary text-lg leading-tight capitalize",children:t}),e.jsxs("div",{className:"flex items-center gap-2 text-text-tertiary text-xs mt-1 flex-wrap",children:[e.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-semibold ${l} ${i}`,children:[e.jsx(x,{className:"w-3 h-3"}),r]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(qs,{className:"w-3 h-3"}),Do(n)]}),a&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-accent",children:[e.jsx(We,{className:"w-3 h-3"}),"Video"]}),u&&e.jsx(me,{tone:"warning",children:"Analyse partielle"})]})]})]}),d&&e.jsxs("div",{className:"flex items-center gap-4 bg-surface-elevated rounded-2xl p-4",children:[e.jsxs("div",{className:"relative w-20 h-20 flex-shrink-0",children:[e.jsxs("svg",{className:"w-full h-full -rotate-90",viewBox:"0 0 80 80",children:[e.jsx("circle",{cx:"40",cy:"40",r:"34",fill:"none",className:"stroke-white/[0.06]",strokeWidth:"8"}),e.jsx("circle",{cx:"40",cy:"40",r:"34",fill:"none",className:`${b} transition-[stroke-dasharray] duration-[800ms] ease-out motion-reduce:transition-none`,stroke:"currentColor",strokeWidth:"8",strokeLinecap:"round",strokeDasharray:`${g/100*(2*Math.PI*34)} ${2*Math.PI*34}`})]}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[e.jsx("span",{className:`text-2xl font-bold font-mono-numbers leading-none ${b}`,children:g}),e.jsx("span",{className:"text-[9px] font-mono-numbers text-text-tertiary mt-0.5",children:"/100"})]})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs text-text-tertiary uppercase tracking-wide mb-0.5",children:"Score de forme"}),f&&e.jsx("p",{className:`text-lg font-display font-bold leading-tight ${b}`,children:f.text}),e.jsx("p",{className:"text-xs text-text-secondary mt-1 leading-snug",children:"Évaluation globale de la technique sur l'ensemble des répétitions analysées."})]})]}),!d&&!u&&e.jsx("div",{className:"bg-surface-elevated rounded-2xl p-4",children:e.jsx("p",{className:"text-xs text-text-secondary text-center",children:"Pas de score disponible pour cette analyse"})})]})})}function Tt({icon:t,label:s,value:n,unit:a,toneClass:r}){return e.jsxs("div",{className:"bg-surface-elevated rounded-xl p-3 flex flex-col items-center justify-center",children:[e.jsx(t,{className:`w-4 h-4 mb-1.5 ${r}`}),e.jsx("span",{className:"text-[10px] text-text-tertiary uppercase tracking-wide mb-0.5",children:s}),e.jsxs("span",{className:"text-base font-bold text-text-primary font-mono-numbers leading-tight",children:[n,a&&e.jsx("span",{className:"text-[10px] font-normal text-text-tertiary ml-0.5",children:a})]})]})}function Lo({repCount:t,tempoEcc:s,tempoConc:n,cameraConfidence:a,confidence:r}){const l=t!=null&&Number.isFinite(t)&&t>0,i=s!=null&&Number.isFinite(s)&&s>0||n!=null&&Number.isFinite(n)&&n>0,c=a!=null&&Number.isFinite(a),m=r!=null&&Number.isFinite(r);if(!l&&!i&&!c&&!m)return null;const u=i&&s!=null&&n!=null?`${Math.round(s*10)/10}/${Math.round(n*10)/10}`:i&&s!=null?`${Math.round(s*10)/10}/-`:i&&n!=null?`-/${Math.round(n*10)/10}`:null,x=[];l&&x.push(e.jsx(Tt,{icon:Hs,label:"Reps",value:String(t),toneClass:"text-cyan-400"},"reps")),u&&x.push(e.jsx(Tt,{icon:ia,label:"Tempo",value:u,unit:"s",toneClass:"text-warning"},"tempo")),m&&x.push(e.jsx(Tt,{icon:ue,label:"Confiance",value:`${Math.round(r*100)}`,unit:"%",toneClass:"text-success"},"conf")),c&&x.push(e.jsx(Tt,{icon:Ft,label:"Cadrage",value:`${Math.round(a*100)}`,unit:"%",toneClass:"text-violet-400"},"cam"));const d=x.length===1?"grid-cols-1":x.length===2?"grid-cols-2":x.length===3?"grid-cols-3":"grid-cols-4";return e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-text-primary mb-2.5",children:"Métriques"}),e.jsx("div",{className:`grid ${d} gap-2`,children:x})]})}const $n={critical:{label:"Critique",bg:"bg-error/15",text:"text-error",border:"border-error/30",tone:"error"},high:{label:"Élevée",bg:"bg-error/15",text:"text-error",border:"border-error/30",tone:"error"},major:{label:"Majeure",bg:"bg-warning/15",text:"text-warning",border:"border-warning/30",tone:"warning"},moderate:{label:"Modérée",bg:"bg-warning/15",text:"text-warning",border:"border-warning/30",tone:"warning"},medium:{label:"Modérée",bg:"bg-warning/15",text:"text-warning",border:"border-warning/30",tone:"warning"},minor:{label:"Mineure",bg:"bg-surface-elevated",text:"text-text-tertiary",border:"border-white/10",tone:"neutral"},low:{label:"Mineure",bg:"bg-surface-elevated",text:"text-text-tertiary",border:"border-white/10",tone:"neutral"}};function qo(t){return t.replace(/_/g," ").replace(/\b\w/g,s=>s.toUpperCase())}function $o({errors:t}){const s=_e();return!t||t.length===0?null:e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[e.jsx(Te,{className:"w-4 h-4 text-warning"}),e.jsxs("h3",{className:"text-sm font-semibold text-text-primary",children:[e.jsx("span",{className:"font-mono-numbers",children:t.length})," erreur",t.length>
571?"s":""," détectée",t.length>1?"s":""]})]}),e.jsx("div",{className:"space-y-2",children:t.map((n,a)=>{const r=$n[n.severity]||$n.minor;return e.jsx(te.div,{initial:s?!1:{opacity:0,y:6},animate:{opacity:1,y:0},transition:s?{duration:0,delay:0}:{delay:a*.04},className:`bg-surface-elevated rounded-xl p-3 border ${r.border}`,children:e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx("div",{className:`w-7 h-7 rounded-lg flex items-center justify-center flex-shrink-0 ${r.bg}`,children:e.jsx(Te,{className:`w-3.5 h-3.5 ${r.text}`})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mb-1",children:[e.jsx("span",{className:"text-sm font-medium text-text-primary",children:qo(n.type)}),e.jsx(me,{tone:r.tone,children:r.label})]}),n.description&&e.jsx("p",{className:"text-xs text-text-secondary leading-relaxed",children:n.description}),n.correction&&e.jsxs("div",{className:"mt-2 pt-2 border-t border-white/5 flex items-start gap-1.5",children:[e.jsx(la,{className:"w-3 h-3 text-success flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-xs text-success/90 leading-relaxed",children:n.correction})]})]})]})},`${n.type}-${a}`)})})]})}function Fn(t){return t.assessable===!1||(typeof t.note=="string"?t.note.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/['’]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""):"")==="non-visible-sur-la-video"?"unknown":"observed"}function ds(t){return t.replace(/_/g," ").replace(/\b\w/g,s=>s.toUpperCase())}function Fo({whatIsGood:t,correctivePriority:s,recommendations:n,corrections:a,detailedExplanation:r,overallAssessment:l,summary:i,loadAssessment:c,asymmetries:m,safetyChecks:u,phaseScores:x,fatiguePattern:d}){const g=(t||[]).filter(Boolean),b=(s?.length?s:a||[]).filter(Boolean),f=(n||[]).filter(Boolean),h=(u||[]).filter(p=>Fn(p)==="observed"),v=h.filter(p=>p.pass===!1),w=h.filter(p=>p.pass===!0),_=(u||[]).filter(p=>Fn(p)==="unknown"),T=(m||[]).filter(p=>p&&p.description),N=(x||[]).filter(p=>p&&p.score!=null),y=d?.degradation_detected===!0,k=!!(i||l||r);return e.jsxs(e.Fragment,{children:[k&&e.jsx("div",{className:"bg-surface-elevated rounded-xl p-4",children:e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-accent/10 flex items-center justify-center flex-shrink-0",children:e.jsx($s,{className:"w-4 h-4 text-accent"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"text-xs font-semibold text-text-secondary uppercase tracking-wide mb-1.5",children:"Évaluation"}),i&&e.jsx("p",{className:"text-sm text-text-primary leading-relaxed",children:i}),l&&l!==i&&e.jsx("p",{className:"text-sm text-text-primary leading-relaxed mt-2",children:l}),r&&e.jsx("p",{className:"text-xs text-text-secondary leading-relaxed mt-2",children:r})]})]})}),g.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[e.jsx(ya,{className:"w-4 h-4 text-success"}),e.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:"Points forts"})]}),e.jsx("div",{className:"bg-success/5 border border-success/15 rounded-xl p-3 space-y-1.5",children:g.map((p,S)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Ie,{className:"w-3.5 h-3.5 text-success flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-sm text-text-primary leading-relaxed",children:p})]},S))})]}),b.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[e.jsx(Ms,{className:"w-4 h-4 text-accent"}),e.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:"Actions prioritaires"})]}),e.jsx("div",{className:"bg-surface-elevated rounded-xl p-3 space-y-2",children:b.map((p,S)=>e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx("div",{className:"w-5 h-5 rounded-full bg-accent/15 flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx("span",{className:"text-[10px] font-bold font-mono-numbers text-accent",children:S+1})}),e.jsx("p",{className:"text-sm text-text-primary leading-relaxed",children:p})]},S))})]}),N.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[e.jsx(_a,{className:"w-4 h-4 text-accent"}),e.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:"Score par phase"})]}),e.jsx("div",{className:"space-y-2",children:N.map((p,S)=>{const j=Math.max(0,Math.min(100,p.score<=10?p.score*10:p.score)),C=j>=80?"success":j>=60?"warning":"error",A=j>=80?"text-success":j>=60?"text-warning":"text-error";return e.jsxs("div",{className:"bg-surface-elevated rounded-lg p-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("span",{className:"text-xs font-medium text-text-primary capitalize",children:p.phase}),e.jsx("span",{className:`text-sm font-bold font-mono-numbers ${A}`,children:Math.round(j)})]}),e.jsx(zt,{value:j,max:100,label:`Score ${p.phase}`,valueText:`${Math.round(j)} sur 100`,tone:C,size:"sm"}),p.notes&&e.jsx("p",{className:"text-[11px] text-text-tertiary mt-1.5 leading-snug",children:p.notes})]},`${p.phase}-${S}`)})})]}),(v.length>0||w.length>0||_.length>0)&&e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-text-primary mb-2.5",children:"Contrôles sécurité"}),e.jsxs("div",{className:"space-y-1.5",children:[v.map(p=>e.jsxs("div",{className:"flex items-start gap-2.5 bg-error/5 border border-error/15 rounded-lg p-2.5",children:[e.jsx(Bt,{className:"w-4 h-4 text-error flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-xs font-medium text-text-primary",children:ds(p.id)}),p.note&&e.jsx("p",{className:"text-[11px] text-text-secondary mt-0.5 leading-snug",children:p.note})]})]}
57,p.id)),_.map(p=>e.jsxs("div",{className:"flex items-start gap-2.5 bg-surface-elevated rounded-lg p-2.5",children:[e.jsx(kr,{className:"w-4 h-4 text-text-tertiary flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("span",{className:"text-xs font-medium text-text-primary",children:[ds(p.id)," — Non observable"]}),p.note&&e.jsx("p",{className:"text-[11px] text-text-secondary mt-0.5 leading-snug",children:p.note})]})]},p.id)),w.map(p=>e.jsxs("div",{className:"flex items-start gap-2.5 bg-surface-elevated rounded-lg p-2.5",children:[e.jsx(Ie,{className:"w-4 h-4 text-success flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-xs font-medium text-text-primary",children:ds(p.id)}),p.note&&e.jsx("p",{className:"text-[11px] text-text-tertiary mt-0.5 leading-snug",children:p.note})]})]},p.id))]})]}),T.length>0&&e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-text-primary mb-2.5",children:"Asymétries détectées"}),e.jsx("div",{className:"space-y-1.5",children:T.map((p,S)=>e.jsxs("div",{className:"flex items-center justify-between gap-2.5 bg-surface-elevated rounded-lg p-2.5",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(ue,{className:"w-3.5 h-3.5 text-warning flex-shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{className:"text-xs font-medium text-text-primary capitalize",children:p.side}),e.jsx("p",{className:"text-[11px] text-text-secondary leading-snug truncate",children:p.description})]})]}),p.deficit_pct!=null&&Number.isFinite(p.deficit_pct)&&e.jsxs("span",{className:"text-sm font-bold font-mono-numbers text-warning flex-shrink-0",children:["-",Math.round(p.deficit_pct),"%"]})]},S))})]}),y&&e.jsxs("div",{className:"bg-warning/5 border border-warning/15 rounded-xl p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[e.jsx(ue,{className:"w-4 h-4 text-warning"}),e.jsx("span",{className:"text-sm font-semibold text-warning",children:"Fatigue détectée"})]}),d?.first_rep_score!=null&&d?.last_rep_score!=null&&e.jsxs("p",{className:"text-xs text-text-secondary leading-relaxed",children:["Le score chute de"," ",e.jsx("span",{className:"font-mono-numbers font-semibold text-text-primary",children:Math.round(d.first_rep_score)})," ","à"," ",e.jsx("span",{className:"font-mono-numbers font-semibold text-text-primary",children:Math.round(d.last_rep_score)})," ","entre la première et la dernière répétition."]})]}),c&&e.jsxs("div",{className:"bg-surface-elevated rounded-xl p-3",children:[e.jsx("h4",{className:"text-xs font-semibold text-text-secondary uppercase tracking-wide mb-1",children:"Charge évaluée"}),e.jsx("p",{className:"text-sm text-text-primary capitalize",children:c})]}),f.length>0&&e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-text-primary mb-2.5",children:"Recommandations"}),e.jsx("div",{className:"bg-surface-elevated rounded-xl p-3 space-y-1.5",children:f.map((p,S)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("div",{className:"w-1 h-1 rounded-full bg-accent mt-2 flex-shrink-0"}),e.jsx("p",{className:"text-sm text-text-secondary leading-relaxed",children:p})]},S))})]})]})}function Po({videoUrl:t}){const[s,n]=o.useState(!1);return t?s?e.jsx("div",{className:"rounded-xl overflow-hidden bg-black aspect-video",children:e.jsx("video",{src:t,controls:!0,autoPlay:!0,playsInline:!0,className:"w-full h-full object-contain",onError:()=>n(!1),children:e.jsx("track",{kind:"captions"})})}):e.jsxs("button",{onClick:()=>n(!0),className:"w-full bg-surface-elevated rounded-xl p-3 flex items-center gap-3 hover:bg-surface transition-colors motion-reduce:transition-none group",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-accent/15 flex items-center justify-center flex-shrink-0 group-hover:bg-accent/25 transition-colors motion-reduce:transition-none",children:e.jsx(zi,{className:"w-4 h-4 text-accent ml-0.5",fill:"currentColor"})}),e.jsxs("div",{className:"flex-1 text-left min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(We,{className:"w-3.5 h-3.5 text-text-tertiary"}),e.jsx("span",{className:"text-sm font-medium text-text-primary",children:"Voir la vidéo"})]}),e.jsx("p",{className:"text-xs text-text-tertiary",children:"Lecture en ligne (URL signée temporaire)"})]})]}):null}const Oo={home:"Maison",gym:"Salle de sport",outdoor:"Extérieur",kitchen:"Cuisine",restaurant:"Restaurant",office:"Bureau",other:"Autre"},Bo={exercise:"Exercice",meal:"Repas",body:"Corps",equipment:"Équipement",environment:"Environnement",cooking:"Cuisine",other:"Divers"};function Uo({data:t}){const s=t.scene_type?Oo[t.scene_type]||t.scene_type:null,n=t.primary_content?Bo[t.primary_content]||t.primary_content:null,a=(t.detected_objects||[]).filter(
57Boolean).slice(0,12),r=(t.usable_for_training||[]).filter(Boolean).slice(0,8),l=t.person_exercising===!0&&(t.exercise_name||t.exercise_observations||t.rep_count_estimate!=null);return e.jsxs(e.Fragment,{children:[t.description&&e.jsx("div",{className:"bg-surface-elevated rounded-xl p-4",children:e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-accent/10 flex items-center justify-center flex-shrink-0",children:e.jsx(ge,{className:"w-4 h-4 text-accent"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"text-xs font-semibold text-text-secondary uppercase tracking-wide mb-1.5",children:"Ce que je vois"}),e.jsx("p",{className:"text-sm text-text-primary leading-relaxed",children:t.description}),(s||n)&&e.jsxs("div",{className:"flex items-center gap-1.5 mt-2 flex-wrap",children:[s&&e.jsx("span",{className:"text-[10px] font-medium px-2 py-0.5 rounded-full bg-surface text-text-secondary",children:s}),n&&e.jsx("span",{className:"text-[10px] font-medium px-2 py-0.5 rounded-full bg-accent/10 text-accent",children:n})]})]})]})}),l&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[e.jsx(Q,{className:"w-4 h-4 text-accent"}),e.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:"Exercice détecté"})]}),e.jsxs("div",{className:"bg-surface-elevated rounded-xl p-3 space-y-2",children:[t.exercise_name&&e.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[e.jsx("span",{className:"text-xs text-text-tertiary uppercase tracking-wide",children:"Mouvement"}),e.jsx("span",{className:"text-sm font-bold text-text-primary capitalize",children:t.exercise_name})]}),t.rep_count_estimate!=null&&Number.isFinite(t.rep_count_estimate)&&e.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[e.jsxs("span",{className:"text-xs text-text-tertiary uppercase tracking-wide flex items-center gap-1",children:[e.jsx(Hs,{className:"w-3 h-3"}),"Reps estimées"]}),e.jsxs("span",{className:"text-sm font-bold text-text-primary font-mono-numbers",children:["~",t.rep_count_estimate]})]}),t.exercise_observations&&e.jsx("div",{className:"pt-2 border-t border-white/5",children:e.jsx("p",{className:"text-xs text-text-secondary leading-relaxed",children:t.exercise_observations})})]})]}),r.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[e.jsx(Xe,{className:"w-4 h-4 text-success"}),e.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:"Utilisable pour le training"})]}),e.jsx("div",{className:"bg-success/5 border border-success/15 rounded-xl p-3 space-y-1.5",children:r.map((i,c)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("div",{className:"w-1 h-1 rounded-full bg-success mt-2 flex-shrink-0"}),e.jsx("p",{className:"text-sm text-text-primary leading-relaxed",children:i})]},c))})]}),a.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[e.jsx(Ri,{className:"w-4 h-4 text-text-tertiary"}),e.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:"Objets détectés"})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:a.map((i,c)=>e.jsx("span",{className:"text-[11px] font-medium px-2 py-1 rounded-full bg-surface-elevated text-text-secondary capitalize",children:i},c))})]}),t.coaching_relevance&&e.jsx("div",{className:"bg-surface-elevated rounded-xl p-3",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Sr,{className:"w-4 h-4 text-accent flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"text-xs font-semibold text-text-secondary uppercase tracking-wide mb-1",children:"Pertinence coaching"}),e.jsx("p",{className:"text-sm text-text-primary leading-relaxed",children:t.coaching_relevance})]})]})}),l&&e.jsx("div",{className:"bg-accent/5 border border-accent/15 rounded-xl p-3",children:e.jsxs("p",{className:"text-xs text-text-secondary leading-relaxed",children:[e.jsx("span",{className:"font-semibold text-accent",children:"Astuce"})," — pour une analyse complète de ta forme (score, erreurs, corrections détaillées), refilme en mode paysage, de profil, à 2-3m de distance, avec 3 à 5 répétitions propres."]})}),t.suggested_follow_up&&!l&&e.jsx("div",{className:"bg-accent/5 border border-accent/15 rounded-xl p-3",children:e.jsx("p",{className:"text-sm text-text-primary leading-relaxed",children:t.suggested_follow_up}
57)})]})}const Pn={exercise_form:{label:"Analyse de forme",toneClass:"text-cyan-400",surfaceClass:"bg-cyan-500/10",washClass:"from-cyan-500/10",icon:ge},injury_risk:{label:"Risque de blessure",toneClass:"text-error",surfaceClass:"bg-error/10",washClass:"from-error/10",icon:Is},progression_comparison:{label:"Comparaison progression",toneClass:"text-success",surfaceClass:"bg-success/10",washClass:"from-success/10",icon:oe},mobility_assessment:{label:"Mobilité",toneClass:"text-warning",surfaceClass:"bg-warning/10",washClass:"from-warning/10",icon:ue},posture:{label:"Posture",toneClass:"text-violet-400",surfaceClass:"bg-violet-500/10",washClass:"from-violet-500/10",icon:ge},posture_workstation:{label:"Posture",toneClass:"text-violet-400",surfaceClass:"bg-violet-500/10",washClass:"from-violet-500/10",icon:ge},stretching:{label:"Étirement",toneClass:"text-success",surfaceClass:"bg-success/10",washClass:"from-success/10",icon:oe},stretching_validation:{label:"Étirement",toneClass:"text-success",surfaceClass:"bg-success/10",washClass:"from-success/10",icon:oe},initial_assessment:{label:"Évaluation",toneClass:"text-cyan-400",surfaceClass:"bg-cyan-500/10",washClass:"from-cyan-500/10",icon:ge},body_video_journal:{label:"Journal corporel",toneClass:"text-warning",surfaceClass:"bg-warning/10",washClass:"from-warning/10",icon:Ft},general_video:{label:"Aperçu vidéo",toneClass:"text-cyan-400",surfaceClass:"bg-cyan-500/10",washClass:"from-cyan-500/10",icon:Ft}};function zo({analysis:t,onClose:s}){const n=t.analysis_result,a=t.processing_status==="processing",r=t.processing_status==="failed",l=t.analysis_type==="general_video",i=n?.general_video,c=!!(n?.partial||n?.parse_failed||i?.partial||i?.parse_failed),m=l?i?.exercise_name||(i?.person_exercising?"Exercice détecté":"Aperçu vidéo"):n?.exercise_identified||n?.catalog_exercise_name||(a?"Analyse en cours...":"Exercice non identifié"),u=l?void 0:n?.form_score,x=(n?.errors||[]).filter(k=>k&&k.type),d=(n?.corrections||[]).filter(Boolean),g=n?.summary,b=(n?.recommendations||[]).filter(Boolean),f=Pn[t.analysis_type]||Pn.exercise_form,[h,v]=o.useState(null),[w,_]=o.useState(!1),[T,N]=o.useState(!1);o.useEffect(()=>{if(a||r)return;let k=!0;return Ao(()=>$.from("video_analysis_feedback").select("feedback").eq("video_analysis_id",t.id).maybeSingle(),{op:"analysisDetail.feedback.fetch"}).then(({data:p})=>{k&&p?.feedback&&(v(p.feedback),N(!0))}),()=>{k=!1}},[t.id,a,r]);const y=o.useCallback(async k=>{if(T||w)return;_(!0);const{error:p}=await $.from("video_analysis_feedback").insert({user_id:t.user_id,video_analysis_id:t.id,feedback:k,source:"dashboard"});_(!1),p||(v(k),N(!0))},[t.id,t.user_id,T,w]);return e.jsx(ke,{open:!0,onClose:s,eyebrow:f.label,title:m,media:e.jsx(Mo,{exerciseName:m,score:a||r?null:u,createdAt:t.created_at,videoUrl:t.video_url,typeLabel:f.label,typeToneClass:f.toneClass,typeSurfaceClass:f.surfaceClass,typeWashClass:f.washClass,typeIcon:f.icon,isPartial:c}),children:e.jsxs("div",{className:"p-4 space-y-4",children:[a&&e.jsxs("div",{className:"bg-surface-elevated rounded-xl p-4 flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-accent/10 flex items-center justify-center flex-shrink-0",children:e.jsx("div",{className:"w-4 h-4 border-2 border-accent border-t-transparent rounded-full animate-spin motion-reduce:animate-none"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-text-primary",children:"Analyse en cours"}),e.jsx("p",{className:"text-xs text-text-tertiary mt-0.5",children:"L'IA analyse ta vidéo, cela peut prendre 30 à 90 secondes. Le résultat s'affichera ici automatiquement."})]})]}),r&&e.jsx("div",{className:"bg-error/5 border border-error/15 rounded-xl p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-error/15 flex items-center justify-center flex-shrink-0",children:e.jsx($t,{className:"w-4 h-4 text-error"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-error",children:"Analyse échouée"}),e.jsx("p",{className:"text-xs text-text-secondary mt-1 leading-relaxed",children:t.error_message||"L'analyse n'a pas pu aboutir. Réessaie avec une vidéo plus courte (15-30s), bien éclairée, en mode paysage de profil."})]})]})}),c&&!r&&!a&&e.jsx("div",{className:"bg-warning/5 border border-warning/15 rounded-xl p-3",children:e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx($t,{className:"w-4 h-4 text-warning flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-warning",children:"Analyse partielle"}),e.jsx("p",{className:"text-xs text-text-secondary leading-relaxed mt-0.5",children:"L'IA n'a pas pu extraire toutes les métriques. Renvoie une vidéo de profil, à 2-3m, avec 3-5 reps propres pour un retour complet."})]})]})}),!a&&!r&&e.jsxs(e.Fragment,{children:[e.jsx(Po,{videoUrl:t.video_url}),l&&i?e.jsx(Uo,{data:i}):e.jsxs(e.Fragment,{children:[e.jsx(Lo,{repCount:n?.rep_count,tempoEcc:n?.tempo?.e
57ccentric_sec,tempoConc:n?.tempo?.concentric_sec,cameraConfidence:n?.camera_confidence,confidence:n?.confidence}),e.jsx($o,{errors:x}),e.jsx(Fo,{whatIsGood:n?.what_is_good,correctivePriority:n?.corrective_priority,recommendations:b,corrections:d,detailedExplanation:n?.detailed_explanation,overallAssessment:n?.overall_assessment,summary:g,loadAssessment:n?.load_assessment,asymmetries:n?.asymmetries,safetyChecks:n?.safety_checks,phaseScores:n?.phase_scores,fatiguePattern:n?.fatigue_pattern})]}),e.jsx("div",{className:"bg-surface-elevated rounded-xl p-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-text-secondary",children:T?"Merci pour ton retour !":"Cette analyse t'a aidée ?"}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{type:"button",onClick:()=>y("positive"),disabled:T||w,className:`min-h-11 min-w-11 rounded-lg flex items-center justify-center transition-all motion-reduce:transition-none motion-reduce:transform-none ${h==="positive"?"bg-success/20 text-success scale-110":T?"bg-surface text-text-tertiary/40 cursor-not-allowed":"bg-surface text-text-tertiary hover:bg-success/10 hover:text-success"}`,"aria-label":"Analyse utile",children:e.jsx(ya,{className:"w-4 h-4"})}),e.jsx("button",{type:"button",onClick:()=>y("negative"),disabled:T||w,className:`min-h-11 min-w-11 rounded-lg flex items-center justify-center transition-all motion-reduce:transition-none motion-reduce:transform-none ${h==="negative"?"bg-error/20 text-error scale-110":T?"bg-surface text-text-tertiary/40 cursor-not-allowed":"bg-surface text-text-tertiary hover:bg-error/10 hover:text-error"}`,"aria-label":"Analyse pas utile",children:e.jsx(al,{className:"w-4 h-4"})})]})]})})]}),e.jsx(Ai,{message:`Je voudrais discuter de ${m} avec toi`,label:"Parler de l’analyse",icon:"analysis"}),e.jsx("div",{className:"pt-1",children:e.jsx(P,{fullWidth:!0,variant:"secondary",onClick:s,children:"Fermer"})})]})})}function Io(){return e.jsx("div",{className:"space-y-3",children:[0,1].map(t=>e.jsx(Ps,{label:"Chargement de tes analyses…",minHeight:"min-h-24",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(fe,{className:"h-14 w-20 flex-none rounded-xl",tone:"dim"}),e.jsxs("div",{className:"min-w-0 flex-1 flex flex-col gap-2",children:[e.jsx(fe,{className:"h-3 w-2/3 rounded-full"}),e.jsx(fe,{className:"h-2.5 w-1/3 rounded-full",tone:"dim"})]})]})},t))})}function Wo(){const{user:t}=Fs(),[s,n]=o.useState(null),{analyses:a,loading:r,error:l,filter:i,setFilter:c,refetch:m}=ni(t?.id),{items:u,loading:x,error:d,refetch:g}=jl(t?.id),{recurring:b,improving:f,loading:h,error:v,refetch:w,getStretchRecommendations:_}=wl(t?.id),T=r||x||h,N=l||d||v,y=a.filter(A=>A.processing_status==="processing"),k=a.some(A=>A.processing_status!=="processing"),p=u.length>0||b.length>0||f.length>0,S=k||p,j=y.length>0&&!S,C=()=>{m(),g(),w()};return e.jsx(Ue,{loading:T,error:N,empty:i==="all"&&!j&&!S,loadingFallback:e.jsx(Io,{}),onRetry:C,errorTitle:"Analyses indisponibles",errorMessage:"Impossible de charger tes analyses vidéo. Réessaie sans renvoyer ta vidéo.",emptyFallback:e.jsx(st,{density:"section",state:"first_use",icon:We,theme:"aqua",eyebrow:"Analyse vidéo",title:"Fais analyser ton premier mouvement",description:"Envoie une vidéo à Alloy pour recevoir des repères techniques et suivre tes progrès.",action:e.jsx(Wt,{label:"Envoyer une vidéo",icon:"video",message:"Je veux faire analyser une vidéo de mon mouvement.",variant:"secondary"})}),children:j?e.jsx(st,{density:"inline",state:"handoff",icon:aa,theme:"aqua",title:y.length>1?`${y.length} vidéos reçues`:"Vidéo reçue",description:"L’analyse apparaîtra ici dès qu’elle sera disponible.",role:"status"}):e.jsxs("div",{className:"space-y-5",children:[(a.length>0||i!=="all")&&e.jsxs("section",{children:[e.jsxs("div",{className:"mb-2 flex items-baseline justify-between px-1",children:[e.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:"Analyses récentes"}),a.length>0&&e.jsxs("span",{className:"text-[11px] text-text-tertiary",children:[a.length," analyse",a.length>
571?"s":""]})]}),e.jsx(No,{analyses:a,loading:!1,error:null,filter:i,onFilterChange:c,onSelect:n,onRetry:C})]}),u.length>0&&e.jsxs("section",{children:[e.jsx("h2",{className:"mb-2 px-1 text-sm font-semibold text-text-primary",children:"Progression"}),e.jsx(So,{items:u,loading:!1,onSelectExercise:A=>{const D=a.find(E=>E.analysis_result?.exercise_identified===A);D&&n(D)}})]}),(b.length>0||f.length>0)&&e.jsxs("section",{children:[e.jsx("h2",{className:"mb-2 px-1 text-sm font-semibold text-text-primary",children:"Points faibles"}),e.jsx(Ro,{recurring:b,improving:f,loading:!1,getStretchRecommendations:_})]}),e.jsx(Oe,{children:s&&e.jsx(zo,{analysis:s,onClose:()=>n(null)})})]})})}const Ho={gym:Q,home:Tr,outdoor:hn,park:hn,hotel:Ii,other:Os},Vo={gym:"Salle de sport",home:"Maison",outdoor:"Extérieur",park:"Parc",hotel:"Hôtel",other:"Autre"},On={ember:"bg-accent/10 text-accent",flame:"bg-forge-ember/10 text-forge-ember",steel:"bg-slate-400/10 text-slate-400",verdant:"bg-success/10 text-success",aqua:"bg-blue-500/10 text-blue-400",gold:"bg-amber/10 text-amber",rose:"bg-rose-400/10 text-rose-400",crimson:"bg-red-400/10 text-red-400",charcoal:"bg-white/10 text-text-tertiary",whatsapp:"bg-green-500/10 text-green-400"},Go={ember:"bg-accent/20 text-accent",flame:"bg-forge-ember/20 text-forge-ember",steel:"bg-slate-400/20 text-slate-400",verdant:"bg-success/20 text-success",aqua:"bg-blue-500/20 text-blue-500",gold:"bg-amber/20 text-amber",rose:"bg-rose-400/20 text-rose-400",crimson:"bg-red-400/20 text-red-400",charcoal:"bg-black/40 text-text-secondary",whatsapp:"bg-green-500/20 text-green-500"};function Yo(t){if(!t)return"steel";const s=t.toLowerCase();return ao[s]||"steel"}function Ko({scan:t,onUpdate:s}){const[n,a]=o.useState(!1),[r,l]=o.useState(!1),[i,c]=o.useState(t.detected_equipment),[m,u]=o.useState(""),[x,d]=o.useState(!1),[g,b]=o.useState(!1),[f,h]=o.use
57State(!1),v=o.useRef(null),w=o.useRef(null),_=_e(),T=Ds();Cr(g,()=>b(!1),w,v,!0);const N=async()=>{if(t.photo_url){const L=t.photo_url.split("/gym-photos/"),q=L.length>0?L[L.length-1]:null;q&&await $.storage.from("gym-photos").remove([q])}const{error:E}=await $.from("gym_scans").delete().eq("id",t.id);if(E)throw T.error("Erreur lors de la suppression"),E;T.success("Lieu supprimé"),s()},y=Sn[t.location_type]||Sn.other,k=Ho[t.location_type]||Os,p=Vo[t.location_type]||"Autre",S=()=>{const E=m.trim();E&&(c(L=>[...L,{name:E,category:"accessory"}]),u(""))},j=E=>{c(L=>L.filter((q,R)=>R!==E))},C=async()=>{d(!0);const{error:E}=await $.from("gym_scans").update({detected_equipment:i}).eq("id",t.id);E?T.error("Erreur lors de la sauvegarde"):(T.success("Équipement mis à jour"),l(!1),s()),d(!1)},A=()=>{c(t.detected_equipment),l(!1)},D=n?i:i.slice(0,6);return e.jsxs(e.Fragment,{children:[e.jsxs(V,{padding:"none",className:"overflow-hidden",children:[t.photo_url&&e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:t.photo_url,alt:p,className:"w-full h-48 object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/60 via-trans
57parent to-transparent"}),e.jsx("button",{type:"button",onClick:()=>b(!0),"aria-label":`Agrandir la photo de ${p}`,className:"absolute right-2 top-2 flex h-11 w-11 items-center justify-center rounded-full bg-black/55 text-white backdrop-blur-sm transition-colors hover:bg-black/70 motion-reduce:transition-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white",children:e.jsx(sl,{className:"w-4 h-4"})}),e.jsxs("div",{className:"absolute bottom-3 left-3 flex items-center gap-2",children:[e.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold backdrop-blur-sm ${Go[y]}`,children:[e.jsx(k,{className:"w-3.5 h-3.5"}),p]}),t.space_assessment&&e.jsx("span",{className:"px-2 py-1 rounded-full text-xs text-white/70 bg-white/10 backdrop-blur-sm capitalize",children:t.space_assessment})]}),e.jsx("div",{className:"absolute bottom-3 right-3",children:e.jsx("span",{className:"text-xs text-white/60",children:je(new Date(t.created_at),"d MMM yyyy",{locale:ye})})})]}),!t.photo_url&&e.jsx("div",{className:"h-32 flex items-center justify-center bg-surface",children:e.jsx(xe,{icon:k,theme:y,size:"xl"})}),e.jsxs("div",{className:"p-4 space-y-3",children:[!t.photo_url&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold ${On[y]}`,children:[e.jsx(k,{className:"w-3.5 h-3.5"}),p]}),e.jsx("span",{className:"text-xs text-text-tertiary",children:je(new Date(t.created_at),"d MMM yyyy",{locale:ye})})]}),i.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("h4",{className:"text-xs uppercase tracking-wide text-text-tertiary",children:["Équipement ",e.jsxs("span",{className:"font-mono-numbers",children:["(",i.length,")"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>r?A():l(!0),className:"flex min-h-11 items-center gap-1 rounded-lg px-2 text-xs text-text-tertiary transition-colors hover:text-accent motion-reduce:transition-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent",children:[r?e.jsx(xt,{className:"w-3 h-3"}):e.jsx(Zr,{className:"w-3 h-3"}),r?"Annuler":"Modifier"]}),!r&&e.jsx("button",{type:"button",onClick:()=>h(!0),"aria-label":"Supprimer ce lieu",className:"flex h-11 w-11 items-center justify-center rounded-lg text-text-tertiary transition-colors hover:text-error motion-reduce:transition-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-error",children:e.jsx(xn,{className:"w-3.5 h-3.5"})})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[D.map((E,L)=>{const q=Yo(E.category);return e.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-1 rounded-lg text-xs font-medium ${On[q]}`,children:[E.name,r&&e.jsx("button",{type:"button",onClick:()=>j(L),"aria-label":`Retirer ${E.name}`,className:"-my-2 -mr-2 ml-0.5 flex h-11 w-11 items-center justify-center rounded-lg transition-colors hover:text-error motion-reduce:transition-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-error",children:e.jsx(xt,{className:"w-3 h-3"})})]},E.name)}),!n&&i.length>6&&e.jsxs("button",{type:"button",onClick:()=>a(!0),className:"font-mono-numbers min-h-11 rounded-lg bg-surface px-3 py-2 text-xs font-medium text-text-tertiary transition-colors hover:text-text-secondary motion-reduce:transition-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent",children:["+",i.length-6]})]}),r&&e.jsxs("div",{className:"mt-3 flex gap-2",children:[e.jsx("input",{type:"text",value:m,onChange:E=>u(E.target.value),onKeyDown:E=>E.key==="Enter"&&S(),placeholder:"Ajouter un équipement…","aria-label":"Nom de l’équipement",className:"min-h-11 min-w-0 flex-1 rounded-lg border border-border bg-surface px-3 py-2 text-sm text-text-primary placeholder:text-text-tertiary focus:border-accent focus:outline-none focus-visible:ring-2 focus-visible:ring-accent"}),e.jsx("button",{type:"button",onClick:S,"aria-label":"Ajouter cet équipement",className:"flex h-11 w-11 items-center justify-center rounded-lg bg-accent/20 text-accent transition-colors hover:bg-accent/30 motion-reduce:transition-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent",children:e.jsx(Wi,{className:"w-4 h-4"})})]}),r&&e.jsx(P,{type:"button",variant:"primary",size:"sm",fullWidth:!0,loading:x,icon:e.jsx(Bs,{className:"h-4 w-4","aria-hidden":"true"}),className:"mt-2",onClick:C,children:"Sauvegarder"})]}),i.length===0&&e.jsxs("button",{type:"button",onClick:()=>h(!0),"aria-label":"Supprimer ce lieu",className:"flex min-h-11 items-center gap-1.5 rounded-lg px-2 text-xs text-text-tertiary transition-colors hover:text-error motion-reduce:transition-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-error",children:[e.jsx(xn,{className:"w-3.5 h-3.5"}),"Supprimer"]}),t.coach_feedback&&e.jsx("div",{className:"bg-surface rounded-xl p-3",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Hi,{className:"w-4 h-4 text-accent flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-sm text-text-secondary leading-relaxed italic",children:t.coach_feedback})]})}),t.analysis_summary&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>a(!n),"aria-expanded":n,className:"flex min-h-11 items-center gap-2 rounded-lg px-2 text-sm text-text-tertiary transition-colors hover:text-text-secondary motion-reduce:transition-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent",children:[n?e.jsx(et,{className:"w-4 h-4"}):e.jsx(Be,{className:"w-4 h-4"}),n?"Masquer l’analyse":"Voir l’analyse complète"]}),e.jsx(Oe,{children:n&&e.jsx(te.div,{initial:_?!1:{height:0,opacity:0}
57,animate:_?void 0:{height:"auto",opacity:1},exit:_?void 0:{height:0,opacity:0},transition:_?{duration:0}:void 0,className:"overflow-hidden",children:e.jsx("div",{className:"bg-surface rounded-xl p-3",children:e.jsx("p",{className:"text-sm text-text-secondary leading-relaxed",children:t.analysis_summary})})})})]})]})]}),typeof document<"u"&&g&&t.photo_url&&xr.createPortal(e.jsxs("div",{ref:v,role:"dialog","aria-modal":"true","aria-label":`Photo du lieu ${p}`,tabIndex:-1,className:"fixed inset-0 z-modal flex items-center justify-center bg-black/90 pt-[max(1rem,env(safe-area-inset-top))] pr-[max(1rem,env(safe-area-inset-right))] pb-[max(1rem,env(safe-area-inset-bottom))] pl-[max(1rem,env(safe-area-inset-left))] focus:outline-none",onClick:E=>{E.target===E.currentTarget&&b(!1)},children:[e.jsx("button",{ref:w,type:"button",onClick:()=>b(!1),"aria-label":"Fermer la photo",className:"absolute right-[max(1rem,env(safe-area-inset-right))] top-[max(1rem,env(safe-area-inset-top))] flex h-11 w-11 items-center justify-center rounded-full bg-white/10 text-white transition-colors hover:bg-white/20 motion-reduce:transition-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white",children:e.jsx(xt,{className:"w-5 h-5"})}),e.jsx("img",{src:t.photo_url,alt:p,className:"max-w-full max-h-full rounded-xl object-contain"})]}),document.body),e.jsx($i,{isOpen:f,onClose:()=>h(!1),onConfirm:N,title:"Supprimer ce lieu",description:"Ce lieu d’entraînement et son équipement détecté seront définitivement supprimés."})]})}function Jo(){const{user:t}=Fs(),{scans:s,loading:n,error:a,refetch:r}=ai(t?.id);return e.jsx(Ue,{loading:n,error:a,empty:s.length===0,loadingFallback:e.jsx("div",{className:"space-y-4",children:[0,1].map(l=>e.jsxs(Ps,{label:"Chargement de tes lieux…",minHeight:"min-h-72",children:[e.jsx(fe,{className:"h-40 w-full rounded-2xl",tone:"dim"}),e.jsx(fe,{className:"h-4 w-24 rounded-full"}),e.jsx("div",{className:"flex gap-2",children:[0,1,2,3].map(i=>
57e.jsx(fe,{className:"h-6 w-20 rounded-lg",tone:"dim"},i))})]},l))}),onRetry:r,errorTitle:"Lieux indisponibles",errorMessage:"Impossible de charger tes lieux d’entraînement. Tes scans enregistrés ne sont pas modifiés.",emptyFallback:e.jsx(st,{density:"section",state:"first_use",icon:Ft,theme:"ember",eyebrow:"Maison, salle ou extérieur",title:"Scanne ton lieu d’entraînement",description:"Une photo suffit pour qu’Alloy repère ton espace et le matériel disponible.",action:e.jsx(Wt,{label:"Scanner mon lieu",icon:"place",message:"Je veux scanner mon lieu d’entraînement et le matériel disponible.",variant:"secondary"})}),children:e.jsx("div",{className:"space-y-4",children:s.map(l=>e.jsx(Ko,{scan:l,onUpdate:r},l.id))})})}function Ma(t){const[s,n,a]=t.split("-").map(Number);return new Date(s,(n??1)-1,a??1)}function Ks(t){return t>=75?"text-success":t>=55?"text-accent":t>=40?"text-warning":"text-error"}function Zo(t){return t>=70?"success":t>=40?"warning":"error"}const Qo={sleep_quality:ft,sleep_trend_3n:oe,sleep_debt:ft,acwr:ue,rhr_deviation:Mt,nutrition_quality:Rr,calendar_stress:Vi,menstrual_phase:Mt,vocal_energy:Er};function Xo({signal:t}){const s=Qo[t.key],n=t.status!=="measured",a=li(t),r=Ks(a);return e.jsxs("div",{className:`flex flex-col items-center gap-1 rounded-lg px-1 py-1.5 ${n?"border border-dashed border-white/20 bg-transparent":"bg-surface/50"}`,title:t.label_detail??void 0,children:[e.jsx(s,{className:`w-3.5 h-3.5 ${n?"text-white/30":r}`}),n?e.jsx("div",{className:"w-full h-1.5 rounded-full bg-background overflow-hidden",children:e.jsx("div",{className:"h-full w-[5px] rounded-full bg-white/20"})}):e.jsx(zt,{value:a,max:100,label:t.label,valueText:`${Math.round(a)} sur 100`,tone:Zo(a),size:"sm",className:"training-signal-progress"}),e.jsx("span",{className:`text-[10px] truncate ${n?"text-white/35":"text-text-tertiary"}`,children:t.label}),e.jsx("span",{className:`text-[8px] text-text-tertiary ${n?"":"font-mono-numbers"}`,children:n?"Non renseigné":`${t.weightPct} %`})]})}function ec({data:t}){if(t.length<2)return null;const s=120,n=32,a=2,r=t.map(g=>g.score),l=Math.min(...r,0),c=Math.max(...r,100)-l||1,m=r.map((g,b)=>({x:a+b/(r.length-1)*(s-a*2),y:a+(n-a*2)-(g-l)/c*(n-a*2)})),u=m.map((g,b)=>`${b===0?"M":"L"} ${g.x} ${g.y}`).join(" "),x=m[m.length-1],d=r[r.length-1];return e.jsxs("svg",{viewBox:`0 0 ${s} ${n}`,className:`w-[120px] h-8 ${Ks(d)}`,"aria-hidden":"true",children:[e.jsx("path",{d:u,fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"}),e.jsx("circle",{cx:x.x,cy:x.y,r:"3",fill:"currentColor"})]})}function tc(){return e.jsxs(V,{padding:"md",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(xe,{icon:ht,theme:"verdant",size:"sm"}),e.jsx("span",{className:"font-medium text-text-primary",children:"Récupération"})]}),e.jsx("p",{className:"text-sm text-text-secondary",children:"Pas encore de score de récupération"}),e.jsx("p",{className:"mt-1 text-xs text-text-tertiary leading-relaxed",children:"Il se calcule chaque matin à partir de tes nuits, de ta charge et de ton check-in. Réponds au check-in du matin d’Alloy, ou note une nuit, et il apparaîtra ici."})]})}function sc({today:t,latest:s,history:n,signals:a,wellbeingToday:r}){const l=_e(),i=t??s;if(!i)return e.jsx(tc,{});const c=t!==null,m=ha(a),u=ri(a),x=ii(a),d=i.score,g=Ks(d),b=44,f=7,h=2*Math.PI*b,v=h-d/100*h,w=(b+f)*2;return e.jsxs(V,{padding:"md",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{icon:ht,theme:"verdant",size:"sm"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{className:"font-medium text-text-primary",children:"Récupération"}),e.jsx("p",{className:"text-[10px] text-text-tertiary",children:c?"Mesurée ce matin":`Mesurée le ${je(Ma(i.date),"d MMMM",{locale:ye})}`})]})]}),e.jsx(ec,{data:n})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"relative flex-shrink-0",children:[e.jsxs("svg",{width:w,height:w,className:`transform -rotate-90 ${g}`,"aria-hidden":"true",children:[e.jsx("circle",{cx:w/2,cy:w/2,r:b,fill:"none",className:"stroke-surface-solid",strokeWidth:f}),e.jsx(te.circle,{cx:w/2,cy:w/2,r:b,fill:"none",stroke:"currentColor",strokeWidth:f,strokeLinecap:"round",strokeDasharray:h,initial:l?{strokeDashoffset:v}:{strokeDashoffset:h},animate:{strokeDashoffset:v},transition:l?{duration:0,delay:0}:{duration:1,ease:[.34,1.56,.64,1]}})]}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[e.jsx("span",{className:"text-2xl font-mono-numbers font-bold text-text-primary",children:d}),e.jsx("span",{className:"text-[10px] font-mono-numbers text-text-tertiary",children:"/100"})]})]}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-1",children:[e.jsx("p",{className:`text-sm font-medium ${g}`,children:Aa(d)}),x&&e.jsx("p",{className:"text-[11px] text-text-tertiary",children:x}),i.recommendation&&e.jsx("p",{className:"text-xs text-text-tertiary leading-relaxed line-clamp-2",children:i.recommendation})]})]}),m.length>0&&e.jsxs("div",{className:"mt-3 grid grid-cols-4 sm:grid-cols-5 ga
57p-1.5",children:[m.map(_=>e.jsx(Xo,{signal:_},_.key)),r&&r.composite_score!==null&&e.jsxs("div",{className:"flex flex-col items-center gap-1 px-1 py-1.5 rounded-lg bg-surface/50",children:[e.jsx(na,{className:"w-3.5 h-3.5 text-rose-400"}),e.jsx(zt,{value:r.composite_score,max:100,label:"Bien-être",valueText:`${r.composite_score} sur 100`,size:"sm",className:"training-signal-progress"}),e.jsx("span",{className:"text-[10px] text-text-tertiary truncate",children:"Bien-être"})]})]}),u&&e.jsx("p",{className:"mt-2.5 text-[11px] leading-relaxed text-text-tertiary",children:u}),d>=80&&e.jsxs("div",{className:"mt-2.5 flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-success/10 w-fit mx-auto",children:[e.jsx(Xe,{className:"w-3 h-3 text-success"}),e.jsx("span",{className:"text-xs text-success font-medium",children:"Séance intense possible"})]})]})}const nc={none:{text:"text-success",label:"Bien récupéré"},mild:{text:"text-accent",label:"Dette légère"},moderate:{text:"text-warning",label:"Dette modérée"},severe:{text:"text-error",label:"Dette sévère"},unknown:{text:"text-text-tertiary",label:"Dette inconnue"}},ac={improving:{icon:gt,tone:"bg-success/15 text-success",label:"En récupération"},worsening:{icon:oe,tone:"bg-error/15 text-error",label:"En augmentation"},stable:{icon:It,tone:"bg-surface text-text-tertiary",label:"Stable"}};function rc({nights:t}){const s=_e();if(t.length===0)return null;const n=Math.max(...t.map(a=>Math.max(a.target_hours,a.actual_hours??0)),1);return e.jsxs("div",{className:"mt-2",children:[e.jsx("div",{className:"flex items-end gap-1 h-11",children:t.map((a,r)=>{const l=a.actual_hours!==null,i=l?Math.min(100,a.actual_hours/n*100):0,c=l&&a.actual_hours<a.target_hours,m=je(Ma(a.date),"EEEEE",{locale:ye}).toUpperCase();return e.jsxs("div",{className:"flex-1 flex flex-col items-center gap-0.5",children:[e.jsx("div",{className:"relative w-full flex-1",children:l?e.jsx(te.div,{className:`absolute bottom-0 w-full rounded-t-sm ${c?"bg-amber-500/60":"bg-sky-400/60"}`,initial:s?!1:{height:0},animate:{height:`${i}%`},transition:s?{duration:0,delay:0}:{delay:.15+r*.04}}):e.jsx("div",{className:"absolute inset-x-0 bottom-0 h-full rounded-t-sm border border-b-0 border-dashed border-white/15",title:"Nuit notée sans durée"})}),e.jsx("span",{className:"text-[9px] text-text-tertiary",children:m})]},a.date)})}),e.jsxs("div",{className:"mt-1.5 flex items-center justify-center gap-3 text-[9px] text-text-tertiary",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"h-2 w-2 rounded-sm bg-sky-400/60"}),"chiffrée"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"h-2 w-2 rounded-sm border border-dashed border-white/30"}),"sans durée"]})]})]})}function ic({debtHours:t,nightsTimed:s,nightsUntimed:n,isMeasured:a,severity:r,nights:l,trend:i}){const c=nc[r],m=i?ac[i]:null,u=m?.icon;return e.jsxs(V,{padding:"md",className:"h-full",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(xe,{icon:ft,theme:"aqua",size:"sm"}),e.jsx("span",{className:"text-xs font-semibold tracking-wide text-text-secondary uppercase",children:"Sommeil"})]}),m&&u&&e.jsxs("div",{className:`flex items-center gap-1 rounded-full px-1.5 py-0.5 text-[10px] flex-none ${m.tone}`,children:[e.jsx(u,{className:"h-2.5 w-2.5"}),e.jsx("span",{children:m.label})]})]}),a&&t!==null?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-baseline gap-1",children:[e.jsx("span",{className:"text-2xl font-mono-numbers font-bold text-text-primary",children:t.toFixed(1)}),e.jsx("span",{className:"text-xs text-text-tertiary",children:"h de dette"})]}),e.jsx("p",{className:`text-[11px] font-medium ${c.text}`,children:c.label}),e.jsxs("p",{className:"mt-0.5 text-[10px] font-mono-numbers text-text-tertiary",children:["estimée sur ",s," nuit",s>1?"s":""," chiffrée",s>1?"s":"",n>0&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"font-mono-numbers",children:n})," sans durée, hors calcul"]})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-sm text-text-secondary",children:"Aucune nuit chiffrée"}),e.jsx("p",{className:"mt-0.5 text-[10px] text-text-tertiary leading-relaxed",children:n>0?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-mono-numbers",children:n})," nuit",n>1?"s":""," notée",n>1?"s":""," sans durée. Dis « j'ai dormi ",e.jsx("span",{className:"font-mono-numbers",children:"7h"})," » à Alloy pour que la dette se calcule."]}):e.jsxs(e.Fragment,{children:["Dis « j’ai dormi ",e.jsx("span",{className:"font-mono-numbers",children:"7h"})," » à Alloy, ou connecte ta montre, et la dette se calcule ici."]})})]}),e.jsx(rc,{nights:l})]})}const La={optimal:{text:"text-success",badge:"bg-success/15 text-success",label:"Charge optimale",icon:oa},high:{text:"text-warning",badge:"bg-warning/15 text-warning",label:"Charge élevée",icon:Te},danger:{text:"text-error",badge:"bg-error/15 text-error",label:"Risque blessure",icon:Te},low:{text:"text-blue-400",badge:"bg-blue-500/15 text-blue-400",label:"Sous-entraîné",icon:gt}},ie=[.8,1.3,1.5],Bn=2;function lc(t){return t>ie[2]?"danger":t>ie[1]?"high":t>=ie[0]?"optimal":"low"}function oc({ratio:t}){const s=_e(),n=200,a=24,r=9,l=7,i=c=>Math.min(Bn,Math.max(0,c))/Bn*n;return e.jsxs("svg",{viewBox:`0 0 ${n} ${a}`,className:"w-full h-6","aria-hidden":"true",children:[e.jsx("rect",{x:0,y:r,width:n,height:l,rx:3.5,className:"fill-surface-solid"}),e.jsx("rect",{x:0,y:r,width:i(ie[0]),height:l,className:"fill-blue-500/15"}),e.jsx("rect",{x:i(ie[0]),y:r,width:i(ie[1])-i(ie[0]),height:l,className:"fill-success/20"}),e.jsx("rect",{x:i(ie[1]),y:r,width:i(ie[2])-i(ie[1]),height:l,className:"fill-warning/20"}),e.jsx("rect",{x:i(ie[2]),y:r,width:n-i(ie[2]),height:l,rx:3.5,className:"fill-error/20"}),e.jsx(te.line,{x1:i(t),y1:r-2,x2:i(t),y2:r+l+2,className:La[lc(t)].text,stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",initial:s?!1:{opacity:0}
57,animate:{opacity:1},transition:s?{duration:0,delay:0}:{delay:.4}}),ie.map(c=>e.jsx("text",{x:i(c),y:r-2,className:"fill-text-tertiary font-mono-numbers",fontSize:"6.5",textAnchor:"middle",children:c.toLocaleString("fr-FR")},c))]})}function cc({acwr:t,zone:s,acuteLoad:n,chronicLoad:a,sessionsLogged:r}){const l=s?La[s]:null,i=t!==null&&Number.isFinite(t);return e.jsxs(V,{padding:"md",className:"h-full",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(xe,{icon:Q,theme:"gold",size:"sm"}),e.jsx("span",{className:"text-xs font-semibold tracking-wide text-text-secondary uppercase",children:"Charge"})]}),i&&l&&e.jsxs("div",{className:`flex items-center gap-1 rounded-full px-1.5 py-0.5 text-[10px] flex-none ${l.badge}`,children:[e.jsx(l.icon,{className:"h-2.5 w-2.5"}),e.jsx("span",{children:l.label})]})]}),i?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-baseline gap-1",children:[e.jsx("span",{className:"text-2xl font-mono-numbers font-bold text-text-primary",children:t.toLocaleString("fr-FR",{minimumFractionDigits:2,maximumFractionDigits:2})}),e.jsxs("span",{className:"text-xs text-text-tertiary",children:["ratio ",e.jsx("span",{className:"font-mono-numbers",children:"7 j / 28 j"})]})]}),e.jsx(oc,{ratio:t}),n!==null&&a!==null&&e.jsxs("div",{className:"mt-1 flex justify-between text-[10px] text-text-tertiary",children:[e.jsxs("span",{children:["Récent :"," ",e.jsx("span",{className:"font-mono-numbers text-text-secondary",children:Math.round(n)})]}),e.jsxs("span",{children:["Base :"," ",e.jsx("span",{className:"font-mono-numbers text-text-secondary",children:Math.round(a)})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-sm text-text-secondary",children:"Pas encore de charge mesurée"}),e.jsx("p",{className:"mt-0.5 text-[10px] text-text-tertiary leading-relaxed",children:r>0?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-mono-numbers",children:r})," séance",r>1?"s":""," enregistrée",r>1?"s":""," sur"," ",e.jsx("span",{className:"font-mono-numbers",children:_s})," jours. Le ratio a besoin de quelques semaines de séances suivies pour vouloir dire quelque chose."]}):e.jsxs(e.Fragment,{children:["Le ratio compare tes ",e.jsx("span",{className:"font-mono-numbers",children:"7"})," derniers jours à tes ",e.jsx("span",{className:"font-mono-numbers",children:_s}),". Enregistre tes séances et il apparaîtra ici."]})})]})]})}function us({minHeight:t,label:s}){return e.jsxs(Ps,{label:s,minHeight:t,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fe,{className:"h-8 w-8 rounded-xl"}),e.jsx(fe,{className:"h-4 min-w-0 flex-1 rounded-full"})]}),e.jsx(fe,{className:"h-2 w-full rounded-full",tone:"dim"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(fe,{className:"h-12 flex-1 rounded-xl",tone:"dim"}),e.jsx(fe,{className:"h-12 flex-1 rounded-xl",tone:"dim"})]})]})}function dc({userId:t,timezone:s,openTool:n=null,onOpenToolChange:a}){const[r,l]=o.useState(!1),i=oi(t,s),c=Tl(t),m=Al(t),[u,x]=o.useState(!1),{today:d,loading:g,error:b,refetch:f}=ci(u?t:void 0,30,s);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("section",{"aria-label":"Ton état",className:"overflow-hidden rounded-[22px] border border-white/10 bg-gradient-to-b from-surface to-surface-solid",children:[e.jsx(Gr,{title:"Ton état",subtitle:"Ton corps, tes repères du moment"}),e.jsx(go,{userId:t,afterStage:e.jsx(mo,{userId:t,readiness:i,sleep:c,load:m,onDetails:()=>{x(!0),l(!0)}})})]}),e.jsx(ke,{open:r,onClose:()=>l(!1),title:"Comprendre mon état",eyebrow:"Signaux et historiques",children:e.jsxs("div",{className:"space-y-4 p-4",children:[e.jsx(Me,{label:"Récupération",resetKeys:[t],children:e.jsx(Ue,{loading:i.loading||g,error:i.error||b,loadingFallback:e.jsx(us,{minHeight:"min-h-44",label:"Chargement de ta récupération…"}),onRetry:()=>{i.refetch(),f()},errorTitle:"Récupération indisponible",errorMessage:"Impossible de charger ton état de récupération.",children:e.jsx(Ke,{helpKey:"etat.recovery",children:e.jsx(sc,{today:i.today,latest:i.latest,history:i.history,signals:i.signals,wellbeingToday:d})})})}),e.jsx(Me,{label:"Sommeil",resetKeys:[t],children:e.jsx(Ue,{loading:c.loading,error:c.error,loadingFallback:e.jsx(us,{minHeight:"min-h-40",label:"Chargement de ta dette de sommeil…"}),onRetry:c.refetch,errorTitle:"Sommeil indisponible",errorMessage:"Impossible de charger tes nuits enregistrées.",children:e.jsx(Ke,{helpKey:"etat.sleep",children:e.jsx(ic,{debtHours:c.debtHours,nightsTimed:c.nightsTimed,nightsUntimed:c.nightsUntimed,isMeasured:c.isMeasured,severity:c.severity,nights:c.nights,trend:c.trend})})})}),e.jsx(Me,{label:"Charge",resetKeys:[t],children:e.jsx(Ue,{loading:m.loading,error:m.error,loadingFallback:e.jsx(us,{minHeight:"min-h-40",label:"Chargement de ta charge…"}),onRetry:m.refetch,errorTitle:"Charge indisponible",errorMessage:"Impossible de charger ta charge d’entraînement.",children:e.jsx(Ke,{helpKey:"etat.load",children:e.jsx(cc,{acwr:m.acwr,zone:m.zone,acuteLoad:m.acuteLoad,chronicLoad:m.chronicLoad,sessionsLogged:m.sessionsLogged})})})})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(Me,{label:"Analyses",resetKeys:[t],children:e.jsxs("div",{id:"section-analyses",className:"scroll-mt-32 space-y-3",children:[e.jsx(Un,{icon:Gi,title:"Analyses vidéo",open:n==="analyses",onToggle:()=>a?.(n==="analyses"?null:"analyses")}),n==="analyses"&&e.jsx(Ke,{helpKey:"training.analyses",children:e.jsx(Wo,{})})]})}),e.jsx(Me,{label:"Lieux",resetKeys:[t],children:e.jsxs("div",{id:"section-lieu",className:"scroll-mt-32 space-y-3",children:[e.jsx(Un,{icon:Os,title:"Lieux d’entraînement",open:n==="lieu",onToggle:()=>a?.(n==="lieu"?null:"lieu")}),n==="lieu"&&e.jsx(Ke,{helpKey:"training.locations",children:e.jsx(Jo,{})})]})})]})]})}function Un({icon:t,title:s,open:n,onToggle:a}){return e.jsxs("button",{type:"button",onClick:a,"aria-expanded":n,className:"flex min-h-11 w-full items-center gap-2 rounded-xl text-left transition-colors hover:bg-white/[0.03] motion-reduce:transition-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/60",children:[e.jsx("span",{className:"min-w-0 flex-1",children:e.jsx(Da,{icon:t,title:s})}),e.jsx(Be,{className:`h-4 w-4 flex-none text-text-tertiary transition-transform duration-200 motion-reduce:transition-none ${n?"rotate-180":""}`,"aria-hidden":"true"})]})}function zn(t){if(!t||typeof t!="object"||Array.isArray(t))return null;const s=t,n=Array.isArray(s.muscles)?s.muscles.filter(g=>typeof g=="string").map(g=>
57g.trim()).filter(Boolean).slice(0,8):[],a=typeof s.rationale=="string"&&s.rationale.trim()?di(s.rationale).slice(0,280):null,r=Number(s.suggested_duration_min),l=Number.isFinite(r)&&r>0&&r<=240?Math.round(r):null,i=(g,b=80)=>typeof g=="string"&&g.trim()?g.trim().slice(0,b):null,c=i(s.focus,60),m=i(s.style,40),u=i(s.target_date,10),x=s.presentation&&typeof s.presentation=="object"?s.presentation:null,d=x?{emoji:i(x.emoji,8),label:i(x.label,40)}:null;return n.length===0&&!a&&l===null&&!c?null:{muscles:n,rationale:a,suggestedDurationMin:l,focus:c,style:m,targetDate:u,presentation:d,scheduleReason:i(s.schedule_reason,240),durationReason:i(s.duration_reason,240)}}function uc(t){if(!t||typeof t!="object"||Array.isArray(t))return null;const s=t,n=typeof s.local_date=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(s.local_date)?s.local_date:null;return n?{localDate:n,overridable:s.overridable===!0,dose:s.dose==="light"||s.dose==="full"?s.dose:null,doseSource:s.dose_source==="button"||s.dose_source==="card"?s.dose_source:null,consumed:typeof s.consumed_at=="string"&&s.consumed_at.length>0}:null}function Js(t){if(!t)return null;const s=t.focus?.trim()??"",n=ba(s)??mc(t.muscles)??(s||null);return n?`${n.charAt(0).toLocaleUpperCase("fr-FR")}${n.slice(1)}`:null}function mc(t){if(t.length===0)return null;const s=ga(t).map(a=>a.replace(/[_-]+/g," ")),n=s.length===1?s[0]:`${s.slice(0,-1).join(", ")} et ${s[s.length-1]}`;return n.charAt(0).toUpperCase()+n.slice(1)}const Cu=22,xc=25;function ks(t,s){const n=t==="prepare"?"Préparer : ":"Plutôt : ",a=t==="prepare"?"Préparer la suite":"Plutôt l’autre option",r=c=>c&&`${n}${c}`.length<=xc?`${n}${c}`:null,l=c=>c&&`${c.charAt(0).toLocaleUpperCase("fr-FR")}${c.slice(1)}`,i=s?.muscles.length===1?l(ga(s.muscles)[0]??""):null;return r(vi(s?.focus))??r(i)??a}const pc={full_body:"corps entier",upper_lower:"haut et bas du corps en alternance",push_pull_legs:"poussée, tirage, jambes"};function qa(t){if(!t||typeof t!="object"||Array.isArray(t))return null;const s=t,n=[],a=s.presentation&&typeof s.presentation=="object"?s.presentation:null,r=typeof a?.label=="string"?a.label.trim():"";r&&n.push(`Phase ${r}`);const l=typeof s.rationale=="string"?s.rationale.trim():"",i=/^(?:alternative — )?rotation ([a-z_]+)/.exec(l);if(i){const d=pc[i[1]];d&&n.push(`la suite de ta rotation ${d}`);const g=/— (.+?) sauté \(récupération\)/.exec(l);g&&n.push(`${g[1]} attend : ces muscles récupèrent encore`),/tous les groupes en récupération/.test(l)&&n.push("tout récupère encore, on reprend le groupe le plus ancien")}const c=s.calendar_slot&&typeof s.calendar_slot=="object"?s.calendar_slot:null,m=typeof c?.start_at=="string"?new Date(c.start_at):null,u=typeof c?.timezone=="string"&&fc(c.timezone)?c.timezone:null;if(m&&Number.isFinite(m.getTime())&&u){const d=new Intl.DateTimeFormat("fr-FR",{timeZone:u,hour:"2-digit",minute:"2-digit"}).format(m);n.push(`calée sur ton créneau de ${d}`)}if(n.length===0)return null;const x=n.join(" · ");return`${x.charAt(0).toUpperCase()}${x.slice(1)}.`}function fc(t){if(t==="UTC")return!0;const s=Intl.supportedValuesOf;return typeof s=="function"&&s("timeZone").includes(t)}const In="objective, split_type, next_focus, next_focus_alt";function hc(t){const[s,n]=o.useState(null),[a,r]=o.useState(!!t),[l,i]=o.useState(null),[c,m]=o.useState(void 0),u=o.useRef(!0),x=o.useRef(0),d=o.useRef(t);d.current=t,o.useEffect(()=>(u.current=!0,()=>{u.current=!1}),[]);const g=o.useCallback(async()=>{if(!u.current||d.current!==t)return;const b=++x.current,f=()=>u.current&&b===x.current&&d.current===t;if(m(t),n(null),r(!!t),i(null),!t){f()&&r(!1);return}try{const h=_=>$.from("training_trajectory").select(_).eq("user_id",t).eq("status","active").maybeSingle();let v=await h(`${In}, rest_advice`);if(v.error&&v.error.code==="42703"&&(be("training","trajectory_rest_advice_unreadable",{error:v.error}),v=await h(In)),!f())return;if(v.error)throw v.error;const w=v.data;n(w?{objective:w.objective,splitType:w.split_type,nextFocus:zn(w.next_focus),nextFocusAlt:zn(w.next_focus_alt),restAdvice:uc(w.rest_advice)}:null)}catch(h){f()&&(n(null),i(h instanceof Error?h.message:"Trajectoire indisponible"))}finally{f()&&r(!1)}},[t]);return o.useEffect(()=>{g()},[g]),c!==t?{trajectory:null,loading:!!t,error:null,refetch:g}:{trajectory:s,loading:a,error:l,refetch:g}}const gc={accepted:"Training accepté",declined:"Training refusé",personalizing:"Adaptation en cours de vérification"};function bc(t){if(!t||typeof t!="object")return!1;const s=t;return s.status==="conflict_scheduled"||s.reason==="team_session_conflict"}function yc(t){return Gt(t)?"La génération a pris trop de temps. Son résultat n’est pas confirmé : actualise avant toute nouvelle tentative.":t instanceof Error?t.message:"Ton choix n’a pas été confirmé."}function jc({trainingProposal:t,onRespondTrainingProposal:s,onRefreshTeam:n,allowWithdraw:a=!1,onWithdrawn:r,context:l="gaming",withdrawOpen:i,onWithdrawOpenChange:c,showWithdrawButton:m=!0,primarySlot:u}){const x=`response-${o.useId().replace(/:/g,"")}`,[d,g]=o.useState(!1),b=i??d,f=F=>{g(F),c?.(F)},[h,v]=o.useState(null),w=o.useRef(!1),_=o.useRef(null),[T,N]=o.useState(null),[y,k]=o.useState(null),[p,S]=o.useState(!1),[j,C]=o.useState(""),[A,D]=o.use
57State(null),[E,L]=o.useState(!1),q=o.useRef(t);o.useEffect(()=>{q.current!==t&&(q.current=t,E||N(null),k(null),D(null)),t.own_response===_.current&&_.current!==null&&(L(!1),N(null))},[t,E]);const R=async(F,K=!1)=>{if(!(!t||!s||w.current||E)){w.current=!0,_.current=F.response==="declined"?"declined":"accepted",v(F.response),N(null),k(null);try{await s(t.id,F.response,{personalizationRequest:F.personalizationRequest,replaceExisting:K}),F.response==="declined"&&r?.(),k(F.response==="declined"?"Ton choix est enregistré.":"Ton training personnel est prêt."),S(!1),C(""),D(null)}catch(Ee){if(!K&&bc(Ee))S(!1),D(F);else{const se=Gt(Ee);L(se),N(yc(Ee))}}finally{w.current=!1,v(null)}}},B=()=>{const F=j.trim();!F||F.length>500||R({response:"personalize",personalizationRequest:F})},O=t?.own_response,G=O==="accepted"||O==="declined"||O==="personalizing",z=!!h||E,Y=l==="training"&&(O==="accepted"||O==="declined"),X=l==="training",ae=X?e.jsx(P,{type:"button",variant:"aqua",disabled:z,className:"min-h-12 flex-1",onClick:()=>void R({response:"accepted"}),children:h==="accepted"?"Validation…":"Participer"}):e.jsx(P,{type:"button",disabled:z,onClick:()=>void R({response:"accepted"}),variant:"secondary",children:h==="accepted"?"Validation…":"Même training"}),I=t.can_personalize?e.jsx(P,{type:"button",disabled:z,onClick:()=>{N(null),k(null),S(!0)},variant:"secondary",className:X?"flex-1":"",children:X?"Adapter ma séance":"Adapter pour moi"}):null,M=e.jsx(P,{type:"button",disabled:z,onClick:()=>void R({response:"declined"}),variant:"ghost",className:X?"flex-1":"",children:h==="declined"?"Enregistrement…":X?"Passer mon tour":"Pas cette fois"});return e.jsxs(e.Fragment,{children:[G&&Y?null:e.jsx("div",{className:"mt-4",children:G?e.jsxs("p",{role:"status",className:"rounded-xl border border-white/[0.08] bg-white/[0.04] px-3 py-2 text-sm font-medium",children:["Ton choix : ",gc[O]]}):s?X?e.jsxs("div",{className:"space-y-2","aria-label":"Répondre au training proposé",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[ae,u]}),e.jsxs("div",{className:"flex items-center gap-2",children:[I,M]})]}):e.jsxs("div",{className:"grid gap-2 sm:grid-cols-3","aria-label":"Répondre au training proposé",children:[ae,I,M]}):e.jsx("p",{className:"text-xs text-text-secondary",children:"Ta réponse est en attente."})}),T&&e.jsx("p",{role:"alert",className:"mt-3 text-sm text-error",children:T}),y&&e.jsx("p",{role:"status",className:"mt-3 text-sm text-cyan-200",children:y}),(E||O==="personalizing")&&n&&e.jsx(P,{type:"button",variant:"secondary",fullWidth:!0,disabled:!!h,onClick:()=>void n(),children:"Vérifier le résultat"}),a&&m&&O==="accepted"&&e.jsx(P,{type:"button",variant:"ghost",fullWidth:!0,disabled:z,onClick:()=>f(!0),children:"Me désister du raid"}),e.jsx(ke,{open:b,onClose:()=>{h||f(!1)},title:"Te désister du raid ?",eyebrow:"Ton choix",footer:e.jsx(P,{type:"button",variant:"danger",fullWidth:!0,disabled:z,onClick:async()=>{await R({response:"declined"}),f(!1)},children:"Confirmer mon désistement"}),children:e.jsx("p",{className:"p-4 text-sm text-text-secondary",children:"Ta séance personnelle reste enregistrée. Elle ne comptera plus pour ce raid. Les autres membres conservent leur séance."})}),e.jsx(ke,{open:p,onClose:()=>{h||S(!1)},title:"Adapter ce training pour moi",eyebrow:"Raid de l’escouade",maxWidthClassName:"sm:max-w-md",footer
57:e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsx(P,{type:"button",disabled:!!h,onClick:()=>S(!1),variant:"secondary",children:"Annuler"}),e.jsx(P,{type:"button",disabled:!j.trim()||!!h,onClick:B,variant:"primary",children:h==="personalize"?"Adaptation…":"Créer ma version"})]}),children:e.jsxs("div",{className:"space-y-4 p-4",children:[e.jsx("p",{id:`${x}-personalization-private`,className:"text-sm text-text-secondary",children:"Cette demande est privée : elle sert uniquement à adapter ta séance. Les autres membres gardent les mêmes exercices dans le même ordre, sans voir ton texte. La durée du raid reste commune ; Alloy adapte tes charges, séries, repos et contraintes."}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:`${x}-personalization`,className:"text-sm font-semibold text-text-primary",children:"Ce qu’Alloy doit adapter pour toi"}),e.jsx("textarea",{id:`${x}-personalization`,value:j,maxLength:500,rows:5,disabled:!!h,"aria-describedby":`${x}-personalization-private ${x}-personalization-count`,onChange:F=>C(F.currentTarget.value),placeholder:"Ex. : protège mon genou gauche et propose une variante sans saut.",className:"mt-2 min-h-32 w-full resize-y rounded-xl border border-white/10 bg-black/20 px-3 py-3 text-base text-text-primary placeholder:text-text-tertiary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent disabled:opacity-50"}),e.jsxs("p",{id:`${x}-personalization-count`,className:"mt-1 text-right text-xs text-text-tertiary","aria-live":"polite",children:[e.jsxs("span",{className:"font-mono-numbers",children:[j.length,"/500"]})," ","caractères"]})]})]})}),e.jsx(ke,{open:!!A,onClose:()=>{h||D(null)},title:"Remplacer ta séance planifiée ?",eyebrow:"Confirmation requise",maxWidthClassName:"sm:max-w-md",footer
57:e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsx(P,{type:"button",disabled:!!h,onClick:()=>D(null),variant:"secondary",children:"Garder ma séance"}),e.jsx(P,{type:"button",disabled:!A||!!h,onClick:()=>{A&&R(A,!0)},variant:"primary",children:h?"Remplacement…":"Remplacer ma séance"})]}),children:e.jsxs("div",{className:"space-y-3 p-4 text-sm leading-relaxed text-text-secondary",children:[e.jsx("p",{children:"Une séance est déjà planifiée aujourd’hui. La séance du raid la remplacera seulement pour toi ; les choix des autres membres ne changent pas."}),e.jsx("p",{children:"Une séance déjà commencée ne sera jamais remplacée."})]})})]})}function vc(t){return t.kind==="transfer"?{title:`Nommer ${t.member.display_name} chef d’escouade ?`,confirm:"Confirmer le transfert",body:"Tu deviendras membre. Les liens d’invitation actifs seront révoqués et le nouveau chef pourra en créer un autre."}:t.kind==="leave"?{title:"Quitter cette escouade ?",confirm:"Confirmer ma sortie",body:"Ton suivi et tes séances personnelles restent conservés. Tu ne verras plus les activités réservées à cette escouade."}:{title:"Mettre fin à cette escouade ?",confirm:"Mettre fin à l’escouade",body:"Tous les membres seront retirés. Les invitations, le défi et la proposition de training actifs seront annulés. Les suivis personnels restent conservés."}}function _c({open:t,onClose:s,team:n,onTransferLeadership:a,onLeaveTeam:r,onEndTeam:l,onRefresh:i}){const[c,m]=o.useState(null),[u,x]=o.useState(!1),d=o.useRef(!1),[g,b]=o.useState(null),[f,h]=o.use
57State(!1),v=n.role==="leader",w=n.members.filter(y=>!y.is_self&&y.role!=="leader");o.useEffect(()=>{t||(m(null),d.current=!1,x(!1),b(null))},[t]),o.useEffect(()=>{h(!1)},[n]);const _=()=>{d.current||s()},T=async()=>{if(!(!c||d.current||f)){d.current=!0,x(!0),b(null);try{c.kind==="transfer"?await a(c.member.member_id):c.kind==="leave"?await r():await l(),s()}catch(y){if(Gt(y)){h(!0);let k=!1;try{k=await i()}catch{k=!1}h(!k),b(k?"Le résultat n’était pas confirmé. L’état de l’escouade a été actualisé : vérifie-le avant de recommencer.":"Le résultat n’est pas confirmé et l’escouade n’a pas pu être actualisée. Réessaie l’actualisation avant toute autre action.")}else b(y instanceof Error?y.message:"Cette action n’a pas été confirmée.")}finally{d.current=!1,x(!1)}}},N=c?vc(c):null;return e.jsx(ke,{open:t,onClose:_,title:N?.title??"Gérer l’escouade",eyebrow:n.name,maxWidthClassName:"sm:max-w-md",footer:N?e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsx(P,{type:"button",disabled:u||f,onClick:()=>m(null),variant:"secondary",children:"Annuler"}),e.jsx(P,{type:"button",disabled:u||f,onClick:()=>void T(),variant:"danger",children:u?"Enregistrement…":N.confirm})]}):void 0,children:e.jsxs("div",{className:"space-y-5 p-4",children:[N?e.jsx("div",{className:"rounded-2xl border border-error/20 bg-error/[0.06] p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Is,{className:"mt-0.5 h-5 w-5 flex-none text-error","aria-hidden":"true"}),e.jsx("p",{className:"text-sm leading-relaxed text-text-secondary",children:N.body})]})}):v?e.jsxs(e.Fragment,{children:[e.jsxs("section",{"aria-labelledby":"team-management-transfer-title",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ca,{className:"mt-0.5 h-5 w-5 flex-none text-amber-200","aria-hidden":"true"}),e.jsxs("div",{children:[e.jsx("h3",{id:"team-management-transfer-title",className:"font-bold text-text-primary",children:"Choisir un nouveau chef"}),e.jsx("p",{className:"mt-1 text-sm leading-relaxed text-text-secondary",children:"Pour quitter une escouade qui compte plusieurs membres, transfère d’abord ce rôle."})]})]}),w.length>0?e.jsx("ul",{className:"mt-3 space-y-2","aria-label":"Membres pouvant devenir chef",children:w.map(y=>e.jsxs("li",{className:"flex min-h-12 items-center justify-between gap-3 rounded-xl border border-white/[0.08] bg-white/[0.03] px-3 py-2",children:[e.jsx("span",{className:"min-w-0 truncate text-sm font-medium text-text-primary",children:y.display_name}),e.jsxs("button",{type:"button",disabled:u||f,onClick:()=>{b(null),m({kind:"transfer",member:y})},className:"min-h-11 flex-none rounded-xl px-3 text-xs font-bold text-cyan-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-cyan-300 disabled:opacity-50","aria-label":`Nommer ${y.display_name} chef d’escouade`,children:[e.jsx(rl,{className:"mr-1.5 inline h-4 w-4","aria-hidden":"true"}),"Nommer chef"]})]},y.member_id))}):e.jsx("p",{className:"mt-3 text-sm text-text-tertiary",children:"Aucun autre membre ne peut recevoir le rôle pour le moment."})]}),e.jsx("section",{className:"border-t border-white/[0.08] pt-4","aria-label":"Fin de l’escouade",children:e.jsx("button",{type:"button",disabled:u||f,onClick:()=>{b(null),m({kind:"end"})},className:"min-h-11 text-sm font-semibold text-error focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-error disabled:opacity-50",children:"Mettre fin à l’escouade"})})]}):e.jsxs("section",{"aria-labelledby":"team-management-leave-title",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Na,{className:"mt-0.5 h-5 w-5 flex-none text-text-secondary","aria-hidden":"true"}),e.jsxs("div",{children:[e.jsx("h3",{id:"team-management-leave-title",className:"font-bold text-text-primary",children:"Quitter l’escouade"}),e.jsx("p",{className:"mt-1 text-sm leading-relaxed text-text-secondary",children:"Tu gardes ton compte, tes séances et ton suivi personnel."})]})]}),e.jsx("button",{type:"button",disabled:u||f,onClick:()=>{b(null),m({kind:"leave"})},className:"mt-4 min-h-11 text-sm font-semibold text-error focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-error disabled:opacity-50",children:"Qu
57itter cette escouade"})]}),g&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{role:"alert",className:"text-sm leading-relaxed text-error",children:g}),f&&e.jsx(P,{type:"button",disabled:u,onClick:()=>{d.current||(d.current=!0,x(!0),(async()=>{try{const y=await i();h(!y),b(y?"L’état de l’escouade a été actualisé. Vérifie-le avant de continuer.":"L’escouade n’a pas pu être actualisée. Aucune nouvelle action n’est autorisée pour le moment.")}catch{h(!0),b("L’escouade n’a pas pu être actualisée. Aucune nouvelle action n’est autorisée pour le moment.")}finally{d.current=!1,x(!1)}})())},variant:"secondary",children:"Actualiser l’escouade"})]})]})})}const ut="flex min-h-11 w-full items-center gap-2.5 rounded-lg px-3 text-left text-[13px] text-text-primary transition-colors motion-reduce:transition-none hover:bg-white/[0.06] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/50 disabled:cursor-not-allowed disabled:opacity-50";function Nc({team:t,onInvite:s,canWithdraw:n=!1,onWithdraw:a,onTransferLeadership:r,onLeaveTeam:l,onEndTeam:i,onRefresh:c,fullDescribedBy:m}){const[u,x]=o.useState(!1),[d,g]=o.useState(!1),b=o.useRef(null),h=Math.max(t.member_count,t.members.length)>=Math.min(t.member_limit,ys),v=t.role==="leader";return e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",ref:b,onClick:()=>x(w=>!w),"aria-expanded":u,"aria-haspopup":"menu","aria-label":"Plus d’actions sur l’escouade",className:"flex min-h-11 w-11 flex-none items-center justify-center rounded-xl border border-cyan-300/30 text-cyan-100 transition-colors motion-reduce:transition-none hover:bg-cyan-300/[0.12] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-cyan-300",children:e.jsx(wi,{className:"h-5 w-5","aria-hidden":"true"})}),e.jsx(Ar,{open:u,onClose:()=>x(!1),anchorRef:b,label:"Actions de l’escouade",widthClassName:"w-64",children:e.jsxs("div",{className:"p-1.5",role:"menu",children:[v&&e.jsxs("button",{type:"button",role:"menuitem",disabled:h,"aria-describedby":h?m:void 0,onClick:()=>{x(!1),s()},className:ut,children:[e.jsx(wa,{className:"h-4 w-4 shrink-0 text-text-tertiary","aria-hidden":"true"}),h?"Escouade complète":"Inviter des proches"]}),e.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{x(!1),g(!0)},className:ut,children:[e.jsx(Dr,{className:"h-4 w-4 shrink-0 text-text-tertiary","aria-hidden":"true"}),"Gérer l’escouade"]}),n&&a&&e.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{x(!1),a()},className:ut,children:[e.jsx(Na,{className:"h-4 w-4 shrink-0 text-text-tertiary","aria-hidden":"true"}),"Me désister du raid"]}),e.jsxs(mn,{to:"/settings/notifications#social",role:"menuitem",onClick:()=>x(!1),className:ut,children:[e.jsx(Mr,{className:"h-4 w-4 shrink-0 text-text-tertiary","aria-hidden":"true"}),"Messages des défis et de l’escouade"]}),e.jsxs(mn,{to:"/settings/community",role:"menuitem",onClick:()=>x(!1),className:ut,children:[e.jsx(ge,{className:"h-4 w-4 shrink-0 text-text-tertiary","aria-hidden":"true"}),"Visibilité et partage"]})]})}),e.jsx(_c,{open:d,onClose:()=>g(!1),team:t,onTransferLeadership:r,onLeaveTeam:l,onEndTeam:i,onRefresh:c})]})}function De(t){return typeof t=="string"?t.replace(/\s+/g," ").trim():""}function wc(t){const s=[],n=(a,r="execution")=>{if(typeof a=="string"){const c=De(a);c&&s.push({type:r,text:c,priority:0,target_level:"all"});return}if(!a||typeof a!="object"||Array.isArray(a))return;const l=a,i=De(l.cue_fr)||De(l.cue)||De(l.text);i&&s.push({type:De(l.type)||r,text:i,priority:typeof l.priority=="number"&&Number.isFinite(l.priority)?l.priority:0,target_level:De(l.target_level)||"all"})};if(Array.isArray(t))t.forEach(a=>n(a));else if(t&&typeof t=="object"){const a=t;if(a.cue_fr||a.cue||a.text)n(a);else for(const[r,l]of Object.entries(a))Array.isArray(l)?l.forEach(i=>n(i,r)):n(l,r)}return s}function kc(t,s){return`https://www.youtube.com/results?search_query=${encodeURIComponent(`${De(s)||De(t)} exercice tutorial`)}`}const Sc=1,Cc=.5,Tc=2.5;function Zs({card:t,variant:s,alt:n,fallback:a,height:r,className:l="",loading:i="lazy"}
57){const c=ja(t,s),m=ki(t,s),[u,x]=o.useState(null),[d,g]=o.useState(null),b=m??(u&&u.src===c?u.ratio:Sc),f=r!==void 0?{height:r,width:Math.round(r*b)}:{aspectRatio:String(b)},h=c&&d!==c?c:null;return e.jsx("div",{className:`relative overflow-hidden ${r!==void 0?"flex-none":"block"} ${l}`,style:f,"data-illustration-ratio":b.toFixed(3),children:h?e.jsx("img",{src:h,alt:n,loading:i,decoding:"async",className:"h-full w-full object-contain",onLoad:v=>{if(m!==null)return;const{naturalWidth:w,naturalHeight:_}=v.currentTarget;if(!(w>0)||!(_>0))return;const T=w/_;x({src:h,ratio:Math.min(Tc,Math.max(Cc,T))})},onError:()=>g(h)}):e.jsx("div",{className:"flex h-full w-full items-center justify-center",children:a})})}function Ec({open:t,onClose:s,src:n,title:a}){return e.jsx(Lr,{open:t,onClose:s,title:a,description:"Fais glisser de côté pour voir chaque phase.",maxWidthClassName:"max-w-5xl",children:e.jsx("div",{className:"overflow-x-auto overscroll-x-contain rounded-xl bg-surface",children:e.jsx("img",{src:n,alt:a,className:"block h-[60vh] max-h-[1024px] w-auto max-w-none","data-testid":"exercise-illustration-viewer-image"})})})}const Wn={primary:{bg:"bg-accent/15",text:"text-accent"},secondary:{bg:"bg-blue-500/15",text:"text-blue-400"},stabilizer:{bg:"bg-slate-500/15",text:"text-slate-400"}},Rc={beginner:{label:"Debutant",tone:"success"},easy:{label:"Facile",tone:"success"},intermediate:{label:"Intermediaire",tone:"accent"},advanced:{label:"Avance",tone:"warning"}
57,expert:{label:"Expert",tone:"error"}},Hn={safety:{label:"Securite",color:"text-error",bg:"bg-error/10"},setup:{label:"Placement",color:"text-blue-400",bg:"bg-blue-500/10"},execution:{label:"Execution",color:"text-accent",bg:"bg-accent/10"},breathing:{label:"Respiration",color:"text-teal-400",bg:"bg-teal-500/10"}};function Et({title:t,icon:s,children:n,defaultOpen:a=!1}){const[r,l]=o.useState(a);return e.jsxs("div",{className:"border border-white/5 rounded-xl overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>l(!r),"aria-expanded":r,className:"w-full flex items-center gap-2.5 px-3.5 py-3 text-left hover:bg-surface/50 transition-colors motion-reduce:transition-none",children:[s,e.jsx("span",{className:"text-sm font-medium text-text-primary flex-1",children:t}),r?e.jsx(et,{className:"w-4 h-4 text-text-tertiary"}):e.jsx(Be,{className:"w-4 h-4 text-text-tertiary"})]}),r&&e.jsx("div",{className:"px-3.5 pb-3.5 pt-0",children:n})]})}function ms(t){return t.name_fr||t.name||t.exercise_name||""}function Qs({exercise:t,catalogImageUrl:s,sessionForgeTheme:n="ember",onClose:a}){const{detail:r,loading:l}=bl(t.name),i=s||t.image_url||r?.image_url,c=ja(i,"clean"),[m,u]=o.useState(!1),x=kc(t.name,r?.translation_fr?.name||r?.name_fr),d=r?Rc[r.difficulty]:null,g=r?.coaching_cues?wc(r.coaching_cues):[],b=g.reduce((f,h)=>{var v;return(f[v=h.type]||(f[v]=[])).push(h.text),f},{});return e.jsxs(ke,{open:!0,onClose:a,title:t.name,children:[e.jsx("button",{type:"button",onClick:()=>c&&u(!0),disabled:!c,"aria-label":`Agrandir l'illustration : ${t.name}`,className:"block w-full cursor-zoom-in disabled:cursor-default",children:e.jsx(Zs,{card:i,variant:"clean",alt:t.name,loading:"eager",className:"mx-4 rounded-2xl bg-surface",fallback:e.jsx(xe,{icon:Q,theme:n,size:"xl"})})}),c&&e.jsx(Ec,{open:m,onClose:()=>u(!1),src:c,title:t.name}),e.jsxs("div",{className:"px-4 pt-4 space-y-4",children:[r?.description_short&&e.jsx("p",{className:"text-sm text-text-secondary leading-relaxed",children:r.description_short}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.sets!=null&&t.reps!=null&&e.jsxs("div",{className:"font-mono-numbers flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-surface text-sm text-text-primary",children:[e.jsx(Ut,{className:"w-3.5 h-3.5 text-accent"}),t.sets," x ",t.reps]}),t.rest_seconds!=null&&e.jsxs("div",{className:"font-mono-numbers flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-surface text-sm text-text-primary",children:[e.jsx(Vs,{className:"w-3.5 h-3.5 text-accent"}),t.rest_seconds,"s repos"]}),t.weight_kg!=null&&e.jsxs("div",{className:"font-mono-numbers flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-surface text-sm text-text-primary",children:[e.jsx(Q,{className:"w-3.5 h-3.5 text-accent"}),t.weight_kg," kg"]})]}),l&&e.jsxs("div",{className:"flex items-center gap-2 py-4",children:[e.jsx("div",{className:"w-4 h-4 border-2 border-accent border-t-transparent rounded-full animate-spin motion-reduce:animate-none"}),e.jsx("span",{className:"text-sm text-text-tertiary",children:"Chargement details..."})]}),r&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[d&&e.jsx(me,{icon:ht,tone:d.tone,size:"md",children:d.label}),r.discipline&&e.jsx("span",{className:"inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium bg-surface text-text-secondary capitalize",children:r.discipline}),r.movement_pattern&&e.jsxs("span",{className:"inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium bg-surface text-text-secondary capitalize",children:[e.jsx(Ms,{className:"w-3 h-3"}),r.movement_pattern.replace(/_/g," ")]})]}),r.muscle_groups?.length>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium text-text-secondary mb-2",children:"Muscles cibles"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:r.muscle_groups.map(f=>{const h=Wn[f.involvement_type]||Wn.secondary;return e.jsxs("span",{className:`px-2.5 py-1 rounded-lg text-xs font-medium ${h.bg} ${h.text}`,children:[f.name_fr||f.name,e.jsx("span",{className:"opacity-50 ml-1",children:f.involvement_type==="primary"?"P":f.involvement_type==="secondary"?"S":"St"})]}
57,`${f.name}-${f.involvement_type}`)})})]}),r.equipment?.length>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium text-text-secondary mb-2",children:"Equipement"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:r.equipment.map(f=>e.jsxs("span",{className:`px-2.5 py-1 rounded-lg text-xs font-medium ${f.is_required?"bg-accent/15 text-accent":"bg-surface text-text-secondary"}`,children:[f.name_fr||f.name,f.is_required&&e.jsx("span",{className:"opacity-50 ml-1",children:"*"})]},f.name))})]}),r.target_goals.length>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium text-text-secondary mb-2",children:"Objectifs"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:r.target_goals.map(f=>e.jsx("span",{className:"px-2.5 py-1 rounded-lg text-xs font-medium bg-success/15 text-success capitalize",children:f.replace(/_/g," ")},f))})]}),g.length>0&&e.jsx(Et,{title:"Conseils d'execution",icon:e.jsx(Ji,{className:"w-4 h-4 text-accent"}),defaultOpen:!0,children:e.jsx("div",{className:"space-y-3",children:Object.entries(b).map(([f,h])=>{const v=Hn[f]||Hn.execution;return e.jsxs("div",{children:[e.jsx("span",{className:`inline-block text-[10px] font-semibold uppercase tracking-wider mb-1.5 ${v.color}`,children:v.label}),e.jsx("ul",{className:"space-y-1.5",children:h.map((w,_)=>e.jsxs("li",{className:`flex gap-2 text-sm leading-relaxed rounded-lg px-2.5 py-2 ${v.bg}`,children:[e.jsx(Ie,{className:`w-3.5 h-3.5 mt-0.5 flex-shrink-0 ${v.color}`}),e.jsx("span",{className:"text-text-primary",children:w})]},_))})]},f)})})}),r.common_mistakes?.length>0&&e.jsx(Et,{title:"Erreurs courantes",icon:e.jsx(Te,{className:"w-4 h-4 text-warning"}),children:e.jsx("ul",{className:"space-y-1.5",children:r.common_mistakes.map((f,h)=>e.jsxs("li",{className:"flex gap-2 text-sm leading-relaxed rounded-lg px-2.5 py-2 bg-warning/10",children:[e.jsx(xt,{className:"w-3.5 h-3.5 mt-0.5 flex-shrink-0 text-warning"}),e.jsx("span",{className:"text-text-primary",children:f})]},h))})}),r.contraindications?.length>0&&e.jsx(Et,{title:"Contre-indications",icon:e.jsx(Te,{className:"w-4 h-4 text-error"}),children:e.jsx("ul",{className:"space-y-1.5",children:r.contraindications.map((f,h)=>e.jsxs("li",{className:"flex gap-2 text-sm leading-relaxed rounded-lg px-2.5 py-2 bg-error/10",children:[e.jsx(ht,{className:"w-3.5 h-3.5 mt-0.5 flex-shrink-0 text-error"}),e.jsx("span",{className:"text-text-primary",children:f})]},h))})}),(r.progressions?.length>0||r.regressions?.length>0||r.alternatives?.length>0)&&e.jsx(Et,{title:"Variantes",icon:e.jsx(Hs,{className:"w-4 h-4 text-blue-400"}),children:e.jsxs("div",{className:"space-y-3",children:[r.progressions?.length>0&&e.jsxs("div",{children:[e.jsxs("span",{className:"flex items-center gap-1 text-[10px] font-semibold uppercase tracking-wider text-success mb-1.5",children:[e.jsx(Zi,{className:"w-3 h-3"})," Progressions"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:r.progressions.map((f,h)=>{const v=ms(f);return v?e.jsx("span",{className:"px-2.5 py-1 rounded-lg text-xs font-medium bg-success/10 text-success",children:v},h):null})})]}),r.regressions?.length>0&&e.jsxs("div",{children:[e.jsxs("span",{className:"flex items-center gap-1 text-[10px] font-semibold uppercase tracking-wider text-blue-400 mb-1.5",children:[e.jsx(tl,{className:"w-3 h-3"})," Regressions"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:r.regressions.map((f,h)=>{const v=ms(f);return v?e.jsx("span",{className:"px-2.5 py-1 rounded-lg text-xs font-medium bg-blue-500/10 text-blue-400",children:v},h):null})})]}),r.alternatives?.length>0&&e.jsxs("div",{children:[e.jsxs("span",{className:"flex items-center gap-1 text-[10px] font-semibold uppercase tracking-wider text-text-secondary mb-1.5",children:[e.jsx(ge,{className:"w-3 h-3"})," Alternatives"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:r.alternatives.map((f,h)=>{const v=ms(f);return v?e.jsx("span",{className:"px-2.5 py-1 rounded-lg text-xs font-medium bg-surface text-text-secondary",children:v},h):null})})]})]})})]}),t.notes&&e.jsxs("div",{className:"bg-surface rounded-xl p-3",children:[e.jsx("h4",{className:"text-sm font-medium text-text-secondary mb-1",children:"Notes de la coach"}),e.jsx("p",{className:"text-sm text-text-primary leading-relaxed",children:t.notes})]}),e.jsxs("a",{href:x,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-3 w-full p-3 rounded-xl bg-[#FF0000]/10 border border-[#FF0000]/20 hover:bg-[#FF0000]/15 transition-colors motion-reduce:transition-none",children:[e.jsx(ll,{className:"w-5 h-5 text-[#FF0000] flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium text-text-primary",children:"Voir sur YouTube"}),e.jsx("p",{className:"text-xs text-text-tertiary",children:"Tutoriels et demonstrations"})]}),e.jsx(Qi,{className:"w-4 h-4 text-text-tertiary flex-shrink-0"})]})]})]})}const $a=4;function Fa(t){return Array.isArray(t)?t.map(s=>typeof s=="string"?s.trim():"").filter(s=>s.length>0):[]}
57const Ac={epaules:"Épaules",épaules:"Épaules",shoulders:"Épaules",deltoides:"Épaules",deltoïdes:"Épaules",pectoraux:"Pectoraux",chest:"Pectoraux",dos:"Dos",back:"Dos",dorsaux:"Dorsaux",trapezes:"Trapèzes",trapèzes:"Trapèzes",lombaires:"Lombaires",biceps:"Biceps",triceps:"Triceps","avant-bras":"Avant-bras",quadriceps:"Quadriceps","ischio-jambiers":"Ischio-jambiers",ischiojambiers:"Ischio-jambiers",ischios:"Ischio-jambiers",hamstrings:"Ischio-jambiers",fessiers:"Fessiers",glutes:"Fessiers",mollets:"Mollets",calves:"Mollets",adducteurs:"Adducteurs",abdominaux:"Abdominaux",abs:"Abdominaux",obliques:"Obliques",core:"Gainage",gainage:"Gainage","corps entier":"Corps entier",full_body:"Corps entier","full body":"Corps entier"};function Pa(t){return Ac[t.toLowerCase().trim()]??t.charAt(0).toUpperCase()+t.slice(1)}function Dc(t){return!(typeof t?.completed_sets=="number"&&t.completed_sets<=0)}function Mc(t,s=$a){if(t.status==="completed"){const r=Vn((t.exercises??[]).filter(Dc),s);if(r.length>0)return r}const n=t.trajectoryFocus,a=Fa(n?.muscles);return a.length>0?Lc(a.map(Pa)).slice(0,s):Vn(t.exercises??[],s)}function Vn(t,s){const n=new Map;for(const a of t){const r=new Set;for(const l of Fa(a?.muscle_groups)){const i=Pa(l);r.has(i)||(r.add(i),n.set(i,(n.get(i)??0)+1))}}return n.size===0?[]:[...n.entries()].sort((a,r)=>r[1]-a[1]||a[0].localeCompare(r[0],"fr")).slice(0,s).map(([a])=>a)}function Lc(t){const s=new Set,n=[];for(const a of t){const r=a.toLowerCase();s.has(r)||(s.add(r),n.push(a))}return n}function Oa(t,s=$a){const n=Mc(t,s);return n.length>0?n.join(" · "):null}function Ba({label:t,message:s,choose:n,variant:a="secondary",onStale:r}){const l=Es(),[i,c]=o.useState(!1),[m,u]=o.useState(null),x=async d=>{if(!n||(d.preventDefault(),i))return;c(!0),u(null);const g=await n();if(c(!1),g.ok){l(Ze(s));return}u(g.refusal),g.stale&&r?.()};return e.jsxs("div",{className:"w-full",children:[e.jsx(Wt,{label:t,message:s,icon:"training",variant:a,className:"w-full",onClick:d=>void x(d)}),m?e.jsx("p",{role:"alert",className:"mt-1 text-xs leading-relaxed text-amber-200",children:m}):null]})}const qc=new Set(["chosen","unchanged","focus_unavailable","no_quest","invalid_focus","not_authenticated"]);async function $c(t){try{const s=$.rpc.bind($),{data:n,error:a}=await s("choose_training_quest_option_v1",{p_focus:t});if(a)throw a;const r=n?.outcome;if(r==="chosen"||r==="unchanged")return{ok:!0,outcome:r};const l=typeof r=="string"&&qc.has(r)?r:"rpc_failed";return be("training","quest_choice_refused",{outcome:l,focus:t}),{ok:!1,outcome:l}}catch(s){return be("training","quest_choice_failed",{focus:t,error:s}),{ok:!1,outcome:"rpc_failed"}}}function Fc(t){return t==="focus_unavailable"||t==="no_quest"?"Cette proposition a changé : la carte se met à jour.":"Ton choix n’a pas pu être enregistré. Réessaie."}function Ot({label:t,message:s,focus:n,variant:a="secondary",onStale:r}){return e.jsx(Ba,{label:t,message:s,variant:a,onStale:r,choose:n?async()=>{const l=await $c(n);return l.ok?{ok:!0}:{ok:!1,refusal:Fc(l.outcome),stale:l.outcome==="focus_unavailable"||l.outcome==="no_quest"}}:void 0})}function Pc({tone:t,headingId:s,title:n,status:a,children:r}){const l=t==="aqua";return e.jsxs("section",{"aria-labelledby":s,className:`loading-frame-card relative overflow-hidden rounded-[22px] ${l?"gaming-squad-ground gaming-squad-streaks":"gaming-forge-rank gaming-rank-streaks"}`,children:[e.jsx("span",{"aria-hidden":"true",className:`forge-halo-top ${l?"forge-halo-top--aqua":"forge-halo-top--ambient"}`}),l?e.jsx("span",{"aria-hidden":"true",className:"gaming-hex-grid"}):e.jsx("span",{"aria-hidden":"true",className:"gaming-arena-rays gaming-rank-rays"}),e.jsx("span",{"aria-hidden":"true",className:"forge-metal-grain"}),e.jsx("span",{"aria-hidden":"true",className:`forge-rim-light ${l?"forge-rim-light--aqua":""}`}),e.jsxs("div",{className:"relative space-y-5 p-4 sm:p-5",children:[e.jsxs("header",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-3 pr-9",children:[e.jsx("h2",{id:s,className:`min-w-0 flex-1 font-mono text-[10px] font-bold uppercase tracking-[0.2em] ${l?"text-cyan-300":"text-amber-300"}`,children:"Ta séance"}),a]}),e.jsx("p",{className:"font-display text-lg font-bold text-text-primary",children:n})]}),r]})]})}function Ss(t,s="Exercice"){const n=typeof t.name=="string"?t.name.trim():"",a=typeof t.name_fr=="string"?t.name_fr.trim():"";
57return a&&n&&t.name_fr_of===t.name?a:n||s}const Oc=/^\s*\d+(?:\s*(?:-|–|à)\s*\d+)?\s*$/;function Gn(t){if(t==null)return null;const s=String(t).trim();return s?Oc.test(s)?`${s} rép.`:s:null}function Cs({exercises:t,images:s,tone:n,onOpen:a}){if(t.length===0)return null;const r=n==="aqua"?"text-cyan-200":"text-amber-300";return e.jsxs("div",{className:"relative",children:[e.jsx("span",{"aria-hidden":"true",className:"gaming-raid-thread absolute bottom-7 left-[5px] top-7 w-px"}),e.jsx("ol",{className:"relative divide-y divide-white/[0.06]","aria-label":"Exercices de la séance",children:t.map((l,i)=>e.jsx("li",{children:e.jsxs("button",{type:"button",className:"group flex min-h-16 w-full items-center gap-3 py-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent",onClick:()=>a(i),children:[e.jsxs("span",{className:"relative flex-none",children:[e.jsx(Zs,{card:s[l.name],variant:"thumb",alt:"",height:56,className:"gaming-raid-thumb rounded-[10px]",fallback:e.jsx(Q,{className:"h-5 w-5 text-text-tertiary","aria-hidden":"true"})}),e.jsx("span",{"aria-hidden":"true",className:"gaming-raid-badge absolute -left-1 -top-1 flex h-[18px] w-[18px] items-center justify-center",style:mt,children:e.jsx("span",{className:"font-mono-numbers text-[10px] font-extrabold leading-none text-accent-ink",children:i+1})})]}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block break-words text-sm font-semibold leading-snug",children:Ss(l)}),l.sets?e.jsxs("span",{className:"font-mono-numbers mt-1 block text-xs text-text-secondary",children:[l.sets," séries",Gn(l.reps)?` · ${Gn(l.reps)}`:"",l.weight_kg?` · ${l.weight_kg} kg`:""]}):null]}),e.jsx(la,{className:`h-4 w-4 flex-none ${r}`,"aria-hidden":"true"})]})},`${l.name}-${i}`))})]})}const xs={done:{label:"séance faite",icon:Bs,className:"bg-emerald-300 text-emerald-950"},accepted:{label:"partant",icon:Ws,className:"bg-accent text-accent-ink"},pending:{label:"en attente",icon:qr,className:"bg-cyan-200 text-cyan-950"},personalizing:{label:"adapte sa séance",icon:Xi,className:"bg-cyan-200 text-cyan-950"},declined:{label:"passe son tour",icon:xt,className:"bg-white/15 text-text-secondary"}};function Bc(t){const s=t.trim();return s?s[0].toUpperCase():"·"}function Uc({members:t,onInvite:s,responses:n}){if(t.length===0)return null;const a=[...t].sort((r,l)=>Number(l.is_self)-Number(r.is_self));return e.jsxs("div",{className:"relative flex items-start gap-4 px-0.5 pt-0.5",children:[e.jsx("span",{"aria-hidden":"true",className:"gaming-party-thread absolute left-[26px] right-[26px] top-[26px] h-px"}),e.jsxs("ul",{className:"flex flex-wrap items-start gap-4","aria-label":"Membres de l’escouade",children:[a.map(r=>{const l=n?.[r.member_id],i=l?xs[l].icon:null;return e.jsxs("li",{className:"relative flex flex-col items-center gap-1",children:[e.jsxs("span",{className:`relative h-12 w-12 flex-none ${r.is_self?"gaming-hex-avatar-glow":""}`,children:[e.jsx("span",{"aria-hidden":"true",className:"gaming-hex-avatar-rim absolute inset-0",style:mt}),e.jsx("span",{"aria-hidden":"true",className:"gaming-hex-avatar-face absolute inset-[1.5px] flex items-center justify-center",style:mt,children:e.jsx("span",{className:"font-display text-base font-bold text-stone-300",children:Bc(r.is_self?"Toi":r.display_name)})}),r.role==="leader"&&e.jsx("span",{"aria-hidden":"true",className:"gaming-hex-crown absolute -right-1 -top-1 flex h-[17px] w-[17px] items-center justify-center rounded-full",children:e.jsx(ca,{className:"h-2.5 w-2.5 text-accent-ink"})}),l&&i&&e.jsx("span",{"aria-hidden":"true",className:`absolute -bottom-0.5 -right-1 flex h-[17px] w-[17px] items-center justify-center rounded-full ring-2 ring-background ${xs[l].className}`,children:e.jsx(i,{className:"h-2.5 w-2.5"})})]}),e.jsx("span",{className:"max-w-[64px] truncate text-[11px] font-semibold text-text-secondary",children:r.is_self?"Toi":r.display_name}),r.role==="leader"&&e.jsx("span",{className:"sr-only",children:"Chef d’escouade"}),l&&e.jsx("span",{className:"sr-only",children:xs[l].label})]},r.member_id)}),s&&e.jsxs("li",{className:"relative flex flex-col items-center gap-1",children:[e.jsxs("button",{type:"button",onClick:s,className:"relative h-12 w-12 flex-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-cyan-300","aria-label":"Inviter une personne dans l’escouade",children:[e.jsx("span",{"aria-hidden":"true",className:"gaming-hex-invite-rim absolute inset-0",style:mt}),e.jsx("span",{"aria-hidden":"true",className:"gaming-hex-invite-face absolute inset-[1.5px] flex items-center justify-center",style:mt,children:e.jsx(wa,{className:"h-[19px] w-[19px] text-cyan-300"})})]}),e.jsx("span",{"aria-hidden":"true",className:"text-[11px] font-semibold text-cyan-200",children:"Inviter"})]})]})]})}function zc(t,s){const n=new Date(t).getTime();if(Number.isNaN(n))return null;const a=n-s;if(a<=0)return null;const r=Math.floor(a/36e5),l=Math.floor(r/24);return l>0?`${l} j ${r%24} h`:`${r} h`}function Ic(t,s){if(!t||t.status!=="active"||t.participants.length===0)return;const n={};for(const a of t.participants)n[a.member_id]=a.response==="accepted"&&a.completed&&!s?"done":a.response;return n}function Wc({team:t,raid:s,squad:n,qualitative:a,now:r,activeRaid:l,onInvite:i}){const c=l&&s?zc(s.expires_at,r):null,m=!a&&n&&n.raids_succeeded>0?n.raids_succeeded:0;return e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"truncate font-display text-[15px] font-bold text-cyan-100",children:t.name}),c?e.jsxs("span",{className:"font-mono-numbers flex min-h-6 flex-none items-center gap-1.5 rounded-full border border-cyan-400/25 bg-cyan-400/10 px-2 text-[10px] font-semibold text-cyan-100",children:[e.jsx("span",{className:"hourglass-tilt",children:e.jsx(Ws,{className:"h-3 w-3","aria-hidden":"true"})}),"expire dans ",c]}):null]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{className:"sr-only",children:"Membres"}),e.jsx(Uc,{members:t.members,onInvite:i,responses:Ic(s,a)})]}),m>0?e.jsxs("span",{className:"font-mono-numbers mt-3 inline-flex min-h-6 flex-none items-center gap-1.5 rounded-full border border-cyan-300/20 bg-cyan-300/[0.06] px-2.5 text-[10px] font-semibold text-cyan-200",children:[e.jsx($r,{className:"h-3 w-3","aria-hidden":"true"}),m," ",m>1?"raids réussis":"raid réussi"]}):null]})]})}function Dt({session:t,todayLocal:s,tone:n,onDetails:a}){const r=o.useId(),[l,i]=o.useState(null),{images:c}
57=Gs(t.exercises.map(b=>b.name)),m=qe(t.session_type),u=Hc(t.trajectory_focus),x=Oa({exercises:t.exercises,trajectoryFocus:t.trajectory_focus,status:t.status}),d=qa(t.trajectory_focus),g=t.exercises.length;return e.jsxs("section",{"aria-labelledby":r,className:"rounded-2xl border border-white/[0.07] bg-black/20 p-3","data-testid":"next-session",children:[e.jsxs("p",{id:r,className:"flex items-center gap-1.5 text-[10px] font-black uppercase tracking-[0.2em] text-accent",children:[e.jsx(va,{className:"h-3 w-3","aria-hidden":"true"}),"Prochaine séance"]}),e.jsx("p",{className:"mt-1 text-xs font-semibold text-text-secondary",children:ml(t.session_local_date??null,s)}),e.jsxs("p",{className:"mt-1.5 text-sm font-semibold text-text-primary",children:[u?`${u} `:"",m.label]}),(t.duration_min!=null||g>0)&&e.jsxs("p",{className:"mt-0.5 text-xs text-text-secondary",children:[t.duration_min!=null?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-mono-numbers",children:t.duration_min})," min"]}):null,t.duration_min!=null&&g>0?" · ":"",g>0?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-mono-numbers",children:g})," exercice",g>1?"s":""]}):null]}),x?e.jsx("p",{className:"mt-1 text-xs leading-relaxed text-text-secondary",children:x}):null,d?e.jsx("p",{className:"mt-1 text-xs leading-relaxed text-text-secondary",children:d}):null,g>0?e.jsx("div",{className:"mt-2",children:e.jsx(zs,{summary:"Voir les exercices",label:"Voir les exercices de la prochaine séance",accent:n==="aqua"?"text-cyan-200":"text-amber-300",children:e.jsx(Cs,{exercises:t.exercises,images:c,tone:n,onOpen:i})})}):null,e.jsx(P,{type:"button",variant:"secondary",size:"sm",fullWidth:!0,className:"mt-2",onClick:()=>a(t.id),children:"Voir la séance"}),l!==null&&t.exercises[l]?e.jsx(Qs,{exercise:t.exercises[l],catalogImageUrl:c[t.exercises[l].name],sessionForgeTheme:n==="aqua"?"aqua":"ember",onClose:()=>i(null)}):null]})}function Hc(t){if(!t||typeof t!="object")return null;const s=t.presentation;if(!s||typeof s!="object")return null;const n=s.emoji;return typeof n=="string"&&n.trim()?n.trim().slice(0,8):null}function Vc(t){const s=t.targetDate?at(t.targetDate):null;return[s?`${s.charAt(0).toLocaleUpperCase("fr-FR")}${s.slice(1)}`:null,t.style,t.suggestedDurationMin?`~${t.suggestedDurationMin} min`:null].filter(Boolean).join(" · ")}function Yn(t){const s=Js(t);return s?`Prépare ma prochaine séance : ${s}.`:"Prépare ma prochaine séance."}function Gc(t){const{nextFocus:s,nextFocusAlt:n,qualitative:a,nextSession:r}=t,l=at(Vt(t.session,t.timezone)),i=`Faite ${l}${l.endsWith(".")?"":"."}`,c=s?qa({rationale:s.rationale,presentation:s.presentation}):null,m=!!(n&&n.focus!==s?.focus),u=_e(),x=o.useRef(null);return o.useEffect(()=>{t.arrived&&x.current?.scrollIntoView?.({block:"nearest",behavior:u?"auto":"smooth"})},[t.arrived,u]),e.jsxs(te.div,{ref:x,className:"scroll-mb-[var(--bottom-nav-h)] scroll-mt-[calc(var(--header-h)+5rem)] space-y-3",initial:u?!1:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:ua,ease:da},children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"flex h-11 w-11 flex-none items-center justify-center rounded-2xl border border-emerald-300/25 bg-emerald-300/10 text-emerald-200",children:e.jsx(Ie,{className:"h-5 w-5","aria-hidden":"true"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-[10px] font-black uppercase tracking-[0.2em] text-emerald-300",children:"Quête accomplie"}),e.jsx("p",{role:"status",className:"mt-1 text-sm text-emerald-100",children:i}),t.raidNote?e.jsx("p",{className:"mt-1 text-xs leading-relaxed text-text-secondary",children:t.raidNote}):null,t.recap?e.jsx("p",{"aria-live":"polite",className:"mt-1 text-xs leading-relaxed text-text-secondary",children:t.recap.line}):null,t.recap?.inChat&&t.onOpenChat?e.jsxs("button",{type:"button",onClick:t.onOpenChat,className:"mt-1 inline-flex min-h-11 items-center gap-1.5 rounded-xl text-xs font-bold text-emerald-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-300",children:[e.jsx($s,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Voir mon bilan"]}):null]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-2xl border border-white/[0.06] bg-black/20 p-3",children:[a?e.jsx("p",{className:"text-xs font-semibold text-text-secondary",children:"Ton effort est enregistré."}):e.jsxs("p",{className:"font-mono-numbers text-xs font-semibold text-text-secondary",children:[t.exerciseCount," exercice",t.exerciseCount>1?"s":"",t.durationMin?` · ${t.durationMin} min`:""]}),e.jsx("button",{type:"button",onClick:t.onDetails,className:"min-h-11 flex-none rounded-xl border border-emerald-300/20 bg-emerald-300/10 px-3 text-xs font-bold text-emerald-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-300",children:"Voir le détail"})]}),r&&t.todayLocal?e.jsx(Dt,{session:r,todayLocal:t.todayLocal,tone:"ember",onDetails:t.onOpenSession??(()=>t.onDetails())}
57):s?e.jsxs("div",{className:"rounded-2xl border border-white/[0.07] bg-black/20 p-3","data-testid":"next-quest",children:[e.jsx("p",{className:"text-[10px] font-black uppercase tracking-[0.2em] text-accent",children:"Prochaine quête"}),e.jsxs("p",{className:"mt-1.5 text-sm font-semibold text-text-primary",children:[s.presentation?.emoji?`${s.presentation.emoji} `:"",Js(s)??"Ta prochaine séance"]}),e.jsx("p",{className:"mt-0.5 text-xs text-text-secondary",children:Vc(s)}),s.scheduleReason||s.durationReason?e.jsx("p",{className:"mt-1 text-xs leading-relaxed text-text-primary/80",children:[s.scheduleReason,s.durationReason].filter(Boolean).join(" ")}):c?e.jsx("p",{className:"mt-1 text-xs text-text-secondary",children:c}):null,e.jsxs("div",{className:"mt-3 flex flex-col items-stretch gap-1",children:[e.jsx(Ot,{label:ks("prepare",s),focus:s.focus,message:Yn(s),onStale:t.onQuestStale}),m&&n?e.jsx(Ot,{label:ks("instead",n),focus:n.focus,message:Yn(n),onStale:t.onQuestStale}):null]})]}):e.jsxs("div",{className:"rounded-2xl border border-white/[0.07] bg-black/20 p-3",children:[e.jsx("p",{className:"text-[10px] font-black uppercase tracking-[0.2em] text-accent",children:"La suite"}),e.jsx("p",{className:"mt-1.5 text-sm text-text-secondary",children:t.nextSessionUnreadable?"Ta prochaine séance n’a pas pu être lue.":"Ta prochaine séance n’est pas encore prévue."}),t.nextSessionUnreadable?null:e.jsx("div",{className:"mt-3 flex flex-col items-stretch",children:e.jsx(Kt,{label:"Préparer la suite",message:"Prépare ma prochaine séance, en respectant mon profil, mon matériel et ma semaine."})})]})]})}function Yc({next:t,planned:s,actions:n,arrived:a}){const r=_e(),l=o.useRef(null);return o.useEffect(()=>{a&&l.current?.scrollIntoView?.({block:"nearest",behavior:r?"auto":"smooth"})},[a,r]),e.jsxs(te.div,{ref:l,className:"scroll-mb-[var(--bottom-nav-h)] scroll-mt-[calc(var(--header-h)+5rem)] space-y-3",initial:r?!1:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:ua,ease:da},"data-testid":"session-skipped",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"flex h-11 w-11 flex-none items-center justify-center rounded-2xl border border-white/10 bg-white/5 text-text-secondary",children:e.jsx(el,{className:"h-5 w-5","aria-hidden":"true"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-[10px] font-black uppercase tracking-[0.2em] text-text-secondary",children:"Pas faite aujourd’hui"}),e.jsx("p",{role:"status",className:"mt-1 text-sm text-text-primary",children:"Séance passée : rien à rattraper."}),e.jsx("p",{className:"mt-1 text-xs leading-relaxed text-text-secondary",children:s?"Ta prochaine séance est prévue.":t?`Alloy te la repropose : ${t}. Choisis le jour dans son message.`:"Alloy te propose la suite dans son message."})]})]}),s,n]})}const Kc=new Set(["no_advice","stale_advice","not_overridable","already_used","invalid_dose","not_authenticated"]);async function Jc(t){try{const s=$.rpc.bind($),{data:n,error:a}=await s("choose_rest_dose_v1",{p_dose:t});if(a)throw a;const r=n?.outcome;if(r==="chosen"||r==="unchanged")return{ok:!0,outcome:r};const l=typeof r=="string"&&Kc.has(r)?r:"rpc_failed";return be("training","rest_dose_refused",{outcome:l,dose:t}),{ok:!1,outcome:l}}catch(s){return be("training","rest_dose_failed",{dose:t,error:s}),{ok:!1,outcome:"rpc_failed"}}}function Zc(t){return t==="no_advice"||t==="stale_advice"||t==="already_used"?"Ce conseil a changé : la carte se met à jour.":t==="not_overridable"?"Ta convalescence est en cours : Alloy te conseille d’attendre.":"Ton choix n’a pas pu être enregistré. Réessaie."}function Qc(t){return t==="light"?"Prépare ma séance du jour en version allégée, malgré le repos conseillé.":"Prépare ma séance du jour à pleine charge, malgré le repos conseillé."}function Kn({dose:t,onStale:s}){return e.jsx(Ba,{label:t==="light"?"Séance allégée":"Pleine charge",message:Qc(t),onStale:s,choose:async()=>{const n=await Jc(t);return n.ok?{ok:!0}:{ok:!1,refusal:Zc(n.outcome),stale:n.outcome==="no_advice"||n.outcome==="stale_advice"||n.outcome==="already_used"}}})}function Xc({advice:t,onStale:s}
57){const n=t.dose&&t.doseSource==="card"?`Choix enregistré : ${t.dose==="light"?"séance allégée":"pleine charge"}. Envoie le message à Alloy pour la préparer.`:null;return e.jsxs("div",{className:"space-y-3","data-testid":"session-rest-advice",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"flex h-11 w-11 flex-none items-center justify-center rounded-2xl border border-sky-300/20 bg-sky-300/10 text-sky-200",children:e.jsx(ft,{className:"h-5 w-5","aria-hidden":"true"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-[10px] font-black uppercase tracking-[0.2em] text-sky-200",children:"Repos conseillé"}),e.jsx("p",{role:"status",className:"mt-1 text-sm text-text-primary",children:"Alloy te conseille de récupérer aujourd’hui."}),e.jsx("p",{className:"mt-1 text-xs leading-relaxed text-text-secondary",children:t.overridable?"Il t’explique pourquoi dans son message. Si tu veux y aller quand même, c’est ton choix :":"Ta convalescence est en cours : on reprend quand tu iras mieux."}),n?e.jsx("p",{className:"mt-1 text-xs leading-relaxed text-text-primary/80",children:n}):null]})]}),t.overridable?e.jsxs("div",{className:"flex flex-col items-stretch gap-1",children:[e.jsx(Kn,{dose:"light",onStale:s}),e.jsx(Kn,{dose:"full",onStale:s})]}):null]})}function Ua(t){return Js(t)??(t.focus?qe(t.focus).label:"Ta prochaine séance")}function Ts(t){return ba(t.focus)??t.focus??Ua(t)}function ed(t,s,n){if(!t||!n)return null;const a=Ts(t),r=a?`${a.charAt(0).toLocaleUpperCase("fr-FR")}${a.slice(1)}`:null;if(!r)return null;const l=td(n,1),i=x=>x?x===n?"aujourd’hui":x===l?"demain":at(x):null,c=i(t.targetDate),m=s&&s.focus===t.focus?i(s.targetDate):null,u=[c,m].filter(Boolean).join(" ou ");return u?`${r}, ${u}`:r}function td(t,s){const n=new Date(`${t}T12:00:00Z`);return n.setUTCDate(n.getUTCDate()+s),n.toISOString().slice(0,10)}function sd(t){return t?.status==="active"&&t.own_response==="accepted"?"squad":"solo"}const nd={live:"border-cyan-400/35 bg-cyan-400/[0.14] text-cyan-100",call:"border-accent/60 bg-accent/20 text-accent",done:"border-emerald-300/35 bg-emerald-300/[0.12] text-emerald-100",none:"border-white/10 bg-white/[0.04] text-text-secondary"};function ad({label:t,tone:s,icon:n}){return e.jsxs("span",{className:`inline-flex min-h-6 flex-none items-center gap-1.5 rounded-full border px-2.5 text-[11px] font-semibold ${nd[s]}`,children:[n?e.jsx(n,{className:"h-3 w-3","aria-hidden":"true"}):null,t]})}function rd(t){const s=!!(t.soloLoading||t.loading||t.ownLoading),n=Fr("training-session",`${t.loadingScope??""}:${t.qualitative}`,{solo:t.solo,ownSession:t.ownSession,team:t.team,raid:t.raid,proposal:t.proposal,squad:t.squad,soloCompleted:t.soloCompleted,soloSkipped:t.soloSkipped,completedToday:t.completedToday,nextFocus:t.nextFocus,nextFocusAlt:t.nextFocusAlt,restAdvice:t.restAdvice,suggestedDuration:t.suggestedDuration,dayContext:t.dayContext,nextSession:t.nextSession},s,t.soloError||t.error||t.ownError),a={...t,...n.value,soloLoading:n.loading&&t.soloLoading,loading:n.loading&&t.loading,ownLoading:n.loading&&t.ownLoading,soloError:n.refreshError?null:t.soloError,error:n.refreshError?null:t.error,ownError:n.refreshError?null:t.ownError},{solo:r,ownSession:l,team:i,raid:c,proposal:m,qualitative:u,onRefresh:x}=a,d=a.nextSession??null,g=a.squad??null,b=o.useId(),[f,h]=o.use
57State(null),[v,w]=o.useState(!1),[_,T]=o.useState(Date.now()),N=c?.status==="active";o.useEffect(()=>{if(!N)return;const U=setInterval(()=>T(Date.now()),3e4);return()=>clearInterval(U)},[N]),o.useEffect(()=>{a.requestedMode&&h(a.requestedMode)},[a.requestedMode]);const y=c?.status==="active"&&Date.parse(c.expires_at)>_,k=y&&c.own_response==="accepted",p=f??sd(y?c:null),S=p==="squad"&&!y&&!c?.own_completed,j=p==="solo"?r??(k?l:null)??a.soloCompleted??a.soloSkipped??null:k||c?.own_completed?l:S?r:null,C=j?.status==="completed",A=j?.status==="skipped",D=!j&&a.restAdvice&&a.todayLocal&&a.restAdvice.localDate===a.todayLocal&&!a.restAdvice.consumed?a.restAdvice:null,E=A?ed(a.nextFocus,a.nextFocusAlt,a.todayLocal):null,L=o.useRef(null),[q,R]=o.useState(null);o.useEffect(()=>{const U=L.current;j&&U?.id===j.id&&U.status==="scheduled"&&(j.status==="completed"||j.status==="skipped")&&R(j.id),L.current=j?{id:j.id,status:j.status}:null},[j]);const B=p==="squad"&&!j?[...c?.shared_exercises??[]].sort((U,Pe)=>U.order-Pe.order).map(({order:U,name:Pe})=>({order:U,name:Pe})):[],O=j?.exercises??B,{images:G}=Gs(O.map(U=>U.name)),[z,Y]=o.useState(null),X=j?qe(j.session_type).label:p==="squad"&&c&&y?c.title:p==="squad"?"L’effort se partage":a.completedToday?"Ta séance est terminée":D?"Jour de récupération":"À toi de jouer",ae=j?.duration_min??(p==="squad"&&y?c.duration_minutes:null),I=p==="squad"&&y&&c.launched_by.display_name?c.launched_by.is_self?"toi":c.launched_by.display_name:null,M=j?Oa({exercises:j.exercises,trajectoryFocus:j.trajectory_focus,status:j.status}):null,F=p==="squad"&&c?.own_completed?c.succeeded_at?"Raid réussi par l’escouade.":y?c.accepted_count<2?"Ta séance est comptée. Le raid attend qu’un autre membre soit partant.":"Ta séance est comptée. Le raid attend encore les autres partants.":"Ce raid est terminé. Ta séance a bien été comptée.":null,K=p==="solo"&&k&&!c.own_completed,Ee=j&&j.status==="scheduled"&&!K&&(p==="solo"||y),se=Ra({session:j,todayLocal:a.todayLocal??"",timezone:a.timezone,completionFlagLoading:!!a.completionFlagLoading}),[Se,He]=o.useState(null),[bt,yt]=o.useState(null),jt=async(U,Pe)=>{if(!Se){He(U),yt(null);try{await Pe()}catch(ce){be("training","session_action_failed",{action:U,session_id:j?.id??null,error:ce instanceof Error?ce.message:String(ce)}),yt("L’action n’a pas pu être confirmée. Réessaie.")}finally{He(null)}}},vt=p==="squad"&&k&&!j,$e=m?.id===c?.id?m:null,Jt=y&&$e!==null&&($e.own_response==null||$e.own_response==="pending"),ee=p==="squad"?"aqua":"ember",_t=i?Math.max(i.member_count,i.members.length):0,Nt=i?.role==="leader",wt=i?_t>=Math.min(i.member_limit,ys):!1,rt=`${b}-full`,it=C||p==="squad"&&y&&c.own_completed?{label:"Séance faite",tone:"done",icon:Bs}:A?{label:"Passée",tone:"none"}:p==="squad"&&y?k?{label:"Tu es partant",tone:"live",icon:Ws}:c.own_response==="declined"?{label:"Tu passes ton tour",tone:"none"}:{label:"À toi de répondre",tone:"call",icon:xa}:p==="squad"&&i?{label:"Aucun raid en cours",tone:"none"}:p==="squad"?{label:"Aucune escouade",tone:"none"}:{label:"À ton rythme",tone:"none"},Ne=p==="squad"&&y?c.accepted_count:0,pe=p==="squad"&&y?Math.min(c.completed_count,Ne):0,Ve=u&&Ne>0?pe>=Ne?"Tous les partants ont fait leur séance.":pe>0?"Une partie des partants a déjà fait sa séance.":"Les séances de ce raid sont à venir.":null,Fe=p==="squad"&&i?e.jsx(Nc,{team:i,onInvite:a.onInvite,canWithdraw:!!(k&&!c.own_completed),onWithdraw:()=>w(!0),onTransferLeadership:a.onTransferLeadership,onLeaveTeam:a.onLeaveTeam,onEndTeam:a.onEndTeam,onRefresh:x,fullDescribedBy:rt}):null,H=Fe?Ee?"start":Jt?"response":y?"row":"launch":null;return e.jsx(Pr,{name:"training-session",scope:t.loadingScope,minHeight:280,variant:n.loading?f??a.requestedMode?`${f??a.requestedMode}:unknown`:void 0:`${p}:${j?"ready":"empty"}`,pending:n.loading,resolved:!n.loading&&!n.error&&!n.refreshError,children:n.loading?e.jsx(Or,{announce:!0,scope:t.loadingScope,mode:f??a.requestedMode??void 0}):e.jsxs(e.Fragment,{children:[e.jsx("fieldset",{className:"m-0 min-w-0 border-0 p-0",disabled:n.refreshing||!!n.refreshError,"aria-busy":n.refreshing||void 0,children:e.jsxs(Pc,{tone:ee,headingId:b,title:p==="squad"?"Entraînement en escouade":"Entraînement en solo",status:e.jsx(ad,{label:it.label,tone:it.tone,icon:it.icon}),children:[e.jsx("div",{className:"grid grid-cols-2 gap-1 rounded-xl bg-black/25 p-1",role:"group","aria-label":"Mode d’entraînement",children:["solo","squad"].map(U=>e.jsxs("button",{type:"button","aria-pressed":p===U,onClick:()=>{h(U),Y(null)},className:`flex min-h-11 items-center justify-center gap-2 rounded-lg text-sm font-semibold focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent ${p===U?U==="solo"?"bg-amber-300/15 text-amber-200":"bg-cyan-200/15 text-cyan-100":"text-text-secondary hover:bg-white/5"}`,children:[U==="solo"?e.jsx(ma,{className:"h-4 w-4","aria-hidden":"true"}):e.jsx(Lt,{className:"h-4 w-4","aria-hidden":"true"}),U==="solo"?"Solo":"Escouade",U==="squad"&&y&&c.own_response==="pending"&&e.jsx("span",{className:"h-2 w-2 rounded-full bg-cyan-200","aria-label":"Invitation à répondre"})]},U))}),p==="solo"&&a.soloLoading?e.jsx(as,{theme:"gold",label:"Vérification de ta séance…"}):p==="solo"&&a.soloError?e.jsxs("div",{role:"alert",className:"space-y-3 text-sm",children:[e.jsx("p",{children:"Impossible de vérifier ta séance. Actualise avant d’en demander une autre."}),e.jsx(Le,{onRetry:()=>void x(),className:"w-full"})]}):p==="squad"&&a.loading?e.jsx(as,{theme:p==="squad"?"aqua":"gold",label:"Vérification de ton escouade…"}):p==="squad"&&a.error?e.jsxs("div",{role:"alert",className:"space-y-3 text-sm",children:[e.jsx("p",{children:"Impossible de vérifier ton escouade."}),e.jsx(Le,{onRetry:()=>void x(),className:"w-full"})]}):e.jsxs(e.Fragment,{children:[p==="squad"&&i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Wc,{team:i,raid:c,squad:g,qualitative:u,now:_,activeRaid:!!y,onInvite:Nt&&!wt?a.onInvite:void 0}),Nt&&wt&&e.jsxs("p",{id:rt,className:"text-xs text-text-tertiary",children:["La limite de ",e.jsx("span",{className:"font-mono-numbers",children:ys})," ","membres est atteinte."]}),a.inviteError&&e.jsx("p",{role:"alert",className:"text-sm text-error",children:a.inviteError})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"font-display text-xl font-bold leading-tight text-text-primary sm:text-2xl",children:X}),ae!=null&&e.jsxs("p",{className:"flex flex-wrap items-center gap-x-2 text-xs text-text-secondary",children:[e.jsx(qs,{className:"h-3.5 w-3.5","aria-hidden":"true"}),e.jsx("span",{className:"font-mono-numbers",children:ae})," min",e.jsx("span",{"aria-hidden":"true",children:"·"}),e.jsx("span",{className:"font-mono-numbers",children:O.length})," exercices",I?e.jsxs(e.Fragment,{children:[e.jsx("span",{"aria-hidden":"true",children:"·"}),"lancé par ",I]}):null]}),M&&e.jsx("p",{className:"text-xs leading-relaxed text-text-secondary",children:M}),p==="squad"&&y&&e.jsx("p",{className:"text-xs leading-relaxed text-text-secondary",children:k?"Ta version personnelle, avec tes charges.":"Les mêmes mouvements, adaptés à chacun par Alloy."})]}),vt&&a.ownLoading?e.jsx(as,{theme:p==="squad"?"aqua":"gold",label:"Chargement de ta séance personnelle…"}):vt?e.jsxs("div",{className:"space-y-2 text-sm",role:a.ownError?"alert":"status",children:[e.jsx("p",{children:a.ownError??"Ta participation est enregistrée. La séance liée au raid reste à vérifier."}),e.jsx(P,{type:"button",variant:"secondary",size:"sm",fullWidth:!0,onClick:()=>void x(),children:"Vérifier ma séance"})]}):(C||A)&&O.length>0?e.jsx(zs,{summary:"Revoir les exercices",label:"Revoir les exercices de la séance",accent:"text-emerald-300",children:e.jsx(Cs,{exercises:O,images:G,tone:ee,onOpen:Y})}):e.jsx(Cs,{exercises:O,images:G,tone:ee,onOpen:Y}),p==="squad"&&c&&!y&&!C&&e.jsxs("p",{role:"status",className:"text-sm text-text-secondary",children:[c.succeeded_at?"Raid réussi par l’escouade.":c.status==="expired"||c.status==="active"&&!y?"Ce raid a expiré.":"Ce raid est terminé."," ",c.own_completed?"Ta séance a bien été comptée.":""]}),p==="squad"&&y&&!u&&Ne>1&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[e.jsx("span",{className:"text-xs text-text-secondary",children:"Séances faites"}),e.jsxs("span",{className:"font-mono-numbers text-xs font-bold text-cyan-200",children:[pe,"/",Ne]})]}),e.jsx("div",{className:"mt-1",children:e.jsx(zt,{value:pe,max:Ne,size:"sm",tone:"accent",label:`Séances de raid terminées : ${pe} sur ${Ne} partants`,valueText:`${pe} sur ${Ne}`})})]}),p==="squad"&&y&&Ve&&e.jsx("p",{className:"text-xs text-text-secondary",children:Ve}),Ee&&e.jsxs("div",{className:"space-y-2","aria-busy":Se?!0:void 0,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(P,{type:"button",variant:p==="squad"?"aqua":"primary",className:"min-h-12 flex-1",disabled:!!se.markDone||Se!==null,"aria-describedby":se.markDone?`${b}-done-guard`:void 0,onClick:()=>void jt("markDone",()=>a.onMarkDone(j.id)),children:"✅ C’est fait"}
57),H==="start"?Fe:null]}),se.markDone?e.jsxs("p",{id:`${b}-done-guard`,className:"flex items-start gap-1.5 text-xs font-medium text-amber-200",children:[e.jsx(Us,{className:"mt-0.5 h-3 w-3 flex-none","aria-hidden":"true"}),e.jsx("span",{children:se.markDone})]}):null,e.jsx(P,{type:"button",variant:"ghost",fullWidth:!0,disabled:!!se.skip||Se!==null,"aria-describedby":se.skip?`${b}-skip-guard`:void 0,onClick:()=>void jt("skip",()=>a.onSkip(j.id)),children:Se==="skip"?"Alloy prépare la suite…":"Je ne la fais pas"}),se.skip?e.jsx("p",{id:`${b}-skip-guard`,className:"text-center text-xs text-text-tertiary",children:se.skip}):null,bt?e.jsx("p",{role:"alert",className:"text-sm text-text-secondary",children:bt}):null,e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx("button",{type:"button",className:"min-h-11 w-full rounded-xl text-sm text-text-secondary focus-visible:ring-2 focus-visible:ring-accent",onClick:()=>a.onDetails(j.id),children:"Voir toute la séance"}),e.jsxs("button",{type:"button",className:"inline-flex min-h-11 w-full items-center justify-center gap-1.5 rounded-xl text-sm text-teal-200 focus-visible:ring-2 focus-visible:ring-teal-400",onClick:()=>a.onVideoAnalysis(qe(j.session_type).label),children:[e.jsx(We,{className:"h-4 w-4","aria-hidden":"true"}),"Analyse vidéo"]})]}),p==="solo"&&d&&a.todayLocal?e.jsx(Dt,{session:d,todayLocal:a.todayLocal,tone:ee,onDetails:a.onDetails}):null]}),C&&j&&e.jsx(Gc,{sessionType:j.session_type,exerciseCount:j.exercises.length,durationMin:j.duration_min,session:j,timezone:a.timezone,qualitative:u,onDetails:()=>a.onDetails(j.id),nextFocus:a.nextFocus,nextFocusAlt:a.nextFocusAlt,raidNote:F,nextSession:p==="solo"?d:null,nextSessionUnreadable:a.nextSessionUnreadable,todayLocal:a.todayLocal,onOpenSession:a.onDetails,recap:a.recapBySession?.[j.id]??null,arrived:q===j.id,onOpenChat:a.onOpenChat,onQuestStale:a.onQuestStale}),A&&j&&e.jsx(Yc,{next:E,planned:p==="solo"&&d&&a.todayLocal?e.jsx(Dt,{session:d,todayLocal:a.todayLocal,tone:ee,onDetails:a.onDetails}):null,arrived:q===j.id,actions:e.jsx("p",{className:"text-sm text-text-secondary",children:"Une séance passée ne se rouvre pas."})}),K&&e.jsx("p",{className:"text-sm text-text-secondary",children:"Tu es partant pour le raid. Désiste-toi avant de commencer en Solo ; ta séance restera enregistrée."}),y&&$e&&e.jsx("div",{hidden:p!=="squad"&&!K,children:e.jsx(jc,{context:"training",trainingProposal:$e,onRespondTrainingProposal:a.onRespond,onRefreshTeam:x,allowWithdraw:!c.own_completed,onWithdrawn:()=>h("solo"),withdrawOpen:v,onWithdrawOpenChange:w,showWithdrawButton:p==="solo",primarySlot:H==="response"?Fe:void 0})}),p==="solo"&&!j&&e.jsxs("p",{className:"text-sm leading-relaxed text-text-secondary",children:[a.nextFocus?`${[Ua(a.nextFocus),a.nextFocus.style].filter(Boolean).join(" · ")}.`:"Alloy prépare ta séance selon ton temps, ton matériel et ton profil.",a.suggestedDuration?` Environ ${a.suggestedDuration} min.`:"",a.dayContext?` ${a.dayContext}.`:"",a.nextFocus?.scheduleReason?` ${a.nextFocus.scheduleReason}`:"",a.nextFocus?.durationReason?` ${a.nextFocus.durationReason}`:""]}),p==="solo"&&!j&&d&&a.todayLocal?e.jsx(Dt,{session:d,todayLocal:a.todayLocal,tone:ee,onDetails:a.onDetails}):null,p==="solo"&&!K&&D?e.jsx(Xc,{advice:D,onStale:a.onQuestStale}):null,p==="solo"&&!K&&!C&&!A&&!j&&!D&&a.nextFocus?e.jsx(Ot,{variant:"primary",label:"Préparer ma séance",focus:a.nextFocus.focus,message:`Prépare ma séance du jour avec le focus ${Ts(a.nextFocus)}, en respectant mon profil et mon matériel.`,onStale:a.onQuestStale}):null,p==="solo"&&!K&&!C&&!A&&(j||!a.nextFocus&&!D)&&e.jsx(Kt,{variant:j?"secondary":"primary",label:j?"Modifier avec Alloy":"Préparer ma séance",message:j?`Je veux modifier ma séance ${qe(j.session_type).label} (${j.id}). Aide-moi à adapter sa durée ou ses exercices en respectant mon profil.`:"Prépare ma séance du jour en respectant mon profil et mon matériel."}),p==="solo"&&!j&&!D&&a.nextFocusAlt&&a.nextFocusAlt.focus!==a.nextFocus?.focus&&e.jsx(Ot,{label:ks("instead",a.nextFocusAlt),focus:a.nextFocusAlt.focu
57s,message:`Je choisis la deuxième option pour ma séance : ${Ts(a.nextFocusAlt)}. Respecte mon profil et mon matériel.`,onStale:a.onQuestStale}),p==="squad"&&!i&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-text-secondary",children:"Crée ton escouade ou rejoins tes proches. Vous partagez les mouvements, chacun garde sa séance."}),e.jsx(P,{type:"button",variant:"primary",fullWidth:!0,icon:e.jsx(Lt,{className:"h-4 w-4","aria-hidden":"true"}),onClick:a.onInvite,children:"Créer ou rejoindre"})]}),p==="squad"&&i&&!y&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(P,{type:"button",disabled:!!a.launchDisabledReason||!r||r.status!=="scheduled",variant:"primary",className:"flex-1",onClick:a.onLaunch,children:"Lancer le raid"}),H==="launch"?Fe:null]}),e.jsx("p",{className:"text-xs text-text-secondary",children:a.launchDisabledReason??(r?"Chaque membre confirme et reçoit sa propre version.":"Prépare d’abord une séance Solo avec Alloy.")})]}),H==="row"?e.jsx("div",{className:"flex justify-end",children:Fe}):null]}),z!==null&&O[z]&&e.jsx(Qs,{exercise:O[z],catalogImageUrl:G[O[z].name],sessionForgeTheme:p==="squad"?"aqua":"ember",onClose:()=>Y(null)})]})}),n.refreshError?e.jsxs("div",{role:"alert",className:"mt-2 text-sm text-text-secondary",children:["Actualisation indisponible."," ",e.jsx(Le,{onRetry:()=>void x(),className:"ml-1"})]}):null]})})}function id(t,s){const n=`${t??""}:${s??""}`,a=o.useRef(n);a.current=n;const r=o.useRef(0),[l,i]=o.useState({scope:n,session:null,loading:!!(t&&s),error:null}),c=o.useCallback(async()=>{const m=++r.current;if(!t||!s)return i({scope:n,session:null,loading:!1,error:null}),!0;i(u=>({scope:n,session:u.scope===n?u.session:null,loading:!0,error:null}));try{const{data:u,error:x}=await $.from("training_sessions").select("id,session_type,scheduled_at,session_local_date,performed_local_date,completed_at,created_at,status,exercises,warmup,cooldown,duration_min,calories_burned,user_feedback,difficulty_rating,adherence_pct,trajectory_focus").eq("id",s).eq("user_id",t).maybeSingle();if(x)throw x;if(!u)throw new Error("Ta séance du raid n’est pas disponible. Vérifie à nouveau.");return a.current===n&&r.current===m&&i({scope:n,session:u,loading:!1,error:null}),!0}catch(u){return a.current===n&&r.current===m&&i({scope:n,session:null,loading:!1,error:u instanceof Error?u.message:"Séance indisponible."}),!1}},[n,t,s]);return o.useEffect(()=>{c();const m=r;return()=>{++m.current}},[c]),{...l.scope===n?l:{session:null,loading:!!(t&&s),error:null},refetch:c}}function ld(t){const s=t?.recap_delivery_status??"pending",n=typeof t?.recap_last_error=="string"?t.recap_last_error:null;if(s==="sent"){const a=t?.recap_delivery_channel;return{state:"sent",channel:a==="whatsapp"||a==="telegram"||a==="app"?a:null}}return s==="delegated"?{state:"sent",channel:"conversation"}:s==="generated"&&n?.startsWith("held:")?{state:"held",reason:n.slice(5),terminal:!1}:s==="failed"&&n?.startsWith("delivery_refused:")?{state:"held",reason:n.slice(17),terminal:!0}:{state:"queued",reason:n}}const od="L’état de ton bilan n’a pas pu être lu.";function cd(t){if(t.state==="sent")switch(t.channel){case"app":return{line:"Ton bilan est dans le chat d’Alloy.",inChat:!0,settled:!0};case"whatsapp":return{line:"Ton bilan est parti sur WhatsApp.",inChat:!1,settled:!0};case"telegram":return{line:"Ton bilan est parti sur Telegram.",inChat:!1,settled:!0};case"conversation":return{line:"Ton bilan est dans ta conversation avec Alloy.",inChat:!1,settled:!0};default:return{line:"Ton bilan est parti.",inChat:!1,settled:!0}}return t.state==="held"?t.terminal?{line:t.reason.startsWith("proactive_opted_out")?"Ton bilan est prêt, mais tu as demandé à Alloy de ne plus t’écrire.":"Ton bilan n’a pas pu partir. Demande-le à Alloy dans le chat.",inChat:!1,settled:!0}:{line:t.reason.startsWith("sleep_window")?"Ton bilan est prêt : il partira à ton réveil.":"Ton bilan est prêt : il partira un peu plus tard.",inChat:!1,settled:!0}
57:{line:"Ton bilan se prépare.",inChat:!1,settled:!1}}const dd=4e3,ud=30;function md(t,s,n){const a=n&&t?[...new Set(s)].sort().join(","):"",[r,l]=o.useState({}),i=o.useRef(0),c=o.useRef(0),m=o.useCallback(async()=>{if(!a||!t)return!0;const u=a.split(","),x=++c.current;let d=null,g=null;try{const h=await $.from("training_completion_v2").select("*").eq("user_id",t).in("session_id",u);d=h.data,g=h.error}catch(h){g={message:h instanceof Error?h.message:String(h)}}if(x!==c.current)return!0;if(g){be("training","recap_state_unreadable",{session_ids:u,error:g.message});const h={line:od,inChat:!1,settled:!0};return l(Object.fromEntries(u.map(v=>[v,h]))),!0}const b=d??[],f=Object.fromEntries(u.map(h=>[h,cd(ld(b.find(v=>v.session_id===h)))]));return l(f),Object.values(f).every(h=>h.settled)},[a,t]);return o.useEffect(()=>{if(i.current=0,l({}),!a)return;let u=null,x=!1;const d=async()=>{i.current+=1;const g=await m();x||g||i.current>=ud||(u=setTimeout(()=>void d(),dd))};return d(),()=>{x=!0,c.current+=1,u&&clearTimeout(u)}},[a,m]),a?r:{}}function Jn(t,s,n){return!!(t&&!Number.isNaN(Date.parse(t))&&pt(t,n)===s)}function xd(t,{raid:s,todayLocal:n,timezone:a}){const r=s?.status==="active"&&s.own_response==="accepted"?s.own_training_session_id:null,l=t.filter(u=>u.id!==r),i=l.filter(u=>typeof u.session_local_date=="string"),c=l.filter(u=>typeof u.session_local_date!="string"),m=c.find(u=>!["completed","skipped","cancelled"].includes(u.status)&&(Jn(u.scheduled_at,n,a)||!u.scheduled_at&&Jn(u.created_at,n,a)))??null;return{session:ui(i,n)??m,undatedCount:c.length}}function pd(t,{raid:s,todayLocal:n}){const a=s?.status==="active"&&s.own_response==="accepted"?s.own_training_session_id:null;return t.find(r=>r.id!==a&&r.status==="skipped"&&r.session_local_date===n)??null}function fd(t){const s=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);return s?new Date(Date.UTC(Number(s[1]),Number(s[2])-1,Number(s[3])-1)).toISOString().slice(0,10):null}function hd(t,{raid:s,todayLocal:n}){const a=fd(n);if(!a)return null;const r=s?.status==="active"&&s.own_response==="accepted"?s.own_training_session_id:null;return t.find(l=>l.id!==r&&l.status==="scheduled"&&l.session_local_date===a)??null}function gd({session:t,guards:s,onMarkDone:n,onSkip:a}){const[r,l]=o.useState(null),[i,c]=o.useState(null),m=qe(t.session_type).label,u=async x=>{if(!r){l(x),c(null);try{await(x==="markDone"?n(t.id):a(t.id))}catch(d){be("training","session_action_failed",{action:x,session_id:t.id,surface:"yesterday_session",error:d instanceof Error?d.message:String(d)}),c("L’action n’a pas pu être confirmée. Réessaie.")}finally{l(null)}}};return e.jsxs("section",{"aria-labelledby":"yesterday-session-title","data-testid":"yesterday-session",className:"mb-4 space-y-3 rounded-2xl border border-white/10 bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"flex h-11 w-11 flex-none items-center justify-center rounded-2xl border border-white/10 bg-white/5 text-text-secondary",children:e.jsx(Di,{className:"h-5 w-5","aria-hidden":"true"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-xs font-black uppercase tracking-[0.2em] text-text-secondary",children:"Hier"}),e.jsxs("h3",{id:"yesterday-session-title",className:"mt-1 text-sm font-semibold text-text-primary",children:[m,t.duration_min?` · ${t.duration_min} min`:""]}),e.jsx("p",{className:"mt-1 text-xs leading-relaxed text-text-secondary",children:"Pas encore notée. Dis-moi si tu l’as faite : la suite en dépend."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(P,{type:"button",variant:"primary",fullWidth:!0,className:"min-h-12 whitespace-nowrap",disabled:!!s.markDone||r!==null,"aria-describedby":s.markDone?"yesterday-done-guard":void 0,onClick:()=>void u("markDone"),children:"✅ C’est fait"}),e.jsx(P,{type:"button",variant:"ghost",fullWidth:!0,className:"min-h-11",disabled:!!s.skip||r!==null,"aria-describedby":s.skip?"yesterday-skip-guard":void 0,onClick:()=>void u("skip"),children:r==="skip"?"Alloy prépare la suite…":"Je ne l’ai pas faite"})]}),s.markDone?e.jsxs("p",{id:"yesterday-done-guard",className:"flex items-start gap-1.5 text-xs font-medium text-amber-200",children:[e.jsx(Us,{className:"mt-0.5 h-3 w-3 flex-none","aria-hidden":"true"}),e.jsx("span",{children:s.markDone})]}
57):null,s.skip?e.jsx("p",{id:"yesterday-skip-guard",className:"text-xs text-text-tertiary",children:s.skip}):null,i?e.jsx("p",{role:"alert",className:"text-sm text-text-secondary",children:i}):null]})}function bd({activeTrainingTab:t,switchTrainingTab:s,trainingV2Loading:n,reduceMotion:a}){const[r,l]=o.useState(()=>{const m=window.location.hash.slice(1).split("?")[0].split("&")[0];return m==="analyses"||m==="lieu"?m:null}),[i,c]=o.useState(()=>window.location.hash.slice(1).split("?")[0].split("&")[0]||null);return o.useEffect(()=>{if(!i||n)return;const m=i==="analyses"||i==="lieu"?i:null,u=m?`section-${m}`:i==="training"||i==="session"?"daily-quest-title":null;if(!u){c(null);return}if(m){if(t!=="etat"){s("etat");return}if(r!==m){l(m);return}}const x=setTimeout(()=>{document.getElementById(u)?.scrollIntoView({behavior:a?"auto":"smooth"}),c(null)},a?0:300);return()=>clearTimeout(x)},[i,t,r,n,s,a]),{openTool:r,setOpenTool:l}}function yd(t){return t?Math.max(t.member_count,t.members.length):0}function jd({hasActiveProposal:t,memberCount:s,todayExerciseCount:n}){return t?le.raidAlreadyRunning:s<2?le.inviteFirst:n===0?le.noShareableExercise:void 0}function vd({hasTeam:t,hasActiveProposal:s,memberCount:n,todaySession:a,todayExerciseCount:r}){return t?s?{outcome:"raid_running"}:n<2?{outcome:"refused",message:le.inviteFirst}:a?a.status!=="scheduled"?{outcome:"refused",message:le.sessionNoLongerScheduled}:r?{outcome:"open",sessionId:a.id}:{outcome:"refused",message:le.noShareableExercise}:{outcome:"waiting_for_session",message:le.noSessionYet}:{outcome:"refused",message:le.noTeam}}function _d({activeTeam:t,teamLoading:s,teamError:n,searchParams:a,setSearchParams:r,setRequestedMode:l}){const[i,c]=o.useState(!1),[m,u]=o.useState(null),x=()=>{if(t?.role==="member"){u(le.leaderOnlyInvite);return}u(null),c(!0)};return o.useEffect(()=>{if(a.get("open")!=="invite"||s||n)return;l("squad"),t?.role==="member"?u(le.leaderOnlyInvite):c(!0);const d=new URLSearchParams(a);d.delete("open"),r(d,{replace:!0})},[t?.role,a,r,l,n,s]),o.useEffect(()=>{if(a.get("open")!=="squad")return;l("squad");const d=new URLSearchParams(a);d.delete("open"),r(d,{replace:!0})},[a,r,l]),{showTeamInvite:i,setShowTeamInvite:c,teamActionError:m,openTeamInvite:x}}function Nd({activeTeam:t,trainingProposal:s,teamLoading:n,teamError:a,sessionSourcesLoading:r,todayQuestSession:l,todayQuestView:i,reduceMotion:c,searchParams:m,setSearchParams:u,setRequestedMode:x}){const[d,g]=o.useState(null),[b,f]=o.useState(null),h=yd(t),v=jd({hasActiveProposal:!!s,memberCount:h,todayExerciseCount:i?i.exercises.length:null}),w=o.useCallback(()=>{const N=new URLSearchParams(m);N.delete("team"),N.get("open")==="proposal"&&N.delete("open"),u(N,{replace:!0})},[m,u]),_=m.get("team")==="propose"||m.get("open")==="proposal";o.useEffect(()=>{if(!_||n||r||a)return;const N=()=>document.getElementById("daily-quest-title")?.scrollIntoView({behavior:c?"auto":"smooth"}),y=vd({hasTeam:!!t,hasActiveProposal:!!s,memberCount:h,todaySession:l,todayExerciseCount:i?.exercises.length});switch(y.outcome){case"refused":f(y.message),w();return;case"raid_running":f(null),x("squad"),N(),w();return;case"waiting_for_session":f(y.message),N();return;case"open":f(null),g(y.sessionId),w();return}},[t,w,_,r,x,a,n,h,l,i?.exercises.length,c,s]);const T=o.useMemo(()=>d&&l?.id===d&&i?{id:i.id,sessionType:i.session_type,status:i.status,durationMinutes:i.duration_min,exerciseNames:i.exercises.map(N=>N.name).filter(Boolean)}:null,[d,l?.id,i]);return o.useEffect(()=>{d&&(T&&t||g(null))},[t,T,d]),{teamProposalSessionId:d,setTeamProposalSessionId:g,teamProposalIntentError:b,setTeamProposalIntentError:f,selectedTeamProposalSource:T,teamProposalUnavailableReason:v}}function wd({user:t,trainingV2Enabled:s,activeTrainingTab:n,todayQuestSessionId:a}){const r=o.useRef(new Set),l=o.useRef(new Set),i=o.useRef(new Set),c=o.useRef(t?.id);return o.useEffect(()=>{c.current!==t?.id&&(c.current=t?.id,r.current.clear(),l.current.clear(),i.current.clear())},[t?.id]),o.useEffect(()=>{if(!s||!t?.id)return;const m=r.current;n==="arena"&&!m.has("arena")&&(m.add("arena"),Rt({name:"training_arena_viewed",userId:t.id,featureKey:"training_arena_v2",surface:"training",metadata:{state:n}})),n==="arena"&&!m.has("quest")&&(m.add("quest"),Rt({name:"training_quest_viewed",userId:t.id,featureKey:"training_arena_v2",surface:"training",metadata:{state:"arena"}}))},[n,s,t?.id]),o.useEffect(()=>{const m=a;!s||n!=="arena"||!t?.id||!m||l.current.has(m)||(l.current.add(m),Rt({name:"training_session_generated",userId:t.id,featureKey:"training_arena_v2",surface:"training",entityType:"training_session",entityId:m,metadata:{state:"ready"}}))},[n,a,s,t?.id]),{completedSessionEvents:i}}function kd({user:t,raid:s,trainingV2Enabled:n,trainingLoopV2Enabled:a,trainingLoopV2Loading:r,todayLocal:l,optimisticCompletions:i,setOptimisticCompletions:c,handleStatusChange:m,refreshTraining:u,toast:x,navigate:d,completedSessionEvents:g}){const b=o.useCallback(_=>{d(Ze(`Voici mes vidéos pour ${_||"ma séance"}. Analyse ma forme, s’il te plaît.`))},[d]),f=o.useCallback(async(_,T={})=>{const N=await m(_,"completed",{raid:s?.own_training_session_id===_,todayLocal:l,...T.background?{background:!0}:{}});N&&await Gl(_);const y=await u();return N?(y||x.warning("Séance enregistrée. Certaines informations restent à actualiser."),n&&!a&&s?.own_training_session_id!==_&&t?.id&&!g.current.has(_)&&(g.current.add(_),Rt({name:"training_session_completed",userId:t.id,featureKey:"training_arena_v2",surface:"training",entityType:"training_session",entityId:_,metadata:{source:"manual_completion"}})),!0):!1},[m,n,a,t?.id,s,l,u,x,g]),h=o.useCallback(async _=>{if(i[_])return!0;
57if(r)return x.warning(Yt),!1;c(N=>({...N,[_]:{completedAt:new Date().toISOString(),localDate:l}}));const T=a||s?.own_training_session_id===_;return x.success(T?"Séance faite, bravo ! Ton bilan arrive.":"Séance faite, bravo !"),f(_,{background:!0}).then(N=>{N||(c(y=>Zn(y,_)),ze.warn("[training.completion] séance dite faite, non confirmée — retour arrière",{reason:"completion_not_confirmed",sessionId:_}))},N=>{c(y=>Zn(y,_)),ze.warn("[training.completion] séance dite faite, non confirmée — retour arrière",{reason:"completion_not_confirmed",sessionId:_,error:N instanceof Error?N.message:String(N)}),x.error("La séance n’a pas pu être enregistrée. Réessaie.")}),!0},[i,c,l,a,r,s,x,f]),v=o.useCallback(async _=>await m(_,"skipped")?u():!1,[m,u]);return{confirmCompletion:f,completeSession:h,skipSession:v,openVideoAnalysis:b,changeSessionStatus:async(_,T)=>{T==="completed"?await h(_):T==="skipped"?await v(_):await m(_,T)&&await u()}}}function Zn(t,s){const n={...t};return delete n[s],n}function za(t,s){if(!t)return t;const n=s[t.id];return!n||Ia(t.status)?t:{...t,status:"completed",completed_at:t.completed_at??n.completedAt,performed_local_date:t.performed_local_date??n.localDate}}function Qn(t,s){return t.some(n=>s[n.id]&&!Ia(n.status))?t.map(n=>za(n,s)):t}function Ia(t){return t==="completed"||t==="cancelled"||t==="skipped"}function Sd({sessions:t,standaloneSessions:s,archivedSessions:n},a){const r=new Map,l=(i,c)=>{r.set(i.id,{key:`completed-${i.id}`,date:Vt(i,a)??c??"",session:i})};return t.filter(i=>i.status==="completed").forEach(i=>l(i,i.completed_at||i.scheduled_at||i.created_at)),s.filter(i=>i.status==="completed").forEach(i=>l(i,i.completed_at||i.performed_at||i.scheduled_at||i.created_at)),n.forEach(i=>l(i,i.completed_at||i.performed_at||i.scheduled_at||i.created_at)),[...r.values()].sort((i,c)=>new Date(c.date||0).getTime()-new Date(i.date||0).getTime())}function Cd(t,s){return t.find(n=>n.date&&n.date===s)?.session??null}function Td(t,s,n){const a=t.session_local_date??(t.scheduled_at?pt(t.scheduled_at,n):null);return`Je veux modifier ma séance ${s}${Ed(a,Ls(n))} (${t.id}). Ce que je veux changer : `}function Ed(t,s){if(!t)return"";const n=Date.parse(`${t}T12:00:00Z`),a=Date.parse(`${s}T12:00:00Z`);if(!Number.isFinite(n))return"";const r=Number.isFinite(a)?Math.round((n-a)/864e5):null;return r===0?" d'aujourd'hui":r===1?" de demain":` du ${new Intl.DateTimeFormat("fr-FR",{timeZone:"UTC",weekday:"long",day:"numeric",month:"long"}).format(new Date(n))}`}function Xn(t){const s=t===Z.to_failure||t.startsWith(Z.dropset),n=t===Z.warmup_set;return s?"error":n?"neutral":"accent"}function Rd(t){return t>=9?"error":t>=7?"warning":"success"}function Ad({current:t,previous:s}){if(!t||!s)return null;const n=t-s;return n===0?e.jsx("span",{className:"flex items-center gap-0.5 text-text-tertiary",title:"Maintien",children:e.jsx(It,{className:"w-3 h-3"})}):n>0?e.jsxs("span",{className:"flex items-center gap-0.5 text-success",title:`+${n}kg`,children:[e.jsx(oe,{className:"w-3 h-3"}),e.jsxs("span",{className:"font-mono-numbers text-[10px] font-medium",children:["+",n]})]}):e.jsxs("span",{className:"flex items-center gap-0.5 text-warning",title:`${n}kg`,children:[e.jsx(gt,{className:"w-3 h-3"}),e.jsx("span",{className:"font-mono-numbers text-[10px] font-medium",children:n})]})}function ps({exercise:t,index:s,imageUrl:n,forgeTheme:a="ember",isSessionActive:r=!1,onToggleComplete:l}){const[i,c]=o.useState(!1),[m,u]=o.useState(!1),x=_e(),d=n||t.image_url,g=t.completed_sets!=null&&t.completed_sets>=t.sets;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:`flex gap-3 py-3 border-b border-border last:border-0 cursor-pointer group ${g?"opacity-60":""}`,onClick:()=>u(!0),children:[e.jsxs("div",{className:"relative flex-shrink-0",children:[e.jsx(Zs,{card:d,variant:"thumb",alt:Ss(t),height:80,className:"rounded-xl bg-surface ring-1 ring-white/10 group-hover:ring-accent/40 transition-all motion-reduce:transition-none",fallback:e.jsx(xe,{icon:t.is_endurance?Je:Q,theme:a,size:"md",glow:!1})}),e.jsx("div",{className:"font-mono-numbers absolute -top-1 -left-1 w-5 h-5 rounded-full bg-accent text-white text-xs font-bold flex items-center justify-center shadow-sm",children:s+1}),g&&e.jsx("div",{className:"absolute -bottom-1 -right-1 w-5 h-5 rounded-full bg-emerald-500 text-white flex items-center justify-center shadow-sm",children:e.jsx(Ie,{className:"w-3.5 h-3.5"})})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h4",{className:`font-medium text-sm group-hover:text-accent transition-colors motion-reduce:transition-none ${g?"text-text-tertiary line-through":"text-text-primary"}`,children:Ss(t)}),r&&l&&e.jsx("button",{onClick:b=>{b.stopPropagation(),l(s)},className:`ml-auto flex-shrink-0 w-6 h-6 rounded-full border-2 flex items-center justify-center transition-all motion-reduce:transition-none ${g?"border-emerald-500 bg-emerald-500/20":"border-border hover:border-accent"}`,children:g&&e.jsx(Ie,{className:"w-4 h-4 text-emerald-400"})}),!r&&e.jsx(Ht,{className:"w-3.5 h-3.5 text-text-tertiary opacity-0 group-hover:opacity-100 transition-opacity motion-reduce:transition-none flex-shrink-0"})]}),e.jsx("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 mt-1 text-xs text-text-secondary",children:t.is_endurance?e.jsxs("span",{className:"font-mono-numbers flex items-center gap-1",children:[e.jsx(Je,{className:"w-3 h-3"}),t.reps]}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"font-mono-numbers flex items-center gap-1",children:[e.jsx(Ut,{className:"w-3 h-3"}),r&&t.completed_sets!=null?`${t.completed_sets}/${t.sets} x ${t.reps}`:`${t.sets} x ${t.reps}`]}),t.rest_seconds>0&&e.jsxs("span",{className:"font-mono-numbers flex items-center gap-1",children:[e.jsx(Vs,{className:"w-3 h-3"}),t.rest_seconds,"s repos"]}),t.bodyweight===!0?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Q,{className:"w-3 h-3"}),Z.bodyweight]}):t.weight_kg!=null&&e.jsxs("span",{className:"font-mono-numbers flex items-center gap-1",children:[e.jsx(Q,{className:"w-3 h-3"}),t.weight_kg,"kg",t.per_side===!0?` ${Z.per_side}`:"",e.jsx(Ad,{current:t.weight_kg,previous:t.previous_weight_kg})]})]})}),(t.actual_rpe||t.target_rpe||t.superset_group||(t.qualifiers?.length??0)>0)&&e.jsxs("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:[(t.actual_rpe??t.target_rpe)&&e.jsxs(me,{icon:ia,tone:Rd(t.actual_rpe??t.target_rpe),className:"font-mono-numbers",children:["RPE ",t.actual_rpe??t.target_rpe]}),t.superset_group&&e.jsx(me,{icon:hs,tone:Xn(Nn(t.superset_group)??""),children:Nn(t.superset_group)??""}),t.qualifiers?.filter(b=>!b.startsWith("RPE ")).map(b=>e.jsx(me,{icon:hs,tone:Xn(b),children:b},b))]}),t.muscle_groups&&t.muscle_groups.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-1.5",children:t.muscle_groups.map(b=>e.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-accent/10 text-accent rounded",children:b},b))}),t.notes&&e.jsx("button",{onClick:b=>{b.stopPropagation(),c(!i)},className:"text-xs text-accent mt-2 hover:underline",children:i?"Masquer notes":"Voir notes"}),e.jsx(Oe,{children:i&&t.notes&&e.jsx(te.p,{initial:x?!1:{height:0,opacity:0}
57,animate:{height:"auto",opacity:1},exit:x?void 0:{height:0,opacity:0},transition:x?{duration:0}:void 0,className:"text-xs text-text-tertiary mt-2 italic overflow-hidden",children:t.notes})})]})]}),m&&e.jsx(Qs,{exercise:t,catalogImageUrl:d,sessionForgeTheme:a,onClose:()=>u(!1)})]})}const ea={scheduled:"neutral",completed:"success",skipped:"error"};function Xs({session:t,exerciseImages:s={},onStatusChange:n,variant:a="full",defaultExpanded:r=!1,highlighted:l=!1,className:i="",hideCalories:c=!0,onOpenDetails:m,onProposeToTeam:u,teamProposalUnavailableReason:x,completionUnavailableReason:d=null}){const g=`team-proposal-${o.useId().replace(/:/g,"")}`,b=`completion-guard-${o.useId().replace(/:/g,"")}`,f=!!d,[h,v]=o.useState(r||l),w=o.useRef(null),[_,T]=o.useState(l),N=_e();o.useEffect(()=>{if(l&&w.current){v(!0);const R=setTimeout(()=>{w.current?.scrollIntoView({behavior:N?"auto":"smooth",block:"center"})},N?0:150),B=setTimeout(()=>T(!1),3e3);return()=>{clearTimeout(R),clearTimeout(B)}}},[l,N]);const[y,k]=o.useState(!1),[p,S]=o.useState(!1),j=qe(t.session_type),C=kn[t.status]||kn.scheduled,A=C.icon,D=ea[t.status]||ea.scheduled,E=t.scheduled_at?gn(new Date(t.scheduled_at))&&!js(new Date(t.scheduled_at))&&t.status==="scheduled":!1,L=()=>{if(t.status==="completed")return at(Vt(t));if(!t.scheduled_at)return"Non planifié";const R=new Date(t.scheduled_at);return js(R)?"Aujourd'hui":ol(R)?"Demain":gn(R)&&t.status==="scheduled"?je(R,"EEEE d MMM",{locale:ye})+" — En retard":je(R,"EEEE d MMM",{locale:ye})},q=t.status==="scheduled"&&!!n;return a==="compact"?e.jsx(V,{padding:"sm",hoverable:!0,className:`cursor-pointer ${i}`,onClick:()=>m?m():v(!h),onKeyDown:R=>{(R.key==="Enter"||R.key===" ")&&(R.preventDefault(),m?m():v(!h))},role:"button",tabIndex:0,children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-text-primary text-sm",children:j.label}),e.jsx(me,{tone:D,children:C.label})]}),e.jsx("p",{className:"text-xs text-text-tertiary",children:L()})]}),e.jsxs("div",{className:"text-right flex-shrink-0",children:[e.jsxs("div",{className:"font-mono-numbers text-sm font-medium text-text-primary",children:[t.exercises.length," ex."]}),t.duration_min&&e.jsxs("div",{className:"font-mono-numbers text-xs text-text-tertiary",children:[t.duration_min,"min"]})]})]})}):e.jsx("div",{ref:w,children:e.jsxs(V,{padding:"none",className:`${i} ${_?"ring-2 ring-accent ring-offset-2 ring-offset-background transition-shadow duration-1000 motion-reduce:transition-none":""} ${E?"ring-1 ring-orange-500/30":""}`,children:[E&&e.jsxs("div",{className:"flex items-center gap-1.5 px-4 py-1.5 bg-orange-500/10 border-b border-orange-500/20",children:[e.jsx($t,{className:"w-3.5 h-3.5 text-orange-400 flex-shrink-0"}),e.jsx("span",{className:"text-xs font-semibold text-orange-400",children:"Séance d’un jour passé — dis-moi si tu l’as faite"})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("div",{className:"flex items-start justify-between",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(xe,{icon:j.icon,theme:j.forgeTheme,size:"lg"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-text-primary",children:j.label}),e.jsx(me,{icon:E?$t:A,tone:E?"warning":D,children:E?"En retard":C.label})]}),e.jsxs("div",{className:"flex items-center gap-1 text-sm text-text-tertiary mt-0.5",children:[e.jsx(qs,{className:"w-3.5 h-3.5"}),L()]})]})]})}),e.jsxs("div",{className:"flex items-center gap-4 mt-4 text-sm",children:[e.jsxs("div",{className:"font-mono-numbers flex items-center gap-1.5 text-text-secondary",children:[e.jsx(Q,{className:"w-4 h-4"}),t.exercises.length," exercices"]}),t.duration_min&&e.jsxs("div",{className:"font-mono-numbers flex items-center gap-1.5 text-text-secondary",children:[e.jsx(Vs,{className:"w-4 h-4"}),t.duration_min," min"]}
57),!c&&t.calories_burned?e.jsxs("div",{className:"font-mono-numbers flex items-center gap-1.5 text-text-secondary",children:[e.jsx(hs,{className:"w-4 h-4"}),t.calories_burned," kcal"]}):null,t.status==="completed"&&t.adherence_pct!=null&&e.jsxs("div",{className:"flex items-center gap-1.5 text-text-secondary",children:[e.jsx(ra,{className:"w-4 h-4"}),e.jsxs("span",{className:`font-mono-numbers ${t.adherence_pct>=80?"text-success font-medium":t.adherence_pct>=50?"text-warning font-medium":"text-error font-medium"}`,children:[t.adherence_pct,"%"]})]})]}),e.jsx("div",{className:"flex items-center gap-2 mt-4",children:e.jsxs("button",{onClick:()=>v(!h),className:"flex-1 flex items-center justify-center gap-2 py-2 rounded-lg bg-surface text-sm text-text-secondary hover:bg-surface-elevated transition-colors motion-reduce:transition-none",children:[h?"Masquer les détails":"Voir les exercices",h?e.jsx(et,{className:"w-4 h-4"}):e.jsx(Be,{className:"w-4 h-4"})]})}),q&&n&&e.jsxs("div",{className:"mt-3 grid grid-cols-2 gap-2",children:[e.jsx(P,{variant:"primary",size:"sm",onClick:()=>n(t.id,"completed"),disabled:f,"aria-describedby":f?b:void 0,icon:e.jsx(oa,{className:"h-4 w-4","aria-hidden":"true"}),children:"C’est fait"}),e.jsx(P,{variant:"ghost",size:"sm",onClick:()=>n(t.id,"skipped"),icon:e.jsx(Bt,{className:"h-4 w-4","aria-hidden":"true"}),children:E?"Pas faite":"Je ne la fais pas"})]}),f&&q&&e.jsxs("p",{id:b,className:"mt-2 flex items-start gap-1.5 text-xs font-medium text-amber-200",children:[e.jsx(Us,{className:"mt-0.5 h-3 w-3 flex-none","aria-hidden":"true"}),e.jsx("span",{children:d})]}),e.jsx("div",{className:"mt-2",children:e.jsx(Kt,{message:Td(t,j.label),label:"Modifier avec Alloy",icon:"training"})}),t.status==="scheduled"&&u&&e.jsxs("div",{className:"mt-2",children:[e.jsx(P,{type:"button",variant:"secondary",fullWidth:!0,disabled:!!x,"aria-describedby":x?g:void 0,onClick:()=>u(t.id),icon:e.jsx(Lt,{className:"h-4 w-4","aria-hidden":"true"}),children:"Proposer à mon escouade"}),x&&e.jsx("p",{id:g,className:"mt-1 text-xs leading-relaxed text-text-tertiary",children:x})]})]}),e.jsx(Oe,{children:h&&e.jsx(te.div,{initial:N?!1:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:N?void 0:{height:0,opacity:0},transition:{duration:N?0:.2},className:"overflow-hidden",children:e.jsxs("div",{className:"px-4 pb-4 border-t border-border",children:[t.warmup&&t.warmup.length>0&&e.jsxs("div",{className:"mt-3",children:[e.jsxs("button",{onClick:()=>k(!y),className:"flex items-center gap-2 text-sm text-text-secondary mb-2",children:[y?e.jsx(et,{className:"w-4 h-4"}):e.jsx(Be,{className:"w-4 h-4"}),"Échauffement"," ",e.jsxs("span",{className:"font-mono-numbers",children:["(",t.warmup.length,")"]})]}),e.jsx(Oe,{children:y&&e.jsx(te.div,{initial:N?!1:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:N?void 0:{height:0,opacity:0},transition:N?{duration:0}:void 0,className:"overflow-hidden bg-surface rounded-lg px-3",children:t.warmup.map((R,B)=>e.jsx(ps,{exercise:R,index:B,imageUrl:s[R.name],forgeTheme:j.forgeTheme},`warmup-${R.name}-${B}`))})})]}),e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"text-xs uppercase tracking-wide text-text-tertiary mb-2",children:"Exercices principaux"}),t.exercises.map((R,B)=>e.jsx(ps,{exercise:R,index:B,imageUrl:s[R.name],forgeTheme:j.forgeTheme},`ex-${R.name}-${B}`))]}),t.cooldown&&t.cooldown.length>0&&e.jsxs("div",{className:"mt-3",children:[e.jsxs("button",{onClick:()=>S(!p),className:"flex items-center gap-2 text-sm text-text-secondary mb-2",children:[p?e.jsx(et,{className:"w-4 h-4"}):e.jsx(Be,{className:"w-4 h-4"}),"Retour au calme"," ",e.jsxs("span",{className:"font-mono-numbers",children:["(",t.cooldown.length,")"]})]}),e.jsx(Oe,{children:p&&e.jsx(te.div,{initial:N?!1:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:N?void 0:{height:0,opacity:0},transition:N?{duration:0}:void 0,className:"overflow-hidden bg-surface rounded-lg px-3",children:t.cooldown.map((R,B)=>e.jsx(ps,{exercise:R,index:B,imageUrl:s[R.name],forgeTheme:j.forgeTheme},`cool-${R.name}-${B}`))})})]})]})})})]})})}const ta=6;function Dd({completedHistory:t,qualitativeForge:s,loading:n,error:a,onRetry:r,transformSession:l,exerciseImages:i,onOpenDetails:c,onShowAll:m}){const u=o.useMemo(()=>t.slice(0,ta).map(x=>({entry:x,view:l(x.session)})),[t,l]);return e.jsxs("section",{className:"space-y-3","aria-labelledby":"training-history-title",children:[e.jsx("div",{id:"training-history-title",children:e.jsx(Da,{icon:bn,eyebrow:"Historique",title:"Tes coups portés",action:t.length>0&&!s?e.jsxs("span",{className:"font-mono-numbers text-xs text-text-tertiary",children:[u.length,"/",t.length]}):void 0})}),e.jsx(Ue,{loading:n,error:a,empty:u.length===0,loadingFallback:e.jsx(Br,{}),onRetry:r,errorTitle:"Historique indisponible",errorMessage:"Impossible de charger tes séances terminées.",emptyFallback:e.jsx(st,{density:"inline",state:"contextual_empty",icon:bn,theme:"steel",title:"Tes séances terminées apparaîtront ici",description:"Chaque séance validée s’ajoute à cette liste, avec sa durée et ses exercices."}),children:e.jsx("div",{className:"space-y-2",children:u.map(({entry:x,view:d})=>e.jsx(Xs,{hideCalories:s,session:d,exerciseImages:i,variant:"compact",onOpenDetails:()=>c(x.session.id)},x.key))})}),t.length>ta&&e.jsx("button",{type:"button",onClick:m,className:"min-h-11 w-full rounded-xl border border-white/10 bg-white/5 py-2.5 text-sm font-semibold text-text-secondary hover:bg-white/10 hover:text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent",children:"Voir tout l'historique"})]})}const fs=12;function Md({open:t,onClose:s,completedHistory:n,qualitativeForge:a,transformSession:r,exerciseImages:l,onOpenDetails:i}
57){const[c,m]=o.useState(fs),u=o.useMemo(()=>n.slice(0,c).map(x=>({entry:x,view:r(x.session)})),[n,c,r]);return e.jsx(ke,{open:t,onClose:()=>{s(),m(fs)},eyebrow:"Historique",title:"Toutes tes séances",children:e.jsxs("div",{className:"space-y-2 p-4",children:[u.map(({entry:x,view:d})=>e.jsx(Xs,{hideCalories:a,session:d,exerciseImages:l,variant:"compact",onOpenDetails:()=>i(x.session.id)},`history-sheet-${x.key}`)),e.jsx(Mi,{hasMore:c<n.length,loading:!1,onLoadMore:()=>m(x=>x+fs)})]})})}function Ld({openSessionDetail:t,onClose:s,recap:n,onOpenChat:a,qualitativeForge:r,transformSession:l,exerciseImages:i,onStatusChange:c,onProposeToTeam:m,teamProposalUnavailableReason:u,completionFlagLoading:x=!1}){const d=x?Yt:null,g=o.useMemo(()=>t?l(t):null,[t,l]);return e.jsx(ke,{open:!!t,onClose:s,eyebrow:t?.status==="completed"?"Historique":"Ta séance",title:"Détail de la séance",children:e.jsxs("div",{className:"space-y-4 p-4",children:[t?.status==="completed"&&n&&e.jsxs("div",{className:"space-y-1 text-sm",role:"status",children:[e.jsx("p",{children:"Ta séance est enregistrée."}),e.jsx("p",{className:"text-text-secondary",children:n.line}),n.inChat?e.jsxs("button",{type:"button",onClick:a,className:"inline-flex min-h-11 items-center gap-1.5 rounded-xl text-xs font-bold text-emerald-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-300",children:[e.jsx($s,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Voir mon bilan"]}):null]}),t&&g&&e.jsx(Xs,{hideCalories:r,session:g,exerciseImages:i,onStatusChange:c,onProposeToTeam:t.status==="scheduled"?m:void 0,teamProposalUnavailableReason:u,completionUnavailableReason:d,variant:"full",defaultExpanded:!0})]})})}const qd={dense:"Journée chargée",flexible:"Journée flexible",social:"Journée sociale",travel:"Journée en déplacement",rest:"Journée de récupération",training:"Journée d'entraînement"};function $d(){const{user:t,profile:s}=Fs(),n=_e(),a=s?.timezone,r=Ls(a),l=Es(),[i,c]=pr(),{enabled:m,loading:u}=is("training_arena_v2",t?.id),{enabled:x,loading:d}=is("training_loop_v2",t?.id),{enabled:g,loading:b}=is("forge_cards_v2",t?.id),f=!s||s.avoid_calorie_display===!0||s.eating_disorder_history===!0,h=i.get("tab"),v=h==="twin"||h==="etat"?"etat":"arena",w=m||u?t?.id:void 0,{trajectory:_,loading:T,error:N,refetch:y}=hc(w),{profile:k,trusted:p}=Dl(w),{plan:S,loading:j,error:C,refetch:A}=dl(t?.id),D=S?.is_active===!0?S.id:null,{sessions:E,loading:L,error:q,refetch:R}=oo(t?.id,D),{sessions:B,loading:O,error:G,refetch:z}=hl(w),{session:Y,error:X,refetch:ae}=uo(w,r),{activeTeam:I,trainingProposal:M,raid:F,squad:K,qualitative:Ee,loading:se,error:Se,refetch:He,proposeTeamTraining:bt,respondTrainingProposal:yt,createTeamInvite:jt,transferLeadership:vt,leaveTeam:$e,endTeam:Jt}=Yi(t?.id,!0),ee=id(t?.id,F?.own_training_session_id),_t=ee.refetch,Nt=Ds(),wt=o.useMemo(()=>[...E,...B,...ee.session?[ee.session]:[]],[E,B,ee.session]),{sessions:rt,loading:it,error:Ne,refetch:pe,exerciseImages:Ve,handleStatusChange:Fe,transformSession:H}=Xl(t?.id,D,x,d,wt),[U,Pe]=o.useState({}),ce=o.useMemo(()=>Qn(rt,U),[rt,U]),Re=o.useMemo(()=>Qn(E,U),[E,U]),Ae=o.useMemo(()=>za(ee.session,U),[ee.session,U]),Zt=it||j||L,en=Ne||C||q,Wa=o.useCallback(()=>{pe(),A(),R()},[pe,A,R]),[tn,Ha]=o.useState(0),Qt=o.useCallback(async()=>{const W=await Promise.allSettled([He(),_t(),pe(),A(),R(),z(),ae(),y()]);return Ha(Ce=>Ce+1),W.every(Ce=>Ce.status==="fulfilled"&&Ce.value!==!1)},[He,_t,pe,A,R,z,ae,y]),sn=o.useMemo(()=>xd([...ce,...Re],{raid:F,todayLocal:r,timezone:a}),[ce,Re,F,r,a]),ne=sn.session,lt=sn.undatedCount,nn=o.useRef(0);o.useEffect(()=>{lt!==nn.current&&(nn.current=lt,lt!==0&&ze.warn("[training.today] séance sans jour local — repli sur scheduled_at",{reason:"session_local_date_missing",count:lt}))},[lt]);const an=o.useMemo(()=>ne?H(ne):null,[ne,H]),Va=o.useMemo(()=>Ae?H(Ae):null,[Ae,H]),Ga=o.useMemo(()=>Y?H(Y):null,[Y,H]),[Ya,Xt]=o.useState(!1),[Ge,ot]=o.useState(null),[Ka,es]=o.useState(null),{showTeamInvite:Ja,setShowTeamInvite:Za,teamActionError:Qa,openTeamInvite:Xa}=_d({activeTeam:I,teamLoading:se,teamError:Se,searchParams:i,setSearchParams:c,setRequestedMode:es}),{completedSessionEvents:er}=wd({user:t,trainingV2Enabled:m,activeTrainingTab:v,todayQuestSessionId:ne?.id}),rn=o.useCallback(W=>{const Ce=new URLSearchParams(i);Ce.set("tab",W),c(Ce,{replace:!0})},[i,c]),{openTool:tr,setOpenTool:sr}=bd({activeTrainingTab:v,switchTrainingTab:rn,trainingV2Loading:u,reduceMotion:n}),{teamProposalSessionId:nr,setTeamProposalSessionId:kt,teamProposalIntentError:ln,setTeamProposalIntentError:ar,selectedTeamProposalSource:rr,teamProposalUnavailableReason:on}=Nd({activeTeam:I,trainingProposal:M,teamLoading:se,teamError:Se,sessionSourcesLoading:Zt,todayQuestSession:ne,todayQuestView:an,reduceMotion:n,searchParams:i,setSearchParams:c,setRequestedMode:es}),ts=p?k?.suggested_training_duration_min:null,ir=_?.nextFocus?.suggestedDurationMin??(typeof ts=="number"&&ts>0?ts:null)??(s?.session_duration_min&&s.session_duration_min>0?s.session_duration_min:null),lr=p&&k?.day_mode?qd[k.day_mode]??null:null,Ye=o.useMemo(()=>Sd({sessions:ce,standaloneSessions:Re,archivedSessions:B},a),[B,ce,Re,a]),we=o.useMemo(()=>Cd(Ye,r),[Ye,r]),or=o.useMemo(()=>we?H(we):null,[we,H]),ss=o.useMemo(()=>
57{if(ne||we)return null;const W=pd([...ce,...Re],{raid:F,todayLocal:r});return W?H(W):null},[ne,we,ce,Re,F,r,H]),ns=o.useMemo(()=>{if(ne||we||ss)return null;const W=hd([...ce,...Re],{raid:F,todayLocal:r});return W?H(W):null},[ne,we,ss,ce,Re,F,r,H]),ct=o.useMemo(()=>Ge?Ae?.id===Ge?Ae:ne?.id===Ge?ne:Y?.id===Ge?Y:Ye.find(W=>W.session.id===Ge)?.session??null:null,[Ye,Ge,ne,Ae,Y]),cr=o.useMemo(()=>[we,Ae,ct].filter(W=>W?.status==="completed").map(W=>W.id),[we,Ae,ct]),cn=md(t?.id,cr,x),{completeSession:dn,skipSession:un,openVideoAnalysis:dr,changeSessionStatus:ur}=kd({user:t,raid:F,trainingV2Enabled:m,trainingLoopV2Enabled:x,trainingLoopV2Loading:d,todayLocal:r,optimisticCompletions:U,setOptimisticCompletions:Pe,handleStatusChange:Fe,refreshTraining:Qt,toast:Nt,navigate:l,completedSessionEvents:er});return Ur({title:"Training",subtitle:u?"Préparation de ton arène":m?v==="arena"?"Ta forge du jour":"Ta récupération et ta couverture":"Ta séance du jour"}),e.jsxs("div",{className:"min-h-screen bg-background",children:[(m||u)&&e.jsx("div",{className:"sticky top-[calc(var(--header-h)+var(--chrome-shift,0px))] z-30 border-b border-white/5 bg-background/95 backdrop-blur-sm",children:e.jsx("div",{className:"mx-auto max-w-lg px-4",children:e.jsx(Li,{tabs:[{id:"arena",label:"Arène",icon:xa,guideAnchor:"tab-training-arena"},{id:"etat",label:"Ton état",icon:ma,guideAnchor:"tab-training-etat"}],activeTab:v,onTabChange:rn,layoutId:"trainingTab",ariaLabel:"Training"})})}),e.jsx(te.div,{className:"max-w-lg mx-auto px-4 py-4 space-y-4",variants:zr,initial:n?!1:"hidden",animate:"visible",children:v==="arena"?e.jsx(te.div,{id:"trainingTab-arena-panel",role:"tabpanel","aria-labelledby":"trainingTab-arena-tab",className:"space-y-4",variants:pn,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{id:"daily-quest-title",children:[ln&&e.jsx("p",{role:"status",className:"mb-3 text-sm text-text-secondary",children:ln}),ns&&e.jsx(gd,{session:ns,guards:Ra({session:ns,todayLocal:r,timezone:a,completionFlagLoading:d}),onMarkDone:dn,onSkip:un}),e.jsx(Ke,{helpKey:"training.squad",children:e.jsx(rd,{loadingScope:Ir(t?.id,s),solo:an,ownSession:Va,team:I,raid:F,proposal:M,qualitative:f||Ee,loading:se,error:Se,soloLoading:Zt||O||T,soloError:en||G||N,ownLoading:ee.loading,ownError:ee.error,launchDisabledReason:on,onLaunch:()=>{ne&&kt(ne.id)},squad:K,onInvite:Xa,onTransferLeadership:vt,onLeaveTeam:$e,onEndTeam:Jt,requestedMode:Ka,inviteError:Qa,onMarkDone:dn,onSkip:un,onVideoAnalysis:dr,completionFlagLoading:d,onDetails:ot,onRefresh:async()=>(y(),Qt()),onRespond:async(W,Ce,mr)=>{if(await yt(W,Ce,mr),!await Qt())throw Object.assign(new Error("Ton choix a été envoyé. La relecture reste à vérifier."),{status:"unknown"})},soloCompleted:or,soloSkipped:ss,timezone:a,completedToday:!!we,nextFocus:_?.nextFocus??null,nextFocusAlt:_?.nextFocusAlt??null,suggestedDuration:ir,dayContext:lr,nextSession:Ga,nextSessionUnreadable:!!X,todayLocal:r,recapBySession:cn,onOpenChat:()=>l("/alloy"),onQuestStale:()=>void y(),restAdvice:_?.restAdvice??null},t?.id??"anonymous")})]}),e.jsx(lo,{refreshToken:tn,userId:t?.id,profile:s,onDefineTarget:()=>l("/profile/personal?open=lifestyle"),qualitative:f}),b?e.jsx(Wr,{}):g?e.jsx(qi,{userId:t?.id,domain:"training",title:"Tes stickers training",compact:!0,qualitativeOnly:f},`cards-${tn}`):null,e.jsx(so,{userId:t?.id,timezone:a}),e.jsx(Dd,{completedHistory:Ye,qualitativeForge:f,loading:Zt||O,error:en||G,onRetry:()=>{Wa(),z()},transformSession:H,exerciseImages:Ve,onOpenDetails:ot,onShowAll:()=>Xt(!0)})]})}):e.jsx(te.div,{id:"trainingTab-etat-panel",role:"tabpanel","aria-labelledby":"trainingTab-etat-tab",variants:pn,children:e.jsx(dc,{userId:t?.id,timezone:a,openTool:tr,onOpenToolChange:sr})})},`training-${v}`),I&&e.jsx(io,{open:!!nr,onClose:()=>kt(null),team:I,source:rr,activeProposal:!!M,onConfirm:bt,onRefresh:He,onViewRaid:()=>{kt(null),es("squad")}}),e.jsx(Ki,{prepareOnOpen:!0,isOpen:Ja&&(!I||I.role==="leader"),onClose:()=>Za(!1),createTeamInvite:jt,teamName:I?.name,memberCount:I?.member_count}),e.jsx(Md,{open:Ya,onClose:()=>Xt(!1),completedHistory:Ye,qualitativeForge:f,transformSession:H,exerciseImages:Ve,onOpenDetails:W=>{Xt(!1),ot(W)}}),e.jsx(Ld,{openSessionDetail:ct,onClose:()=>ot(null),completionFlagLoading:d,recap:ct?cn[ct.id]??null:null,onOpenChat:()=>l("/alloy"),qualitativeForge:f,transformSession:H,exerciseImages:Ve,onStatusChange:ur,onProposeToTeam:I?W=>{ot(null),ar(null),kt(W)}:void 0,teamProposalUnavailableReason:on})]})}const Tu=Object.freeze(Object.defineProperty({__proto__:null,TrainingPage:$d},Symbol.toStringTag,{value:"Module"}));
57export{Cu as A,Kt as T,Tu as a};

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.