1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["_assets/pdf-dNxa0vXk.js","_assets/vendor-B5KZbkSs.js","_assets/index-rQLcFmgX.js","_assets/_commonjs-dynamic-modules-TDtrdbi3.js"])))=>i.map(i=>d[i]); 2import{o as Ee,w as rt,s as X,S as K,k as Me,l as Ye,p as $e,f as gt,A as Ve,g as ms,an as po,m as $n,ap as q,r as u,j as e,R as je,fp as ba,fq as mo,bN as ho,fr as go,X as qt,fs as _o,aa as Mn,dv as fo,ad as ts,i as xo,bP as yo,$ as Ps,aD as jo,aB as Do,bR as pn,cq as wa,ft as Sa,ev as vo,Z as ss,c5 as Na,c6 as Ta,aZ as hs,bu as An,Y as Co,b1 as ko,b5 as Ia,bh as nn,dc as Ea,bz as Pa,fu as $a,dl as Bn,cY as Hn,a8 as ps,aV as Ma,bm as Aa,ac as Ln,cB as Ba,q as ia,c1 as bo,bI as wo,fv as Fs,fw as Us,a3 as Ha,cT as So,_ as No,O as oa,x as On,fx as To,a_ as ra,bj as an,fy as mn,ab as Io,cC as La,e5 as Eo,fz as Po,fA as Oa,fB as $o,bT as Mo,f0 as Ao,eg as Bo,eh as Ho,dh as la,e2 as Lo,a4 as Oo,fC as Ra,bD as wn,ex as Ro,er as ca,dk as Fo,fD as Uo,fE as qo,bL as zo,cn as Wo,u as Go,ay as da}from"./vendor-B5KZbkSs.js";import{bb as Vo,u as ye,B as L,P as on,j as rn,k as ln,z as Ws,S as ne,b as Vt,C as gs,A as Yo,a1 as Qo,a as wt,Q as bs,V as ws,W as Ss,I as Pe,aa as _s,d as nt,e as at,f as it,h as ot,i as J,c as Ts,J as Ls,l as Fa,aR as Ko,T as cn,af as Jo,D as Xo,v as Ua,w as qa,x as za,y as Wa,H as Zo,G as er,an as tr,X as ua,bc as sr,b1 as nr}from"./index-DS57U4Yv.js";import{u as ar}from"./useUserLocation-Dts38EZh.js";import{u as Gs,S as ir}from"./useSpecialtyColors-Bz7sU1UY.js";import{u as Yt,a as or,B as rr}from"./useBusinessHours-RKRRflEN.js";import{p as lr,T as Ga}from"./index-DFBgI_f0.js";import{Q as fs,u as cr,i as pa,b as Va}from"./useQuotes-DtxUvnfS.js";import{C as ds,b as dr,p as ma,c as ur,a as Ya}from"./useCalendarEvents-Dt78U2ht.js";import{g as Qa,i as us}from"./businessHoursCalculator-DUO5-fuc.js";import{U as pr}from"./useProjects-DTmemrwO.js";import{b as mr,c as hr}from"./useCloudinaryUpload-ZlXd7UVy.js";import{p as gr,a as Ka,u as _r,b as fr}from"./useTaskPhotos-CZUCXkzQ.js";import{a as hn,u as $s,D as Ja,H as xr}from"./index-Dvey2BgZ.js";import{t as yr,h as ge,s as Tn,f as De,e as Vs}from"./format-C_M5ysWh.js";import{e as es}from"./endOfDay-ZAAguv9p.js";import{e as In,s as jr,b as Xa,d as ha,f as Ns,C as En,a as Za,i as Dr}from"./Calendar-DZgfhkMq.js";import{e as vr}from"./endOfMonth-DOFPxRvG.js";import{D as Qe,a as Ke,b as lt,c as Je,d as $t,e as Ct,f as Cr}from"./Dialog-CfnQaIW4.js";import{a as kr,b as br}from"./useQuoteExtras-B1EH3IS4.js";import{f as zt}from"./fr-Ck3aJIFh.js";import{s as wr,E as Sr,C as Nr}from"./CalendarHeader-BHK3tDTt.js";import{h as ce}from"./moment-BLMuvzoS.js";import{A as Tr,a as Ir,b as Er}from"./Avatar-Bg_OztuK.js";import{i as Pn}from"./imageThumbnailUrl-Caq-69-_.js";import{u as Ys,F as Qs,a as oe,b as pe,c as re,d as _e}from"./Form-2-ZGlGts.js";import{C as St}from"./Checkbox-h7cLIofq.js";import{u as Ks}from"./useTeamMembers-sPIB-WK9.js";import{u as Pr}from"./useClients-BLMEtRrN.js";import{s as dn,a as un}from"./setMinutes-C4Z53o4d.js";import{a as $r,P as Mr}from"./PhotoCapture-CpHz6mBz.js";import{V as Ar,E as Br,W as Hr}from"./EventManager-BGM1lsyf.js";import{A as ei,a as ti,b as si,c as ni}from"./Accordion-e4_UCFjk.js";import{T as Lr,a as Or,b as is,c as os}from"./Tabs-CXq4B6O8.js";import{u as ai,s as ii,C as Pt}from"./zod-CQbJRvuO.js";import{S as Rn}from"./Separator-CyqI3WAh.js";import{L as Ut}from"./Label-DXPbztsI.js";import{R as Fn,a as Is}from"./RadioGroup-ClJ_Ydrh.js";import{u as Rr,P as Fr,C as Ur,a as qr}from"./useUpdateClientNotes-BcVMuYb6.js";import{p as zr}from"./create_POST.schema-DQoK3GYU.js";import{u as Wr}from"./useCompanyLogo-80u3wne4.js";import{D as Gr}from"./DocumentViewer-CiiKEjRX.js";import{e as Vr}from"./en-CA-tcymBlnb.js";import{u as Yr}from"./useCcqApplicable-BPRTDVQH.js";import{u as Qr}from"./useCcqCompliance-BTi1fazR.js";import{D as oi,a as ri,b as li,c as mt,d as Xt,f as Kr,g as Jr,h as Xr}from"./DropdownMenu-H7Fl589o.js";import{e as ga}from"./eachDayOfInterval-KoKmFq3D.js";import{f as Zr}from"./formatDurationMinutes-x_yJqpjZ.js";import{u as el}from"./useCanViewRoutePrices-Dci_JxDf.js";import{W as tl}
2from"./WeatherWidget-DuBHVEcc.js";import{S as sl}from"./SpecialtyColorManager-C71RxkwY.js";import{u as nl}from"./useGuidedTourStatus-BeDB_vbA.js";import{M as al}from"./MobilePullToRefresh-CUbMANB_.js";import{u as il}from"./useColorThemes-R_6ZV0VN.js";import"./list_GET.schema-DwoddtI-.js";import"./upload_POST.schema-crfCjAaa.js";import"./subMonths-CtxeLMFI.js";import"./index-DjPIeaRR.js";import"./index-Dco-aJNU.js";import"./index-CFwldOsu.js";import"./index-DI8S_1Qo.js";import"./Progress-Br4BZzO2.js";import"./useSessionPackages-6jjm495f.js";import"./useLoyaltyProgram-BHAmGBsY.js";import"./useInvoicePayments-D4Vx00de.js";import"./useInvoices-Cw5ycxat.js";import"./usePaymentReminders-CDaj1O1F.js";import"./useFinancingRate-B9SBE-Z0.js";import"./quebecTaxCalculator-DHjTTjLj.js";import"./generate-pdf_POST.schema-B6U48_TP.js";import"./ColorPicker-B9I67jSf.js";function _a(t,a){return yr(t,a?.in).getHours()}let Zs;function ol(){return Zs||(Zs=new Image,Zs.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="),Zs}let rl="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",fa=(t=21)=>{let a="",s=t|0;for(;s--;)a+=rl[Math.random()*64|0];return a};Ee({startDate:X().datetime("Start date must be a valid date"),endDate:X().datetime("End date must be a valid date"),specialty:X().optional(),assignedUserId:rt.number().int().positive().optional(),unassignedOnly:rt.boolean().optional()});const ll=async(t,a)=>{const s=new URLSearchParams;s.set("startDate",t.startDate),s.set("endDate",t.endDate),t.specialty&&s.set("specialty",t.specialty),t.assignedUserId&&s.set("assignedUserId",String(t.assignedUserId)),t.unassignedOnly&&s.set("unassignedOnly","true");const n=await fetch(`/_api/client-assignments/list?${s.toString()}`,{method:"GET",...a,headers:{"Content-Type":"application/json"}});if(!n.ok){const o=K.parse(await n.text());throw new Error(typeof o=="object"&&o!==null&&"error"in o?String(o.error):"An unknown error occurred")}return K.parse(await n.text())},cl=Ee({clientId:Me().int().positive().optional().nullable(),quoteId:Me().int().positive().optional().nullable(),startDate:rt.date(),endDate:rt.date().optional().nullable(),notes:X().optional().nullable(),specialty:X().optional(),isPinned:$e().optional(),isHalfDay:$e().optional(),halfDayPeriod:Ye(["morning","afternoon"]).optional().nullable(),allDay:$e().optional(),taskTitle:X().optional().nullable(),taskDescription:X().optional().nullable(),taskLocation:X().optional().nullable(),taskPriority:Ye(["low","medium","high"]).optional().nullable(),taskStatus:Ye(["pending","in_progress","completed"]).optional().nullable(),assignedUserId:Me().int().positive().optional().nullable()}).refine(t=>t.clientId||t.taskTitle,{message:"Either clientId or taskTitle must be provided.",path:["clientId"]}).refine(t=>!t.endDate||t.endDate>=t.startDate,{message:"End date must be on or after the start date.",path:["endDate"]}).refine(t=>!t.isHalfDay||t.halfDayPeriod,{message:"Half day period must be provided when isHalfDay is true.",path:["halfDayPeriod"]}),dl=async(t,a)=>{const s=cl.parse(t),n=await fetch("/_api/client-assignments/create",{method:"POST",body:K.stringify(s),...a,headers:{"Content-Type":"application/json"}});if(!n.ok){const o=K.parse(await n.text());throw new Error(typeof o=="object"&&o!==null&&"error"in o?String(o.error):"An unknown error occurred")}return K.parse(await n.text())},ul=Ee({id:Me().int().positive(),applyToSeries:$e().optional(),startDate:rt.date().optional(),endDate:rt.date().optional().nullable(),notes:X().optional().nullable(),specialty:X().optional().nullable(),isPinned:$e().optional(),isHalfDay:$e().optional(),halfDayPeriod:Ye(["morning","afternoon"]).optional().nullable(),allDay:$e().optional(),taskTitle:X().optional().nullable(),taskDescription:X().optional().nullable(),taskLocation:X().optional().nullable(),taskPriority:Ye(["low","medium","high"]).optional().nullable(),taskStatus:Ye(["pending","in_progress","completed"]).optional().nullable(),assignedUserId:Me().int().positive().optional().nullable()}),pl=async(t,a)=>{const s=ul.parse(t),n=await fetch("/_api/client-assignments/update",{method:"POST",body:K.stringify(s),...a,headers:{"Content-Type":"application/json"}});if(!n.ok){const o=K.parse(await n.text());throw new Error(typeof o=="object"&&o!==null&&"error"in o?String(o.error):"An unknown error occurred")}return K.parse(await n.text())}
2,ml=Ee({id:Me().int().positive()}),hl=async(t,a)=>{const s=ml.parse(t),n=await fetch("/_api/client-assignments/delete",{method:"POST",body:K.stringify(s),...a,headers:{"Content-Type":"application/json"}});if(!n.ok){const o=K.parse(await n.text());throw new Error(typeof o=="object"&&o!==null&&"error"in o?String(o.error):"An unknown error occurred")}return K.parse(await n.text())},Wt="clientAssignments",Es=t=>ms({queryKey:[Wt,t.startDate,t.endDate,t.specialty,t.assignedUserId,t.unassignedOnly],queryFn:()=>ll(t),enabled:!!t.startDate&&!!t.endDate,refetchOnWindowFocus:!0,refetchOnMount:!1,refetchOnReconnect:!0,staleTime:3e5,placeholderData:a=>a}),ci=()=>{const t=gt();return Ve({mutationFn:a=>dl(a),onSuccess:()=>{t.invalidateQueries({queryKey:[Wt]}),t.invalidateQueries({queryKey:[fs,"list"]})}})},Ms=()=>{const t=gt();return Ve({mutationFn:a=>pl(a),onSuccess:()=>{t.invalidateQueries({queryKey:[Wt]}),t.invalidateQueries({queryKey:[fs,"list"]})}})},gl=()=>{const t=gt();return Ve({mutationFn:a=>hl(a),onSuccess:()=>{t.invalidateQueries({queryKey:[Wt]}),t.invalidateQueries({queryKey:[fs,"list"]})}})},_l=Ee({eventId:Me().int().positive(),oldStartDate:rt.date(),newStartDate:rt.date(),sendNotifications:$e(),companyId:Me().int().positive()}),fl=Ee({updates:$n(Ee({eventId:Me().int().positive(),oldStartDate:rt.date(),newStartDate:rt.date()})),companyId:Me().int().positive(),sendNotifications:$e().default(!0)}),xl=po([_l,fl]),yl=async(t,a)=>{const s=xl.parse(t),n=await fetch("/_api/calendar/events/cascade-update",{method:"POST",body:K.stringify(s),...a,headers:{"Content-Type":"application/json"}});if(!n.ok){const o=K.parse(await n.text());throw typeof o=="object"&&o!==null&&"error"in o?new Error(String(o.error)):new Error(`An unknown error occurred: ${n.statusText}`)}return K.parse(await n.text())},jl=()=>(gt(),Ve({mutationFn:t=>yl(t),onSuccess:t=>{q.success(t.message||"Schedule updated successfully."),t.notificationsSent>0&&q.info(`${t.notificationsSent} notification(s) sent to: ${t.notifiedClients.map(a=>a.name).join(", ")}.`)},onError:t=>{const a=t instanceof Error?t.message:"Une erreur inconnue s'est produite.";q.error(`Ãchec de mise à jour du calendrier : ${a}`),console.error("Cascade update failed:",t)}})),Dl=Ee({assignmentId:Me().int().positive(),oldStartDate:rt.date(),oldEndDate:rt.date(),newStartDate:rt.date(),newEndDate:rt.date(),sendNotifications:$e().default(!1),specialty:X().nullable().optional(),isHourlyMode:$e().optional()}).refine(t=>t.newEndDate>=t.newStartDate,{message:"New end date cannot be before new start date.",path:["newEndDate"]}),vl=async(t,a)=>{const s=Dl.parse(t),n=await fetch("/_api/client-assignments/cascade-update",{method:"POST",body:K.stringify(s),...a,headers:{"Content-Type":"application/json"}});if(!n.ok){const o=K.parse(await n.text());throw new Error(typeof o=="object"&&o!==null&&"error"in o?String(o.error):"An unknown error occurred")}return K.parse(await n.text())},Cl=()=>Ve({mutationFn:t=>(console.log("[DEBUG] Client assignment cascade update triggered:",{assignmentId:t.assignmentId,oldStartDate:t.oldStartDate,newStartDate:t.newStartDate,oldEndDate:t.oldEndDate,newEndDate:t.newEndDate,sendNotifications:t.sendNotifications,isHourlyMode:t.isHourlyMode}),vl(t)),onSuccess:t=>{console.log("[DEBUG] Client assignment cascade update succeeded:",{affectedCount:t.affectedAssignments.length,affectedAssignments:t.affectedAssignments}),t.affectedAssignments.forEach(a=>{console.log(`[DEBUG] Assignment ${a.id} (Client ${a.clientId}):`,{oldStartDate:a.oldStartDate,newStartDate:a.newStartDate,oldEndDate:a.oldEndDate,newEndDate:a.newEndDate})})},onError:t=>{const a=t instanceof Error?t.message:"Une erreur inconnue s'est produite.";console.error("[ERROR] Client assignment cascade update failed:",{error:t,message:a})}}),kl=Ee({id:Me().int().positive(),startDate:rt.date().optional(),endDate:rt.date().optional().nullable(),notes:X().optional().nullable(),specialty:X().optional().nullable(),isPinned:$e().optional(),isHalfDay:$e().optional(),halfDayPeriod:Ye(["morning","afternoon"]).optional().nullable(),allDay:$e().optional(),taskTitle:X().optional().nullable(),taskDescription:X().optional().nullable(),taskLocation:X().optional().nullable(),taskPriority:Ye(["low","medium","high"]).optional().nullable(),taskStatus:Ye(["pending","in_progress","completed"]).optional().nullable()}),bl=Ee({updates:$n(kl),skipConflictCheck:$e().optional()}),wl=async(t,a)=>{const s=bl.parse(t),n=await fetch("/_api/client-assignments/batch-update",{method:"POST",body:K.stringify(s),...a,headers:{"Content-Type":"application/json",...a?.headers??{}}});if(!n.ok){let o="An unknown error occurred";try{const i=K.parse(await n.text());typeof i=="object"&&i!==null&&"error"in i&&(o=String(i.error))}catch{}throw new Error(o)}return K.parse(await n.text())};function gn(t){const a=t.getDay();return a===0||a===6}function _n(t){const a=t.getFullYear(),s=Qa(a),n=`${t.getFullYear()}
2-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`;return s.some(o=>`${o.date.getFullYear()}-${String(o.date.getMonth()+1).padStart(2,"0")}-${String(o.date.getDate()).padStart(2,"0")}`===n)}function fn(t,a){if(!a||a.length===0)return!1;const s=new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime();return a.some(n=>{const o=new Date(n.startDate.getFullYear(),n.startDate.getMonth(),n.startDate.getDate()).getTime(),i=new Date(n.endDate.getFullYear(),n.endDate.getMonth(),n.endDate.getDate()).getTime();return s>=o&&s<=i})}function en(t,a,s,n){const o=new Date(t);let i=365,p=0;for(;p<i;){let c=!1;if((a&&gn(o)||s&&_n(o)||fn(o,n))&&(c=!0),!c)return o;o.setDate(o.getDate()+1),p++}return console.error("getNextWorkingDay: Max iterations reached"),o}function qs(t,a,s,n,o){if(a<t)return 0;let i=0;const p=new Date(t);for(;p<=a;){let c=!0;(s&&gn(p)||n&&_n(p)||fn(p,o))&&(c=!1),c&&i++,p.setDate(p.getDate()+1)}return i}function xn(t,a,s,n,o){if(a===0)return new Date(t);const i=new Date(t);let p=0,c=Math.max(a*7,30),m=0;for(;p<a&&m<c;){i.setDate(i.getDate()+1);let h=!0;(s&&gn(i)||n&&_n(i)||fn(i,o))&&(h=!1),h&&p++,m++}return p<a&&console.error("addWorkingDays: Max iterations reached without finding enough working days"),i}function Sl(t,a,s,n,o){if(a<=0)return new Date(t);const i=new Date(t);let p=0,c=Math.max(a*7,30),m=0;for(;p<a&&m<c;){i.setDate(i.getDate()-1);let h=!0;(s&&gn(i)||n&&_n(i)||fn(i,o))&&(h=!1),h&&p++,m++}return p<a&&console.error("subtractWorkingDays: Max iterations reached without finding enough working days"),i}function di(t,a,s,n,o,i,p){const c=i.find(b=>b.id===t),m=c?c.isHalfDay:!1,h=c?c.halfDayPeriod:null,r=i.filter(b=>{if(b.id===t||b.isPinned)return!1;const y=new Date(b.startDate);return!((b.endDate?new Date(b.endDate):y)<n)}).sort((b,y)=>new Date(b.startDate).getTime()-new Date(y.startDate).getTime());if(r.length===0)return[];const C=[];let g=new Date(o||n);g.setUTCDate(g.getUTCDate()+1);let l=new Date(g);l.setUTCHours(0,0,0,0);let k=m,j=h,x=o?new Date(o):new Date(n);const d=(b,y,S)=>{if(!k||!b||!j||!y||j===y)return!1;const D=x??new Date(o??n);return S.getUTCFullYear()===D.getUTCFullYear()&&S.getUTCMonth()===D.getUTCMonth()&&S.getUTCDate()===D.getUTCDate()};for(const b of r){const y=new Date(b.startDate);if(d(b.isHalfDay,b.halfDayPeriod,y)){k=b.isHalfDay,j=b.halfDayPeriod,x=b.endDate?new Date(b.endDate):y,g=new Date(b.endDate??b.startDate),g.setUTCDate(g.getUTCDate()+1),l=new Date(g),l.setUTCHours(0,0,0,0);continue}if(y<l){const S=new Date(b.startDate),D=new Date(l);D.setUTCHours(S.getUTCHours(),S.getUTCMinutes(),0,0);let _=null;if(b.endDate){const f=new Date(b.endDate),v=Math.round((f.getTime()-S.getTime())/(1e3*3600*24));_=new Date(D),_.setUTCDate(_.getUTCDate()+v),_.setUTCHours(f.getUTCHours(),f.getUTCMinutes(),0,0)}C.push({assignment:b,newStartDate:D,newEndDate:_}),k=b.isHalfDay,j=b.halfDayPeriod,x=_??D,g=new Date(_||D),g.setUTCDate(g.getUTCDate()+1),l=new Date(g),l.setUTCHours(0,0,0,0)}else break}return C}function xa(t,a,s,n,o,i,p,c,m="subsequent"){if(n.getTime()>=a.getTime())return[];const h=p.avoidWeekends,r=p.avoidHolidays,C=i.filter(j=>{if(j.id===t||j.isPinned)return!1;const x=new Date(j.startDate);return!(m==="subsequent"&&x<a)}).sort((j,x)=>new Date(j.startDate).getTime()-new Date(x.startDate).getTime());if(C.length===0)return[];let g=0,l=0;h||r?g=qs(n,a,h,r,c)-1:l=Math.round((a.getTime()-n.getTime())/(1e3*3600*24));const k=[];for(const j of C){const x=new Date(j.startDate);let d;h||r?(d=Sl(x,g,h,r,c),d=en(d,h,r,c)):(d=new Date(x),d.setUTCDate(d.getUTCDate()-l)),d.setUTCHours(x.getUTCHours(),x.getUTCMinutes(),0,0);let b=null;if(j.endDate){const D=new Date(j.endDate);if(h||r){const _=qs(x,D,h,r,c);b=xn(d,_-1,h,r,c)}else{const _=Math.round((D.getTime()-x.getTime())/864e5);b=new Date(d),b.setUTCDate(b.getUTCDate()+_)}b.setUTCHours(D.getUTCHours(),D.getUTCMinutes(),0,0)}const y=x.getTime()!==d.getTime(),S=j.endDate&&b?new Date(j.endDate).getTime()!==b.getTime():!1;(y||S)&&k.push({assignment:j,newStartDate:d,newEndDate:b})}return k}function ui(t,a,s,n,o,i,p,c){const m=i.find(D=>D.id===t),h=m?m.isHalfDay:!1,r=m?m.halfDayPeriod:null,C=p.avoidWeekends,g=p.avoidHolidays,l=i.filter(D=>{if(D.id===t||D.isPinned)return!1;const _=new Date(D.startDate);return!((D.endDate?new Date(D.endDate):_)<n)}).sort((D,_)=>new Date(D.startDate).getTime()-new Date(_.startDate).getTime());if(l.length===0)return[];const k=[];let j=new Date(o||n);j.setUTCDate(j.getUTCDate()+1);let x=en(j,C,g,c);x.setUTCHours(0,0,0,0);let d=h,b=r,y=o?new Date(o):new Date(n);const S=(D,_,f)=>{if(!d||!D||!b||!_||b===_)return!1;const v=y??new Date(o??n);return f.getUTCFullYear()===v.getUTCFullYear()&&f.getUTCMonth()===v.getUTCMonth()&&f.getUTCDate()===v.getUTCDate()};for(const D of l){const _=new Date(D.startDate);
2if(S(D.isHalfDay,D.halfDayPeriod,_)){d=D.isHalfDay,b=D.halfDayPeriod,y=D.endDate?new Date(D.endDate):_,j=new Date(D.endDate??D.startDate),j.setUTCDate(j.getUTCDate()+1),x=en(j,C,g,c),x.setUTCHours(0,0,0,0);continue}if(_<x){const f=new Date(D.startDate),v=new Date(x);v.setUTCHours(f.getUTCHours(),f.getUTCMinutes(),0,0);let M=null;if(D.endDate){const W=new Date(D.endDate),N=qs(f,W,C,g,c);M=xn(v,N-1,C,g,c),M.setUTCHours(W.getUTCHours(),W.getUTCMinutes(),0,0)}k.push({assignment:D,newStartDate:v,newEndDate:M}),d=D.isHalfDay,b=D.halfDayPeriod,y=M??v,j=new Date(M||v),j.setUTCDate(j.getUTCDate()+1),x=en(j,C,g,c),x.setUTCHours(0,0,0,0)}else break}return k}function tn(t){return t==null?!1:Number.isInteger(t)&&t>0}async function Nl(t){const{pendingChanges:a,queryClient:s,createClientAssignment:n,cascadeUpdateCalendarEvent:o,cascadeUpdateClientAssignment:i,updateCalendarEvent:p,batchUpdateClientAssignments:c}=t,m=a.filter(_=>!_.cascadeFromChangeId);if(m.length===0)throw q.info("Aucune modification à publier."),new Error("NO_CHANGES");const h=m.filter(_=>_.type==="new-assignment"),r=m.filter(_=>_.type==="client-assignment"&&tn(_.payload.id)),C=new Set,g=[];for(const _ of r)_.payload.id&&!C.has(_.payload.id)&&(C.add(_.payload.id),g.push(_));const l=a.filter(_=>_.cascadeFromChangeId&&_.type==="client-assignment"&&tn(_.payload.id));l.length>0&&console.log("[PUBLISH] Including backward cascade changes in batch:",l.map(_=>({id:_.payload.id,cascadeFrom:_.cascadeFromChangeId})));const k=[...g];for(const _ of l)C.has(_.payload.id)||(C.add(_.payload.id),k.push(_));const j=m.filter(_=>_.type==="calendar-event"),x=m.filter(_=>_.type==="client-assignment"&&!tn(_.payload.id));for(const _ of x)console.warn("[PUBLISH] Skipping update for invalid/temporary ID:",_.payload.id);let d=0,b=0;const y=[];for(const _ of h)try{console.log("[PUBLISH] Creating new assignment:",_.payload);const f=await n.mutateAsync(_.payload);if(d++,!_.payload.clientId)console.log("[PUBLISH] Skipping cascade for internal task (no clientId):",{assignmentId:f.assignment?.id,taskTitle:_.payload.taskTitle});else if(f.assignment&&_.payload.startDate){const M=new Date(_.payload.startDate),W=_.payload.endDate?new Date(_.payload.endDate):M,N=M,O=M;console.log("[PUBLISH] Triggering cascade for new assignment:",{assignmentId:f.assignment.id,oldStartDate:N.toISOString(),oldEndDate:O.toISOString(),newStartDate:M.toISOString(),newEndDate:W.toISOString(),daysDuration:(W.getTime()-M.getTime())/(1e3*60*60*24),specialty:_.payload.specialty});try{const w=await i.mutateAsync({assignmentId:f.assignment.id,oldStartDate:N,oldEndDate:O,newStartDate:M,newEndDate:W,sendNotifications:!0,specialty:_.payload.specialty});console.log("[PUBLISH] Cascade for new assignment completed:",{assignmentId:f.assignment.id,affectedCount:w.affectedAssignments.length})}catch(w){console.error("[PUBLISH] Cascade update error (non-blocking):",w)}}if(f.assignment&&_.payload._pendingPhotos?.length>0){console.log("[PUBLISH] Uploading photos for new assignment:",_.payload._pendingPhotos.length);for(const M of _.payload._pendingPhotos)try{const W=await mr(M.base64,"task-photos");await gr({clientCalendarAssignmentId:f.assignment.id,caption:M.caption||null,photoType:M.photoType,photoUrl:W})}catch(W){console.error("[PUBLISH] Failed to upload/save photo:",W)}}}catch(f){console.error("[PUBLISH] Error creating new assignment:",_,f),b++;const v=f instanceof Error?f.message:String(f);y.push(v)}if(k.length>0){const _=k.map(f=>f.payload);console.log("[PUBLISH] Batch updating assignments:",_.map(f=>f.id));try{const f=await c({updates:_,skipConflictCheck:!0});console.log("[PUBLISH] Batch update succeeded:",{results:f.results,updatedCount:f.updatedAssignments.length}),d+=f.results.filter(v=>v.status==="success").length,b+=f.results.filter(v=>v.status==="failed").length;for(const v of f.results)v.status==="failed"&&v.error&&y.push(v.error);for(const v of g){if(v.skipCascade){console.log("[PUBLISH] Skipping cascade for assignment (user chose leave gap):",v.payload.id);continue}if(!v.originalSnapshot||!v.payload.startDate&&v.payload.endDate===void 0)continue;const M=new Date(v.originalSnapshot.startDate),W=v.originalSnapshot.endDate?new Date(v.originalSnapshot.endDate):M,N=v.payload.startDate?new Date(v.payload.startDate):M,O=v.payload.endDate!==void 0?v.payload.endDate?new Date(v.payload.endDate):N:W;if(M.getTime()!==N.getTime()||W.getTime()!==O.getTime()){console.log("[PUBLISH] Triggering cascade for updated assignment:",{assignmentId:v.payload.id,oldStartDate:M.toISOString(),oldEndDate:W.toISOString(),newStartDate:N.toISOString(),newEndDate:O.toISOString(),specialty:v.payload.specialty});try{const B=await i.mutateAsync({assignmentId:v.payload.id,oldStartDate:M,oldEndDate:W,newStartDate:N,newEndDate:O,sendNotifications:!0,specialty:v.payload.specialty});console.log("[PUBLISH] Cascade for updated assignment completed:",{assignmentId:v.payload.id,affectedCount:B.affectedAssignments.length})}catch(B){console.error("[PUBLISH] Cascade update error (non-blocking):",B)}}else console.log("[PUBLISH] Dates unchanged, skipping cascade for assignment:",v.payload.id)}}catch(f){console.error("[PUBLISH] Batch update failed:",f);const v=f instanceof Error?f.message:String(f);b+=k.length,y.push(v),q.error(`Erreur lors de la mise à jour groupée : ${v}`)}}const S=[],D={};for(const _ of j){const f=_.payload.companyId;f?(D[f]||(D[f]=[]),D[f].push(_)):S.push(p.mutateAsync(_.payload))}for(const[_,f]of Object.entries(D))for(const v of f)S.push(o.mutateAsync({eventId:v.payload.eventId,oldStartDate:v.payload.oldStartDate||v.originalSnapshot?.startDatetime,newStartDate:v.payload.newStartDate||v.payload.startDatetime,sendNotifications:!0,companyId:p
2arseInt(_)}));if(S.length>0){const _=await Promise.allSettled(S);d+=_.filter(v=>v.status==="fulfilled").length,b+=_.filter(v=>v.status==="rejected").length;const f=_.filter(v=>v.status==="rejected").map(v=>v.reason instanceof Error?v.reason.message:String(v.reason));y.push(...f)}return await s.invalidateQueries({queryKey:[Wt]}),await s.invalidateQueries({queryKey:ds}),await s.invalidateQueries({queryKey:pr}),await s.invalidateQueries({queryKey:[fs,"list"]}),{successes:d,failures:b,errorMessages:y.join("; ")}}const Tl={pendingChanges:[],isPublishing:!1,publishError:null},Il=(t,a)=>lr(t,s=>{switch(a.type){case"REGISTER_CHANGE":s.pendingChanges.unshift(a.payload);break;case"REGISTER_CHANGES":for(const n of a.payload)s.pendingChanges.unshift(n);break;case"REMOVE_CHANGE":s.pendingChanges=s.pendingChanges.filter(n=>n.id!==a.payload.changeId);break;case"REMOVE_CHANGES":s.pendingChanges=s.pendingChanges.filter(n=>!a.payload.changeIds.includes(n.id));break;case"CLEAR_ALL":s.pendingChanges=[],s.publishError=null;break;case"SET_PUBLISHING":s.isPublishing=a.payload;break;case"PUBLISH_SUCCESS":s.pendingChanges=[],s.isPublishing=!1,s.publishError=null;break;case"PUBLISH_ERROR":s.isPublishing=!1,s.publishError=a.payload;break}}),pi=u.createContext(void 0),El=({children:t,businessHoursSettings:a})=>{const[s,n]=u.useReducer(Il,Tl),o=gt(),p=a??{enabled:!1,workDays:[1,2,3,4,5],startTime:"08:00",endTime:"17:00",avoidWeekends:!0,avoidHolidays:!0},c=ci(),m=gl(),h=jl(),r=Cl(),C=dr(),g=u.useCallback(_=>{const f=s.pendingChanges.find(v=>v.type==="new-assignment"&&v.payload.tempId===_);f&&n({type:"REMOVE_CHANGE",payload:{changeId:f.id}})},[s.pendingChanges]),l=u.useCallback((_,f,v,M,W)=>{const N=v??p;let O=_.payload;_.type==="new-assignment"&&!O.tempId&&(O={...O,tempId:-Math.abs(Date.now()+Math.random())});const w={..._,payload:O,id:fa(),timestamp:new Date};if(_.skipCascade){n({type:"REGISTER_CHANGE",payload:w});return}if(_.type==="client-assignment"&&_.payload?.id&&tn(_.payload.id)&&_.originalSnapshot&&f&&(_.payload.startDate||_.payload.endDate)){const B=new Date(_.originalSnapshot.startDate),I=_.originalSnapshot.endDate?new Date(_.originalSnapshot.endDate):null,F=_.payload.startDate?new Date(_.payload.startDate):B,de=_.payload.endDate!==void 0?_.payload.endDate?new Date(_.payload.endDate):null:I;if(B.getTime()!==F.getTime()||(I?.getTime()??null)!==(de?.getTime()??null)){const A=N.avoidWeekends||N.avoidHolidays?ui(_.payload.id,B,I,F,de,f,N,M):di(_.payload.id,B,I,F,de,f),Y=A.length>0?A:W||[];if(Y.length>0){const E=Y.map(({assignment:$,newStartDate:R,newEndDate:Q})=>({id:fa(),type:"client-assignment",payload:{id:$.id,startDate:R,endDate:Q},originalSnapshot:{...$,startDate:$.startDate,endDate:$.endDate},timestamp:new Date,description:`Décalage automatique: ${$.firstName} ${$.lastName}`,cascadeFromChangeId:w.id}));n({type:"REGISTER_CHANGES",payload:[w,...E]});return}}}n({type:"REGISTER_CHANGE",payload:w})},[p]),k=u.useCallback(_=>{n({type:"REMOVE_CHANGE",payload:{changeId:_}})},[]),j=u.useCallback(_=>{const v=s.pendingChanges.filter(M=>M.cascadeFromChangeId===_).map(M=>M.id);v.length>0?n({type:"REMOVE_CHANGES",payload:{changeIds:[_,...v]}}):k(_)},[s.pendingChanges,k]),x=u.useCallback(()=>{const _=s.pendingChanges.find(f=>!f.cascadeFromChangeId);_&&j(_.id)},[s.pendingChanges,j]),d=u.useCallback(()=>{n({type:"CLEAR_ALL"})},[]),b=u.useCallback(async()=>{n({type:"SET_PUBLISHING",payload:!0});try{const _=await Nl({pendingChanges:s.pendingChanges,queryClient:o,createClientAssignment:c,deleteClientAssignment:m,cascadeUpdateCalendarEvent:h,cascadeUpdateClientAssignment:r,updateCalendarEvent:C,batchUpdateClientAssignments:wl}),{successes:f,failures:v,errorMessages:M}=_;v===0?(n({type:"PUBLISH_SUCCESS"}),q.success(`${f} modification${f>1?"s":""} publiée${f>1?"s":""} avec succès !`)):(n({type:"PUBLISH_ERROR",payload:M}),f>0?q.warning(`${f} modification${f>1?"s":""} publiée${f>1?"s":""}, mais ${v} ont échoué.`):q.error(`Ãchec de la publication : ${M}`))}catch(_){if(_ instanceof Error&&_.message==="NO_CHANGES"){n({type:"SET_PUBLISHING",payload:!1});return}const f=_ instanceof Error?_.message:"Une erreur inconnue s'est produite.";n({type:"PUBLISH_ERROR",payload:f}),q.error(`Erreur lors de la publication : ${f}`),console.error("Publish draft error:",_)}},[s.pendingChanges,o,c,m,h,r,C]),y=u.useMemo(()=>s.pendingChanges.length,[s.pendingChanges]),S=u.useMemo(()=>y>0,[y]),D={...s,registerChange:l,revertChange:j,removeChange:k,removeAssignmentDraft:g,undoLastChange:x,clearAll:d,publishDraft:b,pendingCount:y,hasPendingChanges:S};return e.jsx(pi.Provider,{value:D,children:t})},Qt=()=>{const t=u.useContext(pi);if(t===void 0)throw new Error("useScheduleDraft must be used within a DraftScheduleProvider");return t},Pl=Ee({assignmentIdA:Me().int().positive(),assignmentIdB:Me().int().positive()}),$l=async(t,a)=>{const s=Pl.parse(t),n=await fetch("/_api/client-assignments/swap",{method:"POST",body:K.stringify(s),...a,headers:{"Content-Type":"application/json"}});if(!n.ok){const o=K.parse(await n.text());throw new Error(typeof o=="object"&&o!==null&&"error"in o?String(o.error):"An unknown error occurred")}return K.parse(await n.text())},Ml=Ee({afterAssignmentId:Me().int().positive(),gapDays:Me().int().positive(),sendNotifications:$e().default(!1)}),Al=async(t,a)=>{const s=Ml.parse(t),n=await fetch("/_api/client-assignments/fill-swap-gap",{method:"POST",body:K.stringify(s),...a,headers:{"Content-Type":"application/json"}});if(!n.ok){const o=K.parse(await n.text());throw new Error(typeof o=="object"&&o!==null&&"error"in o?String(o.error):"An unknown error occurred")}return K.parse(await n.text())},mi=u.createContext(void 0),Bl=({children:t,onSwapComplete:a})=>
2{const[s,n]=u.useState(null),[o,i]=u.useState(null),[p,c]=u.useState(!1),m=gt(),h=je.useRef(a);je.useEffect(()=>{h.current=a},[a]);const r=Ve({mutationFn:d=>$l(d),onSuccess:d=>{d.gaps&&d.gaps.length>0?(i(d.gaps),q.info("Ãchange effectué. Un trou a été créé dans le calendrier.")):q.success("Ãchange effectué avec succès !"),m.invalidateQueries({queryKey:[Wt]}),n(null),h.current?.()},onError:d=>{q.error(`Ãchec de l'échange : ${d.message}`)}}),C=u.useCallback(d=>{n(d);const b=d.taskTitle?`Tâche: ${d.taskTitle}`:`${d.firstName||""} ${d.lastName||""}`.trim()||"Assignation sans nom";q.info(`Sélectionné pour échange : ${b}`)},[]),g=u.useCallback(()=>{n(null)},[]),l=u.useCallback(async d=>{if(s){if(s.id===d){q.warning("Impossible d'échanger avec la même assignation.");return}await r.mutateAsync({assignmentIdA:s.id,assignmentIdB:d})}},[s,r]),k=u.useCallback(async d=>{if(!(!o||o.length===0)){c(!0);try{for(const b of o)await Al({afterAssignmentId:b.afterAssignmentId,gapDays:b.gapDays,sendNotifications:d});q.success("Trous comblés avec succès !"),i(null),m.invalidateQueries({queryKey:[Wt]})}catch(b){const y=b instanceof Error?b.message:"Erreur inconnue";q.error(`Erreur lors du comblement des trous : ${y}`)}finally{c(!1)}}},[o,m]),j=u.useCallback(()=>{i(null),q.success("Ãchange effectué avec succès !")}
2,[]),x={selectedAssignment:s,isSwapMode:!!s,selectForSwap:C,clearSelection:g,executeSwap:l,isSwapping:r.isPending,pendingGaps:o,fillGaps:k,dismissGaps:j,isFillingGaps:p};return e.jsx(mi.Provider,{value:x,children:t})},Un=()=>{const t=u.useContext(mi);if(t===void 0)throw new Error("useSwapSelection must be used within a SwapSelectionProvider");return t},vs=t=>{const a=new Date(t);return a.setUTCHours(0,0,0,0),a.toISOString()},Hl=(t,a)=>u.useMemo(()=>{if(a==="day"){const s=ge(t),n=es(t);return{startDateISO:vs(s),endDateISO:vs(n),calendarStart:s,calendarEnd:n,currentDate:t}}else if(a==="week"){const s=Tn(t,{weekStartsOn:1}),n=In(t,{weekStartsOn:1});return{startDateISO:vs(s),endDateISO:vs(n),calendarStart:s,calendarEnd:n,currentDate:t}}else{const s=jr(t),n=vr(t),o=Tn(s,{weekStartsOn:1}),i=In(n,{weekStartsOn:1});return{startDateISO:vs(o),endDateISO:vs(i),calendarStart:o,calendarEnd:i,currentDate:t}}},[t,a]);Ee({startDate:X().min(1,"Start date is required"),endDate:X().min(1,"End date is required"),specialty:X().optional()});const Ll=async(t,a)=>{const s=new URLSearchParams;s.set("startDate",t.startDate),s.set("endDate",t.endDate),t.specialty&&s.set("specialty",t.specialty);const n=await fetch(`/_api/calendar-blocks/list?${s.toString()}`,{method:"GET",...a,headers:{"Content-Type":"application/json"}});if(!n.ok){const o=K.parse(await n.text());throw new Error(o.error||"An unknown error occurred")}return K.parse(await n.text())},Ol=Ee({blockType:Ye(["client_reservation","company_block"]),startDate:rt.date(),endDate:rt.date(),specialty:X().min(1,"Specialty is required"),clientId:Me().int().positive().optional().nullable(),notes:X().optional().nullable()}),Rl=async(t,a)=>{const s=Ol.parse(t),n=await fetch("/_api/calendar-blocks/create",{method:"POST",body:K.stringify(s),...a,headers:{"Content-Type":"application/json"}});if(!n.ok){const o=K.parse(await n.text());throw new Error(o.error||"An unknown error occurred")}return K.parse(await n.text())},Fl=Ee({blockId:Me().int().positive()}),Ul=async(t,a)=>{const s=Fl.parse(t),n=await fetch("/_api/calendar-blocks/delete",{method:"POST",body:K.stringify(s),...a,headers:{"Content-Type":"application/json"}});if(!n.ok){const o=K.parse(await n.text());throw new Error(o.error||"An unknown error occurred")}return K.parse(await n.text())},qn="calendarBlocks",ql=t=>ms({queryKey:[qn,t.startDate,t.endDate,t.specialty],queryFn:()=>Ll(t),enabled:!!t.startDate&&!!t.endDate,refetchOnWindowFocus:!0,refetchOnMount:!1,refetchOnReconnect:!0,staleTime:3e5,placeholderData:a=>a}),zl=()=>{const t=gt();return Ve({mutationFn:a=>Rl(a),onSuccess:()=>{t.invalidateQueries({queryKey:[qn]})}})},Wl=()=>{const t=gt();return Ve({mutationFn:a=>Ul(a),onSuccess:()=>{t.invalidateQueries({queryKey:[qn]})}})},hi=()=>{const t=gt(),a=r=>{q.success(r)},s=()=>{t.invalidateQueries({queryKey:ds})},n=(r,C)=>{const g=r instanceof Error?r.message:"An unknown error occurred.";q.error(`${C}: ${g}`),console.error(C,r)},o=Ve({mutationFn:r=>ma(r),onSuccess:()=>{a("Tâche créée avec succès."),t.invalidateQueries({queryKey:["projectTasks"]})},onError:r=>n(r,"Erreur lors de la création de la tâche"),onSettled:s}),i=Ve({mutationFn:r=>ur(r),onMutate:async r=>{await t.cancelQueries({queryKey:ds});const C=t.getQueriesData({queryKey:ds});return t.setQueriesData({queryKey:[...ds,"list"]},g=>{if(!g?.events)return g;const l=g.events.map(k=>k.id===r.eventId?{...k,...Object.fromEntries(Object.entries(r).filter(([j,x])=>j!=="eventId"&&j!=="taskStatus"&&j!=="taskCategory"&&x!==void 0))}:k);return{...g,events:l}}),{previousQueries:C}},onSuccess:()=>a("Tâche mise à jour avec succès."),onError:(r,C,g)=>{if(g?.previousQueries)for(const[l,k]of g.previousQueries)t.setQueryData(l,k);n(r,"Erreur lors de la mise à jour de la tâche")},onSettled:s}),p=Ve({mutationFn:r=>Vo(r),onSuccess:()=>a("Tâche supprimée avec succès."),onError:r=>n(r,"Erreur lors de la suppression de la tâche"),onSettled:s}),c=Ve({mutationFn:async r=>{const C={title:`${r.title} (copie)`,description:r.description,startDatetime:new Date(new Date(r.startDatetime).getTime()+864e5).toISOString(),endDatetime:new Date(new Date(r.endDatetime).getTime()+864e5).toISOString(),allDay:r.allDay??!1,location:r.location,projectId:r.projectId,taskId:r.taskId,isWeatherDependent:r.isWeatherDependent??!1};return ma(C)},onSuccess:()=>a("Tâche dupliquée avec succès."),onError:r=>n(r,"Erreur lors de la duplication de la tâche"),onSettled:s}),m=o.isPending||i.isPending||p.isPending||c.isPending,h={create:o.error,update:i.error,delete:p.error,duplicate:c.error};return{createEvent:o.mutateAsync,updateEvent:i.mutateAsync,deleteEvent:p.mutateAsync,duplicateEvent:c.mutateAsync,isLoading:m,error:h}},gi=u.createContext({}),zn=()=>u.useContext(gi),Gl=gi.Provider,Vl=(t,a,s)=>{const n=[...t],o=new Set;for(const i of a)if(i.type==="client-assignment"&&i.payload.id){if(o.has(i.payload.id))continue;o.add(i.payload.id);const p=n.findIndex(c=>c.id===i.payload.id);p!==-1&&(n[p]={...n[p],startDate:i.payload.startDate instanceof Date?i.payload.startDate:new Date(i.payload.startDate),endDate:i.payload.endDate!==void 0?i.payload.endDate instanceof Date?i.payload.endDate:i.payload.endDate?new Date(i.payload.endDate):null:n[p].endDate,notes:i.payload.notes!==void 0?i.payload.notes:n[p].notes,specialty:i.payload.specialty!==void 0?i.payload.specialty:n[p].specialty})}else if(i.type==="new-assignment"&&(i.payload.clientId||i.payload.taskTitle)){const p=i.payload.tempId??-Math.abs(Date.now()+Math.random());if(o.has(p)||(o.add(p),s&&i.payload.specialty!==s))continue;n.push({id:p,clientId:i.payload.clientId??null,startDate:i.payload.startDate instanceof Date?i.payload.startDate:new Date(i.payload.startDate),endDate:i.payload.endDate?i.payload.endDate instanceof Date?i.payload.endDate:new Date(i.payload.endDate):null,notes:i.payload.notes||null,specialty:i.payload.specialty||null,isPinned:i.payload.isPinned!==void 0?i.payload.isPinned:!1,isHalfDay:i.payload.isHalfDay!==void 0?i.payload.isHalfDay:!1,halfDayPeriod:i.payload.halfDayPeriod||null,allDay:i.payload.allDay!==void 0?i.payload.allDay:!0,quoteId:i.payload.quoteId??null,quoteTitle:i.payload.quoteTitle??null,createdAt:new Date,updatedAt:new Date,firstName:i.payload.firstName||"",lastName:i.payload.lastName||"",email:i.payload.email||"",activeProjectCount:0,quoteLineItemCount:i.payload.quoteLineItemCount??0,taskTitle:i.payload.taskTitle||null,taskDescription:i.payload.taskDescription||null,taskLocation:i.payload.taskLocation||null,taskPriority:i.payload.taskPriority||null,taskStatus:i.payload.taskStatus||null,isSoldePaid:!1})}return n},Yl="_dialogContent_gyjws_1",Ql="_optionsContainer_gyjws_5",Kl="_optionCard_gyjws_13",Jl="_selected_gyjws_32",Xl="_iconContainer_gyjws_37",Zl="_icon_gyjws_37",ec="_textContainer_gyjws_59",tc="_optionTitle_gyjws_66",sc="_optionDesc_gyjws_73",nc="_radioIndicator_gyjws_79",ac="_radioDot_gyjws_95",Ae={dialogContent:Yl,optionsContainer:Ql,optionCard:Kl,selected:Jl,iconContainer:Xl,icon:Zl,textContainer:ec,optionTitle:tc,optionDesc:sc,radioIndicator:nc,radioDot:ac};function ic({isOpen:t,onClose:a,onChoice:s,movedAssignmentName:n,shiftDays:o,fromDate:i,toDate:p,monthCount:c,yearCount:m,specialtyName:h,isLoadingYearData:r=!1}){const{language:C}=ye(),[g,l]=u.useState("month");u.useEffect(()=>{t&&l("month")},[t]);const k=()=>{s(g)},j=new Intl.DateTimeFormat(C==="fr"?"fr-FR":"en-US",{day:"numeric",month:"short",year:"numeric"}),x=j.format(i),d=j.format(p),b={title:C==="fr"?"Rapprocher les contrats":"Close schedule gap",description:C==="fr"?`${n} déplacé du ${x} au ${d} (${o} jour(s) plus tôt).`:`${n} moved from ${x} to ${d} (${o} day(s) earlier).`,optNoneTitle:C==="fr"?"Déplacer uniquement ce contrat":"Move only this contract",optNoneDesc:C==="fr"?"Les autres contrats restent à leur place.":"Other contracts stay in place.",optMonthTitle:C==="fr"?`Rapprocher les contrats du mois (${c})`:`Close gap for this month's contracts (${c})`,optMonthDesc:C==="fr"?`Les contrats non-épinglés du mois en cours se rapprochent de ${o} jour(s).`:`Unpinned contracts in the current month are moved ${o} day(s) earlier.`,optYearTitle:C==="fr"?`Rapprocher TOUS les contrats de l'année (${r?"...":m})`:`Close gap for ALL year's contracts (${r?"...":m})`,optYearDesc:C==="fr"?`Tous les contrats non-épinglés de ${h} pour l'année se rapprochent de ${o} jour(s).`:`All unpinned ${h} contracts for the year are moved ${o} day(s) earlier.`,confirm:C==="fr"?"Confirmer":"Confirm",cancel:C==="fr"?"Annuler":"Cancel"};return e.jsx(Qe,{open:t,onOpenChange:y=>!y&&a(),children:e.jsxs(Ke,{className:Ae.dialogContent,children:[e.jsxs(lt,{children:[e.jsx(Je,{children:b.title}),e.jsx($t,{children:b.description})]}),e.jsxs("div",{className:Ae.optionsContainer,children:[e.jsxs("button",{type:"button",className:`${Ae.optionCard} ${g==="none"?Ae.selected:""}`,onClick:()=>l("none"),children:[e.jsx("div",{className:Ae.iconContainer,children:e.jsx(ba,{className:Ae.icon})}),e.jsxs("div",{className:Ae.textContainer,children:[e.jsx("span",{className:Ae.optionTitle,children:b.optNoneTitle}),e.jsx("span",{className:Ae.optionDesc,children:b.optNoneDesc})]}),e.jsx("div",{className:Ae.radioIndicator,children:g==="none"&&e.jsx("div",{className:Ae.radioDot})})]}),e.jsxs("button",{type:"button",className:`${Ae.optionCard} ${g==="month"?Ae.selected:""}`,onClick:()=>l("month"),children:[e.jsx("div",{className:Ae.iconContainer,children:e.jsx(mo,{className:Ae.icon})}),e.jsxs("div",{className:Ae.textContainer,children:[e.jsx("span",{className:Ae.optionTitle,children:b.optMonthTitle}),e.jsx("span",{className:Ae.optionDesc,children:b.optMonthDesc})]}),e.jsx("div",{className:Ae.radioIndicator,children:g==="month"&&e.jsx("div",{className:Ae.radioDot})})]}),e.jsxs("button",{type:"button",className:`${Ae.optionCard} ${g==="year"?Ae.selected:""}`,onClick:()=>l("year"),children:[e.jsx("div",{className:Ae.iconContainer,children:e.jsx(ho,{className:Ae.icon})}),e.jsxs("div",{className:Ae.textContainer,children:[e.jsx("span",{className:Ae.optionTitle,children:b.optYearTitle}),e.jsx("span",{className:Ae.optionDesc,children:b.optYearDesc})]}),e.jsx("div",{className:Ae.radioIndicator,children:g==="year"&&e.jsx("div",{className:Ae.radioDot})})]})]}),e.jsxs(Ct,{children:[e.jsx(L,{variant:"secondary",onClick:a,children:b.cancel}),e.jsx(L,{onClick:k,disabled:g==="year"&&r,children:b.confirm})]})]})})}const oc="_dialogContent_gyjws_1",rc="_optionsContainer_gyjws_5",lc="_optionCard_gyjws_13",cc="_selected_gyjws_32",dc="_iconContainer_gyjws_37",uc="_icon_gyjws_37",pc="_textContainer_gyjws_59",mc="_optionTitle_gyjws_66",hc="_optionDesc_gyjws_73",gc="_radioIndicator_gyjws_79",_c="_radioDot_gyjws_95",We={dialogContent:oc,optionsContainer:rc,optionCard:lc,selected:cc,iconContainer:dc,icon:uc,textContainer:pc,optionTitle:mc,optionDesc:hc,radioIndicator:gc,radioDot:_c};function fc({isOpen:t,onClose:a,onChoice:s,movedAssignmentName:n,shiftDays:o,fromDate:i,toDate:p,conflictCount:c,specialtyName:m}){const{language:h}=ye(),[r,C]=u.useState("move-only");u.useEffect(()=>{t&&C("move-only")},[t]);const g=()=>{s(r)},l=new Intl.DateTimeFormat(h==="fr"?"fr-FR":"en-US",{day:"numeric",month:"short",year:"numeric"}),k=l.format(i),j=l.format(p),x={title:h==="fr"?"Déplacer le contrat":"Move contract",description:h==="fr"?`${n} déplacé du ${k} au ${j} (${o} jour(s) plus tard).`:`${n} moved from ${k} to ${j} (${o} day(s) later).`,optNoneTitle:h==="fr"?"Déplacer uniquement ce contrat":"Move only this contract",optNoneDesc:h==="fr"?"Les autres contrats restent à leur place. Un espace sera libéré.":"Other contracts stay in place. A gap will be created.",optCascadeTitle:h==="fr"?`Décaler les contrats suivants (${c})`:`Shift subsequent contracts (${c})`,optCascadeDesc:h==="fr"?`Les ${c} contrats suivants en conflit de ${m} seront décalés automatiquement.`:`The ${c} subsequent conflicting ${m} contracts will be shifted automatically.`,confirm:h==="fr"?"Confirmer":"Confirm",cancel:h==="fr"?"Annuler":"Cancel"};return e.jsx(Qe,{open:t,onOpenChange:d=>!d&&a(),children:e.jsxs(Ke,{className:We.dialogContent,children:[e.jsxs(lt,{children:[e.jsx(Je,{children:x.title}),e.jsx($t,{children:x.description})]}),e.jsxs("div",{className:We.optionsContainer,children:[e.jsxs("button",{type:"button",className:`${We.optionCard} ${r==="move-only"?We.selected:""}`,onClick:()=>C("move-only"),children:[e.jsx("div",{className:We.iconContainer,children:e.jsx(ba,{className:We.icon})}),e.jsxs("div",{className:We.textContainer,children:[e.jsx("span",{className:We.optionTitle,children:x.optNoneTitle}),e.jsx("span",{className:We.optionDesc,children:x.optNoneDesc})]}),e.jsx("div",{className:We.radioIndicator,children:r==="move-only"&&e.jsx("div",{className:We.radioDot})})]}),e.jsxs("button",{type:"button",className:`${We.optionCard} ${r==="cascade"?We.selected:""}`,onClick:()=>C("cascade"),children:[e.jsx("div",{className:We.iconContainer,children:e.jsx(go,{className:We.icon})}),e.jsxs("div",{className:We.textContainer,children:[e.jsx("span",{className:We.optionTitle,children:x.optCascadeTitle}),e.jsx("span",{className:We.optionDesc,children:x.optCascadeDesc})]}),e.jsx("div",{className:We.radioIndicator,children:r==="cascade"&&e.jsx("div",{className:We.radioDot})})]})]}),e.jsxs(Ct,{children:[e.jsx(L,{variant:"secondary",onClick:a,children:x.cancel}),e.jsx(L,{onClick:g,children:x.confirm})]})]})})}const xc="_container_1ndfz_1",yc="_header_1ndfz_7",jc="_title_1ndfz_16",Dc="_closeButton_1ndfz_23",vc="_list_1ndfz_39",Cc="_changeItem_1ndfz_59",kc="_changeContent_1ndfz_70",bc="_changeDescription_1ndfz_77",wc="_cascadeInfo_1ndfz_83",Sc="_revertButton_1ndfz_91",Nc="_emptyState_1ndfz_109",At={container:xc,header:yc,title:jc,closeButton:Dc,list:vc,changeItem:Cc,changeContent:kc,changeDescription:bc,cascadeInfo:wc,revertButton:Sc,emptyState:Nc},Tc=({onClose:t})=>{const{pendingChanges:a,revertChange:s}=Qt(),{t:n}
2=ye(),{mainChanges:o,cascadeCountMap:i}=u.useMemo(()=>{const c=[],m={};return a.forEach(h=>{if(h.cascadeFromChangeId){const r=h.cascadeFromChangeId;m[r]=(m[r]||0)+1}else c.push(h)}),{mainChanges:c,cascadeCountMap:m}},[a]),p=c=>{if(c.description)return c.description;switch(c.type){case"new-assignment":return n("draft_new_assignment");case"client-assignment":return n("draft_modify_assignment");case"calendar-event":return n("draft_event_modification");case"delete-event":return n("draft_event_delete");case"duplicate-event":return n("draft_event_duplicate");default:return n("draft_unknown_change")}};return o.length===0?e.jsx("div",{className:At.emptyState,children:n("draft_no_changes")}):e.jsxs("div",{className:At.container,children:[e.jsxs("div",{className:At.header,children:[e.jsx("h3",{className:At.title,children:n("draft_list_title")}),t&&e.jsx("button",{className:At.closeButton,onClick:t,children:e.jsx(qt,{size:16})})]}),e.jsx("div",{className:At.list,children:o.map(c=>{const m=i[c.id]||0;return e.jsxs("div",{className:At.changeItem,children:[e.jsxs("div",{className:At.changeContent,children:[e.jsx("div",{className:At.changeDescription,children:p(c)}),m>0&&e.jsxs("div",{className:At.cascadeInfo,children:[e.jsx(_o,{size:12}),e.jsx("span",{children:n("draft_auto_shift",{count:m})})]})]}),e.jsx("button",{className:At.revertButton,onClick:()=>s(c.id),title:n("draft_revert_change"),children:e.jsx(qt,{size:14})})]},c.id)})})]})},Ic="_banner_buuoz_1",Ec="_content_buuoz_33",Pc="_icon_buuoz_41",$c="_clickableText_buuoz_47",Mc="_actions_buuoz_77",Ac="_button_buuoz_84",Bc="_publishButton_buuoz_103",Hc="_cancelButton_buuoz_113",Lc="_spinner_buuoz_123",Tt={banner:Ic,content:Ec,icon:Pc,clickableText:$c,actions:Mc,button:Ac,publishButton:Bc,cancelButton:Hc,spinner:Lc},Oc=({className:t})=>{const{hasPendingChanges:a,pendingCount:s,publishDraft:n,clearAll:o,undoLastChange:i,isPublishing:p}=Qt(),{t:c,language:m}=ye(),h=()=>{n()},r=()=>{o()};return a?e.jsxs("div",{className:`${Tt.banner} ${t||""}`,children:[e.jsxs("div",{className:Tt.content,children:[e.jsx(Mn,{className:Tt.icon}),e.jsxs(on,{children:[e.jsx(rn,{asChild:!0,children:e.jsx("button",{className:Tt.clickableText,type:"button",children:c("draft_modifications_pending",{count:s})})}),e.jsx(ln,{align:"start",sideOffset:8,children:e.jsx(Tc,{})})]})]}),e.jsxs("div",{className:Tt.actions,children:[e.jsx("button",{className:`${Tt.button} ${Tt.cancelButton}`,onClick:i,disabled:p,title:m==="fr"?"Annuler la dernière action":"Undo last action",children:e.jsx(fo,{size:16})}),e.jsxs("button",{className:`${Tt.button} ${Tt.cancelButton}`,onClick:r,disabled:p,children:[e.jsx(qt,{size:16}),e.jsx("span",{children:c("draft_cancel")})]}),e.jsxs("button",{className:`${Tt.button} ${Tt.publishButton}`,onClick:h,disabled:p,children:[p?e.jsx(ts,{size:16,className:Tt.spinner}):e.jsx(xo,{size:16}),e.jsx("span",{children:c(p?"draft_publishing":"draft_publish")})]})]})]}):null};Ee({});const Rc=async t=>{const a=await fetch("/_api/routes/ready-to-plan",{method:"GET",...t,headers:{"Content-Type":"application/json"}});if(!a.ok){const s=K.parse(await a.text());throw new Error(s.error||"An unknown error occurred")}return K.parse(await a.text())},Fc=Ee({routeId:Me().int().positive(),startDate:rt.date(),allowOutOfSeason:$e().default(!1),recurrenceType:Ye(["none","daily","every_2_days","every_3_days","weekly","biweekly","monthly"]),recurrenceWeeks:Me().int().min(1).max(52).default(1),specialty:X().default("Route"),assignedUserId:Me().int().positive().optional().nullable(),isHalfDay:$e().default(!1),halfDayPeriod:Ye(["am","pm"]).optional().nullable(),notes:X().optional().nullable()}),Uc=async(t,a)=>{const s=Fc.parse(t),n=await fetch("/_api/routes/plan-to-calendar",{method:"POST",body:K.stringify(s),...a,headers:{"Content-Type":"application/json",...a?.headers??{}}});if(!n.ok){const o=K.parse(await n.text());throw new Error(o.error||"An unknown error occurred")}return K.parse(await n.text())},_i="routePlanning",qc="routes";function zc(){return ms({queryKey:[_i],queryFn:()=>Rc(),staleTime:12e4,placeholderData:t=>t})}function Wc(){const t=gt(),{language:a}=ye();return Ve({mutationFn:Uc,onSuccess:s=>{t.invalidateQueries({queryKey:[_i]}),t.invalidateQueries({queryKey:[Wt]}),t.invalidateQueries({queryKey:[qc]});const n=a==="fr"?`Route planifiée avec succès (${s.assignmentsCreated} assignations créées).`:`Route planned successfully (${s.assignmentsCreated} assignments created).`;q.success(n)},onError:s=>{const n=s instanceof Error?s.message:String(s),o=a==="fr"?`Erreur lors de la planification : ${n}`:`Error planning route: ${n}`;q.error(o)}})}const Gc=Ee({quoteId:Me().int().positive(),excluded:$e()}),Vc=async(t,a)=>{const s=Gc.parse(t),n=await fetch("/_api/quotes/scheduling-exclude",{method:"POST",body:K.stringify(s),...a,headers:{"Content-Type":"application/json"}});if(!n.ok){const o=K.parse(await n.text());throw new Error(o.error||"An unknown error occurred")}return K.parse(await n.text())},Yc=()=>{const t=gt(),{language:a}=ye();return Ve({mutationFn:s=>Vc(s),onSuccess:(s,n)=>{t.invalidateQueries({queryKey:[fs]}),t.invalidateQueries({queryKey:ds}),n.excluded?q.success(a==="en"?"Quote removed from scheduling":"Devis retiré de la planification"):q.success(a==="en"?"Quote moved back to scheduling":"Remis dans les devis à planifier")},onError:s=>{q.error(a==="en"?`Error: ${s.message}`:`Erreur : ${s.message}`)}})},Qc="_container_1u06s_1",Kc="_segmentSwitch_1u06s_11",Jc="_segmentBtn_1u06s_19",Xc="_segmentBtnActive_1u06s_37",Zc="_searchContainer_1u06s_56",ed="_searchInputWrapper_1u06s_61",td="_searchIcon_1u06s_76",sd="_searchInput_1u06s_61",nd="_clearBtn_1u06s_96",ad="_tabBar_1u06s_114",id="_tabBtn_1u06s_122",od="_tabBtnActive_1u06s_143",rd="_tabCount_1u06s_149",ld="_tabCountActive_1u06s_164",cd="_listContainer_1u06s_169",dd="_list_1u06s_169",ud="_quoteItem_1u06s_181",pd="_itemHeader_1u06s_197",md="_dragging_1u06s_205",hd="_quoteInfo_1u06s_210",gd="_clientNameRow_1u06s_219",_d="_clientName_1u06s_219",fd="_assignmentBadge_1u06s_231",xd="_metaInfo_1u06s_242",yd="_metaItem_1u06s_252",jd="_rightSide_1u06s_258",Dd="_expandBtn_1u06s_264",vd="_quoteNumber_1u06s_279",Cd="_dragHandle_1u06s_289",kd="_selected_1u06s_306",bd="_expandedArea_1u06s_313",wd="_expandedAreaOpen_1u06s_320",Sd="_expandedContentWrapper_1u06s_324",Nd="_expandedContent_1u06s_324",Td="_innerCard_1u06s_332",Id="_lineItem_1u06s_341",Ed="_lineItemMain_1u06s_355",Pd="_lineItemTitle_1u06s_361",$d="_lineItemDesc_1u06s_367",Md="_lineItemTotals_1u06s_377",Ad="_lineItemPrice_1u06s_385",Bd="_lineItemQty_1u06s_391",Hd="_subtotalRow_1u06s_396",Ld="_extrasSection_1u06s_408",Od="_extraContainer_1u06s_415",Rd="_extraHeader_1u06s_425",Fd="_extraBadge_1u06s_434",Ud="_extraTitle_1u06s_445",qd="_cancelBtn_1u06s_456",zd="_accessDenied_1u06s_478",Wd="_emptyState_1u06s_508",Gd="_emptyMessage_1u06s_519",Vd="_error_1u06s_525",Yd="_skeletonItem_1u06s_531",Qd="_skeletonText_1u06s_542",Kd="_excludeSc
2hedulingBtn_1u06s_549",Jd="_noSchedulingBadge_1u06s_571",H={container:Qc,segmentSwitch:Kc,segmentBtn:Jc,segmentBtnActive:Xc,searchContainer:Zc,searchInputWrapper:ed,searchIcon:td,searchInput:sd,clearBtn:nd,tabBar:ad,tabBtn:id,tabBtnActive:od,tabCount:rd,tabCountActive:ld,listContainer:cd,list:dd,quoteItem:ud,itemHeader:pd,dragging:md,quoteInfo:hd,clientNameRow:gd,clientName:_d,assignmentBadge:fd,metaInfo:xd,metaItem:yd,rightSide:jd,expandBtn:Dd,quoteNumber:vd,dragHandle:Cd,selected:kd,expandedArea:bd,expandedAreaOpen:wd,expandedContentWrapper:Sd,expandedContent:Nd,innerCard:Td,lineItem:Id,lineItemMain:Ed,lineItemTitle:Pd,lineItemDesc:$d,lineItemTotals:Md,lineItemPrice:Ad,lineItemQty:Bd,subtotalRow:Hd,extrasSection:Ld,extraContainer:Od,extraHeader:Rd,extraBadge:Fd,extraTitle:Ud,cancelBtn:qd,accessDenied:zd,emptyState:Wd,emptyMessage:Gd,error:Vd,skeletonItem:Yd,skeletonText:Qd,excludeSchedulingBtn:Kd,noSchedulingBadge:Jd},ht={SIGNED_QUOTE:"SIGNED_QUOTE",CLIENT_ASSIGNMENT:"CLIENT_ASSIGNMENT",ROUTE_ITEM:"ROUTE_ITEM"},Xd=({extraId:t,canViewPrices:a,formatCurrency:s})=>{const{language:n}=ye(),{data:o,isLoading:i}=br(t);return i?e.jsx("div",{className:H.extraContainer,children:e.jsx(ne,{style:{height:"1.25rem",width:"100%"}})}):o?e.jsxs("div",{className:H.extraContainer,children:[e.jsxs("div",{className:H.extraHeader,children:[e.jsxs("span",{className:H.extraBadge,children:["Extra #",o.extraNumber]}),e.jsx("span",{className:H.extraTitle,children:o.title})]}),o.lineItems.map(p=>e.jsxs("div",{className:H.lineItem,children:[e.jsxs("div",{className:H.lineItemMain,children:[e.jsx("span",{className:H.lineItemTitle,children:p.title}),p.description&&e.jsx("span",{className:H.lineItemDesc,children:p.description})]}),e.jsx("div",{className:H.lineItemTotals,children:a?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:H.lineItemPrice,children:s(p.totalPrice)}),e.jsxs("span",{className:H.lineItemQty,children:[p.quantity," ",p.unit||"u"," à ",s(p.unitPrice)]})]}):e.jsxs("span",{className:H.lineItemQty,children:[p.quantity," ",p.unit||"u"]})})]},p.id)),a&&e.jsxs("div",{className:H.subtotalRow,children:[e.jsx("span",{children:n==="en"?"Extra Subtotal":"Sous-total extra"}),e.jsx("span",{children:s(o.totalAmount)})]})]}):null},Zd=({quote:t,onQuoteSelect:a,isSelected:s,isMobile:n,showAssignmentBadge:o})=>{const[i,p]=je.useState(!1),[c,m]=je.useState(!1),{t:h,language:r}=ye(),C=gt(),{authState:g}=Vt(),{hasPermission:l}=gs(),{formatCurrency:k}=Yo(),j=Yc(),x=g.type==="authenticated"?g.user.role:null,d=x==="admin"||x==="company"||x==="owner"||l("quotes.view"),b=l("quotes.view_without_pricing"),y=d||b,S=Ve({mutationFn:T=>Qo({id:T,status:"annulé_client"}),onSuccess:()=>{q.success(r==="fr"?"Devis annulé par le client":"Quote cancelled by client"),C.invalidateQueries({queryKey:[fs]})},onError:T=>{q.error(r==="fr"?`Erreur: ${T.message}`:`Error: ${T.message}`)}}),D=T=>{T.stopPropagation();const A=r==="fr"?"Confirmer l'annulation du devis par le client ?":"Confirm cancellation by the client?";window.confirm(A)&&S.mutate(t.id)},_=T=>{T.stopPropagation();const A=t.schedulingExcludedAt!=null,Y=A?r==="fr"?"Remettre ce devis dans la planification ?":"Move this quote back to scheduling?":r==="fr"?"Retirer ce devis de la colonne à planifier ? Il restera signé et facturable.":"Remove this quote from the To schedule column? It will remain signed and billable.";window.confirm(Y)&&j.mutate({quoteId:t.id,excluded:!A})},{data:f,isLoading:v}=Va(c?t.id:0),{data:M}=kr(c?t.id:0),W=je.useMemo(()=>M?.extras.filter(T=>T.status==="signé")||[],[M]),[{isDragging:N},O,w]=hn(()=>({type:ht.SIGNED_QUOTE,item:()=>({type:ht.SIGNED_QUOTE,id:t.id,quoteId:t.id,projectId:t.projectId,clientId:t.clientId,quoteData:t}),collect:T=>({isDragging:T.isDragging()})}),[t]);je.useEffect(()=>{if(N)p(!0);else{const T=setTimeout(()=>p(!1),100);return()=>clearTimeout(T)}},[N]);const B=je.useCallback(T=>{w(T)},[w]),I=je.useCallback(T=>{O(T)},[O]),F=T=>{i||T.target.closest(`.${H.dragHandle}`)||T.target.closest(`.${H.excludeSchedulingBtn}`)||T.target.closest(`.${H.cancelBtn}`)||(m(!c),n&&a&&a(t))},de=T=>{T.stopPropagation()},fe=r==="en"?Vs:zt;return e.jsxs("div",{ref:B,className:`${H.quoteItem} ${N?H.dragging:""} ${s?H.selected:""} ${c?H.itemExpanded:""}`,role:"listitem",onClick:F,children:[e.jsxs("div",{className:H.itemHeader,children:[e.jsxs("div",{className:H.quoteInfo,children:[e.jsxs("div",{className:H.clientNameRow,children:[e.jsxs("span",{className:H.clientName,children:[t.clientFirstName," ",t.clientLastName]}
2),o&&t.assignmentCount>0&&e.jsxs("span",{className:H.assignmentBadge,children:[t.assignmentCount,"Ã"]}),t.schedulingExcludedAt!=null&&e.jsx("span",{className:H.noSchedulingBadge,children:r==="fr"?"Sans planification":"No scheduling"})]}),e.jsxs("div",{className:H.metaInfo,children:[e.jsxs("span",{className:H.metaItem,children:[e.jsx(Ps,{size:12}),h("planning_signed")," ",t.signedAt?De(new Date(t.signedAt),"d MMM yyyy",{locale:fe}):"â"]}),e.jsxs("span",{className:H.quoteNumber,children:["#",t.quoteNumber]})]})]}),e.jsxs("div",{className:H.rightSide,children:[e.jsx("div",{className:H.expandBtn,children:c?e.jsx(jo,{size:18}):e.jsx(Do,{size:18})}),e.jsx("button",{ref:I,className:H.dragHandle,"aria-label":`${h("planning_drag_quote")} ${t.quoteNumber}`,onClick:de,children:e.jsx(pn,{size:18})})]}),e.jsx("button",{className:H.excludeSchedulingBtn,onClick:_,disabled:j.isPending,"aria-label":t.schedulingExcludedAt!=null?r==="fr"?"Remettre à planifier":"Move back to scheduling":r==="fr"?"Aucune planification requise":"No scheduling required",title:t.schedulingExcludedAt!=null?r==="fr"?"Remettre à planifier":"Move back to scheduling":r==="fr"?"Aucune planification requise":"No scheduling required",children:t.schedulingExcludedAt!=null?e.jsx(wa,{size:16}):e.jsx(Sa,{size:16})}),e.jsx("button",{className:H.cancelBtn,onClick:D,disabled:S.isPending,"aria-label":r==="fr"?"Annulé par le client":"Cancelled by client",title:r==="fr"?"Annulé par le client":"Cancelled by client",children:e.jsx(vo,{size:16})})]}),e.jsx("div",{className:`${H.expandedArea} ${c?H.expandedAreaOpen:""}`,children:e.jsx("div",{className:H.expandedContentWrapper,children:e.jsx("div",{className:H.expandedContent,children:v?e.jsxs("div",{className:H.innerCard,children:[e.jsx(ne,{style:{height:"1.25rem",width:"100%"}}),e.jsx(ne,{style:{height:"1.25rem",width:"80%"}})]}):y?f?e.jsxs("div",{className:H.innerCard,children:[f.lineItems.map(T=>e.jsxs("div",{className:H.lineItem,children:[e.jsxs("div",{className:H.lineItemMain,children:[e.jsx("span",{className:H.lineItemTitle,children:T.title}),T.description&&e.jsx("span",{className:H.lineItemDesc,children:T.description})]}),e.jsx("div",{className:H.lineItemTotals,children:d?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:H.lineItemPrice,children:k(T.totalPrice)}),e.jsxs("span",{className:H.lineItemQty,children:[T.quantity," ",T.unit||"u"," à ",k(T.unitPrice)]})]}):e.jsxs("span",{className:H.lineItemQty,children:[T.quantity," ",T.unit||"u"]})})]},T.id)),d&&e.jsxs("div",{className:H.subtotalRow,children:[e.jsx("span",{children:r==="en"?"Subtotal":"Sous-total"}),e.jsx("span",{children:k(f.totalAmount)})]}),W.length>0&&e.jsx("div",{className:H.extrasSection,children:W.map(T=>e.jsx(Xd,{extraId:T.id,canViewPrices:d,formatCurrency:k},T.id))})]}):null:e.jsx("div",{className:H.innerCard,children:e.jsxs("div",{className:H.accessDenied,children:[e.jsx(ss,{size:16}),e.jsx("span",{children:r==="en"?"Access denied to view quote details":"Accès refusé pour voir les détails du devis"})]})})})})})]})},eu=({route:t})=>{const{language:a}=ye(),[{isDragging:s},n,o]=hn(()=>({type:ht.ROUTE_ITEM,item:()=>({type:ht.ROUTE_ITEM,routeId:t.id,routeName:t.name,stopCount:t.stopCount}),collect:m=>({isDragging:m.isDragging()})}),[t]),i=je.useCallback(m=>{n(m)},[n]),p=je.useCallback(m=>{o(m)},[o]),c=t.clientNames.slice(0,3).join(", ")+(t.clientNames.length>3?` +${t.clientNames.length-3}`:"");return e.jsx("div",{ref:p,className:`${H.quoteItem} ${s?H.dragging:""}`,role:"listitem",children:e.jsxs("div",{className:H.itemHeader,children:[e.jsxs("div",{className:H.quoteInfo,children:[e.jsxs("div",{className:H.clientNameRow,children:[e.jsx("span",{className:H.clientName,children:t.name}),e.jsxs("span",{className:H.assignmentBadge,children:[t.stopCount," ",a==="en"?"stops":"arrêts"]})]}),e.jsxs("div",{className:H.metaInfo,children:[e.jsx("span",{className:H.metaItem,children:c}),e.jsx(wt,{variant:"outline",children:t.status})]})]}),e.jsx("div",{className:H.rightSide,children:e.jsx("button",{ref:i,className:H.dragHandle,"aria-label":"Drag route",children:e.jsx(pn,{size:18})})})]})})},fi=({className:t,onQuoteSelect:a,selectedQuoteId:s}
2)=>{const{data:n,isFetching:o,error:i}=cr(),{data:p,isFetching:c,error:m}=zc(),h=Ws(),{t:r,language:C}=ye(),[g,l]=je.useState("quotes"),[k,j]=je.useState("to_schedule"),[x,d]=je.useState(""),b=N=>N.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase(),y=je.useMemo(()=>{const N=n??[];if(!x)return N;const O=b(x);return N.filter(w=>{const B=`${w.clientFirstName} ${w.clientLastName}`;return b(B).includes(O)})},[n,x]),S=je.useMemo(()=>y.filter(N=>pa(N)),[y]),D=je.useMemo(()=>y.filter(N=>!pa(N)),[y]),_=k==="to_schedule"?S:D,f=p?.routes??[],v=je.useMemo(()=>{if(!x)return f;const N=b(x);return f.filter(O=>b(O.name).includes(N))},[f,x]),M=N=>N==="to_schedule"?C==="en"?"To schedule":"à planifier":C==="en"?"Already assigned":"Déjà attribué",W=()=>Array.from({length:5}).map((N,O)=>e.jsxs("div",{className:H.skeletonItem,children:[e.jsxs("div",{className:H.skeletonText,children:[e.jsx(ne,{style:{height:"1rem",width:"80%"}}),e.jsx(ne,{style:{height:"0.8rem",width:"50%"}})]}),e.jsx(ne,{style:{height:"1.5rem",width:"1.5rem"}})]},O));return e.jsxs("div",{className:`${H.container} ${t||""}`,children:[e.jsxs("div",{className:H.segmentSwitch,children:[e.jsx("button",{className:`${H.segmentBtn} ${g==="quotes"?H.segmentBtnActive:""}`,onClick:()=>l("quotes"),children:C==="en"?"Signed Quotes":"Devis signés"}),e.jsx("button",{className:`${H.segmentBtn} ${g==="routes"?H.segmentBtnActive:""}`,onClick:()=>l("routes"),children:"Routes"})]}),e.jsx("div",{className:H.searchContainer,children:e.jsxs("div",{className:H.searchInputWrapper,children:[e.jsx(yo,{size:16,className:H.searchIcon}),e.jsx("input",{type:"text",className:H.searchInput,placeholder:C==="en"?"Search...":"Rechercher...",value:x,onChange:N=>d(N.target.value)}),x&&e.jsx("button",{className:H.clearBtn,onClick:()=>d(""),"aria-label":"Clear search",children:e.jsx(qt,{size:14})})]})}),g==="quotes"&&e.jsx("div",{className:H.tabBar,role:"tablist",children:["to_schedule","already_assigned"].map(N=>{const O=N==="to_schedule"?S.length:D.length;return e.jsxs("button",{role:"tab","aria-selected":k===N,className:`${H.tabBtn} ${k===N?H.tabBtnActive:""}`,onClick:()=>j(N),children:[M(N),e.jsx("span",{className:`${H.tabCount} ${k===N?H.tabCountActive:""}`,children:O})]},N)})}),g==="quotes"?e.jsxs("div",{className:H.listContainer,children:[o&&W(),i&&e.jsxs("p",{className:H.error,children:[r("common_error"),": ",i.message]}),!o&&!i&&(_.length===0?e.jsxs("div",{className:H.emptyState,children:[e.jsx("p",{className:H.emptyMessage,children:r("planning_no_signed_quotes")}),e.jsx("small",{children:r("planning_quotes_will_appear")})]}):e.jsx("div",{className:H.list,role:"list",children:_.map(N=>e.jsx(Zd,{quote:N,onQuoteSelect:a,isSelected:s===N.id,isMobile:h,showAssignmentBadge:k==="already_assigned"},N.id))}))]}):e.jsxs("div",{className:H.listContainer,children:[c&&W(),m&&e.jsxs("p",{className:H.error,children:[r("common_error"),": ",m.message]}),!c&&!m&&(v.length===0?e.jsx("div",{className:H.emptyState,children:e.jsx("p",{className:H.emptyMessage,children:C==="en"?"No routes to plan":"Aucune route à planifier"})}):e.jsx("div",{className:H.list,role:"list",children:v.map(N=>e.jsx(eu,{route:N},N.id))}))]})]})},tu=t=>{const a=[];for(let s=0;s<t.length;s++){const n=t[s],o=[];for(let i=s+1;i<t.length;i++){const p=t[i],c=n.startDatetime.getTime(),m=n.endDatetime.getTime(),h=p.startDatetime.getTime(),r=p.endDatetime.getTime();c<r&&h<m&&o.push(p.id)}o.length>0&&a.push({eventId:n.id,conflictingEventIds:o})}return a},su=(t,a)=>{if(t.projectId&&a){const s=a.find(n=>n.id===t.projectId);if(s?.color)return s.color}return t.taskCategory&&{management:"var(--primary)",construction:"var(--accent)",electrical:"#fbbf24",plumbing:"#3b82f6",demolition:"#ef4444",cleanup:"#10b981",travel:"#8b5cf6"}[t.taskCategory]||"var(--primary)"},nu=(t,a)=>{const s=t.getHours(),n=t.getMinutes(),o=a.getHours(),i=a.getMinutes();return`${s.toString().padStart(2,"0")}:${n.toString().padStart(2,"0")} - ${o.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}`},au="_header_1wwgr_1",iu="_navigation_1wwgr_10",ou="_title_1wwgr_16",Sn={header:au,navigation:iu,title:ou},ru=({date:t,onDateChange:a,onClose:s,lang:n="fr"})=>{const o=n==="fr"?zt:Vs,i=()=>{a(wr(t))},p=()=>{a(Xa(t,1))};return e.jsxs("div",{className:Sn.header,children:[e.jsxs("div",{className:Sn.navigation,children:[e.jsx(L,{variant:"outline",size:"icon-sm",onClick:i,children:e.jsx(Na,{size:16})}),e.jsx("h3",{className:Sn.title,children:De(t,"eeee, d MMMM yyyy",{locale:o})}),e.jsx(L,{variant:"outline",size:"icon-sm",onClick:p,children:e.jsx(Ta,{size:16})})]}),e.jsx(L,{variant:"ghost",size:"icon-sm",onClick:s,children:e.jsx(qt,{size:20})})]})}
2,lu="_timeSlot_1az32_1",cu="_halfHour_1az32_19",du="_dropTarget_1az32_36",Nn={timeSlot:lu,halfHour:cu,dropTarget:du},uu=({hour:t,minute:a=0,isHalfHour:s=!1,onCreateEvent:n,onDropEvent:o})=>{const[{isOver:i,canDrop:p},c]=$s({accept:"EVENT",drop:C=>{o(C.id,t,a)},collect:C=>({isOver:C.isOver(),canDrop:C.canDrop()})}),m=u.useCallback(C=>{c(C)},[c]),h=()=>{n(t,a)},r=[Nn.timeSlot,s&&Nn.halfHour,i&&p&&Nn.dropTarget].filter(Boolean).join(" ");return e.jsx("div",{ref:m,className:r,onClick:h,title:`Cliquez pour créer une tâche à ${t.toString().padStart(2,"0")}:${a.toString().padStart(2,"0")}`})},pu="_dialogContent_1ktpx_1",mu="_scrollableContent_1ktpx_10",hu="_dialogTitle_1ktpx_16",gu="_dialogDescription_1ktpx_23",_u="_detailsGrid_1ktpx_30",fu="_detailItem_1ktpx_45",xu="_icon_1ktpx_53",yu="_section_1ktpx_60",ju="_sectionTitle_1ktpx_65",Du="_projectInfo_1ktpx_75",vu="_projectDetails_1ktpx_85",Cu="_projectName_1ktpx_91",ku="_clientInfo_1ktpx_96",bu="_clientIcon_1ktpx_104",wu="_attendeesList_1ktpx_108",Su="_attendee_1ktpx_108",Nu="_attendeeInfo_1ktpx_126",Tu="_attendeeName_1ktpx_131",Iu="_attendeeRole_1ktpx_136",Eu="_photoGrid_1ktpx_142",Pu="_photoCard_1ktpx_148",$u="_thumbnailWrapper_1ktpx_162",Mu="_thumbnail_1ktpx_162",Au="_photoBadge_1ktpx_177",Bu="_caption_1ktpx_185",Hu="_skeletonPhoto_1ktpx_194",Lu="_lightbox_1ktpx_211",Ou="_lightboxClose_1ktpx_226",Ru="_lightboxImg_1ktpx_244",Fu="_metadataGrid_1ktpx_251",Uu="_metadataItem_1ktpx_263",qu="_dialogFooter_1ktpx_269",zu="_dialogHeader_1ktpx_292",ee={dialogContent:pu,scrollableContent:mu,dialogTitle:hu,dialogDescription:gu,detailsGrid:_u,detailItem:fu,icon:xu,section:yu,sectionTitle:ju,projectInfo:Du,projectDetails:vu,projectName:Cu,clientInfo:ku,clientIcon:bu,attendeesList:wu,attendee:Su,attendeeInfo:Nu,attendeeName:Tu,attendeeRole:Iu,photoGrid:Eu,photoCard:Pu,thumbnailWrapper:$u,thumbnail:Mu,photoBadge:Au,caption:Bu,skeletonPhoto:Hu,lightbox:Lu,lightboxClose:Ou,lightboxImg:Ru,metadataGrid:Fu,metadataItem:Uu,dialogFooter:qu,dialogHeader:zu},Wu=t=>{const a=t.split(" ");return a.length===1?a[0].substring(0,2).toUpperCase():(a[0][0]+a[a.length-1][0]).toUpperCase()},Gu=t=>{if(!t)return"secondary";switch(t.toLowerCase()){case"completed":case"terminé":return"success";case"in_progress":case"en cours":return"default";case"cancelled":case"annulé":return"destructive";case"pending":case"en attente":return"warning";default:return"secondary"}},xi=({event:t,isOpen:a,onClose:s,onEdit:n,onDelete:o,onDuplicate:i})=>{const[p,c]=je.useState(null),{data:m,isLoading:h}=Ka({calendarEventId:t?.id});if(!t)return null;const r=m?.photos||[],C=()=>{n(t),s()},g=()=>{o(t.id),s()},l=()=>{i(t),s()},k=ce(t.startDatetime),j=ce(t.endDatetime),x=ce.duration(j.diff(k)),d=`${x.hours()}h ${x.minutes()}m`,b=t.clientFirstName&&t.clientLastName?`${t.clientFirstName} ${t.clientLastName}`:"N/A";return e.jsx(Qe,{open:a,onOpenChange:y=>!y&&s(),children:e.jsxs(Ke,{className:ee.dialogContent,children:[e.jsxs(lt,{className:ee.dialogHeader,children:[e.jsx(Je,{className:ee.dialogTitle,children:t.title}),t.description&&e.jsx($t,{className:ee.dialogDescription,children:t.description})]}),e.jsxs("div",{className:ee.scrollableContent,children:[e.jsxs("div",{className:ee.detailsGrid,children:[e.jsxs("div",{className:ee.detailItem,children:[e.jsx(Ps,{className:ee.icon}),e.jsx("span",{children:k.format("dddd, D MMMM YYYY")})]}),e.jsxs("div",{className:ee.detailItem,children:[e.jsx(hs,{className:ee.icon}),e.jsx("span",{children:`${k.format("HH:mm")} - ${j.format("HH:mm")} (${d})`})]}),t.location&&e.jsxs("div",{className:ee.detailItem,children:[e.jsx(An,{className:ee.icon}),e.jsx("span",{children:t.location})]})]}),t.projectName&&e.jsxs("div",{className:ee.section,children:[e.jsxs("h3",{className:ee.sectionTitle,children:[e.jsx(Co,{className:ee.icon}),"Projet"]}),e.jsxs("div",{className:ee.projectInfo,children:[e.jsxs("div",{className:ee.projectDetails,children:[e.jsx("span",{className:ee.projectName,children:t.projectName}),e.jsxs("div",{className:ee.clientInfo,children:[e.jsx(ko,{size:14,className:ee.clientIcon}),e.jsx("span",{children:b})]})]}),e.jsx(wt,{variant:Gu(t.projectStatus),children:t.projectStatus||"N/A"})]})]}),t.attendeeDetails&&t.attendeeDetails.length>0&&e.jsxs("div",{className:ee.section,children:[e.jsxs("h3",{className:ee.sectionTitle,children:[e.jsx(Ia,{className:ee.icon}),"Participants"]}),e.jsx("div",{className:ee.attendeesList,children:t.attendeeDetails.map(y=>e.jsxs("div",{className:ee.attendee,children:[e.jsxs(Tr,{children:[e.jsx(Ir,{src:y.avatarUrl||void 0,alt:y.displayName}),e.jsx(Er,{children:Wu(y.displayName)})]}),e.jsxs("div",{className:ee.attendeeInfo,children:[e.jsx("span",{className:ee.attendeeName,children:y.displayName}),e.jsx("span",{className:ee.attendeeRole,children:y.role})]})]},y.id))})]}),(h||r.length>0)&&e.jsxs("div",{className:ee.section,children:[e.jsxs("h3",{className:ee.sectionTitle,children:[e.jsx(nn,{className:ee.icon}),"Photos"]}),h?e.jsxs("div",{className:ee.photoGrid,children:[e.jsx("div",{className:ee.skeletonPhoto}),e.jsx("div",{className:ee.skeletonPhoto}),e.jsx("div",{className:ee.skeletonPhoto})]}):e.jsx("div",{className:ee.photoGrid,children:r.map(y=>e.jsxs("div",{className:ee.photoCard,onClick:()=>c(y.photoUrl),children:[e.jsxs("div",{className:ee.thumbnailWrapper,children:[e.jsx("img",{src:Pn(y.photoUrl,400),alt:y.caption||"Task photo",className:ee.thumbnail,loading:"lazy"}),e.jsx(wt,{variant:"secondary",className:ee.photoBadge,children:y.photoType})]}),y.caption&&e.jsx("div",{className:ee.caption,children:y.caption})]},y.id))})]}),e.jsxs("div",{className:ee.section,children:[e.jsxs("h3",{className:ee.sectionTitle,children:[e.jsx(Ea,{className:ee.icon}),"Métadonnées"]}),e.jsxs("div",{className:ee.metadataGrid,children:[t.taskCategory&&e.jsxs("div",{className:ee.metadataItem,children:[e.jsx(Pa,{className:ee.icon}),e.jsxs("span",{children:["Catégorie: ",e.jsx(wt,{variant:"secondary",children:t.taskCategory})]})]}),t.isWeatherDependent!==null&&e.jsxs("div",{className:ee.metadataItem,children:[e.jsx($a,{className:ee.icon}),e.jsxs("span",{children:["Météo-dépendant: ",t.isWeatherDependent?"Oui":"Non"]})]})]})]})]}),e.jsxs(Ct,{className:ee.dialogFooter,children:[e.jsxs(L,{variant:"outline",size:"sm",onClick:C,children:[e.jsx(Bn,{size:16}),"Modifier"]}),e.jsxs(L,{variant:"outline",size:"sm",onClick:l,children:[e.jsx(Hn,{size:16}),"Dupliquer"]}),e.jsxs(L,{variant:"destructive",size:"sm",onClick:g,children:[e.jsx(ps,{size:16}),"Supprimer"]})]}),p&&e.jsxs("div",{className:ee.lightbox,onClick:()=>c(null),children:[e.jsx("button",{className:ee.lightboxClose,onClick:y=>{y.stopPropagation(),c(null)},children:e.jsx(qt,{size:24})}),e.jsx("img",{src:p,alt:"Zoomed view",className:ee.lightboxImg})]})]})})},Vu="_eventBlock_8owy4_1",Yu="_dragging_8owy4_20",Qu="_hasConflicts_8owy4_24",Ku="_eventContent_8owy4_30",Ju="_eventTitle_8owy4_34",Xu="_eventTime_8owy4_42",Zu
2="_eventLocation_8owy4_48",ep="_resizeHandle_8owy4_57",tp="_tooltip_8owy4_71",sp="_tooltipContent_8owy4_76",np="_clickHint_8owy4_88",Bt={eventBlock:Vu,dragging:Yu,hasConflicts:Qu,eventContent:Ku,eventTitle:Ju,eventTime:Xu,eventLocation:Zu,resizeHandle:ep,tooltip:tp,tooltipContent:sp,clickHint:np},ap=({event:t,hasConflicts:a,onEventUpdate:s,onEventResize:n,onEventEdit:o,onEventDelete:i,onEventDuplicate:p,projects:c,style:m})=>{const h=u.useRef(null),r=u.useRef(null),[C,g]=u.useState(!1),[l,k]=u.useState(!1),j=u.useCallback(()=>{k(!0)},[]),x=u.useCallback(()=>{k(!1)},[]),[{isDragging:d},b,y]=hn(()=>({type:"EVENT",item:{id:t.id},collect:w=>({isDragging:w.isDragging()})}),[t.id]);u.useEffect(()=>{d?j():l&&x()},[d,l,j,x]);const[{isOver:S},D]=$s({accept:"EVENT",drop:()=>{},collect:w=>({isOver:w.isOver()})});u.useEffect(()=>{y(ol(),{captureDraggingState:!0})},[y]);const _=su(t,c),f=nu(t.startDatetime,t.endDatetime),v=w=>{r.current&&r.current.contains(w.target)||l||(w.preventDefault(),w.stopPropagation(),g(!0))},M=w=>{if(r.current&&r.current.contains(w.target)){w.preventDefault();return}},W=()=>{g(!1)},N=[Bt.eventBlock,a&&Bt.hasConflicts,d&&Bt.dragging].filter(Boolean).join(" "),O={...m,backgroundColor:`color-mix(in srgb, ${_} 80%, transparent)`,borderLeftColor:_,color:_,opacity:d?.5:1};return e.jsxs(e.Fragment,{children:[e.jsxs(bs,{children:[e.jsx(ws,{asChild:!0,children:e.jsxs("div",{ref:w=>{b(w),D(w),h.current=w},className:N,style:O,onMouseDown:M,onClick:v,children:[e.jsxs("div",{className:Bt.eventContent,children:[e.jsx("p",{className:Bt.eventTitle,children:t.title}),e.jsx("p",{className:Bt.eventTime,children:f}),t.location&&e.jsx("p",{className:Bt.eventLocation,children:t.location})]}),e.jsx("div",{ref:r,className:Bt.resizeHandle})]})}),e.jsx(Ss,{side:"right",className:Bt.tooltip,children:e.jsxs("div",{className:Bt.tooltipContent,children:[e.jsx("h4",{children:t.title}),e.jsxs("p",{children:[e.jsx("strong",{children:"Heure:"})," ",f]}),t.description&&e.jsxs("p",{children:[e.jsx("strong",{children:"Description:"})," ",t.description]}),t.location&&e.jsxs("p",{children:[e.jsx("strong",{children:"Lieu:"})," ",t.location]}),t.projectName&&e.jsxs("p",{children:[e.jsx("strong",{children:"Projet:"})," ",t.projectName]}),t.taskCategory&&e.jsxs("p",{children:[e.jsx("strong",{children:"Catégorie:"})," ",t.taskCategory]}),t.attendeeDetails&&t.attendeeDetails.length>0&&e.jsxs("p",{children:[e.jsx("strong",{children:"Participants:"})," ",t.attendeeDetails.map(w=>w.displayName).join(", ")]}),e.jsx("p",{className:Bt.clickHint,children:"Cliquez pour plus de détails"})]})})]}),e.jsx(xi,{event:t,isOpen:C,onClose:W,onEdit:o,onDelete:i,onDuplicate:p})]})},ip="_overlay_u3yao_1",op="_modal_u3yao_12",rp="_content_u3yao_24",lp="_timeColumn_u3yao_30",cp="_timeLabel_u3yao_37",dp="_toolbar_u3yao_50",up="_blockActions_u3yao_58",pp="_halfHourLabel_u3yao_63",mp="_scheduleArea_u3yao_70",hp="_blocksSection_u3yao_96",gp="_blockItem_u3yao_105",_p="_blockCompany_u3yao_115",fp="_blockClient_u3yao_121",xp="_blockTitle_u3yao_127",yp="_blockClientName_u3yao_131",jp="_blockNotes_u3yao_135",Dp="_deleteBlockBtn_u3yao_144",vp="_btnReserve_u3yao_155",Cp="_btnBlock_u3yao_161",kp="_formGroup_u3yao_167",Re={overlay:ip,modal:op,content:rp,timeColumn:lp,timeLabel:cp,toolbar:dp,blockActions:up,halfHourLabel:pp,scheduleArea:mp,blocksSection:hp,blockItem:gp,blockCompany:_p,blockClient:fp,blockTitle:xp,blockClientName:yp,blockNotes:jp,deleteBlockBtn:Dp,btnReserve:vp,btnBlock:Cp,formGroup:kp},bp=({date:t,events:a,isOpen:s,onClose:n,onDateChange:o,onEventUpdate:i,onEventCreate:p,onCreateTask:c,projects:m=[],lang:h="fr",timeSlotInterval:r=60,calendarBlocks:C=[],onCreateBlock:g,onDeleteBlock:l,selectedSpecialty:k})=>{const{data:j}=Yt(),[x,d]=u.useState(null),[b,y]=u.useState(De(t,"yyyy-MM-dd")),[S,D]=u.useState(""),[_,f]=u.useState(""),v=u.useMemo(()=>{if(j?.enabled&&j.startTime&&j.endTime){const E=parseInt(j.startTime.split(":")[0],10),$=parseInt(j.endTime.split(":")[0],10);if(!isNaN(E)&&!isNaN($)&&E<$){const R=$-E+1;return Array.from({length:R},(Q,se)=>se+E)}}return Array.from({length:24},(E,$)=>$)},[j]),M=v[0],W=u.useMemo(()=>tu(a),[a]),N=u.useMemo(()=>{const E=new Set;return W.forEach($=>{E.add($.eventId),$.conflictingEventIds.forEach(R=>E.add(R))}),E},[W]);if(!s)return null;const O=E=>{const $=E.startDatetime.getHours(),R=E.startDatetime.getMinutes(),Q=E.endDatetime.getHours(),se=E.endDatetime.getMinutes(),ae=r===30?120:60,Z=($-M+R/60)*ae,ve=(Q+se/60-($+R/60))*ae;return{top:`${Z}px`,height:`${Math.max(ve,20)}px`}},w=(E,$)=>{c?.(E,$)},B=async(E,$,R)=>{if(!i)return;const Q=a.find(ue=>ue.id===E);if(!Q)return;const se=Q.endDatetime.getTime()-Q.startDatetime.getTime(),ae=new Date(t);ae.setHours($,R,0,0);const Z=new Date(ae.getTime()+se),ve={...Q,startDatetime:ae,endDatetime:Z};await i(ve)},I=async(E,$,R,Q)=>{if(!i)return;const se=a.find(ue=>ue.id===E);if(!se)return;const ae=new Date(t);ae.setHours($,R,0,0);const Z=new Date(ae);Z.setMinutes(Z.getMinutes()+Q);const ve={...se,startDatetime:ae,endDatetime:Z};await i(ve)},F=E=>
2{},de=E=>{},fe=E=>{},T=()=>{if(x&&g&&k){const E=new Date(b);E.setHours(23,59,59,999);const $=new Date(t);$.setHours(0,0,0,0),g({blockType:x,startDate:$,endDate:E,specialty:k,clientId:_?parseInt(_,10):void 0,notes:S||void 0}),d(null),D(""),f("")}},Y=(()=>{const E=[];for(const $ of v)r===30?(E.push({hour:$,minute:0,isHalfHour:!1}),E.push({hour:$,minute:30,isHalfHour:!0})):E.push({hour:$,minute:0,isHalfHour:!1});return E})();return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:Re.overlay,onClick:n,children:e.jsxs("div",{className:Re.modal,onClick:E=>E.stopPropagation(),children:[e.jsx(ru,{date:t,onDateChange:o||(()=>{}),onClose:n,lang:h}),C.length>0&&e.jsx("div",{className:Re.blocksSection,children:C.map(E=>e.jsxs("div",{className:`${Re.blockItem} ${E.blockType==="company_block"?Re.blockCompany:Re.blockClient}`,children:[E.blockType==="company_block"?e.jsx(Ma,{size:14}):e.jsx(Aa,{size:14}),e.jsx("span",{className:Re.blockTitle,children:E.blockType==="company_block"?h==="fr"?"Bloqué":"Blocked":h==="fr"?"Réservé":"Reserved"}),(E.clientFirstName||E.clientLastName)&&e.jsxs("span",{className:Re.blockClientName,children:["- ",E.clientFirstName," ",E.clientLastName]}),E.notes&&e.jsxs("span",{className:Re.blockNotes,children:[": ",E.notes]}),l&&e.jsx(L,{variant:"ghost",size:"icon-sm",onClick:()=>l(E.id),className:Re.deleteBlockBtn,children:e.jsx(ps,{size:14})})]},E.id))}),e.jsxs("div",{className:Re.toolbar,children:[g&&k&&e.jsxs("div",{className:Re.blockActions,children:[e.jsx(L,{variant:"outline",size:"sm",onClick:()=>d("client_reservation"),className:Re.btnReserve,children:h==="fr"?"Réserver pour un client":"Reserve for a client"}),e.jsx(L,{variant:"outline",size:"sm",onClick:()=>d("company_block"),className:Re.btnBlock,children:h==="fr"?"Bloquer la journée":"Block this day"})]}),c&&e.jsxs(L,{variant:"outline",size:"sm",onClick:()=>c(),children:[e.jsx(Ln,{size:16}),h==="fr"?"Ajouter une tâche interne":"Add internal task"]})]}),e.jsxs("div",{className:Re.content,children:[e.jsx("div",{className:Re.timeColumn,children:v.map(E=>e.jsxs("div",{className:Re.timeLabel,children:[De(new Date(0,0,0,E),"HH:mm"),r===30&&e.jsx("div",{className:Re.halfHourLabel,children:De(new Date(0,0,0,E,30),"HH:mm")})]},E))}),e.jsxs("div",{className:Re.scheduleArea,children:[Y.map((E,$)=>e.jsx(uu,{hour:E.hour,minute:E.minute,isHalfHour:E.isHalfHour,onCreateEvent:w,onDropEvent:B},`${E.hour}-${E.minute}`)),a.map(E=>e.jsx(ap,{event:E,hasConflicts:N.has(E.id),onEventUpdate:i||(()=>{}),onEventResize:I,onEventEdit:F,onEventDelete:de,onEventDuplicate:fe,projects:m,style:O(E)},E.id))]})]})]})}),e.jsx(Qe,{open:!!x,onOpenChange:E=>!E&&d(null),children:e.jsxs(Ke,{children:[e.jsxs(lt,{children:[e.jsx(Je,{children:x==="company_block"?h==="fr"?"Bloquer la journée":"Block day":h==="fr"?"Réserver la journée":"Reserve day"}),e.jsx($t,{children:x==="company_block"?h==="fr"?"Bloquer la disponibilité pour l'entreprise.":"Block availability for the company.":h==="fr"?"Réserver la disponibilité pour un client.":"Reserve availability for a client."})]}),e.jsxs("div",{className:Re.formGroup,children:[e.jsx("label",{children:h==="fr"?"Date de fin":"End Date"}),e.jsx(Pe,{type:"date",value:b,onChange:E=>y(E.target.value)})]}),x==="client_reservation"&&e.jsxs("div",{className:Re.formGroup,children:[e.jsx("label",{children:h==="fr"?"ID Client (optionnel)":"Client ID (optional)"}),e.jsx(Pe,{type:"number",value:_,onChange:E=>f(E.target.value)})]}),e.jsxs("div",{className:Re.formGroup,children:[e.jsx("label",{children:h==="fr"?"Notes (optionnel)":"Notes (optional)"}),e.jsx(Pe,{value:S,onChange:E=>D(E.target.value)})]}),e.jsxs(Ct,{children:[e.jsx(L,{variant:"secondary",onClick:()=>d(null),children:h==="fr"?"Annuler":"Cancel"}),e.jsx(L,{onClick:T,children:h==="fr"?"Confirmer":"Confirm"})]})]})})]})},ya=t=>{const a=new Date(t.startDate),s=t.endDate?new Date(t.endDate):new Date(t.startDate);let n=new Date(a),o=new Date(s);if(t.isHalfDay){const i=t.halfDayPeriod?.toUpperCase();i==="MORNING"||i==="AM"?(n=ge(n),o=dn(un(o,12),0)):i==="AFTERNOON"||i==="PM"?(n=dn(un(n,12),0),o=es(o)):(n=ge(n),o=es(o))}else t.allDay&&(n=ge(n),o=es(o));return{start:n,end:o}},wp=(t,a,s,n)=>ha(t,n)&&ha(s,a),Sp=(t,a,s)=>{const n=a.filter(i=>{const p=t.specialty||null,c=i.specialty||null;return p===c}),o=ya(t);for(const i of n){const p=ya(i);if(wp(o.start,o.end,p.start,p.end))return{hasConflict:!0,conflictingAssignment:i}}return{hasConflict:!1}},Np="_dialogContent_mxuyp_1",Tp="_form_mxuyp_5",Ip="_durationButtons_mxuyp_11",Ep="_dateGrid_mxuyp_18",Pp="_dateTimeGrid_mxuyp_24",$p="_allDayContainer_mxuyp_30",Mp="_halfDayContainer_mxuyp_39",Ap="_checkboxItem_mxuyp_45",Bp="_halfDaySelect_mxuyp_54",Hp="_pinnedContainer_mxuyp_59",Lp="_pinnedLabel_mxuyp_69",Op="_pinnedDescription_mxuyp_75",Rp="_noSpecialtiesWarning_mxuyp_81",Fp="_warningIcon_mxuyp_92",Up="_warningContent_mxuyp_97",qp="_loaderIcon_mxuyp_111",zp="_submitButton_mxuyp_117",Ge={dialogContent:Np,form:Tp,durationButtons:Ip,dateGrid:Ep,dateTimeGrid:Pp,allDayContainer:$p,halfDayContainer:Mp,checkboxItem:Ap,halfDaySelect:Bp,pinnedContainer:Hp,pinnedLabel:Lp,pinnedDescription:Op,noSpecialtiesWarning:Rp,warningIcon:Fp,warningContent:Up,loaderIcon:qp,submitButton:zp},Wp=({isOpen:t,onClose:a,initialDate:s,className:n,preselectedClientId:o,quoteId:i,quoteTitle:p,quoteLineItemCount:c,onSuccess:m,defaultSpecialty:h,existingAssignments:r,onOpenSpecialtyManager:C})=>{const{data:g,isFetching:l}=Ks(),{data:k,isFetching:j}=Pr({limit:9999}),{data:x,isFetching:d}=_s(),{registerChange:b}=Qt(),[y,S]=u.useState(!1),[D,_]=u.useState(null),{t:f,language:v}=ye(),M=x&&!("error"in x)?x.specialties||[]:[],W=u.useMemo(()=>Ee({clientId:X().min(1,f("assignment_error_select_client")),allDay:$e(),startDate:X().min(1,f("assignment_error_start_date")),startTime:X().optional(),endDate:X().min(1,f("assignment_error_end_date")),endTime:X().optional(),duration:X().optional(),isHalfDay:$e(),halfDayPeriod:Ye(["morning","afternoon"]).nullable(),specialty:X().min(1,f("assignment_error_select_specialty")),assignedUserId:X().optional().nullable(),isPinned:$e()}).refine(I=>I.isHalfDay?!!I.halfDayPeriod:!0,{message:f("assignment_error_select_period"),path:["halfDayPeriod"]}
2).refine(I=>{if(I.allDay)return ce(I.endDate).isSameOrAfter(I.startDate);{const F=ce(`${I.startDate} ${I.startTime}`);return ce(`${I.endDate} ${I.endTime}`).isAfter(F)}},{message:f("assignment_error_end_after_start"),path:["endDate"]}),[f]),N=Ys({schema:W,defaultValues:{clientId:"",allDay:!0,startDate:"",startTime:"08:00",endDate:"",endTime:"15:00",duration:"420",isHalfDay:!1,halfDayPeriod:null,specialty:"",assignedUserId:null,isPinned:!1}});u.useEffect(()=>{if(!t)return;_(null);const I=ce(s),F=ce(s);N.setValues({clientId:o?String(o):"",allDay:!0,startDate:I.format("YYYY-MM-DD"),startTime:"08:00",endDate:F.format("YYYY-MM-DD"),endTime:"15:00",duration:"420",isHalfDay:!1,halfDayPeriod:null,specialty:h||"",assignedUserId:null,isPinned:!1})},[t,s.getTime(),o,h]);const O=I=>{const F=parseInt(I,10),fe=ce(`${N.values.startDate} ${N.values.startTime}`).clone().add(F,"minutes");N.setValues(T=>({...T,duration:I,endDate:fe.format("YYYY-MM-DD"),endTime:fe.format("HH:mm")}))},w=I=>{_(I);const F=ce(N.values.startDate);let de=F.clone();if(N.values.allDay){switch(I){case"1d":de=F.clone();break;case"2d":de=F.clone().add(1,"day");break;case"1w":de=F.clone().add(6,"days");break}N.setValues(fe=>({...fe,endDate:de.format("YYYY-MM-DD")}))}else switch(I){case"1d":O("420");break;case"2d":O("840");break;case"1w":O("2520");break}},B=I=>{S(!0);const F=k?.clients.find(Y=>Y.id===parseInt(I.clientId,10)),de=F?`${F.firstName} ${F.lastName}`:f("assignment_client_label"),fe=p?`"${p}"`:de;let T,A;if(I.allDay?(T=ce(I.startDate).hour(8).minute(0).second(0).toDate(),A=ce(I.endDate).hour(15).minute(0).second(0).toDate()):(T=ce(`${I.startDate} ${I.startTime}`).toDate(),A=ce(`${I.endDate} ${I.endTime}`).toDate()),r){const Y={startDate:T,endDate:A,specialty:I.specialty||null,allDay:I.allDay,isHalfDay:I.isHalfDay,halfDayPeriod:I.halfDayPeriod},E=r.map(R=>({id:R.id,startDate:new Date(R.startDate),endDate:R.endDate?new Date(R.endDate):null,specialty:R.specialty,allDay:R.allDay,isHalfDay:R.isHalfDay,halfDayPeriod:R.halfDayPeriod}));if(Sp(Y,E).hasConflict){q.error(v==="fr"?"Un client est déjà assigné à ce créneau horaire pour ce corps de métier.":"A client is already assigned to this time slot for this trade."),S(!1);return}}b({type:"new-assignment",payload:{clientId:parseInt(I.clientId,10),startDate:T,endDate:A,isHalfDay:I.isHalfDay,halfDayPeriod:I.halfDayPeriod,specialty:I.specialty||void 0,assignedUserId:I.assignedUserId&&I.assignedUserId!=="__empty"?parseInt(I.assignedUserId,10):null,allDay:I.allDay,isPinned:I.isPinned,quoteId:i||void 0,quoteTitle:p||void 0,quoteLineItemCount:c,firstName:F?.firstName||"",lastName:F?.lastName||"",email:F?.email||""},description:f("assignment_create_description",{name:fe,date:ce(T).format("DD/MM/YYYY")})+(I.allDay?"":` à ${ce(T).format("HH:mm")}`)}),S(!1),a(),m?.()};return e.jsx(Qe,{open:t,onOpenChange:I=>!I&&a(),children:e.jsxs(Ke,{className:`${Ge.dialogContent} ${n||""}`,children:[e.jsxs(lt,{children:[e.jsx(Je,{children:f("assignment_modal_title")}),e.jsx($t,{children:f("assignment_modal_description")})]}),e.jsx(Qs,{...N,children:e.jsxs("form",{onSubmit:N.handleSubmit(B),className:Ge.form,id:"quick-assignment-form",children:[e.jsxs(oe,{name:"clientId",children:[e.jsx(pe,{children:f("assignment_client_label")}),e.jsxs(nt,{value:N.values.clientId,onValueChange:I=>N.setValues(F=>({...F,clientId:I})),disabled:j,children:[e.jsx(re,{children:e.jsx(at,{children:e.jsx(it,{placeholder:f("assignment_select_client")})})}),e.jsx(ot,{children:k?.clients.map(I=>e.jsxs(J,{value:String(I.id),children:[I.firstName," ",I.lastName]},I.id))})]}),e.jsx(_e,{})]}),e.jsxs(oe,{name:"assignedUserId",children:[e.jsx(pe,{children:v==="fr"?"Employé assigné":"Assigned employee"}),e.jsxs(nt,{value:N.values.assignedUserId||"__empty",onValueChange:I=>N.setValues(F=>({...F,assignedUserId:I==="__empty"?null:I})),disabled:l,children:[e.jsx(re,{children:e.jsx(at,{children:e.jsx(it,{placeholder:v==="fr"?"Sélectionner un employé":"Select employee"})})}),e.jsxs(ot,{children:[e.jsx(J,{value:"__empty",children:v==="fr"?"Non assigné":"Unassigned"}),g?.map(I=>e.jsx(J,{value:String(I.id),children:I.displayName},I.id))]})]}),e.jsx(_e,{})]}),e.jsx("div",{className:Ge.allDayContainer,children:e.jsxs(oe,{name:"allDay",className:Ge.checkboxItem,children:[e.jsx(re,{children:e.jsx(St,{id:"allDay",checked:N.values.allDay,onCheckedChange:I=>{N.setValues(F=>({...F,allDay:I===!0}))}})}),e.jsx(pe,{htmlFor:"allDay",children:f("assignment_all_day")})]})}),e.jsxs("div",{className:Ge.durationButtons,children:[e.jsx(L,{type:"button",variant:D==="1d"?"default":"outline",size:"sm",onClick:()=>w("1d"),children:f("assignment_1_day")}),e.jsx(L,{type:"button",variant:D==="2d"?"default":"outline",size:"sm",onClick:()=>w("2d"),children:f("assignment_2_days")}),e.jsx(L,{type:"button",variant:D==="1w"?"default":"outline",size:"sm",onClick:()=>w("1w"),children:f("assignment_1_week")})]}),N.values.allDay?e.jsxs("div",{className:Ge.dateGrid,children:[e.jsxs(oe,{name:"startDate",children:[e.jsx(pe,{children:f("assignment_start_date")}),e.jsx(re,{children:e.jsx(Pe,{type:"date",value:N.values.startDate,onChange:I=>{_(null),N.setValues(F=>({...F,startDate:I.target.value}))}})}),e.jsx(_e,{})]}),e.jsxs(oe,{name:"endDate",children:[e.jsx(pe,{children:f("assignment_end_date")}),e.jsx(re,{children:e.jsx(Pe,{type:"date",value:N.values.endDate,onChange:I=>{_(null),N.setValues(F=>({...F,endDate:I.target.value}))}})}),e.jsx(_e,{})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:Ge.dateTimeGrid,children:[e.jsxs(oe,{name:"startDate",children:[e.jsx(pe,{children:f("assignment_start_date")}),e.jsx(re,{children:e.jsx(Pe,{type:"date",value:N.values.startDate,onChange:I=>{_(null),N.setValues(F=>({...F,startDate:I.target.value}))}})}),e.jsx(_e,{})]}),e.jsxs(oe,{name:"startTime",children:[e.jsx(pe,{children:f("assignment_start_time")}
2),e.jsx(re,{children:e.jsx(Pe,{type:"time",value:N.values.startTime,onChange:I=>N.setValues(F=>({...F,startTime:I.target.value}))})}),e.jsx(_e,{})]})]}),e.jsxs(oe,{name:"duration",children:[e.jsx(pe,{children:f("assignment_duration")}),e.jsxs(nt,{value:N.values.duration,onValueChange:O,children:[e.jsx(re,{children:e.jsx(at,{children:e.jsx(it,{})})}),e.jsxs(ot,{children:[e.jsx(J,{value:"30",children:f("assignment_30_min")}),e.jsx(J,{value:"60",children:f("assignment_1_hour")}),e.jsx(J,{value:"90",children:f("assignment_1h30")}),e.jsx(J,{value:"120",children:f("assignment_2_hours")}),e.jsx(J,{value:"180",children:f("assignment_3_hours")}),e.jsx(J,{value:"240",children:f("assignment_4_hours")}),e.jsx(J,{value:"420",children:f("assignment_7_hours")}),e.jsx(J,{value:"480",children:f("assignment_8_hours")})]})]}),e.jsx(_e,{})]}),e.jsxs("div",{className:Ge.dateTimeGrid,children:[e.jsxs(oe,{name:"endDate",children:[e.jsx(pe,{children:f("assignment_end_date")}),e.jsx(re,{children:e.jsx(Pe,{type:"date",value:N.values.endDate,onChange:I=>{_(null),N.setValues(F=>({...F,endDate:I.target.value}))}})}),e.jsx(_e,{})]}),e.jsxs(oe,{name:"endTime",children:[e.jsx(pe,{children:f("assignment_end_time")}),e.jsx(re,{children:e.jsx(Pe,{type:"time",value:N.values.endTime,onChange:I=>N.setValues(F=>({...F,endTime:I.target.value}))})}),e.jsx(_e,{})]})]})]}),N.values.allDay&&e.jsxs("div",{className:Ge.halfDayContainer,children:[e.jsxs(oe,{name:"isHalfDay",className:Ge.checkboxItem,children:[e.jsx(re,{children:e.jsx(St,{id:"isHalfDay",checked:N.values.isHalfDay,onCheckedChange:I=>{N.setValues(F=>({...F,isHalfDay:I===!0,halfDayPeriod:I===!0?F.halfDayPeriod:null}))}})}),e.jsx(pe,{htmlFor:"isHalfDay",children:f("assignment_half_day")})]}),N.values.isHalfDay&&e.jsxs(oe,{name:"halfDayPeriod",className:Ge.halfDaySelect,children:[e.jsxs(nt,{value:N.values.halfDayPeriod??"",onValueChange:I=>N.setValues(F=>({...F,halfDayPeriod:I==="morning"||I==="afternoon"?I:null})),children:[e.jsx(re,{children:e.jsx(at,{children:e.jsx(it,{placeholder:f("assignment_period")})})}),e.jsxs(ot,{children:[e.jsx(J,{value:"morning",children:f("assignment_morning")}),e.jsx(J,{value:"afternoon",children:f("assignment_afternoon")})]})]}),e.jsx(_e,{})]})]}),M.length===0?e.jsxs("div",{className:Ge.noSpecialtiesWarning,children:[e.jsx(Mn,{className:Ge.warningIcon,size:20}),e.jsxs("div",{className:Ge.warningContent,children:[e.jsx("p",{children:f("assignment_no_specialties_warning")}),e.jsx(L,{type:"button",variant:"outline",size:"sm",onClick:()=>{a(),C?.()},children:f("assignment_configure_specialties")})]})]}):e.jsxs(oe,{name:"specialty",children:[e.jsx(pe,{children:f("assignment_specialty")}),e.jsxs(nt,{value:N.values.specialty||"__empty",onValueChange:I=>N.setValues(F=>({...F,specialty:I==="__empty"?"":I})),disabled:d,children:[e.jsx(re,{children:e.jsx(at,{children:e.jsx(it,{placeholder:f("assignment_select_specialty")})})}),e.jsxs(ot,{children:[e.jsx(J,{value:"__empty",children:f("assignment_no_specialty")}),M.map(I=>e.jsx(J,{value:I,children:I},I))]})]}),e.jsx(_e,{})]}),e.jsx("div",{className:Ge.pinnedContainer,children:e.jsxs(oe,{name:"isPinned",className:Ge.checkboxItem,children:[e.jsx(re,{children:e.jsx(St,{id:"isPinned",checked:N.values.isPinned,onCheckedChange:I=>{N.setValues(F=>({...F,isPinned:I===!0}))}})}),e.jsxs("div",{className:Ge.pinnedLabel,children:[e.jsx(pe,{htmlFor:"isPinned",children:f("assignment_do_not_move")}),e.jsx("span",{className:Ge.pinnedDescription,children:f("assignment_do_not_move_description")})]})]})})]})}),e.jsxs(Ct,{children:[e.jsx(L,{variant:"outline",onClick:a,disabled:y,children:f("assignment_cancel")}),e.jsx(L,{type:"submit",form:"quick-assignment-form",disabled:!N.values.clientId||y||M.length===0,className:Ge.submitButton,children:y?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:Ge.loaderIcon}),f("assignment_creating")]}):f("assignment_create")})]})]})})},Os="07:00",Rs="17:00",yi=600,zs="600",ji=t=>Ee({taskTitle:X().min(1,t("task_error_title_required")),taskDescription:X().optional(),taskLocation:X().optional(),taskPriority:Ye(["low","medium","high"]).optional(),taskStatus:Ye(["pending","in_progress","completed"]).optional(),allDay:$e(),startDate:X().min(1,t("assignment_error_start_date")),startTime:X().optional(),endDate:X().min(1,t("assignment_error_end_date")),endTime:X().optional(),duration:X().optional(),isHalfDay:$e(),halfDayPeriod:Ye(["morning","afternoon"]).nullable(),assignedUserId:Me().nullable().optional()}).refine(a=>a.isHalfDay?!!a.halfDayPeriod:!0,{message:t("assignment_error_select_period"),path:["halfDayPeriod"]}
2).refine(a=>{if(a.allDay)return ce(a.endDate).isSameOrAfter(a.startDate);{const s=ce(`${a.startDate} ${a.startTime}`);return ce(`${a.endDate} ${a.endTime}`).isAfter(s)}},{message:t("assignment_error_end_after_start"),path:["endDate"]}),Gp="_dialogContent_kgx0q_1",Vp="_form_kgx0q_5",Yp="_row_kgx0q_11",Qp="_flex1_kgx0q_16",Kp="_specialtyBadge_kgx0q_20",Jp="_durationButtons_kgx0q_31",Xp="_dateGrid_kgx0q_38",Zp="_dateTimeGrid_kgx0q_44",em="_allDayContainer_kgx0q_50",tm="_halfDayContainer_kgx0q_59",sm="_checkboxItem_kgx0q_65",nm="_halfDaySelect_kgx0q_74",am="_loaderIcon_kgx0q_81",im="_submitButton_kgx0q_87",om="_priorityItem_kgx0q_97",rm="_priorityDot_kgx0q_103",lm="_priorityLow_kgx0q_109",cm="_priorityMedium_kgx0q_113",dm="_priorityHigh_kgx0q_117",um="_photoSection_kgx0q_130",pm="_photoGrid_kgx0q_135",mm="_photoCard_kgx0q_142",hm="_photoThumbnail_kgx0q_152",gm="_photoRemoveBtn_kgx0q_159",_m="_photoControls_kgx0q_178",fm="_uploadLabel_kgx0q_197",ke={dialogContent:Gp,form:Vp,row:Yp,flex1:Qp,specialtyBadge:Kp,durationButtons:Jp,dateGrid:Xp,dateTimeGrid:Zp,allDayContainer:em,halfDayContainer:tm,checkboxItem:sm,halfDaySelect:nm,loaderIcon:am,submitButton:im,priorityItem:om,priorityDot:rm,priorityLow:lm,priorityMedium:cm,priorityHigh:dm,photoSection:um,photoGrid:pm,photoCard:mm,photoThumbnail:hm,photoRemoveBtn:gm,photoControls:_m,uploadLabel:fm},Di=({form:t,onSubmit:a,formId:s,photos:n,onPhotosChange:o})=>{const{t:i}=ye(),[p,c]=u.useState(!1),m=t.values,h=t.setValues,r=g=>{const l=parseInt(g,10),j=ce(`${m.startDate} ${m.startTime}`).clone().add(l,"minutes");h(x=>({...x,duration:g,endDate:j.format("YYYY-MM-DD"),endTime:j.format("HH:mm")}))},C=g=>{const l=ce(m.startDate);let k=l.clone();if(m.allDay){switch(g){case"1d":k=l.clone();break;case"2d":k=l.clone().add(1,"day");break;case"1w":k=l.clone().add(6,"days");break}h(j=>({...j,endDate:k.format("YYYY-MM-DD")}))}else switch(g){case"1d":r(zs);break;case"2d":r("1200");break;case"1w":r("3000");break}};return e.jsxs("form",{onSubmit:t.handleSubmit(a),className:ke.form,id:s,children:[e.jsxs(oe,{name:"taskTitle",children:[e.jsx(pe,{children:i("task_title_label")}),e.jsx(re,{children:e.jsx(Pe,{placeholder:i("task_title_placeholder"),value:m.taskTitle,onChange:g=>h(l=>({...l,taskTitle:g.target.value}))})}),e.jsx(_e,{})]}),e.jsxs("div",{className:ke.row,children:[e.jsxs(oe,{name:"taskPriority",className:ke.flex1,children:[e.jsx(pe,{children:i("task_priority")}),e.jsxs(nt,{value:m.taskPriority,onValueChange:g=>h(l=>({...l,taskPriority:g})),children:[e.jsx(re,{children:e.jsx(at,{children:e.jsx(it,{})})}),e.jsxs(ot,{children:[e.jsx(J,{value:"low",children:e.jsxs("div",{className:ke.priorityItem,children:[e.jsx("span",{className:`${ke.priorityDot} ${ke.priorityLow}`}),i("task_priority_low")]})}),e.jsx(J,{value:"medium",children:e.jsxs("div",{className:ke.priorityItem,children:[e.jsx("span",{className:`${ke.priorityDot} ${ke.priorityMedium}`}),i("task_priority_medium")]})}),e.jsx(J,{value:"high",children:e.jsxs("div",{className:ke.priorityItem,children:[e.jsx("span",{className:`${ke.priorityDot} ${ke.priorityHigh}`}),i("task_priority_high")]})})]})]}),e.jsx(_e,{})]}),e.jsxs(oe,{name:"taskStatus",className:ke.flex1,children:[e.jsx(pe,{children:i("task_status")}),e.jsxs(nt,{value:m.taskStatus,onValueChange:g=>h(l=>({...l,taskStatus:g})),children:[e.jsx(re,{children:e.jsx(at,{children:e.jsx(it,{})})}),e.jsxs(ot,{children:[e.jsx(J,{value:"pending",children:i("task_status_pending")}),e.jsx(J,{value:"in_progress",children:i("task_status_in_progress")}),e.jsx(J,{value:"completed",children:i("task_status_completed")})]})]}),e.jsx(_e,{})]})]}),e.jsxs(oe,{name:"taskDescription",children:[e.jsx(re,{children:e.jsx(Ar,{label:i("task_description_optional"),value:m.taskDescription||"",onChange:g=>h(l=>({...l,taskDescription:g})),placeholder:i("task_description_placeholder"),rows:3})}),e.jsx(_e,{})]}),e.jsxs(oe,{name:"taskLocation",children:[e.jsx(pe,{children:i("task_location_optional")}),e.jsx(re,{children:e.jsx(Pe,{placeholder:i("task_location_placeholder"),value:m.taskLocation||"",onChange:g=>h(l=>({...l,taskLocation:g.target.value}))})}),e.jsx(_e,{})]}),e.jsx("div",{className:ke.allDayContainer,children:e.jsxs(oe,{name:"allDay",className:ke.checkboxItem,children:[e.jsx(re,{children:e.jsx(St,{id:"allDay",checked:m.allDay,onCheckedChange:g=>{h(l=>({...l,allDay:g===!0}))}})}),e.jsx(pe,{htmlFor:"allDay",children:i("assignment_all_day")})]})}),e.jsxs("div",{className:ke.durationButtons,children:[e.jsx(L,{type:"button",variant:"outline",size:"sm",onClick:()=>C("1d"),children:i("assignment_1_day")}),e.jsx(L,{type:"button",variant:"outline",size:"sm",onClick:()=>C("2d"),children:i("assignment_2_days")}),e.jsx(L,{type:"button",variant:"outline",size:"sm",onClick:()=>C("1w"),children:i("assignment_1_week")})]}),m.allDay?e.jsxs("div",{className:ke.dateGrid,children:[e.jsxs(oe,{name:"startDate",children:[e.jsx(pe,{children:i("assignment_start_date")}),e.jsx(re,{children:e.jsx(Pe,{type:"date",value:m.startDate,onChange:g=>h(l=>({...l,startDate:g.target.value}))})}),e.jsx(_e,{})]}),e.jsxs(oe,{name:"endDate",children:[e.jsx(pe,{children:i("assignment_end_date")}),e.jsx(re,{children:e.jsx(Pe,{type:"date",value:m.endDate,onChange:g=>h(l=>({...l,endDate:g.target.value}))})}),e.jsx(_e,{})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:ke.dateTimeGrid,children:[e.jsxs(oe,{name:"startDate",children:[e.jsx(pe,{children:i("assignment_start_date")}),e.jsx(re,{children:e.jsx(Pe,{type:"date",value:m.startDate,onChange:g=>h(l=>({...l,startDate:g.target.value}))})}),e.jsx(_e,{})]}),e.jsxs(oe,{name:"startTime",children:[e.jsx(pe,{children:i("assignment_start_time")}
2),e.jsx(re,{children:e.jsx(Pe,{type:"time",value:m.startTime||"",onChange:g=>h(l=>({...l,startTime:g.target.value}))})}),e.jsx(_e,{})]})]}),e.jsxs(oe,{name:"duration",children:[e.jsx(pe,{children:i("assignment_duration")}),e.jsxs(nt,{value:m.duration||"",onValueChange:r,children:[e.jsx(re,{children:e.jsx(at,{children:e.jsx(it,{})})}),e.jsxs(ot,{children:[e.jsx(J,{value:"30",children:i("assignment_30_min")}),e.jsx(J,{value:"60",children:i("assignment_1_hour")}),e.jsx(J,{value:"90",children:i("assignment_1h30")}),e.jsx(J,{value:"120",children:i("assignment_2_hours")}),e.jsx(J,{value:"180",children:i("assignment_3_hours")}),e.jsx(J,{value:"240",children:i("assignment_4_hours")}),e.jsx(J,{value:"420",children:i("assignment_7_hours")}),e.jsx(J,{value:"480",children:i("assignment_8_hours")})]})]}),e.jsx(_e,{})]}),e.jsxs("div",{className:ke.dateTimeGrid,children:[e.jsxs(oe,{name:"endDate",children:[e.jsx(pe,{children:i("assignment_end_date")}),e.jsx(re,{children:e.jsx(Pe,{type:"date",value:m.endDate,onChange:g=>h(l=>({...l,endDate:g.target.value}))})}),e.jsx(_e,{})]}),e.jsxs(oe,{name:"endTime",children:[e.jsx(pe,{children:i("assignment_end_time")}),e.jsx(re,{children:e.jsx(Pe,{type:"time",value:m.endTime||"",onChange:g=>h(l=>({...l,endTime:g.target.value}))})}),e.jsx(_e,{})]})]})]}),m.allDay&&e.jsxs("div",{className:ke.halfDayContainer,children:[e.jsxs(oe,{name:"isHalfDay",className:ke.checkboxItem,children:[e.jsx(re,{children:e.jsx(St,{id:"isHalfDay",checked:m.isHalfDay,onCheckedChange:g=>{h(l=>{const k={...l,isHalfDay:g===!0};return g===!1&&(k.halfDayPeriod=null),k})}})}),e.jsx(pe,{htmlFor:"isHalfDay",children:i("assignment_half_day")})]}),m.isHalfDay&&e.jsxs(oe,{name:"halfDayPeriod",className:ke.halfDaySelect,children:[e.jsxs(nt,{value:m.halfDayPeriod||"_empty",onValueChange:g=>h(l=>({...l,halfDayPeriod:g==="morning"||g==="afternoon"?g:null})),children:[e.jsx(re,{children:e.jsx(at,{children:e.jsx(it,{placeholder:i("assignment_period")})})}),e.jsxs(ot,{children:[e.jsx(J,{value:"morning",children:i("assignment_morning")}),e.jsx(J,{value:"afternoon",children:i("assignment_afternoon")})]})]}),e.jsx(_e,{})]})]}),e.jsx("div",{className:ke.photoSection,children:e.jsx(ei,{type:"single",collapsible:!0,children:e.jsxs(ti,{value:"photos",children:[e.jsx(si,{children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"var(--spacing-2)"},children:[e.jsx(nn,{size:18}),e.jsx("span",{children:"Photos (optionnel)"})]})}),e.jsxs(ni,{children:[e.jsxs("div",{className:ke.photoActionsRow,children:[e.jsxs(L,{type:"button",variant:"outline",onClick:()=>c(!0),children:[e.jsx(nn,{size:16}),e.jsx("span",{children:"Prendre une photo"})]}),e.jsxs("label",{className:ke.uploadLabel,children:[e.jsx(Ba,{size:16}),e.jsx("span",{children:"Ajouter des photos"}),e.jsx("input",{type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:g=>{const l=Array.from(g.target.files||[]);l.length&&(Promise.all(l.map(k=>new Promise(j=>{const x=new FileReader;x.onload=d=>j({id:Math.random().toString(),base64:d.target?.result,caption:"",photoType:"general"}),x.readAsDataURL(k)}))).then(k=>{o&&n&&o([...n,...k])}),g.target.value="")}})]})]}),n&&n.length>0&&e.jsx("div",{className:ke.photoGrid,children:n.map((g,l)=>e.jsxs("div",{className:ke.photoCard,children:[e.jsx("button",{type:"button",className:ke.photoRemoveBtn,onClick:()=>{if(o){const k=[...n];k.splice(l,1),o(k)}},children:e.jsx(qt,{size:14})}),e.jsx("img",{src:g.base64,alt:"Preview",className:ke.photoThumbnail}),e.jsxs("div",{className:ke.photoControls,children:[e.jsxs(nt,{value:g.photoType,onValueChange:k=>{if(o){const j=[...n];j[l].photoType=k,o(j)}},children:[e.jsx(at,{children:e.jsx(it,{})}),e.jsxs(ot,{children:[e.jsx(J,{value:"before",children:"Avant (Before)"}),e.jsx(J,{value:"general",children:"Général (General)"}),e.jsx(J,{value:"after",children:"Après (After)"})]})]}),e.jsx(Pe,{placeholder:"Légende...",value:g.caption,onChange:k=>{if(o){const j=[...n];j[l].caption=k.target.value,o(j)}}})]})]},g.id))})]})]})})}),e.jsx($r,{isOpen:p,onClose:()=>c(!1),onCapture:g=>{if(o){const l={id:Math.random().toString(),base64:g,caption:"",photoType:"general"};o(n?[...n,l]:[l])}},onError:g=>q.error(g),translations:{cameraTitle:"Prendre une photo / Take photo",cancel:"Annuler / Cancel",capture:"Capturer / Capture",cameraError:"Erreur de caméra / Camera error",processing:"Traitement... / Processing..."}})]})},vi=({isOpen:t,onClose:a,initialDate:s,specialty:n,className:o,onSuccess:i,initialStartTime:p})=>{const{data:c,isFetching:m}=Ks(),{registerChange:h}=Qt(),[r,C]=u.useState(!1),{t:g,language:l}=ye(),[k,j]=u.useState([]),x=u.useMemo(()=>ji(g),[g]),d=Ys({schema:x,defaultValues:{taskTitle:"",taskDescription:"",taskLocation:"",taskPriority:"medium",taskStatus:"pending",allDay:!0,startDate:"",startTime:Os,endDate:"",endTime:Rs,duration:zs,isHalfDay:!1,halfDayPeriod:null,assignedUserId:null}}),{setValues:b}=d;u.useEffect(()=>{if(!t)return;j([]);const D=ce(s),_=ce(s);let f=Os,v=Rs,M=!0;if(p){M=!1;const W=ce(s).hour(p.hour).minute(p.minute);f=W.format("HH:mm"),v=W.clone().add(yi,"minutes").format("HH:mm")}b({taskTitle:"",taskDescription:"",taskLocation:"",taskPriority:"medium",taskStatus:"pending",allDay:M,startDate:D.format("YYYY-MM-DD"),startTime:f,endDate:_.format("YYYY-MM-DD"),endTime:v,duration:zs,isHalfDay:!1,halfDayPeriod:null,assignedUserId:null})},[t,s,p,b]);const y=D=>{C(!0);let _,f;if(D.allDay){const[v,M]=Os.split(":").map(Number),[W,N]=Rs.split(":").map(Number);_=ce(D.startDate).hour(v).minute(M).second(0).toDate(),f=ce(D.endDate).hour(W).minute(N).second(0).toDate()}else _=ce(`${D.startDate} ${D.startTime}`).toDate(),f=ce(`${D.endDate} ${D.endTime}`).toDate();h({type:"new-assignment",payload:{taskTitle:D.taskTitle,taskDescription:D.taskDescription||void 0,taskLocation:D.taskLocation||void 0,taskPriority:D.taskPriority,taskStatus:D.taskStatus,startDate:_,endDate:f,isHalfDay:D.isHalfDay,halfDayPeriod:D.halfDayPeriod,specialty:n,assignedUserId:D.assignedUserId??null,allDay:D.allDay,isPinned:!1,_pendingPhotos:k.length>0?k:void 0},description:g("task_create_description",{title:D.taskTitle,date:ce(_).format("DD/MM/YYYY")})}),C(!1),a(),i?.()},S=!!d.values.taskTitle;return e.jsx(Qe,{open:t,onOpenChange:D=>!D&&a(),children:e.jsxs(Ke,{className:`${ke.dialogContent} ${o||""}`,children:[e.jsxs(lt,{children:[e.jsx(Je,{children:g("task_modal_title")}),e.jsxs($t,{children:[g("task_modal_description")," ",e.jsx("span",{className:ke.specialtyBadge,children:n}),"."]})]}),e.jsx(Qs,{...d,children:e.jsxs("div",{className:ke.form,children:[e.jsxs(oe,{name:"assignedUserId",children:[e.jsx(pe,{children:l==="fr"?"Employé assigné":"Assigned employee"}),e.jsxs(nt,{value:d.values.assignedUserId!=null?String(d.values.assignedUserId):"__none",onValueChange:D=>d.setValues(_=>({..._,assignedUserId:D==="__none"?null:Number(D)}
2)),disabled:m,children:[e.jsx(re,{children:e.jsx(at,{children:e.jsx(it,{placeholder:l==="fr"?"Sélectionner un employé":"Select employee"})})}),e.jsxs(ot,{children:[e.jsx(J,{value:"__none",children:l==="fr"?"Non assigné":"Unassigned"}),c?.map(D=>e.jsx(J,{value:String(D.id),children:D.displayName},D.id))]})]}),e.jsx(_e,{})]}),e.jsx(Di,{form:d,onSubmit:y,formId:"quick-task-assignment-form",photos:k,onPhotosChange:j})]})}),e.jsxs(Ct,{children:[e.jsx(L,{variant:"outline",onClick:a,disabled:r,children:g("assignment_cancel")}),e.jsx(L,{type:"submit",form:"quick-task-assignment-form",disabled:!S||r,className:ke.submitButton,children:r?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:ke.loaderIcon}),g("task_creating")]}):g("task_create")})]})]})})};function sn(t,a,s){const n=ge(a),o=es(a),i=ge(new Date(t.startDate)),p=t.endDate?es(new Date(t.endDate)):es(i);if(!(i<=o&&p>=n))return!1;if(n.getTime()===i.getTime()||n.getTime()===ge(p).getTime())return!0;if(s?.enabled){const m={workingDays:s.workDays,avoidWeekends:s.avoidWeekends,avoidHolidays:s.avoidHolidays,startTime:s.startTime,endTime:s.endTime};if(!us(a,m))return!1}return!0}const xm=Ee({assignmentId:Me().int().positive(),cascadeMode:Ye(["pull-up","leave-gap"]),sendNotifications:$e().default(!1),specialty:X().nullable().optional()}),ym=async(t,a)=>{const s=xm.parse(t),n=await fetch("/_api/client-assignments/delete-with-cascade",{method:"POST",body:K.stringify(s),...a,headers:{"Content-Type":"application/json"}});if(!n.ok){const o=K.parse(await n.text());throw new Error(typeof o=="object"&&o!==null&&"error"in o?String(o.error):"An unknown error occurred")}return K.parse(await n.text())},Wn=()=>{const t=gt();return Ve({mutationFn:a=>ym(a),onSuccess:()=>{t.invalidateQueries({queryKey:[Wt]}),t.invalidateQueries({queryKey:[fs,"list"]})}})};function jm(t){const a=t.getDay();return a===0||a===6}function Dm(t){const a=t.getFullYear(),s=Qa(a),n=`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`;return s.some(o=>`${o.date.getFullYear()}-${String(o.date.getMonth()+1).padStart(2,"0")}-${String(o.date.getDate()).padStart(2,"0")}`===n)}function vm(t,a){return!1}function Ci(t,a,s,n,o){if(a===0)return new Date(t);const i=new Date(t);let p=0,c=a*7+365,m=0;for(;p<a&&m<c;){i.setDate(i.getDate()-1);let h=!0;(s&&jm(i)||n&&Dm(i)||vm())&&(h=!1),h&&p++,m++}return m>=c&&console.error("subtractWorkingDays: Max iterations reached"),i}const ki=(t,a,s,n)=>u.useMemo(()=>{if(!t||!s)return{affectedAssignments:[],gapDuration:0,notificationBreakdown:{smsEmail:0,portalOnly:0}};const o=s.avoidWeekends,i=s.avoidHolidays,p=new Date(t.startDate),c=t.endDate?new Date(t.endDate):p,m=qs(p,c,o,i);if(m<=0)return{affectedAssignments:[],gapDuration:0,notificationBreakdown:{smsEmail:0,portalOnly:0}};const r=a.filter(x=>x.id===t.id||x.isPinned||new Date(x.startDate)<=c?!1:x.specialty===t.specialty||!x.specialty&&!t.specialty).sort((x,d)=>new Date(x.startDate).getTime()-new Date(d.startDate).getTime()).map(x=>{const d=new Date(x.startDate),b=Ci(d,m,o,i);return{id:x.id,clientId:x.clientId,clientName:x.firstName?`${x.firstName} ${x.lastName}`:x.taskTitle||"Unknown",oldStartDate:d,newStartDate:b}});let C=0,g=0;const l=2,k=new Date,j=new Date(k);return j.setDate(j.getDate()+l*7),r.forEach(x=>{x.clientId&&(x.newStartDate<=j?C++:g++)}),{affectedAssignments:r,gapDuration:m,notificationBreakdown:{smsEmail:C,portalOnly:g}}},[t,a,s,n]),Cm="_dialogContent_173xj_1",km="_loadingContainer_173xj_5",bm="_content_173xj_12",wm="_radioGroup_173xj_19",Sm="_radioOption_173xj_25",Nm="_radioHeader_173xj_39",Tm="_radioLabel_173xj_45",Im="_radioDescription_173xj_51",Em="_notificationSection_173xj_57",Pm="_notificationStats_173xj_66",$m="_statItem_173xj_71",Mm="_statCount_173xj_76",Am="_statLabel_173xj_82",Bm="_checkboxWrapper_173xj_89",qe={dialogContent:Cm,loadingContainer:km,content:bm,radioGroup:wm,radioOption:Sm,radioHeader:Nm,radioLabel:Tm,radioDescription:Im,notificationSection:Em,notificationStats:Pm,statItem:$m,statCount:Mm,statLabel:Am,checkboxWrapper:Bm},bi=({isOpen:t,onClose:a,assignment:s,preview:n,onConfirm:o,isLoading:i})=>{const{t:p}=ye(),[c,m]=u.useState("pull-up"),[h,r]=u.useState(!1);u.useEffect(()=>{t&&(m("pull-up"),r(!1))},[t]);const C=()=>
2{console.log("[DELETE DIALOG] handleConfirm called, cascadeMode:",c,"sendNotifications:",h),o(c,h)},g=s?s.firstName?`${s.firstName} ${s.lastName}`:s.taskTitle||p("schedule_gap_project"):"";return e.jsx(Qe,{open:t,onOpenChange:l=>!l&&a(),children:e.jsx(Ke,{className:qe.dialogContent,children:s?e.jsxs(e.Fragment,{children:[e.jsxs(lt,{children:[e.jsx(Je,{children:p("schedule_gap_delete_title",{name:g})}),e.jsx($t,{children:p("schedule_gap_delete_description")})]}),e.jsxs("div",{className:qe.content,children:[e.jsxs(Fn,{value:c,onValueChange:l=>m(l),className:qe.radioGroup,children:[e.jsxs("div",{className:qe.radioOption,children:[e.jsxs("div",{className:qe.radioHeader,children:[e.jsx(Is,{value:"pull-up",id:"mode-pull-up"}),e.jsx("label",{htmlFor:"mode-pull-up",className:qe.radioLabel,children:p("schedule_gap_option_pull_up")})]}),e.jsx("div",{className:qe.radioDescription,children:p("schedule_gap_option_pull_up_desc",{count:n.affectedAssignments.length,days:n.gapDuration})})]}),e.jsxs("div",{className:qe.radioOption,children:[e.jsxs("div",{className:qe.radioHeader,children:[e.jsx(Is,{value:"leave-gap",id:"mode-leave-gap"}),e.jsx("label",{htmlFor:"mode-leave-gap",className:qe.radioLabel,children:p("schedule_gap_option_leave_gap")})]}),e.jsx("div",{className:qe.radioDescription,children:p("schedule_gap_option_leave_gap_desc")})]})]}),c==="pull-up"&&n.affectedAssignments.length>0&&e.jsxs("div",{className:qe.notificationSection,children:[e.jsxs("div",{className:qe.notificationStats,children:[e.jsxs("div",{className:qe.statItem,children:[e.jsx("span",{className:qe.statCount,children:n.notificationBreakdown.smsEmail}),e.jsx("span",{className:qe.statLabel,children:p("schedule_gap_notifications_sms_email")})]}),e.jsxs("div",{className:qe.statItem,children:[e.jsx("span",{className:qe.statCount,children:n.notificationBreakdown.portalOnly}),e.jsx("span",{className:qe.statLabel,children:p("schedule_gap_notifications_portal")})]})]}),e.jsxs("div",{className:qe.checkboxWrapper,children:[e.jsx(St,{id:"send-notifications",checked:h,onCheckedChange:l=>r(l===!0)}),e.jsx("label",{htmlFor:"send-notifications",children:p("schedule_gap_send_notifications")})]})]})]}),e.jsxs(Ct,{children:[e.jsx(L,{variant:"secondary",onClick:a,disabled:i,children:p("cancel")}),e.jsxs(L,{variant:"destructive",onClick:C,disabled:i,children:[i?e.jsx(Ts,{size:"sm"}):null,p("schedule_gap_confirm_delete")]})]})]}):e.jsx("div",{className:qe.loadingContainer,children:e.jsx(Ts,{size:"lg"})})})})},Hm="_container_174ro_1",Lm="_clientInfoCard_174ro_7",Om="_clientInfoName_174ro_15",Rm="_clientInfoGrid_174ro_22",Fm="_clientInfoItem_174ro_35",Um="_clientInfoIcon_174ro_45",qm="_infoSkeleton_174ro_52",zm="_separator_174ro_58",Wm="_form_174ro_63",Gm="_switchesRow_174ro_70",Vm="_switchItem_174ro_79",Ym="_switchLabel_174ro_85",Qm="_compactSwitch_174ro_93",Km="_periodRow_174ro_98",Jm="_periodControlContainer_174ro_103",Xm="_horizontalRadioGroup_174ro_109",Zm="_compactRadioOption_174ro_115",eh="_radioLabel_174ro_131",th="_radioIcon_174ro_146",sh="_inlineError_174ro_150",nh="_datesRow_174ro_156",ah="_dateField_174ro_161",ih="_dateInput_174ro_174",oh="_notesField_174ro_192",rh="_notesInput_174ro_204",lh="_footerActions_174ro_224",ch="_saveActions_174ro_233",dh="_deleteButton_174ro_238",he={container:Hm,clientInfoCard:Lm,clientInfoName:Om,clientInfoGrid:Rm,clientInfoItem:Fm,clientInfoIcon:Um,infoSkeleton:qm,separator:zm,form:Wm,switchesRow:Gm,switchItem:Vm,switchLabel:Ym,compactSwitch:Qm,periodRow:Km,periodControlContainer:Jm,horizontalRadioGroup:Xm,compactRadioOption:Zm,radioLabel:eh,radioIcon:th,inlineError:sh,datesRow:nh,dateField:ah,dateInput:ih,notesField:oh,notesInput:rh,footerActions:lh,saveActions:ch,deleteButton:dh},uh=t=>t==="morning"||t==="afternoon"?t:null,ph=({assignment:t,onClose:a,onDraftDeleted:s,clientData:n,isClientFetching:o})=>{const{t:i}=ye(),[p,c]=u.useState(!1),m=t.id,h=u.useMemo(()=>Ee({startDate:ia({required_error:i("clients_start_date_required")}),endDate:ia().nullable(),notes:X().nullable(),isPinned:$e().optional(),isHalfDay:$e().optional(),halfDayPeriod:Ye(["morning","afternoon"]).optional().nullable()}).refine(w=>!w.endDate||w.endDate>=w.startDate,{message:i("clients_end_date_after_start"),path:["endDate"]}).refine(w=>!w.isHalfDay||w.halfDayPeriod,{message:i("clients_half_day_period_required"),path:["halfDayPeriod"]}
2),[i]),r=u.useMemo(()=>({startDate:new Date,endDate:null,notes:null,isPinned:!1,isHalfDay:!1,halfDayPeriod:null}),[]),{mutate:C,isPending:g}=Ms(),{removeAssignmentDraft:l,registerChange:k}=Qt(),j=u.useMemo(()=>{const w=new Date;w.setHours(0,0,0,0);const B=new Date(w);B.setFullYear(B.getFullYear()-1);const I=new Date(w);return I.setFullYear(I.getFullYear()+1),{startDate:B.toISOString(),endDate:I.toISOString()}},[]),{data:x}=Es(j),{data:d}=Yt(),b=ki(t,x?.assignments||[],d),{mutate:y,isPending:S}=Wn(),D=()=>{m<0?confirm(i("clients_confirm_delete"))&&(l(m),a(),s?.()):c(!0)},{control:_,handleSubmit:f,reset:v,watch:M}=ai({resolver:ii(h),defaultValues:r}),W=M("isHalfDay");je.useEffect(()=>{v(t?{startDate:new Date(t.startDate),endDate:t.endDate?new Date(t.endDate):null,notes:t.notes??null,isPinned:t.isPinned??!1,isHalfDay:t.isHalfDay??!1,halfDayPeriod:uh(t.halfDayPeriod)}:r)},[t,v,r]);const N=w=>{m<0?(k({type:"client-assignment",payload:{id:m,startDate:w.startDate.toISOString(),endDate:w.endDate?.toISOString()??null,notes:w.notes,isPinned:w.isPinned??!1,isHalfDay:w.isHalfDay??!1,halfDayPeriod:w.halfDayPeriod??null},originalSnapshot:t,description:`Modification: ${t.firstName} ${t.lastName}`}),a()):C({id:m,...w},{onSuccess:a})},O=(w,B)=>{y({assignmentId:m,cascadeMode:w,sendNotifications:B,specialty:t.specialty},{onSuccess:()=>{c(!1),a()}})};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:he.container,children:[(o||n)&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:he.clientInfoCard,children:o?e.jsxs("div",{className:he.infoSkeleton,children:[e.jsx(ne,{style:{height:"1.25rem",width:"50%"}}),e.jsx(ne,{style:{height:"0.875rem",width:"70%"}}),e.jsx(ne,{style:{height:"0.875rem",width:"40%"}})]}):n&&e.jsxs(e.Fragment,{children:[e.jsxs("h3",{className:he.clientInfoName,children:[n.firstName," ",n.lastName]}),e.jsxs("div",{className:he.clientInfoGrid,children:[n.email&&e.jsxs("div",{className:he.clientInfoItem,children:[e.jsx(bo,{size:14,className:he.clientInfoIcon}),e.jsx("span",{children:n.email})]}),n.phone&&e.jsxs("div",{className:he.clientInfoItem,children:[e.jsx(wo,{size:14,className:he.clientInfoIcon}),e.jsx("span",{children:n.phone})]}),(n.address||n.city)&&e.jsxs("div",{className:he.clientInfoItem,children:[e.jsx(An,{size:14,className:he.clientInfoIcon}),e.jsx("span",{children:[n.address,n.city,n.postalCode].filter(Boolean).join(", ")})]})]})]})}),e.jsx(Rn,{className:he.separator})]}),e.jsxs("form",{onSubmit:f(N),className:he.form,children:[e.jsxs("div",{className:he.switchesRow,children:[e.jsxs("div",{className:he.switchItem,children:[e.jsx(Pt,{name:"isPinned",control:_,render:({field:w})=>e.jsx(Ls,{id:"isPinned",checked:w.value??!1,onCheckedChange:w.onChange,className:he.compactSwitch})}),e.jsx(Ut,{htmlFor:"isPinned",className:he.switchLabel,children:i("clients_fixed_date")})]}),e.jsxs("div",{className:he.switchItem,children:[e.jsx(Pt,{name:"isHalfDay",control:_,render:({field:w})=>e.jsx(Ls,{id:"isHalfDay",checked:w.value??!1,onCheckedChange:w.onChange,className:he.compactSwitch})}),e.jsx(Ut,{htmlFor:"isHalfDay",className:he.switchLabel,children:i("clients_half_day")})]})]}),W&&e.jsx("div",{className:he.periodRow,children:e.jsx(Pt,{name:"halfDayPeriod",control:_,render:({field:w,fieldState:B})=>e.jsxs("div",{className:he.periodControlContainer,children:[e.jsxs(Fn,{value:w.value??"",onValueChange:w.onChange,className:he.horizontalRadioGroup,children:[e.jsxs("div",{className:he.compactRadioOption,children:[e.jsx(Is,{value:"morning",id:"morning"}),e.jsxs("label",{htmlFor:"morning",className:he.radioLabel,children:[e.jsx(Fs,{size:14,className:he.radioIcon}),e.jsx("span",{children:i("clients_morning")})]})]}),e.jsxs("div",{className:he.compactRadioOption,children:[e.jsx(Is,{value:"afternoon",id:"afternoon"}),e.jsxs("label",{htmlFor:"afternoon",className:he.radioLabel,children:[e.jsx(Us,{size:14,className:he.radioIcon}),e.jsx("span",{children:i("clients_afternoon")})]})]})]}),B.error&&e.jsx("span",{className:he.inlineError,children:B.error.message})]})})}),e.jsxs("div",{className:he.datesRow,children:[e.jsxs("div",{className:he.dateField,children:[e.jsx("label",{htmlFor:"startDate",children:i("clients_start_date")}),e.jsx(Pt,{name:"startDate",control:_,render:({field:w})=>e.jsx("input",{type:"date",...w,value:w.value?.toISOString().split("T")[0],onChange:B=>w.onChange(new Date(B.target.value)),className:he.dateInput})})]}),e.jsxs("div",{className:he.dateField,children:[e.jsx("label",{htmlFor:"endDate",children:i("clients_end_date")}),e.jsx(Pt,{name:"endDate",control:_,render:({field:w})=>e.jsx("input",{type:"date",...w,value:w.value?.toISOString().split("T")[0]??"",onChange:B=>w.onChange(B.target.value?new Date(B.target.value):null),className:he.dateInput})})]})]}),e.jsxs("div",{className:he.notesField,children:[e.jsx("label",{htmlFor:"notes",children:i("clients_notes")}),e.jsx(Pt,{name:"notes",control:_,render:({field:w})=>e.jsx("textarea",{...w,value:w.value??"",className:he.notesInput,rows:3})})]}),e.jsxs("div",{className:he.footerActions,children:[e.jsxs(L,{type:"button",variant:"destructive",size:"sm",onClick:D,className:he.deleteButton,disabled:g,children:[e.jsx(ps,{size:14}),i("common_delete")]}),e.jsxs("div",{className:he.saveActions,children:[e.jsx(L,{type:"button",variant:"ghost",size:"sm",onClick:a,disabled:g,children:i("common_cancel")}),e.jsx(L,{type:"submit",size:"sm",disabled:g,children:i(g?"clients_saving":"common_save")})]})]})]})]}),e.jsx(bi,{isOpen:p,onClose:()=>c(!1),assignment:t,preview:b,onConfirm:O,isLoading:S})]})};Ee({clientId:Me().int().positive()});const mh=async(t,a)=>{const s=new URL("/_api/clients/plan",Fa());s.searchParams.set("clientId",t.clientId.toString());const n=await fetch(s.toString(),{method:"GET",...a,headers:{"Content-Type":"application/json"}});if(!n.ok){const o=K.parse(await n.text());throw new Error(typeof o=="object"&&o!==null&&"error"in o?String(o.error):"An unknown error occurred")}return K.parse(await n.text())},hh=Ee({clientId:Me().int().positive(),planImageData:X().refine(t=>t.startsWith("data:image/")&&t.includes(";base64,"),{message:"Image data must be a valid base64 data URL (e.g., data:image/png;base64,...)"})}),gh=async(t,a)=>{const s=hh.parse(t),n=await fetch("/_api/clients/upload-plan",{method:"POST",body:K.stringify(s),...a,headers:{"Content-Type":"application/json"}});if(!n.ok){const o=K.parse(await n.text());throw new Error(typeof o=="object"&&o!==null&&"error"in o?String(o.error):"An unknown error occurred")}return K.parse(await n.text())},wi="clientPlan",_h="client-detail",fh=t=>ms({queryKey:[wi,t],queryFn:()=>t?mh({clientId:t}):Promise.reject(new Error("Client ID is required.")),enabled:!!t&&t>0,staleTime:300*1e3}),xh=()=>{const t=gt();return Ve({mutationFn:a=>gh(a),onSuccess:(a,s)=>{const{clientId:n}=s;q.success("Plan a été téléversé avec succès ! / Plan uploaded successfully!"),t.invalidateQueries({queryKey:[wi,n]}),t.invalidateQueries({queryKey:[_h,n]})},onError:a=>{console.error("Failed to upload client plan:",a),q.error(`Ãchec du téléversement du plan : ${a.message}`)}})};Ee({clientId:Me().int().positive()});const yh=async(t,a)=>{const s=new URL("/_api/client-plan-files/list",Fa());s.searchParams.set("clientId",t.clientId.toString());const n=await fetch(s.toString(),{method:"GET",...a,headers:{"Content-Type":"application/json"}});if(!n.ok){const o=await n.text();let i;try{i=K.parse(o)}catch{throw new Error("An unknown error occurred while fetching client plan files")}throw new Error(i.error)}return K.parse(await n.text())},jh=Ee({id:Me().int().positive()}),Dh=async(t,a)=>{const s=jh.parse(t),n=await fetch("/_api/client-plan-files/delete",{method:"POST",body:K.stringify(s),...a,headers:{"Content-Type":"application/json"}});if(!n.ok){const o=await n.text();let i;try{i=K.parse(o)}catch{throw new Error("Failed to delete plan file")}throw new Error(i.error)}return K.parse(await n.text())};Ee({fileIds:$n(Me().int().positive())});const Gn="clientPlanFiles",vh=t=>ms({queryKey:[Gn,t],queryFn:()=>!t||t<=0?Promise.reject(new Error("Valid Client ID is required.")):yh({clientId:t}),enabled:!!t&&t>0,staleTime:300*1e3}),Ch=()=>{const t=gt();return Ve({mutationFn:a=>zr(a),onSuccess:(a,s)=>{q.success("Fichier ajouté avec succès ! / File added successfully!"),t.invalidateQueries({queryKey:[Gn,s.clientId]})},onError:a=>{q.error(`Erreur / Error: ${a instanceof Error?a.message:"Ãchec de l'ajout du fichier / Failed to add file"}`)}})},kh=t=>{const a=gt();return Ve({mutationFn:s=>Dh(s),onSuccess:()=>{q.success("Fichier supprimé avec succès ! / File deleted successfully!"),a.invalidateQueries({queryKey:[Gn,t]})},onError:s=>{q.error(`Erreur / Error: ${s instanceof Error?s.message:"Ãchec de la suppression du fichier / Failed to delete file"}`)}})},bh="_planSection_18app_1",wh="_headerActions_18app_8",Sh="_cameraContainer_18app_14",Nh="_cancelCameraBtn_18app_24",Th="_filesSection_18app_28",I
2h="_grid_18app_34",Eh="_card_18app_52",Ph="_legacyBadge_18app_63",$h="_imageWrapper_18app_78",Mh="_image_18app_78",Ah="_pdfIconContainer_18app_98",Bh="_pdfIcon_18app_98",Hh="_cardFooter_18app_116",Lh="_fileName_18app_125",Oh="_deleteBtn_18app_134",Rh="_skeletonCard_18app_142",Fh="_emptyState_18app_148",Uh="_pdfViewerContent_18app_161",qh="_pdfHeader_18app_179",zh="_pdfPagesContainer_18app_186",Wh="_pdfPageImage_18app_197",Gh="_pdfLoading_18app_204",Vh="_pdfViewerFooter_18app_212",Te={planSection:bh,headerActions:wh,cameraContainer:Sh,cancelCameraBtn:Nh,filesSection:Th,grid:Ih,card:Eh,legacyBadge:Ph,imageWrapper:$h,image:Mh,pdfIconContainer:Ah,pdfIcon:Bh,cardFooter:Hh,fileName:Lh,deleteBtn:Oh,skeletonCard:Rh,emptyState:Fh,pdfViewerContent:Uh,pdfHeader:qh,pdfPagesContainer:zh,pdfPageImage:Wh,pdfLoading:Gh,pdfViewerFooter:Vh},ja="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",Yh=({clientId:t})=>{const{t:a}=ye(),[s,n]=u.useState(!1),[o,i]=u.useState(!1),[p,c]=u.useState(null),[m,h]=u.useState([]),[r,C]=u.useState(!1),[g,l]=u.useState(""),k=u.useRef(null),{data:j,isFetching:x}=fh(t),{mutate:d,isPending:b}=xh(),{data:y,isFetching:S}=vh(t),{mutateAsync:D}=Ch(),{mutate:_,isPending:f}=kh(t),{mutateAsync:v}=hr(),M=j?.clientPlan?.planImageData,W=!x&&M&&M!==ja,N=async T=>{const A=Array.from(T.target.files||[]);if(A.length!==0){n(!0);try{for(const Y of A){const E=await v({file:Y,folder:`client-plans/${t}`});await D({clientId:t,fileUrl:E,fileName:Y.name,fileType:Y.type||"application/octet-stream",fileSize:Y.size})}}catch(Y){console.error("Failed to upload file(s):",Y);const E=Y instanceof Error?Y.message.toLowerCase():"";E.includes("size")||E.includes("large")?q.error("Fichier trop volumineux / File too large"):q.error("Ãchec du téléversement / Upload failed")}finally{n(!1),k.current&&(k.current.value="")}}},O=async T=>{if(T){n(!0);try{const Y=await(await fetch(T)).blob(),E=new File([Y],`Capture_${new Date().toISOString().replace(/:/g,"-")}.png`,{type:"image/png"}),$=await v({file:E,folder:`client-plans/${t}`});await D({clientId:t,fileUrl:$,fileName:E.name,fileType:"image/png",fileSize:E.size}),i(!1)}catch(A){console.error("Camera capture upload error:",A),q.error("Ãchec du téléversement de la photo / Photo upload failed")}finally{n(!1)}}},w=async(T,A)=>{const Y=q.loading(a("common_loading")||"Ouverture du fichier... / Opening file...");C(!0);try{const E=await fetch(`/_api/cloudinary/download?url=${encodeURIComponent(T)}`);if(!E.ok)throw new Error("Failed to download file");const $=await E.arrayBuffer();c($),l(A);const R=await No(()=>import("./pdf-dNxa0vXk.js").then(se=>se.p),__vite__mapDeps([0,1,2,3])),Q=async se=>{R.GlobalWorkerOptions.workerSrc=se;const ae=await R.getDocument({data:$.slice(0)}).promise,Z=[];for(let ve=1;ve<=ae.numPages;ve++){const ue=await ae.getPage(ve),P=ue.getViewport({scale:1.5}),z=document.createElement("canvas"),V=z.getContext("2d");if(V){z.height=P.height,z.width=P.width;const Se={canvasContext:V,viewport:P};await ue.render(Se).promise,Z.push(z.toDataURL("image/png"))}}return Z};try{const se=await Q("https://unpkg.com/[email protected]/build/pdf.worker.min.js");h(se)}catch(se){console.warn("First PDF rendering attempt failed, retrying without worker...",se);const ae=await Q("");h(ae)}}catch(E){console.error("Failed to open PDF:",E),q.error("Ãchec de l'ouverture du fichier / Failed to open file")}finally{C(!1),q.dismiss(Y)}},B=(T,A,Y)=>{A==="application/pdf"||Y.toLowerCase().endsWith(".pdf")||T.includes("/raw/upload/")?w(T,Y):window.open(T,"_blank")},I=T=>{T.includes("/raw/upload/")||T.toLowerCase().endsWith(".pdf")?w(T,"Plan.pdf"):window.open(T,"_blank")},F=()=>{c(null),h([]),C(!1),l("")},de=()=>{if(!p)return;const T=new Blob([p],{type:"application/pdf"}),A=URL.createObjectURL(T);try{const Y=document.createElement("a");Y.href=A,Y.download=g||"document.pdf",document.body.appendChild(Y),Y.click(),document.body.removeChild(Y),setTimeout(()=>URL.revokeObjectURL(A),1e3)}catch(Y){console.warn("Standard download failed, falling back to window.open",Y),window.open(A,"_blank"),setTimeout(()=>URL.revokeObjectURL(A),1e3)}},fe=()=>{t&&d({clientId:t,planImageData:ja})};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:Te.planSection,children:[e.jsxs("div",{className:Te.headerActions,children:[e.jsx("input",{type:"file",ref:k,style:{display:"none"},multiple:!0,accept:"image/jpeg,image/png,image/webp,image/gif,application/pdf",onChange:N}),e.jsxs(L,{variant:"primary",onClick:()=>k.current?.click(),disabled:s,children:[s?e.jsx(Ts,{size:"sm"}):e.jsx(Ba,{size:16}),"Téléverser des fichiers / Upload files"]}),e.jsxs(L,{variant:"outline",onClick:()=>i(!0),disabled:s||o,children:[e.jsx(nn,{size:16}),"Prendre une photo / Take photo"]})]}),o&&e.jsxs("div",{className:Te.cameraContainer,children:[e.jsx(Mr,{value:null,onChange:O,disabled:s,placeholder:a("clients_add_plan")}),e.jsx(L,{variant:"ghost",size:"sm",onClick:()=>i(!1),className:Te.cancelCameraBtn,disabled:s,children:a("common_cancel")})]}),e.jsx("div",{className:Te.filesSection,children:S||x?e.jsxs("div",{className:Te.grid,children:[e.jsx(ne,{className:Te.skeletonCard}),e.jsx(ne,{className:Te.skeletonCard}),e.jsx(ne,{className:Te.skeletonCard})]}):W||y?.files&&y.files.length>0?e.jsxs("div",{className:Te.grid,children:[W&&e.jsxs("div",{className:Te.card,children:[e.jsx("div",{className:Te.legacyBadge,children:"Image existante"}),e.jsx("div",{onClick:()=>I(M),className:Te.imageWrapper,role:"button",tabIndex:0,children:e.jsx("img",{src:Pn(M,400),alt:"Legacy Plan",className:Te.image,loading:"lazy"})}),e.jsxs("div",{className:Te.cardFooter,children:[e.jsx("span",{className:Te.fileName,title:"Ancien plan / Legacy plan",children:"Ancien plan / Legacy plan"}),e.jsx(L,{variant:"ghost",size:"icon-sm",className:Te.deleteBtn,onClick:fe,disabled:b,children:e.jsx(ps,{size:14})})]})]}),y?.files.map(T=>e.jsxs("div",{className:Te.card,children:[e.jsx("div",{onClick:()=>B(T.fileUrl,T.fileType,T.fileName),className:Te.imageWrapper,role:"button",tabIndex:0,children:T.fileType==="application/pdf"||T.fileName.toLowerCase().endsWith(".pdf")?e.jsx("div",{className:Te.pdfIconContainer,children:e.jsx(Ha,{size:48,className:Te.pdfIcon})}):e.jsx("img",{src:Pn(T.fileUrl,400),alt:T.fileName,className:Te.image,loading:"lazy"})}),e.jsxs("div",{className:Te.cardFooter,children:[e.jsx("span",{className:Te.fileName,title:T.fileName,children:T.fileName}),e.jsx(L,{variant:"ghost",size:"icon-sm",className:Te.deleteBtn,onClick:()=>_({id:T.id}),disabled:f,children:e.jsx(ps,{size:14})})]})]},T.id))]}):e.jsx("div",{className:Te.emptyState,children:e.jsx("p",{children:"Aucun fichier de plan / No plan files"})})})]}),e.jsx(Qe,{open:!!p,onOpenChange:T=>!T&&F(),children:e.jsxs(Ke,{className:Te.pdfViewerContent,children:[e.jsx(lt,{className:Te.pdfHeader,children:e.jsx(Je,{children:g})}),e.jsx("div",{className:Te.pdfPagesContainer,children:r&&m.length===0?e.jsx("div",{className:Te.pdfLoading,children:e.jsx(Ts,{size:"lg"})}):m.map((T,A)=>e.jsx("img",{src:T,alt:`Page ${A+1} de ${g}`,className:Te.pdfPageImage},A))}),e.jsxs("div",{className:Te.pdfViewerFooter,children:[e.jsxs(L,{variant:"outline",onClick:de,children:[e.jsx(So,{size:16}),"Télécharger / Download"]}),e.jsx(L,{onClick:F,children:"Fermer / Close"})]})]})})]})},Qh="_container_wi15c_1",Kh="_emptyState_wi15c_8",Jh="_errorState_wi15c_9",Xh="_emptyIcon_wi15c_23",Zh="_errorIcon_wi15c_24",eg="_loadingContainer_wi15c_40",tg="_skeletonCard_wi15c_46",sg="_skeletonHeader_wi15c_56",ng="_skeletonRows_wi15c_62",ag="_skeletonRow_wi15c_62",tt={container:Qh,emptyState:Kh,errorState:Jh,emptyIcon:Xh,errorIcon:Zh,loadingContainer:eg,skeletonCard:tg,skeletonHeader:sg,skeletonRows:ng,skeletonRow:ag},ig=({quoteId:t})=>{const{language:a}=ye(),{hasPermission:s}=gs(),{authState:n}=Vt(),{data:o,isLoading:i,isError:p}=Va(t||0),{data:c,isLoading:m}=_s(),{data:h}=Wr(),r=n.type==="authenticated"?n.user.role:null,C=r==="admin"||r==="company"||s("quotes.view"),g=s("quotes.view_without_pricing"),l=C||g,k=!C,j=i||m;return t?l?j?e.jsxs("div",{className:tt.loadingContainer,children:[e.jsxs("div",{className:tt.skeletonCard,children:[e.jsx(ne,{className:tt.skeletonHeader}),e.jsxs("div",{className:tt.skeletonRows,children:[e.jsx(ne,{className:tt.skeletonRow}),e.jsx(ne,{className:tt.skeletonRow}),e.jsx(ne,{className:tt.skeletonRow})]})]}),!k&&e.jsxs("div",{className:tt.skeletonCard,children:[e.jsx(ne,{className:tt.skeletonHeader}),e.jsxs("div",{className:tt.skeletonRows,children:[e.jsx(ne,{className:tt.skeletonRow}),e.jsx(ne,{className:tt.skeletonRow})]})]})]}):p||!o?e.jsxs("div",{className:tt.errorState,children:[e.jsx(ss,{className:tt.errorIcon}),e.jsx("p",{children:"Erreur lors du chargement du devis."})]}):e.jsx("div",{className:tt.container,children:e.jsx(Gr,{documentId:o.id,document:o,type:"quote",presentation:"modal",lang:a==="fr"||a==="en"?a:"fr",companyLogo:h?.logoUrl??void 0,hidePrices:k,isMobile:!0,hideTermsAndSignature:!0})}):e.jsxs("div",{className:tt.errorState,children:[e.jsx(ss,{className:tt.errorIcon}),e.jsx("p",{children:"Vous n'avez pas la permission de voir ce devis."})]}):e.jsxs("div",{className:tt.emptyState,children:[e.jsx(Ha,{className:tt.emptyIcon}),e.jsx("p",{children:"Aucun devis associé à cette assignation."})]})},og="_container_2tn6n_2",rg="_section_2tn6n_10",lg="_header_2tn6n_18",cg="_title_2tn6n_26",dg="_editButton_2tn6n_33",ug="_content_2tn6n_37",pg="_viewSection_2tn6n_44",mg="_notesDisplay_2tn6n_53",hg="_emptyState_2tn6n_61",gg="_emptyIcon_2tn6n_73",_g="_editSection_2tn6n_78",fg="_textarea_2tn6n_84",xg="_actions_2tn6n_89",yg="_skeletonTitle_2tn6n_96",jg="_skeletonButton_2tn6n_101",Dg="_skeletonBody_2tn6n_106",Ne={container:og,section:rg,header:lg,title:cg,editButton:dg,content:ug,viewSection:pg,notesDisplay:mg,emptyState:hg,emptyIcon:gg,editSection:_g,textarea:fg,actions:xg,skeletonTitle:yg,
2skeletonButton:jg,skeletonBody:Dg},vg=({client:t,assignment:a,isLoading:s})=>{const{t:n,language:o}=ye(),{canWriteClientNotes:i}=Ko(),{mutate:p,isPending:c}=Rr(),[m,h]=u.useState(!1),[r,C]=u.useState(""),{mutate:g,isPending:l}=Ms(),[k,j]=u.useState(!1),[x,d]=u.useState("");if(u.useEffect(()=>{t&&C(t.internalNotes||"")},[t?.internalNotes]),u.useEffect(()=>{a&&d(a.notes||"")},[a?.notes]),s||!t)return e.jsx("div",{className:Ne.container,children:e.jsxs("div",{className:Ne.section,children:[e.jsxs("div",{className:Ne.header,children:[e.jsx(ne,{className:Ne.skeletonTitle}),e.jsx(ne,{className:Ne.skeletonButton})]}),e.jsx(ne,{className:Ne.skeletonBody}),e.jsx(ne,{className:Ne.skeletonBody}),e.jsx(ne,{className:Ne.skeletonBody})]})});const b=()=>{p({clientId:t.id,internalNotes:r},{onSuccess:()=>{h(!1)}})},y=()=>{C(t.internalNotes||""),h(!1)},S=()=>{a&&g({id:a.id,notes:x},{onSuccess:()=>{j(!1)}})},D=()=>{a&&(d(a.notes||""),j(!1))};return e.jsxs("div",{className:Ne.container,children:[a&&e.jsxs("div",{className:Ne.section,children:[e.jsxs("div",{className:Ne.header,children:[e.jsx("h3",{className:Ne.title,children:o==="fr"?"Notes de l'assignation":"Assignment Notes"}),!k&&e.jsxs(L,{variant:"outline",size:"sm",onClick:()=>j(!0),className:Ne.editButton,children:[e.jsx(oa,{size:14}),o==="fr"?"Ãditer":"Edit"]})]}),e.jsx("div",{className:Ne.content,children:k?e.jsxs("div",{className:Ne.editSection,children:[e.jsx(cn,{value:x,onChange:_=>d(_.target.value),placeholder:o==="fr"?"Notes de l'assignation...":"Assignment notes...",className:Ne.textarea,autoFocus:!0,disabled:l}),e.jsxs("div",{className:Ne.actions,children:[e.jsx(L,{variant:"ghost",size:"md",onClick:D,disabled:l,children:n("common_cancel")}),e.jsx(L,{variant:"primary",size:"md",onClick:S,disabled:l,children:n("common_save")})]})]}):e.jsx("div",{className:Ne.viewSection,children:a.notes?e.jsx("div",{className:Ne.notesDisplay,children:a.notes}):e.jsxs("div",{className:Ne.emptyState,children:[e.jsx(ss,{size:20,className:Ne.emptyIcon}),e.jsx("p",{children:o==="fr"?"Aucune note pour cette assignation.":"No notes for this assignment."})]})})})]}),e.jsxs("div",{className:Ne.section,children:[e.jsxs("div",{className:Ne.header,children:[e.jsx("h3",{className:Ne.title,children:n("clients_internal_notes")}),!m&&i&&e.jsxs(L,{variant:"outline",size:"sm",onClick:()=>h(!0),className:Ne.editButton,children:[e.jsx(oa,{size:14}),o==="fr"?"Ãditer":"Edit"]})]}),e.jsx("div",{className:Ne.content,children:m?e.jsxs("div",{className:Ne.editSection,children:[e.jsx(cn,{value:r,onChange:_=>C(_.target.value),placeholder:n("clients_note_placeholder"),className:Ne.textarea,autoFocus:!0,disabled:c}),e.jsxs("div",{className:Ne.actions,children:[e.jsx(L,{variant:"ghost",size:"md",onClick:y,disabled:c,children:n("common_cancel")}),e.jsx(L,{variant:"primary",size:"md",onClick:b,disabled:c,children:n("common_save")})]})]}):e.jsx("div",{className:Ne.viewSection,children:t.internalNotes?e.jsx("div",{className:Ne.notesDisplay,children:t.internalNotes}):e.jsxs("div",{className:Ne.emptyState,children:[e.jsx(ss,{size:20,className:Ne.emptyIcon}),e.jsx("p",{children:o==="fr"?"Aucune note interne pour ce client.":"No internal notes for this client."})]})})})]})]})},Cg="_modalContent_1p871_1",kg="_compactHeader_1p871_11",bg="_headerTitle_1p871_15",wg="_headerDesc_1p871_20",Sg="_dateDisplay_1p871_25",Ng="_headerSkeleton_1p871_31",Tg="_tabs_1p871_38",Ig="_tabsList_1p871_45",Eg="_tabContent_1p871_50",jt={modalContent:Cg,compactHeader:kg,headerTitle:bg,headerDesc:wg,dateDisplay:Sg,headerSkeleton:Ng,tabs:Tg,tabsList:Ig,tabContent:Eg},Si=({isOpen:t,onClose:a,assignment:s,onDraftDeleted:n})=>{const{t:o,language:i}=ye(),{hasPermission:p}=gs(),{authState:c}=Vt(),{data:m}=_s(),h=m?.activities?.some(d=>d.id>=35&&d.id<=45),r=m?.activities?.some(d=>d.id>=35&&d.id<=45||d.id>=52&&d.id<=54),C=c.type==="authenticated"&&(["admin","company","owner"].includes(c.user.role)||p("quotes.view")||p("quotes.view_without_pricing")),g=s.clientId,l=p("planning.edit"),k=()=>{const d=i==="fr"?zt:Vr,b=new Date(s.startDate),y=s.endDate?new Date(s.endDate):null,S=De(b,"d MMM yyyy",{locale:d});if(y&&!Ns(b,y)){const _=De(y,"d MMM yyyy",{locale:d});return`${S} â ${_}`}if(s.isHalfDay){const _=s.halfDayPeriod==="AM"?i==="fr"?"Matin":"Morning":s.halfDayPeriod==="PM"?i==="fr"?"Après-midi":"Afternoon":s.halfDayPeriod;return`${S} - ${_}`}if(s.allDay)return`${S} - ${i==="fr"?"Journée complète":"All day"}`;const D=De(b,"HH:mm");if(y){const _=De(y,"HH:mm");return`${S} ⢠${D} - ${_}`}return`${S} ⢠${D}`},{data:j,isFetching:x}=ms({queryKey:["client-detail",g],queryFn:()=>Jo({id:g,limit:1}),enabled:t&&!!g,select:d=>d.clients.find(b=>b.id===g)});return e.jsx(Qe,{open:t,onOpenChange:d=>!d&&a(),children:e.jsxs(Ke,{className:jt.modalContent,onClick:d=>d.stopPropagation(),onPointerDownOutside:d=>d.stopPropagation(),onInteractOutside:d=>d.stopPropagation(),children:[e.jsxs(lt,{className:jt.compactHeader,children:[x?e.jsxs("div",{className:jt.headerSkeleton,children:[e.jsx(ne,{style:{height:"1.25rem",width:"150px"}}),e.jsx(ne,{style:{height:"0.875rem",width:"200px"}})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Je,{className:jt.headerTitle,children:[j?.firstName," ",j?.lastName]}),e.jsx($t,{className:jt.headerDesc,children:j?.email})]}),e.jsx("div",{className:jt.dateDisplay,children:k()})]}),e.jsxs(Lr,{defaultValue:l?"assignment":"plan",className:jt.tabs,children:[e.jsxs(Or,{className:jt.tabsList,children:[l&&e.jsx(is,{value:"assignment",children:o("clients_edit_assignment")}),e.jsx(is,{value:"plan",children:o("clients_plan")}),e.jsx(is,{value:"notes",children:"Notes"}),h&&e.jsx(is,{value:"patient-record",children:i==="fr"?"Dossier patient":"Patient Record"}),r&&e.jsxs(e.Fragment,{children:[e.jsx(is,{value:"packages",children:i==="fr"?"Forfaits":"Packages"}),e.jsx(is,{value:"loyalty",children:i==="fr"?"Fidélité":"Loyalty"})]}),s.quoteId&&C&&e.jsx(is,{value:"quote",children:o("quotes")})]}),l&&e.jsx(os,{value:"assignment",className:jt.tabContent,children:e.jsx(ph,{assignment:s,onClose:a,onDraftDeleted:n,clientData:j,isClientFetching:x})}),e.jsx(os,{value:"plan",className:jt.tabContent,children:e.jsx(Yh,{clientId:g})}),e.jsx(os,{value:"notes",className:jt.tabContent,children:e.jsx(vg,{client:j,assignment:s,isLoading:x})}),h&&e.jsx(os,{value:"patient-record",className:jt.tabContent,children:e.jsx(Fr,{clientId:g})}),r&&e.jsxs(e.Fragment,{children:[e.jsx(os,{value:"packages",className:jt.tabContent,children:e.jsx(Ur,{clientId:g})}),e.jsx(os,{value:"loyalty",className:jt.tabContent,children:e.jsx(qr,{clientId:g})})]}),s.quoteId&&C&&e.jsx(os,{value:"quote",className:jt.tabContent,children:e.jsx(ig,{quoteId:s.quoteId})})]})]})})},Pg="_warningBanner_1ramx_2",$g="_compact_1ramx_14",Mg="_icon_1ramx_24",Ag="_content_1ramx_38",Bg="_titleWrapper_1ramx_46",Hg="_badge_1ramx_53",Lg="_title_1ramx_46",Og="_description_1ramx_69",Zt={warningBanner:Pg,compact:$g,icon:Mg,content:Ag,titleWrapper:Bg,badge:Hg,title:Lg,description:Og},Ni=({date:t,startDate:a,endDate:s,compact:n=!1,className:o})=>{const{t:i,language:p}=ye(),c=Yr(),m=u.useMemo(()=>a?new Date(a):t?new Date(t):null,[a,t]),h=u.useMemo(()=>s?new Date(s):t?new Date(t):null,[s,t]),r=m?m.getFullYear():new Date().getFullYear(),{data:C,isLoading:g}=Qr.useCcqCalendar({year:r});if(!c.isCcqApplicable||g||!m||!h||!C)return null;const l=new Date(m);l.setHours(0,0,0,0);const k=new Date(h);k.setHours(23,59,59,999);let j=null,x=null;for(const y of C.holidays){const S=new Date(y.dateKey||y.date);if(S.setHours(0,0,0,0),S>=l&&S<=k){j=y;break}}for(const y of C.vacationPeriods){const S=new Date(y.startDateKey);S.setHours(0,0,0,0);const D=new Date(y.endDateKey);if(D.setHours(23,59,59,999),l<=D&&k>=S){x=y;break}}if(!j&&!x)return null;const d=j?p==="fr"?j.nameFr:j.nameEn:p==="fr"?x.nameFr:x.nameEn,b=i(j?"ccq_holiday_
2warning":"ccq_vacation_warning");return e.jsxs("div",{className:`${Zt.warningBanner} ${n?Zt.compact:""} ${o||""}`,children:[e.jsx(Mn,{className:Zt.icon}),e.jsxs("div",{className:Zt.content,children:[e.jsxs("div",{className:Zt.titleWrapper,children:[e.jsx("span",{className:Zt.badge,children:b}),e.jsx("span",{className:Zt.title,children:d})]}),!n&&e.jsx("p",{className:Zt.description,children:i("ccq_holiday_work_not_allowed")})]})]})},Rg="_dialogContent_daax2_1",Fg="_formContainer_daax2_8",Ug="_specialtySection_daax2_16",qg="_checkboxItem_daax2_20",zg="_helperText_daax2_26",Wg="_loaderIcon_daax2_31",Gg="_submitButton_daax2_37",rs={dialogContent:Rg,formContainer:Fg,specialtySection:Ug,checkboxItem:qg,helperText:zg,loaderIcon:Wg,submitButton:Gg},Ti=({isOpen:t,onClose:a,assignment:s,className:n,onSuccess:o})=>{const{data:i,isFetching:p}=Ks(),{t:c,language:m}=ye(),{mutateAsync:h}=Ms(),[r,C]=u.useState(!1),[g,l]=u.useState([]),k=u.useMemo(()=>ji(c).and(Ee({specialty:X().min(1,m==="fr"?"La spécialité est requise":"Specialty is required")})),[c,m]),j=Ys({schema:k,defaultValues:{taskTitle:"",taskDescription:"",taskLocation:"",taskPriority:"medium",taskStatus:"pending",allDay:!0,startDate:"",startTime:Os,endDate:"",endTime:Rs,duration:zs,isHalfDay:!1,halfDayPeriod:null,specialty:"",assignedUserId:null}}),{setValues:x}=j,[d,b]=u.useState(!0),y=s&&(s.recurrenceParentId!==null||s.recurrenceType!==null),S=s&&s.routeId!==null;u.useEffect(()=>{if(!t||!s)return;l([]);const v=ce(s.startDate),M=s.endDate?ce(s.endDate):v.clone().add(yi,"minutes");let W=zs;!s.allDay&&s.endDate&&(W=M.diff(v,"minutes").toString()),x({taskTitle:s.taskTitle||"",taskDescription:s.taskDescription||"",taskLocation:s.taskLocation||"",taskPriority:s.taskPriority||"medium",taskStatus:s.taskStatus||"pending",allDay:s.allDay,startDate:v.format("YYYY-MM-DD"),startTime:v.format("HH:mm"),endDate:M.format("YYYY-MM-DD"),endTime:M.format("HH:mm"),duration:W,isHalfDay:s.isHalfDay,halfDayPeriod:s.halfDayPeriod||null,specialty:s.specialty||"",assignedUserId:s.assignedUserId??null})},[t,s,x]);const D=async v=>{if(!s)return;C(!0);let M,W;if(v.allDay){const[N,O]=Os.split(":").map(Number),[w,B]=Rs.split(":").map(Number);M=ce(v.startDate).hour(N).minute(O).second(0).toDate(),W=ce(v.endDate).hour(w).minute(B).second(0).toDate()}else M=ce(`${v.startDate} ${v.startTime}`).toDate(),W=ce(`${v.endDate} ${v.endTime}`).toDate();try{await h({id:s.id,startDate:M,endDate:W,specialty:v.specialty,assignedUserId:v.assignedUserId??null,allDay:v.allDay,isHalfDay:v.isHalfDay,halfDayPeriod:v.halfDayPeriod,taskTitle:v.taskTitle,taskDescription:v.taskDescription||null,taskLocation:v.taskLocation||null,taskPriority:v.taskPriority,taskStatus:v.taskStatus,applyToSeries:y?d:void 0}),q.success(m==="fr"?"Tâche mise à jour avec succès":"Task updated successfully"),o?.(),a()}catch(N){q.error(N instanceof Error?N.message:"An error occurred while saving the assignment")}finally{C(!1)}},_=!!j.values.taskTitle,f=!!j.values.specialty;return e.jsx(Qe,{open:t,onOpenChange:v=>!v&&a(),children:e.jsxs(Ke,{className:`${rs.dialogContent} ${n||""}`,children:[e.jsxs(lt,{children:[e.jsx(Je,{children:m==="fr"?"Modifier la tâche":"Edit Task"}),e.jsx($t,{children:m==="fr"?"Modifiez les détails de cette tâche interne.":"Modify the details for this internal task."})]}),e.jsx(Qs,{...j,children:e.jsxs("div",{className:rs.formContainer,children:[e.jsxs("div",{className:rs.specialtySection,children:[e.jsxs(oe,{name:"specialty",children:[e.jsx(pe,{children:m==="fr"?"Spécialité":"Specialty"}),e.jsx(re,{children:e.jsx(Pe,{placeholder:m==="fr"?"ex: Plomberie, Excavation":"e.g., Plumbing, Excavation",value:j.values.specialty||"",onChange:v=>x(M=>({...M,specialty:v.target.value}))})}),e.jsx(_e,{})]}),e.jsxs(oe,{name:"assignedUserId",children:[e.jsx(pe,{children:m==="fr"?"Employé assigné":"Assigned employee"}),e.jsxs(nt,{value:j.values.assignedUserId!=null?String(j.values.assignedUserId):"__none",onValueChange:v=>x(M=>({...M,assignedUserId:v==="__none"?null:Number(v)})),disabled:p,children:[e.jsx(re,{children:e.jsx(at,{children:e.jsx(it,{placeholder:m==="fr"?"Sélectionner un employé":"Select employee"})})}),e.jsxs(ot,{children:[e.jsx(J,{value:"__none",children:m==="fr"?"Non assigné":"Unassigned"}),i?.map(v=>e.jsx(J,{value:String(v.id),children:v.displayName},v.id))]})]}),y&&e.jsxs("div",{className:rs.checkboxItem,style:{marginTop:"var(--spacing-2)"},children:[e.jsx(St,{id:"applyToSeries",checked:d,onCheckedChange:v=>b(v===!0)}),e.jsx("label",{htmlFor:"applyToSeries",style:{fontSize:"0.875rem"},children:m==="fr"?"Appliquer à toute la série":"Apply to the whole series"})]}),S&&e.jsx("p",{className:rs.helperText,style:{marginTop:"var(--spacing-1)"},children:m==="fr"?"Changer l'employé mettra également à jour le responsable de la tournée (sauf si l'on n'applique pas à la série).":"Changing the employee will also update the route's assigned user (unless not applied to the series)."}),e.jsx(_e,{})]})]}
2),e.jsx(Ni,{startDate:j.values.startDate,endDate:j.values.endDate||j.values.startDate,compact:!0}),e.jsx(Di,{form:j,onSubmit:D,formId:"edit-task-assignment-form",photos:g,onPhotosChange:l})]})}),e.jsxs(Ct,{children:[e.jsx(L,{variant:"outline",onClick:a,disabled:r,children:c("assignment_cancel")}),e.jsx(L,{type:"submit",form:"edit-task-assignment-form",disabled:!_||!f||r,className:rs.submitButton,children:r?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:rs.loaderIcon}),m==="fr"?"Enregistrement...":"Saving..."]}):m==="fr"?"Enregistrer":"Save Changes"})]})]})})},Vg="_taskDialogContent_kezgv_1",Yg="_taskScrollableContent_kezgv_8",Qg="_taskDialogHeader_kezgv_14",Kg="_taskDialogTitle_kezgv_18",Jg="_taskDetailsGrid_kezgv_25",Xg="_taskDetailItem_kezgv_40",Zg="_taskIcon_kezgv_48",e_="_taskSection_kezgv_55",t_="_taskSectionTitle_kezgv_60",s_="_taskDescriptionText_kezgv_70",n_="_taskMetadataGrid_kezgv_77",a_="_taskMetadataItem_kezgv_89",i_="_completeButton_kezgv_97",o_="_completedBadge_kezgv_108",r_="_spin_kezgv_115",l_="_taskDialogFooter_kezgv_124",be={taskDialogContent:Vg,taskScrollableContent:Yg,taskDialogHeader:Qg,taskDialogTitle:Kg,taskDetailsGrid:Jg,taskDetailItem:Xg,taskIcon:Zg,taskSection:e_,taskSectionTitle:t_,taskDescriptionText:s_,taskMetadataGrid:n_,taskMetadataItem:a_,completeButton:i_,completedBadge:o_,spin:r_,taskDialogFooter:l_},Ii=({isOpen:t,onClose:a,assignment:s,canEditPlanning:n,onEdit:o,onDelete:i,onMarkCompleted:p,onActionSuccess:c})=>{const{t:m,language:h}=ye(),r=(S,D)=>h==="fr"?S:D,{authState:C}=Vt(),g=On(),l=Ms(),[k,j]=u.useState(!1);if(!s)return null;const x=()=>{a(),g(`/dashboard/geolocalisation?tab=routes&routeId=${s.routeId}`)},d=S=>{if(!S)return"";switch(S.toLowerCase()){case"high":return r("Haute","High");case"medium":return r("Moyenne","Medium");case"low":return r("Basse","Low");default:return S}},b=S=>{if(!S)return"";switch(S.toLowerCase()){case"pending":return r("En attente","Pending");case"in_progress":case"in-progress":return r("En cours","In Progress");case"completed":return r("Terminé","Completed");case"cancelled":return r("Annulé","Cancelled");default:return S}},y=async()=>{if(p){p();return}j(!0);try{await l.mutateAsync({id:s.id,taskStatus:"completed"}),q.success(r("Tâche marquée comme complétée","Task marked as completed")),c?.(),a()}catch{q.error(m("common_error_occurred"))}finally{j(!1)}};return e.jsx(Qe,{open:t,onOpenChange:S=>!S&&a(),children:e.jsxs(Ke,{onClick:S=>S.stopPropagation(),className:be.taskDialogContent,children:[e.jsx(lt,{className:be.taskDialogHeader,children:e.jsx(Je,{className:be.taskDialogTitle,children:s.taskTitle||m("clients_untitled_task")})}),e.jsxs("div",{className:be.taskScrollableContent,children:[e.jsxs("div",{className:be.taskDetailsGrid,children:[e.jsxs("div",{className:be.taskDetailItem,children:[e.jsx(hs,{className:be.taskIcon}),e.jsxs("span",{children:[new Date(s.startDate).toLocaleString(r("fr-CA","en-CA"),{dateStyle:"medium",timeStyle:s.allDay?void 0:"short"}),s.endDate&&e.jsxs(e.Fragment,{children:[" - ",new Date(s.endDate).toLocaleString(r("fr-CA","en-CA"),{dateStyle:"medium",timeStyle:s.allDay?void 0:"short"})]})]})]}),s.taskLocation&&e.jsxs("div",{className:be.taskDetailItem,children:[e.jsx(An,{className:be.taskIcon}),e.jsx("span",{children:s.taskLocation})]})]}),s.taskDescription&&e.jsxs("div",{className:be.taskSection,children:[e.jsxs("h3",{className:be.taskSectionTitle,children:[e.jsx(To,{className:be.taskIcon}),r("Description","Description")]}),e.jsx("p",{className:be.taskDescriptionText,children:s.taskDescription})]}),e.jsxs("div",{className:be.taskSection,children:[e.jsxs("h3",{className:be.taskSectionTitle,children:[e.jsx(Ea,{className:be.taskIcon}),r("Informations","Information")]}),e.jsxs("div",{className:be.taskMetadataGrid,children:[s.taskPriority&&e.jsxs("div",{className:be.taskMetadataItem,children:[e.jsx(ss,{className:be.taskIcon}),e.jsxs("span",{children:[r("Priorité","Priority"),": ",e.jsx(wt,{variant:s.taskPriority==="high"?"destructive":s.taskPriority==="low"?"secondary":"warning",children:d(s.taskPriority)})]})]}),s.taskStatus&&e.jsxs("div",{className:be.taskMetadataItem,children:[e.jsx(ra,{className:be.taskIcon}),e.jsxs("span",{children:[r("Statut","Status"),": ",e.jsx(wt,{variant:s.taskStatus==="completed"?"success":"default",children:b(s.taskStatus)})]})]}),s.specialty&&e.jsxs("div",{className:be.taskMetadataItem,children:[e.jsx(an,{className:be.taskIcon}),e.jsxs("span",{children:[r("Spécialité","Specialty"),": ",e.jsx(wt,{variant:"outline",children:s.specialty})]})]}),s.isPinned&&e.jsxs("div",{className:be.taskMetadataItem,children:[e.jsx(mn,{className:be.taskIcon}),e.jsx("span",{children:r("Ãpinglé","Pinned")})]}),s.isHalfDay&&s.halfDayPeriod&&e.jsxs("div",{className:be.taskMetadataItem,children:[s.halfDayPeriod==="morning"?e.jsx(Fs,{className:be.taskIcon}):e.jsx(Us,{className:be.taskIcon}),e.jsx("span",{children:s.halfDayPeriod==="morning"?m("clients_morning"):m("clients_afternoon")})]}),s.notes&&e.jsxs("div",{className:be.taskMetadataItem,children:[e.jsx(Pa,{className:be.taskIcon}),e.jsxs("span",{children:[m("clients_notes"),": ",s.notes]})]})]})]})]}),e.jsxs(Ct,{className:be.taskDialogFooter,children:[C.type==="authenticated"&&(s.taskStatus!=="completed"?e.jsxs(L,{variant:"outline",size:"sm",onClick:y,disabled:k,className:be.completeButton,children:[k?e.jsx(ts,{size:16,className:be.spin}):e.jsx(Io,{size:16}),r("Marquer complété","Mark completed")]}):e.jsxs(L,{variant:"outline",size:"sm",disabled:!0,className:be.completedBadge,children:[e.jsx(ra,{size:16}),r("Complété","Completed")]})),s.routeId!=null&&e.jsxs(L,{variant:"outline",size:"sm",onClick:x,children:[e.jsx(La,{size:16}),m("clients_view_route")]}),n&&e.jsxs(e.Fragment,{children:[e.jsxs(L,{variant:"outline",size:"sm",onClick:o,children:[e.jsx(Bn,{size:16}),m("common_edit")]}),e.jsxs(L,{variant:"destructive",size:"sm",onClick:i,children:[e.jsx(ps,{size:16}),m("common_delete")]})]})]})]})})};function c_(t,a){if(!t)return!1;const s=t.trim().toLowerCase();return!!(s.includes("note")||a[s]===!1)}const d_=({isOpen:t,onClose:a,originalAssignment:s,onSuccess:n})=>{const{t:o}=ye(),{data:i}=_s(),p=ci(),[c,m]=u.useState(""),[h,r]=u.useState(!0),[C,g]=u.useState(s.startDate?new Date(s.startDate):void 0),[l,k]=u.useState(s.endDate?new Date(s.endDate):void 0);u.useEffect(()=>{t&&(m(""),r(!0),g(s.startDate?new Date(s.startDate):void 0),k(s.endDate?new Date(s.endDate):void 0))},[t,s]);const j=async()=>
2{if(!c){q.error(o("clients_select_specialty_required"));return}const d=h?new Date(s.startDate):C,b=h?s.endDate?new Date(s.endDate):null:l;if(d)try{await p.mutateAsync({clientId:s.clientId,quoteId:s.quoteId,startDate:d,endDate:b,specialty:c,isPinned:s.isPinned,isHalfDay:s.isHalfDay,halfDayPeriod:s.halfDayPeriod,allDay:s.allDay,taskTitle:s.taskTitle,taskDescription:s.taskDescription,taskLocation:s.taskLocation,taskPriority:s.taskPriority,taskStatus:s.taskStatus,notes:null}),q.success(o("common_success")),n?.(),a()}catch(y){console.error("Failed to create additional assignment",y),q.error(o("common_error_occurred"))}},x=i&&!("error"in i)&&i.specialties?i.specialties.filter(d=>d!==s.specialty):[];return e.jsx(Qe,{open:t,onOpenChange:d=>!d&&a(),children:e.jsxs(Ke,{children:[e.jsxs(lt,{children:[e.jsx(Je,{children:o("clients_additional_assignment_title")}),e.jsx($t,{children:o("clients_additional_assignment_description")})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"var(--spacing-4)",marginTop:"var(--spacing-4)"},children:[e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"var(--spacing-2)"},children:[e.jsx("label",{style:{fontSize:"0.875rem",fontWeight:500},children:o("clients_select_specialty_required")}),e.jsxs(nt,{value:c,onValueChange:m,children:[e.jsx(at,{children:e.jsx(it,{placeholder:o("clients_select_specialty_required")})}),e.jsx(ot,{children:e.jsx(Xo,{children:x.length>0?x.map(d=>e.jsx(J,{value:d,children:d},d)):e.jsx("div",{style:{padding:"var(--spacing-2)",fontSize:"0.875rem",color:"var(--muted-foreground)"},children:"No other specialties available"})})})]})]}),e.jsx(Ni,{startDate:h?s.startDate:C,endDate:h?s.endDate??void 0:l??void 0,compact:!0}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"var(--spacing-2)"},children:[e.jsx(St,{id:"same-dates",checked:h,onCheckedChange:d=>r(d===!0)}),e.jsx("label",{htmlFor:"same-dates",style:{fontSize:"0.875rem",cursor:"pointer"},children:o("clients_same_dates")})]}),!h&&e.jsxs("div",{style:{display:"flex",gap:"var(--spacing-4)",flexWrap:"wrap"},children:[e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"var(--spacing-2)",flex:1,minWidth:"150px"},children:[e.jsx("label",{style:{fontSize:"0.875rem",fontWeight:500},children:"Start Date"}),e.jsxs(on,{children:[e.jsx(rn,{asChild:!0,children:e.jsx(L,{variant:"outline",style:{justifyContent:"flex-start",textAlign:"left"},children:C?De(C,"P",{locale:zt}):"Select date"})}),e.jsx(ln,{removeBackgroundAndPadding:!0,children:e.jsx(En,{mode:"single",selected:C,onSelect:g,initialFocus:!0})})]})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"var(--spacing-2)",flex:1,minWidth:"150px"},children:[e.jsx("label",{style:{fontSize:"0.875rem",fontWeight:500},children:"End Date"}),e.jsxs(on,{children:[e.jsx(rn,{asChild:!0,children:e.jsx(L,{variant:"outline",style:{justifyContent:"flex-start",textAlign:"left"},children:l?De(l,"P",{locale:zt}):"Select date"})}),e.jsx(ln,{removeBackgroundAndPadding:!0,children:e.jsx(En,{mode:"single",selected:l,onSelect:k,disabled:d=>C?d<C:!1,initialFocus:!0})})]})]})]})]}),e.jsxs(Ct,{children:[e.jsx(L,{variant:"secondary",onClick:a,children:o("common_cancel")}),e.jsx(L,{onClick:j,disabled:!c||p.isPending,children:p.isPending?"Creating...":e.jsxs(e.Fragment,{children:[e.jsx(Hn,{size:16,style:{marginRight:"8px"}})," ",o("clients_create_additional_assignment")]})})]})]})})},u_=({assignment:t,compactMode:a,companyProfile:s,onSelectForSwap:n,onOpenSpecialtyDialog:o,onOpenAdditionalAssignmentDialog:i,onOpenDeleteDialog:p,styles:c})=>{const[m,h]=u.useState(!1),{t:r}=ye(),C=Ms(),g=On(),{data:l}=Yt(),{onActionSuccess:k}=zn(),{registerChange:j}=Qt(),x=new Date(t.startDate),d=Za(x,6),{data:b}=Es({startDate:m?x.toISOString():"",endDate:m?d.toISOString():"",specialty:t.specialty||void 0}),y=async O=>{O.stopPropagation(),await C.mutateAsync({id:t.id,isPinned:!t.isPinned}),k?.()},S=async O=>{O.stopPropagation(),await C.mutateAsync({id:t.id,isHalfDay:!1,halfDayPeriod:null}),k?.()},D=async O=>{O.stopPropagation(),await C.mutateAsync({id:t.id,isHalfDay:!0,halfDayPeriod:"morning"}),k?.()},_=async O=>{O.stopPropagation(),await C.mutateAsync({id:t.id,isHalfDay:!0,halfDayPeriod:"afternoon"}),k?.()},f=async(O,w)=>{O.stopPropagation(),await C.mutateAsync({id:t.id,specialty:w}),k?.()},v=O=>{if(O.stopPropagation(),!l)return;const w=new Date(t.startDate),B=t.endDate?new Date(t.endDate):w,I=xn(B,1,l.avoidWeekends,l.avoidHolidays);j({type:"client-assignment",payload:{id:t.id,startDate:t.startDate,endD
2ate:I},originalSnapshot:t,description:`${r("clients_extend_one_day")}: ${t.firstName} ${t.lastName}`},b?.assignments)},M=O=>{if(O.stopPropagation(),!l)return;const w=new Date(t.startDate),B=t.endDate?new Date(t.endDate):w;if(Ns(w,B))return;const I=Ci(B,1,l.avoidWeekends,l.avoidHolidays),F=I<w?w:I,de=Ns(w,F)?null:F;j({type:"client-assignment",payload:{id:t.id,startDate:t.startDate,endDate:de},originalSnapshot:t,description:`${r("clients_reduce_one_day")}: ${t.firstName} ${t.lastName}`},b?.assignments)},W=t.endDate&&!Ns(new Date(t.startDate),new Date(t.endDate)),N=O=>{O.stopPropagation(),h(!1),g(`/dashboard/geolocalisation?tab=routes&routeId=${t.routeId}`)};return e.jsx("div",{className:`${c.actions} ${a?c.actionsCompact:""}`,onClick:O=>O.stopPropagation(),children:e.jsxs(oi,{open:m,onOpenChange:h,children:[e.jsx(ri,{asChild:!0,children:e.jsx(L,{variant:"ghost",size:"icon-sm","aria-label":r("clients_more_actions"),children:e.jsx(Eo,{size:16})})}),e.jsxs(li,{align:"end",children:[e.jsx(mt,{onClick:y,children:t.isPinned?e.jsxs(e.Fragment,{children:[e.jsx(Po,{size:16,style:{marginRight:"8px"}}),r("clients_unpin_date")]}):e.jsxs(e.Fragment,{children:[e.jsx(mn,{size:16,style:{marginRight:"8px"}}),r("clients_pin_date")]})}),e.jsxs(mt,{onClick:n,children:[e.jsx(Oa,{size:16,style:{marginRight:"8px"}}),r("clients_select_for_swap")]}),e.jsx(Xt,{}),t.isHalfDay?e.jsxs(e.Fragment,{children:[t.halfDayPeriod==="morning"&&e.jsxs(mt,{onClick:_,children:[e.jsx(Us,{size:16,style:{marginRight:"8px"}}),r("clients_switch_to_afternoon")]}),t.halfDayPeriod==="afternoon"&&e.jsxs(mt,{onClick:D,children:[e.jsx(Fs,{size:16,style:{marginRight:"8px"}}),r("clients_switch_to_morning")]}),e.jsxs(mt,{onClick:S,children:[e.jsx(hs,{size:16,style:{marginRight:"8px"}}),r("clients_set_full_day")]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(mt,{onClick:D,children:[e.jsx(Fs,{size:16,style:{marginRight:"8px"}}),r("clients_set_as_morning")]}),e.jsxs(mt,{onClick:_,children:[e.jsx(Us,{size:16,style:{marginRight:"8px"}}),r("clients_set_as_afternoon")]})]}),e.jsx(Xt,{}),e.jsxs(mt,{onClick:v,children:[e.jsx(wa,{size:16,style:{marginRight:"8px"}}),r("clients_extend_one_day")]}),W&&e.jsxs(mt,{onClick:M,children:[e.jsx($o,{size:16,style:{marginRight:"8px"}}),r("clients_reduce_one_day")]}),e.jsx(Xt,{}),e.jsxs(Kr,{children:[e.jsxs(Jr,{children:[e.jsx(an,{size:16,style:{marginRight:"8px"}}),r("clients_change_specialty")]}),e.jsxs(Xr,{children:[e.jsxs(mt,{onClick:o,children:[e.jsx(Bn,{size:16,style:{marginRight:"8px"}}),r("clients_enter_new_specialty")]}),e.jsx(Xt,{}),e.jsxs(mt,{onClick:O=>f(O,null),children:[e.jsx(qt,{size:16,style:{marginRight:"8px"}}),r("clients_no_specialty")]}),s&&!("error"in s)&&s.specialties&&s.specialties.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Xt,{}),s.specialties.map(O=>e.jsxs(mt,{onClick:w=>f(w,O),children:[e.jsx(an,{size:16,style:{marginRight:"8px"}}),O]},O))]})]})]}),e.jsx(Xt,{}),e.jsx(Xt,{}),t.routeId!=null&&e.jsxs(mt,{onClick:N,children:[e.jsx(La,{size:16,style:{marginRight:"8px"}}),r("clients_view_route")]}),e.jsxs(mt,{onClick:i,children:[e.jsx(Hn,{size:16,style:{marginRight:"8px"}}),r("clients_create_additional_assignment")]}),e.jsx(Xt,{}),e.jsxs(mt,{onClick:p,className:c.deleteMenuItem,children:[e.jsx(ps,{size:16,style:{marginRight:"8px"}}),r("clients_delete_assignment")]})]})]})})},p_="_block_8lfty_1",m_="_compact_8lfty_31",h_="_content_8lfty_38",g_="_clientName_8lfty_42",__="_notDraggable_8lfty_50",f_="_pinned_8lfty_58",x_="_fullyPaid_8lfty_70",y_="_selectedForSwap_8lfty_89",j_="_pulse_8lfty_1",D_="_swapTarget_8lfty_95",v_="_isStart_8lfty_105",C_="_isEnd_8lfty_110",k_="_isContinuation_8lfty_115",b_="_dragging_8lfty_119",w_="_dragHandle_8lfty_133",S_="_dragDisabled_8lfty_155",N_="_details_8lfty_164",T_="_titleRow_8lfty_173",I_="_pinIcon_8lfty_191",E_="_meta_8lfty_207",P_="_articleCount_8lfty_214",$_="_quoteContainer_8lfty_220",M_="_quoteText_8lfty_231",A_="_assignedUserBadge_8lfty_237",B_="_c
2ompactAssignedUserBadge_8lfty_253",H_="_assignedUserAvatar_8lfty_263",L_="_specialtyBadge_8lfty_269",O_="_periodBadge_8lfty_281",R_="_morningBadge_8lfty_291",F_="_afternoonBadge_8lfty_297",U_="_calendarIcon_8lfty_303",q_="_internalBadge_8lfty_307",z_="_actions_8lfty_319",W_="_actionsCompact_8lfty_348",G_="_deleteMenuItem_8lfty_364",Ie={block:p_,compact:m_,content:h_,clientName:g_,notDraggable:__,pinned:f_,fullyPaid:x_,selectedForSwap:y_,pulse:j_,swapTarget:D_,isStart:v_,isEnd:C_,isContinuation:k_,dragging:b_,dragHandle:w_,dragDisabled:S_,details:N_,titleRow:T_,pinIcon:I_,meta:E_,articleCount:P_,quoteContainer:$_,quoteText:M_,assignedUserBadge:A_,compactAssignedUserBadge:B_,assignedUserAvatar:H_,specialtyBadge:L_,periodBadge:O_,morningBadge:R_,afternoonBadge:F_,calendarIcon:U_,internalBadge:q_,actions:z_,actionsCompact:W_,deleteMenuItem:G_},yn=({assignment:t,isStart:a,isEnd:s,isContinuation:n,className:o,compactMode:i,onDraftDeleted:p})=>{const{t:c,language:m}=ye(),h=(te,kt)=>m==="fr"?te:kt,[r,C]=u.useState(!1),[g,l]=u.useState(!1),[k,j]=u.useState(!1),[x,d]=u.useState(!1),[b,y]=u.useState(!1),[S,D]=u.useState(!1),[_,f]=u.useState(""),{authState:v}=Vt(),{hasPermission:M}=gs(),W=Ms(),N=je.useMemo(()=>{if(v.type!=="authenticated")return!1;const te=v.user.role;return["admin","company","owner"].includes(te)?!0:M("planning.edit")},[v,M]),O=Wn(),{removeAssignmentDraft:w}=Qt(),{data:B}=_s(),{data:I}=Yt(),{colorsMap:F,clientVisibleLowerMap:de}=Gs(),fe=u.useRef(null),{selectedAssignment:T,isSwapMode:A,selectForSwap:Y,executeSwap:E}=Un(),{onActionSuccess:$}=zn(),R=new Date(t.startDate),Q=Za(R,6),{data:se}=Es({startDate:x?R.toISOString():"",endDate:x?Q.toISOString():"",specialty:t.specialty||void 0}),ae=ki(x?t:null,se?.assignments||[],I),[{isDragging:Z},ve,ue]=hn(()=>({type:ht.CLIENT_ASSIGNMENT,item:()=>(console.log("[DRAG START] Assignment:",t.id,t.firstName,t.lastName),{type:"CLIENT_ASSIGNMENT",id:t.id,originalDate:t.startDate}),canDrag:!t.isPinned&&N,collect:te=>({isDragging:te.isDragging()})}),[t.id,t.startDate,t.isPinned,t.firstName,t.lastName,N]),He=A&&T?.id===t.id,P=A&&T&&T.id!==t.id,z=t.clientId===null,V=[Ie.block,a&&Ie.isStart,s&&Ie.isEnd,n&&Ie.isContinuation,Z&&Ie.dragging,t.isPinned&&Ie.pinned,He&&Ie.selectedForSwap,P&&Ie.swapTarget,i&&Ie.compact,t.isSoldePaid&&!z&&Ie.fullyPaid,!N&&Ie.notDraggable,o].filter(Boolean).join(" "),Se=!a||!s,ut=z?t.taskTitle||c("clients_untitled_task"):i?`${t.firstName||""} ${t.lastName?t.lastName.charAt(0).toUpperCase()+".":""}`.trim():`${t.firstName||""} ${t.lastName||""}`.trim(),_t=z&&t.routeId==null?"#64748b":t.specialty&&F[t.specialty]?F[t.specialty]:"var(--primary)",ft=c_(t.specialty,de),Le=te=>{if(te?.stopPropagation(),!Z){if(A&&T&&T.id!==t.id){E(t.id);return}z?l(!0):C(!0)}},U=()=>C(!1),Ce=te=>{te.stopPropagation(),Y({id:t.id,clientId:t.clientId,firstName:t.firstName,lastName:t.lastName,taskTitle:t.taskTitle,startDate:t.startDate,endDate:t.endD
2ate})},Xe=te=>{te.stopPropagation(),f(""),j(!0)},ie=te=>{te.stopPropagation(),y(!0)},ze=async()=>{_.trim()&&(await W.mutateAsync({id:t.id,specialty:_.trim()}),j(!1),f(""),$?.())},xs=()=>{j(!1),f("")},Kt=te=>{if(te.stopPropagation(),t.id<0){confirm(c("clients_confirm_delete"))&&(w(t.id),q.success(c("common_success")),C(!1),console.log("[DRAFT DELETE] Calling onDraftDeleted callback, exists:",!!p),p?.());return}d(!0)},ys=async(te,kt)=>{try{await O.mutateAsync({assignmentId:t.id,cascadeMode:te,sendNotifications:kt,specialty:t.specialty}),q.success(c("common_success")),d(!1),C(!1),$?.()}catch(Rt){console.error("Failed to delete assignment:",Rt),q.error(c("common_error_occurred"))}},Nt=()=>{d(!1)},Lt=je.useCallback(te=>{ve(te),ue(te)},[ve,ue]),Ot=te=>te.split(" ").map(kt=>kt[0]).join("").substring(0,2).toUpperCase(),Gt=()=>{if(!t.isHalfDay||!t.halfDayPeriod)return null;const te=t.halfDayPeriod==="morning",kt=te?Fs:Us,Rt=c(te?"clients_morning":"clients_afternoon"),ns=te?Ie.morningBadge:Ie.afternoonBadge;return e.jsxs(bs,{children:[e.jsx(ws,{asChild:!0,children:e.jsxs(wt,{variant:"outline",className:`${Ie.periodBadge} ${ns}`,children:[e.jsx(kt,{size:12}),e.jsx("span",{children:Rt})]})}),e.jsx(Ss,{children:c("clients_assignment_period_only",{label:Rt.toLowerCase()})})]})};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:Lt,className:V,onClick:Le,style:{backgroundColor:_t},"data-calendar-block":"true",role:"button",tabIndex:0,onKeyDown:te=>{(te.key==="Enter"||te.key===" ")&&(te.preventDefault(),Le())},children:[e.jsxs("div",{className:Ie.content,children:[!i&&e.jsx("div",{className:`${Ie.dragHandle} ${t.isPinned?Ie.dragDisabled:""}`,children:e.jsx(pn,{size:16})}),e.jsxs("div",{className:Ie.details,children:[e.jsxs("div",{className:Ie.titleRow,children:[e.jsx("span",{className:Ie.clientName,children:ut}),t.assignedUserName&&i&&e.jsxs(bs,{children:[e.jsx(ws,{asChild:!0,children:e.jsx("div",{className:`${Ie.assignedUserBadge} ${Ie.compactAssignedUserBadge}`,children:t.assignedUserAvatarUrl?e.jsx("img",{src:t.assignedUserAvatarUrl,alt:"",className:Ie.assignedUserAvatar}):e.jsx("span",{children:Ot(t.assignedUserName)})})}),e.jsx(Ss,{children:t.assignedUserName})]}),!i&&t.isPinned&&e.jsxs(bs,{children:[e.jsx(ws,{asChild:!0,children:e.jsx("div",{className:Ie.pinIcon,children:e.jsx(mn,{size:14})})}),e.jsx(Ss,{children:c("clients_fixed_date_tooltip")})]})]}),!i&&e.jsxs("div",{className:Ie.meta,children:[t.assignedUserName&&e.jsxs(bs,{children:[e.jsx(ws,{asChild:!0,children:e.jsx("div",{className:Ie.assignedUserBadge,children:t.assignedUserAvatarUrl?e.jsx("img",{src:t.assignedUserAvatarUrl,alt:"",className:Ie.assignedUserAvatar}):e.jsx("span",{children:Ot(t.assignedUserName)})})}),e.jsx(Ss,{children:t.assignedUserName})]}),e.jsx("span",{className:Ie.articleCount,children:t.quoteId&&t.quoteLineItemCount>0?`${t.quoteLineItemCount} ${t.quoteLineItemCount>1?c("clients_articles"):c("clients_article")}`:`${t.activeProjectCount} ${t.activeProjectCount>1?h("projets","projects"):h("projet","project")}`}),t.specialty&&e.jsxs(wt,{variant:"outline",className:Ie.specialtyBadge,children:[e.jsx(an,{size:12}),e.jsx("span",{children:t.specialty})]}),ft&&e.jsxs(bs,{children:[e.jsx(ws,{asChild:!0,children:e.jsxs(wt,{variant:"outline",className:Ie.internalBadge,children:[e.jsx(Mo,{size:12}),e.jsx("span",{children:h("Interne","Internal")})]})}),e.jsx(Ss,{children:h("Ce créneau n'apparaît pas dans le portail client.","This slot does not appear in the client portal.")})]}),Gt(),Se&&e.jsx(Ps,{size:14,className:Ie.calendarIcon})]})]})]}),N&&e.jsx(u_,{assignment:t,compactMode:i,companyProfile:B,onSelectForSwap:Ce,onOpenSpecialtyDialog:Xe,onOpenAdditionalAssignmentDialog:ie,onOpenDeleteDialog:Kt,styles:Ie})]}),!z&&r&&e.jsx(Si,{isOpen:r,onClose:U,assignment:t,onDraftDeleted:p}),e.jsx(Qe,{open:k,onOpenChange:j,children:e.jsxs(Ke,{onClick:te=>te.stopPropagation(),onPointerDownOutside:te=>te.stopPropagation(),onInteractOutside:te=>te.stopPropagation(),children:[e.jsx(lt,{children:e.jsx(Je,{children:c("clients_new_specialty")})}),e.jsx("div",{style:{marginTop:"var(--spacing-4)",marginBottom:"var(--spacing-4)"},children:e.jsx(Pe,{ref:fe,type:"text",placeholder:c("clients_specialty_name"),value:_,onCh
2ange:te=>f(te.target.value),onKeyDown:te=>{te.key==="Enter"&&(te.preventDefault(),ze())}})}),e.jsxs(Ct,{children:[e.jsx(L,{variant:"secondary",onClick:xs,children:c("common_cancel")}),e.jsx(L,{onClick:ze,disabled:!_.trim(),children:c("common_save")})]})]})}),e.jsx(bi,{isOpen:x,onClose:Nt,assignment:t,preview:ae,onConfirm:ys,isLoading:O.isPending}),e.jsx(d_,{isOpen:b,onClose:()=>y(!1),originalAssignment:t,onSuccess:()=>$?.()}),e.jsx(Ti,{isOpen:S,onClose:()=>D(!1),assignment:t,onSuccess:()=>{$?.(),D(!1)}}),e.jsx(Ii,{isOpen:g,onClose:()=>l(!1),assignment:t,canEditPlanning:N,onEdit:()=>{l(!1),D(!0)},onDelete:te=>{l(!1),Kt(te)},onActionSuccess:$})]})},V_="_block_i10im_1",Y_="_compact_i10im_25",Q_="_accentBar_i10im_30",K_="_content_i10im_39",J_="_icon_i10im_47",X_="_label_i10im_53",Cs={block:V_,compact:Y_,accentBar:Q_,content:K_,icon:J_,label:X_},jn=({tasks:t,onClick:a,compactMode:s=!1,lang:n="fr",className:o})=>{const i=t.length;if(i===0)return null;const p=n==="fr"?`${i} tâche${i>1?"s":""}`:`${i} task${i>1?"s":""}`,c=m=>{m.stopPropagation(),a(m)};return e.jsxs("div",{className:`${Cs.block} ${s?Cs.compact:""} ${o||""}`,onClick:c,role:"button",tabIndex:0,onKeyDown:m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),c(m))},children:[e.jsx("div",{className:Cs.accentBar}),e.jsxs("div",{className:Cs.content,children:[e.jsx(Ln,{size:s?12:14,className:Cs.icon}),e.jsx("span",{className:Cs.label,children:p})]})]})},Z_="_sheetContent_100ma_1",ef="_header_100ma_8",tf="_headerIcon_100ma_14",sf="_taskList_100ma_26",nf="_taskItem_100ma_36",af="_taskMain_100ma_70",of="_taskHeader_100ma_76",rf="_taskTitle_100ma_83",lf="_priorityIndicator_100ma_91",cf="_priorityIconUrgent_100ma_99",df="_priorityIconHigh_100ma_100",uf="_priorityIconLow_100ma_101",pf="_priorityIconNormal_100ma_102",mf="_taskMeta_100ma_104",hf="_metaItem_100ma_113",gf="_categoryDot_100ma_119",_f="_categoryName_100ma_126",ff="_taskFooter_100ma_130",xf="_statusBadge_100ma_136",yf="_emptyState_100ma_142",jf="_emptyIcon_100ma_153",Fe={sheetContent:Z_,header:ef,headerIcon:tf,taskList:sf,taskItem:nf,taskMain:af,taskHeader:of,taskTitle:rf,priorityIndicator:lf,priorityIconUrgent:cf,priorityIconHigh:df,priorityIconLow:uf,priorityIconNormal:pf,taskMeta:mf,metaItem:hf,categoryDot:gf,categoryName:_f,taskFooter:ff,statusBadge:xf,emptyState:yf,emptyIcon:jf},Df=({isOpen:t,onClose:a,tasks:s,date:n,lang:o="fr",onTaskClick:i})=>{const p=o==="fr"?zt:Vs,c=u.useMemo(()=>[...s].sort((l,k)=>{const j=l.createdAt?new Date(l.createdAt).getTime():0,x=k.createdAt?new Date(k.createdAt).getTime():0;return j-x}),[s]),m=De(n,"EEEE d MMMM yyyy",{locale:p}),h=m.charAt(0).toUpperCase()+m.slice(1),r=l=>{switch(l?.toLowerCase()||"normal"){case"urgent":case"critical":return e.jsx(ss,{size:14,className:Fe.priorityIconUrgent});case"high":return e.jsx(Ho,{size:14,className:Fe.priorityIconHigh});case"low":return e.jsx(Bo,{size:14,className:Fe.priorityIconLow});default:return e.jsx(Ao,{size:14,className:Fe.priorityIconNormal})}},C=l=>{switch(l?.toLowerCase()||"pending"){case"completed":case"done":return"success";case"in_progress":case"active":return"secondary";case"blocked":case"delayed":return"destructive";default:return"outline"}},g=l=>l?De(new Date(l),"HH:mm",{locale:p}):"";return e.jsx(Ua,{open:t,onOpenChange:l=>!l&&a(),children:e.jsxs(qa,{side:"right",className:Fe.sheetContent,children:[e.jsxs(za,{className:Fe.header,children:[e.jsx("div",{className:Fe.headerIcon,children:e.jsx(Ps,{size:20})}),e.jsx(Wa,{children:h}),e.jsxs(Zo,{children:[s.length," ",o==="fr"?"tâches prévues":"tasks scheduled"]})]}),e.jsx("div",{className:Fe.taskList,children:c.length===0?e.jsxs("div",{className:Fe.emptyState,children:[e.jsx(Ln,{size:48,className:Fe.emptyIcon}),e.jsx("p",{children:o==="fr"?"Aucune tâche pour ce jour":"No tasks for this day"})]}):c.map(l=>e.jsxs("div",{className:Fe.taskItem,onClick:()=>i?.(l),role:i?"button":void 0,tabIndex:i?0:void 0,children:[e.jsxs("div",{className:Fe.taskMain,children:[e.jsxs("div",{className:Fe.taskHeader,children:[e.jsx("h4",{className:Fe.taskTitle,children:l.title}),l.taskPriority&&e.jsx("div",{className:Fe.priorityIndicator,title:`Priority: ${l.taskPriority}`,children:r(l.taskPriority)})]}),e.jsxs("div",{className:Fe.taskMeta,children:[l.createdAt&&e.jsxs("div",{className:Fe.metaItem,children:[e.jsx(hs,{size:12}),e.jsxs("span",{children:[o==="fr"?"Créé à ":"Created at"," ",g(l.createdAt)]})]}),l.taskCategory&&e.jsxs("div",{className:Fe.metaItem,children:[e.jsx("span",{className:Fe.categoryDot}),e.jsx("span",{className:Fe.categoryName,children:l.taskCategory})]})]})]}),e.jsx("div",{className:Fe.taskFooter,children:l.taskStatus&&e.jsx(wt,{variant:C(l.taskStatus),className:Fe.statusBadge,children:l.taskStatus})})]},l.id))})]})})},vf="_dayCell_ym5v6_1",Cf="_dayNumber_ym5v6_15",kf="_otherMonth_ym5v6_23",bf="_today_ym5v6_33",wf="_dropTarget_ym5v6_45",Sf="_nonWorkingDay_ym5v6_51",Nf="_weekendDay_ym5v6_57",Tf="_nonWorkingDayIndicator_ym5v6_82",If="_invalidDropTarget_ym5v6_111",Ef="_eventsContainer_ym5v6_117",Pf="_blockedDay_ym5v6_178",$f="_blockIndicator_ym5v6_182",Mf="_blockIndicatorCompany_ym5v6_190",Af="_blockIndicatorClient_ym5v6_194",Bf="_blockIcon_ym5v6_198",Hf="_blockIconCompany_ym5v6_204",Lf="_blockIconCl
2ient_ym5v6_208",Of="_selectableDay_ym5v6_213",dt={dayCell:vf,dayNumber:Cf,otherMonth:kf,today:bf,dropTarget:wf,nonWorkingDay:Sf,weekendDay:Nf,nonWorkingDayIndicator:Tf,invalidDropTarget:If,eventsContainer:Ef,blockedDay:Pf,blockIndicator:$f,blockIndicatorCompany:Mf,blockIndicatorClient:Af,blockIcon:Bf,blockIconCompany:Hf,blockIconClient:Lf,selectableDay:Of},Rf=({day:t,isCurrentMonth:a,isToday:s,isNonWorkingDay:n,isWeekend:o,isBlockedDay:i,blockedInfo:p,eventCount:c,onDrop:m,onClick:h,onDoubleClick:r,lang:C,children:g,selectedClientId:l,isMobile:k,onMobileClientAssign:j})=>{const[x,d]=u.useState(null),{shouldIgnoreNextClickRef:b}=zn(),[{isOver:y,canDrop:S},D]=$s({accept:[ht.SIGNED_QUOTE,ht.CLIENT_ASSIGNMENT,ht.ROUTE_ITEM],drop:M=>{if(console.log("[DROP] Item dropped:",M),console.log("[DROP] Target day:",t),console.log("[DROP] Is non-working day:",n),n||i){q.error(C==="fr"?"Ce jour est indisponible (fermé ou bloqué). Veuillez sélectionner un autre jour.":"This day is unavailable (closed or blocked). Please select another day.");return}m(M,t)},canDrop:()=>!n&&!i,collect:M=>({isOver:M.isOver(),canDrop:M.canDrop()})}),_=je.useCallback(M=>{D(M)},[D]),f=M=>{if(!M.target.closest('[data-calendar-block="true"]')){if(k&&l&&j){if(n||i){q.error(C==="fr"?"Ce jour est indisponible (fermé ou bloqué). Veuillez sélectionner un autre jour.":"This day is unavailable (closed or blocked). Please select another day.");return}j(l,t);return}if(x)clearTimeout(x),d(null),r(t);else{const N=setTimeout(()=>{if(b?.current){console.log("[DayCell] Ignoring click due to recent action"),d(null);return}h(t),d(null)},250);d(N)}}};u.useEffect(()=>()=>{x&&clearTimeout(x)},[x]);const v=[dt.dayCell,!a&&dt.otherMonth,s&&dt.today,o&&dt.weekendDay,n&&dt.nonWorkingDay,y&&!S&&dt.invalidDropTarget,y&&S&&dt.dropTarget,i&&dt.blockedDay,k&&l&&!n&&!i&&dt.selectableDay].filter(Boolean).join(" ");return e.jsxs("div",{ref:_,className:v,onClick:f,children:[i&&p&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:`${dt.blockIndicator} ${p.blockType==="company_block"?dt.blockIndicatorCompany:dt.blockIndicatorClient}`,title:p.clientName||""}),e.jsx("div",{className:`${dt.blockIcon} ${p.blockType==="company_block"?dt.blockIconCompany:dt.blockIconClient}`,title:p.clientName||"",children:p.blockType==="company_block"?e.jsx(Ma,{size:12}):e.jsx(Aa,{size:12})})]}),e.jsx("div",{className:dt.dayNumber,children:De(t,"d")}),n&&e.jsx("div",{className:dt.nonWorkingDayIndicator,children:e.jsx(Sa,{size:14})}),e.jsx("div",{className:dt.eventsContainer,children:g})]})},Ff="_hourlySlot_k3jtw_1",Uf="_nonWorkingSlot_k3jtw_17",qf="_dropTarget_k3jtw_27",zf="_invalidDropTarget_k3jtw_33",Wf="_assignmentsContainer_k3jtw_39",Gf="_emptySlot_k3jtw_46",Vf="_dropIcon_k3jtw_60",ls={hourlySlot:Ff,nonWorkingSlot:Uf,dropTarget:qf,invalidDropTarget:zf,assignmentsContainer:Wf,emptySlot:Gf,dropIcon:Vf},Yf=({day:t,hour:a,assignments:s,isNonWorkingDay:n,onDrop:o,onClick:i,lang:p,className:c,events:m=[],onTaskSummaryClick:h,isAllSpecialtiesView:r})=>{const C=dn(un(t,a),0),[{isOver:g,canDrop:l},k]=$s({accept:[ht.SIGNED_QUOTE,ht.CLIENT_ASSIGNMENT,ht.ROUTE_ITEM],drop:b=>{if(n){q.error(p==="fr"?"Ce jour est en dehors des heures ouvrables. Veuillez sélectionner un jour ouvrable.":"This day is outside business hours. Please select a working day.");return}o(b,C)},canDrop:()=>!n,collect:b=>({isOver:b.isOver(),canDrop:b.canDrop()})}),j=je.useCallback(b=>{k(b)},[k]),x=b=>{if(!b.target.closest('[data-calendar-block="true"]')){if(n){q.error(p==="fr"?"Ce jour est en dehors des heures ouvrables. Veuillez sélectionner un jour ouvrable.":"This day is outside business hours. Please select a working day.");return}i(C)}},d=[ls.hourlySlot,n&&ls.nonWorkingSlot,g&&!l&&ls.invalidDropTarget,g&&l&&ls.dropTarget,c].filter(Boolean).join(" ");return e.jsx("div",{ref:j,className:d,onClick:x,children:s.length>0||m.length>0?e.jsxs("div",{className:ls.assignmentsContainer,children:[s.map(b=>e.jsx(yn,{assignment:b,isStart:!0,isEnd:!0,isContinuation:!1},b.id)),m.length>0&&e.jsx(jn,{tasks:m,compactMode:r,lang:p,onClick:b=>{b.stopPropagation(),h?.()}})]}):e.jsx("div",{className:ls.emptySlot,children:g&&l&&e.jsx(hs,{size:16,className:ls.dropIcon})})})},Qf="_allDaySlot_8li68_1",Kf="_nonWorkingSlot_8li68_19",Jf="_dropTarget_8li68_29",Xf="_invalidDropTarget_8li68_35",Zf="_assignmentsContainer_8li68_41",ex="_emptySlot_8li68_48",tx="_dropIcon_8li68_62",cs={allDaySlot:Qf,nonWorkingSlot:Kf,dropTarget:Jf,invalidDropTarget:Xf,assignmentsContainer:Zf,emptySlot:ex,dropIcon:tx},sx=({day:t,assignments:a,isNonWorkingDay:s,onDrop:n,onClick:o,lang:i,className:p,events:c=[],onTaskSummaryClick:m,isAllSpecialtiesView:h})=>{const r=ge(t),[{isOver:C,canDrop:g},l]=$s({accept:[ht.SIGNED_QUOTE,ht.CLIENT_ASSIGNMENT,ht.ROUTE_ITEM],drop:d=>
2{if(s){q.error(i==="fr"?"Ce jour est en dehors des heures ouvrables. Veuillez sélectionner un jour ouvrable.":"This day is outside business hours. Please select a working day.");return}n(d,r)},canDrop:()=>!s,collect:d=>({isOver:d.isOver(),canDrop:d.canDrop()})}),k=je.useCallback(d=>{l(d)},[l]),j=d=>{if(!d.target.closest('[data-calendar-block="true"]')){if(s){q.error(i==="fr"?"Ce jour est en dehors des heures ouvrables. Veuillez sélectionner un jour ouvrable.":"This day is outside business hours. Please select a working day.");return}o(r)}},x=[cs.allDaySlot,s&&cs.nonWorkingSlot,C&&!g&&cs.invalidDropTarget,C&&g&&cs.dropTarget,p].filter(Boolean).join(" ");return e.jsx("div",{ref:k,className:x,onClick:j,children:a.length>0||c.length>0?e.jsxs("div",{className:cs.assignmentsContainer,children:[a.map(d=>e.jsx(yn,{assignment:d,isStart:!0,isEnd:!0,isContinuation:!1},d.id)),c.length>0&&e.jsx(jn,{tasks:c,compactMode:h,lang:i,onClick:d=>{d.stopPropagation(),m?.()}})]}):e.jsx("div",{className:cs.emptySlot,children:C&&g&&e.jsx(hs,{size:16,className:cs.dropIcon})})})},nx="_calendarGrid_dxgsm_1",ax="_weekdayHeader_dxgsm_36",ix="_timeColumnHeader_dxgsm_46",ox="_allDayLabel_dxgsm_51",rx="_hourLabel_dxgsm_65",lx="_error_dxgsm_89",cx="_weekPlanningColumn_dxgsm_96",dx="_nonWorkingColumn_dxgsm_112",ux="_dropTarget_dxgsm_117",px="_invalidDropTarget_dxgsm_123",Et={calendarGrid:nx,weekdayHeader:ax,timeColumnHeader:ix,allDayLabel:ox,hourLabel:rx,error:lx,weekPlanningColumn:cx,nonWorkingColumn:dx,dropTarget:ux,invalidDropTarget:px},Da=6,mx=21,hx=({day:t,assignments:a,events:s,isNonWorkingDay:n,onDrop:o,onClick:i,lang:p,isAllSpecialtiesView:c,onDraftDeleted:m,onTaskSummaryClick:h})=>{const[{isOver:r,canDrop:C},g]=$s({accept:[ht.SIGNED_QUOTE,ht.CLIENT_ASSIGNMENT,ht.ROUTE_ITEM],drop:x=>{if(n){q.error(p==="fr"?"Ce jour est en dehors des heures ouvrables. Veuillez sélectionner un jour ouvrable.":"This day is outside business hours. Please select a working day.");return}o(x,ge(t))},canDrop:()=>!n,collect:x=>({isOver:x.isOver(),canDrop:x.canDrop()})}),l=je.useCallback(x=>{g(x)},[g]),k=()=>{if(n){q.error(p==="fr"?"Ce jour est en dehors des heures ouvrables. Veuillez sélectionner un jour ouvrable.":"This day is outside business hours. Please select a working day.");return}i(t)},j=[Et.weekPlanningColumn,n&&Et.nonWorkingColumn,r&&!C&&Et.invalidDropTarget,r&&C&&Et.dropTarget].filter(Boolean).join(" ");return e.jsxs("div",{ref:l,className:j,onClick:k,children:[a.map(x=>e.jsx(yn,{assignment:x,isStart:!0,isEnd:!0,isContinuation:!1,compactMode:c,onDraftDeleted:m},`${x.id}-${t.getTime()}`)),s.length>0&&e.jsx(jn,{tasks:s,compactMode:c,lang:p,onClick:x=>{x.stopPropagation(),h()}})]})},gx=({calendarStart:t,calendarEnd:a,currentDate:s,today:n,viewMode:o,visibleAssignments:i,events:p,isFetching:c,error:m,onDrop:h,onDayCl
2ick:r,onDayDoubleClick:C,onEventClick:g,lang:l,selectedClientId:k,isAllSpecialtiesView:j,onDraftDeleted:x,calendarBlocks:d})=>{const[b,y]=je.useState(!1),[S,D]=je.useState([]),[_,f]=je.useState(null),{data:v}=Yt(),M=u.useRef(v);u.useEffect(()=>{M.current=v},[v]);const W=u.useMemo(()=>{if(v?.enabled&&v.startTime&&v.endTime){const R=parseInt(v.startTime.split(":")[0],10),Q=parseInt(v.endTime.split(":")[0],10);if(!isNaN(R)&&!isNaN(Q)&&R<Q){const se=Q-R+1;return Array.from({length:se},(ae,Z)=>Z+R)}}const $=mx-Da+1;return Array.from({length:$},(R,Q)=>Q+Da)},[v]),N=Ws(),O=u.useMemo(()=>{if(o==="day")return[s];if(o==="week"){const $=Tn(s,{weekStartsOn:1}),R=In(s,{weekStartsOn:1});return ga({start:$,end:R})}else return ga({start:t,end:a})},[t,a,s,o]),w=u.useCallback(($,R,Q)=>{if($.allDay)return!1;const se=new Date($.startDate),ae=ge(se),Z=ge(R);return ae.getTime()!==Z.getTime()?!1:_a(se)===Q},[]),B=u.useCallback(($,R)=>$.filter(Q=>Q.allDay&&sn(Q,R,M.current)),[]),I=u.useCallback(($,R,Q)=>$.filter(se=>w(se,R,Q)),[w]),F=u.useCallback(($,R)=>{const Q=ge(new Date($.startDate)),se=$.endDate?ge(new Date($.endDate)):Q,ae=ge(R),Z=ae.getTime()===Q.getTime(),ve=ae.getTime()===se.getTime();return{isStart:Z,isEnd:ve,isContinuation:!Z&&!ve}},[]),de=u.useMemo(()=>o==="day"?{gridTemplateColumns:"80px 1fr",gridTemplateRows:`auto var(--calendar-row-height) repeat(${W.length}, var(--calendar-row-height))`,minHeight:"500px",width:"100%"}:o==="week"?{gridTemplateColumns:"repeat(7, 1fr)",gridTemplateRows:"auto 1fr",minHeight:"400px",width:"100%"}:{gridTemplateColumns:"repeat(7, minmax(0, 1fr))",gridTemplateRows:"auto repeat(6, 1fr)",minHeight:"400px",width:"100%"},[o,W]);if(c)return e.jsx(ne,{style:{flex:1,width:"100%"}});if(m)return e.jsx("p",{className:Et.error,children:l==="fr"?`Erreur de chargement du calendrier: ${m.message}`:`Error loading calendar: ${m.message}`});const fe=()=>o==="day"?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:Et.timeColumnHeader}),e.jsx("div",{className:Et.weekdayHeader,children:De(s,"EEEE d MMMM",{locale:l==="fr"?zt:void 0})})]}):o==="week"?e.jsx(e.Fragment,{children:O.map(($,R)=>e.jsx("div",{className:Et.weekdayHeader,children:De($,"EEE d",{locale:l==="fr"?zt:void 0})},`weekday-${R}`))}):(l==="fr"?["Lun","Mar","Mer","Jeu","Ven","Sam","Dim"]:["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]).map(($,R)=>e.jsx("div",{className:Et.weekdayHeader,children:$},`weekday-${R}`)),T=()=>O.map($=>{const R=De($,"yyyy-MM-dd");let Q=!1,se;const ae=new Date($.getFullYear(),$.getMonth(),$.getDate()).getTime();if(d&&d.length>0)for(const V of d){const Se=new Date(V.startDate),ut=new Date(V.endDate),_t=new Date(Se.getFullYear(),Se.getMonth(),Se.getDate()).getTime(),ft=new Date(ut.getFullYear(),ut.getMonth(),ut.getDate()).getTime();if(ae>=_t&&ae<=ft){Q=!0,se={blockType:V.blockType,clientName:V.clientFirstName||V.clientLastName?`${V.clientFirstName||""} ${V.clientLastName||""}`.trim():void 0};break}}const Z=$.getDay(),ve=Z===0||Z===6,ue=(()=>{const V=M.current;if(!V?.enabled)return!1;const Se={workingDays:V.workDays,avoidWeekends:V.avoidWeekends,avoidHolidays:V.avoidHolidays,startTime:V.startTime,endTime:V.endTime};return!us($,Se)})(),He=i.filter(V=>sn(V,$,M.current)),P=p.filter(V=>{const Se=ge(V.startDatetime),ut=ge(V.endDatetime),_t=ge($);return Se<=_t&&ut>=_t}),z=He.length+(P.length>0?1:0);return e.jsxs(Rf,{day:$,isCurrentMonth:Dr($,s),isToday:Ns($,n),isNonWorkingDay:ue,isWeekend:ve,isBlockedDay:Q,blockedInfo:se,eventCount:z,onDrop:h,onClick:r,onDoubleClick:C,lang:l,selectedClientId:k,isMobile:N,onMobileClientAssign:(V,Se)=>{r(Se)},children:[He.map(V=>{const Se=F(V,$);return e.jsx(yn,{assignment:V,isStart:Se.isStart,isEnd:Se.isEnd,isContinuation:Se.isContinuation,compactMode:j,onDraftDeleted:x},`${V.id}-${R}`)}),P.length>0&&e.jsx(jn,{tasks:P,compactMode:j,lang:l,onClick:()=>{D(P),f($),y(!0)}})]},R)}),A=()=>{const $=[];return $.push(e.jsx("div",{className:Et.allDayLabel,children:l==="fr"?"Journée":"All day"},"all-day-label")),O.forEach(R=>{const Q=De(R,"yyyy-MM-dd"),se=p.filter(ue=>{const He=ge(ue.startDatetime),P=ge(ue.endDatetime),z=ge(R);return He<=z&&P>=z}),ae=se.filter(ue=>{const He=new Date(ue.startDatetime);return ue.allDay||ge(He).getTime()!==ge(R).getTime()}),Z=(()=>{const ue=M.current;if(!ue?.enabled)return!1;const He={workingDays:ue.workDays,avoidWeekends:ue.avoidWeekends,avoidHolidays:ue.avoidHolidays,startTime:ue.startTime,endTime:ue.endTime};return!us(R,He)})(),ve=B(i,R);$.push(e.jsx(sx,{day:R,assignments:ve,events:ae,isAllSpecialtiesView:j,onTaskSummaryClick:()=>{D(se),f(R),y(!0)},isNonWorkingDay:Z,onDrop:h,onClick:r,lang:l},`all-day-${Q}`))}),$},Y=()=>O.map($=>{const R=De($,"yyyy-MM-dd"),Q=(()=>{const Z=M.current;if(!Z?.enabled)return!1;const ve={workingDays:Z.workDays,avoidWeekends:Z.avoidWeekends,avoidHolidays:Z.avoidHolidays,startTime:Z.startTime,endTime:Z.endTime};return!us($,ve)})(),se=i.filter(Z=>sn(Z,$,M.current)),ae=p.filter(Z=>{const ve=ge(Z.startDatetime),ue=ge(Z.endDatetime),He=ge($);return ve<=He&&ue>=He});return e.jsx(hx,{day:$,assignments:se,events:ae,isNonWorkingDay:Q,onDrop:h,onClick:r,lang:l,isAllSpecialtiesView:j,onDraftDeleted:x,onTaskSummaryClick:()=>{D(ae),f($),y(!0)}},`week-col-${R}`)}),E=()=>{const $=[];return $.push(...A()),W.forEach(R=>{$.push(e.jsx("div",{className:Et.hourLabel,children:De(dn(un(new Date,R),0),"HH:mm")},`time-${R}`)),O.forEach(Q=>{const ae=`${De(Q,"yyyy-MM-dd")}-${R}`,Z=p.filter(P=>{const z=ge(P.startDatetime),V=ge(P.endDatetime),Se=ge(Q);return z<=Se&&V>=Se}),ve=Z.filter(P=>{if(P.allDay||ge(new Date(P.startDatetime)).getTime()!==ge(Q).getTime())return!1;const z=new Date(P.startDatetime);return _a(z)===R}),ue=(()=>{const P=M.current;if(!P?.enabled)return!1;const z={workingDays:P.workDays,avoidWeekends:P.avoidWeekends,avoidHolidays:P.avoidHolidays,startTime:P.startTime,endTime:P.endTime};return!us(Q,z)})(),He=I(i,Q,R);$.push(e.jsx(Yf,{day:Q,hour:R,assignments:He,events:ve,isAllSpecialtiesView:j,onTaskSummaryClick:()=>{D(Z),f(Q),y(!0)},isNonWorkingDay:ue,onDrop:h,onClick:r,lang:l},ae))})}),$};return e.jsxs("div",{className:Et.calendarGrid,style:de,"data-view-mode":o,children:[fe(),o==="month"?T():o==="week"?Y():E(),_&&e.jsx(Df,{isOpen:b,onClose:()=>y(!1),tasks:S,date:_,lang:l,onTaskClick:g?$=>{y(!1),g($)}:void 0})]})},_x="_container_t7h0j_1",fx="_sidebar_t7h0j_15",xx="_mainContent_t7h0j_33",yx="_mobileToolbar_t7h0j_43",jx="_mobileToolbarButton_t7h0j_47",Dx="_mobileSheet_t7h0j_70",vx="_mobileClientListContainer_t7h0j_74",Cx="_selectionBanner_t7h0j_81",kx="_selectionBannerContent_t7h0j_101",bx="_selectionBannerText_t7h0j_108",wx="_selectionBannerCancel_t7h0j_116",Ht={container:_x,sidebar:fx,mainContent:xx,mobileToolbar:yx,mobileToolbarButton:jx,mobileSheet:Dx,mobileClientListContainer:vx,selectionBanner:Cx,selectionBannerContent:kx,selectionBannerText:bx,selectionBannerCancel:wx},Ei=({isOpen:t,onOpenChange:a,onQuoteSelect:s,selectedQuoteId:n})=>{const{t:o}=ye();return e.jsx("div",{className:Ht.mobileToolbar,children:e.jsxs(Ua,{open:t,onOpenChange:a,children:[e.jsx(er,{asChild:!0,children:e.jsxs("button",{className:Ht.mobileToolbarButton,"aria-label":o("calendar_view_quotes_list"),children:[e.jsx(Ia,{size:20}),e.jsx("span",{children:o("calendar_quotes")})]})}),e.jsxs(qa,{side:"bottom",className:Ht.mobileSheet,children:[e.jsx(za,{children:e.jsx(Wa,{children:o("calendar_signed_quotes_to_schedule")})}),e.jsx("div",{className:Ht.mobileClientListContainer,children:e.jsx(fi,{onQuoteSelect:s,selectedQuoteId:n})})]})]})})},Sx=({selectedQuote:t,onCancel:a})=>{const{t:s}=ye();return t?e.jsx("div",{className:Ht.selectionBanner,children:e.jsxs("div",{className:Ht.selectionBannerContent,children:[e.jsx("span",{className:Ht.selectionBannerText,children:s("calendar_select_day_to_schedule",{projectName:t.projectName||s("calendar_unnamed_project"),clientName:`${t.clientFirstName} ${t.clientLastName}`})}),e.jsx("button",{className:Ht.selectionBannerCancel,onClick:a,"aria-label":s("assignment_cancel"),children:s("assignment_cancel")})]})}):null},Nx="_modalContent_o304n_1",Tx="_form_o304n_18",Ix="_dateRow_o304n_24",Ex="_checkboxRow_o304n_36",Px="_checkboxLabel_o304n_42",Hs={modalContent:Nx,form:Tx,dateRow:Ix,checkboxRow:Ex,checkboxLabel:Px}
2,$x=Ee({title:X().min(1,"Title is required"),description:X().optional(),startDatetime:X().min(1,"Start date is required"),endDatetime:X().min(1,"End date is required"),location:X().optional(),isWeatherDependent:$e().default(!1)}).refine(t=>t.startDatetime&&t.endDatetime?new Date(t.endDatetime)>=new Date(t.startDatetime):!0,{message:"End date must be after start date",path:["endDatetime"]}),Mx=({event:t,isOpen:a,onClose:s,onSuccess:n})=>{const{t:o,language:i}=ye(),{updateEvent:p,isLoading:c}=hi(),{data:m,isLoading:h}=Ka({calendarEventId:t?.id}),r=_r(),C=fr(),[g,l]=u.useState([]),[k,j]=u.useState(!1),x=S=>{const D=new Date(S),_=D.getTimezoneOffset()*6e4;return new Date(D.getTime()-_).toISOString().slice(0,16)},d=Ys({schema:$x,defaultValues:{title:"",description:"",startDatetime:"",endDatetime:"",location:"",isWeatherDependent:!1}});u.useEffect(()=>{a||l([]),t&&a&&d.setValues({title:t.title,description:t.description||"",startDatetime:x(t.startDatetime),endDatetime:x(t.endDatetime),location:t.location||"",isWeatherDependent:t.isWeatherDependent||!1})},[t,a,d.setValues]);const b=async S=>{if(t)try{if(await p({eventId:t.id,title:S.title,description:S.description||null,startDatetime:new Date(S.startDatetime),endDatetime:new Date(S.endDatetime),location:S.location||null,isWeatherDependent:S.isWeatherDependent}),g.length>0){j(!0);try{await Promise.all(g.map(D=>r.mutateAsync({calendarEventId:t.id,base64Image:D.base64,caption:D.caption||void 0,photoType:D.photoType})))}catch(D){console.error("Failed to upload some photos",D)}j(!1)}n&&n(),l([]),s()}catch(D){console.error("Failed to update event:",D)}},y={title:i==="fr"?"Modifier l'événement":"Edit Event",eventTitle:i==="fr"?"Titre":"Title",description:"Description",startDate:i==="fr"?"Date de début":"Start Date",endDate:i==="fr"?"Date de fin":"End Date",location:i==="fr"?"Lieu":"Location",weatherDependent:i==="fr"?"Dépendant de la météo":"Weather Dependent",cancel:i==="fr"?"Annuler":"Cancel",save:i==="fr"?"Enregistrer":"Save Changes",saving:i==="fr"?"Enregistrement...":"Saving...",photos:i==="fr"?"Photos (optionnel)":"Photos (optional)",addPhotos:i==="fr"?"Ajouter des photos":"Add Photos",caption:i==="fr"?"Légende":"Caption",before:i==="fr"?"Avant":"Before",after:i==="fr"?"Après":"After",general:i==="fr"?"Général":"General",deleteConfirm:i==="fr"?"Ãtes-vous sûr de vouloir supprimer cette photo ?":"Are you sure you want to delete this photo?",uploading:i==="fr"?"Téléchargement...":"Uploading..."};return e.jsx(Qe,{open:a,onOpenChange:S=>!S&&s(),children:e.jsxs(Ke,{className:Hs.modalContent,children:[e.jsx(lt,{children:e.jsx(Je,{children:y.title})}),e.jsx(Qs,{...d,children:e.jsxs("form",{onSubmit:d.handleSubmit(b),className:Hs.form,children:[e.jsxs(oe,{name:"title",children:[e.jsx(pe,{children:y.eventTitle}),e.jsx(re,{children:e.jsx(Pe,{value:d.values.title,onChange:S=>d.setValues(D=>({...D,title:S.target.value})),placeholder:y.eventTitle})}),e.jsx(_e,{})]}),e.jsxs(oe,{name:"description",children:[e.jsx(pe,{children:y.description}),e.jsx(re,{children:e.jsx(cn,{value:d.values.description||"",onChange:S=>d.setValues(D=>({...D,description:S.target.value})),rows:3,placeholder:y.description})}),e.jsx(_e,{})]}),e.jsxs("div",{className:Hs.dateRow,children:[e.jsxs(oe,{name:"startDatetime",children:[e.jsx(pe,{children:y.startDate}),e.jsx(re,{children:e.jsx(Pe,{type:"datetime-local",value:d.values.startDatetime,onChange:S=>d.setValues(D=>({...D,startDatetime:S.target.value}))})}),e.jsx(_e,{})]}),e.jsxs(oe,{name:"endDatetime",children:[e.jsx(pe,{children:y.endDate}),e.jsx(re,{children:e.jsx(Pe,{type:"datetime-local",value:d.values.endDatetime,onChange:S=>d.setValues(D=>({...D,endDatetime:S.target.value}))})}),e.jsx(_e,{})]})]}),e.jsxs(oe,{name:"location",children:[e.jsx(pe,{children:y.location}),e.jsx(re,{children:e.jsx(Pe,{value:d.values.location||"",onChange:S=>d.setValues(D=>({...D,location:S.target.value})),placeholder:y.location})}),e.jsx(_e,{})]}),e.jsx("div",{className:Hs.checkboxRow,children:e.jsxs(oe,{name:"isWeatherDependent",children:[e.jsx(re,{children:e.jsxs("label",{className:Hs.checkboxLabel,children:[e.jsx(St,{checked:d.values.isWeatherDependent,onCheckedChange:S=>d.setValues(D=>({...D,isWeatherDependent:S===!0}))}),y.weatherDependent]})}),e.jsx(_e,{})]})}),e.jsx(ei,{type:"single",collapsible:!0,children:e.jsxs(ti,{value:"photos",children:[e.jsx(si,{children:y.photos}),e.jsx(ni,{children:e.jsx(Sr,{existingPhotos:m?.photos||[],pendingPhotos:g,onAddPendingPhotos:S=>l(D=>
2[...D,...S]),onUpdatePendingPhoto:(S,D)=>l(_=>_.map(f=>f.id===S?{...f,...D}:f)),onRemovePendingPhoto:S=>l(D=>D.filter(_=>_.id!==S)),onDeleteExistingPhoto:S=>C.mutate(S),labels:y})})]})}),e.jsxs(Ct,{children:[e.jsx(L,{type:"button",variant:"outline",onClick:s,disabled:c||k||C.isPending,children:y.cancel}),e.jsx(L,{type:"submit",disabled:c||k||C.isPending,children:c?y.saving:k?y.uploading:y.save})]})]})})]})})},Ax={none:0,daily:1,every_2_days:2,every_3_days:3,weekly:7,biweekly:14,monthly:30},va=(t,a)=>{const s=new Date(t);return s.setDate(s.getDate()+a),s};function Pi({startDate:t,recurrenceType:a,recurrenceWeeks:s}){const n=[new Date(t)];if(a==="none")return n;if(a==="monthly"){const c=Math.max(1,s);for(let m=1;m<c;m++){const h=new Date(t),r=h.getMonth()+m;h.setMonth(r),h.getDate()!==t.getDate()&&h.setDate(0),n.push(h)}return n}const o=va(t,s*7),i=Ax[a]||7;let p=1;for(;;){const c=va(t,p*i);if(c>=o)break;n.push(c),p++}return n}const Bx="_container_oa5su_1",Hx="_header_oa5su_11",Lx="_dates_oa5su_17",Ox="_revenueBox_oa5su_22",Rx="_revenueRow_oa5su_31",Fx="_revenueLabel_oa5su_38",Ux="_revenueValue_oa5su_42",qx="_durationRow_oa5su_47",zx="_explanation_oa5su_52",It={container:Bx,header:Hx,dates:Lx,revenueBox:Ox,revenueRow:Rx,revenueLabel:Fx,revenueValue:Ux,durationRow:qx,explanation:zx},Wx=({startDate:t,recurrenceType:a,recurrenceWeeks:s,revenueEstimate:n,totalEstimatedMinutes:o,language:i,className:p})=>{const c=(b,y)=>i==="fr"?b:y,{authState:m}=Vt(),h="user"in m?m.user.regionCode:null,r=tr(h).locale,{occurrenceDates:C,occurrenceCount:g,firstDateStr:l,lastDateStr:k}=u.useMemo(()=>{const b=Pi({startDate:t,recurrenceType:a,recurrenceWeeks:s}),y=S=>new Intl.DateTimeFormat(r,{day:"numeric",month:"short",year:"numeric"}).format(S);return{occurrenceDates:b,occurrenceCount:b.length,firstDateStr:y(b[0]),lastDateStr:y(b[b.length-1])}},[t,a,s,r]),j=u.useMemo(()=>!n||n<=0||g===0?null:n/g,[n,g]),x=u.useMemo(()=>!j||o<=0?null:j/(o/60),[j,o]),d=u.useMemo(()=>Zr(o,i),[o,i]);return e.jsxs("div",{className:`${It.container} ${p||""}`,children:[e.jsxs("div",{className:It.header,children:[e.jsx("strong",{children:g})," ",g===1?c("passage sera créé au calendrier","visit will be created in the calendar"):c("passages seront créés au calendrier","visits will be created in the calendar")]}),e.jsxs("div",{className:It.dates,children:[c("Du","From")," ",l," ",c("au","to")," ",k]}),j!==null&&e.jsxs("div",{className:It.revenueBox,children:[e.jsxs("div",{className:It.revenueRow,children:[e.jsx("span",{className:It.revenueLabel,children:c("Revenu par passage â","Revenue per visit â")}),e.jsx("span",{className:It.revenueValue,children:ua(j,h)})]}),x!==null&&e.jsxs("div",{className:It.revenueRow,children:[e.jsx("span",{className:It.revenueLabel,children:c("Revenu horaire â","Hourly revenue â")}),e.jsxs("span",{className:It.revenueValue,children:[ua(x,h),"/",c("h","hr")]})]}),e.jsxs("div",{className:It.durationRow,children:[c("Durée sur place","Time on site"),": ",d]}),e.jsx("div",{className:It.explanation,children:c("Estimation basée sur la valeur des contrats rattachés aux arrêts.","Estimate based on the value of contracts attached to the stops.")})]})]})},Gx=Ee({specialty:X().trim().min(2,"Specialty name must be at least 2 characters.").max(50,"Specialty name cannot exceed 50 characters."),color:X().regex(/^#[0-9a-fA-F]{6}$/,"Color must be a valid hex code in #RRGGBB format.").optional(),isTaskBased:$e().optional().default(!1),clientVisible:$e().optional()}),Vx=async(t,a)=>{const s=Gx.parse(t),n=await fetch("/_api/specialties/create",{method:"POST",body:K.stringify(s),...a,headers:{"Content-Type":"application/json"}}),o=await n.text();if(!n.ok)try{const i=K.parse(o);throw new Error(i.error||"Failed to create specialty")}catch(i){throw new Error(i instanceof Error?i.message:`Request failed with status ${n.status}`)}return K.parse(o)},Yx=()=>{const t=gt(),{t:a,language:s}=ye();return Ve({mutationFn:n=>Vx(n),onSuccess:n=>{t.invalidateQueries({queryKey:ir}),t.invalidateQueries({queryKey:["companyProfile"]}),n.created?q.success(s==="fr"?`Corps de métier "${n.specialty}" créé.`:`Trade "${n.specialty}" created.`):q.info(s==="fr"?`Le corps de métier "${n.specialty}" existe déjà .`:`The trade "${n.specialty}" already exists.`)},onError:n=>{q.error(s==="fr"?`Ãchec de la création : ${n.message}`:`Creation failed: ${n.message}`)}})},Ca=["#3b82f6","#ef4444","#22c55e","#eab308","#8b5cf6","#f97316","#14b8a6","#ec4899","#6366f1","#06b6d4","#d946ef","#84cc16"],ks=t=>{let a=0;for(let n=0;n<t.length;n++)a=t.charCodeAt(n)+((a<<5)-a),a=a&a;const s=Math.abs(a)%Ca.length;return Ca[s]},Qx="_dialogContent_19xtx_1",Kx="_dialogDescription_19xtx_5",Jx="_createSpecialtyBlock_19xtx_11",Xx="_colorInput_19xtx_22",Zx="_helperText_19xtx_29",ey="_form_19xtx_35",ty="_grid2_19xtx_42",sy="_halfDayContainer_19xtx_48",ny="_checkboxItem_19xtx_58",ay="_halfDaySelect_19xtx_68",iy="_recurrenceContainer_19xtx_73",oy="_recurrenceSelect_19xtx_79",ry="_weeksInput_19xtx_84",ly="_loaderIcon_19xtx_89",cy="_summaryInfo_19xtx_96",dy="_weeksHelpText_19xtx_100",uy="_seasonWarning_19xtx_107",st={dialogContent:Qx,dialogDescription:Kx,createSpecialtyBlock:Jx,colorInput:Xx,helperText:Zx,form:ey,grid2:ty,halfDayContainer:sy,checkboxItem:ny,halfDaySelect:ay,recurrenceContainer:iy,recurrenceSelect:oy,weeksInput:ry,loaderIcon:ly,summaryInfo:cy,weeksHelpText:dy,seasonWarning:uy},py=({isOpen:t,onClose:a,routeId:s,routeName:n,stopCount:o,initialDate:i,onSuccess:p})=>{const{language:c}=ye(),{mutateAsync:m,isPending:h}=Wc(),{canViewRoutePrices:r,isResolvingRoutePrices:C}=el(),{data:g}=_s(),{colorsMap:l}=Gs(),{data:k}=Ks(),{mutateAsync:j,isPending:x}=Yx(),[d,b]=u.useState(!1),[y,S]=u.useState(""),[D,_]=u.useState(""),[f,v]=u.useState(!1),[M,W]=u.useState(!1),[N,O]=u.useState(!1),w=c==="fr",B={title:w?"Planifier la route":"Schedule Route",route:"Route",stops:w?"arrêts":"stops",startDate:w?"Date de début":"Start Date",specialty:w?"Spécialité":"Specialty",recurrence:w?"Récurrence":"Recurrence",weeks:w?"Nombre de semaines":"Number of weeks",months:w?"Nombre de mois":"Number of months",weeksHelp:w?"Durée de la période de récurrence : la route sera répétée selon la fréquence choisie pendant ce nombre de semaines.":"Length of the recurrence period: the route will repeat at the chosen frequency for this number of weeks.",monthsHelp:w?"Durée de la période de récurrence : la route sera répétée une fois par mois pendant ce nombre de mois.":"Length of the recurrence period: the route will repeat once a month for this number of months.",halfDay:w?"Demi-journée":"Half-day",period:w?"Période":"Period",morning:w?"Matin":"Morning",afternoon:w?"Après-midi":"Afternoon",notes:"Notes",cancel:w?"Annuler":"Cancel",submit:w?"Planifier":"Schedule",creating:w?"Planification...":"Scheduling...",reqDate:w?"Date requise":"Date is required",reqSpecialty:w?"Spécialité requise":"Specialty is required",reqPeriod:w?"Veuillez choisir une période":"Please select a period",reqWeeks:w?"Veuillez entrer un nombre de semaines (1-52)":"Please enter a number of weeks (1-52)",reqMonths:w?"Veuillez entrer un nombre de mois (1-12)":"Please enter a number of months (1-12)",recNone:w?"Aucune récurrence":"No recurrence",recDaily:w?"Chaque jour":"Every day",recEvery2:w?"Aux 2 jours":"Every 2 days",recEvery3:w?"Aux 3 jours":"Every 3 days",recWeekly:w?"Chaque semaine":"Every week",recBiweekly:w?"Aux 2 semaines":"Every 2 weeks",recMonthly:w?"Chaque mois":"Every month",assignedEmployee:w?"Employé assigné":"Assigned employee",unassigned:w?"Non assigné":"Unassigned",selectEmployee:w?"Sélectionner un employé":"Select employee",fromRoute:w?"Employé de la tournée":"From the route",willBeCreated:w?"sera créé":"will be created",createSpecialty:w?"Créer un corps de métier":"Create specialty",specialtyName:w?"Nom du corps de métier":"Specialty name",save:w?"Enregistrer":"Save"},I=w?"Tournée":"Route",F=g?.specialties||[],de=F.some(P=>P.toLowerCase()===I.toLowerCase()),fe=de?F.find(P=>P.toLowerCase()===I.toLowerCase()):I,T=u.useMemo(()=>Ee({startDate:X().min(1,B.reqDate),specialty:X().min(1,B.reqSpecialty),assignedUserId:Me().nullable().optional(),recurrenceType:Ye(["none","daily","every_2_days","every_3_days","weekly","biweekly","monthly"]),recurrenceWeeks:Me().min(1).max(52,B.reqWeeks).optional(),isHalfDay:$e(),halfDayPeriod:Ye(["am","pm"]).nullable(),notes:X().optional()}).refine(P=>P.isHalfDay?!!P.halfDayPeriod:!0,{message:B.reqPeriod,path:["halfDayPeriod"]}
2).refine(P=>!(P.recurrenceType!=="none"&&(P.recurrenceWeeks===void 0||P.recurrenceWeeks<1||P.recurrenceType==="monthly"&&P.recurrenceWeeks>12||P.recurrenceType!=="monthly"&&P.recurrenceWeeks>52)),P=>({message:P.recurrenceType==="monthly"?B.reqMonths:B.reqWeeks,path:["recurrenceWeeks"]})),[B]),A=Ys({schema:T,defaultValues:{startDate:ce(i).format("YYYY-MM-DD"),specialty:fe,assignedUserId:null,recurrenceType:"none",recurrenceWeeks:4,isHalfDay:!1,halfDayPeriod:null,notes:""}}),{data:Y,isFetching:E}=sr(t?s:0);u.useEffect(()=>{t&&(b(!1),S(""),_(""),W(!1),v(!1),O(!1),A.setValues({startDate:ce(i).format("YYYY-MM-DD"),specialty:fe,assignedUserId:null,recurrenceType:"none",recurrenceWeeks:4,isHalfDay:!1,halfDayPeriod:null,notes:""}))},[t,i.getTime()]),u.useEffect(()=>{t&&g&&A.setValues(P=>(P.specialty==="Route"||P.specialty==="Tournée")&&fe!==P.specialty?{...P,specialty:fe}:P)},[t,g,fe,A.setValues]),u.useEffect(()=>{t&&Y&&Y.route.id===s&&!M&&A.setValues(P=>({...P,assignedUserId:Y.route.assignedUserId}))},[t,Y,s,M,A.setValues]);const $=u.useMemo(()=>{if(!A.values.startDate)return[];try{const P=new Date(`${A.values.startDate}T12:00:00.000Z`);return isNaN(P.getTime())?[]:Pi({startDate:P,recurrenceType:A.values.recurrenceType,recurrenceWeeks:A.values.recurrenceType!=="none"?A.values.recurrenceWeeks??1:1})}catch{return[]}},[A.values.startDate,A.values.recurrenceType,A.values.recurrenceWeeks]),R=$.length>0?$[$.length-1]:null,Q=Y?.contractSeasonEnd,se=Q&&R&&R>new Date(Q),ae=r&&!C&&!!Y&&Y.revenueEstimate!==null&&Y.revenueEstimate>0,Z=async P=>{try{const z={routeId:s,startDate:new Date(`${P.startDate}T12:00:00.000Z`),recurrenceType:P.recurrenceType,recurrenceWeeks:P.recurrenceType!=="none"?P.recurrenceWeeks??1:1,specialty:P.specialty,assignedUserId:P.assignedUserId,isHalfDay:P.isHalfDay,halfDayPeriod:P.isHalfDay?P.halfDayPeriod:null,notes:P.notes||null,allowOutOfSeason:se?N:void 0},V=await m(z);if(V&&V.skippedOutOfSeasonCount>0&&q.info(w?`${V.skippedOutOfSeasonCount} passages ignorés car postérieurs à la fin de saison (${ce(V.seasonEndDate).format("YYYY-MM-DD")}).`:`${V.skippedOutOfSeasonCount} stops skipped because they fall after the season end (${ce(V.seasonEndDate).format("YYYY-MM-DD")}).`),V&&V.conflicts&&V.conflicts.length>0){const Se=V.conflicts.filter(ft=>ft.kind==="employee").length,ut=V.conflicts.filter(ft=>ft.kind==="specialty").length,_t=[];Se>0&&_t.push(w?`${Se} date(s) où l'employé est déjà occupé`:`${Se} date(s) where the employee is already busy`),ut>0&&_t.push(w?`${ut} date(s) en conflit avec un bloc existant du même corps de métier`:`${ut} date(s) conflicting with an existing block of the same specialty`),q.warning(w?`Conflits détectés : ${_t.join(", ")}. La planification a été effectuée quand même.`:`Conflicts detected: ${_t.join(", ")}. Scheduling was done anyway.`)}V&&V.outOfSeasonStops&&V.outOfSeasonStops.count>0&&q.warning(w?`${V.outOfSeasonStops.count} arrêt(s) sortiront de saison avant la dernière occurrence (fin la plus proche : ${ce(V.outOfSeasonStops.earliestSeasonEnd).format("YYYY-MM-DD")}).`:`${V.outOfSeasonStops.count} stop(s) will fall out of season before the last occurrence (earliest season end: ${ce(V.outOfSeasonStops.earliestSeasonEnd).format("YYYY-MM-DD")}).`),p?.(),a()}catch{}},ve=P=>{const z=P.target.value;S(z),f||_(ks(z||"Nouveau"))},ue=P=>{_(P.target.value),v(!0)},He=A.values.specialty&&!F.includes(A.values.specialty)&&A.values.specialty!==I;return e.jsx(Qe,{open:t,onOpenChange:P=>!P&&a(),children:e.jsxs(Ke,{className:st.dialogContent,children:[e.jsxs(lt,{children:[e.jsx(Je,{children:B.title}),e.jsxs($t,{className:st.dialogDescription,children:[e.jsxs("strong",{children:[B.route,":"]})," ",n," ",e.jsx("br",{}),e.jsxs("strong",{children:[B.stops,":"]})," ",o]})]}),e.jsx(Qs,{...A,children:e.jsxs("form",{onSubmit:A.handleSubmit(Z),className:st.form,id:"route-calendar-plan-form",children:[e.jsxs("div",{className:st.grid2,children:[e.jsxs(oe,{name:"startDate",children:[e.jsx(pe,{children:B.startDate}),e.jsx(re,{children:e.jsx(Pe,{type:"date",value:A.values.startDate,onChange:P=>A.setValues(z=>({...z,startDate:P.target.value}))})}),e.jsx(_e,{})]}),e.jsxs(oe,{name:"assignedUserId",children:[e.jsx(pe,{children:B.assignedEmployee}),e.jsxs(nt,{value:A.values.assignedUserId?.toString()||"__empty",onValueChange:P=>{W(!0),A.setValues(z=>({...z,assignedUserId:P==="__empty"?null:parseInt(P,10)}))},children:[e.jsx(re,{children:e.jsx(at,{children:e.jsx(it,{placeholder:B.selectEmployee})})}),e.jsxs(ot,{children:[e.jsx(J,{value:"__empty",children:B.unassigned}),k?.map(P=>e.jsx(J,{value:P.id.toString(),children:P.displayName},P.id))]})]}),Y?.route.assignedUserId===A.values.assignedUserId&&Y?.route.assignedUserId!==null&&e.jsx("div",{className:st.helperText,children:B.fromRoute}),e.jsx(_e,{})]})]}),e.jsxs(oe,{name:"specialty",children:[e.jsx(pe,{children:B.specialty}),e.jsxs(nt,{value:A.values.specialty||"",onValueChange:P=>A.setValues(z=>({...z,specialty:P})),children:[e.jsx(re,{children:e.jsx(at,{children:e.jsx(it,{placeholder:B.specialty})})}),e.jsxs(ot,{children:[!de&&e.jsx(J,{value:I,children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"var(--spacing-2)"},children:[e.jsx("div",{style:{width:12,height:12,borderRadius:"50%",backgroundColor:ks(I)}}),I," ",e.jsxs("span",{style:{opacity:.6,fontSize:"0.8em"},children:["(",B.willBeCreated,")"]})]})}),F.map(P=>e.jsx(J,{value:P,children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"var(--spacing-2)"},children:[e.jsx("div",{style:{width:12,height:12,borderRadius:"50%",backgroundColor:l[P]||ks(P)}}),P]})},P)),He&&e.jsx(J,{value:A.values.specialty,children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"var(--spacing-2)"},children:[e.jsx("div",{style:{width:12,height:12,borderRadius:"50%",backgroundColor:l[A.values.specialty]||ks(A.values.specialty)}}),A.values.specialty]})})]})]}),e.jsx(_e,{}),!d&&e.jsxs(L,{type:"button",variant:"link",size:"sm",onClick:()=>b(!0),style:{padding:0,height:"auto",fontSize:"0.75rem",marginTop:"var(--spacing-1)",display:"inline-block"},children:["+ ",B.createSpecialty]}
2),d&&e.jsxs("div",{className:st.createSpecialtyBlock,children:[e.jsx(Pe,{placeholder:B.specialtyName,value:y,onChange:ve,style:{flex:1}}),e.jsx(Pe,{type:"color",value:D||ks("Nouveau"),onChange:ue,className:st.colorInput}),e.jsx(L,{type:"button",size:"sm",disabled:x||y.trim().length<2,onClick:async()=>{const P=await j({specialty:y.trim(),color:D||ks(y.trim()),isTaskBased:!1,clientVisible:!0});A.setValues(z=>({...z,specialty:P.specialty})),b(!1),S(""),_(""),v(!1)},children:x?e.jsx(ts,{className:st.loaderIcon}):B.save}),e.jsx(L,{type:"button",variant:"ghost",size:"sm",onClick:()=>b(!1),children:B.cancel})]})]}),e.jsxs("div",{className:st.halfDayContainer,children:[e.jsxs(oe,{name:"isHalfDay",className:st.checkboxItem,children:[e.jsx(re,{children:e.jsx(St,{id:"isHalfDay",checked:A.values.isHalfDay,onCheckedChange:P=>{A.setValues(z=>({...z,isHalfDay:P===!0,halfDayPeriod:P===!0?z.halfDayPeriod:null}))}})}),e.jsx(pe,{htmlFor:"isHalfDay",children:B.halfDay})]}),A.values.isHalfDay&&e.jsxs(oe,{name:"halfDayPeriod",className:st.halfDaySelect,children:[e.jsxs(nt,{value:A.values.halfDayPeriod??"",onValueChange:P=>A.setValues(z=>({...z,halfDayPeriod:P==="am"||P==="pm"?P:null})),children:[e.jsx(re,{children:e.jsx(at,{children:e.jsx(it,{placeholder:B.period})})}),e.jsxs(ot,{children:[e.jsx(J,{value:"am",children:B.morning}),e.jsx(J,{value:"pm",children:B.afternoon})]})]}),e.jsx(_e,{})]})]}),e.jsxs("div",{className:st.recurrenceContainer,children:[e.jsxs(oe,{name:"recurrenceType",className:st.recurrenceSelect,children:[e.jsx(pe,{children:B.recurrence}),e.jsxs(nt,{value:A.values.recurrenceType,onValueChange:P=>A.setValues(z=>{let V=z.recurrenceWeeks;return P==="monthly"&&V&&V>12&&(V=12),{...z,recurrenceType:P,recurrenceWeeks:V}}),children:[e.jsx(re,{children:e.jsx(at,{children:e.jsx(it,{placeholder:B.recurrence})})}),e.jsxs(ot,{children:[e.jsx(J,{value:"none",children:B.recNone}),e.jsx(J,{value:"daily",children:B.recDaily}),e.jsx(J,{value:"every_2_days",children:B.recEvery2}),e.jsx(J,{value:"every_3_days",children:B.recEvery3}),e.jsx(J,{value:"weekly",children:B.recWeekly}),e.jsx(J,{value:"biweekly",children:B.recBiweekly}),e.jsx(J,{value:"monthly",children:B.recMonthly})]})]}),e.jsx(_e,{})]}),A.values.recurrenceType!=="none"&&e.jsxs(oe,{name:"recurrenceWeeks",className:st.weeksInput,children:[e.jsx(pe,{children:A.values.recurrenceType==="monthly"?B.months:B.weeks}),e.jsx(re,{children:e.jsx(Pe,{type:"number",min:1,max:A.values.recurrenceType==="monthly"?12:52,value:A.values.recurrenceWeeks??"",onChange:P=>A.setValues(z=>({...z,recurrenceWeeks:parseInt(P.target.value,10)||1}))})}),e.jsx("div",{className:st.weeksHelpText,children:A.values.recurrenceType==="monthly"?B.monthsHelp:B.weeksHelp}),e.jsx(_e,{})]})]}),se&&Q&&e.jsxs("div",{className:st.seasonWarning,children:[e.jsxs("p",{children:[e.jsx("strong",{children:w?"Attention :":"Warning:"})," ",w?`La dernière occurrence dépasse la date de fin de saison du contrat (${ce(Q).format("YYYY-MM-DD")}). Les passages suivants ne seront pas créés.`:`The last occurrence goes beyond the contract season end date (${ce(Q).format("YYYY-MM-DD")}). Later occurrences won't be created.`]}),e.jsxs("div",{className:st.checkboxItem,style:{marginTop:"var(--spacing-2)"},children:[e.jsx(St,{id:"allowOutOfSeason",checked:N,onCheckedChange:P=>O(P===!0)}),e.jsx("label",{htmlFor:"allowOutOfSeason",style:{fontSize:"0.875rem"},children:w?"Planifier même après la fin de saison du contrat":"Schedule even after contract season end"})]})]}),e.jsxs(oe,{name:"notes",children:[e.jsx(pe,{children:B.notes}),e.jsx(re,{children:e.jsx(cn,{placeholder:"...",value:A.values.notes,onChange:P=>A.setValues(z=>({...z,notes:P.target.value})),rows:3})}),e.jsx(_e,{})]})]})}),e.jsx(Wx,{startDate:isNaN(new Date(`${A.values.startDate}T12:00:00.000Z`).getTime())?new Date:new Date(`${A.values.startDate}T12:00:00.000Z`),recurrenceType:A.values.recurrenceType,recurrenceWeeks:A.values.recurrenceType!=="none"?A.values.recurrenceWeeks??1:1,revenueEstimate:ae?Y.revenueEstimate:null,totalEstimatedMinutes:ae?Y.totalEstimatedMinutes:0,language:c==="fr"?"fr":"en",className:st.summaryInfo}),e.jsxs(Ct,{children:[e.jsx(L,{variant:"outline",onClick:a,disabled:h,children:B.cancel}),e.jsx(L,{type:"submit",form:"route-calendar-plan-form",disabled:h,children:h?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:st.loaderIcon}),B.creating]}):B.submit})]})]})})},my=({className:t,selectedSpecialty:a,selectedAssignedUserId:s,isTaskBasedSpecialty:n,controlledCurrentDate:o,onDateChange:i,viewMode:p="month",controlledSelectedDate:c,onSelectedDateChange:m,highlightedQuoteId:h,isMobileClientListOpen:r,setIsMobileClientListOpen:C,onOpenSpecialtyManager:g})=>{const{t:l,language:k}=ye(),j=Ws(),x=j?Ga:xr,d=j?{enableMouseEvents:!0,delayTouchStart:120}:void 0,[b,y]=u.useState(!1),[S,D]=u.useState({isOpen:!1}),[_,f]=u.useState(!1),[v,M]=u.useState(null),[W,N]=u.useState(void 0),[O,w]=u.useState(null),[B,I]=u.useState(void 0),[F,de]=u.useState(null),[fe,T]=u.useState(null),[A,Y]=u.useState(null),[E,$]=u.useState(null),[R,Q]=u.useState(null),[se,ae]=u.useState(!1),[Z,ve]=u.useState(null),ue=r!==void 0?r:_,He=C||f,P=c!==void 0?c:v,z=m||M,V=P!==null,[Se,ut]=u.useState(()=>{const G=new Date;return G.setHours(0,0,0,0),G}),ft=Hl(o||Se,p),Le=u.useCallback(G=>{const me=new Date(G);me.setHours(0,0,0,0),i?i(me):ut(me)},[i]),{startDateISO:U,endDateISO:Ce,currentDate:Xe}=ft,{taskCategoryMappings:ie}=Gs(),ze=u.useMemo(()=>({startDate:U,endDate:Ce,specialty:a??void 0,...typeof s=="number"?{assignedUserId:s}:{},...s==="unassigned"?{unassignedOnly:!0}:{}}),[U,Ce,a,s]),xs=u.useMemo(()=>{const G=n&&a&&ie[a]||null;return{startDate:U,endDate:Ce,...G?{taskCategory:G}:{}}}
2,[U,Ce,n,a,ie]),{data:Kt,isFetching:ys,error:Nt}=Es(ze),{data:Lt,isFetching:Ot,error:Gt}=Ya(xs),{data:te}=ql({startDate:U,endDate:Ce,specialty:a??void 0}),{data:kt}=Yt(),Rt=u.useMemo(()=>{if(!E)return{startDate:"",endDate:"",specialty:a??void 0};const G=E.originalStartDate.getFullYear();return{startDate:new Date(G,0,1).toISOString(),endDate:new Date(G,11,31,23,59,59).toISOString(),specialty:a??void 0}},[E,a]),{data:ns,isFetching:$i}=Es(Rt),{deleteEvent:Vn,duplicateEvent:Yn}=hi(),{mutateAsync:Qn}=zl(),{mutateAsync:Kn}=Wl(),{authState:Dn}=Vt(),{hasPermission:Jn}=gs(),pt=u.useMemo(()=>{if(Dn.type!=="authenticated")return!1;const G=Dn.user.role;return["admin","company","owner"].includes(G)?!0:Jn("planning.edit")},[Dn,Jn]),Ze=kt||{enabled:!1,workDays:[1,2,3,4,5],startTime:"08:00",endTime:"17:00",avoidWeekends:!0,avoidHolidays:!0},xt=Kt?.assignments||[],vn=Lt?.events||[],As=te?.blocks||[],Dt=u.useMemo(()=>As.map(G=>({startDate:new Date(G.startDate),endDate:new Date(G.endDate)})),[As]),Cn=u.useMemo(()=>E?E.item.type!=="CLIENT_ASSIGNMENT"?[]:xa(E.item.id,E.originalStartDate,E.assignment.endDate?new Date(E.assignment.endDate):null,E.targetDate,E.newEndDate,xt,Ze,Dt,"subsequent"):[],[E,xt,Ze,Dt]),kn=u.useMemo(()=>!E||!ns?.assignments?[]:E.item.type!=="CLIENT_ASSIGNMENT"?[]:xa(E.item.id,E.originalStartDate,E.assignment.endDate?new Date(E.assignment.endDate):null,E.targetDate,E.newEndDate,ns.assignments,Ze,Dt,"subsequent"),[E,ns,Ze,Dt]),{registerChange:js,pendingChanges:Xn}=Qt(),Bs=u.useMemo(()=>Vl(xt,Xn,a),[xt,Xn,a]),Mi=u.useRef(xt);u.useEffect(()=>{Mi.current=xt},[xt]);const Zn=u.useRef(Bs),Ds=u.useRef(!1);u.useEffect(()=>{Zn.current=Bs},[Bs]);const Ai=u.useCallback((G,me)=>{if(!pt){q.error(k==="fr"?"Vous n'avez pas la permission de modifier la planification.":"You do not have permission to edit the schedule.");return}const ct=new Date(me.getFullYear(),me.getMonth(),me.getDate()).getTime();if(Dt.some(Oe=>{const et=new Date(Oe.startDate.getFullYear(),Oe.startDate.getMonth(),Oe.startDate.getDate()).getTime(),yt=new Date(Oe.endDate.getFullYear(),Oe.endDate.getMonth(),Oe.endDate.getDate()).getTime();return ct>=et&&ct<=yt})){q.error(k==="fr"?"Ce jour est bloqué.":"This day is blocked.");return}if(G.type==="ROUTE_ITEM"){ve({routeId:G.routeId,routeName:G.routeName,stopCount:G.stopCount}),z(me),ae(!0);return}if(n){if(G.type==="SIGNED_QUOTE"){q.error(l("calendar_cannot_assign_task_specialty"));return}z(me),D({isOpen:!0});return}if(G.type==="SIGNED_QUOTE")N(G.clientId),G.quoteId&&G.quoteData?.title&&w({id:G.quoteId,title:G.quoteData.title,lineItemCount:G.quoteData.lineItemCount??0}),z(me),y(!0);else if(G.type==="CLIENT_ASSIGNMENT"){const Oe=Zn.current.find(Jt=>Jt.id===G.id);if(!Oe){q.error(l("calendar_assignment_not_found"));return}if(Oe.isPinned){q.error(l("calendar_cannot_move_pinned"));return}const et=new Date(G.originalDate);let yt=null;if(Oe.endDate){const Jt=new Date(Oe.endDate);if(Ze.avoidWeekends||Ze.avoidHolidays){const bn=qs(et,Jt,Ze.avoidWeekends,Ze.avoidHolidays,Dt);yt=xn(me,Math.max(0,bn-1),Ze.avoidWeekends,Ze.avoidHolidays,Dt)}else{const bn=Jt.getTime()-et.getTime();yt=new Date(me.getTime()+bn)}}if(me.getTime()<et.getTime()){const Jt=et.getTime()-me.getTime(),Xs=Math.round(Jt/(1e3*3600*24));$({item:G,assignment:Oe,targetDate:me,newEndDate:yt,originalStartDate:et,shiftDays:Xs});return}const sa=Oe.endDate?new Date(Oe.endDate):null,na=Ze.avoidWeekends||Ze.avoidHolidays?ui(G.id,et,sa,me,yt,xt,Ze,Dt):di(G.id,et,sa,me,yt,xt);if(na.length>0){const Jt=me.getTime()-et.getTime(),Xs=Math.round(Jt/(1e3*3600*24));Q({item:G,assignment:Oe,targetDate:me,newEndDate:yt,originalStartDate:et,shiftDays:Xs,conflictCount:na.length});return}const aa=k==="fr"?"dd/MM/yyyy":"MM/dd/yyyy";js({type:"client-assignment",payload:{id:G.id,startDate:me,endDate:yt,notes:Oe.notes,specialty:Oe.specialty},originalSnapshot:{...Oe,startDate:et},description:l("calendar_move_description",{name:`${Oe.firstName} ${Oe.lastName}`,fromDate:De(et,aa),toDate:De(me,aa)})},xt,Ze,Dt),q.info(l("calendar_draft_added"))}},[js,z,xt,Ze,Dt,l,n,k,pt]),Bi=u.useCallback(G=>{if(Ds.current){Ds.current=!1;return}if(j&&F){if(!pt)return;if(n){q.error(l("calendar_cannot_assign_task"));return}
2N(F.clientId),F.id&&F.title&&w({id:F.id,title:F.title,lineItemCount:F.lineItemCount??0}),z(G),y(!0);return}z(G)},[z,j,F,n,l,pt]),Hi=u.useCallback(G=>{pt&&(z(G),n?D({isOpen:!0}):y(!0))},[z,n,pt]),Li=u.useCallback(G=>{T(G)},[]),Oi=u.useCallback(()=>{y(!1),N(void 0),w(null),I(void 0),de(null)},[]),Ri=u.useCallback(()=>{z(null),I(void 0),de(null)},[z]),Fi=u.useCallback(()=>{z(null),Ds.current=!0},[z]),Ui=u.useCallback(()=>{z(null)},[z]),qi=u.useCallback(()=>{D({isOpen:!1})},[]),zi=u.useCallback(()=>{D({isOpen:!1})},[]),Wi=u.useCallback((G,me)=>{D({isOpen:!0,hour:G,minute:me})},[]),Gi=u.useMemo(()=>new Date,[]),ea=u.useMemo(()=>new Date,[]),Vi=u.useMemo(()=>P?vn.filter(G=>{const me=ge(G.startDatetime),ct=ge(G.endDatetime),Mt=ge(P);return me<=Mt&&ct>=Mt}):[],[vn,P]),Yi=u.useMemo(()=>{if(!P)return[];const G=ge(P);return As.filter(me=>{const ct=ge(new Date(me.startDate)),Mt=ge(new Date(me.endDate));return ct<=G&&Mt>=G})},[As,P]),Qi=u.useCallback(async G=>{try{await Qn(G),q.success(k==="fr"?"Bloqué/réservé avec succès":"Block/reservation created successfully")}catch{q.error(k==="fr"?"Erreur lors de la création":"Error creating block")}},[Qn,k]),Ki=u.useCallback(async G=>{try{await Kn({blockId:G}),q.success(k==="fr"?"Bloqué/réservé supprimé avec succès":"Block/reservation deleted successfully")}catch{q.error(k==="fr"?"Erreur lors de la suppression":"Error deleting block")}},[Kn,k]),Ji=ys||Ot,Xi=Nt||Gt,ta=u.useCallback(G=>{pt&&j&&(I(G.id),de(G),He(!1))},[j,He,pt]),Zi=u.useCallback(()=>{I(void 0),de(null)},[]),as=u.useCallback(()=>{T(null)},[]),eo=u.useCallback(G=>{Y(G),as()},[as]),to=u.useCallback(()=>{Y(null)},[]),so=u.useCallback(async G=>{try{await Vn({eventId:G}),as()}catch(me){console.error("Failed to delete event:",me)}},[Vn,as]),no=u.useCallback(async G=>{try{await Yn(G),as()}catch(me){console.error("Failed to duplicate event:",me)}},[Yn,as]),ao=u.useCallback(G=>{if(!E)return;const{item:me,assignment:ct,targetDate:Mt,newEndDate:Oe,originalStartDate:et}=E;if(me.type!=="CLIENT_ASSIGNMENT")return;const yt=k==="fr"?"dd/MM/yyyy":"MM/dd/yyyy",Js=G==="month"?Cn:G==="year"?kn:void 0;
2js({type:"client-assignment",payload:{id:me.id,startDate:Mt,endDate:Oe,notes:ct.notes,specialty:ct.specialty},originalSnapshot:{...ct,startDate:et},description:l("calendar_move_description",{name:`${ct.firstName} ${ct.lastName}`,fromDate:De(et,yt),toDate:De(Mt,yt)})},xt,Ze,Dt,Js),$(null),q.info(l("calendar_draft_added"))},[E,Cn,kn,js,xt,Ze,Dt,k,l]),io=u.useCallback(()=>{$(null)},[]),oo=u.useCallback(G=>{if(!R)return;const{item:me,assignment:ct,targetDate:Mt,newEndDate:Oe,originalStartDate:et}=R;if(me.type!=="CLIENT_ASSIGNMENT")return;const yt=k==="fr"?"dd/MM/yyyy":"MM/dd/yyyy",Js=G==="move-only";js({type:"client-assignment",payload:{id:me.id,startDate:Mt,endDate:Oe,notes:ct.notes,specialty:ct.specialty},originalSnapshot:{...ct,startDate:et},description:l("calendar_move_description",{name:`${ct.firstName} ${ct.lastName}`,fromDate:De(et,yt),toDate:De(Mt,yt)}),skipCascade:Js},xt,Ze,Dt),Q(null),q.info(l("calendar_draft_added"))},[R,js,xt,Ze,Dt,k,l]),ro=u.useCallback(()=>{Q(null)},[]),lo=u.useCallback(()=>{ae(!1),ve(null)},[]),co=u.useCallback(()=>{z(null),ae(!1),ve(null)},[z]),uo=u.useCallback(()=>{z(null),Ds.current=!0,setTimeout(()=>{Ds.current=!1},300)},[z]);return e.jsx(Ja,{backend:x,options:d,children:e.jsx(Gl,{value:{onActionSuccess:uo,shouldIgnoreNextClickRef:Ds},children:e.jsxs("div",{className:`${Ht.container} ${t||""}`,children:[pt&&e.jsx("div",{className:Ht.sidebar,children:e.jsx(fi,{onQuoteSelect:ta,selectedQuoteId:B})}),e.jsxs("div",{className:Ht.mainContent,children:[e.jsx(Nr,{currentDate:Xe,onDateChange:Le,lang:k==="fr"?"fr":"en",viewMode:p,hideTitleOnMobile:!0}),j&&pt&&e.jsx(Ei,{isOpen:ue,onOpenChange:He,onQuoteSelect:ta,selectedQuoteId:B}),pt&&e.jsx(Oc,{}),j&&pt&&e.jsx(Sx,{selectedQuote:F,onCancel:Zi}),e.jsx(gx,{calendarStart:ft.calendarStart,calendarEnd:ft.calendarEnd,currentDate:Xe,today:Gi,viewMode:p,visibleAssignments:Bs,events:vn,calendarBlocks:As,isFetching:Ji,error:Xi,onDrop:Ai,onDayClick:Bi,onDayDoubleClick:Hi,onEventClick:Li,lang:k==="fr"?"fr":"en",selectedClientId:j?F?.clientId:void 0,isAllSpecialtiesView:!a,onDraftDeleted:Fi})]}),pt&&e.jsx(Wp,{isOpen:b,onClose:Oi,initialDate:P||ea,preselectedClientId:W||(F?F.clientId:void 0),quoteId:O?.id,quoteTitle:O?.title,quoteLineItemCount:O?.lineItemCount,onSuccess:Ri,defaultSpecialty:a,existingAssignments:Bs,onOpenSpecialtyManager:g}),pt&&a&&e.jsx(vi,{isOpen:S.isOpen,onClose:qi,initialDate:P||ea,specialty:a,onSuccess:zi,initialStartTime:S.hour!==void 0&&S.minute!==void 0?{hour:S.hour,minute:S.minute}:void 0}),P&&e.jsx(bp,{date:P,events:Vi,isOpen:V,onClose:Ui,lang:k==="fr"?"fr":"en",onCreateTask:pt&&a?Wi:void 0,calendarBlocks:Yi,onCreateBlock:pt?Qi:void 0,onDeleteBlock:pt?Ki:void 0,selectedSpecialty:a}),fe&&e.jsx(xi,{event:fe,isOpen:!!fe,onClose:as,onEdit:eo,onDelete:so,onDuplicate:no}),e.jsx(Mx,{event:A,isOpen:!!A,onClose:to}),e.jsx(ic,{isOpen:!!E,onClose:io,onChoice:ao,movedAssignmentName:E?`${E.assignment.firstName} ${E.assignment.lastName}`:"",shiftDays:E?.shiftDays||0,fromDate:E?.originalStartDate||new Date,toDate:E?.targetDate||new Date,monthCount:Cn.length,yearCount:kn.length,isLoadingYearData:$i&&!!E,specialtyName:a||""}),e.jsx(fc,{isOpen:!!R,onClose:ro,onChoice:oo,movedAssignmentName:R?`${R.assignment.firstName} ${R.assignment.lastName}`:"",shiftDays:R?.shiftDays||0,fromDate:R?.originalStartDate||new Date,toDate:R?.targetDate||new Date,conflictCount:R?.conflictCount||0,specialtyName:a||""}),Z&&e.jsx(py,{isOpen:se,onClose:lo,routeId:Z.routeId,routeName:Z.routeName,stopCount:Z.stopCount,initialDate:P||new Date,onSuccess:co})]})})})},hy="_banner_1x3xz_1",gy="_content_1x3xz_33",_y="_iconWrapper_1x3xz_41",fy="_icon_1x3xz_41",xy="_spin_1x3xz_56",yy="_textContainer_1x3xz_65",jy="_title_1x3xz_71",Dy="_subtitle_1x3xz_76",vy="_cancelButton_1x3xz_81",Ft={banner:hy,content:gy,iconWrapper:_y,icon:fy,spin:xy,textContainer:yy,title:jy,subtitle:Dy,cancelButton:vy},Cy=({className:t})=>
2{const{isSwapMode:a,selectedAssignment:s,clearSelection:n,isSwapping:o}=Un(),{t:i}=ye();if(!a||!s)return null;const p=`${s.firstName} ${s.lastName}`;return e.jsxs("div",{className:`${Ft.banner} ${t||""}`,children:[e.jsxs("div",{className:Ft.content,children:[e.jsx("div",{className:Ft.iconWrapper,children:o?e.jsx(ts,{className:`${Ft.icon} ${Ft.spin}`}):e.jsx(Oa,{className:Ft.icon})}),e.jsxs("div",{className:Ft.textContainer,children:[e.jsx("span",{className:Ft.title,children:i("swap_selected_for_exchange",{name:p})}),e.jsx("span",{className:Ft.subtitle,children:i("swap_click_to_swap")})]})]}),e.jsxs("button",{className:Ft.cancelButton,onClick:n,disabled:o,"aria-label":i("swap_cancel"),children:[e.jsx(qt,{size:18}),e.jsx("span",{children:i("swap_cancel")})]})]})},ky="_dialogContent_1srbx_1",by="_content_1srbx_5",wy="_radioGroup_1srbx_12",Sy="_radioOption_1srbx_18",Ny="_radioHeader_1srbx_32",Ty="_radioLabel_1srbx_38",Iy="_radioDescription_1srbx_44",Ey="_notificationSection_1srbx_50",Py="_checkboxWrapper_1srbx_59",bt={dialogContent:ky,content:by,radioGroup:wy,radioOption:Sy,radioHeader:Ny,radioLabel:Ty,radioDescription:Iy,notificationSection:Ey,checkboxWrapper:Py},$y=()=>{const{pendingGaps:t,fillGaps:a,dismissGaps:s,isFillingGaps:n}=Un(),[o,i]=u.useState("pull-up"),[p,c]=u.useState(!1),m=t!==null&&t.length>0;u.useEffect(()=>{m&&(i("pull-up"),c(!1))},[m]);const h=async()=>{o==="pull-up"?await a(p):s()},r=t?.reduce((C,g)=>C+g.gapDays,0)||0;return e.jsx(Qe,{open:m,onOpenChange:C=>!C&&s(),children:e.jsxs(Ke,{className:bt.dialogContent,children:[e.jsxs(lt,{children:[e.jsx(Je,{children:"Un trou a été créé dans l'horaire"}),e.jsx($t,{children:"L'échange a créé un espacement dans le calendrier. Voulez-vous combler ce trou en avançant les assignations suivantes ?"})]}),e.jsxs("div",{className:bt.content,children:[e.jsxs(Fn,{value:o,onValueChange:C=>i(C),className:bt.radioGroup,children:[e.jsxs("div",{className:bt.radioOption,children:[e.jsxs("div",{className:bt.radioHeader,children:[e.jsx(Is,{value:"pull-up",id:"swap-mode-pull-up"}),e.jsx("label",{htmlFor:"swap-mode-pull-up",className:bt.radioLabel,children:"Combler le trou"})]}),e.jsxs("div",{className:bt.radioDescription,children:["Avancer les assignations suivantes de ",r," jour(s)."]})]}),e.jsxs("div",{className:bt.radioOption,children:[e.jsxs("div",{className:bt.radioHeader,children:[e.jsx(Is,{value:"leave-gap",id:"swap-mode-leave-gap"}),e.jsx("label",{htmlFor:"swap-mode-leave-gap",className:bt.radioLabel,children:"Laisser le trou"})]}),e.jsx("div",{className:bt.radioDescription,children:"Ne rien modifier aux autres assignations."})]})]}),o==="pull-up"&&e.jsx("div",{className:bt.notificationSection,children:e.jsxs("div",{className:bt.checkboxWrapper,children:[e.jsx(St,{id:"swap-send-notifications",checked:p,onCheckedChange:C=>c(C===!0)}),e.jsx("label",{htmlFor:"swap-send-notifications",children:"Envoyer des notifications aux clients concernés"})]})})]}),e.jsxs(Ct,{children:[e.jsx(L,{variant:"secondary",onClick:s,disabled:n,children:"Annuler"}),e.jsxs(L,{variant:"primary",onClick:h,disabled:n,children:[n?e.jsx(Ts,{size:"sm"}):null,"Confirmer"]})]})]})})},My="_container_ks5vc_1",Ay="_title_ks5vc_7",By="_description_ks5vc_14",Hy="_tagsContainer_ks5vc_21",Ly="_tag_ks5vc_21",Oy="_noTags_ks5vc_40",Ry="_removeButton_ks5vc_46",Fy="_inputGroup_ks5vc_74",Uy="_inputWrapper_ks5vc_80",qy="_input_ks5vc_74",zy="_dropdown_ks5vc_90",Wy="_error_ks5vc_98",Gy="_suggestionsList_ks5vc_104",Vy="_suggestionGroup_ks5vc_109",Yy="_suggestionGroupHeading_ks5vc_117",Qy="_suggestionItem_ks5vc_126",Ky="_customOption_ks5vc_149",Jy="_emptyMessage_ks5vc_164",Xy="_emptyHint_ks5vc_175",Ue={container:My,title:Ay,description:By,tagsContainer:Hy,tag:Ly,noTags:Oy,removeButton:Ry,inputGroup:Fy,inputWrapper:Uy,input:qy,dropdown:zy,error:Wy,suggestionsList:Gy,suggestionGroup:Vy,suggestionGroupHeading:Yy,suggestionItem:Qy,customOption:Ky,emptyMessage:Jy,emptyHint:Xy},ka=["Plomberie","Ãlectricité","Maçonnerie","Peinture","Couverture","Charpente","Terrassement","Paysagisme","Menuiserie","Climatisation","Chauffage","Isolation","Revêtement de sol","Démolition","Plâtrerie"],Zy=({companyProfile:t,className:a})=>{const{t:s}
2=ye(),[n,o]=u.useState(""),[i,p]=u.useState(null),c=nr(),m=u.useRef(null),h=u.useMemo(()=>t.specialties||[],[t.specialties]),r=n.trim(),C=ka.some(y=>y.toLowerCase()===r.toLowerCase()),g=r.length>=2&&!C&&!h.some(y=>y.toLowerCase()===r.toLowerCase()),l=y=>{const S={name:t.name,address:t.address,phone:t.phone,email:t.email,specialties:y};c.mutate(S)},k=y=>{const S=y.trim();if(p(null),!S){p(s("specialty_error_empty"));return}if(S.length<2){p(s("specialty_error_too_short"));return}if(S.length>50){p(s("specialty_error_too_long"));return}if(h.some(_=>_.toLowerCase()===S.toLowerCase())){p(s("specialty_error_duplicate")),o("");return}const D=[...h,S];l(D),o(""),m.current?.focus()},j=()=>{k(n)},x=y=>{y.key==="Enter"&&n&&(y.preventDefault(),k(n))},d=y=>{const S=h.filter(D=>D!==y);l(S)},b=u.useMemo(()=>{const y=ka.filter(S=>!h.some(D=>D.toLowerCase()===S.toLowerCase()));return n?y.filter(S=>S.toLowerCase().includes(n.toLowerCase())):y},[n,h]);return e.jsxs("div",{className:`${Ue.container} ${a||""}`,children:[e.jsx("h3",{className:Ue.title,children:s("specialty_title")}),e.jsx("p",{className:Ue.description,children:s("specialty_description")}),e.jsx("div",{className:Ue.tagsContainer,children:h.length>0?h.map(y=>e.jsxs(wt,{variant:"secondary",className:Ue.tag,children:[y,e.jsx("button",{onClick:()=>d(y),className:Ue.removeButton,"aria-label":s("specialty_remove_aria",{name:y}),disabled:c.isPending,children:e.jsx(qt,{size:14})})]},y)):e.jsx("p",{className:Ue.noTags,children:s("specialty_no_tags")})}),e.jsxs("div",{className:Ue.inputGroup,children:[e.jsxs("div",{className:Ue.inputWrapper,children:[e.jsx(Pe,{ref:m,type:"text",placeholder:s("specialty_input_placeholder"),value:n,onChange:y=>o(y.target.value),onKeyDown:x,className:Ue.input,disabled:c.isPending,autoComplete:"off"}),e.jsx("div",{className:Ue.dropdown,children:e.jsxs("div",{className:Ue.suggestionsList,children:[g&&e.jsxs("div",{className:Ue.suggestionGroup,children:[e.jsx("div",{className:Ue.suggestionGroupHeading,children:s("specialty_custom")}),e.jsxs("button",{type:"button",onMouseDown:y=>{y.preventDefault(),k(r)},className:`${Ue.suggestionItem} ${Ue.customOption}`,children:[e.jsx(la,{size:16}),s("specialty_add_custom",{value:r})]})]}),b.length>0&&e.jsxs("div",{className:Ue.suggestionGroup,children:[e.jsx("div",{className:Ue.suggestionGroupHeading,children:s("specialty_suggestions")}),b.map(y=>e.jsx("button",{type:"button",onMouseDown:S=>{S.preventDefault(),k(y)},className:Ue.suggestionItem,children:y},y))]}),!g&&b.length===0&&e.jsxs("div",{className:Ue.emptyMessage,children:[e.jsx("p",{children:s("specialty_no_suggestions")}),r&&e.jsx("p",{className:Ue.emptyHint,children:s("specialty_suggestion_hint",{value:r})})]})]})})]}),e.jsxs(L,{onClick:j,disabled:!n||c.isPending,variant:"primary",children:[e.jsx(la,{size:16}),s("specialty_add")]})]}),i&&e.jsx("p",{className:Ue.error,children:i})]})},ej="_container_uq1tt_1",tj="_header_uq1tt_14",sj="_title_uq1tt_20",nj="_description_uq1tt_27",aj="_formContent_uq1tt_33",ij="_fieldRow_uq1tt_39",oj="_settingsGroup_uq1tt_46",rj="_disabledGroup_uq1tt_53",lj="_fieldGroup_uq1tt_58",cj="_daysContainer_uq1tt_64",dj="_dayCheckbox_uq1tt_70",uj="_presetsContainer_uq1tt_76",pj="_presetButtons_uq1tt_83",mj="_weekendDay_uq1tt_89",hj="_timeInputs_uq1tt_96",gj="_advancedOptionsContainer_uq1tt_106",_j="_footer_uq1tt_123",fj="_errorContainer_uq1tt_130",xj="_errorIcon_uq1tt_137",we={container:ej,header:tj,title:sj,description:nj,formContent:aj,fieldRow:ij,settingsGroup:oj,disabledGroup:rj,fieldGroup:lj,daysContainer:cj,dayCheckbox:dj,presetsContainer:uj,presetButtons:pj,weekendDay:mj,timeInputs:hj,advancedOptionsContainer:gj,footer:_j,errorContainer:fj,errorIcon:xj},yj={fr:{title:"Heures d'ouverture",description:"Définissez les heures de travail pour la planification et le report automatique des tâches.",enableFeature:"Activer les heures d'ouverture",workDays:"Jours ouvrables",days:["Dim","Lun","Mar","Mer","Jeu","Ven","Sam"],workHours:"Heures de travail",startTime:"Heure de début",endTime:"Heure de fin",advancedOptions:"Options avancées",avoidWeekends:"Ãviter les weekends lors du report",avoidHolidays:"Ãviter les jours fériés lors du report",save:"Enregistrer les modifications",saving:"Enregistrement...",error:"Impossible de charger les paramètres.",retry:"Réessayer",presets:"Raccourcis",monFri:"Lun-Ven",monSat:"Lun-Sam",allWeek:"7 jours"},en:{title:"Business Hours",description:"Define working hours for automatic task scheduling and rescheduling.",enableFeature:"Enable business hours",workDays:"Work Days",days:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],workHours:"Work Hours",startTime:"Start Time",endTime:"End Time",advancedOptions:"Advanced Options",avoidWeekends:"Avoid weekends on reschedule",avoidHolidays:"Avoid holidays on reschedule",save:"Save Changes",saving:"Saving...",error:"Could not load settings.",retry:"Retry",presets:"Presets",monFri:"Mon-Fri",monSat:"Mon-Sat",allWeek:"7 days"}},jj=({className:t})=>{const{language:a}=ye(),s=yj[a],{data:n,isFetching:o,isError:i,refetch:p}=Yt(),{mutate:c,isPending:m}=or(),{control:h,handleSubmit:r,reset:C,watch:g,setValue:l,formState:{isDirty:k}}=ai({resolver:ii(rr),defaultValues:{enabled:!1,workDays:[1,2,3,4,5],startTime:"08:00",endTime:"17:00",avoidWeekends:!0,avoidHolidays:!1}});u.useEffect(()=>{n&&C(n)},[n,C]);const j=d=>{c(d)},x=g("enabled");return o?e.jsx(Dj,{}):i?e.jsxs("div",{className:`${we.container} ${we.errorContainer} ${t||""}`,children:[e.jsx(ss,{className:we.errorIcon}),e.jsx("p",{children:s.error}),e.jsx(L,{onClick:()=>p(),variant:"outline",size:"sm",children:s.retry})]}):e.jsxs("form",{onSubmit:r(j),className:`${we.container} ${t||""}`,children:[e.jsxs("header",{className:we.header,children:[e.jsx("h3",{className:we.title,children:s.title}),e.jsx("p",{className:we.description,children:s.description})]}),e.jsx(Rn,{}),e.jsxs("div",{className:we.formContent,children:[e.jsxs("div",{className:we.fieldRow,children:[e.jsx(Ut,{htmlFor:"enabled-switch",children:s.enableFeature}),e.jsx(Pt,{name:"enabled",control:h,render:({field:d})=>e.jsx(Ls,{id:"enabled-switch",checked:d.value,onCheckedChange:d.onChange})})]}),e.jsxs("div",{className:`${we.settingsGroup} ${x?"":we.disabledGroup}`,children:[e.jsxs("div",{className:we.fieldGroup,children:[e.jsxs("div",{className:we.presetsContainer,children:[e.jsx(Ut,{children:s.presets}),e.jsxs("div",{className:we.presetButtons,children:[e.jsx(L,{type:"button",variant:"outline",size:"sm",onClick:()=>l("workDays",[1,2,3,4,5],{shouldDirty:!0}),disabled:!x,children:s.monFri}),e.jsx(L,{type:"button",variant:"outline",size:"sm",onClick:()=>l("workDays",[1,2,3,4,5,6],{shouldDirty:!0}),disabled:!x,children:s.monSat}),e.jsx(L,{type:"button",variant:"outline",size:"sm",onClick:()=>l("workDays",[0,1,2,3,4,5,6],{shouldDirty:!0}),disabled:!x,children:s.allWeek})]})]}),e.jsx(Ut,{children:s.workDays}
2),e.jsx("div",{className:we.daysContainer,children:s.days.map((d,b)=>e.jsx(Pt,{name:"workDays",control:h,render:({field:y})=>{const S=y.value.includes(b),D=b===0||b===6,_=f=>{const v=f?[...y.value,b]:y.value.filter(M=>M!==b);y.onChange(v.sort())};return e.jsxs("div",{className:`${we.dayCheckbox} ${D?we.weekendDay:""}`,children:[e.jsx(St,{id:`day-${b}`,checked:S,onCheckedChange:_,disabled:!x}),e.jsx(Ut,{htmlFor:`day-${b}`,children:d})]})}},b))})]}),e.jsxs("div",{className:we.fieldGroup,children:[e.jsx(Ut,{children:s.workHours}),e.jsxs("div",{className:we.timeInputs,children:[e.jsx(Pt,{name:"startTime",control:h,render:({field:d})=>e.jsx(Pe,{type:"time",...d,"aria-label":s.startTime,disabled:!x})}),e.jsx("span",{children:"-"}),e.jsx(Pt,{name:"endTime",control:h,render:({field:d})=>e.jsx(Pe,{type:"time",...d,"aria-label":s.endTime,disabled:!x})})]})]}),e.jsxs("div",{className:we.fieldGroup,children:[e.jsx(Ut,{children:s.advancedOptions}),e.jsxs("div",{className:we.advancedOptionsContainer,children:[e.jsxs("div",{className:we.fieldRow,children:[e.jsx(Ut,{htmlFor:"avoid-weekends",children:s.avoidWeekends}),e.jsx(Pt,{name:"avoidWeekends",control:h,render:({field:d})=>e.jsx(Ls,{id:"avoid-weekends",checked:d.value,onCheckedChange:d.onChange,disabled:!x})})]}),e.jsxs("div",{className:we.fieldRow,children:[e.jsx(Ut,{htmlFor:"avoid-holidays",children:s.avoidHolidays}),e.jsx(Pt,{name:"avoidHolidays",control:h,render:({field:d})=>e.jsx(Ls,{id:"avoid-holidays",checked:d.value,onCheckedChange:d.onChange,disabled:!x})})]})]})]})]})]}),e.jsx("footer",{className:we.footer,children:e.jsx(L,{type:"submit",disabled:!k||m,children:m?s.saving:e.jsxs(e.Fragment,{children:[e.jsx(Lo,{size:16})," ",s.save]})})})]})},Dj=({className:t})=>e.jsxs("div",{className:`${we.container} ${t||""}`,children:[e.jsxs("header",{className:we.header,children:[e.jsx(ne,{style:{height:"1.75rem",width:"150px",marginBottom:"var(--spacing-2)"}}),e.jsx(ne,{style:{height:"1rem",width:"80%"}})]}),e.jsx(Rn,{}),e.jsxs("div",{className:we.formContent,children:[e.jsxs("div",{className:we.fieldRow,children:[e.jsx(ne,{style:{height:"1.25rem",width:"200px"}}),e.jsx(ne,{style:{height:"24px",width:"44px",borderRadius:"var(--radius-full)"}})]}),e.jsxs("div",{className:we.fieldGroup,children:[e.jsx(ne,{style:{height:"1.25rem",width:"100px",marginBottom:"var(--spacing-2)"}}),e.jsx("div",{className:we.daysContainer,children:Array.from({length:7}).map((a,s)=>e.jsxs("div",{className:we.dayCheckbox,children:[e.jsx(ne,{style:{height:"1rem",width:"1rem"}}),e.jsx(ne,{style:{height:"1rem",width:"30px"}})]},s))})]}),e.jsxs("div",{className:we.fieldGroup,children:[e.jsx(ne,{style:{height:"1.25rem",width:"120px",marginBottom:"var(--spacing-2)"}}),e.jsxs("div",{className:we.timeInputs,children:[e.jsx(ne,{style:{height:"2.5rem",width:"100px"}}),e.jsx(ne,{style:{height:"2.5rem",width:"100px"}})]})]})]}),e.jsx("footer",{className:we.footer,children:e.jsx(ne,{style:{height:"2.5rem",width:"150px"}})})]});Ee({});const vj=async t=>{const a=await fetch("/_api/client-assignments/has-assigned",{method:"GET",...t,headers:{"Content-Type":"application/json"}});if(!a.ok){const s=await a.text();let n="An unknown error occurred";try{const o=K.parse(s);typeof o=="object"&&o!==null&&o.error&&(n=o.error)}catch{n=s||n}throw new Error(n)}return K.parse(await a.text())},Cj=()=>ms({queryKey:[Wt,"hasAssignedUser"],queryFn:()=>vj(),staleTime:300*1e3,refetchOnWindowFocus:!1,refetchOnMount:!1}),kj="_header_1nqx4_1",bj="_headerContent_1nqx4_9",wj="_navigationSection_1nqx4_20",Sj="_viewControls_1nqx4_24",Nj="_dateControls_1nqx4_32",Tj="_datePicker_1nqx4_37",Ij="_specialtySelector_1nqx4_42",Ej="_specialtySelect_1nqx4_42",Pj="_titleSection_1nqx4_63",$j="_titleRow_1nqx4_67",Mj="_tourHelpButton_1nqx4_73",Aj="_title_1nqx4_63",Bj="_subtitle_1nqx4_91",Hj="_settingsRowDesktop_1nqx4_122",Lj="_mobileMoreMenu_1nqx4_130",Oj="_dateNavigationRow_1nqx4_134",Rj="_datePickerText_1nqx4_142",Fj="_filtersWrapper_1nqx4_148",Uj="_employeeSelect_1nqx4_172",qj="_employeeOption_1nqx4_178",zj="_employeeOptionAvatar_1nqx4_184",Wj="_manageSpecialtiesButton_1nqx4_191",Gj="_specialtyManagerDialog_1nqx4_196",Vj="_specialtyOption_1nqx4_202",Yj="_taskBasedBadge_1nqx4_209",Qj="_colorLegendDesktop_1nqx4_218",Kj="_colorLegendMobile_1nqx4_226",Jj="_colorLegendItem_1nqx4_230",Xj="_colorDot_1nqx4_239",Zj="_todayButton_1nqx4_327",eD="_monthNavButtons_1nqx4_332",tD="_colorManagerDialog_1nqx4_398",sD="_settingsDialog_1nqx4_440",xe={header:kj,headerContent:bj,navigationSection:wj,viewControl
2s:Sj,dateControls:Nj,datePicker:Tj,specialtySelector:Ij,specialtySelect:Ej,titleSection:Pj,titleRow:$j,tourHelpButton:Mj,title:Aj,subtitle:Bj,settingsRowDesktop:Hj,mobileMoreMenu:Lj,dateNavigationRow:Oj,datePickerText:Rj,filtersWrapper:Fj,employeeSelect:Uj,employeeOption:qj,employeeOptionAvatar:zj,manageSpecialtiesButton:Wj,specialtyManagerDialog:Gj,specialtyOption:Vj,taskBasedBadge:Yj,colorLegendDesktop:Qj,colorLegendMobile:Kj,colorLegendItem:Jj,colorDot:Xj,todayButton:Zj,monthNavButtons:eD,colorManagerDialog:tD,settingsDialog:sD},nD=({viewMode:t,setViewMode:a,currentDate:s,onDateSelect:n,onGoToToday:o,onGoToPrevious:i,onGoToNext:p,selectedSpecialty:c,onSpecialtyChange:m,specialties:h,taskBasedSpecialties:r,colorsMap:C,companyProfile:g,isLoadingProfile:l,isSpecialtyManagerOpen:k,setIsSpecialtyManagerOpen:j,isColorManagerOpen:x,setIsColorManagerOpen:d,isSettingsOpen:b,setIsSettingsOpen:y,onOpenTour:S,selectedAssignedUserId:D,onAssignedUserChange:_})=>{const{t:f,language:v}=ye(),M=Ws(),{data:W}=Ks(),{data:N,isLoading:O}=Cj(),w=N?.hasAssigned||D!==null,B=()=>{const T=v==="fr"?zt:Vs;if(t==="day")return De(s,M?"EEE d MMM":"EEEE d MMMM yyyy",{locale:T});if(t==="week"){const A=new Date(s),Y=A.getDay(),E=Y===0?-6:1-Y;A.setDate(A.getDate()+E);const $=new Date(A);return $.setDate($.getDate()+6),`${De(A,"d MMM",{locale:T})} - ${De($,"d MMM yyyy",{locale:T})}`}else return s.toLocaleDateString(v==="fr"?"fr-FR":"en-US",{month:"long",year:"numeric"})},I="__ALL__",F=h.length>=1,de="__ALL_EMPLOYEES__",fe="__UNASSIGNED__";return e.jsx("header",{className:xe.header,children:e.jsxs("div",{className:xe.headerContent,children:[e.jsxs("div",{className:xe.titleSection,children:[e.jsxs("div",{className:xe.titleRow,children:[e.jsx("h1",{className:xe.title,children:f("planning_title")}),e.jsx(L,{variant:"ghost",size:"icon-sm",onClick:S,"aria-label":v==="fr"?"Visite guidée":"Guided tour",title:v==="fr"?"Visite guidée":"Guided tour",className:xe.tourHelpButton,children:e.jsx(Oo,{size:18})})]}),e.jsx("p",{className:xe.subtitle,children:f("planning_subtitle")})]}),e.jsxs("div",{className:xe.navigationSection,children:[e.jsxs("div",{className:xe.viewControls,children:[e.jsx(L,{variant:t==="month"?"primary":"outline",size:"sm",onClick:()=>a("month"),children:f("planning_view_month")}),e.jsx(L,{variant:t==="week"?"primary":"outline",size:"sm",onClick:()=>a("week"),children:f("planning_view_week")}),e.jsx(L,{variant:t==="day"?"primary":"outline",size:"sm",onClick:()=>a("day"),children:f("planning_view_day")})]}),e.jsxs("div",{className:xe.dateControls,children:[e.jsx("div",{className:xe.filtersWrapper,children:e.jsxs("div",{className:xe.specialtySelector,children:[e.jsxs(nt,{value:h.length===0?void 0:c||I,onValueChange:T=>m(T===I?null:T),disabled:l||h.length===0,children:[e.jsx(at,{className:xe.specialtySelect,children:e.jsx(it,{placeholder:h.length===0?f("planning_specialty_placeholder"):f("planning_all_specialties")})}),e.jsxs(ot,{children:[F&&e.jsx(J,{value:I,children:f("planning_all_specialties")}),h.map(T=>e.jsx(J,{value:T,children:e.jsxs("div",{className:xe.specialtyOption,children:[T,r.has(T)&&e.jsxs("span",{className:xe.taskBasedBadge,children:[e.jsx(Ra,{size:12}),"(",f("planning_tasks"),")"]})]})},T))]})]}),!O&&w&&e.jsxs(nt,{value:D===null?de:D==="unassigned"?fe:String(D),onValueChange:T=>{_(T===de?null:T===fe?"unassigned":Number(T))},children:[e.jsx(at,{className:xe.employeeSelect,children:e.jsx(it,{placeholder:v==="fr"?"Tous les employés":"All employees"})}),e.jsxs(ot,{children:[e.jsx(J,{value:de,children:v==="fr"?"Tous les employés":"All employees"}),e.jsx(J,{value:fe,children:v==="fr"?"Non assigné":"Unassigned"}),W?.map(T=>e.jsx(J,{value:String(T.id),children:e.jsxs("div",{className:xe.employeeOption,children:[T.avatarUrl&&e.jsx("img",{src:T.avatarUrl,alt:"",className:xe.employeeOptionAvatar}),T.displayName]})},T.id))]})]}),e.jsxs(Qe,{open:k,onOpenChange:j,children:[e.jsx(Cr,{asChild:!0,children:e.jsx(L,{variant:"ghost",size:"icon-sm","aria-label":f("planning_manage_specialties"),className:xe.manageSpecialtiesButton,children:e.jsx(wn,{size:16})})}),e.jsxs(Ke,{className:xe.specialtyManagerDialog,children:[e.jsx(lt,{children:e.jsx(Je,{children:f("planning_manage_specialties")})}),g&&!("error"in g)&&e.jsx(Zy,{companyProfile:g})]})]}),e.jsx("div",{className:xe.mobileMoreMenu,children:e.jsxs(oi,{children:[e.jsx(ri,{asChild:!0,children:e.jsx(L,{variant:"ghost",size:"icon-sm",className:xe.manageSpecialtiesButton,children:e.jsx(Ro,{size:16})})}),e.jsxs(li,{align:"end",children:[e.jsxs(mt,{onSelect:()=>d(!0),children:[e.jsx(ca,{size:16,style:{marginRight:8}}),f("planning_specialty_colors")]}),e.jsxs(mt,{onSelect:()=>y(!0),children:[e.jsx(wn,{size:16,style:{marginRight:8}}),f("planning_business_hours")]})]})]})})]})}),e.jsxs("div",{className:xe.dateNavigationRow,children:[e.jsxs(on,{children:[e.jsx(rn,{asChild:!0,children:e.jsxs(L,{variant:"outline",size:"sm",className:xe.datePicker,children:[e.jsx(Ps,{size:16}),e.jsx("span",{className:xe.datePickerText,children:B()})]})}
2),e.jsx(ln,{removeBackgroundAndPadding:!0,children:e.jsx(En,{mode:"single",selected:s,onSelect:n,defaultMonth:s})})]}),e.jsx(L,{variant:"ghost",size:"sm",onClick:o,className:xe.todayButton,children:f("common_today")}),e.jsxs("div",{className:xe.monthNavButtons,children:[e.jsx(L,{variant:"ghost",size:"icon-sm",onClick:i,"aria-label":f(t==="day"?"planning_previous_day":t==="week"?"planning_previous_week":"planning_previous_month"),children:e.jsx(Na,{size:16})}),e.jsx(L,{variant:"ghost",size:"icon-sm",onClick:p,"aria-label":f(t==="day"?"planning_next_day":t==="week"?"planning_next_week":"planning_next_month"),children:e.jsx(Ta,{size:16})})]})]}),h.length>0&&e.jsx("div",{className:xe.colorLegendMobile,children:h.map(T=>e.jsxs("div",{className:xe.colorLegendItem,children:[e.jsx("span",{className:xe.colorDot,style:{backgroundColor:C[T]}}),e.jsx("span",{children:T})]},T))})]}),e.jsxs("div",{className:xe.settingsRowDesktop,children:[e.jsxs(L,{variant:"outline",size:"sm",onClick:()=>d(!0),"aria-label":f("planning_specialty_colors"),className:xe.colorButton,children:[e.jsx(ca,{size:16}),f("planning_specialty_colors")]}),e.jsxs(L,{variant:"outline",size:"sm",onClick:()=>y(!0),"aria-label":f("planning_business_hours"),className:xe.settingsButton,children:[e.jsx(wn,{size:16}),f("planning_business_hours")]}),h.length>0&&e.jsx("div",{className:xe.colorLegendDesktop,children:h.map(T=>e.jsxs("div",{className:xe.colorLegendItem,children:[e.jsx("span",{className:xe.colorDot,style:{backgroundColor:C[T]}}),e.jsx("span",{children:T})]},T))})]}),e.jsx(Qe,{open:x,onOpenChange:d,children:e.jsxs(Ke,{className:xe.colorManagerDialog,children:[e.jsx(lt,{children:e.jsx(Je,{children:f("planning_specialty_colors")})}),e.jsx(sl,{lang:v==="fr"?"fr-CA":"en-US"})]})}),e.jsx(Qe,{open:b,onOpenChange:y,children:e.jsxs(Ke,{className:xe.settingsDialog,children:[e.jsx(lt,{children:e.jsx(Je,{children:f("planning_business_hours")})}),e.jsx(jj,{})]})})]})]})})},aD="_dialogContent_15bav_1",iD="_content_15bav_9",oD="_fadeIn_15bav_17",rD="_fadeOut_15bav_22",lD="_iconContainer_15bav_27",cD="_title_15bav_44",dD="_description_15bav_53",uD="_footer_15bav_61",pD="_dots_15bav_69",mD="_dot_15bav_69",hD="_active_15bav_83",gD="_actions_15bav_88",_D="_progressText_15bav_95",fD="_srOnly_15bav_107",vt={dialogContent:aD,content:iD,fadeIn:oD,fadeOut:rD,iconContainer:lD,title:cD,description:dD,footer:uD,dots:pD,dot:mD,active:hD,actions:gD,progressText:_D,srOnly:fD},xD=({isOpen:t,onClose:a,startAtStep:s=0,onMarkCompleted:n})=>{const{language:o}=ye(),[i,p]=u.useState(s),[c,m]=u.useState(!1);u.useEffect(()=>{t&&p(s)},[t,s]);const h=()=>{n?.();try{localStorage.setItem("guided-tour-completed-planning","true")}catch(j){console.error("Failed to save tour completion status to localStorage",j)}a()},r=[{icon:Ps,title:o==="fr"?"Vue du calendrier":"Calendar Overview",description:o==="fr"?"Bienvenue dans la planification ! Le calendrier offre 3 modes de vue : Mois, Semaine et Jour. Utilisez les boutons en haut pour basculer entre les vues.":"Welcome to Planning! The calendar offers 3 view modes: Month, Week, and Day. Use the buttons at the top to switch views."},{icon:Fo,title:o==="fr"?"Spécialités et Filtrage":"Specialties & Filtering",description:o==="fr"?"Chaque spécialité représente un type de travail (ex: Terrassement, Plomberie). Filtrez le calendrier par spécialité pour voir uniquement les projets pertinents. Gérez vos spécialités via l'icône âï¸.":"Each specialty represents a work type (e.g., Landscaping, Plumbing). Filter the calendar by specialty to see only relevant projects. Manage your specialties via the âï¸ icon."},{icon:pn,title:o==="fr"?"Assignation Glisser-Déposer":"Drag & Drop Assignment",description:o==="fr"?"Glissez un devis signé depuis la liste des clients vers une date du calendrier pour planifier un projet. Les dates assignées ici seront celles que vos clients verront dans leur portail client. Sur mobile, sélectionnez un devis puis touchez la date souhaitée.":"Drag a signed quote from the client list onto a calendar date to schedule a project. The dates assigned here are the ones your clients will see in their client portal. On mobile, select a quote then tap the desired date."},{icon:Uo,title:o==="fr"?"Logique de Cascade":"Cascade Logic & Impact",description:o==="fr"?"Lorsque vous déplacez un projet, les projets suivants se décalent automatiquement (effet cascade). Visualisez l'impact avant de publier dans le système de brouillon.":"When you move a project, subsequent projects shift automatically (cascade effect). Preview the impact before publishing in the draft system."},{icon:qo,title:o==="fr"?"Système de Brouillon":"Draft System",description:o==="fr"?"Toutes les modifications sont enregistrées comme brouillons. Vous pouvez réviser, annuler ou publier l'ensemble des changements d'un seul coup via la barre de brouillon en haut.":"All changes are saved as drafts. You can review, cancel, or publish all changes at once via the draft bar at the top."},{icon:mn,title:o==="fr"?"Verrouillage (Pinning)":"Pinning",description:o==="fr"?"Ãpinglez un projet pour le protéger des décalages en cascade. Un projet épinglé reste à sa date même si les projets voisins bougent.":"Pin a project to protect it from cascade shifts. A pinned project stays on its date even when neighboring projects move."},{icon:hs,title:o==="fr"?"Planification en Demi-journée":"Half-Day Scheduling",description:o==="fr"?"Planifiez en demi-journées (AM/PM) pour optimiser votre calendrier. Lors de l'assignation, choisissez la plage horaire souhaitée.":"Schedule in half-days (AM/PM) to optimize your calendar. When assigning, choose the desired time slot."},{icon:$a,title:o==="fr"?"Intégration Météo":"Weather Integration",description:o==="fr"?"La météo est intégrée directement dans la planification. Consultez les prévisions pour chaque jour et adaptez votre planification en conséquence. La ville détectée est synchronisée avec votre tableau de bord.":"Weather is integrated directly into planning. Check forecasts for each day and adapt your schedule accordingly. The detected city is synced with your dashboard."}],C=j=>{m(!0),setTimeout(()=>{p(j),m(!1)},150)},g=()=>{i<r.length-1?C(i+1):h()},l=()=>{i>0&&C(i-1)},k=r[i].icon;return e.jsx(Qe,{open:t,onOpenChange:j=>!j&&h(),children:e.jsxs(Ke,{className:vt.dialogContent,"aria-describedby":void 0,children:[e.jsx(Je,{className:vt.srOnly,children:o==="fr"?"Visite guidée de la planification":"Planning Guided Tour"}),e.jsxs("div",{className:`${vt.content} ${c?vt.fadeOut:vt.fadeIn}`,children:[e.jsx("div",{className:vt.iconContainer,children:e.jsx(k,{strokeWidth:1.5})}),e.jsx("h2",{className:vt.title,children:r[i].title}),e.jsx("p",{className:vt.description,children:r[i].description})]}),e.jsxs("div",{className:vt.footer,children:[e.jsx("div",{className:vt.dots,children:r.map((j,x)=>e.jsx("div",{className:`${vt.dot} ${x===i?vt.active:""}`,"aria-label":`Step ${x+1}`},x))}),e.jsxs("div",{className:vt.actions,children:[i===0?e.jsx(L,{variant:"ghost",onClick:h,children:o==="fr"?"Passer":"Skip"}):e.jsx(L,{variant:"outline",onClick:l,children:o==="fr"?"Précédent":"Previous"}),e.jsxs("div",{className:vt.progressText,children:[i+1," / ",r.length]}),e.jsx(L,{variant:"primary",onClick:g,children:i===r.length-1?o==="fr"?"Terminer":"Finish":o==="fr"?"Suivant":"Next"})]})]})]})})},yD="_container_1foin_1",jD="_mobileToolbarWrapper_1foin_9",DD="_dayStrip_1foin_13",vD="_dayButton_1foin_26",CD="_nonWorkingDay_1foin_42",kD="_selectedDay_1foin_48",bD="_dayName_1foin_55",wD="_dayNumber_1foin_62",SD="_eventsList_1foin_68",ND="_allDaySection_1foin_75",TD="_allDayTitle_1foin_79",ID="_timelineGrid_1foin_92",ED="_timelineInner_1foin_101",PD="_timelineRow_1foin_105",$D="_timeLabel_1foin_115",MD="_timeSlot_1foin_126",AD="_eventsContainer_1foin_136",BD="_eventCard_1foin_146",HD="_absoluteCard_1foin_159",LD="_eventTimeContainer_1foin_170",OD="_eventTitle_1foin_174",RD="_eventDetail_1foin_181",FD="_eventTime_1foin_170",UD="_badgesContainer_1foin_198",qD="_statusBadge_1foin_204",zD="_assignmentBadge_1foin_214",WD="_eventBadge_1foin_224",GD="_eventSkeleton_1foin_254",VD="_noEvents_1foin_260",YD="_nonWorkingDayEmpty_1foin_270",QD="_clickableCard_1foin_275",KD="_fab_1foin_290",le={container:yD,mobileToolbarWrapper:jD,dayStrip:DD,dayButton:vD,nonWorkingDay:CD,selectedDay:kD,dayName:bD,dayNumber:wD,eventsList:SD,allDaySection:ND,allDayTitle:TD,timelineGrid:ID,timelineInner:ED,timelineRow:PD,timeLabel:$D,timeSlot:MD,eventsContainer:AD,eventCard:BD,absoluteCard:HD,eventTimeContainer:LD,eventTitle:OD,eventDetail:RD,eventTime:FD,badgesContainer:UD,statusBadge:qD,assignmentBadge:zD,eventBadge:WD,eventSkeleton:GD,noEvents:VD,nonWorkingDayEmpty:YD,clickableCard:QD,fab:KD},JD=({currentDate:t,onDateSelect:a,selectedSpecialty:s,selectedAssignedUserId:n,isTaskBasedSpecialty:o,isMobileClientListOpen:i=!1,setIsMobileClientListOpen:p})=>{const{language:c}=ye(),{authState:m}=Vt(),{hasPermission:h}=gs(),r=u.useMemo(()=>
2{if(m.type!=="authenticated")return!1;const U=m.user.role;return["admin","company","owner"].includes(U)?!0:h("planning.edit")},[m,h]),C=c==="fr"?zt:Vs,{taskCategoryMappings:g,colorsMap:l}=Gs(),k=u.useMemo(()=>({}),[]),{tradeColors:j,roleColors:x}=il(k),[d,b]=je.useState(null),[y,S]=je.useState(null),[D,_]=je.useState(!1),[f,v]=je.useState(!1),[M,W]=je.useState(),{data:N}=Yt(),O=Wn(),w=u.useRef(null),B=u.useRef({startY:0,startX:0,wasScroll:!1}),I=je.useCallback(U=>({onTouchStart:Ce=>{B.current={startY:Ce.touches[0].clientY,startX:Ce.touches[0].clientX,wasScroll:!1}},onTouchEnd:Ce=>{const Xe=Math.abs(Ce.changedTouches[0].clientY-B.current.startY),ie=Math.abs(Ce.changedTouches[0].clientX-B.current.startX);Xe>10||ie>10?B.current.wasScroll=!0:(Ce.cancelable&&Ce.preventDefault(),U())},onClick:Ce=>{U()}}),[]);u.useEffect(()=>{w.current&&w.current.scrollIntoView({behavior:"smooth",block:"start"})},[t]);const F=U=>{U.stopPropagation(),y&&window.confirm(c==="fr"?"Ãtes-vous sûr de vouloir supprimer cette tâche ?":"Are you sure you want to delete this task?")&&(y.id>0&&O.mutate({assignmentId:y.id,cascadeMode:"leave-gap",sendNotifications:!1,specialty:y.specialty||void 0}),S(null),_(!1))},de=u.useMemo(()=>{const U=[],Ce=ge(new Date);for(let Xe=-14;Xe<=30;Xe++)U.push(Xa(Ce,Xe));return U},[]),fe=u.useRef(null);u.useEffect(()=>{if(fe.current){const U=fe.current.querySelector(`.${le.selectedDay}`);U&&U.scrollIntoView({behavior:"smooth",block:"nearest",inline:"center"})}},[t]);const T=ge(t).toISOString(),A=es(t).toISOString(),Y=o&&s&&g[s]||null,{data:E,isFetching:$}=Ya({startDate:T,endDate:A,...Y?{taskCategory:Y}:{}}),R=E?.events||[],{data:Q,isFetching:se}=Es({startDate:T,endDate:A,...s?{specialty:s}:{},...typeof n=="number"?{assignedUserId:n}:{},...n==="unassigned"?{unassignedOnly:!0}:{}}),ae=Q?.assignments||[],Z=$||se;let ve=!0;if(N?.enabled){const U={workingDays:N.workDays,avoidWeekends:N.avoidWeekends??!0,avoidHolidays:N.avoidHolidays??!0,startTime:N.startTime,endTime:N.endTime};ve=us(t,U)}const ue=N?.enabled?Math.min(6,parseInt(N.startTime.split(":")[0])):6,He=N?.enabled?Math.max(20,parseInt(N.endTime.split(":")[0])):20,P=Array.from({length:He-ue+1},(U,Ce)=>ue+Ce),z=70,V=[],Se=[];ae.forEach(U=>{if(U.allDay||U.isHalfDay||!U.startDate||!U.endDate)sn(U,t,N)&&V.push({type:"assignment",data:U});else{const Ce=ge(new Date(U.startDate)),Xe=ge(t);Ce.getTime()===Xe.getTime()&&Se.push({type:"assignment",data:U})}}),R.forEach(U=>{U.allDay||!U.startDatetime||!U.endDatetime?V.push({type:"event",data:U}):Se.push({type:"event",data:U})});const ut=V.length===0&&Se.length===0,_t=U=>{if(!s){q.error(c==="fr"?"Veuillez d'abord sélectionner une spécialité":"Please select a specialty first");return}W({hour:U,minute:0}),v(!0)},ft=()=>{if(!s){q.error(c==="fr"?"Veuillez d'abord sélectionner une spécialité":"Please select a specialty first");return}W(void 0),v(!0)},Le=(U,Ce)=>{const Xe=U.type==="assignment",ie=Xe?U.data:null,ze=Xe?null:U.data;if(Xe){const Kt=ie.firstName||ie.lastName?`${ie.firstName||""} ${ie.lastName||""}`.trim():ie.taskTitle||(c==="fr"?"Intervention":"Assignment"),ys=ie.specialty?l[ie.specialty]:"var(--primary)";let Nt=c==="fr"?"Toute la journée":"All Day";ie.isHalfDay?ie.halfDayPeriod==="morning"?Nt=c==="fr"?"Matin":"Morning":ie.halfDayPeriod==="afternoon"&&(Nt=c==="fr"?"Après-midi":"Afternoon"):!ie.allDay&&ie.startDate&&ie.endDate&&(Nt=`${De(new Date(ie.startDate),"HH:mm")} - ${De(new Date(ie.endDate),"HH:mm")}`);let Lt={borderLeftColor:ys};if(Ce&&ie.startDate&&ie.endDate){const Ot=new Date(ie.startDate),Gt=new Date(ie.endDate),te=Ot.getHours()+Ot.getMinutes()/60,kt=Gt.getHours()+Gt.getMinutes()/60,Rt=(te-ue)*z,ns=Math.max((kt-te)*z,30);Lt={...Lt,top:`${Rt}px`,height:`${ns}px`}}return e.jsxs("div",{className:`${le.eventCard} ${le.clickableCard} ${Ce?le.absoluteCard:""}`,style:Lt,...I(()=>{ie.clientId!==null?b(ie):S(ie)}),role:"button",tabIndex:0,children:[e.jsxs("div",{className:le.eventTimeContainer,children:[e.jsx("span",{className:le.eventTime,children:Nt}),e.jsxs("div",{className:le.badgesContainer,children:[e.jsx("span",{className:le.assignmentBadge,children:ie.clientId===null&&ie.taskTitle?c==="fr"?"Tâche":"Task":c==="fr"?"Affectation":"Assignment"}),ie.clientId===null&&ie.taskStatus&&e.jsx("span",{className:le.statusBadge,children:c==="fr"?{pending:"En attente",in_progress:"En cours",completed:"Terminé",cancelled:"Annulé"}[ie.taskStatus]||ie.taskStatus:{pending:"Pending",in_progress:"In Progress",completed:"Completed",cancelled:"Cancelled"}[ie.taskStatus]||ie.taskStatus})]})]}),e.jsx("div",{className:le.eventTitle,children:Kt}),ie.specialty&&!Ce&&e.jsxs("div",{className:le.eventDetail,children:[e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"M12 2v20M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"})}),ie.specialty]}),ie.quoteTitle&&!Ce&&e.jsxs("div",{className:le.eventDetail,children:[e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),e.jsx("polyline",{points:"14 2 14 8 20 8"}),e.jsx("line",{x1:"16",y1:"13",x2:"8",y2:"13"}),e.jsx("line",{x1:"16",y1:"17",x2:"8",y2:"17"}),e.jsx("polyline",{points:"10 9 9 9 8 9"})]}),ie.quoteTitle]}),ie.notes&&!Ce&&e.jsxs("div",{className:le.eventDetail,children:[e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"})}),ie.notes]})]},`assignment-${ie.id}`)}else{const xs=ze.tradeType||"general",Kt=ze.assignedRole||"employee";let Nt={borderLeftColor:j[xs]||x[Kt]||"var(--primary)"};if(Ce&&ze.startDatetime&&ze.endDatetime){const Lt=new Date(ze.startDatetime),Ot=new Date(ze.endDatetime),Gt=Lt.getHours()+Lt.getMinutes()/60,te=Ot.getHours()+Ot.getMinutes()/60,kt=(Gt-ue)*z,Rt=Math.max((te-Gt)*z,30);Nt={...Nt,top:`${kt}px`,height:`${Rt}px`}}return e.jsxs("div",{className:`${le.eventCard} ${Ce?le.absoluteCard:""}`,style:Nt,children:[e.jsxs("div",{className:le.eventTimeContainer,children:[e.jsx("span",{className:le.eventTime,children:ze.allDay?c==="fr"?"Toute la journée":"All Day":`${De(new Date(ze.startDatetime),"HH:mm")} - ${De(new Date(ze.endDatetime),"HH:mm")}`}),e.jsx("span",{className:le.eventBadge,children:c==="fr"?"Ãvénement":"Event"})]}),e.jsx("div",{className:le.eventTitle,children:ze.title}),(ze.clientFirstName||ze.clientLastName)&&!Ce&&e.jsxs("div",{className:le.eventDetail,children:[e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"12",cy:"7",r:"4"})]}),ze.clientFirstName," ",ze.clientLastName]})]},`event-${ze.id}`)}};return e.jsx(Ja,{backend:Ga,options:{enableMouseEvents:!0,delayTouchStart:120},children:e.jsxs("div",{className:le.container,ref:w,children:[r&&p&&e.jsx("div",{className:le.mobileToolbarWrapper,children:e.jsx(Ei,{isOpen:i,onOpenChange:p,onQuoteSelect:()=>p(!1)})}),e.jsx("div",{className:le.dayStrip,ref:fe,children:de.map(U=>{const Ce=Ns(U,t);let Xe=!0;if(N?.enabled){const ie={workingDays:N.workDays,avoidWeekends:N.avoidWeekends??
2!0,avoidHolidays:N.avoidHolidays??!0,startTime:N.startTime,endTime:N.endTime};Xe=us(U,ie)}return e.jsxs("button",{className:`${le.dayButton} ${Ce?le.selectedDay:""} ${Xe?"":le.nonWorkingDay}`,onClick:()=>a(U),children:[e.jsx("span",{className:le.dayName,children:De(U,"E",{locale:C})}),e.jsx("span",{className:le.dayNumber,children:De(U,"d")})]},U.toISOString())})}),Z?e.jsxs("div",{className:le.eventsList,children:[e.jsx(ne,{className:le.eventSkeleton}),e.jsx(ne,{className:le.eventSkeleton}),e.jsx(ne,{className:le.eventSkeleton})]}):e.jsxs(e.Fragment,{children:[!ve&&ut&&e.jsx("div",{className:`${le.noEvents} ${le.nonWorkingDayEmpty}`,children:c==="fr"?"Jour non ouvrable - Aucune activité planifiée":"Non-working day - No activity scheduled"}),V.length>0&&e.jsxs("div",{className:le.allDaySection,children:[e.jsx("h4",{className:le.allDayTitle,children:c==="fr"?"Toute la journée":"All day"}),e.jsx("div",{className:le.eventsList,children:V.map(U=>Le(U,!1))})]}),e.jsx("div",{className:le.timelineGrid,children:e.jsxs("div",{className:le.timelineInner,children:[P.map(U=>e.jsxs("div",{className:le.timelineRow,children:[e.jsx("div",{className:le.timeLabel,children:`${U.toString().padStart(2,"0")}:00`}),e.jsx("div",{className:le.timeSlot,...I(()=>_t(U))})]},U)),e.jsx("div",{className:le.eventsContainer,children:Se.map(U=>Le(U,!0))})]})})]}),d&&d.clientId&&e.jsx(Si,{isOpen:!!d,onClose:()=>b(null),assignment:d}),y&&!D&&e.jsx(Ii,{isOpen:!!y&&!D,onClose:()=>S(null),assignment:y,canEditPlanning:r,onEdit:()=>_(!0),onDelete:F}),y&&D&&e.jsx(Ti,{isOpen:D,onClose:()=>{_(!1),S(null)},assignment:y}),f&&s&&e.jsx(vi,{isOpen:f,onClose:()=>v(!1),initialDate:t,initialStartTime:M,specialty:s}),r&&e.jsx("button",{className:le.fab,onClick:ft,"aria-label":"Add task",children:e.jsx(zo,{size:24})})]})})},XD="_container_sevk1_1",ZD="_draftBar_sevk1_7",ev="_draftInfo_sevk1_20",tv="_draftActions_sevk1_29",sv="_taskModeBar_sevk1_57",nv="_header_sevk1_86",av="_verticalLayout_sevk1_94",iv="_calendarCard_sevk1_100",ov="_weatherSection_sevk1_109",rv="_weatherGrid_sevk1_113",lv="_weatherCard_sevk1_119",cv="_error_sevk1_164",dv="_loadingState_sevk1_205",uv="_titleSkeleton_sevk1_209",pv="_subtitleSkeleton_sevk1_216",mv="_cardSkeleton_sevk1_240",hv="_sidebarCardSkeleton_sevk1_246",Be={container:XD,draftBar:ZD,draftInfo:ev,draftActions:tv,taskModeBar:sv,header:nv,verticalLayout:av,calendarCard:iv,weatherSection:ov,weatherGrid:rv,weatherCard:lv,error:cv,loadingState:dv,titleSkeleton:uv,subtitleSkeleton:pv,cardSkeleton:mv,sidebarCardSkeleton:hv},gv=()=>{const{authState:t}=Vt(),a=Ws(),{t:s,language:n}=ye(),{city:o,isLocating:i,refreshLocation:p}=ar(),{pendingCount:c,clearAll:m,publishDraft:h,isPublishing:r}=Qt(),[C,g]=Wo(),l=Go(),k=On(),j=C.get("quoteId"),[x,d]=u.useState(()=>{const Le=new Date;return Le.setHours(0,0,0,0),Le}),[b,y]=u.useState(null),S=y,[D,_]=u.useState(a?"day":"month"),f=u.useCallback(()=>{_("month")},[]),[v,M]=u.useState(!1),[W,N]=u.useState(!1),[O,w]=u.useState(null),[B,I]=u.useState(null),[F,de]=u.useState(!1),[fe,T]=u.useState(!1),{isCompleted:A,isFetching:Y,markCompleted:E}=nl("planning"),[$,R]=u.useState(!1),Q=je.useRef(!1);je.useEffect(()=>{!Y&&!Q.current&&(Q.current=!0,A||R(!0))},[Y,A]);const{data:se,isFetching:ae}=_s(),{visibleCalendarSpecialties:Z}=gs(),{data:ve}=Yt(),{taskBasedSpecialties:ue,colorsMap:He}=Gs(),P=O?ue.has(O):!1;u.useEffect(()=>{l.state?.openEditor&&(T(!0),k(l.pathname+l.search,{replace:!0,state:{...l.state,openEditor:void 0}}))},[l.state,l.pathname,l.search,k]),u.useEffect(()=>{if(j&&window.innerWidth<=768){T(!0);const U=new URLSearchParams(C);U.delete("quoteId"),g(U,{replace:!0})}},[j,C,g]);const z=u.useMemo(()=>{if(!se||"error"in se)return[];const Le=se.specialties||[];return t.type==="authenticated"&&!["admin","company","owner"].includes(t.user.role)?Z&&Z.length>0?Le.filter(Ce=>Z.includes(Ce)):[]:Le},[se,t,Z]);u.useEffect(()=>{!ae&&z.length>0&&O&&!z.includes(O)&&w(null)},[z,ae,O]);const V=Le=>{const U=new Date(Le);return U.setHours(0,0,0,0),U},Se=u.useCallback(()=>{d(Le=>{const U=new Date(Le);return D==="day"?U.setDate(U.getDate()-1):D==="week"?U.setDate(U.getDate()-7):U.setMonth(U.getMonth()-1),V(U)})},[D]),ut=u.useCallback(()=>{d(Le=>{const U=new Date(Le);return D==="day"?U.setDate(U.getDate()+1):D==="week"?U.setDate(U.getDate()+7):U.setMonth(U.getMonth()+1),V(U)})},[D]),_t=()=>{const Le=V(new Date);d(Le),S(Le)},ft=Le=>{Le&&d(V(Le))};return t.type==="loading"?e.jsxs(e.Fragment,{children:[e.jsxs(da,{children:[e.jsx("title",{children:s("planning_page_title")}),e.jsx("meta",{name:"description",content:s("planning_page_description")})]}),e.jsx("div",{className:Be.container,children:e.jsxs("div",{className:Be.loadingState,children:[e.jsxs("div",{className:Be.header,children:[e.jsx(ne,{className:Be.titleSkeleton}),e.jsx(ne,{className:Be.subtitleSkeleton})]}),e.jsxs("div",{className:Be.verticalLayout,children:[e.jsx("div",{className:Be.calendarCard,children:e.jsx(ne,{className:Be.cardSkeleton})}),e.jsx("div",{className:Be.weatherSection,children:e.jsxs("div",{className:Be.weatherGrid,children:[e.jsx(ne,{className:Be.sidebarCardSkeleton}),e.jsx(ne,{className:Be.sidebarCardSkeleton}),e.jsx(ne,{className:Be.sidebarCardSkeleton})]})})]})]})})]}):t.type==="unauthenticated"?e.jsx("div",{className:Be.container,children:e.jsxs("div",{className:Be.error,children:[e.jsx("h2",{children:s("common_unauthorized")}),e.jsx("p",{children:s("common_login_required")})]})}):e.jsx(Bl,{onSwapComplete:f,children:e.jsxs(e.Fragment,{children:[e.jsxs(da,{children:[e.jsx("title",{children:s("planning_title")}),e.jsx("meta",{name:"description",content:s("planning_subtitle")})]}),e.jsx(al,{queryKeys:[[...ds]],children:e.jsxs("div",{className:Be.container,children:[c>0&&e.jsxs("div",{className:Be.draftBar,children:[e.jsxs("div",{className:Be.draftInfo,children:[e.jsx(wt,{variant:"default",children:c}),e.jsx("span",{children:s("planning_pending_changes",{count:c}
2)})]}),e.jsxs("div",{className:Be.draftActions,children:[e.jsx(L,{onClick:m,variant:"ghost",size:"sm",disabled:r,children:s("planning_cancel_all")}),e.jsxs(L,{onClick:h,disabled:r,size:"sm",children:[r&&e.jsx(Ts,{size:"sm"}),s("planning_publish_changes")]})]})]}),e.jsx(Cy,{}),e.jsx($y,{}),P&&e.jsx("div",{className:`${Be.draftBar} ${Be.taskModeBar}`,children:e.jsxs("div",{className:Be.draftInfo,children:[e.jsx(Ra,{size:18}),e.jsx("span",{children:s("planning_task_mode_info")})]})}),e.jsx(nD,{viewMode:D,setViewMode:_,currentDate:x,onDateSelect:ft,onGoToToday:_t,onGoToPrevious:Se,onGoToNext:ut,selectedSpecialty:O,onSpecialtyChange:w,selectedAssignedUserId:B,onAssignedUserChange:I,specialties:z,taskBasedSpecialties:ue,colorsMap:He,companyProfile:se,isLoadingProfile:ae,isSpecialtyManagerOpen:F,setIsSpecialtyManagerOpen:de,isColorManagerOpen:W,setIsColorManagerOpen:N,isSettingsOpen:v,setIsSettingsOpen:M,onOpenTour:()=>R(!0)}),e.jsxs("div",{className:Be.verticalLayout,children:[e.jsx("div",{className:Be.calendarCard,children:a&&D==="day"?e.jsx(JD,{currentDate:x,onDateSelect:ft,selectedSpecialty:O||void 0,selectedAssignedUserId:B,isTaskBasedSpecialty:P,isMobileClientListOpen:fe,setIsMobileClientListOpen:T}):e.jsx(my,{lang:n,selectedSpecialty:O||void 0,selectedAssignedUserId:B,isTaskBasedSpecialty:P,controlledCurrentDate:x,onDateChange:d,viewMode:D,controlledSelectedDate:b,onSelectedDateChange:S,highlightedQuoteId:j?Number(j):void 0,isMobileClientListOpen:fe,setIsMobileClientListOpen:T,onOpenSpecialtyManager:()=>de(!0)})}),e.jsx("div",{className:Be.weatherSection,children:e.jsxs("div",{className:Be.weatherGrid,children:[e.jsx("div",{className:Be.weatherCard,children:e.jsx(tl,{defaultCity:o||"Montreal",externalCity:o,externalIsLocating:i,externalRefreshLocation:p})}),e.jsx("div",{className:Be.weatherCard,children:e.jsx(Br,{})}),e.jsx("div",{className:Be.weatherCard,children:e.jsx(Hr,{city:o||"Montreal"})})]})})]})]})}),e.jsx(xD,{isOpen:$,onClose:()=>R(!1),onMarkCompleted:E})]})})},MC=()=>e.jsx(El,{children:e.jsx(gv,{})});export{MC as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.