1import{j as e}from"./safeEnv-BKCh0bOi.js";import{R as aa}from"./ResponsiveTable-DY7x04GS.js";import{r as x,R as ms}from"./vendor-stripe-C8iz1xSA.js";import{w as De,d as A,g as T,cW as Be,k as Ee,v as qe,P as ot,ae as Xo,U as Re,E as xs,B as st,ap as sa,am as vt,aE as tr,R as Xe,p as Aa,aD as hs,ai as Zr,c as oa,G as en,a2 as _r,av as tn,S as na,ab as ps,x as Ot,u as rn,ah as Pa,f as an,$ as Oa}from"./main-CCOOqq6t.js";import{u as Q,q as V,w as K,k as Z,x as Jr,s as Lt,g as oe,d as B,i as H,j as ee,T as ht,l as ie,a as ke,o as we,C as sn,v as on}from"./firebase-BH_dHDUU.js";import{d as _,F as et,S as rr,r as Ma,s as Fa,u as nn,i as ln,l as cn,h as Hr,b as Br}from"./firebaseClient-CouQa0TO.js";import{d as gt}from"./firebase-BRNEutob.js";import{u as dn}from"./useUrlTabState-Bt-MKnJD.js";import{C as la}from"./chevron-left-DM7kBAcd.js";import{C as nt}from"./chevron-right-DupsYY89.js";import{L as un}from"./layers-BrIZI30N.js";import{S as Nr}from"./send-Yu6PwMuv.js";import{U as ft}from"./user-plus-BYX-oASS.js";import{S as vs}from"./square-B1wCiOxp.js";import{C as ve}from"./clock-CiYV-4Gj.js";import{E as fs}from"./ellipsis-BvFAIiMh.js";import{C as be}from"./calendar-BCzLAoYK.js";import{X as de}from"./x-BZf9NxSq.js";import{M as Je}from"./map-pin-DRBZlZtI.js";import{H as mn}from"./history-CwyKzQLj.js";import{A as xn}from"./arrow-right-DRzZuELH.js";import{c as ar,C as Te}from"./loader-circle-DtBveqEe.js";import{C as Rr}from"./chevron-up-Cp9PDhOE.js";import{P as qt}from"./pen-CAfKIGhW.js";import{C as Rt}from"./circle-check-big-Bo3Ij-RJ.js";import{U as tt}from"./user-BEdnsVfy.js";import{M as gs}from"./message-square-B0nwaKed.js";import{C as Ve}from"./circle-alert-zQM-OsIg.js";import{C as ia}from"./circle-x-DNbtJ5h6.js";import{H as hn}from"./hourglass-BRp5cn3H.js";import{B as ca}from"./building-Cj7IQYNZ.js";import{A as La}from"./archive-BePUEBSt.js";import{C as yr}from"./coffee-Ds_xI2X4.js";import{P as pn}from"./play-C_9lo7rZ.js";import{A as sr}from"./award-SE1JyXHW.js";import{Z as vn}from"./zoom-in-DSutOfix.js";import{M as fn}from"./maximize-2-DdUgs8Mn.js";import{M as da}from"./mail-CObwKa-h.js";import{U as Ft}from"./upload-DETMHvnp.js";import{H as bs}from"./heart-B2a8rFl_.js";import{B as gn}from"./badge-check-e52PsW5C.js";import{R as bn}from"./receipt-DDJuOxFQ.js";import{T as yn}from"./tag-VC3ad6ZD.js";import{P as wn}from"./paperclip-BZcuLAFc.js";import{S as dr}from"./SafeResponsiveContainer-Dl-Cqfiz.js";import{C as jn}from"./chart-column-arskxGrO.js";import{S as _n,L as Nn,a as Sn}from"./LineChart-B9uqw9FO.js";import{X as zr,Y as Wr}from"./YAxis-ZjWVJC8R.js";import{j as Se,b3 as or,b4 as Cn,b5 as kn,b6 as yt,b7 as Rn,b8 as Dn,b9 as ys,ba as En,bb as Tn,P as pt,bc as In,bd as An,be as Pn,bf as On,k as ws,bg as Mn,bh as Fn,bi as Ln,bj as qn,bk as Un,bl as $n,C as js,al as Hn,r as ua,h as _s,z as Bn,bm as zn,D as Ns,ac as Ss,d as Zt,bn as Wn,J as ma,M as Ut,Z as Cs,E as Vn,U as Kn,W as Yn,ax as Gn,X as qa,i as Ua,ak as wr,bo as Xr,bp as Qn,ag as Zn,aj as Jn,bq as Xn,br as el,bs as tl,ai as rl,$ as al,bt as sl,at as Jt,ah as $a,a2 as ol,ay as nl,a8 as ll,bu as il,bv as cl,bw as dl,bx as ul,by as ml,bz as xl,a7 as hl,T as ur}from"./CartesianChart-CW8Ev85R.js";import{C as Sr,u as pl,b as vl,c as fl,B as Ha,a as Ba}from"./BarChart-CWkjBEhr.js";import{F as gl}from"./flame-DJmdg9nF.js";import{T as bl}from"./trending-down-Cjw3g02I.js";import{M as yl}from"./minus-B29DO6-I.js";import{D as wl}from"./download-BOsbBXzV.js";import{P as ks}from"./phone-lb_NrP-2.js";import{U as jl}from"./user-check-BmVvDC7c.js";import{S as Xt}from"./smartphone-BrVTCHKR.js";import{F as _l}from"./file-spreadsheet-Dpc88Rqw.js";import{v as Nl}from"./v4-CtRu48qb.js";import{H as Sl}from"./hash--BdRhKld.js";import{U as Cl}from"./user-cog-DJ-O5lyx.js";import{L as Vr}from"./layout-template-CeFTNkFs.js";import"./vendor-preload-C7KM9AI0.js";/* empty css */import"./navigation-modules-BmHRB6Py.js";import"./vendor-storage-Bn1DMRyg.js";import"./index-BRvVOvjp.js";import"./react-redux-HxvwsopZ.js";import"./value-BGBiTkF3.js";import"./tiny-invariant-BaFNuDhB.js";/** 2 * @license lucide-react v0.554.0 - ISC 3 * 4 * This source code is licensed under the ISC license. 5 * See the LICENSE file in the root directory of this source tree. 6 */const kl=[["path",{d:"m16 3 4 4-4 4",key:"1x1c3m"}],["path",{d:"M20 7H4",key:"zbl0bi"}],["path",{d:"m8 21-4-4 4-4",key:"h9nckh"}],["path",{d:"M4 17h16",key:"g4d7ey"}]],Rl=ar("arrow-right-left",kl);/** 7 * @license lucide-react v0.554.0 - ISC 8 * 9 * This source code is licensed under the ISC license. 10 * See the LICENSE file in the root directory of this source tree. 11 */const Dl=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M16 22a4 4 0 0 0-8 0",key:"7a83pg"}],["circle",{cx:"12",cy:"15",r:"3",key:"g36mzq"}]],El=ar("file-user",Dl);/** 12 * @license lucide-react v0.554.0 - ISC 13 * 14 * This source code is licensed under the ISC license. 15 * See the LICENSE file in the root directory of this source tree. 16 */const Tl=[["path",{d:"M18 11V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2",key:"1fvzgz"}],["path",{d:"M14 10V4a2 2 0 0 0-2-2a2 2 0 0 0-2 2v2",key:"1kc0my"}],["path",{d:"M10 10.5V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2v8",key:"10h0bg"}],["path",{d:"M18 8a2 2 0 1 1 4 0v6a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15",key:"1s1gnw"}]],Rs=ar("hand",Tl);/** 17 * @license lucide-react v0.554.0 - ISC 18 * 19 * This source code is licensed under the ISC license. 20 * See the LICENSE file in the root directory of this source tree. 21 */const Il=[["path",{d:"M16 10h2",key:"8sgtl7"}],["path",{d:"M16 14h2",key:"epxaof"}],["path",{d:"M6.17 15a3 3 0 0 1 5.66 0",key:"n6f512"}],["circle",{cx:"9",cy:"11",r:"2",key:"yxgjnd"}],["rect",{x:"2",y:"5",width:"20",height:"14",rx:"2",key:"qneu4z"}]],Al=ar("id-card",Il);/** 22 * @license lucide-react v0.554.0 - ISC 23 * 24 * This source code is licensed under the ISC license. 25 * See the LICENSE file in the root directory of this source tree. 26 */const Pl=[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}
26]],Ol=ar("zoom-out",Pl);var Ds=l=>l.graphicalItems.polarItems,Ml=Se([or,Cn],kn),Dr=Se([Ds,yt,Ml],Rn),Fl=Se([Dr],Dn),Er=Se([Fl,ys],En),Ll=Se([Er,yt,Dr],Tn);Se([Er,yt,Dr],(l,t,r)=>r.length>0?l.flatMap(a=>r.flatMap(o=>{var s,i=pt(a,(s=t.dataKey)!==null&&s!==void 0?s:o.dataKey);return{value:i,errorDomain:[]}})).filter(Boolean):(t==null?void 0:t.dataKey)!=null?l.map(a=>({value:pt(a,t.dataKey),errorDomain:[]})):l.map(a=>({value:a,errorDomain:[]})));var za=()=>{},ql=Se([Er,yt,Dr,In,or],An),Ul=Se([yt,Pn,On,za,ql,za,ws,or],Mn),Es=Se([yt,ws,Er,Ll,Fn,or,Ul],Ln),$l=Se([Es,yt,qn],Un);Se([yt,Es,$l,or],$n);function Wa(l,t){var r=Object.keys(l);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(l);t&&(a=a.filter(function(o){return Object.getOwnPropertyDescriptor(l,o).enumerable})),r.push.apply(r,a)}return r}function Va(l){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Wa(Object(r),!0).forEach(function(a){Hl(l,a,r[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(l,Object.getOwnPropertyDescriptors(r)):Wa(Object(r)).forEach(function(a){Object.defineProperty(l,a,Object.getOwnPropertyDescriptor(r,a))})}return l}function Hl(l,t,r){return(t=Bl(t))in l?Object.defineProperty(l,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):l[t]=r,l}function Bl(l){var t=zl(l,"string");return typeof t=="symbol"?t:t+""}function zl(l,t){if(typeof l!="object"||!l)return l;var r=l[Symbol.toPrimitive];if(r!==void 0){var a=r.call(l,t);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(l)}var Wl=(l,t)=>t,xa=Se([Ds,Wl],(l,t)=>l.filter(r=>r.type==="pie").find(r=>r.id===t)),Vl=[],ha=(l,t,r)=>(r==null?void 0:r.length)===0?Vl:r,Ts=Se([ys,xa,ha],(l,t,r)=>{var{chartData:a}=l;if(t!=null){var o;if((t==null?void 0:t.data)!=null&&t.data.length>0?o=t.data:o=a,(!o||!o.length)&&r!=null&&(o=r.map(s=>Va(Va({},t.presentationProps),s.props))),o!=null)return o}}),Kl=Se([Ts,xa,ha],(l,t,r)=>{if(!(l==null||t==null))return l.map((a,o)=>{var s,i=pt(a,t.nameKey,t.name),n;return r!=null&&(s=r[o])!==null&&s!==void 0&&(s=s.props)!==null&&s!==void 0&&s.fill?n=r[o].props.fill:typeof a=="object"&&a!=null&&"fill"in a?n=a.fill:n=t.fill,{value:js(i,t.dataKey),color:n,payload:a,type:t.legendType}})}),Yl=Se([Ts,xa,ha,Hn],(l,t,r,a)=>{if(!(t==null||l==null))return pi({offset:a,pieSettings:t,displayedData:l,cells:r})}),Gl=["key"],Ql=["onMouseEnter","onClick","onMouseLeave"],Zl=["id"],Jl=["id"];function Ka(l,t){var r=Object.keys(l);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(l);t&&(a=a.filter(function(o){return Object.getOwnPropertyDescriptor(l,o).enumerable})),r.push.apply(r,a)}return r}function he(l){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Ka(Object(r),!0).forEach(function(a){Xl(l,a,r[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(l,Object.getOwnPropertyDescriptors(r)):Ka(Object(r)).forEach(function(a){Object.defineProperty(l,a,Object.getOwnPropertyDescriptor(r,a))})}return l}function Xl(l,t,r){return(t=ei(t))in l?Object.defineProperty(l,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):l[t]=r,l}function ei(l){var t=ti(l,"string");return typeof t=="symbol"?t:t+""}function ti(l,t){if(typeof l!="object"||!l)return l;var r=l[Symbol.toPrimitive];if(r!==void 0){var a=r.call(l,t);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(l)}function bt(){return bt=Object.assign?Object.assign.bind():function(l){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var a in r)({}).hasOwnProperty.call(r,a)&&(l[a]=r[a])}return l},bt.apply(null,arguments)}function Tr(l,t){if(l==null)return{};var r,a,o=ri(l,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(l);for(a=0;a<s.length;a++)r=s[a],t.indexOf(r)===-1&&{}.propertyIsEnumerable.call(l,r)&&(o[r]=l[r])}return o}function ri(l,t){if(l==null)return{};var r={};for(var a in l)if({}.hasOwnProperty.call(l,a)){if(t.indexOf(a)!==-1)continue;r[a]=l[a]}return r}function ai(l){var t=x.useMemo(()=>Ss(l.children,Sr),[l.children]),r=Zt(a=>Kl(a,l.id,t));return r==null?null:x.createElement(Wn,{legendPayload:r})}var si=x.memo(l=>{var{dataKey:t,nameKey:r,sectors:a,stroke:o,strokeWidth:s,fill:i,name:n,hide:c,tooltipType:d}=l,m={dataDefinedOnItem:a.map(u=>u.tooltipPayload),positions:a.map(u=>u.tooltipPosition),settings:{stroke:o,strokeWidth:s,fill:i,dataKey:t,nameKey:r,name:js(n,t),hide:c,type:d,color:i,unit:""}}
26;return x.createElement(Vn,{tooltipEntrySettings:m})}),oi=(l,t)=>l>t?"start":l<t?"end":"middle",ni=(l,t,r)=>typeof t=="function"?Jt(t(l),r,r*.8):Jt(t,r,r*.8),li=(l,t,r)=>{var{top:a,left:o,width:s,height:i}=t,n=sl(s,i),c=o+Jt(l.cx,s,s/2),d=a+Jt(l.cy,i,i/2),m=Jt(l.innerRadius,n,0),u=ni(r,l.outerRadius,n),h=l.maxRadius||Math.sqrt(s*s+i*i)/2;return{cx:c,cy:d,innerRadius:m,outerRadius:u,maxRadius:h}},ii=(l,t)=>{var r=wr(t-l),a=Math.min(Math.abs(t-l),360);return r*a};function ci(l){return l&&typeof l=="object"&&"className"in l&&typeof l.className=="string"?l.className:""}var di=(l,t)=>{if(x.isValidElement(l))return x.cloneElement(l,t);if(typeof l=="function")return l(t);var r=ma("recharts-pie-label-line",typeof l!="boolean"?l.className:""),{key:a}=t,o=Tr(t,Gl);return x.createElement(ol,bt({},o,{type:"linear",className:r}))},ui=(l,t,r)=>{if(x.isValidElement(l))return x.cloneElement(l,t);var a=r;if(typeof l=="function"&&(a=l(t),x.isValidElement(a)))return a;var o=ma("recharts-pie-label-text",ci(l));return x.createElement(nl,bt({},t,{alignmentBaseline:"middle",className:o}),a)};function mi(l){var{sectors:t,props:r,showLabels:a}=l,{label:o,labelLine:s,dataKey:i}=r;if(!a||!o||!t)return null;var n=_s(r),c=$a(o),d=$a(s),m=typeof o=="object"&&"offsetRadius"in o&&typeof o.offsetRadius=="number"&&o.offsetRadius||20,u=t.map((h,v)=>{var y=(h.startAngle+h.endAngle)/2,p=Xr(h.cx,h.cy,h.outerRadius+m,y),N=he(he(he(he({},n),h),{},{stroke:"none"},c),{},{index:v,textAnchor:oi(p.x,h.cx)},p),S=he(he(he(he({},n),h),{},{fill:"none",stroke:h.fill},d),{},{index:v,points:[Xr(h.cx,h.cy,h.outerRadius,y),p],key:"line"});return x.createElement(Cs,{zIndex:Ns.label,key:"label-".concat(h.startAngle,"-").concat(h.endAngle,"-").concat(h.midAngle,"-").concat(v)},x.createElement(Ut,null,s&&di(s,S),ui(o,N,pt(h,i))))});return x.createElement(Ut,{className:"recharts-pie-labels"},u)}function xi(l){var{sectors:t,props:r,showLabels:a}=l,{label:o}=r;return typeof o=="object"&&o!=null&&"position"in o?x.createElement(al,{label:o}):x.createElement(mi,{sectors:t,props:r,showLabels:a})}function hi(l){var{sectors:t,activeShape:r,inactiveShape:a,allOtherPieProps:o,shape:s,id:i}=l,n=Zt(Zn),c=Zt(Jn),d=Zt(Xn),{onMouseEnter:m,onClick:u,onMouseLeave:h}=o,v=Tr(o,Ql),y=pl(m,o.dataKey,i),p=vl(h),N=fl(u,o.dataKey,i);return t==null||t.length===0?null:x.createElement(x.Fragment,null,t.map((S,j)=>{if((S==null?void 0:S.startAngle)===0&&(S==null?void 0:S.endAngle)===0&&t.length!==1)return null;var I=d==null||d===i,$=String(j)===n&&(c==null||o.dataKey===c)&&I,R=n?a:null,E=r&&$?r:R,O=he(he({},S),{},{stroke:S.stroke,tabIndex:-1,[tl]:j,[el]:o.dataKey});return x.createElement(Ut,bt({key:"sector-".concat(S==null?void 0:S.startAngle,"-").concat(S==null?void 0:S.endAngle,"-").concat(S.midAngle,"-").concat(j),tabIndex:-1,className:"recharts-pie-sector"},rl(v,S,j),{onMouseEnter:y(S,j),onMouseLeave:p(S,j),onClick:N(S,j)}),x.createElement(_n,bt({option:s??E,index:j,shapeType:"sector",isActive:$},O)))}))}function pi(l){var t,{pieSettings:r,displayedData:a,cells:o,offset:s}=l,{cornerRadius:i,startAngle:n,endAngle:c,dataKey:d,nameKey:m,tooltipType:u}=r,h=Math.abs(r.minAngle),v=ii(n,c),y=Math.abs(v),p=a.length<=1?0:(t=r.paddingAngle)!==null&&t!==void 0?t:0,N=a.filter(E=>pt(E,d,0)!==0).length,S=(y>=360?N:N-1)*p,j=y-N*h-S,I=a.reduce((E,O)=>{var D=pt(O,d,0);return E+(Ua(D)?D:0)},0),$;if(I>0){var R;$=a.map((E,O)=>{var D=pt(E,d,0),b=pt(E,m,O),P=li(r,s,E),W=(Ua(D)?D:0)/I,k,f=he(he({},E),o&&o[O]&&o[O].props);O?k=R.endAngle+wr(v)*p*(D!==0?1:0):k=n;var g=k+wr(v)*((D!==0?h:0)+W*j),L=(k+g)/2,z=(P.innerRadius+P.outerRadius)/2,X=[{name:b,value:D,payload:f,dataKey:d,type:u}],C=Xr(P.cx,P.cy,z,L);return R=he(he(he(he({},r.presentationProps),{},{percent:W,cornerRadius:typeof i=="string"?parseFloat(i):i,name:b,tooltipPayload:X,midAngle:L,middleRadius:z,tooltipPosition:C},f),P),{},{value:D,dataKey:d,startAngle:k,endAngle:g,payload:f,paddingAngle:wr(v)*p}),R})}return $}function vi(l){var{showLabels:t,sectors:r,children:a}=l,o=x.useMemo(()=>!t||!r?[]:r.map(s=>({value:s.value,payload:s.payload,clockWise:!1,parentViewBox:void 0,viewB
26ox:{cx:s.cx,cy:s.cy,innerRadius:s.innerRadius,outerRadius:s.outerRadius,startAngle:s.startAngle,endAngle:s.endAngle,clockWise:!1},fill:s.fill})),[r,t]);return x.createElement(Qn,{value:t?o:void 0},a)}function fi(l){var{props:t,previousSectorsRef:r,id:a}=l,{sectors:o,isAnimationActive:s,animationBegin:i,animationDuration:n,animationEasing:c,activeShape:d,inactiveShape:m,onAnimationStart:u,onAnimationEnd:h}=t,v=Kn(t,"recharts-pie-"),y=r.current,[p,N]=x.useState(!1),S=x.useCallback(()=>{typeof h=="function"&&h(),N(!1)},[h]),j=x.useCallback(()=>{typeof u=="function"&&u(),N(!0)},[u]);return x.createElement(vi,{showLabels:!p,sectors:o},x.createElement(Yn,{animationId:v,begin:i,duration:n,isActive:s,easing:c,onAnimationStart:j,onAnimationEnd:S,key:v},I=>{var $=[],R=o&&o[0],E=R==null?void 0:R.startAngle;return o==null||o.forEach((O,D)=>{var b=y&&y[D],P=D>0?Gn(O,"paddingAngle",0):0;if(b){var W=qa(b.endAngle-b.startAngle,O.endAngle-O.startAngle,I),k=he(he({},O),{},{startAngle:E+P,endAngle:E+W+P});$.push(k),E=k.endAngle}else{var{endAngle:f,startAngle:g}=O,L=qa(0,f-g,I),z=he(he({},O),{},{startAngle:E+P,endAngle:E+L+P});$.push(z),E=z.endAngle}}),r.current=$,x.createElement(Ut,null,x.createElement(hi,{sectors:$,activeShape:d,inactiveShape:m,allOtherPieProps:t,shape:t.shape,id:a}))}),x.createElement(xi,{showLabels:!p,sectors:o,props:t}),t.children)}var gi={animationBegin:400,animationDuration:1500,animationEasing:"ease",cx:"50%",cy:"50%",dataKey:"value",endAngle:360,fill:"#808080",hide:!1,innerRadius:0,isAnimationActive:"auto",label:!1,labelLine:!0,legendType:"rect",minAngle:0,nameKey:"name",outerRadius:"80%",paddingAngle:0,rootTabIndex:0,startAngle:0,stroke:"#fff",zIndex:Ns.area};function bi(l){var{id:t}=l,r=Tr(l,Zl),{hide:a,className:o,rootTabIndex:s}=l,i=x.useMemo(()=>Ss(l.children,Sr),[l.children]),n=Zt(m=>Yl(m,t,i)),c=x.useRef(null),d=ma("recharts-pie",o);return a||n==null?(c.current=null,x.createElement(Ut,{tabIndex:s,className:d})):x.createElement(Cs,{zIndex:l.zIndex},x.createElement(si,{dataKey:l.dataKey,nameKey:l.nameKey,sectors:n,stroke:l.stroke,strokeWidth:l.strokeWidth,fill:l.fill,name:l.name,hide:l.hide,tooltipType:l.tooltipType}),x.createElement(Ut,{tabIndex:s,className:d},x.createElement(fi,{props:he(he({},r),{},{sectors:n}),previousSectorsRef:c,id:t})))}function Is(l){var t=ua(l,gi),{id:r}=t,a=Tr(t,Jl),o=_s(a);return x.createElement(Bn,{id:r,type:"pie"},s=>x.createElement(x.Fragment,null,x.createElement(zn,{type:"pie",id:s,data:a.data,dataKey:a.dataKey,hide:a.hide,angleAxisId:0,radiusAxisId:0,name:a.name,nameKey:a.nameKey,tooltipType:a.tooltipType,legendType:a.legendType,fill:a.fill,cx:a.cx,cy:a.cy,startAngle:a.startAngle,endAngle:a.endAngle,paddingAngle:a.paddingAngle,minAngle:a.minAngle,innerRadius:a.innerRadius,outerRadius:a.outerRadius,cornerRadius:a.cornerRadius,presentationProps:o,maxRadius:t.maxRadius}),x.createElement(ai,bt({},a,{id:s})),x.createElement(bi,bt({},a,{id:s}))))}Is.displayName="Pie";function yi(l){var t=ll();return x.useEffect(()=>{t(il(l))},[t,l]),null}var wi=["layout"];function ea(){return ea=Object.assign?Object.assign.bind():function(l){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var a in r)({}).hasOwnProperty.call(r,a)&&(l[a]=r[a])}return l},ea.apply(null,arguments)}function ji(l,t){if(l==null)return{};var r,a,o=_i(l,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(l);for(a=0;a<s.length;a++)r=s[a],t.indexOf(r)===-1&&{}.propertyIsEnumerable.call(l,r)&&(o[r]=l[r])}return o}function _i(l,t){if(l==null)return{};var r={};for(var a in l)if({}.hasOwnProperty.call(l,a)){if(t.indexOf(a)!==-1)continue;r[a]=l[a]}return r}var Ni={top:5,right:5,bottom:5,left:5},As={accessibilityLayer:!0,stackOffset:"none",barCategoryGap:"10%",barGap:4,margin:Ni,reverseStackOrder:!1,syncMethod:"index",layout:"radial",responsive:!1,cx:"50%",cy:"50%",innerRadius:0,outerRadius:"80%"},Si=x.forwardRef(function(t,r){var a,o=ua(t.categoricalChartProps,As),{layout:s}=o,i=ji(o,wi),{chartName:n,defaultTooltipEventType:c,validateTooltipEventTypes:d,tooltipPayloadSearcher:m}=t,u={chartName:n,defaultTooltipEventType:c,validateTooltipEventTypes:d,tooltipPayloadSearcher:m,eventEmitter:void 0};return x.createElement(cl,{preloadedState:{options:u},reduxStoreName:(a=o.id)!==null&&a!==void 0?a:n},x.createElement(dl,{chartData:o.data}),x.createElement(ul,{layout:s,margin:o.margin}),x.createElement(ml,{baseValue:void 0,accessibilityLayer:o.accessibilityLayer,barCategoryGap:o.barCategoryGap,maxBarSize:o.maxBarSize,stackOffset:o.stackOffset,barGap:o.barGap,barSize:o.barSize,syncId:o.syncId,syncMethod:o.syncMethod,className:o.className,reverseStackOrder:o.reverseStackOrder}),x.createElement(yi,{cx:o.cx,cy:o.cy,startAngle:o.startAngle,endAngle:o.endAngle,innerRadius:o.innerRadius,outerRadius:o.outerRadius}),x.createElement(xl,ea({},i,{ref:r})))});function Ya(l,t){var r=Object.keys(l);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(l);t&&(a=a.filter(function(o){return Object.getOwnPropertyDescriptor(l,o).enumerable})),r.push.apply(r,a)}return r}function Ga(l){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};
26t%2?Ya(Object(r),!0).forEach(function(a){Ci(l,a,r[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(l,Object.getOwnPropertyDescriptors(r)):Ya(Object(r)).forEach(function(a){Object.defineProperty(l,a,Object.getOwnPropertyDescriptor(r,a))})}return l}function Ci(l,t,r){return(t=ki(t))in l?Object.defineProperty(l,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):l[t]=r,l}function ki(l){var t=Ri(l,"string");return typeof t=="symbol"?t:t+""}function Ri(l,t){if(typeof l!="object"||!l)return l;var r=l[Symbol.toPrimitive];if(r!==void 0){var a=r.call(l,t);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(l)}var Di=["item"],Ei=Ga(Ga({},As),{},{layout:"centric",startAngle:0,endAngle:360}),Ti=x.forwardRef((l,t)=>{var r=ua(l,Ei);return x.createElement(Si,{chartName:"PieChart",defaultTooltipEventType:"item",validateTooltipEventTypes:Di,tooltipPayloadSearcher:hl,categoricalChartProps:r,ref:t})});const Mt={prefix:"EMP",separator:"-",paddingLength:3,startingNumber:1,nextNumber:1,includeYear:!1,yearFormat:"4"};function Ir(){var t;const l=(t=De.getCurrentTenant())==null?void 0:t.id;if(!l)throw new Error("No tenant selected");return B(gt,"tenants",l,"settings","employeeNumberSchema")}function Ps(){var t;const l=(t=De.getCurrentTenant())==null?void 0:t.id;if(!l)throw new Error("No tenant selected");return H(gt,"tenants",l,"employees")}function Ii(l,t){return l.toString().padStart(t,"0")}function pa(l,t){const r=[l.prefix];if(l.includeYear){const a=new Date().getFullYear(),o=l.yearFormat==="2"?a.toString().slice(-2):a.toString();r.push(o)}return r.push(Ii(t,l.paddingLength)),r.join(l.separator)}async function nr(){try{const l=Ir(),t=await oe(l);return t.exists()?{...Mt,...t.data()}:(await Lt(l,Mt),Mt)}catch(l){return console.error("[EmployeeNumberService] Failed to get schema:",l),Mt}}async function Ai(l){const t=Ir(),a={...await nr(),...l};return l.startingNumber!==void 0&&l.startingNumber>a.nextNumber&&(a.nextNumber=l.startingNumber),await Lt(t,a),a}async function Pi(){const l=Ir(),t=await nr(),r=pa(t,t.nextNumber);return await Q(l,{nextNumber:t.nextNumber+1}),r}async function Oi(){const l=await nr();return pa(l,l.nextNumber)}function Mi(l,t){return pa(l,t??l.nextNumber)}async function Fi(l){const t=Ps(),r=V(t,K("employeeNumber","==",l),Jr(1));return!(await Z(r)).empty}async function Li(){const l=await nr(),t=Ps(),r=V(t,K("employeeNumber","!=",null)),a=await Z(r);let o=l.startingNumber-1;const s=new RegExp(`^${l.prefix}${l.separator}(?:\\d+${l.separator})?(\\d+)$`);for(const n of a.docs){const c=n.data().employeeNumber;if(!c)continue;const d=c.match(s);if(d){const m=parseInt(d[1],10);m>o&&(o=m)}}const i=o+1;return await Q(Ir(),{nextNumber:i}),i}function qi(l,t){const r=l.split(t.separator);if(r[0]!==t.prefix)return!1;const a=t.includeYear?3:2;if(r.length!==a)return!1;const o=r[r.length-1];return!!/^\d+$/.test(o)}const Gt={getSchema:nr,updateSchema:Ai,generateNextNumber:Pi,previewNextNumber:Oi,previewWithSchema:Mi,numberExists:Fi,syncNextNumber:Li,validateFormat:qi,DEFAULT_SCHEMA:Mt};class Ui{constructor(){this.employees=[],this.listeners=[],this.unsubscribeFn=null,this.initialized=!1}async initialize(){if(this.initialized)return;const t=this.resolveTenantId();if(!t){console.warn("[HREmployeeService] tenantId not available yet, will retry"),setTimeout(()=>this.initialize(),1e3);return}await this.loadEmployees(t),this.setupRealtimeListener(t),this.initialized=!0,console.log("[HREmployeeService] Initialized with",this.employees.length,"employees")}resolveTenantId(){var r;const t=typeof window<"u"?window.localStorage.getItem("tenantId"):null;if(t)return t;try{return((r=De.getCurrentTenant())==null?void 0:r.id)||null}catch{return null}}async getEmployees(){const t=A.getCurrentUser().tenantId,r=T(t,Be),a=H(_,r),o=V(a,ee("lastName","asc"));return(await Z(o)).docs.map(i=>({...i.data(),id:i.id}))}async getEmployee(t){const r=A.getCurrentUser().tenantId,a=T(r,Be),o=B(_,a,t),s=await oe(o);return s.exists()?{...s.data(),id:s.id}:null}async createEmployee(t){const r=A.getCurrentUser(),a=r.tenantId,o=T(a,Be),s=H(_,o);let i=t.employeeNumber;if(!i)try{i=await Gt.generateNextNumber()}catch(m){console.warn("[HREmployeeService] Failed to generate employee number:",m)}const n={tenantId:a,employeeNumber:i||null,firstName:t.firstName||"",lastName:t.lastName||"",email:t.email||"",phone:t.phone||"",role:t.role||"",department:t.department||"",managerId:t.managerId||null,hireDate:t.hireDate||new Date().toISOString().split("T")[0],status:t.status||"Active",employmentType:t.employmentType||"Full Time",address:t.address||"",dob:t.dob||"",emergencyContact:t.emergencyContact||null,payType:t.payType||"Salary",payRate:t.payRate||0,flightRiskScore:t.flightRiskScore||0,burnoutRiskScore:t.burnoutRiskScore||0,performanceRating:t.performanceRating||3,notes:t.notes||"",hasUserAccount:t.hasUserAccount||!1,userAccountInvitedAt:t.userAccountInvitedAt||null,createdAt:ht.now(),updatedAt:ht.now(),createdBy:r.i
26d};Object.keys(n).forEach(m=>{n[m]===void 0&&delete n[m]});const c=await ie(s,n),d={...n,id:c.id};return this.employees.push(d),this.notifyListeners(),console.log("[HREmployeeService] Created employee:",c.id),d}async updateEmployee(t,r){const a=A.getCurrentUser().tenantId,o=T(a,Be),s=B(_,o,t),i={...r,updatedAt:ht.now()};delete i.id,delete i.tenantId,delete i.createdAt,delete i.createdBy,Object.keys(i).forEach(c=>{i[c]===void 0&&delete i[c]}),await Q(s,i);const n=this.employees.findIndex(c=>c.id===t);return n!==-1&&(this.employees[n]={...this.employees[n],...r},this.notifyListeners()),console.log("[HREmployeeService] Updated employee:",t),this.getEmployee(t)}async deleteEmployee(t,r=!0){const a=A.getCurrentUser().tenantId,o=T(a,Be),s=B(_,o,t);if(r?(await Q(s,{status:"Terminated",updatedAt:ht.now()}),console.log("[HREmployeeService] Soft deleted (terminated) employee:",t)):(await ke(s),console.log("[HREmployeeService] Hard deleted employee:",t)),r){const i=this.employees.findIndex(n=>n.id===t);i!==-1&&(this.employees[i].status="Terminated")}else this.employees=this.employees.filter(i=>i.id!==t);return this.notifyListeners(),!0}getEmployeesFromCache(){return this.employees}async getActiveEmployees(){return(await this.getEmployees()).filter(r=>r.status==="Active")}async getEmployeesByDepartment(t){const r=A.getCurrentUser().tenantId,a=T(r,Be),o=H(_,a),s=V(o,K("department","==",t),ee("lastName","asc"));return(await Z(s)).docs.map(n=>({...n.data(),id:n.id}))}async getEmployeesByStatus(t){const r=A.getCurrentUser().tenantId,a=T(r,Be),o=H(_,a),s=V(o,K("status","==",t),ee("lastName","asc"));return(await Z(s)).docs.map(n=>({...n.data(),id:n.id}))}filterEmployees(t,r){return t.filter(a=>{if(r.query){const o=r.query.toLowerCase();if(!((a.firstName||"").toLowerCase().includes(o)||(a.lastName||"").toLowerCase().includes(o)||(a.email||"").toLowerCase().includes(o)||(a.role||"").toLowerCase().includes(o)||(a.department||"").toLowerCase().includes(o)))return!1}return!(r.departments&&r.departments.length>0&&!r.departments.includes(a.department)||r.statuses&&r.statuses.length>0&&!r.statuses.includes(a.status)||r.employmentTypes&&r.employmentTypes.length>0&&!r.employmentTypes.includes(a.employmentType))})}getDepartments(){const t=new Set;return this.employees.forEach(r=>{r.department&&t.add(r.department)}),Array.from(t).sort()}async getDirectReports(t){const r=A.getCurrentUser().tenantId,a=T(r,Be),o=H(_,a),s=V(o,K("managerId","==",t),ee("lastName","asc"));return(await Z(s)).docs.map(n=>({...n.data(),id:n.id}))}async getManagerChain(t){const r=[];let a=await this.getEmployee(t);for(;a!=null&&a.managerId;){const o=await this.getEmployee(a.managerId);if(o)r.push(o),a=o;else break}return r}async bulkCreateEmployees(t){const r={succeeded:0,failed:0,errors:[]};for(let a=0;a<t.length;a++)try{await this.createEmployee(t[a]),r.succeeded++}catch(o){r.failed++,r.errors.push(`Row ${a+1}: ${o.message||"Unknown error"}`)}return r}async bulkUpdateEmployees(t,r){const a=t.map(o=>this.updateEmployee(o,r));await Promise.all(a)}async loadEmployees(t){const r=T(t,Be),a=H(_,r),o=V(a,ee("lastName","asc")),s=await Z(o);this.employees=s.docs.map(i=>({...i.data(),id:i.id}))}setupRealtimeListener(t){this.unsubscribeFn&&this.unsubscribeFn();const r=T(t,Be),a=H(_,r),o=V(a,ee("lastName","asc"));this.unsubscribeFn=we(o,s=>{this.employees=s.docs.map(i=>({...i.data(),id:i.id})),console.log("[HREmployeeService] Real-time update:",this.employees.length,"employees"),this.notifyListeners()},s=>{console.warn("[HREmployeeService] Listener error:",s)})}subscribe(t){return this.listeners.push(t),this.initialized||this.initialize(),()=>{this.listeners=this.listeners.filter(r=>r!==t)}}subscribeToEmployees(t,r){const a=this.resolveTenantId();return a?this.setupFilteredSubscription(a,t,r):(console.warn("[HREmployeeService] No tenantId available for subscription"),r([]),setTimeout(()=>{const o=this.resolveTenantId();o&&this.setupFilteredSubscription(o,t,r)},1e3),()=>{})}setupFilteredSubscription(t,r,a){const o=T(t,Be),s=H(_,o),i=V(s,ee("lastName","asc"));return we(i,c=>{let d=c.docs.map(m=>({...m.data(),id:m.id}));r&&(d=this.filterEmployees(d,{query:r.query||"",departments:r.departments||[],statuses:r.statuses||[],employmentTypes:r.employmentTypes||[]})),a(d)},c=>{console.error("[HREmployeeService] Subscription error:",c),a([])})}
26notifyListeners(){this.listeners.forEach(t=>t())}cleanup(){this.unsubscribeFn&&(this.unsubscribeFn(),this.unsubscribeFn=null),this.listeners=[],this.employees=[],this.initialized=!1}}const Qe=new Ui,St="hr_location_managers",$i="hr_locations";class Hi{async getLocationManagers(){const t=A.getCurrentUser().tenantId,r=T(t,St),a=H(_,r),o=V(a,ee("created_at","desc"));return(await Z(o)).docs.map(i=>({...i.data(),id:i.id}))}async getManagersForLocation(t){const r=A.getCurrentUser().tenantId,a=T(r,St),o=H(_,a),s=V(o,K("location_id","==",t),ee("created_at","desc"));return(await Z(s)).docs.map(n=>({...n.data(),id:n.id}))}async getLocationsForUser(t){const r=A.getCurrentUser().tenantId,a=T(r,St),o=H(_,a),s=V(o,K("user_id","==",t));return(await Z(s)).docs.map(n=>({...n.data(),id:n.id}))}async addLocationManager(t,r,a){const o=A.getCurrentUser().tenantId,s=T(o,St),i=H(_,s),c=(await this.getLocationsForUser(r)).find(h=>h.location_id===t);if(c)return this.updateLocationManagerRole(c.id,a);const d=new Date().toISOString(),m={tenant_id:o,location_id:t,user_id:r,role:a,created_at:d},u=await ie(i,m);return console.log("[HRLocationManagerService] Added location manager:",u.id),{...m,id:u.id}}async updateLocationManagerRole(t,r){const a=A.getCurrentUser().tenantId,o=T(a,St),s=B(_,o,t);if(!(await oe(s)).exists())return null;await Q(s,{role:r}),console.log("[HRLocationManagerService] Updated role for:",t);const n=await oe(s);return{...n.data(),id:n.id}}async removeLocationManager(t){const r=A.getCurrentUser().tenantId,a=T(r,St),o=B(_,a,t);return(await oe(o)).exists()?(await ke(o),console.log("[HRLocationManagerService] Removed location manager:",t),!0):!1}async getCurrentUserScope(){const t=A.getCurrentUser();if(t.role==="admin")return{location_ids:[],is_admin:!0,role:"admin"};const r=await this.getLocationsForUser(t.id);if(r.length===0)return{location_ids:[],is_admin:!1,role:"viewer"};const a=["viewer","scheduler","manager"];let o="viewer";for(const s of r){const i=a.indexOf(s.role),n=a.indexOf(o);i>n&&(o=s.role)}return{location_ids:r.map(s=>s.location_id),is_admin:!1,role:o}}async canAccessLocation(t){const r=await this.getCurrentUserScope();return r.is_admin?!0:r.location_ids.length===0?!1:r.location_ids.includes(t)}async hasRoleForLocation(t,r){const a=A.getCurrentUser();if(a.role==="admin")return!0;const s=(await this.getLocationsForUser(a.id)).find(i=>i.location_id===t);return s?r.includes(s.role):!1}async getAccessibleLocations(){const t=A.getCurrentUser().tenantId,r=await this.getCurrentUserScope(),a=T(t,$i),o=H(_,a),s=V(o,K("status","==","active"));let n=(await Z(s)).docs.map(c=>({...c.data(),id:c.id}));return!r.is_admin&&r.location_ids.length>0?n=n.filter(c=>r.location_ids.includes(c.id)):!r.is_admin&&r.location_ids.length===0&&(n=[]),n}async checkSchedulingPermission(t,r){if(A.getCurrentUser().role==="admin")return{allowed:!0};if(r&&!await this.canAccessLocation(r))return{allowed:!1,reason:"No access to this location"};const s={"hr.schedule.view":["viewer","scheduler","manager"],"hr.schedule.create":["scheduler","manager"],"hr.schedule.edit":["scheduler","manager"],"hr.schedule.delete":["scheduler","manager"],"hr.schedule.assign":["scheduler","manager"],"hr.schedule.publish":["manager"],"hr.schedule.manage":["manager"],"hr.schedule.approve_requests":["manager"],"hr.template.manage":["manager"],"hr.template.apply":["scheduler","manager"]}[t];if(!s)return{allowed:!1,reason:"Unknown permission"};if(r){const u=await this.hasRoleForLocation(r,s);return{allowed:u,reason:u?void 0:"Insufficient role for this location"}}const i=await this.getCurrentUserScope();if(i.location_ids.length===0)return{allowed:!1,reason:"No location assignments"};const n=["viewer","scheduler","manager"],c=n.indexOf(i.role),d=Math.min(...s.map(u=>n.indexOf(u))),m=c>=d;return{allowed:m,reason:m?void 0:"Insufficient role"}}subscribeToLocationManagers(t,r){var c;const a=(c=A.getCurrentUser())==null?void 0:c.tenantId;if(!a)return r([]),()=>{};const o=T(a,St),s=H(_,o),i=V(s,K("location_id","==",t),ee("created_at","desc"));return we(i,d=>{const m=d.docs.map(u=>({...u.data(),id:u.id}));r(m)},d=>{console.error("[HRLocationManagerService] Subscription error:",d),r([])})}}const Bi=new Hi,mr="hr_domain_events";class zi{constructor(){this.consumers=new Map,this.requestId="",this.correlationId=""}setContext(t,r){this.requestId=t,this.correlationId=r||t}generateUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const r=Math.random()*16|0;return(t==="x"?r:r&3|8).toString(16)})}async publish(t,r,a="web"){const o=A.getCurrentUser(),s=(o==null?void 0:o.tenantId)||"unknown",i=this.generateUUID(),n=new Date().toISOString(),c={event_id:i,event_type:t,event_version:"1.0",tenant_id:s,actor_id:(o==null?void 0:o.id)||null,occurred_at:n,payload:r,metadata:{request_id:this.requestId||this.generateUUID(),source:a,correlation_id:this.correlationId||this.generateUUID(),module:"hr.scheduling",hr_tier:"hris"}},d=T(s,mr),m=H(_,d),u=await ie(m,c),h={...c,id:u.id};return console.log("[HREventBusService] Published:",t,i),await this.notifyConsumers(h),h}subscribe(t,r){const a=this.consumers.get(t)||[];return a.push(r),this.consumers.set(t,a),()=>{var s;const o=((s=this.consumers.get(t))==null?void 0:s.filter(i=>i!==r))||[];this.consumers.set(t,o)}}async notifyConsumers(t){const r=t,a=this.consumers.get(t.event_type)||[];for(const s of a)try{await s(r)}catch(i){console.error("[HREventBusService] Consumer error:",i)}const o=this.consumers.get("*")||[];for(const s of o)try{await s(r)}catch(i){console.error("[HREventBusService] Wildcard consumer error:",i)}}
26async publishShiftCreated(t){await this.publish("hr.shift.created",t)}async publishShiftPublished(t){await this.publish("hr.shift.published",t)}async publishShiftAssigned(t){await this.publish("hr.shift.assigned",t)}async publishShiftUnassigned(t){await this.publish("hr.shift.unassigned",t)}async publishShiftOpened(t,r){await this.publish("hr.shift.opened",{shift_id:t,version:r})}async publishCoverageRequested(t){await this.publish("hr.coverage.requested",t)}async publishCoverageResolved(t){await this.publish("hr.coverage.resolved",t)}async publishSwapRequested(t){await this.publish("hr.swap.requested",t)}async publishSwapCompleted(t){await this.publish("hr.swap.completed",t)}async publishTemplateApplied(t){await this.publish("hr.template.applied",t)}async publishBatchPublish(t){await this.publish("hr.schedule.publish_batch",t)}async publishSuspensionShiftsCleared(t){await this.publish("hr.suspension.shifts_cleared",t)}async publishShiftUpdated(t){await this.publish("hr.shift.updated",t)}async publishShiftCanceled(t){await this.publish("hr.
26shift.canceled",t)}async publishPickupRequested(t){await this.publish("hr.pickup.requested",t)}async publishPickupApproved(t){await this.publish("hr.pickup.approved",t)}async publishPickupRejected(t){await this.publish("hr.pickup.rejected",t)}async publishPickupClaimed(t){await this.publish("hr.pickup.claimed",t)}async publishCoverageApproved(t){await this.publish("hr.coverage.approved",t)}async publishCoverageRejected(t){await this.publish("hr.coverage.rejected",t)}async publishSwapAccepted(t){await this.publish("hr.swap.accepted",t)}async publishSwapRejected(t){await this.publish("hr.swap.rejected",t)}async publishSwapCanceled(t){await this.publish("hr.swap.canceled",t)}async publishAvailabilityUpdated(t){await this.publish("hr.availability.updated",t)}async getRecentEvents(t,r=50){const a=A.getCurrentUser().tenantId,o=T(a,mr),s=H(_,o);let i=V(s,ee("occurred_at","desc"),Jr(r)),c=(await Z(i)).docs.map(d=>({...d.data(),id:d.id}));return t!=null&&t.length&&(c=c.filter(d=>t.includes(d.event_type))),c}async getEventsForEntity(t,r){const a=A.getCurrentUser().tenantId,o=T(a,mr),s=H(_,o),i=V(s,ee("occurred_at","desc"));return(await Z(i)).docs.map(d=>({...d.data(),id:d.id})).filter(d=>{const m=d.payload;switch(t){case"shift":return m.shift_id===r;case"swap":return m.swap_id===r;case"coverage":return m.coverage_request_id===r;default:return!1}})}subscribeToEvents(t,r){var c;const a=(c=A.getCurrentUser())==null?void 0:c.tenantId;if(!a)return r([]),()=>{};const o=T(a,mr),s=H(_,o),i=V(s,ee("occurred_at","desc"),Jr(100));return we(i,d=>{let m=d.docs.map(u=>({...u.data(),id:u.id}));t!=="*"&&t.length&&(m=m.filter(u=>t.includes(u.event_type))),r(m)},d=>{console.error("[HREventBusService] Subscription error:",d),r([])})}}const se=new zi,ct="hr_shift_coverage_requests";class Wi{async getCoverageRequests(t){var c;const r=A.getCurrentUser().tenantId,a=T(r,ct),o=H(_,a),s=V(o,ee("created_at","desc"));let n=(await Z(s)).docs.map(d=>({...d.data(),id:d.id}));return t&&(t.employee_id&&(n=n.filter(d=>d.requested_by_employee_id===t.employee_id)),t.shift_id&&(n=n.filter(d=>d.shift_id===t.shift_id)),(c=t.statuses)!=null&&c.length&&(n=n.filter(d=>t.statuses.includes(d.status))),t.include_resolved||(n=n.filter(d=>d.status!=="resolved"))),n}async getCoverageRequest(t){const r=A.getCurrentUser().tenantId,a=T(r,ct),o=B(_,a,t),s=await oe(o);return s.exists()?{...s.data(),id:s.id}:null}async getPendingCoverageRequests(){return this.getCoverageRequests({statuses:["pending"],include_resolved:!1})}async getCoverageRequestsForShift(t){return this.getCoverageRequests({shift_id:t,include_resolved:!0})}async createCoverageRequest(t){const r=A.getCurrentUser().tenantId,a=T(r,ct),o=H(_,a),s=new Date().toISOString(),i={tenant_id:r,shift_id:t.shift_id,requested_by_employee_id:t.requested_by_employee_id,status:"pending",resolution:null,resolved_by_user_id:null,reason:t.reason,created_at:s,updated_at:s},n=await ie(o,i);return await se.publishCoverageRequested({shift_id:t.shift_id,employee_id:t.requested_by_employee_id,coverage_request_id:n.id,reason:t.reason}),console.log("[HRCoverageService] Created coverage request:",n.id),{...i,id:n.id}}async resolveCoverageRequest(t,r){const a=A.getCurrentUser(),o=a.tenantId,s=T(o,ct),i=B(_,s,t),n=await this.getCoverageRequest(t);if(!n)return null;if(n.status!=="pending"&&n.status!=="approved")throw new Error("Can only resolve pending or approved coverage requests");const c=new Date().toISOString();return await Q(i,{status:"resolved",resolution:r.resolution,resolved_by_user_id:a.id,updated_at:c}),await se.publishCoverageResolved({shift_id:n.shift_id,resolution:r.resolution,replacement_employee_id:r.reassign_to_employee_id,coverage_request_id:t}),console.log("[HRCoverageService] Resolved coverage request:",t,"as",r.resolution),this.getCoverageRequest(t)}async approveCoverageRequest(t){const a=A.getCurrentUser().tenantId,o=T(a,ct),s=B(_,o,t),i=await this.getCoverageRequest(t);if(!i)return null;if(i.status!=="pending")throw new Error("Can only approve pending coverage requests");const n=new Date().toISOString();return await Q(s,{status:"approved",updated_at:n}),await se.publishCoverageApproved({coverage_request_id:t,shift_id:i.shift_id,employee_id:i.requested_by_employee_id}),console.log("[HRCoverageService] Approved coverage request:",t),this.getCoverageRequest(t)}async rejectCoverageRequest(t,r){const o=A.getCurrentUser().tenantId,s=T(o,ct),i=B(_,s,t),n=await this.getCoverageRequest(t);if(!n)return null;if(n.status!=="pending")throw new Error("Can only reject pending coverage requests");const c=new Date().toISOString();return await Q(i,{status:"rejected",reason:r||n.reason,updated_at:c}),await se.publishCoverageRejected({coverage_request_id:t,shift_id:n.shift_id,employee_id:n.requested_by_employee_id,reason:r}),console.log("[HRCoverageService] Rejected coverage request:",t),this.getCoverageRequest(t)}async denyCoverageRequest(t,r){return this.rejectCoverageRequest(t,r)}
26async cancelCoverageRequest(t){const r=A.getCurrentUser().tenantId,a=T(r,ct),o=B(_,a,t),s=await this.getCoverageRequest(t);if(!s)return null;if(s.status==="resolved")throw new Error("Cannot cancel already resolved coverage request");const i=new Date().toISOString();return await Q(o,{status:"canceled",updated_at:i}),console.log("[HRCoverageService] Canceled coverage request:",t),this.getCoverageRequest(t)}subscribeToCoverageRequests(t,r){var c;const a=(c=A.getCurrentUser())==null?void 0:c.tenantId;if(!a)return r([]),()=>{};const o=T(a,ct),s=H(_,o),i=V(s,ee("created_at","desc"));return we(i,d=>{var u;let m=d.docs.map(h=>({...h.data(),id:h.id}));t.employee_id&&(m=m.filter(h=>h.requested_by_employee_id===t.employee_id)),t.shift_id&&(m=m.filter(h=>h.shift_id===t.shift_id)),(u=t.statuses)!=null&&u.length&&(m=m.filter(h=>t.statuses.includes(h.status))),t.include_resolved||(m=m.filter(h=>h.status!=="resolved")),r(m)},d=>{console.error("[HRCoverageService] Subscription error:",d),r([])})}subscribeToPendingRequests(t){return this.subscribeToCoverageRequests({statuses:["pending"],include_resolved:!1},t)}async hasPendingCoverageRequest(t){return(await this.getCoverageRequestsForShift(t)).some(a=>a.status==="pending"||a.status==="approved")}async getCoverageStats(){const t=await this.getCoverageRequests({include_resolved:!0}),r=new Date;return r.setHours(0,0,0,0),{pending:t.filter(a=>a.status==="pending").length,approved:t.filter(a=>a.status==="approved").length,resolved_today:t.filter(a=>a.status!=="resolved"?!1:new Date(a.updated_at)>=r).length,total_open:t.filter(a=>a.status==="pending"||a.status==="approved").length}}}const jr=new Wi,dt="hr_time_off_requests",Vi=["Vacation","Sick","Personal","Bereavement","Jury Duty","Military","FMLA","Unpaid","Other"];class Ki{constructor(){this.requests=[],this.listeners=[],this.unsubscribeFn=null}resolveTenantId(){return(typeof window<"u"?window.localStorage.getItem("tenantId"):null)||null}async getTimeOffRequests(t){var c,d,m;const r=A.getCurrentUser().tenantId,a=T(r,dt),o=H(_,a),s=V(o,ee("start_at_utc","desc"));let n=(await Z(s)).docs.map(u=>({...u.data(),id:u.id}));return t&&((c=t.employee_ids)!=null&&c.length&&(n=n.filter(u=>t.employee_ids.includes(u.employee_id))),(d=t.statuses)!=null&&d.length&&(n=n.filter(u=>t.statuses.includes(u.status))),(m=t.types)!=null&&m.length&&(n=n.filter(u=>t.types.includes(u.type))),t.start_date&&(n=n.filter(u=>u.start_at_utc>=t.start_date)),t.end_date&&(n=n.filter(u=>u.end_at_utc<=t.end_date))),n}async getTimeOffRequest(t){const r=A.getCurrentUser().tenantId,a=T(r,dt),o=B(_,a,t),s=await oe(o);return s.exists()?{...s.data(),id:s.id}:null}async createTimeOffRequest(t){const r=A.getCurrentUser().tenantId,a=T(r,dt),o=H(_,a),s=new Date().toISOString(),i={tenant_id:r,employee_id:t.employee_id,start_at_utc:t.start_at_utc,end_at_utc:t.end_at_utc,status:"submitted",type:t.type,notes:t.notes||null,decided_by:null,decided_at:null,created_at:s,updated_at:s},n=await ie(o,i);return console.log("[HRTimeOffService] Created time off request:",n.id),{...i,id:n.id}}async updateTimeOffRequest(t,r){const a=A.getCurrentUser().tenantId,o=T(a,dt),s=B(_,o,t),i=await this.getTimeOffRequest(t);if(!i)return null;if(i.status!=="submitted")throw new Error("Can only update submitted requests");return await Q(s,{...r,updated_at:new Date().toISOString()}),console.log("[HRTimeOffService] Updated time off request:",t),this.getTimeOffRequest(t)}async cancelTimeOffRequest(t){const r=A.getCurrentUser().tenantId,a=T(r,dt),o=B(_,a,t),s=await this.getTimeOffRequest(t);if(!s)return null;if(!["submitted","approved"].includes(s.status))throw new Error("Can only cancel submitted or approved requests");return await Q(o,{status:"canceled",updated_at:new Date().toISOString()}),console.log("[HRTimeOffService] Canceled time off request:",t),this.getTimeOffRequest(t)}async approveTimeOffRequest(t){const r=A.getCurrentUser(),a=r.tenantId,o=T(a,dt),s=B(_,o,t),i=await this.getTimeOffRequest(t);if(!i)return null;if(i.status!=="submitted")throw new Error("Can only approve submitted requests");const n=new Date().toISOString();await Q(s,{status:"approved",decided_by:r.id,decided_at:n,updated_at:n}),console.log("[HRTimeOffService] Approved time off request:",t);try{const c=await this.unassignEmployeeFromShiftsDuringTimeOff(a,i.employee_id,i.start_at_utc,i.end_at_utc,r.id);c>0&&console.log(`[HRTimeOffService] Unassigned employee from ${c} shifts during time off period`)}catch(c){console.error("[HRTimeOffService] Error unassigning shifts during time off approval:",c)}
26return this.getTimeOffRequest(t)}async unassignEmployeeFromShiftsDuringTimeOff(t,r,a,o,s){const i=T(t,"hr_shifts"),n=H(_,i),c=V(n,K("assigned_employee_id","==",r),ee("start_at_utc","asc")),d=await Z(c),m=new Date().toISOString();let u=0;const h=new Date(a),v=new Date(o);for(const y of d.docs){const p=y.data(),N=new Date(p.start_at_utc),S=new Date(p.end_at_utc);if(!(p.is_deleted||p.status==="canceled")&&p.status!=="draft"&&N<v&&S>h){const j=B(_,i,y.id);await Q(j,{assigned_employee_id:null,status:"open",version:(p.version||1)+1,updated_by_user_id:s,updated_at:m});const $=T(t,"hr_shift_transactions"),R=H(_,$);await ie(R,{tenant_id:t,shift_id:y.id,type:"unassign",from_employee_id:r,to_employee_id:null,requested_by_user_id:s,approved_by_user_id:null,status:"applied",policy_snapshot:{reason:"time_off_approved",time_off_start:a,time_off_end:o},reason:"Automatically unassigned due to approved time off request",created_at:m,resolved_at:m}),u++,console.log(`[HRTimeOffService] Unassigned shift ${y.id} (${p.start_at_utc}) due to time off`)}}return u}async denyTimeOffRequest(t,r){const a=A.getCurrentUser(),o=a.tenantId,s=T(o,dt),i=B(_,s,t),n=await this.getTimeOffRequest(t);if(!n)return null;if(n.status!=="submitted")throw new Error("Can only deny submitted requests");const c=new Date().toISOString();return await Q(i,{status:"denied",decided_by:a.id,decided_at:c,notes:r?`${n.notes||""} 27 28Denial reason: ${r}`.trim():n.notes,updated_at:c}),console.log("[HRTimeOffService] Denied time off request:",t),this.getTimeOffRequest(t)}subscribeToTimeOffRequests(t,r){const a=this.resolveTenantId();if(!a)return r([]),()=>{};const o=T(a,dt),s=H(_,o),i=V(s,ee("start_at_utc","desc"));return we(i,c=>{var m,u,h;let d=c.docs.map(v=>({...v.data(),id:v.id}));(m=t.employee_ids)!=null&&m.length&&(d=d.filter(v=>t.employee_ids.includes(v.employee_id))),(u=t.statuses)!=null&&u.length&&(d=d.filter(v=>t.statuses.includes(v.status))),(h=t.types)!=null&&h.length&&(d=d.filter(v=>t.types.includes(v.type))),t.start_date&&(d=d.filter(v=>v.start_at_utc>=t.start_date)),t.end_date&&(d=d.filter(v=>v.end_at_utc<=t.end_date)),r(d)},c=>{console.error("[HRTimeOffService] Subscription error:",c),r([])})}subscribeToPendingRequests(t){return this.subscribeToTimeOffRequests({statuses:["submitted"]},t)}subscribeToEmployeeRequests(t,r){return this.subscribeToTimeOffRequests({employee_ids:[t]},r)}async hasOverlappingRequest(t,r,a,o){return(await this.getTimeOffRequests({employee_ids:[t],statuses:["submitted","approved"]})).some(i=>o&&i.id===o?!1:i.start_at_utc<a&&i.end_at_utc>r)}async getTimeOffForDateRange(t,r,a){const o={statuses:["approved"]};return a!=null&&a.length&&(o.employee_ids=a),(await this.getTimeOffRequests(o)).filter(i=>i.start_at_utc<r&&i.end_at_utc>t)}calculateDaysOff(t,r,a=!1){const o=new Date(t),s=new Date(r);let i=0;const n=new Date(o);for(;n<s;)(a||n.getDay()!==0&&n.getDay()!==6)&&i++,n.setDate(n.getDate()+1);return i}}const xt=new Ki,Yi={cross_location_conflict_mode:"warn_only",overtime_threshold_hours:40,break_requirement_minutes:30,notice_period_hours:24,lockout_window_hours:12,open_shift_requires_approval:!0};class Gi{constructor(t){this.tenantId=t}async checkEligibility(t,r,a,o,s,i,n,c,d,m){const u={...Yi,...m},h=[];if(a!=="active")return{eligible:!1,block:{reason:"employee_not_active",details:{status:a}},warnings:[]};if(!this.hasActiveAssignment(t,r.location_id,r.position_id||void 0,r.start_at_utc,o))return{eligible:!1,block:{reason:"no_active_assignment"},warnings:[]};if(this.overlapsApprovedTimeOff(t,r.start_at_utc,r.end_at_utc,i))return{eligible:!1,block:{reason:"approved_time_off_overlap"},warnings:[]};const y=this.checkAvailabilityRules(s,r.timezone,r.start_at_utc,r.end_at_utc);if(y.hasCannotOverlap)return{eligible:!1,block:{reason:"cannot_work_availability"},warnings:[]};const p=this.checkCrossLocationOverlap(t,r,n);if(p.hasOverlap&&u.cross_location_conflict_mode==="block")return{eligible:!1,block:{reason:"cross_location_overlap",details:{conflicting_shift_id:p.conflictingShiftId,overlap_minutes:p.overlapMinutes}},warnings:[]};p.hasOverlap&&h.push({type:"cross_location_overlap_warn",details:{conflicting_shift_id:p.conflictingShiftId,overlap_minutes:p.overlapMinutes}});const N=this.checkTravelBuffer(t,r,n,d);N.insufficientBuffer&&h.push({type:"insufficient_travel_time",details:{ga
28p_minutes:N.gapMinutes,required_minutes:N.requiredMinutes,adjacent_shift_id:N.adjacentShiftId}}),y.outsidePrefer&&h.push({type:"outside_preferred_availability"});const S=c.find(I=>I.shift_id===r.id&&I.employee_id===t);S!=null&&S.conflict_flag&&h.push({type:"calendar_conflict_warn_only",details:{overlap_minutes:S.overlap_minutes}});const j=this.computeCrossLocationOvertimeRisk(t,r,n,u.overtime_threshold_hours);return j.atRisk&&h.push({type:"overtime_risk",details:{projected_hours:j.projectedTotal,threshold:j.threshold,by_location:j.breakdown}}),{eligible:!0,warnings:h}}hasActiveAssignment(t,r,a,o,s){const i=new Date(o);return s.some(n=>{if(n.employee_id!==t||n.location_id!==r||n.status!=="active"||a&&n.position_id!==a)return!1;const c=new Date(n.start_date);if(i<c)return!1;if(n.end_date){const d=new Date(n.end_date);if(i>d)return!1}return!0})}overlapsApprovedTimeOff(t,r,a,o){const s=new Date(r),i=new Date(a);return o.some(n=>{if(n.employee_id!==t||n.status!=="approved")return!1;const c=new Date(n.start_at_utc),d=new Date(n.end_at_utc);return s<d&&i>c})}checkAvailabilityRules(t,r,a,o){const s=new Date(a),i=new Date(o),n=s.getDay(),c=t.filter(u=>u.weekday===n);let d=!1,m=!1;for(const u of c){if(u.effective_start_date){const O=new Date(u.effective_start_date);if(s<O)continue}if(u.effective_end_date){const O=new Date(u.effective_end_date);if(s>O)continue}const[h,v]=u.start_local_time.split(":").map(Number),[y,p]=u.end_local_time.split(":").map(Number),N=s.getHours(),S=i.getHours(),j=h*60+v,I=y*60+p,$=N*60+s.getMinutes(),R=S*60+i.getMinutes(),E=$<I&&R>j;u.type==="cannot"&&E&&(d=!0),u.type==="prefer"&&E&&(m=!0)}return{hasCannotOverlap:d,outsidePrefer:c.some(u=>u.type==="prefer")&&!m}}checkCrossLocationOverlap(t,r,a){const o=new Date(r.start_at_utc),s=new Date(r.end_at_utc);for(const i of a){if(i.assigned_employee_id!==t||i.location_id===r.location_id||i.status==="canceled"||i.is_deleted||i.id===r.id)continue;const n=new Date(i.start_at_utc),c=new Date(i.end_at_utc);if(o<c&&s>n){const d=new Date(Math.max(o.getTime(),n.getTime())),m=new Date(Math.min(s.getTime(),c.getTime())),u=Math.round((m.getTime()-d.getTime())/6e4);return{hasOverlap:!0,conflictingShiftId:i.id,conflictingLocationId:i.location_id,overlapMinutes:u}}}return{hasOverlap:!1}}checkTravelBuffer(t,r,a,o){const s=new Date(r.start_at_utc),i=new Date(r.end_at_utc);for(const n of a){if(n.assigned_employee_id!==t||n.location_id===r.location_id||n.status==="canceled"||n.is_deleted||n.id===r.id)continue;const c=new Date(n.start_at_utc),d=new Date(n.end_at_utc),m=[n.location_id,r.location_id].sort().join(":"),u=o.get(m)||0;if(u!==0){if(s>d){const h=Math.round((s.getTime()-d.getTime())/6e4);if(h<u)return{insufficientBuffer:!0,gapMinutes:h,requiredMinutes:u,adjacentShiftId:n.id}}if(i<c){const h=Math.round((c.getTime()-i.getTime())/6e4);if(h<u)return{insufficientBuffer:!0,gapMinutes:h,requiredMinutes:u,adjacentShiftId:n.id}}}}return{insufficientBuffer:!1}}computeCrossLocationOvertimeRisk(t,r,a,o){const s=new Date(r.start_at_utc),i=new Date(s);i.setDate(i.getDate()-i.getDay()),i.setHours(0,0,0,0);const n=new Date(i);n.setDate(n.getDate()+7);const c={};let d=0;for(const u of a){if(u.assigned_employee_id!==t||u.status==="canceled"||u.is_deleted||u.id===r.id)continue;const h=new Date(u.start_at_utc),v=new Date(u.end_at_utc);if(h>=i&&h<n){const y=(v.getTime()-h.getTime())/36e5;c[u.location_id]=(c[u.location_id]||0)+y,d+=y}}const m=(new Date(r.end_at_utc).getTime()-new Date(r.start_at_utc).getTime())/(1e3*60*60);return c[r.location_id]=(c[r.location_id]||0)+m,d+=m,{atRisk:d>o,projectedTotal:Math.round(d*10)/10,threshold:o,breakdown:c}}async getEligibleEmployees(t,r,a,o,s){const i=[];for(const n of r){const c=await this.checkEligibility(n.employee_id,t,n.status,n.assignments,n.availability_rules,n.time_off_requests,n.existing_shifts,a.filter(d=>d.employee_id===n.employee_id),o,s);i.push({employee_id:n.employee_id,result:c})}return i.sort((n,c)=>n.result.eligible!==c.result.eligible?n.result.eligible?-1:1:n.result.warnings.length-c.result.warnings.length)}}const ge="hr_shifts",Ct="hr_shift_transactions",Et="hr_schedule_templates",Kt="hr_template_shifts",ut="hr_shift_swaps",kt="hr_availability_rules",xr="hr_location_travel_buffers",Qi={draft:["published","assigned","canceled"],published:["assigned","open","canceled"],open:["assigned","canceled"],assigned:["open","assigned","coverage_requested","canceled"],coverage_requested:["open","assigned","canceled"],covered:[],canceled:[]};class Zi{constructor(){this.shifts=[],this.templates=[],this.listeners=[],this.unsubscribeFn=null,this.initialized=!1}async initialize(){if(this.initialized)return;const t=this.resolveTenantId();if(!t){console.warn("[HRSchedulingService] tenantId not available yet, will retry"),setTimeout(()=>this.initialize(),1e3);return}await this.loadShifts(t),this.setupRealtimeListener(t),this.initialized=!0,console.log("[HRSchedulingService] Initialized with",this.shifts.length,"shifts")}resolveTenantId(){var r;const t=typeof window<"u"?window.localStorage.getItem("tenantId"):null;if(t)return t;try{return((r=De.getCurrentTenant())==null?void 0:r.id)||null}catch{return null}}async getShifts(t){var c,d,m,u;const r=A.getCurrentUser().tenantId,a=T(r,ge),o=H(_,a);let s=V(o,ee("start_at_utc","asc")),n=(await Z(s)).docs.map(h=>({...h.data(),id:h.id}));if(t){if(t.include_deleted||(n=n.filter(h=>!h.is_deleted)),(c=t.location_ids)!=null&&c.length&&(n=n.filter(h=>t.location_ids.includes(h.location_id))),(d=t.position_ids)!=null&&d.length&&(n=n.filter(h=>h.position_id&&t.position_ids.includes(h.position_id))),(m=t.employee_ids)!=null&&m.length&&(n=n.filter(h=>h.assigned_employee_id&&t.employee_ids.includes(h.assigned_employee_id))),(u=t.statuses)!=null&&u.length&&(n=n.filter(h=>t.statuses.includes(h.status))),t.start_date){const h=new Date(t.start_date);n=n.filter(v=>new Date(v.start_at_utc)>=h)}if(t.end_date){const h=new Date(t.end_date);n=n.filter(v=>new Date(v.end_at_utc)<=h)}}return n}async getShift(t){const r=A.getCurrentUser().tenantId,a=T(r,ge),o=B(_,a,t),s=await oe(o);return s.exists()?{...s.data(),id:s.id}:null}async createShift(t){const r=A.getCurrentUser(),a=r.tenantId,o=T(a,ge),s=H(_,o),i=new Date().toISOString(),n={tenant_id:a,location_id:t.location_id,position_id:t.position_id||null,start_at_utc:t.start_at_utc,end_at_utc:t.end_at_utc,timezone:"America/Ne
28w_York",status:t.status||"draft",assigned_employee_id:t.assigned_employee_id||null,published_at:t.status==="published"?i:null,template_id:null,template_shift_id:null,notes:t.notes||null,version:1,is_deleted:!1,created_by_user_id:r.id,updated_by_user_id:r.id,created_at:i,updated_at:i},c=await ie(s,n),d={...n,id:c.id};return d.status==="published"&&await this.recordTransaction(d.id,"publish",{}),await se.publishShiftCreated({shift_id:c.id,location_id:t.location_id,position_id:t.position_id,start_at_utc:t.start_at_utc,end_at_utc:t.end_at_utc,timezone:n.timezone}),console.log("[HRSchedulingService] Created shift:",c.id),d}async updateShift(t,r){const a=A.getCurrentUser(),o=a.tenantId,s=T(o,ge),i=B(_,s,t),n=await this.getShift(t);if(!n)return null;if(n.is_deleted)throw new Error("Cannot update deleted shift");const c=n.status!=="draft",d={...r,updated_by_user_id:a.id,updated_at:new Date().toISOString(),version:(n.version||1)+1};return await Q(i,d),c&&await this.recordTransaction(t,"edit_published_shift",{changes:r}
28),await se.publishShiftUpdated({shift_id:t,version:(n.version||1)+1,changes:r,was_published:c}),console.log("[HRSchedulingService] Updated shift:",t),this.getShift(t)}async deleteShift(t,r=!1){const a=A.getCurrentUser(),o=a.tenantId,s=T(o,ge),i=B(_,s,t),n=await this.getShift(t);return n?(r?(await ke(i),console.log("[HRSchedulingService] Hard deleted shift:",t)):(await Q(i,{status:"canceled",is_deleted:!0,updated_by_user_id:a.id,updated_at:new Date().toISOString()}),await this.recordTransaction(t,"cancel_shift",{was_published:n.status!=="draft",had_employee:!!n.assigned_employee_id}),console.log("[HRSchedulingService] Soft deleted shift:",t)),await se.publishShiftCanceled({shift_id:t,version:(n.version||1)+1,was_published:n.status!=="draft",had_employee:!!n.assigned_employee_id}),!0):!1}isValidTransition(t,r){var a;return((a=Qi[t])==null?void 0:a.includes(r))||!1}async publishShifts(t){const r=A.getCurrentUser(),a=r.tenantId,o=T(a,ge),s=[],i=[],n=new Date().toISOString();for(const c of t.shift_ids)try{const d=await this.get
28Shift(c);if(!d){i.push(c);continue}if(d.status!=="draft"){i.push(c);continue}const m=d.assigned_employee_id?"assigned":"published",u=B(_,o,c);await Q(u,{status:m,published_at:n,version:(d.version||1)+1,updated_by_user_id:r.id,updated_at:n}),await this.recordTransaction(c,"publish",{notify_employees:t.notify_employees}),await se.publishShiftPublished({shift_id:c,assigned_employee_id:d.assigned_employee_id||void 0,version:(d.version||1)+1,published_at:n}),s.push(c)}catch(d){console.error("[HRSchedulingService] Failed to publish shift:",c,d),i.push(c)}if(s.length>1){const d=(await Promise.all(s.map(m=>this.getShift(m)))).filter(m=>m!==null);if(d.length>0){const m=d.map(u=>u.start_at_utc).sort();await se.publishBatchPublish({location_id:d[0].location_id,shift_count:s.length,date_range:{start:m[0],end:m[m.length-1]}})}}return{succeeded:s,failed:i}}async assignEmployee(t,r,a){const o=A.getCurrentUser(),s=o.tenantId,i=T(s,ge),n=await this.getShift(t);if(!n)return{shift:null};if(n.is_deleted||n.status==="canceled")throw new Error("Cannot assign to deleted or canceled shift");const c=await Bi.checkSchedulingPermission("hr.schedule.assign",n.location_id);if(!c.allowed)throw new Error(c.reason||"Permission denied");let d;if(!(a!=null&&a.skipEligibility)&&(a!=null&&a.employeeData)&&(d=await new Gi(s).checkEligibility(r,n,a.employeeData.status,a.employeeData.assignments,a.employeeData.availabilityRules,a.employeeData.timeOffRequests,a.employeeData.existingShifts,[],new Map),!d.eligible&&!a.overrideReason))return{shift:null,eligibility:d};const m=n.assigned_employee_id;let u=n.status;(n.status==="published"||n.status==="open"||n.status==="coverage_requested")&&(u="assigned");const h=B(_,i,t),v=new Date().toISOString();return await Q(h,{status:u,assigned_employee_id:r,version:(n.version||
281)+1,updated_by_user_id:o.id,updated_at:v}),await this.recordTransaction(t,"assign",{from_employee_id:m,to_employee_id:r,override_reason:a==null?void 0:a.overrideReason,eligibility_warnings:d==null?void 0:d.warnings}),await se.publishShiftAssigned({shift_id:t,employee_id:r,version:(n.version||1)+1,previous_employee_id:m||void 0}),console.log("[HRSchedulingService] Assigned employee to shift:",t),{shift:await this.getShift(t),eligibility:d}}async assignEmployeeSimple(t,r,a){return(await this.assignEmployee(t,r,{overrideReason:a,skipEligibility:!0})).shift}async unassignEmployee(t,r){const a=A.getCurrentUser(),o=a.tenantId,s=T(o,ge),i=await this.getShift(t);if(!i)return null;if(!i.assigned_employee_id)throw new Error("Shift has no assigned employee");const n=i.assigned_employee_id,c=i.status==="draft"?"draft":"open",d=B(_,s,t),m=new Date().toISOString();return await Q(d,{status:c,assigned_employee_id:null,version:(i.version||1)+1,updated_by_user_id:a.id,updated_at:m}),await this.recordTransaction(t,"unassign",{from_employee_id:n,reason:r}),await se.publishShiftUnassigned({shift_id:t,from_employee_id:n,version:(i.version||
281)+1,reason:r}),c==="open"&&await se.publishShiftOpened(t,(i.version||1)+1),console.log("[HRSchedulingService] Unassigned employee from shift:",t),this.getShift(t)}async requestCoverage(t,r){const a=A.getCurrentUser(),o=a.tenantId,s=T(o,ge),i=await this.getShift(t);if(!i)return{shift:null};if(i.status!=="assigned")throw new Error("Can only request coverage for assigned shifts");const n=B(_,s,t),c=new Date().toISOString();await Q(n,{status:"coverage_requested",version:(i.version||1)+1,updated_by_user_id:a.id,updated_at:c});const d=await jr.createCoverageRequest({shift_id:t,requested_by_employee_id:i.assigned_employee_id,reason:r});return await this.recordTransaction(t,"coverage_request",{from_employee_id:i.assigned_employee_id,reason:r,coverage_request_id:d.id}),await se.publishCoverageRequested({shift_id:t,employee_id:i.assigned_employee_id,coverage_request_id:d.id,reason:r}),console.log("[HRSchedulingService] Coverage requested for shift:",t),{shift:await this.getShift(t),coverageRequestId:d.id}}async resolveCoverage(t,r,a){const o=await this.get
28Shift(t);if(!o)return null;if(o.status!=="coverage_requested")throw new Error("Shift is not in coverage_requested status");if(r==="open_shift"){const s=A.getCurrentUser(),i=s.tenantId,n=T(i,ge),c=B(_,n,t),d=new Date().toISOString();return await Q(c,{status:"open",assigned_employee_id:null,version:(o.version||1)+1,updated_by_user_id:s.id,updated_at:d}),await this.recordTransaction(t,"coverage_assign",{resolution:"open_shift",from_employee_id:o.assigned_employee_id}),await se.publishCoverageResolved({shift_id:t,resolution:"open_shift",coverage_request_id:t}),await se.publishShiftOpened(t,(o.version||1)+1),console.log("[HRSchedulingService] Coverage resolved as open shift:",t),this.getShift(t)}else if(r==="reassign"&&a){const s=await this.assignEmployee(t,a,{skipEligibility:!0});return s.shift&&(await this.recordTransaction(t,"coverage_assign",{resolution:"reassign",from_employee_id:o.assigned_employee_id,to_employee_id:a}),await se.publishCoverageResolved({shift_id:t,resolution:"reassign",replacement_employee_id:a,coverage_request_id:t})),console.log("[HRSchedulingService] Coverage resolved via reassignment:",t),s.shift}throw new Error("Invalid resolution type or missing reassign employee")}async recordTransaction(t,r,a){const o=A.getCurrentUser(),s=o.tenantId,i=T(s,Ct),n=H(_,i),c={};for(const[m,u]of Object.entries(a))u!==void 0&&(c[m]=u);const d={tenant_id:s,shift_id:t,type:r,from_employee_id:a.from_employee_id||null,to_employee_id:a.to_employee_id||null,requested_by_user_id:o.id,approved_by_user_id:null,status:"applied",policy_snapshot:c,reason:a.reason||null,created_at:new Date().toISOString(),resolved_at:new Date().toISOString()};await ie(n,d)}async getShiftTransactions(t){const r=A.getCurrentUser().tenantId,a=T(r,Ct),o=H(_,a),s=V(o,K("shift_id","==",t),ee("created_at","desc"));return(await Z(s)).docs.map(n=>({...n.data(),id:n.id}))}async getLatestTemplateApplication(){const t=A.getCurrentUser().tenantId,r=T(t,Ct),a=H(_,r),o=V(a,K("type","==","template_apply")),s=await Z(o);if(s.empty)return null;const i=s.docs.map(d=>({...d.data(),id:d.id}));i.sort((d,m)=>new Date(m.created_at).getTime()-new Date(d.created_at).getTime());const n=i[0];return{templateId:n.policy_snapshot&&typeof n.policy_snapshot.template_id=="string"?n.policy_snapshot.template_id:void 0,createdAt:n.created_at}}async getTemplates(t){const r=A.getCurrentUser().tenantId,a=T(r,Et),o=H(_,a);let s=V(o,ee("name","asc"));t&&(s=V(o,K("location_id","==",t),ee("name","asc")));const n=(await Z(s)).docs.map(d=>({...d.data(),id:d.id})),c=[];for(const d of n){const m=await this.getTemplateShifts(d.id);c.push({...d,shifts:m})}return c}async getTemplate(t){const r=A.getCurrentUser().tenantId,a=T(r,Et),o=B(_,a,t),s=await oe(o);if(!s.exists())return null;const i={...s.data(),id:s.id},n=await this.getTemplateShifts(t);return{...i,shifts:n}}async createTemplate(t){const r=A.getCurrentUser(),a=r.tenantId,o=T(a,Et),s=H(_,o),i=new Date().toISOString(),n={tenant_id:a,location_id:t.location_id,name:t.name,period_type:t.period_type||"week",period_days:t.period_days||7,status:"draft",version:1,created_by:r.id,created_at:i,updated_at:i},c=await ie(s,n);return console.log("[HRSchedulingService] Created template:",c.id),{...n,id:c.id}}async duplicateTemplate(t){const r=A.getCurrentUser(),a=r.tenantId,o=T(a,Et),s=T(a,Kt),i=await oe(B(_,o,t));if(!i.exists())throw new Error("The source template no longer exists.");const n=i.data(),c=await Z(V(H(_,s),K("template_id","==",t)));if(c.size>499)throw new Error("This template is too large to duplicate atomically.");const d=B(H(_,o)),m=new Date().toISOString(),u={tenant_id:a,location_id:n.location_id,name:`${n.name} (copy)`,period_type:n.period_type,period_days:n.period_days,status:"draft",version:1,created_by:r.id,created_at:m,updated_at:m},h=sn(_);h.set(d,u);const v=c.docs.map(p=>{const N=p.data(),S=B(H(_,s)),j={template_id:d.id,day_offset:N.day_offset,start_time:N.start_time,end_time:N.end_time,position_id:N.position_id||null,headcount:N.headcount||1,notes:N.notes||null,default_employee_id:N.default_employee_id||null};return h.set(S,j),{...j,id:S.id}});if(await h.commit(),!(await oe(d)).exists())throw new Error("The duplicate could not be verified. Refresh templates before trying again.");return{...u,id:d.id,shifts:v}}async updateTemplate(t,r){const a=A.getCurrentUser().tenantId,o=T(a,Et),s=B(_,o,t),i=await this.getTemplate(t);if(!i)return null;
28await Q(s,{...r,version:(i.version||1)+1,updated_at:new Date().toISOString()}),console.log("[HRSchedulingService] Updated template:",t);const n=await this.getTemplate(t);return n?{...n}:null}async deleteTemplate(t){const r=A.getCurrentUser().tenantId,a=T(r,Et),o=B(_,a,t),s=await this.getTemplateShifts(t);for(const i of s)await this.deleteTemplateShift(t,i.id);return await ke(o),console.log("[HRSchedulingService] Deleted template:",t),!0}async getTemplateShifts(t){const r=A.getCurrentUser().tenantId,a=T(r,Kt),o=H(_,a),s=V(o,K("template_id","==",t),ee("day_offset","asc"));return(await Z(s)).docs.map(n=>({...n.data(),id:n.id}))}async addTemplateShift(t,r){const a=A.getCurrentUser().tenantId,o=T(a,Kt),s=H(_,o),i={template_id:t,day_offset:r.day_offset,start_time:r.start_time,end_time:r.end_time,position_id:r.position_id||null,headcount:r.headcount||1,notes:r.notes||null,default_employee_id:r.default_employee_id||null},n=await ie(s,i);return console.log("[HRSchedulingService] Added template shift:",n.id),{...i,id:n.id}}async updateTemplateShift(t,r,a){const o=A.getCurrentUser().tenantId,s=T(o,Kt),i=B(_,s,r);await Q(i,a);const n=await oe(i);return n.exists()?{...n.data(),id:n.id}:null}async deleteTemplateShift(t,r){const a=A.getCurrentUser().tenantId,o=T(a,Kt),s=B(_,o,r);return await ke(s),console.log("[HRSchedulingService] Deleted template shift:",r),!0}async applyTemplate(t,r="America/New_York"){const a=await this.getTemplate(t.template_id);if(!a)return{shifts:[],errors:["Template not found"]};if(a.status!=="active")return{shifts:[],errors:["Template must be active to apply"]};if(a.shifts.length===0)return{shifts:[],errors:["Template has no shifts"]};const[o,s,i]=t.start_date.split("-").map(Number),n=new Date(o,s-1,i,0,0,0,0);console.log("[HRSchedulingService] Applying template starting:",t.start_date,"-> local date:",n.toLocaleDateString());const c=[],d=[],m=[];for(const u of a.shifts)try{const h=new Date(n);h.setDate(h.getDate()+u.day_offset);const[v,y]=u.start_time.split(":").map(Number),[p,N]=u.end_time.split(":").map(Number),S=new Date(h.getFullYear(),h.getMonth(),h.getDate(),v,y,0,0),j=new Date(h.getFullYear(),h.getMonth(),h.getDate(),p,N,0,0);j<=S&&j.setDate(j.getDate()+1);for(let I=0;I<u.headcount;I++){const $=I===0&&u.default_employee_id;let R,E=null;if($&&u.default_employee_id){const k=u.default_employee_id;(await xt.getTimeOffRequests({employee_ids:[k],statuses:["approved","submitted"]})).some(L=>{const z=new Date(L.start_at_utc),X=new Date(L.end_at_utc);return S<X&&j>z}
28)?E="time_off_conflict":(await this.getShiftsForEmployee(k,S,j)).length>0?E="shift_overlap":R=k,E&&m.push({employee_id:k,day_offset:u.day_offset,start_time:u.start_time,end_time:u.end_time,reason:E,shift_date:h.toISOString().split("T")[0]})}const O=await this.createShift({location_id:a.location_id,position_id:u.position_id||void 0,start_at_utc:S.toISOString(),end_at_utc:j.toISOString(),notes:u.notes||void 0,status:t.create_as_draft?"draft":"published",assigned_employee_id:R}),b=A.getCurrentUser().tenantId,P=T(b,ge),W=B(_,P,O.id);await Q(W,{template_id:a.id,template_shift_id:u.id}),c.push({...O,template_id:a.id,template_shift_id:u.id})}}catch(h){d.push(`Day ${u.day_offset}: ${h.message}`)}return c.length>0&&(await this.recordTransaction(c[0].id,"template_apply",{template_id:a.id,shifts_created:c.length}),await se.publishTemplateApplied({template_id:a.id,location_id:a.location_id,target_week:t.start_date,generated_shift_count:c.length})),console.log("[HRSchedulingService] Applied template, created",c.length,"shifts,",m.length,"conflicts"),{shifts:c,errors:d,conflicts:m}}async getShiftsForEmployee(t,r,a){const s=A.getCurrentUser().tenantId,i=T(s,ge),n=H(_,i),c=V(n,K("assigned_employee_id","==",t),K("is_deleted","==",!1)),d=await Z(c),m=[];return d.forEach(u=>{const h={...u.data(),id:u.id},v=new Date(h.start_at_utc),y=new Date(h.end_at_utc);r<y&&a>v&&m.push(h)}),m}async loadShifts(t){const r=T(t,ge),a=H(_,r),o=V(a,ee("start_at_utc","asc")),s=await Z(o);this.shifts=s.docs.map(i=>({...i.data(),id:i.id}))}setupRealtimeListener(t){this.unsubscribeFn&&this.unsubscribeFn();const r=T(t,ge),a=H(_,r),o=V(a,ee("start_at_utc","asc"));this.unsubscribeFn=we(o,s=>{this.shifts=s.docs.map(i=>({...i.data(),id:i.id})),console.log("[HRSchedulingService] Real-time update:",this.shifts.length,"shifts"),this.notifyListeners()},s=>{console.warn("[HRSchedulingService] Listener error:",s)})}subscribeToShifts(t,r){const a=this.resolveTenantId();if(!a)return console.warn("[HRSchedulingService] No tenantId available for subscription"),r([]),()=>{};const o=T(a,ge),s=H(_,o);let i=V(s,ee("start_at_utc","asc"));return t.start_date&&(i=V(i,K("start_at_utc",">=",t.start_date))),t.end_date&&(i=V(i,K("start_at_utc","<=",t.end_date))),we(i,c=>{var m,u;let d=c.docs.map(h=>({...h.data(),id:h.id}));t.include_deleted||(d=d.filter(h=>!h.is_deleted)),(m=t.location_ids)!=null&&m.length&&(d=d.filter(h=>t.location_ids.includes(h.location_id))),(u=t.statuses)!=null&&u.length&&(d=d.filter(h=>t.statuses.includes(h.status))),r(d)},c=>{console.error("[HRSchedulingService] Subscription error:",c),r([])})}subscribe(t){return this.listeners.push(t),this.initialized||this.initialize(),()=>{this.listeners=this.listeners.filter(r=>r!==t)}}notifyListeners(){this.listeners.forEach(t=>t())}getShiftsFromCache(){return this.shifts}async createSwapRequest(t){const a=A.getCurrentUser().tenantId,o=T(a,ut),s=H(_,o),i=new Date().toISOString(),n={tenant_id:a,swap_type:t.swap_type,shift_id_a:t.shift_id_a,shift_id_b:t.shift_id_b||null,employee_a:t.employee_a,employee_b:t.employee_b,status:"pending",message:t.message||null,created_at:i,updated_at:i},c=await ie(s,n);return await this.recordTransaction(t.shift_id_a,"swap_request",{swap_id:c.id,from_employee_id:t.employee_a,to_employee_id:t.employee_b}),await se.publishSwapRequested({swap_id:c.id,swap_type:t.swap_type,shift_ids:[t.shift_id_a,t.shift_id_b].filter(d=>!!d),employee_ids:[t.employee_a,t.employee_b]}),console.log("[HRSchedulingService] Created swap request:",c.id),{...n,id:c.id}}async getSwapRequests(t){var c;const r=A.getCurrentUser().tenantId,a=T(r,ut),o=H(_,a),s=V(o,ee("created_at","desc"));let n=(await Z(s)).docs.map(d=>({...d.data(),id:d.id}));return t!=null&&t.employee_id&&(n=n.filter(d=>d.employee_a===t.employee_id||d.employee_b===t.employee_id)),t!=null&&t.shift_id&&(n=n.filter(d=>d.shift_id_a===t.shift_id||d.shift_id_b===t.shift_id)),(c=t==null?void 0:t.statuses)!=null&&c.length&&(n=n.filter(d=>t.statuses.includes(d.status))),n}async getSwapRequest(t){const r=A.getCurrentUser().tenantId,a=T(r,ut),o=B(_,a,t),s=await oe(o);return s.exists()?{...s.data(),id:s.id}:null}async acceptSwapRequest(t){const r=A.getCurrentUser(),a=r.tenantId,o=T(a,ut),s=B(_,o,t),i=await this.get
28SwapRequest(t);if(!i)return null;if(i.status!=="pending")throw new Error("Can only accept pending swap requests");const n=new Date().toISOString();return await Q(s,{status:"accepted",updated_at:n}),await this.recordTransaction(i.shift_id_a,"swap_accept",{swap_id:t,accepted_by:r.id}),await se.publishSwapAccepted({swap_id:t,accepted_by_employee_id:r.id}),console.log("[HRSchedulingService] Accepted swap request:",t),this.getSwapRequest(t)}async approveSwapRequest(t){const r=A.getCurrentUser(),a=r.tenantId,o=T(a,ut),s=B(_,o,t),i=await this.getSwapRequest(t);if(!i)return null;if(i.status!=="accepted"&&i.status!=="pending_approval")throw new Error("Can only approve accepted or pending_approval swap requests");const n=new Date().toISOString();return i.swap_type==="handoff"?await this.assignEmployeeSimple(i.shift_id_a,i.employee_b):i.swap_type==="two_shift"&&i.shift_id_b&&(await this.assignEmployeeSimple(i.shift_id_a,i.employee_b),await this.assignEmployeeSimple(i.shift_id_b,i.employee_a)),await Q(s,{status:"approved",updated_at:n}),await this.recordTransaction(i.shift_id_a,"swap_approve",{swap_id:t,approved_by:r.id}),await se.publishSwapCompleted({swap_id:t,shift_ids:[i.shift_id_a,i.shift_id_b].filter(c=>!!c),employee_ids:[i.employee_a,i.employee_b]}),console.log("[HRSchedulingService] Approved swap request:",t),this.getSwapRequest(t)}async rejectSwapRequest(t,r){const a=A.getCurrentUser(),o=a.tenantId,s=T(o,ut),i=B(_,s,t),n=await this.get
28SwapRequest(t);if(!n)return null;if(n.status==="approved"||n.status==="applied")throw new Error("Cannot reject already approved or applied swap requests");const c=new Date().toISOString();return await Q(i,{status:"rejected",policy_snapshot:{rejection_reason:r},updated_at:c}),await se.publishSwapRejected({swap_id:t,rejected_by_user_id:a.id,reason:r}),console.log("[HRSchedulingService] Rejected swap request:",t),this.getSwapRequest(t)}async cancelSwapRequest(t){const r=A.getCurrentUser(),a=r.tenantId,o=T(a,ut),s=B(_,o,t),i=await this.getSwapRequest(t);if(!i)return null;if(i.status==="approved"||i.status==="applied")throw new Error("Cannot cancel already approved or applied swap requests");const n=new Date().toISOString();return await Q(s,{status:"canceled",updated_at:n}),await se.publishSwapCanceled({swap_id:t,canceled_by_user_id:r.id}),console.log("[HRSchedulingService] Canceled swap request:",t),this.getSwapRequest(t)}subscribeToSwaps(t,r){const a=this.resolveTenantId();if(!a)return r([]),()=>{};const o=T(a,ut),s=H(_,o),i=V(s,ee("created_at","desc"));return we(i,c=>{var m;let d=c.docs.map(u=>({...u.data(),id:u.id}));t.employee_id&&(d=d.filter(u=>u.employee_a===t.employee_id||u.employee_b===t.employee_id)),(m=t.statuses)!=null&&m.length&&(d=d.filter(u=>t.statuses.includes(u.status))),r(d)},c=>{console.error("[HRSchedulingService] Swap subscription error:",c),r([])})}async getAvailabilityRules(t){const r=A.getCurrentUser().tenantId,a=T(r,kt),o=H(_,a);let s=V(o,ee("weekday","asc"));return t&&(s=V(o,K("employee_id","==",t),ee("weekday","asc"))),(await Z(s)).docs.map(n=>({...n.data(),id:n.id}))}async createAvailabilityRule(t){const r=A.getCurrentUser().tenantId,a=T(r,kt),o=H(_,a),s=new Date().toISOString(),i={tenant_id:r,employee_id:t.employee_id,weekday:t.weekday,start_local_time:t.start_local_time,end_local_time:t.end_local_time,type:t.type,effective_start_date:t.effective_start_date||null,effective_end_date:t.effective_end_date||null,created_at:s,updated_at:s},n=await ie(o,i);return await se.publishAvailabilityUpdated({employee_id:t.employee_id,rules_count:1,action:"created"}),console.log("[HRSchedulingService] Created availability rule:",n.id),{...i,id:n.id}}async updateAvailabilityRule(t,r){const a=A.getCurrentUser().tenantId,o=T(a,kt),s=B(_,o,t);if(!(await oe(s)).exists())return null;await Q(s,{...r,updated_at:new Date().toISOString()});const n=await oe(s),c={...n.data(),id:n.id};return await se.publishAvailabilityUpdated({employee_id:c.employee_id,rules_count:1,action:"updated"}),console.log("[HRSchedulingService] Updated availability rule:",t),c}async deleteAvailabilityRule(t,r=!0){const a=A.getCurrentUser().tenantId,o=T(a,kt),s=B(_,o,t),i=await oe(s);if(!i.exists())return!1;const n={...i.data(),id:i.id};return await ke(s),r&&await se.publishAvailabilityUpdated({employee_id:n.employee_id,rules_count:1,action:"deleted"}),console.log("[HRSchedulingService] Deleted availability rule:",t),!0}async bulkSetAvailability(t,r){const a=A.getCurrentUser().tenantId;T(a,kt);const o=await this.getAvailabilityRules(t);for(const i of o)await this.deleteAvailabilityRule(i.id,!1);const s=[];for(const i of r){const n=await this.createAvailabilityRuleInternal({employee_id:t,...i});s.push(n)}return await se.publishAvailabilityUpdated({employee_id:t,rules_count:s.length,action:"bulk_set"}),console.log("[HRSchedulingService] Bulk set availability for employee:",t,"rules:",s.length),s}async createAvailabilityRuleInternal(t){const r=A.getCurrentUser().tenantId,a=T(r,kt),o=H(_,a),s=new Date().toISOString(),i={tenant_id:r,employee_id:t.employee_id,weekday:t.weekday,start_local_time:t.start_local_time,end_local_time:t.end_local_time,type:t.type,effective_start_date:t.effective_start_date||null,effective_end_date:t.effective_end_date||null,created_at:s,updated_at:s},n=await ie(o,i);return{...i,id:n.id}}subscribeToAvailabilityRules(t,r){const a=this.resolveTenantId();if(!a)return r([]),()=>{};const o=T(a,kt),s=H(_,o),i=V(s,K("employee_id","==",t),ee("weekday","asc"));return we(i,c=>{const d=c.docs.map(m=>({...m.data(),id:m.id}));r(d)},c=>{console.error("[HRSchedulingService] Availability subscription error:",c),r([])})}async checkAvailability(t,r,a){const o=await this.getAvailabilityRules(t),s=[],i=r.getDay(),n=r.toTimeStr
28ing().slice(0,5),c=a.toTimeString().slice(0,5),d=o.filter(u=>u.weekday===i);for(const u of d)u.effective_start_date&&new Date(u.effective_start_date)>r||u.effective_end_date&&new Date(u.effective_end_date)<r||u.type==="cannot"&&n<u.end_local_time&&c>u.start_local_time&&s.push(`Cannot work ${u.start_local_time} - ${u.end_local_time}`);const m=d.filter(u=>u.type==="can");return m.length>0&&(m.some(h=>n>=h.start_local_time&&c<=h.end_local_time)||s.push("Shift falls outside available hours")),{available:s.length===0,conflicts:s}}async checkEmployeeEligibility(t,r){const a=[],o=new Date(r.start_at_utc),s=new Date(r.end_at_utc),i=await this.checkAvailability(t,o,s);if(!i.available)return{eligible:!1,blocked:!0,blockReason:i.conflicts.join("; "),warnings:[]};if((await this.getShiftsForEmployee(t,o,s)).length>0)return{eligible:!1,blocked:!0,blockReason:"Employee already has a shift during this time",warnings:[]};try{if((await xt.getTimeOffRequests({employee_ids:[t],statuses:["approved"]})).some(m=>{const u=new Date(m.start_at_utc),h=new Date(m.end_at_utc);return o<h&&s>u}))return{eligible:!1,blocked:!0,blockReason:"Employee has approved time off during this shift",warnings:[]}}catch{a.push("Could not verify time off status")}return{eligible:!0,blocked:!1,warnings:a}}async deleteAppliedTemplateShifts(t){const r=A.getCurrentUser().tenantId,a=T(r,ge),o=H(_,a),s=V(o,ee("start_at_utc","asc"));let n=(await Z(s)).docs.map(m=>({...m.data(),id:m.id}));if(n=n.filter(m=>m.template_id!==null&&m.template_id!==void 0),t.templateId&&(n=n.filter(m=>m.template_id===t.templateId)),t.startDate){const m=new Date(t.startDate);n=n.filter(u=>new Date(u.start_at_utc)>=m)}if(t.endDate){const m=new Date(t.endDate);n=n.filter(u=>new Date(u.start_at_utc)<=m)}if(t.createdAfter){const m=new Date(t.createdAfter);n=n.filter(u=>new Date(u.created_at)>=m)}console.log(`[HRSchedulingService] Found ${n.length} template-applied shifts to delete`);let c=0,d=0;for(const m of n)try{await this.deleteShift(m.id,!!t.hardDelete)?c+=1:d+=1}catch(u){console.error("[HRSchedulingService] Failed to delete template-applied shift:",m.id,u),d+=1}return console.log(`[HRSchedulingService] Template shift deletion complete: ${c} deleted, ${d} failed`),{deleted:c,failed:d}}async getOpenShifts(t){var d;const r=A.getCurrentUser().tenantId,a=T(r,ge),o=H(_,a),s=V(o,ee("start_at_utc","asc"));let n=(await Z(s)).docs.map(m=>({...m.data(),id:m.id}));if(n=n.filter(m=>!m.is_deleted&&(m.status==="open"||m.status==="published"&&!m.assigned_employee_id)),(d=t==null?void 0:t.locationIds)!=null&&d.length&&(n=n.filter(m=>t.locationIds.includes(m.location_id))),t!=null&&t.startDate){const m=new Date(t.startDate);n=n.filter(u=>new Date(u.start_at_utc)>=m)}if(t!=null&&t.endDate){const m=new Date(t.endDate);n=n.filter(u=>new Date(u.start_at_utc)<=m)}const c=new Date;return n=n.filter(m=>new Date(m.start_at_utc)>c),console.log(`[HRSchedulingService] Found ${n.length} open shifts`),n}async submitPickupRequest(t,r,a){const o=A.getCurrentUser(),s=o.tenantId,i=await this.get
28Shift(t);if(!i)throw new Error("Shift not found");if(i.status!=="open"&&!(i.status==="published"&&!i.assigned_employee_id))throw new Error("Shift is not available for pickup");const n=await this.checkEmployeeEligibility(r,i);if(n.blocked)throw new Error(`Not eligible: ${n.blockReason}`);const c=T(s,Ct),d=H(_,c),m=new Date().toISOString(),u={tenant_id:s,shift_id:t,type:"pickup_request",from_employee_id:null,to_employee_id:r,requested_by_user_id:o.id,approved_by_user_id:null,status:"pending",policy_snapshot:{eligibility:n,message:a,shift_start:i.start_at_utc,location_id:i.location_id},reason:a||null,created_at:m,resolved_at:null},h=await ie(d,u);return await se.publishPickupRequested({transaction_id:h.id,shift_id:t,employee_id:r,location_id:i.location_id,shift_start_utc:i.start_at_utc,message:a}),console.log("[HRSchedulingService] Pickup request created:",h.id),{...u,id:h.id}}async getPendingPickupRequests(t){const r=A.getCurrentUser().tenantId,a=T(r,Ct),o=H(_,a),s=V(o,K("type","==","pickup_request"),K("status","==","pending"),ee("created_at","desc")),n=(await Z(s)).docs.map(d=>({...d.data(),id:d.id})),c=[];
28for(const d of n){const m=await this.getShift(d.shift_id);t!=null&&t.length&&m&&!t.includes(m.location_id)||c.push({transaction:d,shift:m})}return console.log(`[HRSchedulingService] Found ${c.length} pending pickup requests`),c}async approvePickupRequest(t){const r=A.getCurrentUser(),a=r.tenantId,o=T(a,Ct),s=B(_,o,t),i=await oe(s);if(!i.exists())throw new Error("Transaction not found");const n={...i.data(),id:i.id};if(n.status!=="pending")throw new Error("Transaction is not pending");if(n.type!=="pickup_request")throw new Error("Transaction is not a pickup request");const c=await this.getShift(n.shift_id);if(!c)throw new Error("Shift not found");const d=T(a,ge),m=B(_,d,n.shift_id),u=new Date().toISOString();await Q(m,{assigned_employee_id:n.to_employee_id,status:"assigned",version:(c.version||0)+1,updated_at:u,updated_by_user_id:r.id}),await Q(s,{status:"applied",approved_by_user_id:r.id,resolved_at:u}),await this.recordTransaction(n.shift_id,"pickup_approve",{from_employee_id:null,to_employee_id:n.to_employee_id,pickup_request_id:t}),await se.publishPickupApproved({transaction_id:t,shift_id:n.shift_id,employee_id:n.to_employee_id,approved_by_user_id:r.id}),console.log("[HRSchedulingService] Pickup request approved:",t)}async rejectPickupRequest(t,r){const a=A.getCurrentUser(),o=a.tenantId,s=T(o,Ct),i=B(_,s,t),n=await oe(i);if(!n.exists())throw new Error("Transaction not found");const c={...n.data(),id:n.id},d=new Date().toISOString();await Q(i,{status:"rejected",approved_by_user_id:a.id,resolved_at:d,reason:r||null}),await se.publishPickupRejected({transaction_id:t,shift_id:c.shift_id,employee_id:c.to_employee_id,rejected_by_user_id:a.id,reason:r}),console.log("[HRSchedulingService] Pickup request rejected:",t)}async claimOpenShift(t,r){const a=A.getCurrentUser(),o=a.tenantId,s=await this.get
28Shift(t);if(!s)throw new Error("Shift not found");if(s.status!=="open"&&!(s.status==="published"&&!s.assigned_employee_id))throw new Error("Shift is not available for pickup");const i=await this.checkEmployeeEligibility(r,s);if(i.blocked)throw new Error(`Not eligible: ${i.blockReason}`);const n=T(o,ge),c=B(_,n,t),d=new Date().toISOString();return await Q(c,{assigned_employee_id:r,status:"assigned",version:(s.version||0)+1,updated_at:d,updated_by_user_id:a.id}),await this.recordTransaction(t,"pickup_request",{to_employee_id:r,auto_approved:!0}),await this.recordTransaction(t,"pickup_approve",{from_employee_id:null,to_employee_id:r,auto_approved:!0}),await se.publishPickupClaimed({shift_id:t,employee_id:r,auto_approved:!0}),await se.publishShiftAssigned({shift_id:t,employee_id:r,version:(s.version||0)+1}),console.log("[HRSchedulingService] Open shift claimed:",t,"by employee:",r),await this.getShift(t)}async getTravelBuffers(){const t=A.getCurrentUser().tenantId,r=T(t,xr),a=H(_,r),s=(await Z(a)).docs.map(i=>({...i.data(),id:i.id}));return console.log(`[HRSchedulingService] Retrieved ${s.length} travel buffers`),s}async getTravelBuffer(t,r){const a=A.getCurrentUser().tenantId,o=T(a,xr),s=H(_,o),i=V(s,K("location_a_id","==",t),K("location_b_id","==",r)),n=await Z(i);if(!n.empty)return{...n.docs[0].data(),id:n.docs[0].id};const c=V(s,K("location_a_id","==",r),K("location_b_id","==",t)),d=await Z(c);return d.empty?null:{...d.docs[0].data(),id:d.docs[0].id}}async setTravelBuffer(t,r,a){const s=A.getCurrentUser().tenantId,i=T(s,xr),n=H(_,i),c=await this.getTravelBuffer(t,r);if(c){const d=B(_,i,c.id);return await Q(d,{buffer_minutes:a}),console.log("[HRSchedulingService] Travel buffer updated:",c.id),{...c,buffer_minutes:a}}else{const[d,m]=[t,r].sort(),u={tenant_id:s,location_a_id:d,location_b_id:m,buffer_minutes:a},h=await ie(n,u);return console.log("[HRSchedulingService] Travel buffer created:",h.id),{...u,id:h.id}}}async deleteTravelBuffer(t,r){const a=A.getCurrentUser().tenantId,o=T(a,xr),s=await this.getTravelBuffer(t,r);if(!s)return console.log("[HRSchedulingService] Travel buffer not found, nothing to delete"),!1;const i=B(_,o,s.id);return await ke(i),console.log("[HRSchedulingService] Travel buffer deleted:",s.id),!0}async bulkSetTravelBuffers(t){let r=0,a=0,o=0;for(const s of t)try{const i=await this.getTravelBuffer(s.locationAId,s.locationBId);await this.setTravelBuffer(s.locationAId,s.locationBId,s.bufferMinutes),i?a++:r++}catch(i){console.error("[HRSchedulingService] Failed to set travel buffer:",i),o++}return console.log(`[HRSchedulingService] Bulk travel buffer update: ${r} created, ${a} updated, ${o} failed`),{created:r,updated:a,failed:o}}cleanup(){this.unsubscribeFn&&(this.unsubscribeFn(),this.unsubscribeFn=null),this.listeners=[],this.shifts=[],this.templates=[],this.initialized=!1}}const te=new Zi,Tt="hr_locations",It="hr_positions",hr="hr_location_managers",Kr="hr_location_travel_buffers",Ji=["America/New_York","America/Chicago","America/Denver","America/Los_Angeles","America/Phoenix","America/Anchorage","Pacific/Honolulu"];class Xi{resolveTenantId(){return(typeof window<"u"?window.localStorage.getItem("tenantId"):null)||null}async getLocations(t=!1){const r=A.getCurrentUser().tenantId,a=T(r,Tt),o=H(_,a),s=V(o,ee("name","asc"));let n=(await Z(s)).docs.map(c=>({...c.data(),id:c.id}));return t||(n=n.filter(c=>c.status==="active")),n}async getLocation(t){const r=A.getCurrentUser().tenantId,a=T(r,Tt),o=B(_,a,t),s=await oe(o);return s.exists()?{...s.data(),id:s.id}:null}async createLocation(t){const r=A.getCurrentUser().tenantId,a=T(r,Tt),o=H(_,a),s=new Date().toISOString(),i={tenant_id:r,name:t.name,timezone:t.timezone,legal_entity_id:t.legal_entity_id||null,address:t.address,status:"active",created_at:s,updated_at:s},n=await ie(o,i);return console.log("[HRLocationService] Created location:",n.id),{...i,id:n.id}}async updateLocation(t,r){const a=A.getCurrentUser().tenantId,o=T(a,Tt),s=B(_,o,t);return await this.getLocation(t)?(await Q(s,{...r,updated_at:new Date().toISOString()}),console.log("[HRLocationService] Updated location:",t),this.getLocation(t)):null}async archiveLocation(t){return this.updateLocation(t,{status:"archived"})}async deleteLocation(t){const r=A.getCurrentUser().tenantId,a=T(r,Tt),o=B(_,a,t);return await this.getLocation(t)?(await ke(o),console.log("[HRLocationService] Deleted location:",t),!0):!1}subscribeToLocations(t,r=!1){const a=this.resolveTenantId();if(!a)return t([]),()=>{};const o=T(a,Tt),s=H(_,o),i=V(s,ee("name","asc"));return we(i,c=>{let d=c.docs.map(m=>({...m.data(),id:m.id}));r||(d=d.filter(m=>m.status==="active")),t(d)},c=>{console.error("[HRLocationService] Locations subscription error:",c),t([])})}async getPositions(t=!1){const r=A.getCurrentUser().tenantId,a=T(r,It),o=H(_,a),s=V(o,ee("name","asc"));let n=(await Z(s)).docs.map(c=>({...c.data(),id:c.id}));return t||(n=n.filter(c=>c.status==="active")),n}async getPosition(t){const r=A.getCurrentUser().tenantId,a=T(r,It),o=B(_,a,t),s=await oe(o);return s.exists()?{...s.data(),id:s.id}:null}async createPosition(t){const r=A.getCurrentUser().tenantId,a=T(r,It),o=H(_,a),s=new Date().toISOString(),i={tenant_id:r,name:t.name,description:t.description||null,status:"active",created_at:s,updated_at:s},n=await ie(o,i);return console.log("[HRLocationService] Created position:",n.id),{...i,id:n.id}}async updatePosition(t,r){const a=A.getCurrentUser().tenantId,o=T(a,It),s=B(_,o,t);return await this.getPosition(t)?(await Q(s,{...r,updated_at:new Date().toISOString()}),console.log("[HRLocationService] Updated position:",t),this.getPosition(t)):null}async archivePosition(t){return this.updatePosition(t,{status:"archived"})}async deletePosition(t){const r=A.getCurrentUser().tenantId,a=T(r,It),o=B(_,a,t);return await this.getPosition(t)?(await ke(o),console.log("[HRLocationService] Deleted position:",t),!0):!1}subscribeToPositions(t,r=!1){const a=this.resolveTenantId();if(!a)return t([]),()=>{};const o=T(a,It),s=H(_,o),i=V(s,ee("name","asc"));return we(i,c=>{let d=c.docs.map(m=>({...m.data(),id:m.id}));r||(d=d.filter(m=>m.status==="active")),t(d)},c=>{console.error("[HRLocationService] Positions subscription error:",c),t([])})}async getLocationManagers(t){const r=A.getCurrentUser().tenantId,a=T(r,hr),o=H(_,a),s=V(o,K("location_id","==",t));return(await Z(s)).docs.map(n=>({...n.data(),id:n.id}))}async addLocationManager(t){const r=A.getCurrentUser().tenantId,a=T(r,hr),o=H(_,a),s={tenant_id:r,location_id:t.location_id,user_id:t.user_id,role:t.role,created_at:new Date().toISOString()},i=await ie(o,s);return console.log("[HRLocationService] Added location manager:",i.id),{...s,id:i.id}}async updateLocationManagerRole(t,r){const a=A.getCurrentUser().tenantId,o=T(a,hr),s=B(_,o,t);await Q(s,{role:r});const i=await oe(s);return i.exists()?{...i.data(),id:i.id}:null}async removeLocationManager(t){const r=A.getCurrentUser().tenantId,a=T(r,hr),o=B(_,a,t);return await ke(o),console.log("[HRLocationService] Removed location manager:",t),!0}async getTravelBuffers(){const t=A.getCurrentUser().tenantId,r=T(t,Kr),a=H(_,r);return(await Z(a)).docs.map(s=>({...s.data(),id:s.id}))}async setTravelBuffer(t,r,a){const o=A.getCurrentUser().tenantId,s=T(o,Kr),i=H(_,s),c=(await this.getTravelBuffers()).find(u=>u.location_a_id===t&&u.location_b_id===r||u.location_a_id===r&&u.location_b_id===t);if(c){const u=B(_,s,c.id);return await Q(u,{buffer_minutes:a}),{...c,buffer_minutes:a}}const d={tenant_id:o,location_a_id:t,location_b_id:r,buffer_minutes:a},m=await ie(i,d);return{...d,id:m.id}}async getTravelBuffer(t,r){const o=(await this.getTravelBuffers()).find(s=>s.location_a_id===t&&s.location_b_id===r||s.location_a_id===r&&s.location_b_id===t);return(o==null?void 0:o.buffer_minutes)||0}async removeTravelBuffer(t){const r=A.getCurrentUser().tenantId,a=T(r,Kr),o=B(_,a,t);return await ke(o),!0}}const mt=new Xi,At="hr_calendar_mappings";class ec{constructor(){this.initialized=!1}initialize(){this.initialized||(console.log("[HRCalendarIntegration] Initializing event subscriptions..."),se.subscribe("hr.shift.published",async t=>{await this.handleShiftPublished(t)}),se.subscribe("hr.shift.assigned",async t=>{await this.handleShiftAssigned(t)}),se.subscribe("hr.shift.unassigned",async t=>{await this.handleShiftUnassigned(t)}),se.subscribe("hr.shift.canceled",async t=>{await this.handleShiftCanceled(t)}),this.initialized=!0,console.log("[HRCalendarIntegration] Event subscriptions initialized"))}async handleShiftPublished(t){const{shift_id:r,assigned_employee_id:a,version:o}=t.payload;if(!a){console.log("[HRCalendarIntegration] Shift published without assignment, skipping calendar event");return}console.log("[HRCalendarIntegration] Processing shift.published:",r);
28try{const s=await this.getShiftDetails(t.tenant_id,r);if(!s){console.error("[HRCalendarIntegration] Shift not found:",r);return}await this.createOrUpdateCalendarEvent(t.tenant_id,s,a,o)}catch(s){console.error("[HRCalendarIntegration] Error handling shift.published:",s)}}async handleShiftAssigned(t){const{shift_id:r,employee_id:a,version:o,previous_employee_id:s}=t.payload;console.log("[HRCalendarIntegration] Processing shift.assigned:",r,"->",a);try{s&&await this.deleteCalendarEventForEmployee(t.tenant_id,r,s);const i=await this.getShiftDetails(t.tenant_id,r);if(!i){console.error("[HRCalendarIntegration] Shift not found:",r);return}(i.status==="published"||i.status==="assigned")&&await this.createOrUpdateCalendarEvent(t.tenant_id,i,a,o)}catch(i){console.error("[HRCalendarIntegration] Error handling shift.assigned:",i)}}async handleShiftUnassigned(t){const{shift_id:r,from_employee_id:a}=t.payload;console.log("[HRCalendarIntegration] Processing shift.unassigned:",r,"from",a);try{await this.deleteCalendarEventForEmployee(t.tenant_id,r,a)}catch(o){console.error("[HRCalendarIntegration] Error handling shift.unassigned:",o)}}async handleShiftCanceled(t){const{shift_id:r,had_employee:a}=t.payload;if(console.log("[HRCalendarIntegration] Processing shift.canceled:",r),!!a)try{const o=await this.getMappingsForShift(t.tenant_id,r);for(const s of o)await this.deleteCalendarEventByMapping(t.tenant_id,s)}catch(o){console.error("[HRCalendarIntegration] Error handling shift.canceled:",o)}}async createOrUpdateCalendarEvent(t,r,a,o){const s=await this.getMapping(t,r.id,a);if(s&&s.shiftVersion>=o){console.log("[HRCalendarIntegration] Skipping stale version:",o);return}const i=this.buildCalendarEvent(r,a);if(s)await this.updateLocalCalendarEvent(t,s.localEventId,i),await this.updateMapping(t,s.id,{shiftVersion:o});else{const n=await this.createLocalCalendarEvent(t,a,i);await this.createMapping(t,r.id,a,n,o)}await this.queueExternalSync(t,r.id,a,"upsert"),console.log("[HRCalendarIntegration] Calendar event created/updated for shift:",r.id)}buildCalendarEvent(t,r){var s,i;const a=((s=t.location)==null?void 0:s.name)||"Unknown Location";return{title:`${((i=t.position)==null?void 0:i.name)||t.role||"Shift"} @ ${a}`,type:"SHIFT",start:t.start_at_utc,end:t.end_at_utc,description:this.buildShiftDescription(t),location:a,isAllDay:!1,linkedEmployeeId:r,linkedShiftId:t.id,source:"hr_scheduling"}}buildShiftDescription(t){var a,o,s;const r=[];return(a=t.position)!=null&&a.name&&r.push(`Position: ${t.position.name}`),(o=t.location)!=null&&o.name&&r.push(`Location: ${t.location.name}`),(s=t.location)!=null&&s.address&&r.push(`Address: ${t.location.address}`),t.notes&&(r.push(""),r.push(`Notes: ${t.notes}`)),r.push(""),r.push("--- Managed by NelsonOS HR ---"),r.join(` 29`)}async createLocalCalendarEvent(t,r,a){const o=H(_,"tenants",t,"users",r,"calendar_events"),s={...a,id:`shift-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,calendarId:"work-schedule",createdAt:ht.now(),updatedAt:ht.now(),source:"hr_scheduling"},i=await ie(o,s);return console.log("[HRCalendarIntegration] Created local calendar event:",i.id),i.id}async updateLocalCalendarEvent(t,r,a){const o=await this.getMappingByLocalEventId(t,r);if(!o){console.warn("[HRCalendarIntegration] Mapping not found for event:",r);return}const s=B(_,"tenants",t,"users",o.employeeId,"calendar_events",r);await Q(s,{...a,updatedAt:ht.now()}),console.log("[HRCalendarIntegration] Updated local calendar event:",r)}async deleteCalendarEventForEmployee(t,r,a){const o=await this.getMapping(t,r,a);if(!o){console.log("[HRCalendarIntegration] No mapping found to delete");return}await this.deleteCalendarEventByMapping(t,o)}async deleteCalendarEventByMapping(t,r){try{const o=B(_,"tenants",t,"users",r.employeeId,"calendar_events",r.localEventId);await ke(o),console.log("[HRCalendarIntegration] Deleted local calendar event:",r.localEventId)}catch(o){console.warn("[HRCalendarIntegration] Error deleting local event:",o)}await this.queueExternalSync(t,r.shiftId,r.employeeId,"delete");const a=B(_,"tenants",t,At,r.id);await ke(a),console.log("[HRCalendarIntegration] Deleted mapping:",r.id)}async getMapping(t,r,a){const o=H(_,"tenants",t,At),s=V(o,K("shiftId","==",r),K("employeeId","==",a)),i=await Z(s);
29return i.empty?null:{id:i.docs[0].id,...i.docs[0].data()}}async getMappingByLocalEventId(t,r){const a=H(_,"tenants",t,At),o=V(a,K("localEventId","==",r)),s=await Z(o);return s.empty?null:{id:s.docs[0].id,...s.docs[0].data()}}async getMappingsForShift(t,r){const a=H(_,"tenants",t,At),o=V(a,K("shiftId","==",r));return(await Z(o)).docs.map(i=>({id:i.id,...i.data()}))}async createMapping(t,r,a,o,s){const i=H(_,"tenants",t,At),n=new Date().toISOString(),c={tenantId:t,shiftId:r,employeeId:a,localEventId:o,externalSync:{},shiftVersion:s,createdAt:n,updatedAt:n};return{id:(await ie(i,c)).id,...c}}async updateMapping(t,r,a){const o=B(_,"tenants",t,At,r);await Q(o,{...a,updatedAt:new Date().toISOString()})}async queueExternalSync(t,r,a,o){const s=H(_,"tenants",t,"hr_external_calendar_sync_jobs");await ie(s,{shiftId:r,employeeId:a,action:o,status:"pending",attempts:0,createdAt:ht.now()}),console.log("[HRCalendarIntegration] Queued external sync job:",o,r)}async getExternalCalendarConfig(t,r){const a=[],o=B(_,"tenants",t,"users",r,"integrations","google_calendar"),s=await oe(o);if(s.exists()){const c=s.data();c.status==="connected"&&c.hasWriteAccess&&a.push({provider:"google",hasWriteAccess:!0,calendarId:c.primaryCalendarId||"primary"})}const i=B(_,"tenants",t,"users",r,"integrations","microsoft_calendar"),n=await oe(i);if(n.exists()){const c=n.data();c.status==="connected"&&c.hasWriteAccess&&a.push({provider:"microsoft",hasWriteAccess:!0,calendarId:c.primaryCalendarId||"primary"})}return a}async getShiftDetails(t,r){const a=B(_,"tenants",t,"hr_shifts",r),o=await oe(a);if(!o.exists())return null;const s=o.data();let i;if(s.location_id){const c=B(_,"tenants",t,"hr_locations",s.location_id),d=await oe(c);d.exists()&&(i={id:d.id,...d.data()})}let n;if(s.position_id){const c=B(_,"tenants",t,"hr_positions",s.position_id),d=await oe(c);d.exists()&&(n={id:d.id,...d.data()})}return{id:o.id,...s,location:i,position:n}}}const tc=new ec;function rc(l){const t=[],r=new Date;r.setHours(0,0,0,0);for(let a=0;a<7;a++){const o=new Date(l);o.setDate(o.getDate()+a),o.setHours(0,0,0,0),t.push({date:o,dayName:o.toLocaleDateString("en-US",{weekday:"short"}),dateLabel:o.toLocaleDateString("en-US",{month:"short",day:"numeric"}),isToday:o.getTime()===r.getTime()})}return t}function Qa(l){const t=new Date(l),r=t.getDay(),a=t.getDate()-r;return t.setDate(a),t.setHours(0,0,0,0),t}function Za(l,t){return new Date(l).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function ac(l){switch(l){case"draft":return"bg-gray-500/20 border-gray-500/40 text-[var(--color-text-muted)]";case"published":return"bg-[var(--color-primary-subtle)] border-blue-500/40 text-[var(--color-primary)]";case"open":return"bg-amber-500/20 border-amber-500/40 text-amber-300";case"assigned":return"bg-emerald-500/20 border-emerald-500/40 text-emerald-300";case"coverage_requested":return"bg-orange-500/20 border-orange-500/40 text-orange-300";case"covered":return"bg-teal-500/20 border-teal-500/40 text-teal-300";case"canceled":return"bg-red-500/20 border-red-500/40 text-red-300 opacity-50";default:return"bg-[var(--color-bg-hover)] border-[var(--color-border-default)] text-[var(--color-text-primary)]"}}function sc(l){switch(l){case"draft":return"Draft";case"published":return"Published";case"open":return"Open";case"assigned":return"Assigned";case"coverage_requested":return"Needs Coverage";case"covered":return"Covered";case"canceled":return"Canceled";default:return l}}const oc=({shift:l,onEdit:t,onDelete:r,onAssign:a,selectMode:o=!1,isSelected:s=!1,onToggleSelect:i,overtimeRisk:n="none"})=>{var p;const[c,d]=x.useState(!1),m=n==="overtime"?"border-l-2 border-l-red-500":n==="warning"?"border-l-2 border-l-amber-500":"",u=Za(l.start_at_utc,l.timezone),h=Za(l.end_at_utc,l.timezone),v=((p=l.duration_hours)==null?void 0:p.toFixed(1))||"â",y=N=>{o&&i?(N.stopPropagation(),i()):t()};return e.jsxs("div",{className:`relative p-2 rounded-lg border ${ac(l.status)} 30 ${s?"ring-2 ring-brand-500 ring-offset-1 ring-offset-slate-900":""} 31 ${m} 32 hover:border-white/40 transition-colors cursor-pointer group`,onClick:y,children:[o&&e.jsx("div",{className:"absolute top-1 left-1 z-10",onClick:N=>{N.stopPropagation(),i==null||i()},children:s?e.jsx(Xo,{className:"w-4 h-4 text-brand-400"}):e.jsx(vs,{className:"w-4 h-4 text-[var(--color-text-muted)] hover:text-[var(--color-text-primary)]"})}),e.jsxs("div",{className:`flex items-center gap-1 text-xs font-medium mb-1 ${o?"ml-5":""}`,children:[e.jsx(ve,{className:"w-3 h-3"}),e.jsxs("span",{children:[u," - ",h]}),e.jsxs("span",{className:"text-[var(--color-text-secondary)]",children:["(",v,"h)"]})]}),l.position_name&&e.jsx("div",{className:"text-xs text-[var(--color-text-primary)] mb-1 truncate",children:l.position_name}),e.jsxs("div",{className:"flex items-center gap-1 text-xs",children:[e.jsx(Re,{className:"w-3 h-3"}),l.assigned_employee_name?e.jsx("span",{className:"truncate",children:l.assigned_employee_name}):l.status==="open"?e.jsx("button",{onClick:N=>{N.stopPropagation(),a()},className:"text-amber-400 hover:text-amber-300 underline",children:"Claim Shift"}):e.jsx("button",{onClick:N=>{N.stopPropagation(),a()},className:"text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] underline",children:"Assign"})]}),e.jsx("div",{className:"absolute top-1 right-1",children:e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wide opacity-70",children:sc(l.status)})}),e.jsx("button",{onClick:N=>{N.stopPropagation(),d(!c)},className:`absolute bottom-1 right-1 p-1 rounded opacity-0 group-hover:opacity-100 33 hover:bg-[var(--color-bg-hover)] transition-all`,children:e.jsx(fs,{className:"w-3 h-3"})}),c&&e.jsxs("div",{className:`absolute right-0 top-full mt-1 z-50 bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] 34 rounded-lg shadow-xl py-1 min-w-[120px]`,onClick:N=>N.stopPropagation(),children:[e.jsxs("button",{className:"w-full px-3 py-1.5 text-left text-xs hover:bg-[var(--color-bg-hover)] flex items-center gap-2",onClick:()=>{t(),d(!1)},children:[e.jsx(xs,{className:"w-3 h-3"})," View Details"]}
34),e.jsxs("button",{className:"w-full px-3 py-1.5 text-left text-xs hover:bg-[var(--color-bg-hover)] flex items-center gap-2",onClick:()=>{a(),d(!1)},children:[e.jsx(Re,{className:"w-3 h-3"})," Assign Employee"]}),e.jsx("hr",{className:"my-1 border-[var(--color-border-subtle)]"}),e.jsxs("button",{className:"w-full px-3 py-1.5 text-left text-xs hover:bg-[var(--color-bg-hover)] flex items-center gap-2 text-red-400",onClick:()=>{r(),d(!1)},children:[e.jsx(qe,{className:"w-3 h-3"})," Delete Shift"]})]})]})},nc=({shifts:l,locations:t,selectedLocationId:r,onLocationChange:a,onCreateShift:o,onEditShift:s,onDeleteShift:i,onPublishShifts:n,onAssignEmployee:c,onWeekChange:d,loading:m=!1,onBulkCancel:u,onBulkAssign:h,employees:v=[],overtimeThreshold:y=40,overtimeWarningThreshold:p=35,showOvertimePanel:N=!0})=>{const[S,j]=x.useState(()=>{const U=Qa(new Date);return setTimeout(()=>d==null?void 0:d(U),0),U}),[I,$]=x.useState(new Set),[R,E]=x.useState(!1),[O,D]=x.useState(!1),[b,P]=x.useState(!1),[W,k]=x.useState(""),[f,g]=x.useState(""),[L,z]=x.useState(!1),X=x.useMemo(()=>rc(S),[S]),C=x.useMemo(()=>{const U={};return X.forEach(J=>{const ue=J.date.toISOString().split("T")[0];U[ue]=[]}),l.forEach(J=>{if(J.is_deleted||r&&J.location_id!==r)return;const pe=new Date(J.start_at_utc).toISOString().split("T")[0];U[pe]&&U[pe].push(J)}),Object.values(U).forEach(J=>{J.sort((ue,pe)=>new Date(ue.start_at_utc).getTime()-new Date(pe.start_at_utc).getTime())}),U},[l,X,r]),Y=x.useMemo(()=>l.filter(U=>U.status==="draft"&&!U.is_deleted).length,[l]),F=x.useMemo(()=>{const U={};return l.filter(J=>!J.is_deleted&&J.status!=="canceled"&&J.assigned_employee_id).forEach(J=>{const ue=J.assigned_employee_id,pe=J.duration_hours||0;if(!U[ue]){const Ht=v.find(Bt=>Bt.id===ue);U[ue]={hours:0,name:Ht?`${Ht.firstName} ${Ht.lastName}`:"Unknown"}}U[ue].hours+=pe}),Object.entries(U).map(([J,ue])=>({employeeId:J,employeeName:ue.name,totalHours:ue.hours,overtimeRisk:ue.hours>y?"overtime":ue.hours>p?"warning":"none"}))},[l,v,y,p]),re=x.useMemo(()=>F.filter(U=>U.overtimeRisk!=="none"),[F]),me=x.useCallback(U=>{if(!U)return"none";const J=F.find(ue=>ue.employeeId===U);return(J==null?void 0:J.overtimeRisk)||"none"},[F]),_e=()=>{const U=new Date(S);U.setDate(U.getDate()-7),j(U),d==null||d(U)},Ue=()=>{const U=new Date(S);U.setDate(U.getDate()+7),d==null||d(U),j(U)},q=()=>{j(Qa(new Date))},ne=()=>{const U=l.filter(J=>J.status==="draft"&&!J.is_deleted).map(J=>J.id);U.length>0&&n(U)},ae=x.useCallback(U=>{$(J=>{const ue=new Set(J);return ue.has(U)?ue.delete(U):ue.add(U),ue})},[]),Ie=x.useCallback(()=>{$(new Set),E(!1),D(!1),P(!1)},[]),$e=x.useCallback(()=>{const U=Object.values(C).flat().map(J=>J.id);$(new Set(U))},[C]),Ke=x.useMemo(()=>l.filter(U=>I.has(U.id)),[l,I]),wt=Ke.filter(U=>U.status==="draft").length,jt=Ke.filter(U=>U.status==="published"||U.status==="open").length,Dt=()=>{const U=Ke.filter(J=>J.status==="draft").map(J=>J.id);U.length>0&&(n(U),Ie())},_t=async()=>{if(!(!W||!h)){z(!0);try{const U=Ke.filter(J=>["published","open","coverage_requested"].includes(J.status)).map(J=>J.id);await h(U,W),Ie()}catch(U){console.error("Bulk assign failed:",U)}finally{z(!1)}}},lt=async()=>{if(u){z(!0);try{const U=Ke.filter(J=>J.status!=="canceled").map(J=>J.id);await u(U,f||void 0),Ie()}catch(U){console.error("Bulk cancel failed:",U)}finally{z(!1)}}};return e.jsxs("div",{className:"h-full flex flex-col",children:[N&&re.length>0&&e.jsxs("div",{className:"mb-4 p-3 bg-amber-500/10 border border-amber-500/30 rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2 text-amber-400 font-medium text-sm mb-2",children:[e.jsx(Ee,{className:"w-4 h-4"}),"Overtime Risk (",re.length," employee",re.length!==1?"s":"",")"]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[re.slice(0,5).map(U=>e.jsxs("div",{className:`px-2 py-1 rounded text-xs font-medium 35 ${U.overtimeRisk==="overtime"?"bg-red-500/20 text-red-400 border border-red-500/40":"bg-amber-500/20 text-amber-400 border border-amber-500/40"}`,children:[U.employeeName,": ",U.totalHours.toFixed(1),"h",U.overtimeRisk==="overtime"?" (OT)":" (risk)"]},U.employeeId)),re.length>5&&e.jsxs("span",{className:"px-2 py-1 text-xs text-amber-400/70",children:["+",re.length-5," more"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("select",{value:r||"",onChange:U=>a(U.target.value),className:`bg-[var(--color-bg-hover)] backdrop-blur-xl border border-[var(--color-border-default)] rounded-lg px-3 py-2 36 text-[var(--color-text-primary)] text-sm focus:outline-none focus:border-brand-500`,children:[e.jsx("option",{value:"",children:"All Locations"}),t.map(U=>e.jsx("option",{value:U.id,children:U.name},U.id))]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:_e,className:"p-2 hover:bg-[var(--color-bg-hover)] rounded-lg transition-colors",children:e.jsx(la,{className:"w-4 h-4 text-[var(--color-text-primary)]"})}),e.jsx("button",{onClick:q,className:`px-3 py-1.5 text-sm font-medium text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)] 37 rounded-lg transition-colors`,children:"Today"}),e.jsx("button",{onClick:Ue,className:"p-2 hover:bg-[var(--color-bg-hover)] rounded-lg transition-colors",children:e.jsx(nt,{className:"w-4 h-4 text-[var(--color-text-primary)]"})})]}),e.jsxs("span",{className:"text-[var(--color-text-primary)] font-medium",children:[X[0].dateLabel," - ",X[6].dateLabel]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:()=>{R?Ie():E(!0)},className:`flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-medium transition-colors 38 ${R?"bg-brand-500/20 text-brand-400 border border-brand-500/40":"bg-[var(--color-bg-hover)] text-[var(--color-text-primary)] hover:bg-[var(--color-bg-active)] hover:text-[var(--color-text-primary)]"}`,children:[e.jsx(un,{className:"w-4 h-4"}),R?"Exit Select":"Select"]}),!R&&Y>0&&e.jsxs("button",{onClick:ne,className:`flex items-center gap-2 px-3 py-2 bg-brand-600 hover:bg-brand-500 39 text-[var(--color-text-primary)] rounded-lg text-sm font-medium transition-colors`,children:[e.jsx(Nr,{className:"w-4 h-4"}),"Publish ",Y," Draft",Y!==1?"s":""]})]})]}),R&&e.jsxs("div",{className:"mb-4 p-3 bg-[var(--color-bg-hover)] backdrop-blur-xl border border-[var(--color-border-subtle)] rounded-lg",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("span",{className:"text-sm text-[var(--color-text-primary)]",children:[e.jsx("span",{className:"font-bold text-brand-400",children:I.size})," shifts selected"]}),e.jsx("button",{onClick:$e,className:"text-xs text-brand-400 hover:text-brand-300",children:"Select All Visible"}),e.jsx("button",{onClick:Ie,className:"text-xs text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]",children:"Clear Selection"})]}),I.size>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[wt>0&&e.jsxs("button",{onClick:Dt,disabled:L,className:`flex items-center gap-1 px-3 py-1.5 bg-[var(--color-primary-subtle)] hover:bg-blue-500/30 40 text-[var(--color-primary)] rounded text-xs font-medium disabled:opacity-50`,children:[e.jsx(Nr,{className:"w-3 h-3"}),"Publish (",wt,")"]}),jt>0&&h&&e.jsxs("button",{onClick:()=>D(!O),disabled:L,className:`flex items-center gap-1 px-3 py-1.5 bg-emerald-500/20 hover:bg-emerald-500/30 41 text-emerald-400 rounded text-xs font-medium disabled:opacity-50`,children:[e.jsx(ft,{className:"w-3 h-3"}),"Assign (",jt,")"]}),u&&e.jsxs("button",{onClick:()=>P(!b),disabled:L,className:`flex items-center gap-1 px-3 py-1.5 bg-red-500/20 hover:bg-red-500/30 42 text-red-400 rounded text-xs font-medium disabled:opacity-50`,children:[e.jsx(qe,{className:"w-3 h-3"}),"Cancel"]})]})]}),O&&e.jsxs("div",{className:"mt-3 pt-3 border-t border-[var(--color-border-subtle)] flex items-center gap-3",children:[e.jsxs("select",{value:W,onChange:U=>k(U.target.value),className:"bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded px-3 py-1.5 text-sm text-[var(--color-text-primary)]",children:[e.jsx("option",{value:"",children:"Select employee..."}),v.map(U=>e.jsxs("option",{value:U.id,children:[U.firstName," ",U.lastName]},U.id))]}),e.jsx("button",{onClick:_t,disabled:!W||L,className:`px-3 py-1.5 bg-emerald-500 hover:bg-emerald-400 text-[var(--color-text-primary)] text-xs 43 font-medium rounded disabled:opacity-50`,children:L?"Assigning...":"Assign All"}),e.jsx("button",{onClick:()=>D(!1),className:"text-xs text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]",children:"Cancel"})]}),b&&e.jsxs("div",{className:"mt-3 pt-3 border-t border-[var(--color-border-subtle)] flex items-center gap-3",children:[e.jsx("input",{type:"text",value:f,onChange:U=>g(U.target.value),placeholder:"Cancellation reason (optional)...",className:`flex-1 bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded px-3 py-1.5 text-sm 44 text-[var(--color-text-primary)] placeholder-white/40`}),e.jsx("button",{onClick:lt,disabled:L,className:`px-3 py-1.5 bg-red-500 hover:bg-red-400 text-[var(--color-text-primary)] text-xs 45 font-medium rounded disabled:opacity-50`,children:L?"Cancelling...":`Cancel ${Ke.filter(U=>
45U.status!=="canceled").length} Shifts`}),e.jsx("button",{onClick:()=>P(!1),className:"text-xs text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]",children:"Back"})]})]}),e.jsx("div",{className:"flex-1 grid grid-cols-7 gap-2 overflow-hidden",children:X.map(U=>{const J=U.date.toISOString().split("T")[0],ue=C[J]||[];return e.jsxs("div",{className:`flex flex-col rounded-lg border overflow-hidden 46 ${U.isToday?"border-brand-500/50 bg-brand-500/5":"border-[var(--color-border-subtle)] bg-[var(--color-bg-hover)]"}`,children:[e.jsxs("div",{className:`px-3 py-2 border-b text-center 47 ${U.isToday?"border-brand-500/30 bg-brand-500/10":"border-[var(--color-border-subtle)] bg-[var(--color-bg-hover)]"}`,children:[e.jsx("div",{className:`text-xs font-bold uppercase ${U.isToday?"text-brand-400":"text-[var(--color-text-secondary)]"}`,children:U.dayName}),e.jsx("div",{className:`text-sm font-medium ${U.isToday?"text-brand-300":"text-[var(--color-text-primary)]"}`,children:U.dateLabel})]}),e.jsxs("div",{className:"flex-1 p-2 space-y-2 overflow-y-auto",children:[ue.map(pe=>e.jsx(oc,{shift:pe,onEdit:()=>s(pe),onDelete:()=>i(pe.id),onAssign:()=>c(pe.id),selectMode:R,isSelected:I.has(pe.id),onToggleSelect:()=>ae(pe.id),overtimeRisk:me(pe.assigned_employee_id)},pe.id)),e.jsxs("button",{onClick:()=>o(U.date),className:`w-full p-2 border border-dashed border-[var(--color-border-default)] rounded-lg 48 text-[var(--color-text-muted)] hover:text-[var(--color-text-primary)] hover:border-white/40 49 transition-colors flex items-center justify-center gap-1 text-xs`,children:[e.jsx(ot,{className:"w-3 h-3"}),"Add Shift"]})]})]},J)})}),m&&e.jsx("div",{className:"absolute inset-0 bg-slate-900/50 flex items-center justify-center",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-[var(--color-border-default)] border-t-transparent"})})]})};function lc(l,t){const r=new Date(l),a=new Date,s=(r.getTime()-a.getTime())/(1e3*60*60);return{isWithinLockout:s>0&&s<=t,hoursUntilStart:Math.max(0,s)}}function Ja(l){return new Date(l).toLocaleString("en-US",{weekday:"short",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}function ic(l,t){const r=new Date(l);return`${((new Date(t).getTime()-r.getTime())/(1e3*60*60)).toFixed(1)} hours`}function cc(l){switch(l){case"draft":return"bg-gray-500/20 text-[var(--color-text-muted)] border-gray-500/40";case"published":return"bg-[var(--color-primary-subtle)] text-[var(--color-primary)] border-blue-500/40";case"open":return"bg-amber-500/20 text-amber-300 border-amber-500/40";case"assigned":return"bg-emerald-500/20 text-emerald-300 border-emerald-500/40";case"coverage_requested":return"bg-orange-500/20 text-orange-300 border-orange-500/40";case"covered":return"bg-teal-500/20 text-teal-300 border-teal-500/40";case"canceled":return"bg-red-500/20 text-red-300 border-red-500/40";default:return"bg-[var(--color-bg-hover)] text-[var(--color-text-primary)] border-[var(--color-border-default)]"}}function dc(l){return e.jsx(Ee,{className:"w-4 h-4 text-amber-400"})}function uc(l){var t,r,a,o,s,i;switch(l.type){case"cross_location_overlap_warn":return`Cross-location overlap (${(t=l.details)==null?void 0:t.overlap_minutes} min)`;case"insufficient_travel_time":return`Insufficient travel time (${(r=l.details)==null?void 0:r.gap_minutes} min, need ${(a=l.details)==null?void 0:a.required_minutes} min)`;case"outside_preferred_availability":return"Outside preferred availability";case"calendar_conflict_warn_only":return`Calendar conflict (${(o=l.details)==null?void 0:o.overlap_minutes} min overlap)`;case"overtime_risk":return`Overtime risk (${(s=l.details)==null?void 0:s.projected_hours}h projected, ${(i=l.details)==null?void 0:i.threshold}h threshold)`;default:return l.type}}function mc(l){return{assign:"Assigned",unassign:"Unassigned",offer_open:"Marked as open",pickup_request:"Pickup requested",pickup_approve:"Pickup approved",swap_request:"Swap requested",swap_accept:"Swap accepted",swap_approve:"Swap approved",coverage_request:"Coverage requested",coverage_assign:"Coverage resolved",cancel_shift:"Canceled",edit_published_shift:"Edited",publish:"Published",template_apply:"Created from template"}[l]||l}const xc=({shift:l,locations:t,positions:r,transactions:a,eligibilityResult:o,isOpen:s,isNew:i=!1,onClose:n,onSave:c,onPublish:d,onDelete:m,onAssign:u,onRequestCoverage:h,lockoutWindowHours:v=12,isEmployeeView:y=!1})=>{const[p,N]=x.useState("details"),[S,j]=x.useState(i),[I,$]=x.use
49State(""),[R,E]=x.useState(!1),O=l?lc(l.start_at_utc,v):null,D=y&&(O==null?void 0:O.isWithinLockout),[b,P]=x.useState({location_id:"",position_id:"",start_at_utc:"",end_at_utc:"",notes:""});if(x.useEffect(()=>{l&&P({location_id:l.location_id,position_id:l.position_id||"",start_at_utc:l.start_at_utc,end_at_utc:l.end_at_utc,notes:l.notes||""}),j(i),E(!1),$("")},[l,i]),!s||!l)return null;const W=()=>{c({location_id:b.location_id,position_id:b.position_id||null,start_at_utc:b.start_at_utc,end_at_utc:b.end_at_utc,notes:b.notes||null}),j(!1)},k=()=>{I.trim()&&(h(I),E(!1),$(""))},f=l.status==="draft"||l.status==="published",g=l.status==="draft",L=["published","open","coverage_requested"].includes(l.status),z=l.status==="assigned",X=l.status!=="canceled";return e.jsx("div",{className:"fixed inset-0 bg-slate-900/70 backdrop-blur-sm flex items-center justify-center z-50 p-4",children:e.jsxs("div",{className:"bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] rounded-xl w-full max-w-2xl max-h-[90vh] overflow-hidden shadow-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-[var(--color-border-subtle)]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(be,{className:"w-5 h-5 text-brand-400"}),e.jsx("h2",{className:"text-lg font-bold text-[var(--color-text-primary)]",children:i?"New Shift":"Shift Details"}),e.jsx("span",{className:`px-2 py-0.5 rounded text-xs font-bold uppercase border ${cc(l.status)}`,children:l.status}),(O==null?void 0:O.isWithinLockout)&&e.jsxs("span",{className:"px-2 py-0.5 rounded text-xs font-bold uppercase border bg-amber-500/20 text-amber-400 border-amber-500/40 flex items-center gap-1",children:[e.jsx(ve,{className:"w-3 h-3"}),"Lockout (",O.hoursUntilStart.toFixed(1),"h)"]})]}),e.jsx("button",{onClick:n,className:"p-2 hover:bg-[var(--color-bg-hover)] rounded-lg transition-colors",children:e.jsx(de,{className:"w-5 h-5 text-[var(--color-text-secondary)]"})})]}),e.jsxs("div",{className:"flex border-b border-[var(--color-border-subtle)]",children:[e.jsx("button",{onClick:()=>N("details"),className:`px-6 py-3 text-sm font-medium border-b-2 transition-colors 50 ${p==="details"?"border-brand-500 text-brand-400":"border-transparent text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"}`,children:"Details"}),e.jsxs("button",{onClick:()=>N("history"),className:`px-6 py-3 text-sm font-medium border-b-2 transition-colors 51 ${p==="history"?"border-brand-500 text-brand-400":"border-transparent text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"}`,children:["History (",a.length,")"]})]}),e.jsxs("div",{className:"p-6 overflow-y-auto max-h-[60vh]",children:[p==="details"&&e.jsxs("div",{className:"space-y-6",children:[D&&e.jsx("div",{className:"bg-amber-500/10 border border-amber-500/30 rounded-lg p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ve,{className:"w-5 h-5 text-amber-400 flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-amber-400",children:"Within Lockout Window"}),e.jsxs("p",{className:"text-xs text-amber-400/80 mt-0.5",children:["This shift starts in ",O==null?void 0:O.hoursUntilStart.toFixed(1)," hours. Self-service actions (coverage requests, swaps) are disabled within"," ",v," hours of shift start. Please contact your manager for any changes."]})]})]})}),o&&o.warnings.length>0&&e.jsxs("div",{className:"bg-amber-500/10 border border-amber-500/30 rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-amber-400 font-medium mb-2",children:[e.jsx(Ee,{className:"w-4 h-4"}),"Eligibility Warnings"]}),e.jsx("ul",{className:"space-y-1",children:o.warnings.map((C,Y)=>e.jsxs("li",{className:"flex items-center gap-2 text-sm text-amber-300/80",children:[dc(C.type),uc(C)]},Y))})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs font-bold text-[var(--color-text-secondary)] uppercase mb-1",children:[e.jsx(Je,{className:"w-3 h-3 inline mr-1"}),"Location"]}),S?e.jsx("select",{value:b.location_id,onChange:C=>P({...b,location_id:C.target.value}),className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-3 py-2 52 text-[var(--color-text-primary)] text-sm focus:outline-none focus:border-brand-500`,children:t.map(C=>e.jsx("option",{value:C.id,children:C.name},C.id))}):e.jsx("p",{className:"text-[var(--color-text-primary)]",children:l.location_name||"Unknown"})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs font-bold text-[var(--color-text-secondary)] uppercase mb-1",children:[e.jsx(st,{className:"w-3 h-3 inline mr-1"}),"Position"]}),S?e.jsxs("select",{value:b.position_id,onChange:C=>P({...b,position_id:C.target.value}),className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-3 py-2 53 text-[var(--color-text-primary)] text-sm focus:outline-none focus:border-brand-500`,children:[e.jsx("option",{value:"",children:"No specific position"}),r.map(C=>e.jsx("option",{value:C.id,children:C.name},C.id))]}):e.jsx("p",{className:"text-[var(--color-text-primary)]",children:l.position_name||"Any"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs font-bold text-[var(--color-text-secondary)] uppercase mb-1",children:[e.jsx(ve,{className:"w-3 h-3 inline mr-1"}),"Start Time"]}),S?e.jsx("input",{type:"datetime-local",value:b.start_at_utc.slice(0,16),onChange:C=>P({...b,start_at_utc:C.target.value+":00.000Z"}),className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-3 py-2 54 text-[var(--color-text-primary)] text-sm focus:outline-none focus:border-brand-500`}):e.jsx("p",{className:"text-[var(--color-text-primary)]",children:Ja(l.start_at_utc)})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs font-bold text-[var(--color-text-secondary)] uppercase mb-1",children:[e.jsx(ve,{className:"w-3 h-3 inline mr-1"}),"End Time"]}),S?e.jsx("input",{type:"datetime-local",value:b.end_at_utc.slice(0,16),onChange:C=>P({...b,end_at_utc:C.target.value+":00.000Z"}),className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-3 py-2 55 text-[var(--color-text-primary)] text-sm focus:outline-none focus:border-brand-500`}):e.jsx("p",{className:"text-[var(--color-text-primary)]",children:Ja(l.end_at_utc)})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-[var(--color-text-secondary)] uppercase mb-1",children:"Duration"}),e.jsx("p",{className:"text-[var(--color-text-primary)]",children:ic(l.start_at_utc,l.end_at_utc)})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs font-bold text-[var(--color-text-secondary)] uppercase mb-1",children:[e.jsx(Re,{className:"w-3 h-3 inline mr-1"}),"Assigned Employee"]}),l.assigned_employee_name?e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-[var(--color-text-primary)]",children:l.assigned_employee_name}),z&&!D&&e.jsx("button",{onClick:()=>E(!0),className:"text-sm text-amber-400 hover:text-amber-300",children:"Request Coverage"}),z&&D&&e.jsx("span",{className:"text-xs text-[var(--color-text-muted)] italic",children:"Coverage requests disabled (lockout)"})]}):e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-[var(--color-text-secondary)] italic",children:l.status==="open"?"Open for pickup":"Not assigned"}),L&&e.jsxs("button",{onClick:u,className:"flex items-center gap-1 text-sm text-brand-400 hover:text-brand-300",children:[e.jsx(ft,{className:"w-4 h-4"}),"Assign Employee"]})]})]}),R&&e.jsxs("div",{className:"bg-amber-500/10 border border-amber-500/30 rounded-lg p-4",children:[e.jsx("label",{className:"block text-sm font-medium text-amber-300 mb-2",children:"Reason for coverage request"}),e.jsx("textarea",{value:I,onChange:C=>$(C.target.value),placeholder:"e.g., Sick, family emergency...",className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-3 py-2 56 text-[var(--color-text-primary)] text-sm placeholder-white/40 focus:outline-none focus:border-amber-500 57 resize-none h-20`}),e.jsxs("div",{className:"flex justify-end gap-2 mt-2",children:[e.jsx("button",{onClick:()=>E(!1),className:"px-3 py-1.5 text-sm text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]",children:"Cancel"}),e.jsx("button",{onClick:k,disabled:!I.trim(),className:`px-3 py-1.5 text-sm bg-amber-500 hover:bg-amber-400 text-[var(--color-text-primary)] 58 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed`,children:"Submit Request"})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs font-bold text-[var(--color-text-secondary)] uppercase mb-1",children:[e.jsx(et,{className:"w-3 h-3 inline mr-1"}),"Notes"]}),S?e.jsx("textarea",{value:b.notes,onChange:C=>P({...b,notes:C.target.value}),placeholder:"Add notes about this shift...",className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-3 py-2 59 text-[var(--color-text-primary)] text-sm placeholder-white/40 focus:outline-none focus:border-brand-500 60 resize-none h-20`}):e.jsx("p",{className:"text-[var(--color-text-primary)]",children:l.notes||"No notes"})]})]}),p==="history"&&e.jsx("div",{className:"space-y-3",children:a.length===0?e.jsx("p",{className:"text-[var(--color-text-secondary)] italic text-center py-8",children:"No history yet"}):a.map(C=>e.jsxs("div",{className:"flex items-start gap-3 p-3 bg-[var(--color-bg-hover)] rounded-lg",children:[e.jsx(mn,{className:"w-4 h-4 text-[var(--color-text-muted)] mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium text-[var(--color-text-primary)]",children:mc(C.type)}),e.jsx("span",{className:"text-xs text-[var(--color-text-muted)]",children:new Date(C.created_at).toLocaleStr
60ing()})]}),C.from_employee_id&&C.to_employee_id&&e.jsxs("div",{className:"flex items-center gap-2 mt-1 text-xs text-[var(--color-text-secondary)]",children:[e.jsx("span",{children:C.from_employee_id}),e.jsx(xn,{className:"w-3 h-3"}),e.jsx("span",{children:C.to_employee_id})]}),C.reason&&e.jsx("p",{className:"text-xs text-[var(--color-text-secondary)] mt-1",children:C.reason})]})]},C.id))})]}),e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-t border-[var(--color-border-subtle)] bg-[var(--color-bg-hover)]",children:[e.jsx("div",{children:X&&e.jsxs("button",{onClick:m,className:`flex items-center gap-2 px-3 py-2 text-red-400 hover:text-red-300 61 hover:bg-red-500/10 rounded-lg transition-colors text-sm`,children:[e.jsx(qe,{className:"w-4 h-4"}),"Delete"]})}),e.jsx("div",{className:"flex items-center gap-2",children:S?e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>j(!1),className:"px-4 py-2 text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] text-sm",children:"Cancel"}),e.jsxs("button",{onClick:W,className:`flex items-center gap-2 px-4 py-2 bg-brand-600 hover:bg-brand-500 62 text-[var(--color-text-primary)] rounded-lg text-sm font-medium`,children:[e.jsx(sa,{className:"w-4 h-4"}),"Save"]})]}):e.jsxs(e.Fragment,{children:[f&&e.jsx("button",{onClick:()=>j(!0),className:"px-4 py-2 text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] text-sm",children:"Edit"}),g&&e.jsxs("button",{onClick:d,className:`flex items-center gap-2 px-4 py-2 bg-brand-600 hover:bg-brand-500 63 text-[var(--color-text-primary)] rounded-lg text-sm font-medium`,children:[e.jsx(Nr,{className:"w-4 h-4"}),"Publish"]})]})})]})]})})};function hc(l,t){const r=new Date(l),a=new Date,s=(r.getTime()-a.getTime())/(1e3*60*60);return{isWithinLockout:s>0&&s<=t,hoursUntilStart:Math.max(0,s)}}function Xa(l){return new Date(l).toLocaleString("en-US",{weekday:"short",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}function pc(l){var t,r,a,o,s,i;switch(l.type){case"cross_location_overlap_warn":return`Cross-location overlap (${((t=l.details)==null?void 0:t.overlap_minutes)||0} min)`;case"insufficient_travel_time":return`Travel time: ${((r=l.details)==null?void 0:r.gap_minutes)||0}min gap, need ${((a=l.details)==null?void 0:a.required_minutes)||0}min`;case"outside_preferred_availability":return"Outside preferred availability";case"calendar_conflict_warn_only":return`Calendar conflict (${((o=l.details)==null?void 0:o.overlap_minutes)||0} min overlap)`;case"overtime_risk":return`Overtime risk: ${((s=l.details)==null?void 0:s.projected_hours)||0}h (>${((i=l.details)==null?void 0:i.threshold)||40}h)`;default:return l.type}}function es(l){switch(l){case"employee_not_active":return"Employee is not active";case"no_active_assignment":return"No active assignment for this location/position";case"approved_time_off_overlap":return"Has approved time off during this shift";case"cannot_work_availability":return"Marked as cannot work during these hours";case"cross_location_overlap":return"Has overlapping shift at another location";default:return l}}const vc=({isOpen:l,shift:t,employees:r,eligibilityResults:a,onClose:o,onAssign:s,loading:i=!1,lockoutWindowHours:n=12})=>{var f;const[c,d]=x.useState(""),[m,u]=x.useState(null),[h,v]=x.useState(!1),[y,p]=x.useState(""),[N,S]=x.useState(null),[j,I]=x.useState(!0),[$,R]=x.useState(!1),E=t?hc(t.start_at_utc,n):null,O=x.useMemo(()=>{let g=r.filter(L=>{if(L.status!=="Active")return!1;if(c){const z=c.toLowerCase(),X=`${L.firstName} ${L.lastName}`.toLowerCase(),C=(L.email||"").toLowerCase(),Y=(L.role||"").toLowerCase();if(!X.includes(z)&&!C.includes(z)&&!Y.includes(z))return!1}return!0});return a&&(g.sort((L,z)=>{var re,me;const X=a.get(L.id),C=a.get(z.id);if((X==null?void 0:X.eligible)!==(C==null?void 0:C.eligible))return X!=null&&X.eligible?-1:1;const Y=((re=X==null?void 0:X.warnings)==null?void 0:re.length)||0,F=((me=C==null?void 0:C.warnings)==null?void 0:me.length)||0;return Y!==F?Y-F:`${L.lastName} ${L.firstName}`.localeCompare(`${z.lastName} ${z.firstName}`)}),j&&(g=g.filter(L=>{const z=a.get(L.id);return(z==null?void 0:z.eligible)!==!1}))),g},[r,c,a,j]),D=g=>{const L=a==null?void 0:a.get(g);L&&!L.eligible?(u(g),v(!0)):(u(g),v(!1))},b=()=>{if(!m)return;const g=a==null?void 0:a.get(m);g&&!g.eligible&&!y.trim()||(s(m,y.trim()||void 0),P())},P=()=>{d(""),u(null),v(!1),p(""),S(null),R(!1),o()};if(!l||!t)return null;const W=r.find(g=>g.id===m),k=m?a==null?void 0:a.get(m):null;return e.jsx("div",{className:"fixed inset-0 bg-slate-900/70 backdrop-blur-sm flex items-center justify-center z-50 p-4",children:e.jsxs("div",{className:"bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] rounded-xl w-full max-w-xl max-h-[90vh] overflow-hidden shadow-2xl flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-[var(--color-border-subtle)]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ft,{className:"w-5 h-5 text-brand-400"}),e.jsx("h2",{className:"text-lg font-bold text-[var(--color-text-primary)]",children:"Assign Employee"})]}),e.jsx("button",{onClick:P,className:"p-2 hover:bg-[var(--color-bg-hover)] rounded-lg transition-colors",children:e.jsx(de,{className:"w-5 h-5 text-[var(--color-text-secondary)]"})})]}),e.jsxs("div",{className:"px-6 py-3 bg-[var(--color-bg-hover)] border-b border-[var(--color-border-subtle)]",children:[e.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-1 text-[var(--color-text-primary)]",children:[e.jsx(ve,{className:"w-4 h-4"}),e.jsx("span",{children:Xa(t.start_at_utc)}),e.jsx("span",{className:"text-[var(--color-text-muted)]",children:"-"}),e.jsx("span",{children:Xa(t.end_at_utc)})]}),t.location_name&&e.jsxs("div",{className:"flex items-center gap-1 text-[var(--color-text-primary)]",children:[e.jsx(Je,{className:"w-4 h-4"}),e.jsx("span",{children:t.location_name})]})]}),t.position_name&&e.jsxs("div",{className:"text-xs text-[var(--color-text-secondary)] mt-1",children:["Position: ",t.position_name]})]}),(E==null?void 0:E.isWithinLockout)&&e.jsx("div",{className:"mx-6 mt-3 p-3 bg-amber-500/20 border border-amber-500/30 rounded-lg",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ee,{className:"w-5 h-5 text-amber-400 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium text-amber-400",children:"Within Lockout Window"}),e.jsxs("p",{className:"text-xs text-amber-400/80 mt-0.5",children:["This shift starts in ",E.hoursUntilStart.toFixed(1)," hours. Assignment changes within ",n," hours of shift start require acknowledgement."]}),e.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:$,onChange:g=>R(g.target.checked),className:`rounded border-amber-500/50 bg-amber-500/10 text-amber-500 64 focus:ring-amber-500/30`}),e.jsx("span",{className:"text-xs text-amber-400",children:"I acknowledge this is a last-minute assignment change"})]})]})]})}),e.jsx("div",{className:"px-6 py-3 border-b border-[var(--color-border-subtle)]",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-[var(--color-text-muted)]"}),e.jsx("input",{type:"text",placeholder:"Search by name, email, or role...",value:c,onChange:g=>d(g.target.value),className:`w-full pl-10 pr-4 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg 65 text-[var(--color-text-primary)] placeholder-white/40 focus:outline-none focus:border-brand-500/50 66 focus:ring-1 focus:ring-brand-500/30 text-sm`})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm text-[var(--color-text-primary)] cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:j,onChange:g=>I(g.target.checked),className:"rounded border-[var(--color-border-default)] bg-[var(--color-bg-hover)] text-brand-500 focus:ring-brand-500/30"}),"Eligible only"]})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto px-6 py-3",children:i?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-[var(--color-border-default)] border-t-transparent"})}):O.length===0?e.jsxs("div",{className:"text-center py-12 text-[var(--color-text-secondary)]",children:[e.jsx(ft,{className:"w-10 h-10 mx-auto mb-3 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No employees found"}),e.jsx("p",{className:"text-sm mt-1",children:j?"Try showing all employees or adju
66sting your search":"Try adjusting your search criteria"})]}):e.jsx("div",{className:"space-y-2",children:O.map(g=>{const L=a==null?void 0:a.get(g.id),z=m===g.id,X=N===g.id,C=L&&L.warnings.length>0,Y=L&&!L.eligible;return e.jsxs("div",{className:`rounded-lg border transition-colors cursor-pointer 67 ${z?"bg-brand-500/20 border-brand-500/40":Y?"bg-red-500/5 border-red-500/20 hover:bg-red-500/10":C?"bg-amber-500/5 border-amber-500/20 hover:bg-amber-500/10":"bg-[var(--color-bg-hover)] border-[var(--color-border-subtle)] hover:bg-[var(--color-bg-hover)]"}`,children:[e.jsxs("div",{onClick:()=>D(g.id),className:"flex items-center gap-3 p-3",children:[e.jsx("div",{className:`w-5 h-5 rounded-full border-2 flex items-center justify-center flex-shrink-0 68 ${z?"border-brand-500 bg-brand-500":"border-[var(--color-border-strong)]"}`,children:z&&e.jsx(Te,{className:"w-3 h-3 text-[var(--color-text-primary)]"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-medium text-[var(--color-text-primary)] truncate",children:[g.firstName," ",g.lastName]}),Y&&e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-bold uppercase bg-red-500/20 text-red-400",children:"Blocked"}),C&&!Y&&e.jsxs("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-bold uppercase bg-amber-500/20 text-amber-400",children:[L.warnings.length," Warning",L.warnings.length!==1?"s":""]})]}),e.jsxs("div",{className:"text-xs text-[var(--color-text-secondary)] truncate",children:[g.role," ",g.department?`⢠${g.department}`:""]})]}),(Y||C)&&e.jsx("button",{onClick:F=>{F.stopPropagation(),S(X?null:g.id)},className:"p-1 hover:bg-[var(--color-bg-hover)] rounded",children:X?e.jsx(Rr,{className:"w-4 h-4 text-[var(--color-text-secondary)]"}):e.jsx(vt,{className:"w-4 h-4 text-[var(--color-text-secondary)]"})})]}),X&&L&&e.jsxs("div",{className:"px-3 pb-3 pl-11 space-y-2",children:[Y&&L.block&&e.jsxs("div",{className:"flex items-start gap-2 text-sm text-red-400",children:[e.jsx(de,{className:"w-4 h-4 flex-shrink-0 mt-0.5"}),e.jsx("span",{children:es(L.block.reason)})]}),L.warnings.map((F,re)=>e.jsxs("div",{className:"flex items-start gap-2 text-sm text-amber-400",children:[e.jsx(Ee,{className:"w-4 h-4 flex-shrink-0 mt-0.5"}),e.jsx("span",{children:pc(F)})]},re))]})]},g.id)})})}),h&&W&&k&&!k.eligible&&e.jsxs("div",{className:"px-6 py-4 border-t border-[var(--color-border-subtle)] bg-red-500/5",children:[e.jsxs("div",{className:"flex items-start gap-2 mb-3",children:[e.jsx(Ee,{className:"w-5 h-5 text-red-400 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium text-red-400",children:[W.firstName," ",W.lastName," is not eligible"]}),e.jsx("p",{className:"text-sm text-red-400/70",children:es(((f=k.block)==null?void 0:f.reason)||"unknown")})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-[var(--color-text-primary)] mb-1",children:"Override reason (required)"}),e.jsx("textarea",{value:y,onChange:g=>p(g.target.value),placeholder:"Enter reason for overriding eligibility check...",className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg px-3 py-2 69 text-[var(--color-text-primary)] text-sm placeholder-white/40 focus:outline-none focus:border-red-500/50 70 resize-none h-16`})]})]}),e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-t border-[var(--color-border-subtle)] bg-[var(--color-bg-hover)]",children:[e.jsxs("div",{className:"text-sm text-[var(--color-text-secondary)]",children:[O.length," employee",O.length!==1?"s":""," shown"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:P,className:"px-4 py-2 text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] text-sm",children:"Cancel"}),e.jsxs("button",{onClick:b,disabled:!m||k&&!k.eligible&&!y.trim()||(E==null?void 0:E.isWithinLockout)&&!$,className:`flex items-center gap-2 px-4 py-2 bg-brand-600 hover:bg-brand-500 71 text-[var(--color-text-primary)] rounded-lg text-sm font-medium transition-colors 72 disabled:opacity-50 disabled:cursor-not-allowed`,children:[e.jsx(ft,{className:"w-4 h-4"}),E!=null&&E.isWithinLockout?"Assign (Lockout Override)":"Assign"]})]})]})]})})},ts=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],pr={day_offset:0,start_time:"09:00",end_time:"17:00",position_id:"",headcount:1,notes:"",default_employee_id:""};function rs(l){const[t,r]=l.split(":").map(Number),a=t>=12?"PM":"AM";return`${t%12||12}:${String(r).padStart(2,"0")} ${a}`}function fc(l){switch(l){case"draft":return"bg-gray-500/20 text-[var(--color-text-muted)] border-gray-500/40";case"active":return"bg-emerald-500/20 text-emerald-300 border-emerald-500/40";case"archived":return"bg-red-500/20 text-red-300 border-red-500/40";default:return"bg-[var(--color-bg-hover)] text-[var(--color-text-primary)] border-[var(--color-border-default)]"}}const gc=({template:l,locations:t,positions:r,employees:a,isNew:o=!1,onSave:s,onAddShift:i,onUpdateShift:n,onDeleteShift:c,onActivate:d,onArchive:m,onDuplicate:u,onClose:h,loading:v=!1})=>{var _e,Ue;const[y,p]=x.useState((l==null?void 0:l.name)||""),[N,S]=x.useState((l==null?void 0:l.location_id)||((_e=t[0])==null?void 0:_e.id)||""),[j,I]=x.useState(o),[$,R]=x.useState(!1),[E,O]=x.use
72State(null),[D,b]=x.useState(null),[P,W]=x.useState(pr);x.useEffect(()=>{l&&(p(l.name),S(l.location_id))},[l]);const k=x.useMemo(()=>{const q={0:[],1:[],2:[],3:[],4:[],5:[],6:[]};return((l==null?void 0:l.shifts)||[]).forEach(ne=>{q[ne.day_offset].push(ne)}),Object.values(q).forEach(ne=>{ne.sort((ae,Ie)=>ae.start_time.localeCompare(Ie.start_time))}),q},[l==null?void 0:l.shifts]),f=((Ue=l==null?void 0:l.shifts)==null?void 0:Ue.length)||0,g=((l==null?void 0:l.shifts)||[]).reduce((q,ne)=>q+(ne.headcount||1),0),L=()=>{y.trim()&&(s({name:y.trim(),location_id:N}),I(!1))},z=q=>{O(q),W({...pr,day_offset:q}),b(null),R(!0)},X=q=>{O(q.day_offset),W({day_offset:q.day_offset,start_time:q.start_time,end_time:q.end_time,position_id:q.position_id||"",headcount:q.headcount||1,notes:q.notes||"",default_employee_id:q.default_employee_id||""}),b(q.id),R(!0)},C=()=>{D?n(D,{day_offset:P.day_offset,start_time:P.start_time,end_time:P.end_time,position_id:P.position_id||null,headcount:P.headcount,notes:P.notes||null,default_employee_id:P.default_employee_id||null}):i({day_offset:P.day_offset,start_time:P.start_time,end_time:P.end_time,position_id:P.position_id||null,headcount:P.headcount,notes:P.notes||null,default_employee_id:P.default_employee_id||null}),R(!1),b(null),W(pr)},Y=q=>{confirm("Delete this shift from the template?")&&c(q)},F=(l==null?void 0:l.status)==="draft"&&f>0,re=(l==null?void 0:l.status)==="active",me=(l==null?void 0:l.status)!=="archived";return e.jsx("div",{className:"fixed inset-0 bg-slate-900/70 backdrop-blur-sm flex items-center justify-center z-50 p-4",children:e.jsxs("div",{className:"bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] rounded-xl w-full max-w-4xl max-h-[90vh] overflow-hidden shadow-2xl flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-[var(--color-border-subtle)]",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[e.jsx(be,{className:"w-5 h-5 text-brand-400"}),j?e.jsxs("div",{className:"flex items-center gap-2 flex-1 max-w-md",children:[e.jsx("input",{type:"text",value:y,onChange:q=>p(q.target.value),placeholder:"Template name...",className:`flex-1 bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-3 py-1.5 73 text-[var(--color-text-primary)] text-sm focus:outline-none focus:border-brand-500`,autoFocus:!0}),e.jsx("button",{onClick:L,disabled:!y.trim(),className:"p-1.5 bg-brand-600 hover:bg-brand-500 rounded-lg disabled:opacity-50",children:e.jsx(Te,{className:"w-4 h-4 text-[var(--color-text-primary)]"})})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h2",{className:"text-lg font-bold text-[var(--color-text-primary)]",children:(l==null?void 0:l.name)||"New Template"}),me&&e.jsx("button",{onClick:()=>I(!0),className:"p-1 hover:bg-[var(--color-bg-hover)] rounded",children:e.jsx(qt,{className:"w-4 h-4 text-[var(--color-text-secondary)]"})})]}),l&&e.jsx("span",{className:`px-2 py-0.5 rounded text-xs font-bold uppercase border ${fc(l.status)}`,children:l.status})]}),e.jsx("button",{onClick:h,className:"p-2 hover:bg-[var(--color-bg-hover)] rounded-lg transition-colors",children:e.jsx(de,{className:"w-5 h-5 text-[var(--color-text-secondary)]"})})]}),e.jsxs("div",{className:"px-6 py-3 bg-[var(--color-bg-hover)] border-b border-[var(--color-border-subtle)] flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("label",{className:"text-sm text-[var(--color-text-primary)]",children:"Location:"}),e.jsx("select",{value:N,onChange:q=>{S(q.target.value),o||s({location_id:q.target.value})},disabled:!me||!o,className:`bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-3 py-1.5 74 text-[var(--color-text-primary)] text-sm focus:outline-none focus:border-brand-500 75 disabled:opacity-50 disabled:cursor-not-allowed`,children:t.map(q=>e.jsx("option",{value:q.id,children:q.name},q.id))})]}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-[var(--color-text-secondary)]",children:[e.jsxs("span",{children:[f," shift",f!==1?"s":""]}),e.jsxs("span",{children:[g," total headcount"]})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden flex",children:e.jsx("div",{className:"flex-1 grid grid-cols-7 divide-x divide-[var(--color-border-subtle)] overflow-hidden",children:ts.map((q,ne)=>e.jsxs("div",{className:"flex flex-col overflow-hidden",children:[e.jsx("div",{className:"px-2 py-2 bg-[var(--color-bg-hover)] border-b border-[var(--color-border-subtle)] text-center",children:e.jsx("div",{className:"text-xs font-bold uppercase text-[var(--color-text-primary)]",children:q})}),e.jsxs("div",{className:"flex-1 p-2 space-y-2 overflow-y-auto",children:[k[ne].map(ae=>{var Ie;return e.jsxs("div",{className:`p-2 bg-[var(--color-bg-hover)] rounded-lg border border-[var(--color-border-default)] group 76 hover:border-brand-500/40 cursor-pointer transition-colors`,onClick:()=>me&&X(ae),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-1 text-xs font-medium text-[var(--color-text-primary)]",children:[e.jsx(ve,{className:"w-3 h-3"}),e.jsx("span",{children:rs(ae.start_time)})]}),me&&e.jsx("button",{onClick:$e=>{$e.stopPropagation(),Y(ae.id)},className:"p-0.5 opacity-0 group-hover:opacity-100 hover:bg-red-500/20 rounded",children:e.jsx(qe,{className:"w-3 h-3 text-red-400"})})]}),e.jsxs("div",{className:"text-[10px] text-[var(--color-text-secondary)] mt-1",children:["to ",rs(ae.end_time)]}),ae.position_id&&e.jsx("div",{className:"text-[10px] text-brand-400 mt-1 truncate",children:(Ie=r.find($e=>$e.id===ae.position_id))==null?void 0:Ie.name}),ae.default_employee_id&&e.jsxs("div",{className:"flex items-center gap-1 text-[10px] text-emerald-400 mt-1 truncate",children:[e.jsx(Re,{className:"w-2.5 h-2.5"}),(()=>{const $e=a.find(Ke=>Ke.id===ae.default_employee_id);return $e?`${$e.firstName} ${$e.lastName}`:"Unknown"})()]}),ae.headcount>1&&e.jsxs("div",{className:"text-[10px] text-[var(--color-text-secondary)] mt-0.5",children:["x",ae.headcount," spots"]})]},ae.id)}),me&&e.jsxs("button",{onClick:()=>z(ne),className:`w-full p-2 border border-dashed border-[var(--color-border-default)] rounded-lg 77 text-[var(--color-text-muted)] hover:text-[var(--color-text-primary)] hover:border-white/40 78 transition-colors flex items-center justify-center gap-1 text-xs`,children:[e.jsx(ot,{className:"w-3 h-3"}),"Add"]})]})]},q))})}),$&&e.jsxs("div",{className:"border-t border-[var(--color-border-subtle)] bg-[var(--color-bg-hover)] px-6 py-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("h3",{className:"font-bold text-[var(--color-text-primary)]",children:[D?"Edit Shift":"Add Shift"," - ",ts[P.day_offset]]}),e.jsx("button",{onClick:()=>{R(!1),b(null),W(pr)},className:"p-1 hover:bg-[var(--color-bg-hover)] rounded",children:e.jsx(de,{className:"w-4 h-4 text-[var(--color-text-secondary)]"})})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-6 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-[var(--color-text-secondary)] mb-1",children:"Start Time"}),e.jsx("input",{type:"time",value:P.start_time,onChange:q=>W({...P,start_time:q.target.value}),className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-3 py-2 79 text-[var(--color-text-primary)] text-sm focus:outline-none focus:border-brand-500`})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-[var(--color-text-secondary)] mb-1",children:"End Time"}),e.jsx("input",{type:"time",value:P.end_time,onChange:q=>W({...P,end_time:q.target.value}),className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-3 py-2 80 text-[var(--color-text-primary)] text-sm focus:outline-none focus:border-brand-500`})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-[var(--color-text-secondary)] mb-1",children:"Position"}),e.jsxs("select",{value:P.position_id,onChange:q=>W({...P,position_id:q.target.value}),className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-3 py-2 81 text-[var(--color-text-primary)] text-sm focus:outline-none focus:border-brand-500`,children:[e.jsx("option",{value:"",children:"Any position"}),r.map(q=>e.jsx("option",{value:q.id,children:q.name},q.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-[var(--color-text-secondary)] mb-1",children:"Default Assign"}),e.jsxs("select",{value:P.default_employee_id,onChange:q=>W({...P,default_employee_id:q.target.value}),className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-3 py-2 82 text-[var(--color-text-primary)] text-sm focus:outline-none focus:border-brand-500`,children:[e.jsx("option",{value:"",children:"Unassigned"}),a.filter(q=>q.status==="Active"||!q.status).map(q=>e.jsxs("option",{value:q.id,children:[q.firstName," ",q.lastName]},q.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-[var(--color-text-secondary)] mb-1",children:"Headcount"}),e.jsx("input",{type:"number",min:"1",max:"10",value:P.headcount,onChange:q=>W({...P,headcount:parseInt(q.target.value)||1}),className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-3 py-2 83 text-[var(--color-text-primary)] text-sm focus:outline-none focus:border-brand-500`})]}),e.jsx("div",{className:"flex items-end gap-2",children:e.jsxs("button",{onClick:C,className:`flex-1 flex items-center justify-center gap-2 px-4 py-2 84 bg-brand-600 hover:bg-brand-500 text-[var(--color-text-primary)] rounded-lg text-sm font-medium`,children:[e.jsx(Te,{className:"w-4 h-4"}),D?"Update":"Add"]})})]}),e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-xs font-medium text-[var(--color-text-secondary)] mb-1",children:"Notes (optional)"}),e.jsx("input",{type:"text",value:P.notes,onChange:q=>W({...P,notes:q.target.value}),placeholder:"e.g., Requires food handler certification...",className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-3 py-2 85 text-[var(--color-text-primary)] text-sm placeholder-white/40 focus:outline-none focus:border-brand-500`})]})]}),e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-t border-[var(--color-border-subtle)] bg-[var(--color-bg-hover)]",children:[e.jsxs("div",{className:"flex gap-2",children:[l&&!o&&e.jsxs("button",{onClick:u,className:`flex items-center gap-2 px-3 py-2 text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] 86 hover:bg-[var(--color-bg-hover)] rounded-lg text-sm`,children:[e.jsx(tr,{className:"w-4 h-4"}),"Duplicate"]}),re&&e.jsxs("button",{onClick:m,className:`flex items-center gap-2 px-3 py-2 text-red-400 hover:text-red-300 87 hover:bg-red-500/10 rounded-lg text-sm`,children:[e.jsx(qe,{className:"w-4 h-4"}),"Archive"]})]}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("span",{className:"text-xs text-[var(--color-text-muted)] mr-2",children:"Changes auto-saved"}),F&&e.jsxs("button",{onClick:d,className:`flex items-center gap-2 px-4 py-2 bg-emerald-600 hover:bg-emerald-500 88 text-[var(--color-text-primary)] rounded-lg text-sm font-medium`,children:[e.jsx(Rt,{className:"w-4 h-4"}),"Activate Template"]}),(l==null?void 0:l.status)==="active"&&e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 text-emerald-400",children:[e.jsx(Rt,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Active"})]}),e.jsxs("button",{onClick:h,className:`flex items-center gap-2 px-4 py-2 bg-brand-600 hover:bg-brand-500 89 text-[var(--color-text-primary)] rounded-lg text-sm font-medium`,children:[e.jsx(Te,{className:"w-4 h-4"}),"Done"]})]})]}),v&&e.jsx("div",{className:"absolute inset-0 bg-slate-900/50 flex items-center justify-center",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-[var(--color-border-default)] border-t-transparent"})})]})})},bc=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function as(l){const t=new Date(l),r=t.getDay(),a=t.getDate()-r;return t.setDate(a),t.setHours(0,0,0,0),t}function ss(l){const t=new Date(l);return t.setDate(t.getDate()+6),`${l.toLocaleDateString("en-US",{month:"short",day:"numeric"})} - ${t.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}`}function yc(l){const[t,r]=l.split(":").map(Number),a=t>=12?"PM":"AM";return`${t%12||12}:${String(r).padStart(2,"0")} ${a}`}const wc=({isOpen:l,templates:t,locations:r,selectedLocationId:a,onClose:o,onApply:s,loading:i=!1})=>{var k;const[n,c]=x.useState(null),[d,m]=x.useState(()=>{const f=new Date;return f.setDate(f.getDate()+7),as(f)}),[u,h]=x.useState(1),[v,y]=x.useState(!0),[p,N]=x.useState(!1),S=x.useMemo(()=>t.filter(f=>!(f.status!=="active"||a&&f.location_id!==a)),[t,a]),j=S.find(f=>f.id===n),I=x.useMemo(()=>
89{if(!j)return{};const f={0:[],1:[],2:[],3:[],4:[],5:[],6:[]};return j.shifts.forEach(g=>{f[g.day_offset].push(g)}),Object.values(f).forEach(g=>{g.sort((L,z)=>L.start_time.localeCompare(z.start_time))}),f},[j]),$=((k=j==null?void 0:j.shifts)==null?void 0:k.length)||0,R=((j==null?void 0:j.shifts)||[]).reduce((f,g)=>f+(g.headcount||1),0),E=()=>{const f=new Date(d);f.setDate(f.getDate()-7),m(f)},O=()=>{const f=new Date(d);f.setDate(f.getDate()+7),m(f)},D=()=>{n&&s(n,d.toISOString().split("T")[0],v,u)},b=x.useMemo(()=>{if(u<=1)return d;const f=new Date(d);return f.setDate(f.getDate()+(u-1)*7),f},[d,u]),P=()=>{if(u===1)return ss(d);const f=new Date(b);return f.setDate(f.getDate()+6),`${d.toLocaleDateString("en-US",{month:"short",day:"numeric"})} - ${f.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})} (${u} weeks)`},W=()=>{c(null),N(!1),o()};return l?e.jsx("div",{className:"fixed inset-0 bg-slate-900/70 backdrop-blur-sm flex items-center justify-center z-50 p-4",children:e.jsxs("div",{className:"bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] rounded-xl w-full max-w-2xl max-h-[90vh] overflow-hidden shadow-2xl flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-[var(--color-border-subtle)]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(tr,{className:"w-5 h-5 text-brand-400"}),e.jsx("h2",{className:"text-lg font-bold text-[var(--color-text-primary)]",children:"Apply Template"})]}),e.jsx("button",{onClick:W,className:"p-2 hover:bg-[var(--color-bg-hover)] rounded-lg transition-colors",children:e.jsx(de,{className:"w-5 h-5 text-[var(--color-text-secondary)]"})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-6",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-[var(--color-text-primary)] mb-3",children:"1. Select a Template"}),S.length===0?e.jsxs("div",{className:"text-center py-8 bg-[var(--color-bg-hover)] rounded-lg border border-[var(--color-border-subtle)]",children:[e.jsx(et,{className:"w-10 h-10 mx-auto mb-3 text-[var(--color-text-muted)]"}),e.jsx("p",{className:"text-[var(--color-text-secondary)]",children:"No active templates found"}),e.jsx("p",{className:"text-sm text-[var(--color-text-muted)] mt-1",children:a?"Try selecting a different location or create a template first":"Create a template first to apply it to schedules"})]}):e.jsx("div",{className:"space-y-2",children:S.map(f=>{var X;const g=n===f.id,L=r.find(C=>C.id===f.location_id),z=((X=f.shifts)==null?void 0:X.length)||0;return e.jsxs("div",{onClick:()=>{c(f.id),N(!1)},className:`p-4 rounded-lg border cursor-pointer transition-colors 90 ${g?"bg-brand-500/20 border-brand-500/40":"bg-[var(--color-bg-hover)] border-[var(--color-border-subtle)] hover:bg-[var(--color-bg-hover)]"}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`w-5 h-5 rounded-full border-2 flex items-center justify-center 91 ${g?"border-brand-500 bg-brand-500":"border-[var(--color-border-strong)]"}`,children:g&&e.jsx(Te,{className:"w-3 h-3 text-[var(--color-text-primary)]"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-[var(--color-text-primary)]",children:f.name}),e.jsxs("div",{className:"text-xs text-[var(--color-text-secondary)]",children:[L==null?void 0:L.name," ⢠",z," shift",z!==1?"s":""]})]})]}),g&&e.jsx("button",{onClick:C=>{C.stopPropagation(),N(!p)},className:"text-xs text-brand-400 hover:text-brand-300",children:p?"Hide":"Preview"})]}),g&&p&&e.jsx("div",{className:"mt-4 pt-4 border-t border-[var(--color-border-subtle)]",children:e.jsx("div",{className:"grid grid-cols-7 gap-1 text-xs",children:bc.map((C,Y)=>{const F=I[Y]||[];return e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-bold text-[var(--color-text-primary)] mb-1",children:C}),e.jsx("div",{className:"space-y-1",children:F.length===0?e.jsx("div",{className:"text-[var(--color-text-muted)]",children:"â"}):F.map(re=>e.jsx("div",{className:"p-1 bg-[var(--color-bg-hover)] rounded text-[10px] text-[var(--color-text-primary)]",children:yc(re.start_time)}
91,re.id))})]},C)})})})]},f.id)})})]}),n&&e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-[var(--color-text-primary)] mb-3",children:"2. Select Date Range"}),e.jsxs("div",{className:"p-4 bg-[var(--color-bg-hover)] rounded-lg border border-[var(--color-border-subtle)] space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-[var(--color-text-secondary)] mb-2",children:"Starting Week"}),e.jsxs("div",{className:"flex items-center justify-center gap-4",children:[e.jsx("button",{onClick:E,className:"p-2 hover:bg-[var(--color-bg-hover)] rounded-lg transition-colors",children:e.jsx(la,{className:"w-5 h-5 text-[var(--color-text-primary)]"})}),e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 bg-[var(--color-bg-hover)] rounded-lg min-w-[200px] justify-center",children:[e.jsx(be,{className:"w-4 h-4 text-brand-400"}),e.jsx("span",{className:"font-medium text-[var(--color-text-primary)]",children:ss(d)})]}),e.jsx("button",{onClick:O,className:"p-2 hover:bg-[var(--color-bg-hover)] rounded-lg transition-colors",children:e.jsx(nt,{className:"w-5 h-5 text-[var(--color-text-primary)]"})})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-[var(--color-text-secondary)] mb-2",children:"Number of Weeks to Apply"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex items-center gap-2",children:[1,2,4,8,12].map(f=>e.jsx("button",{onClick:()=>h(f),className:`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors 92 ${u===f?"bg-brand-500 text-[var(--color-text-primary)]":"bg-[var(--color-bg-hover)] text-[var(--color-text-primary)] hover:bg-[var(--color-bg-active)]"}`,children:f},f))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",min:"1",max:"52",value:u,onChange:f=>h(Math.max(1,Math.min(52,parseInt(f.target.value)||1))),className:`w-16 px-3 py-1.5 bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg 93 text-[var(--color-text-primary)] text-sm text-center focus:outline-none focus:border-brand-500`}),e.jsx("span",{className:"text-sm text-[var(--color-text-secondary)]",children:"weeks"})]})]})]}),u>1&&e.jsx("div",{className:"pt-3 border-t border-[var(--color-border-subtle)]",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm text-brand-400",children:[e.jsx(be,{className:"w-4 h-4"}),e.jsxs("span",{children:["Applying to: ",P()]})]})})]}),d<as(new Date)&&e.jsxs("div",{className:"flex items-center gap-2 mt-2 text-sm text-amber-400",children:[e.jsx(Ee,{className:"w-4 h-4"}),e.jsx("span",{children:"This week is in the past"})]})]}),n&&e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-[var(--color-text-primary)] mb-3",children:"3. Options"}),e.jsxs("div",{className:"p-4 bg-[var(--color-bg-hover)] rounded-lg border border-[var(--color-border-subtle)] space-y-3",children:[e.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[e.jsx("input",{type:"radio",checked:v,onChange:()=>y(!0),className:"mt-1 rounded-full border-[var(--color-border-default)] bg-[var(--color-bg-hover)] text-brand-500 focus:ring-brand-500/30"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-[var(--color-text-primary)]",children:"Create as Draft"}),e.jsx("div",{className:"text-xs text-[var(--color-text-secondary)]",children:"Shifts will be created as drafts. You can review and assign employees before publishing."})]})]}),e.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[e.jsx("input",{type:"radio",checked:!v,onChange:()=>y(!1),className:"mt-1 rounded-full border-[var(--color-border-default)] bg-[var(--color-bg-hover)] text-brand-500 focus:ring-brand-500/30"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-[var(--color-text-primary)]",children:"Publish Immediately"}),e.jsx("div",{className:"text-xs text-[var(--color-text-secondary)]",children:"Shifts will be created and published immediately. Employees will be notified about open shifts."})]})]})]})]}),n&&j&&e.jsxs("div",{className:"p-4 bg-brand-500/10 rounded-lg border border-brand-500/20",children:[e.jsx("h3",{className:"font-bold text-brand-400 mb-2",children:"Summary"}),e.jsxs("ul",{className:"space-y-1 text-sm text-[var(--color-text-primary)]",children:[e.jsxs("li",{children:["⢠Template: ",e.jsx("span",{className:"font-medium text-[var(--color-text-primary)]",children:j.name})]}),e.jsxs("li",{children:["⢠Date Range: ",e.jsx("span",{className:"font-medium text-[var(--color-text-primary)]",children:P()})]}),e.jsxs("li",{children:["⢠Shifts per week: ",e.jsx("span",{className:"font-medium text-[var(--color-text-primary)]",children:R})]}),e.jsxs("li",{children:["⢠Total shifts to create: ",e.jsx("span",{className:"font-medium text-[var(--color-text-primary)]",children:R*u})]}),e.jsxs("li",{children:["⢠Status: ",e.jsx("span",{className:"font-medium text-[var(--color-text-primary)]",children:v?"Draft":"Published"})]})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-t border-[var(--color-border-subtle)] bg-[var(--color-bg-hover)]",children:[e.jsx("div",{className:"text-sm text-[var(--color-text-secondary)]",children:j&&e.jsxs(e.Fragment,{children:[$," shift",$!==1?"s":"","/week ⢠",R*u," total across ",u," week",u!==1?"s":""]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:W,className:"px-4 py-2 text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] text-sm",children:"Cancel"}),e.jsx("button",{onClick:D,disabled:!n||i,className:`flex items-center gap-2 px-4 py-2 bg-brand-600 hover:bg-brand-500 94 text-[var(--color-text-primary)] rounded-lg text-sm font-medium transition-colors 95 disabled:opacity-50 disabled:cursor-not-allowed`,children:v?e.jsxs(e.Fragment,{children:[e.jsx(tr,{className:"w-4 h-4"}),"Create Shifts"]}):e.jsxs(e.Fragment,{children:[e.jsx(Nr,{className:"w-4 h-4"}),"Create & Publish"]})})]})]}),i&&e.jsx("div",{className:"absolute inset-0 bg-slate-900/50 flex items-center justify-center",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-[var(--color-border-default)] border-t-transparent"})})]})}):null}
95,jc=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],os={start:"09:00",end:"17:00"};function vr(l){switch(l){case"can":return"bg-emerald-500/20 text-emerald-300 border-emerald-500/40";case"prefer":return"bg-[var(--color-primary-subtle)] text-[var(--color-primary)] border-blue-500/40";case"cannot":return"bg-red-500/20 text-red-300 border-red-500/40";default:return"bg-[var(--color-bg-hover)] text-[var(--color-text-primary)] border-[var(--color-border-default)]"}}function _c(l){switch(l){case"can":return"Available";case"prefer":return"Preferred";case"cannot":return"Unavailable";default:return l}}const Nc=({employees:l,selectedEmployeeId:t,rules:r,onSelectEmployee:a,onCreateRule:o,onUpdateRule:s,onDeleteRule:i,onBulkSave:n,loading:c=!1})=>{var k,f;const[d,m]=x.useState(!1),[u,h]=x.useState([]),[v,y]=x.useState(null),[p,N]=x.useState(null),S=l.find(g=>g.id===t);x.useEffect(()=>{d&&h(r.map(g=>({weekday:g.weekday,start_local_time:g.start_local_time,end_local_time:g.end_local_time,type:g.type,id:g.id})))},[d,r]);const j=g=>{y(g),N({weekday:g,start_local_time:os.start,end_local_time:os.end,type:"can",isNew:!0})},I=()=>{!p||!t||(d?h([...u,{...p,isNew:!0}]):o({employee_id:t,weekday:p.weekday,start_local_time:p.start_local_time,end_local_time:p.end_local_time,type:p.type}),y(null),N(null))},$=()=>{y(null),N(null)},R=g=>{d?h(u.filter(L=>L.id!==g)):i(g)},E=g=>{h(u.filter((L,z)=>z!==g))},O=(g,L)=>{h(u.map((z,X)=>X===g?{...z,...L}:z))},D=()=>{if(!t||!n)return;const g=u.map(L=>({weekday:L.weekday,start_local_time:L.start_local_time,end_local_time:L.end_local_time,type:L.type}));n(t,g),m(!1)},b=()=>{m(!1),h([])},P=g=>r.filter(L=>L.weekday===g),W=g=>u.filter(L=>L.weekday===g);return t?e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"p-4 border-b border-[var(--color-border-subtle)]",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("button",{onClick:()=>a(""),className:"flex items-center gap-1 text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] text-sm",children:[e.jsx(la,{className:"w-4 h-4"}),"Back to list"]}),n&&e.jsx("div",{className:"flex items-center gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:b,className:"px-3 py-1.5 text-sm text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]",children:"Cancel"}),e.jsxs("button",{onClick:D,disabled:c,className:`flex items-center gap-2 px-3 py-1.5 bg-emerald-600 hover:bg-emerald-500 96 text-[var(--color-text-primary)] rounded-lg text-sm font-medium disabled:opacity-50`,children:[e.jsx(sa,{className:"w-4 h-4"}),"Save All"]})]}):e.jsxs("button",{onClick:()=>m(!0),className:`flex items-center gap-2 px-3 py-1.5 bg-[var(--color-bg-hover)] hover:bg-[var(--color-bg-active)] 97 text-[var(--color-text-primary)] rounded-lg text-sm font-medium`,children:[e.jsx(qt,{className:"w-4 h-4"}),"Edit Mode"]})})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-brand-500/20 flex items-center justify-center",children:e.jsxs("span",{className:"text-lg font-medium text-brand-400",children:[(k=S==null?void 0:S.firstName)==null?void 0:k[0],(f=S==null?void 0:S.lastName)==null?void 0:f[0]]})}),e.jsxs("div",{children:[e.jsxs("h3",{className:"text-lg font-semibold text-[var(--color-text-primary)]",children:[S==null?void 0:S.firstName," ",S==null?void 0:S.lastName]}),e.jsx("p",{className:"text-sm text-[var(--color-text-secondary)]",children:S==null?void 0:S.role})]})]})]}),e.jsxs("div",{className:"px-4 py-2 border-b border-[var(--color-border-subtle)] flex items-center gap-4 bg-[var(--color-bg-hover)]",children:[e.jsx("span",{className:"text-xs text-[var(--color-text-secondary)]",children:"Legend:"}),e.jsxs("div",{className:"flex items-center gap-3 text-xs",children:[e.jsx("span",{className:`px-2 py-0.5 rounded border ${vr("can")}`,children:"Available"}),e.jsx("span",{className:`px-2 py-0.5 rounded border ${vr("prefer")}`,children:"Preferred"}),e.jsx("span",{className:`px-2 py-0.5 rounded border ${vr("cannot")}`,children:"Unavailable"})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:e.jsx("div",{className:"space-y-3",children:jc.map((g,L)=>{const z=d?W(L):P(L),X=v===L;return e.jsxs("div",{className:"bg-[var(--color-bg-hover)] rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-[var(--color-bg-hover)]",children:[e.jsx("span",{className:"font-medium text-[var(--color-text-primary)]",children:g}),!X&&e.jsx("button",{onClick:()=>j(L),className:"p-1 text-[var(--color-text-muted)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)] rounded",children:e.jsx(ot,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:"p-2 space-y-2",children:[z.length===0&&!X&&e.jsx("p",{className:"text-sm text-[var(--color-text-muted)] text-center py-2",children:"No availability set"}),d?u.map((C,Y)=>C.weekday!==L?null:e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-[var(--color-bg-hover)] rounded-lg",children:[e.jsxs("select",{value:C.type,onCh
97ange:F=>O(Y,{type:F.target.value}),className:`bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded px-2 py-1 98 text-sm text-[var(--color-text-primary)] focus:outline-none focus:border-brand-500/50`,children:[e.jsx("option",{value:"can",children:"Available"}),e.jsx("option",{value:"prefer",children:"Preferred"}),e.jsx("option",{value:"cannot",children:"Unavailable"})]}),e.jsx("input",{type:"time",value:C.start_local_time,onChange:F=>O(Y,{start_local_time:F.target.value}),className:`bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded px-2 py-1 99 text-sm text-[var(--color-text-primary)] focus:outline-none focus:border-brand-500/50`}),e.jsx("span",{className:"text-[var(--color-text-muted)]",children:"to"}),e.jsx("input",{type:"time",value:C.end_local_time,onChange:F=>O(Y,{end_local_time:F.target.value}),className:`bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded px-2 py-1 100 text-sm text-[var(--color-text-primary)] focus:outline-none focus:border-brand-500/50`}),e.jsx("button",{onClick:()=>E(Y),className:"p-1 text-red-400 hover:text-red-300 hover:bg-red-500/10 rounded",children:e.jsx(qe,{className:"w-4 h-4"})})]},C.id||`new-${Y}`)):z.map(C=>e.jsxs("div",{className:"flex items-center justify-between p-2 bg-[var(--color-bg-hover)] rounded-lg group",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:`px-2 py-0.5 rounded text-xs font-bold border ${vr(C.type)}`,children:_c(C.type)}),e.jsxs("div",{className:"flex items-center gap-1 text-sm text-[var(--color-text-primary)]",children:[e.jsx(ve,{className:"w-3 h-3 text-[var(--color-text-muted)]"}),C.start_local_time," - ",C.end_local_time]})]}),e.jsx("button",{onClick:()=>R(C.id),disabled:c,className:`p-1 text-red-400/50 hover:text-red-400 hover:bg-red-500/10 101 rounded opacity-0 group-hover:opacity-100 transition-opacity disabled:opacity-50`,children:e.jsx(qe,{className:"w-4 h-4"})})]},C.id)),X&&p&&e.jsxs("div",{className:"p-3 bg-brand-500/10 border border-brand-500/30 rounded-lg",children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsxs("select",{value:p.type,onChange:C=>N({...p,type:C.target.value}),className:`bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded px-2 py-1 102 text-sm text-[var(--color-text-primary)] focus:outline-none focus:border-brand-500/50`,children:[e.jsx("option",{value:"can",children:"Available"}),e.jsx("option",{value:"prefer",children:"Preferred"}),e.jsx("option",{value:"cannot",children:"Unavailable"})]})}),e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("label",{className:"text-xs text-[var(--color-text-secondary)] w-12",children:"From"}),e.jsx("input",{type:"time",value:p.start_local_time,onChange:C=>N({...p,start_local_time:C.target.value}),className:`flex-1 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded px-3 py-1.5 103 text-sm text-[var(--color-text-primary)] focus:outline-none focus:border-brand-500/50`}),e.jsx("label",{className:"text-xs text-[var(--color-text-secondary)] w-8",children:"To"}),e.jsx("input",{type:"time",value:p.end_local_time,onChange:C=>N({...p,end_local_time:C.target.value}),className:`flex-1 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded px-3 py-1.5 104 text-sm text-[var(--color-text-primary)] focus:outline-none focus:border-brand-500/50`})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx("button",{onClick:$,className:"px-3 py-1.5 text-sm text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]",children:"Cancel"}),e.jsxs("button",{onClick:I,disabled:c,className:`flex items-center gap-2 px-3 py-1.5 bg-brand-500 hover:bg-brand-400 105 text-[var(--color-text-primary)] rounded-lg text-sm font-medium disabled:opacity-50`,children:[e.jsx(Te,{className:"w-4 h-4"}),"Add"]})]})]})]})]},L)})})}),c&&e.jsx("div",{className:"absolute inset-0 bg-slate-900/50 flex items-center justify-center",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-[var(--color-border-default)] border-t-transparent"})})]}):e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"p-4 border-b border-[var(--color-border-subtle)]",children:[e.jsxs("h3",{className:"text-lg font-semibold text-[var(--color-text-primary)] flex items-center gap-2",children:[e.jsx(be,{className:"w-5 h-5 text-brand-400"}),"Employee Availability"]}),e.jsx("p",{className:"text-sm text-[var(--color-text-secondary)] mt-1",children:"Select an employee to manage their availability"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:e.jsx("div",{className:"space-y-2",children:l.filter(g=>g.status==="Active").map(g=>{var L,z;return e.jsxs("button",{onClick:()=>a(g.id),className:`w-full p-3 flex items-center gap-3 bg-[var(--color-bg-hover)] hover:bg-[var(--color-bg-hover)] 106 rounded-lg transition-colors text-left`,children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-brand-500/20 flex items-center justify-center",children:e.jsxs("span",{className:"text-sm font-medium text-brand-400",children:[(L=g.firstName)==null?void 0:L[0],(z=g.lastName)==null?void 0:z[0]]})}),e.jsxs("div",{children:[e.jsxs("div",{className:"text-[var(--color-text-primary)] font-medium",children:[g.firstName," ",g.lastName]}),e.jsx("div",{className:"text-xs text-[var(--color-text-secondary)]",children:g.role})]})]},g.id)})})})]})};function Sc(l){const t=new Date(l),a=new Date().getTime()-t.getTime(),o=Math.floor(a/6e4),s=Math.floor(o/60),i=Math.floor(s/24);return o<1?"Just now":o<60?`${o}m ago`:s<24?`${s}h ago`:`${i}d ago`}
106function Cc(l){return new Date(l).toLocaleString("en-US",{weekday:"short",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}function kc(l){if(!l)return{color:"bg-[var(--color-bg-hover)] border-[var(--color-border-default)]",text:"",urgent:!1};const t=new Date(l),r=new Date,a=(t.getTime()-r.getTime())/(1e3*60*60);return a<=12?{color:"bg-red-500/20 border-red-500/50",text:`Starts in ${Math.round(a)}h`,urgent:!0}:a<=24?{color:"bg-amber-500/20 border-amber-500/50",text:`Starts in ${Math.round(a)}h`,urgent:!0}:{color:"bg-[var(--color-bg-hover)] border-[var(--color-border-default)]",text:"",urgent:!1}}const Rc=({request:l,employeeName:t,onApprove:r,onReject:a,isProcessing:o})=>{var y;const[s,i]=x.useState(!1),[n,c]=x.useState(""),{shift:d,transaction:m}=l,u=kc(d==null?void 0:d.start_at_utc),h=(y=m.policy_snapshot)==null?void 0:y.message,v=()=>{a(n||void 0),i(!1),c("")};return e.jsxs("div",{className:`p-3 rounded-lg border ${u.color} transition-colors`,children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-emerald-500/20 flex items-center justify-center",children:e.jsx(tt,{className:"w-4 h-4 text-emerald-400"})}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm font-medium text-[var(--color-text-primary)]",children:t}),e.jsx("div",{className:"text-xs text-[var(--color-text-secondary)]",children:Sc(m.created_at)})]}),u.urgent&&e.jsx("span",{className:"px-2 py-0.5 text-[10px] font-medium bg-red-500/20 text-red-400 rounded ml-auto",children:u.text})]}),d&&e.jsxs("div",{className:"space-y-1 text-xs ml-10",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[var(--color-text-primary)]",children:[e.jsx(ve,{className:"w-3 h-3 text-[var(--color-text-muted)]"}),e.jsx("span",{children:Cc(d.start_at_utc)})]}),d.position_name&&e.jsxs("div",{className:"flex items-center gap-2 text-[var(--color-text-secondary)]",children:[e.jsx(st,{className:"w-3 h-3 text-[var(--color-text-muted)]"}),e.jsx("span",{children:d.position_name})]}),d.location_name&&e.jsxs("div",{className:"flex items-center gap-2 text-[var(--color-text-secondary)]",children:[e.jsx(Je,{className:"w-3 h-3 text-[var(--color-text-muted)]"}),e.jsx("span",{children:d.location_name})]})]}),h&&e.jsxs("div",{className:"mt-2 ml-10 flex items-start gap-2 text-xs text-[var(--color-text-secondary)] italic",children:[e.jsx(gs,{className:"w-3 h-3 mt-0.5 flex-shrink-0"}),e.jsxs("span",{children:['"',h,'"']})]})]}),!o&&e.jsxs("div",{className:"flex flex-col gap-1 ml-3",children:[e.jsxs("button",{onClick:r,className:`px-3 py-1.5 text-xs bg-emerald-500/20 hover:bg-emerald-500/30 107 text-emerald-400 rounded transition-colors flex items-center gap-1`,children:[e.jsx(Te,{className:"w-3 h-3"}),"Approve"]}),e.jsxs("button",{onClick:()=>i(!s),className:`px-3 py-1.5 text-xs bg-red-500/20 hover:bg-red-500/30 108 text-red-400 rounded transition-colors flex items-center gap-1`,children:[e.jsx(de,{className:"w-3 h-3"}),"Reject"]})]}),o&&e.jsx("div",{className:"ml-3",children:e.jsx(Xe,{className:"w-5 h-5 text-[var(--color-text-muted)] animate-spin"})})]}),s&&!o&&e.jsxs("div",{className:"mt-3 pt-3 border-t border-[var(--color-border-subtle)]",children:[e.jsx("textarea",{value:n,onChange:p=>c(p.target.value),placeholder:"Reason for rejection (optional)...",className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded px-2 py-1.5 109 text-xs text-[var(--color-text-primary)] placeholder-[var(--color-text-muted)] resize-none`,rows:2}),e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsx("button",{onClick:v,className:`flex-1 px-2 py-1.5 text-xs bg-red-500 hover:bg-red-400 110 text-[var(--color-text-primary)] rounded transition-colors`,children:"Confirm Rejection"}),e.jsx("button",{onClick:()=>{i(!1),c("")},className:`px-2 py-1.5 text-xs bg-[var(--color-bg-hover)] hover:bg-[var(--color-bg-active)] 111 text-[var(--color-text-primary)] rounded transition-colors`,children:"Cancel"})]})]})]})},Dc=({pickupRequests:l,employees:t,onApprove:r,onReject:a,onRefresh:o,loading:s=!1})=>{const[i,n]=x.useState(null),[c,d]=x.useState(null),m=y=>{if(!y)return"Unknown";const p=t.find(N=>N.id===y);return p?`${p.firstName} ${p.lastName}`:"Unknown"},u=async y=>{n(y),d(null);try{await r(y)}catch(p){console.error("Failed to approve pickup:",p),d(p instanceof Error?p.message:"Failed to approve request")}finally{n(null)}},h=async(y,p)=>{n(y),d(null);try{await a(y,p)}catch(N){console.error("Failed to reject pickup:",N),d(N instanceof Error?N.message:"Failed to reject request")}finally{n(null)}},v=[...l].sort((y,p)=>y.shift?p.shift?new Date(y.shift.start_at_utc).getTime()-new Date(p.shift.start_at_utc).getTime():-1:1);return e.jsxs("div",{className:"space-y-2",children:[c&&e.jsxs("div",{className:`px-3 py-2 bg-red-500/20 border border-red-500/30 rounded-lg 112 flex items-center gap-2 text-sm text-red-400`,children:[e.jsx(Ee,{className:"w-4 h-4"}),e.jsx("span",{children:c}),e.jsx("button",{onClick:()=>d(null),className:"ml-auto text-red-400/70 hover:text-red-400",children:e.jsx(de,{className:"w-4 h-4"})})]}),s?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(Xe,{className:"w-6 h-6 text-[var(--color-text-muted)] animate-spin mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-[var(--color-text-muted)]",children:"Loading requests..."})]}):v.length===0?e.jsxs("div",{className:"text-center py-8 text-[var(--color-text-muted)] text-sm",children:[e.jsx(Rs,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No pending pickup requests"})]}):v.map(y=>e.jsx(Rc,{request:y,employeeName:m(y.transaction.to_employee_id),onApprove:()=>u(y.transaction.id),onReject:p=>h(y.transaction.id,p),isProcessing:i===y.transaction.id},y.transaction.id))]})};function Os(l){const t=new Date(l),a=new Date().getTime()-t.getTime(),o=Math.floor(a/6e4),s=Math.floor(o/60),i=Math.floor(s/24);return o<1?"Just now":o<60?`${o}m ago`:s<24?`${s}h ago`:`${i}d ago`}function Ec(l){const t=new Date(l),r=new Date,a=(t.getTime()-r.getTime())/(1e3*60*60);return a<=12?"bg-red-500/20 border-red-500/50":a<=24?"bg-amber-500/20 border-amber-500/50":"bg-[var(--color-bg-hover)] border-[var(--color-border-default)]"}
112function Cr(l){return new Date(l).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}const Tc=({request:l,shift:t,employeeName:r,onApprove:a,onReject:o,employees:s,suggestions:i=[],loadingSuggestions:n=!1,onLoadSuggestions:c})=>{const[d,m]=x.useState(!1),[u,h]=x.useState(""),[v,y]=x.useState(!1),p=t?Ec(t.start_at_utc):"bg-[var(--color-bg-hover)] border-[var(--color-border-default)]",N=t?Cr(t.start_at_utc):"Unknown",S=()=>{!v&&i.length===0&&c&&c(),y(!v)};return e.jsxs("div",{className:`p-3 rounded-lg border ${p} transition-colors`,children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Ee,{className:"w-4 h-4 text-amber-400"}),e.jsx("span",{className:"text-sm font-medium text-[var(--color-text-primary)]",children:r})]}),e.jsxs("div",{className:"text-xs text-[var(--color-text-secondary)] mb-1",children:["Shift: ",N]}),l.reason&&e.jsxs("div",{className:"text-xs text-[var(--color-text-secondary)] italic",children:['"',l.reason,'"']}),e.jsx("div",{className:"text-xs text-[var(--color-text-muted)] mt-1",children:Os(l.created_at)})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("button",{onClick:()=>a("open_shift"),className:`px-2 py-1 text-xs bg-emerald-500/20 hover:bg-emerald-500/30 113 text-emerald-400 rounded transition-colors`,children:"Open Shift"}),e.jsx("button",{onClick:()=>m(!d),className:`px-2 py-1 text-xs bg-[var(--color-primary-subtle)] hover:bg-blue-500/30 114 text-[var(--color-primary)] rounded transition-colors`,children:"Reassign"}),e.jsx("button",{onClick:o,className:`px-2 py-1 text-xs bg-red-500/20 hover:bg-red-500/30 115 text-red-400 rounded transition-colors`,children:"Deny"})]})]}),c&&e.jsxs("div",{className:"mt-2 pt-2 border-t border-[var(--color-border-subtle)]",children:[e.jsxs("button",{onClick:S,className:"text-xs text-brand-400 hover:text-brand-300 flex items-center gap-1",children:[e.jsx(Re,{className:"w-3 h-3"}),v?"Hide":"Show"," Suggested Employees",i.length>0&&` (${i.length})`]}),v&&e.jsx("div",{className:"mt-2 space-y-1",children:n?e.jsxs("div",{className:"text-xs text-[var(--color-text-muted)] flex items-center gap-1",children:[e.jsx(Xe,{className:"w-3 h-3 animate-spin"}),"Finding eligible employees..."]}):i.length===0?e.jsx("div",{className:"text-xs text-[var(--color-text-muted)]",children:"No eligible employees found"}):i.slice(0,3).map(j=>e.jsxs("div",{className:"flex items-center justify-between p-2 bg-[var(--color-bg-hover)] rounded text-xs",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-[var(--color-text-primary)] font-medium",children:j.name}),e.jsx("span",{className:"text-[var(--color-text-muted)] ml-2",children:j.reason}),j.overtimeRisk&&e.jsx("span",{className:"ml-1 px-1 py-0.5 bg-amber-500/20 text-amber-400 rounded text-[10px]",children:"OT Risk"})]}),e.jsx("button",{onClick:()=>a("reassign",j.id),className:"px-2 py-1 bg-brand-500/20 hover:bg-brand-500/30 text-brand-400 rounded",children:"Assign"})]},j.id))})]}),d&&e.jsxs("div",{className:"mt-2 pt-2 border-t border-[var(--color-border-subtle)]",children:[e.jsxs("select",{value:u,onChange:j=>h(j.target.value),className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded px-2 py-1 116 text-xs text-[var(--color-text-primary)] mb-2`,children:[e.jsx("option",{value:"",children:"Select employee..."}),s.filter(j=>j.id!==l.requested_by_employee_id).map(j=>e.jsxs("option",{value:j.id,children:[j.firstName," ",j.lastName]},j.id))]}),e.jsx("button",{onClick:()=>u&&a("reassign",u),disabled:!u,className:`w-full px-2 py-1 text-xs bg-[var(--color-primary)] hover:bg-[var(--color-primary)] 117 disabled:bg-[var(--color-bg-active)] disabled:cursor-not-allowed 118 text-[var(--color-text-primary)] rounded transition-colors`,children:"Assign to Selected"})]})]})},Ic=({swap:l,shiftA:t,shiftB:r,employeeAName:a,employeeBName:o,onApprove:s,onReject:i})=>{const n=t?Cr(t.start_at_utc):"Unknown",c=r?Cr(r.start_at_utc):null;return e.jsx("div",{className:"p-3 rounded-lg border bg-[var(--color-bg-hover)] border-[var(--color-border-default)]",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Rl,{className:"w-4 h-4 text-[var(--color-primary)]"}),e.jsx("span",{className:"text-xs font-medium text-[var(--color-text-secondary)] uppercase",children:l.swap_type==="handoff"?"Handoff":"Two-Way Swap"})]}),e.jsxs("div",{className:"space-y-1 text-xs",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[var(--color-text-primary)]",children:a}),e.jsx(nt,{className:"w-3 h-3 text-[var(--color-text-muted)]"}),e.jsx("span",{className:"text-[var(--color-text-secondary)]",children:n})]}),l.swap_type==="two_shift"&&c&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[var(--color-text-primary)]",children:o}),e.jsx(nt,{className:"w-3 h-3 text-[var(--color-text-muted)]"}),e.jsx("span",{className:"text-[var(--color-text-secondary)]",children:c})]})]}),l.message&&e.jsxs("div",{className:"text-xs text-[var(--color-text-secondary)] italic mt-2",children:['"',l.message,'"']}),e.jsxs("div",{className:"text-xs text-[var(--color-text-muted)] mt-1",children:[Os(l.created_at),l.status==="accepted"&&e.jsx("span",{className:"ml-2 text-emerald-400",children:"⢠Accepted by target"})]})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("button",{onClick:s,className:`px-2 py-1 text-xs bg-emerald-500/20 hover:bg-emerald-500/30 119 text-emerald-400 rounded transition-colors flex items-center gap-1`,children:[e.jsx(Te,{className:"w-3 h-3"}),"Approve"]}),e.jsxs("button",{onClick:i,className:`px-2 py-1 text-xs bg-red-500/20 hover:bg-red-500/30 120 text-red-400 rounded transition-colors flex items-center gap-1`,children:[e.jsx(de,{className:"w-3 h-3"}),"Reject"]})]})]})})},Ac=({coverageRequests:l,swapRequests:t,pickupRequests:r=[],shifts:a,employees:o,onApproveCoverage:s,onRejectC
120overage:i,onApproveSwap:n,onRejectSwap:c,onApprovePickup:d,onRejectPickup:m,onRefresh:u,loading:h=!1,onGetSuggestions:v})=>{const[y,p]=x.useState("coverage"),[N,S]=x.useState({}),[j,I]=x.useState(null),$=async(k,f)=>{if(!(!v||N[k])){I(k);try{const g=await v(k,f);S(L=>({...L,[k]:g}))}catch(g){console.error("Failed to load suggestions:",g)}finally{I(null)}}},R=l.filter(k=>k.status==="pending"),E=t.filter(k=>k.status==="pending"||k.status==="accepted"||k.status==="pending_approval"),O=r.filter(k=>k.transaction.status==="pending"),D=a.filter(k=>k.status==="open"||!k.assigned_employee_id),b=k=>{if(!k)return"Unknown";const f=o.find(g=>g.id===k);return f?`${f.firstName} ${f.lastName}`:"Unknown"},P=k=>a.find(f=>f.id===k),W=R.length+E.length+O.length;return e.jsxs("div",{className:"bg-[var(--color-bg-hover)] backdrop-blur-xl rounded-xl border border-[var(--color-border-subtle)] overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-[var(--color-border-subtle)]",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Re,{className:"w-5 h-5 text-brand-400"}),e.jsx("h3",{className:"text-sm font-semibold text-[var(--color-text-primary)]",children:"Coverage Queue"}),W>0&&e.jsx("span",{className:"px-2 py-0.5 text-xs font-bold bg-red-500 text-[var(--color-text-primary)] rounded-full",children:W})]}),e.jsx("button",{onClick:u,disabled:h,className:"p-1.5 hover:bg-[var(--color-bg-hover)] rounded-lg transition-colors",children:e.jsx(Xe,{className:`w-4 h-4 text-[var(--color-text-secondary)] ${h?"animate-spin":""}`})})]}),e.jsxs("div",{className:"flex border-b border-[var(--color-border-subtle)]",children:[e.jsxs("button",{onClick:()=>p("coverage"),className:`flex-1 px-3 py-2 text-xs font-medium transition-colors 121 ${y==="coverage"?"text-brand-400 border-b-2 border-brand-400 bg-brand-400/5":"text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)]"}`,children:["Coverage",R.length>0&&e.jsx("span",{className:"ml-1 px-1.5 py-0.5 text-[10px] bg-amber-500/20 text-amber-400 rounded",children:R.length})]}),e.jsxs("button",{onClick:()=>
121p("swaps"),className:`flex-1 px-3 py-2 text-xs font-medium transition-colors 122 ${y==="swaps"?"text-brand-400 border-b-2 border-brand-400 bg-brand-400/5":"text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)]"}`,children:["Swaps",E.length>0&&e.jsx("span",{className:"ml-1 px-1.5 py-0.5 text-[10px] bg-[var(--color-primary-subtle)] text-[var(--color-primary)] rounded",children:E.length})]}),e.jsxs("button",{onClick:()=>p("pickups"),className:`flex-1 px-3 py-2 text-xs font-medium transition-colors 123 ${y==="pickups"?"text-brand-400 border-b-2 border-brand-400 bg-brand-400/5":"text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)]"}`,children:["Pickups",O.length>0&&e.jsx("span",{className:"ml-1 px-1.5 py-0.5 text-[10px] bg-emerald-500/20 text-emerald-400 rounded",children:O.length})]})]}),e.jsxs("div",{className:"p-3 max-h-96 overflow-y-auto space-y-2",children:[y==="coverage"&&e.jsx(e.Fragment,{children:R.length===0?e.jsx("div",{className:"text-center py-8 text-[var(--color-text-muted)] text-sm",children:"No pending coverage requests"}):R.map(k=>e.jsx(Tc,{request:k,shift:P(k.shift_id),employeeName:b(k.requested_by_employee_id),employees:o,onApprove:(f,g)=>s(k.id,f,g),onReject:()=>i(k.id),suggestions:N[k.id],loadingSuggestions:j===k.id,onLoadSuggestions:v?()=>$(k.id,k.shift_id):void 0},k.id))}),y==="swaps"&&e.jsx(e.Fragment,{children:E.length===0?e.jsx("div",{className:"text-center py-8 text-[var(--color-text-muted)] text-sm",children:"No pending swap requests"}):E.map(k=>e.jsx(Ic,{swap:k,shiftA:P(k.shift_id_a),shiftB:k.shift_id_b?P(k.shift_id_b):void 0,employeeAName:b(k.employee_a),employeeBName:b(k.employee_b),onApprove:()=>n(k.id),onReject:()=>c(k.id)},k.id))}),y==="pickups"&&e.jsx(e.Fragment,{children:d&&m?e.jsx(Dc,{pickupRequests:O,employees:o,onApprove:d,onReject:m,onRefresh:u,loading:h}):D.length===0?e.jsx("div",{className:"text-center py-8 text-[var(--color-text-muted)] text-sm",children:"No open or unassigned shifts"}):D.map(k=>{const f=!k.assigned_employee_id,g=k.status==="open",L=g?"Open":f?"Unassigned":"",z=g?"bg-emerald-500/20 text-emerald-400":"bg-amber-500/20 text-amber-400";return e.jsxs("div",{className:`p-3 rounded-lg border ${g?"bg-emerald-500/10 border-emerald-500/30":"bg-amber-500/10 border-amber-500/30"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rs,{className:`w-4 h-4 ${g?"text-emerald-400":"text-amber-400"}`}),e.jsx("span",{className:"text-sm font-medium text-[var(--color-text-primary)]",children:k.position_name||"Shift"})]}),e.jsx("span",{className:`px-2 py-0.5 text-[10px] font-medium rounded ${z}`,children:L})]}),e.jsx("div",{className:"text-xs text-[var(--color-text-secondary)]",children:Cr(k.start_at_utc)}),e.jsx("div",{className:"text-xs text-[var(--color-text-muted)] mt-1",children:k.location_name||"Unknown location"})]},k.id)})})]}),e.jsx("div",{className:"px-4 py-2 border-t border-[var(--color-border-subtle)] bg-[var(--color-bg-hover)]",children:e.jsxs("div",{className:"flex items-center justify-between text-xs text-[var(--color-text-secondary)]",children:[e.jsxs("span",{children:["Pending: ",W]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{children:["Coverage: ",R.length]}),e.jsxs("span",{children:["Swaps: ",E.length]}),e.jsxs("span",{children:["Pickups: ",O.length]})]})]})})]})};function fr(l){return l.split("T")[0]}function gr(l,t=!1){const r=new Date(l);return t?r.setHours(23,59,59,999):r.setHours(0,0,0,0),r.toISOString()}const Pc=({isOpen:l,request:t,employee:r,employees:a=[],isManager:o=!1,onClose:s,onSubmit:i,onUpdate:n,loading:c=!1,error:d=null})=>{var W,k;const[m,u]=x.useState(""),[h,v]=x.useState(""),[y,p]=x.useState(""),[N,S]=x.useState("Vacation"),[j,I]=x.useState(""),[$,R]=x.useState(""),E=!!t;x.useEffect(()=>{if(l){if(t)u(t.employee_id),v(fr(t.start_at_utc)),p(fr(t.end_at_utc)),S(t.type),I(t.notes||"");else{u((r==null?void 0:r.id)||"");const f=new Date;f.setDate(f.getDate()+1),v(fr(f.toISOString())),p(fr(f.toISOString())),S("Vacation"),I("")}R("")}},[l,t,r]);const O=()=>{if(!h||!y)return 0;const f=new Date(h),g=new Date(y);let L=0;const z=new Date(f);for(;z<=g;)z.getDay()!==0&&z.getDay()!==6&&L++,z.setDate(z.getDate()+1);return L},D=()=>!m&&o?(R("Please select an employee"),!1):h?y?new Date(y)<new Date(h)?(R("End date must be after start date"),!1):N?(R(""),!0):(R("Please select a time off type"),!1):(R("Please select an end date"),!1):(R("Please select a start date"),!1),b=()=>{if(!D())return;const f=m||(r==null?void 0:r.id);if(!f){R("No employee selected");return}E&&t&&n?n(t.id,{start_at_utc:gr(h),end_at_utc:gr(y,!0),type:N,notes:j.trim()||void 0}
123):i({employee_id:f,start_at_utc:gr(h),end_at_utc:gr(y,!0),type:N,notes:j.trim()||void 0})};if(!l)return null;const P=O();return a.find(f=>f.id===m),e.jsx("div",{className:"fixed inset-0 bg-slate-900/50 flex items-center justify-center z-50 backdrop-blur-sm p-4",children:e.jsxs("div",{className:"bg-[var(--color-bg-surface)] rounded-xl w-full max-w-lg shadow-2xl border border-[var(--color-border-subtle)]",children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-[var(--color-border-subtle)]",children:[e.jsxs("h2",{className:"text-lg font-bold text-[var(--color-text-primary)] flex items-center gap-2",children:[e.jsx(be,{className:"w-5 h-5 text-brand-400"}),E?"Edit Time Off Request":"Request Time Off"]}),e.jsx("button",{onClick:s,className:"p-2 hover:bg-[var(--color-bg-hover)] rounded-lg text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]",children:e.jsx(de,{className:"w-5 h-5"})})]}),e.jsxs("div",{className:"p-6 space-y-5",children:[o&&a.length>0&&!E&&e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-[var(--color-text-primary)] mb-2",children:[e.jsx(tt,{className:"w-4 h-4 inline mr-1"}),"Employee"]}),e.jsxs("select",{value:m,onChange:f=>u(f.target.value),className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-4 py-2.5 124 text-[var(--color-text-primary)] focus:outline-none focus:border-brand-500/50`,children:[e.jsx("option",{value:"",children:"Select employee..."}),a.filter(f=>f.status==="Active").map(f=>e.jsxs("option",{value:f.id,children:[f.firstName," ",f.lastName]},f.id))]})]}),!o&&r&&e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-[var(--color-bg-hover)] rounded-lg",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-brand-500/20 flex items-center justify-center",children:e.jsxs("span",{className:"text-lg font-medium text-brand-400",children:[(W=r.firstName)==null?void 0:W[0],(k=r.lastName)==null?void 0:k[0]]})}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-medium text-[var(--color-text-primary)]",children:[r.firstName," ",r.lastName]}),e.jsx("div",{className:"text-xs text-[var(--color-text-secondary)]",children:r.role})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-[var(--color-text-primary)] mb-2",children:"Type"}),e.jsx("select",{value:N,onChange:f=>S(f.target.value),className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-4 py-2.5 125 text-[var(--color-text-primary)] focus:outline-none focus:border-brand-500/50`,children:Vi.map(f=>e.jsx("option",{value:f,children:f},f))})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-[var(--color-text-primary)] mb-2",children:"Start Date"}),e.jsx("input",{type:"date",value:h,onChange:f=>v(f.target.value),min:new Date().toISOString().split("T")[0],className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-4 py-2.5 126 text-[var(--color-text-primary)] focus:outline-none focus:border-brand-500/50`})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-[var(--color-text-primary)] mb-2",children:"End Date"}),e.jsx("input",{type:"date",value:y,onChange:f=>p(f.target.value),min:h||new Date().toISOString().split("T")[0],className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-4 py-2.5 127 text-[var(--color-text-primary)] focus:outline-none focus:border-brand-500/50`})]})]}),P>0&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-brand-500/10 border border-brand-500/20 rounded-lg",children:[e.jsx(ve,{className:"w-4 h-4 text-brand-400"}),e.jsxs("span",{className:"text-sm text-brand-300",children:[P," business day",P!==1?"s":""," requested"]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-[var(--color-text-primary)] mb-2",children:[e.jsx(et,{className:"w-4 h-4 inline mr-1"}),"Notes (optional)"]}),e.jsx("textarea",{value:j,onChange:f=>I(f.target.value),placeholder:"Any additional details...",rows:3,className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-4 py-2.5 128 text-[var(--color-text-primary)] placeholder-white/40 focus:outline-none focus:border-brand-500/50 resize-none`})]}),($||d)&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-red-500/10 border border-red-500/20 rounded-lg",children:[e.jsx(Ve,{className:"w-4 h-4 text-red-400"}),e.jsx("span",{className:"text-sm text-red-300",children:$||d})]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-3 px-6 py-4 border-t border-[var(--color-border-subtle)] bg-[var(--color-bg-hover)]",children:[e.jsx("button",{onClick:s,disabled:c,
128className:"px-4 py-2 text-[var(--color-text-primary)] hover:text-[var(--color-text-primary)] font-medium",children:"Cancel"}),e.jsx("button",{onClick:b,disabled:c,className:`px-5 py-2 bg-brand-500 hover:bg-brand-400 text-[var(--color-text-primary)] rounded-lg 129 font-medium disabled:opacity-50 flex items-center gap-2`,children:c?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-2 border-[var(--color-border-default)] border-t-transparent"}),E?"Updating...":"Submitting..."]}):E?"Update Request":"Submit Request"})]})]})})};function er(l){return new Date(l).toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric",year:"numeric"})}function Oc(l,t){const r=new Date(l),a=new Date(t);return r.toDateString()===a.toDateString()?er(l):`${er(l)} - ${er(t)}`}function Mc(l,t){const r=new Date(l),a=new Date(t);let o=0;const s=new Date(r);for(;s<=a;)s.getDay()!==0&&s.getDay()!==6&&o++,s.setDate(s.getDate()+1);return o}function Fc(l){switch(l){case"submitted":return"bg-amber-500/20 text-amber-300 border-amber-500/40";case"approved":return"bg-emerald-500/20 text-emerald-300 border-emerald-500/40";case"denied":return"bg-red-500/20 text-red-300 border-red-500/40";case"canceled":return"bg-gray-500/20 text-[var(--color-text-muted)] border-gray-500/40";default:return"bg-[var(--color-bg-hover)] text-[var(--color-text-primary)] border-[var(--color-border-default)]"}}function Lc(l){switch(l){case"submitted":return e.jsx(hn,{className:"w-3 h-3"});case"approved":return e.jsx(Rt,{className:"w-3 h-3"});case"denied":return e.jsx(ia,{className:"w-3 h-3"});case"canceled":return e.jsx(de,{className:"w-3 h-3"});default:return null}}function qc(l){switch(l){case"submitted":return"Pending";case"approved":return"Approved";case"denied":return"Denied";case"canceled":return"Canceled";default:return l}}function Uc(l){switch(l.toLowerCase()){case"vacation":return"bg-[var(--color-primary-subtle)] text-[var(--color-primary)]";case"sick":return"bg-orange-500/20 text-orange-300";case"personal":return"bg-purple-500/20 text-purple-300";case"bereavement":return"bg-slate-500/20 text-[var(--color-text-muted)]";default:return"bg-[var(--color-bg-hover)] text-[var(--color-text-primary)]"}}const $c=({requests:l,employees:t,currentEmployeeId:r,isManager:a=!1,onApprove:o,onDeny:s,onCancel:i,onEdit:n,onCreateNew:c,loading:d=!1})=>{const[m,u]=x.useState(null),[h,v]=x.useState(null),[y,p]=x.useState(""),[N,S]=x.useState("pending"),j=b=>t.find(P=>P.id===b),$=[...l.filter(b=>{const P=new Date,k=new Date(b.end_at_utc)<P;switch(N){case"pending":return b.status==="submitted";case"approved":return b.status==="approved"&&!k;case"past":return k||["denied","canceled"].includes(b.status);default:return!0}})].sort((b,P)=>N==="pending"?new Date(b.created_at).getTime()-new Date(P.created_at).getTime():new Date(P.start_at_utc).getTime()-new Date(b.start_at_utc).getTime()),R=b=>{s(b,y.trim()||void 0),v(null),p("")},E=b=>a&&b.status==="submitted"?"approve":b.employee_id===r&&["submitted","approved"].includes(b.status)?"cancel":null,O=l.filter(b=>b.status==="submitted").length,D=l.filter(b=>b.status==="approved"&&new Date(b.end_at_utc)>=new Date).length;return l.length===0?e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"p-4 border-b border-[var(--color-border-subtle)] bg-[var(--color-bg-hover)] flex justify-between items-center",children:[e.jsxs("h3",{className:"font-bold text-[var(--color-text-primary)] flex items-center gap-2",children:[e.jsx(be,{className:"w-5 h-5 text-brand-400"}),"Time Off Requests"]}),c&&e.jsxs("button",{onClick:c,className:`flex items-center gap-2 px-3 py-1.5 bg-brand-500 hover:bg-brand-400 130 text-[var(--color-text-primary)] rounded-lg text-sm font-medium`,children:[e.jsx(ot,{className:"w-4 h-4"}),"Request Time Off"]})]}),e.jsx("div",{className:"flex-1 flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx(be,{className:"w-12 h-12 mx-auto mb-3 text-[var(--color-text-muted)]"}),e.jsx("p",{className:"text-[var(--color-text-secondary)] font-medium",children:"No Time Off Requests"}),e.jsx("p",{className:"text-sm text-[var(--color-text-muted)] mt-1",children:a?"No pending requests to review":"You have no time off requests"}),c&&e.jsx("button",{onClick:c,className:`mt-4 px-4 py-2 bg-brand-500 hover:bg-brand-400 text-[var(--color-text-primary)] 131 rounded-lg text-sm font-medium`,children:"Request Time Off"})]})})]}):e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"p-4 border-b border-[var(--color-border-subtle)] bg-[var(--color-bg-hover)] flex justify-between items-center",children:[e.jsxs("h3",{className:"font-bold text-[var(--color-text-primary)] flex items-center gap-2",children:[e.jsx(be,{className:"w-5 h-5 text-brand-400"}),"Time Off Requests"]}),c&&e.jsxs("button",{onClick:c,className:`flex items-center gap-2 px-3 py-1.5 bg-brand-500 hover:bg-brand-400 132 text-[var(--color-text-primary)] rounded-lg text-sm font-medium`,children:[e.jsx(ot,{className:"w-4 h-4"}),"Request"]})]}),e.jsxs("div",{className:"flex gap-1 px-4 py-2 border-b border-[var(--color-border-subtle)] bg-[var(--color-bg-hover)]",children:[e.jsxs("button",{onClick:()=>S("pending"),className:`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors 133 ${N==="pending"?"bg-brand-500/20 text-brand-400":"text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)]"}`,children:["Pending ",O>0&&`(${O})`]}),e.jsxs("button",{onClick:()=>S("approved"),className:`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors 134 ${N==="approved"?"bg-brand-500/20 text-brand-400":"text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)]"}`,children:["Approved ",D>0&&`(${D})`]}),e.jsx("button",{onClick:()=>S("past"),className:`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors 135 ${N==="past"?"bg-brand-500/20 text-brand-400":"text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)]"}`,children:"History"}),e.jsx("button",{onClick:()=>S("all"),className:`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors 136 ${N==="all"?"bg-brand-500/20 text-brand-400":"text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)]"}`,children:"All"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto divide-y divide-[var(--color-border-subtle)]",children:$.length===0?e.jsxs("div",{className:"p-6 text-center text-[var(--color-text-secondary)]",children:["No ",N==="pending"?"pending":N==="approved"?"upcoming approved":""," requests"]}):$.map(b=>{var L,z;const P=j(b.employee_id),W=m===b.id,k=h===b.id,f=E(b),g=Mc(b.start_at_utc,b.end_at_utc);return e.jsxs("div",{className:"p-4 hover:bg-[var(--color-bg-hover)] transition-colors",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-brand-500/20 flex items-center justify-center flex-shrink-0",children:e.jsxs("span",{className:"text-sm font-medium text-brand-400",children:[(L=P==null?void 0:P.firstName)==null?void 0:L[0],(z=P==null?void 0:P.lastName)==null?void 0:z[0]]})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-medium text-[var(--color-text-primary)]",children:[P==null?void 0:P.firstName," ",P==null?void 0:P.lastName]}),e.jsx("span",{className:`px-2 py-0.5 rounded text-xs font-medium ${Uc(b.type)}`,children:b.type})]}),e.jsxs("div",{className:"text-sm text-[var(--color-text-secondary)] mt-0.5",children:[Oc(b.start_at_utc,b.end_at_utc),e.jsxs("span",{className:"ml-2 text-[var(--color-text-muted)]",children:["(",g," day",g!==1?"s":"",")"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:`px-2 py-0.5 rounded text-xs font-bold border flex items-center gap-1 ${Fc(b.status)}`,children:[Lc(b.status),qc(b.status)]}),e.jsx("button",{onClick:()=>u(W?null:b.id),className:"p-1 hover:bg-[var(--color-bg-hover)] rounded",children:W?e.jsx(Rr,{className:"w-4 h-4 text-[var(--color-text-secondary)]"}):e.jsx(vt,{className:"w-4 h-4 text-[var(--color-text-secondary)]"})})]})]}),W&&e.jsxs("div",{className:"mt-4 pl-13 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4 text-sm",children:[e.jsxs("div",{className:"p-3 bg-[var(--color-bg-hover)] rounded-lg",children:[e.jsx("div",{className:"text-[var(--color-text-secondary)] text-xs uppercase mb-1",children:"Submitted"}),e.jsx("div",{className:"text-[var(--color-text-primary)]",children:er(b.created_at)})]}),b.decided_at&&e.jsxs("div",{className:"p-3 bg-[var(--color-bg-hover)] rounded-lg",children:[e.jsx("div",{className:"text-[var(--color-text-secondary)] text-xs uppercase mb-1",children:b.status==="approved"?"Approved":"Decided"}),e.jsx("div",{className:"text-[var(--color-text-primary)]",children:er(b.decided_at)})]})]}),b.notes&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(gs,{className:"w-4 h-4 text-[var(--color-text-muted)] flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-[var(--color-text-primary)]",children:b.notes})]}),k&&e.jsxs("div",{className:"p-3 bg-red-500/10 rounded-lg border border-red-500/20",children:[e.jsx("label",{className:"block text-sm font-medium text-red-300 mb-2",children:"Denial Reason (optional)"}),e.jsx("textarea",{value:y,onChange:X=>p(X.target.value),placeholder:"Enter reason for denial...",className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg px-3 py-2 137 text-[var(--color-text-primary)] text-sm placeholder-white/40 focus:outline-none focus:border-red-500/50 138 resize-none h-16`}),e.jsxs("div",{className:"flex justify-end gap-2 mt-2",children:[e.jsx("button",{onClick:()=>{v(null),p("")},className:"px-3 py-1.5 text-sm text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]",children:"Cancel"}),e.jsx("button",{onClick:()=>R(b.id),className:"px-3 py-1.5 text-sm bg-red-500 hover:bg-red-400 text-[var(--color-text-primary)] rounded-lg",children:"Deny Request"})]})]}),f&&!k&&e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-[var(--color-border-subtle)]",children:[f==="approve"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>o(b.id),disabled:d,className:`flex items-center gap-2 px-3 py-1.5 bg-emerald-600 hover:bg-emerald-500 139 text-[var(--color-text-primary)] rounded-lg text-sm font-medium disabled:opacity-50`,children:[e.jsx(Rt,{className:"w-4 h-4"}),"Approve"]}),e.jsxs("button",{onClick:()=>v(b.id),className:`flex items-center gap-2 px-3 py-1.5 text-red-400 hover:text-red-300 140 hover:bg-red-500/10 rounded-lg text-sm`,children:[e.jsx(ia,{className:"w-4 h-4"}),"Deny"]})]}),f==="cancel"&&e.jsxs("button",{onClick:()=>i(b.id),disabled:d,className:`flex items-center gap-2 px-3 py-1.5 text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] 141 hover:bg-[var(--color-bg-hover)] rounded-lg text-sm`,children:[e.jsx(de,{className:"w-4 h-4"}),"Cancel Request"]}),n&&b.status==="submitted"&&b.employee_id===r&&e.jsx("button",{onClick:()=>n(b),className:`flex items-center gap-2 px-3 py-1.5 text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] 142 hover:bg-[var(--color-bg-hover)] rounded-lg text-sm`,children:"Edit"})]})]})]},b.id)})}),d&&e.jsx("div",{className:"absolute inset-0 bg-slate-900/50 flex items-center justify-center",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-[var(--color-border-default)] border-t-transparent"})})]})}
142,ns={"America/New_York":"Eastern (ET)","America/Chicago":"Central (CT)","America/Denver":"Mountain (MT)","America/Los_Angeles":"Pacific (PT)","America/Phoenix":"Arizona (no DST)","America/Anchorage":"Alaska (AKT)","Pacific/Honolulu":"Hawaii (HT)"};function ls(l){switch(l){case"active":return"bg-emerald-500/20 text-emerald-300 border-emerald-500/40";case"inactive":return"bg-amber-500/20 text-amber-300 border-amber-500/40";case"archived":return"bg-gray-500/20 text-[var(--color-text-muted)] border-gray-500/40";default:return"bg-[var(--color-bg-hover)] text-[var(--color-text-primary)] border-[var(--color-border-default)]"}}const Hc=({isOpen:l,onClose:t,locations:r,positions:a,onCreateLocation:o,onUpdateLocation:s,onArchiveLocation:i,onDeleteLocation:n,onCreatePosition:c,onUpdatePosition:d,onArchivePosition:m,onDeletePosition:u,loading:h=!1})=>{const[v,y]=x.useState("locations"),[p,N]=x.useState(!1),[S,j]=x.useState(null),[I,$]=x.useState(null),[R,E]=x.useState(!1),[O,D]=x.useState({name:"",timezone:"America/New_York",street:"",city:"",state:"",postal_code:"",country:"USA"}),[b,P]=x.useState({name:"",description:""}),W=()=>{D({name:"",timezone:"America/New_York",street:"",city:"",state:"",postal_code:"",country:"USA"}),P({name:"",description:""}),j(null)},k=()=>{W(),N(!0)},f=F=>{var re,me,_e,Ue,q;if(j(F),v==="locations"){const ne=F;D({name:ne.name,timezone:ne.timezone,street:((re=ne.address)==null?void 0:re.street)||"",city:((me=ne.address)==null?void 0:me.city)||"",state:((_e=ne.address)==null?void 0:_e.state)||"",postal_code:((Ue=ne.address)==null?void 0:Ue.postal_code)||"",country:((q=ne.address)==null?void 0:q.country)||"USA"})}else{const ne=F;P({name:ne.name,description:ne.description||""})}N(!0)},g=()=>{if(v==="locations"){const F={name:O.name.trim(),timezone:O.timezone,address:{street:O.street.trim()||void 0,city:O.city.trim()||void 0,state:O.state.trim()||void 0,postal_code:O.postal_code.trim()||void 0,country:O.country.trim()||void 0}};S?s(S.id,F):o(F)}else{const F={name:b.name.trim(),description:b.description.trim()||void 0};S?d(S.id,F):c(F)}N(!1),W()},L=F=>{v==="locations"?i(F):m(F)},z=F=>{confirm("Are you sure you want to delete this item? This cannot be undone.")&&(v==="locations"&&n?n(F):v==="positions"&&u&&u(F))};if(!l)return null;const X=R?r:r.filter(F=>F.status!=="archived"),C=R?a:a.filter(F=>F.status!=="archived"),Y=v==="locations"?O.name.trim().length>0:b.name.trim().length>0;return e.jsx("div",{className:"fixed inset-0 bg-slate-900/50 flex items-center justify-center z-50 backdrop-blur-sm p-4",children:e.jsxs("div",{className:"bg-[var(--color-bg-surface)] rounded-xl w-full max-w-3xl max-h-[80vh] shadow-2xl border border-[var(--color-border-subtle)] flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-[var(--color-border-subtle)] bg-[var(--color-bg-hover)] rounded-t-xl",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("h3",{className:"text-lg font-semibold text-[var(--color-text-primary)] flex items-center gap-2",children:[e.jsx(ca,{className:"w-5 h-5 text-brand-400"}),"Settings"]}),e.jsxs("div",{className:"flex items-center bg-[var(--color-bg-hover)] rounded-lg p-1",children:[e.jsxs("button",{onClick:()=>y("locations"),className:`flex items-center gap-2 px-3 py-1.5 rounded-md text-sm font-medium transition-colors 143 ${v==="locations"?"bg-brand-500/20 text-brand-400":"text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"}`,children:[e.jsx(Je,{className:"w-4 h-4"}),"Locations (",X.length,")"]}),e.jsxs("button",{onClick:()=>y("positions"),className:`flex items-center gap-2 px-3 py-1.5 rounded-md text-sm font-medium transition-colors 144 ${v==="positions"?"bg-brand-500/20 text-brand-400":"text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"}`,children:[e.jsx(st,{className:"w-4 h-4"}),"Positions (",C.length,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm text-[var(--color-text-secondary)] cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:R,onChange:F=>E(F.target.checked),className:"rounded bg-[var(--color-bg-hover)] border-[var(--color-border-default)]"}),"Show archived"]}),e.jsxs("button",{onClick:k,className:`flex items-center gap-2 px-3 py-1.5 bg-brand-500 hover:bg-brand-400 145 text-[var(--color-text-primary)] rounded-lg text-sm font-medium`,children:[e.jsx(ot,{className:"w-4 h-4"}),"Add ",v==="locations"?"Location":"Position"]}),e.jsx("button",{onClick:t,className:"p-2 hover:bg-[var(--color-bg-hover)] rounded-lg text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] ml-2",children:e.jsx(de,{className:"w-5 h-5"})})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto divide-y divide-[var(--color-border-subtle)]",children:v==="locations"?X.length===0?e.jsxs("div",{className:"p-6 text-center",children:[e.jsx(Je,{className:"w-10 h-10 mx-auto mb-3 text-[var(--color-text-muted)]"}),e.jsx("p",{className:"text-[var(--color-text-secondary)] font-medium",children:"No Locations"}),e.jsx("p",{className:"text-sm text-[var(--color-text-muted)] mt-1",children:"Add your first location to start scheduling"})]}):X.map(F=>{var me;const re=I===F.id;return e.jsxs("div",{className:"p-4 hover:bg-[var(--color-bg-hover)] transition-colors",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-brand-500/20 flex items-center justify-center flex-shrink-0",children:e.jsx(Je,{className:"w-5 h-5 text-brand-400"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-[var(--color-text-primary)]",children:F.name}),e.jsx("span",{className:`px-2 py-0.5 rounded text-xs font-bold border ${ls(F.status)}`,children:F.status})]}),e.jsxs("div",{className:"flex items-center gap-3 text-sm text-[var(--color-text-secondary)] mt-0.5",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Aa,{className:"w-3 h-3"}),ns[F.timezone]||F.timezone]}),((me=F.address)==null?void 0:me.city)&&e.jsxs("span",{children:[F.address.city,", ",F.address.state]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:()=>f(F),className:"p-2 text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)] rounded-lg",children:e.jsx(qt,{className:"w-4 h-4"})}),F.status!=="archived"&&e.jsx("button",{onClick:()=>L(F.id),className:"p-2 text-[var(--color-text-secondary)] hover:text-amber-400 hover:bg-amber-500/10 rounded-lg",title:"Archive",children:e.jsx(La,{className:"w-4 h-4"})}),n&&e.jsx("button",{onClick:()=>z(F.id),className:"p-2 text-[var(--color-text-secondary)] hover:text-red-400 hover:bg-red-500/10 rounded-lg",title:"Delete",children:e.jsx(qe,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>$(re?null:F.id),className:"p-2 text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)] rounded-lg",children:re?e.jsx(Rr,{className:"w-4 h-4"}):e.jsx(vt,{className:"w-4 h-4"})})]})]}),re&&F.address&&e.jsxs("div",{className:"mt-4 pl-13 p-3 bg-[var(--color-bg-hover)] rounded-lg text-sm",children:[e.jsx("div",{className:"text-[var(--color-text-secondary)] text-xs uppercase mb-2",children:"Address"}),e.jsxs("div",{className:"text-[var(--color-text-primary)]",children:[F.address.street&&e.jsx("div",{children:F.address.street}),(F.address.city||F.address.state||F.address.postal_code)&&e.jsxs("div",{children:[F.address.city,F.address.city&&F.address.state?", ":"",F.address.state," ",F.address.postal_code]}),F.address.country&&e.jsx("div",{children:F.address.country})]})]})]},F.id)}):C.length===0?e.jsxs("div",{className:"p-6 text-center",children:[e.jsx(st,{className:"w-10 h-10 mx-auto mb-3 text-[var(--color-text-muted)]"}),e.jsx("p",{className:"text-[var(--color-text-secondary)] font-medium",children:"No Positions"}),e.jsx("p",{className:"text-sm text-[var(--color-text-muted)] mt-1",children:"Add job positions for shift assignments"})]}):C.map(F=>e.jsx("div",{className:"p-4 hover:bg-[var(--color-bg-hover)] transition-colors",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-purple-500/20 flex items-center justify-center flex-shrink-0",children:e.jsx(st,{className:"w-5 h-5 text-purple-400"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-[var(--color-text-primary)]",children:F.name}),e.jsx("span",{className:`px-2 py-0.5 rounded text-xs font-bold border ${ls(F.status)}`,children:F.status})]}),F.description&&e.jsx("p",{className:"text-sm text-[var(--color-text-secondary)] mt-0.5",children:F.description})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:()=>f(F),className:"p-2 text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)] rounded-lg",children:e.jsx(qt,{className:"w-4 h-4"})}),F.status!=="archived"&&e.jsx("button",{onClick:()=>L(F.id),className:"p-2 text-[var(--color-text-secondary)] hover:text-amber-400 hover:bg-amber-500/10 rounded-lg",title:"Archive",children:e.jsx(La,{className:"w-4 h-4"})}),u&&e.jsx("button",{onClick:()=>z(F.id),className:"p-2 text-[var(--color-text-secondary)] hover:text-red-400 hover:bg-red-500/10 rounded-lg",title:"Delete",children:e.jsx(qe,{className:"w-4 h-4"})})]})]})},F.id))}),p&&e.jsx("div",{className:"fixed inset-0 bg-slate-900/50 flex items-center justify-center z-50 backdrop-blur-sm p-4",children:e.jsxs("div",{className:"bg-[var(--color-bg-surface)] rounded-xl w-full max-w-lg shadow-2xl border border-[var(--color-border-subtle)]",children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-[var(--color-border-subtle)]",children:[e.jsxs("h2",{className:"text-lg font-bold text-[var(--color-text-primary)] flex items-center gap-2",children:[v==="locations"?e.jsx(Je,{className:"w-5 h-5 text-brand-400"}):e.jsx(st,{className:"w-5 h-5 text-purple-400"}),S?"Edit":"Add"," ",v==="locations"?"Location":"Position"]}),e.jsx("button",{onClick:()=>{N(!1),W()},className:"p-2 hover:bg-[var(--color-bg-hover)] rounded-lg text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]",children:e.jsx(de,{className:"w-5 h-5"})})]}),e.jsx("div",{className:"p-6 space-y-5",children:v==="locations"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-[var(--color-text-primary)] mb-2",children:"Location Name *"}),e.jsx("input",{type:"text",value:O.name,onChange:F=>D({...O,name:F.target.value}),placeholder:"e.g., Main Office, Downtown Branch",className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-4 py-2.5 146 text-[var(--color-text-primary)] placeholder-white/40 focus:outline-none focus:border-brand-500/50`})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-[var(--color-text-primary)] mb-2",children:[e.jsx(Aa,{className:"w-4 h-4 inline mr-1"}),"Timezone *"]}
146),e.jsx("select",{value:O.timezone,onChange:F=>D({...O,timezone:F.target.value}),className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-4 py-2.5 147 text-[var(--color-text-primary)] focus:outline-none focus:border-brand-500/50`,children:Ji.map(F=>e.jsx("option",{value:F,children:ns[F]},F))})]}),e.jsxs("div",{className:"border-t border-[var(--color-border-subtle)] pt-4",children:[e.jsx("label",{className:"block text-sm font-medium text-[var(--color-text-primary)] mb-2",children:"Address (optional)"}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("input",{type:"text",value:O.street,onChange:F=>D({...O,street:F.target.value}),placeholder:"Street Address",className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-4 py-2 148 text-[var(--color-text-primary)] placeholder-white/40 focus:outline-none focus:border-brand-500/50`}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsx("input",{type:"text",value:O.city,onChange:F=>D({...O,city:F.target.value}),placeholder:"City",className:`bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-4 py-2 149 text-[var(--color-text-primary)] placeholder-white/40 focus:outline-none focus:border-brand-500/50`}),e.jsx("input",{type:"text",value:O.state,onChange:F=>D({...O,state:F.target.value}),placeholder:"State",className:`bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-4 py-2 150 text-[var(--color-text-primary)] placeholder-white/40 focus:outline-none focus:border-brand-500/50`}),e.jsx("input",{type:"text",value:O.postal_code,onChange:F=>D({...O,postal_code:F.target.value}),placeholder:"ZIP",className:`bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-4 py-2 151 text-[var(--color-text-primary)] placeholder-white/40 focus:outline-none focus:border-brand-500/50`})]})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-[var(--color-text-primary)] mb-2",children:"Position Name *"}),e.jsx("input",{type:"text",value:b.name,onChange:F=>P({...b,name:F.target.value}),placeholder:"e.g., Manager, Team Lead, Staff",className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-4 py-2.5 152 text-[var(--color-text-primary)] placeholder-white/40 focus:outline-none focus:border-brand-500/50`})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-[var(--color-text-primary)] mb-2",children:"Description (optional)"}),e.jsx("textarea",{value:b.description,onChange:F=>P({...b,description:F.target.value}),placeholder:"Brief description of this position...",rows:3,className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-4 py-2.5 153 text-[var(--color-text-primary)] placeholder-white/40 focus:outline-none focus:border-brand-500/50 resize-none`})]})]})}),e.jsxs("div",{className:"flex items-center justify-end gap-3 px-6 py-4 border-t border-[var(--color-border-subtle)] bg-[var(--color-bg-hover)]",children:[e.jsx("button",{onClick:()=>{N(!1),W()},disabled:h,className:"px-4 py-2 text-[var(--color-text-primary)] hover:text-[var(--color-text-primary)] font-medium",children:"Cancel"}),e.jsx("button",{onClick:g,disabled:h||!Y,className:`px-5 py-2 bg-brand-500 hover:bg-brand-400 text-[var(--color-text-primary)] rounded-lg 154 font-medium disabled:opacity-50 flex items-center gap-2`,children:h?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-2 border-[var(--color-border-default)] border-t-transparent"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Te,{className:"w-4 h-4"}),S?"Save Changes":"Add"]})})]})]})}),h&&e.jsx("div",{className:"absolute inset-0 bg-slate-900/50 flex items-center justify-center rounded-xl",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-[var(--color-border-default)] border-t-transparent"})})]})})},at="hr_time_clock_entries",Yr="hr_time_clock_breaks",is="hr_overtime_rules",cs={daily_threshold_hours:8,weekly_threshold_hours:40,overtime_multiplier:1.5,double_time_threshold_hours:12,double_time_multiplier:2,seventh_day_overtime:!1};class Bc{resolveTenantId(){return(typeof window<"u"?window.localStorage.getItem("tenantId"):null)||null}async getActiveClockEntry(t){const r=A.getCurrentUser().tenantId,a=T(r,at),o=H(_,a),s=V(o,K("employee_id","==",t),K("status","==","active")),i=await Z(s);if(i.empty)return null;const n=i.docs[0];return{...n.data(),id:n.id}}async getTimeClockEntries(t,r,a){const o=A.getCurrentUser().tenantId,s=T(o,at),i=H(_,s),n=V(i,K("employee_id","==",t),K("clock_in_utc",">=",r),K("clock_in_utc","<=",a),ee("clock_in_utc","desc"));return(await Z(n)).docs.map(d=>({...d.data(),id:d.id}))}async getAllActiveClockedIn(){const t=A.getCurrentUser().tenantId,r=T(t,at),a=H(_,r),o=V(a,K("status","==","active"),ee("clock_in_utc","asc"));return(await Z(o)).docs.map(i=>({...i.data(),id:i.id}))}async clockIn(t){const r=A.getCurrentUser().tenantId;if(await this.getActiveClockEntry(t.employee_id))throw new Error("Employee is already clocked in");const o=T(r,at),s=H(_,o),i=new Date().toISOString(),n={tenant_id:r,employee_id:t.employee_id,location_id:t.location_id,position_id:t.position_id||null,shift_id:t.shift_id||null,clock_in_utc:i,clock_out_utc:null,status:"active",clock_in_location:t.location||null,clock_out_location:null,clock_in_ip:null,clock_out_ip:null,total_hours:null,regular_hours:null,overtime_hours:null,break_hours:null,notes:t.notes||null,adjustment_reason:null,adjusted_by_user_id:null,created_at:i,updated_at:i},c=await ie(s,n);return console.log("[HRTimeClockService] Clocked in:",c.id),{...n,id:c.id}}async clockOut(t,r){const a=A.getCurrentUser().tenantId,o=T(a,at),s=B(_,o,t),i=await oe(s);if(!i.exists())throw new Error("Time entry not found");const n={...i.data(),id:i.id};if(n.status!=="active")throw new Error("Entry is not active");await this.endActiveBreaks(t);const c=new Date().toISOString(),u=(await this.getBreaksForEntry(t)).reduce(($,R)=>$+(R.duration_minutes||0),0)/60,h=new Date(n.clock_in_utc),p=(new Date(c).getTime()-h.getTime())/(1e3*60)/60,N=p-u,S=await this.getOvertimeRules(),j=Math.min(N,S.daily_threshold_hours),I=Math.max(0,N-S.daily_threshold_hours);return await Q(s,{clock_out_utc:c,clock_out_location:(r==null?void 0:r.location)||null,status:"completed",total_hours:Math.round(p*100)/100,regular_hours:Math.round(j*100)/100,overtime_hours:Math.round(I*100)/100,break_hours:Math.round(u*100)/100,notes:r!=null&&r.notes?`${n.notes||""} 155${r.notes}`.trim():n.notes,updated_at:c}),console.log("[HRTimeClockService] Clocked out:",t),this.getTimeClockEntry(t)}async getTimeClockEntry(t){const r=A.getCurrentUser().tenantId,a=T(r,at),o=B(_,a,t),s=await oe(o);return s.exists()?{...s.data(),id:s.id}:null}async adjustTimeEntry(t,r){const a=A.getCurrentUser(),o=a.tenantId,s=T(o,at),i=B(_,s,t),n=await this.getTimeClockEntry(t);if(!n)return null;const c={adjustment_reason:r.reason,adjusted_by_user_id:a.id,status:"adjusted",updated_at:new Date().toISOString()};if(r.clock_in_utc&&(c.clock_in_utc=r.clock_in_utc),r.clock_out_utc&&(c.clock_out_utc=r.clock_out_utc),r.clock_in_utc||r.clock_out_utc){const d=new Date(r.clock_in_utc||n.clock_in_utc),m=r.clock_out_utc?new Date(r.clock_out_utc):n.clock_out_utc?new Date(n.clock_out_utc):null;if(m){const h=(m.getTime()-d.getTime())/6e4/60,v=n.break_hours||0,y=h-v,p=await this.getOvertimeRules();c.total_hours=Math.round(h*100)/100,c.regular_hours=Math.round(Math.min(y,p.daily_threshold_hours)*100)/100,c.overtime_hours=Math.round(Math.max(0,y-p.daily_threshold_hours)*100)/100}}return await Q(i,c),console.log("[HRTimeClockService] Adjusted time entry:",t),this.getTimeClockEntry(t)}async getBreaksForEntry(t){const r=A.getCurrentUser().tenantId,a=T(r,Yr),o=H(_,a),s=V(o,K("time_entry_id","==",t),ee("start_utc","asc"));return(await Z(s)).docs.map(n=>({...n.data(),id:n.id}))}async startBreak(t,r="unpaid"){const a=A.getCurrentUser().tenantId;if((await this.getBreaksForEntry(t)).find(u=>u.status==="active"))throw new Error("Already on break");const i=T(a,Yr),n=H(_,i),c=new Date().toISOString(),d={tenant_id:a,time_entry_id:t,break_type:r,start_utc:c,end_utc:null,status:"active",duration_minutes:null,notes:null,created_at:c},m=await ie(n,d);return console.log("[HRTimeClockService] Started break:",m.id),{...d,id:m.id}}async endBreak(t){const r=A.getCurrentUser().tenantId,a=T(r,Yr),o=B(_,a,t),s=await oe(o);if(!s.exists())throw new Error("Break not found");const i={...s.data(),id:s.id};if(i.status!=="active")throw new Error("Break is not active");const n=new Date().toISOString(),c=new Date(i.start_utc),d=Math.round((new Date(n).getTime()-c.getTime())/(1e3*60));return await Q(o,{end_utc:n,status:"completed",duration_minutes:d}),console.log("[HRTimeClockService] Ended break:",t),{...i,end_utc:n,status:"completed",duration_minutes:d}}async endActiveBreaks(t){const a=(await this.getBreaksForEntry(t)).filter(o=>o.status==="active");for(const o of a)await this.endBreak(o.id)}async getActiveBreak(t){return(await this.getBreaksForEntry(t)).find(a=>a.status==="active")||null}async getOvertimeRules(){const t=A.getCurrentUser().tenantId,r=T(t,is),a=H(_,r),o=await Z(a);if(o.empty)return{id:"default",tenant_id:t,...cs,created_at:new Date().toISOString(),updated_at:new Date().toISOString()};const s=o.docs[0];return{...s.data(),id:s.id}}async updateOvertimeRules(t){const r=A.getCurrentUser().tenantId,a=T(r,is),o=H(_,a),s=await Z(o),i=new Date().toISOString();if(s.empty){const c={tenant_id:r,...cs,...t,created_at:i,updated_at:i},d=await ie(o,c);return{...c,id:d.id}}const n=s.docs[0];return await Q(B(_,a,n.id),{...t,updated_at:i}),this.getOvertimeRules()}subscribeToActiveClockedIn(t){const r=this.resolveTenantId();if(!r)return t([]),()=>{};const a=T(r,at),o=H(_,a),s=V(o,K("status","==","active"),ee("clock_in_utc","asc"));return we(s,n=>{const c=n.docs.map(d=>({...d.data(),id:d.id}));t(c)},n=>{console.error("[HRTimeClockService] Subscription error:",n),t([])})}subscribeToEmployeeEntries(t,r,a,o){const s=this.resolveTenantId();if(!s)return o([]),()=>{};const i=T(s,at),n=H(_,i),c=V(n,K("employee_id","==",t),K("clock_in_utc",">=",r),K("clock_in_utc","<=",a),ee("clock_in_utc","desc"));return we(c,m=>{const u=m.docs.map(h=>({...h.data(),id:h.id}));o(u)},m=>{console.error("[HRTimeClockService] Subscription error:",m),o([])})}async getActiveClockStatus(t){const r=await this.getActiveClockEntry(t);if(!r)return{isClockedIn:!1,elapsedMinutes:0,breakMinutes:0};const a=await this.getBreaksForEntry(r.id),o=a.find(c=>c.status==="active"),s=a.filter(c=>c.status==="completed").reduce((c,d)=>c+(d.duration_minutes||0),0),i=Math.round((Date.now()-new Date(r.clock_in_utc).getTime())/(1e3*60));let n=s;return o&&(n+=Math.round((Date.now()-new Date(o.start_utc).getTime())/(1e3*60))),{isClockedIn:!0,currentEntry:r,activeBreak:o||void 0,elapsedMinutes:i,breakMinutes:n}}async getDailyTimeSummaries(t,r,a){const o=await this.getTimeClockEntries(t,r,a),s=new Map;o.forEach(n=>{const c=n.clock_in_utc.split("T")[0];s.has(c)||s.set(c,[]),s.get(c).push(n)});const i=[];
155return s.forEach((n,c)=>{const d=n.reduce((y,p)=>y+(p.total_hours||0),0),m=n.reduce((y,p)=>y+(p.regular_hours||0),0),u=n.reduce((y,p)=>y+(p.overtime_hours||0),0),h=n.reduce((y,p)=>y+(p.break_hours||0),0),v=n.some(y=>y.status==="missed_out"||y.status==="adjusted");i.push({date:c,entries:n,total_hours:Math.round(d*100)/100,regular_hours:Math.round(m*100)/100,overtime_hours:Math.round(u*100)/100,break_hours:Math.round(h*100)/100,has_issues:v,issue_type:n.find(y=>y.status==="missed_out")?"missed_out":null})}),i.sort((n,c)=>c.date.localeCompare(n.date)),i}async getWeeklyTotals(t,r){const a=new Date(r),o=new Date(a);o.setDate(o.getDate()+7);const i=(await this.getTimeClockEntries(t,a.toISOString(),o.toISOString())).filter(u=>u.status==="completed"||u.status==="adjusted"),c={total_hours:0,regular_hours:0,overtime_hours:0,break_hours:0,days_worked:new Set(i.map(u=>u.clock_in_utc.split("T")[0])).size};i.forEach(u=>{c.total_hours+=u.total_hours||0,c.break_hours+=u.break_hours||0});const d=await this.getOvertimeRules(),m=c.total_hours-c.break_hours;return c.regular_hours=Math.min(m,d.weekly_threshold_hours),c.overtime_hours=Math.max(0,m-d.weekly_threshold_hours),c.total_hours=Math.round(c.total_hours*100)/100,c.regular_hours=Math.round(c.regular_hours*100)/100,c.overtime_hours=Math.round(c.overtime_hours*100)/100,c.break_hours=Math.round(c.break_hours*100)/100,c}}const We=new Bc;function zc(l){const t=Math.floor(l/60),r=l%60;return`${t}h ${r}m`}function Pt(l){return`${l.toFixed(2)} hrs`}function Gr(l){return new Date(l).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function Wc(l){return new Date(l).toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"})}const Vc=({employees:l,locations:t,currentEmployeeId:r,isManager:a=!1,onAdjustEntry:o})=>{var g,L,z,X;const[s,i]=x.useState(r||""),[n,c]=x.useState(((g=t[0])==null?void 0:g.id)||""),[d,m]=x.useState(null),[u,h]=x.useState([]),[v,y]=x.useState(null),[p,N]=x.useState(!1),[S,j]=x.useState(null),[I,$]=x.useState(null),[R,E]=x.useState(0),O=x.useCallback(()=>{const C=new Date,Y=C.getDay(),F=C.getDate()-Y+(Y===0?-6:1),re=new Date(C.setDate(F));return re.setHours(0,0,0,0),re},[]),D=x.useCallback(async()=>{if(s){N(!0),j(null);try{const C=await We.getActiveClockStatus(s);m(C);const Y=O(),F=new Date(Y);F.setDate(F.getDate()+7);const re=await We.getDailyTimeSummaries(s,Y.toISOString(),F.toISOString());h(re);const me=await We.getWeeklyTotals(s,Y.toISOString());y(me)}catch(C){console.error("[TimeClockPanel] Failed to load data:",C),j("Failed to load time clock data")}finally{N(!1)}}},[s,O]);x.useEffect(()=>{D()},[D]),x.useEffect(()=>{if(!(d!=null&&d.isClockedIn)||!d.currentEntry)return;const C=()=>{const F=Math.round((Date.now()-new Date(d.currentEntry.clock_in_utc).getTime())/6e4);E(F)};C();const Y=setInterval(C,6e4);return()=>clearInterval(Y)},[d]);const b=async()=>{if(!(!s||!n)){N(!0),j(null);try{await We.clockIn({employee_id:s,location_id:n}),await D()}catch(C){console.error("[TimeClockPanel] Clock in failed:",C),j(C instanceof Error?C.message:"Failed to clock in")}finally{N(!1)}}},P=async()=>{if(d!=null&&d.currentEntry){N(!0),j(null);try{await We.clockOut(d.currentEntry.id),await D()}catch(C){console.error("[TimeClockPanel] Clock out failed:",C),j(C instanceof Error?C.message:"Failed to clock out")}finally{N(!1)}}},W=async(C="unpaid")=>{if(d!=null&&d.currentEntry){N(!0),j(null);try{await We.startBreak(d.currentEntry.id,C),await D()}catch(Y){console.error("[TimeClockPanel] Start break failed:",Y),j(Y instanceof Error?Y.message:"Failed to start break")}finally{N(!1)}}},k=async()=>{if(d!=null&&d.activeBreak){N(!0),j(null);try{await We.endBreak(d.activeBreak.id),await D()}catch(C){console.error("[TimeClockPanel] End break failed:",C),j(C instanceof Error?C.message:"Failed to end break")}finally{N(!1)}}},f=l.find(C=>C.id===s);return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-[var(--color-border-subtle)] bg-[var(--color-bg-hover)]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-brand-500/20 flex items-center justify-center",children:e.jsx(ve,{className:"w-5 h-5 text-brand-400"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-[var(--color-text-primary)]",children:"Time Clock"}),e.jsx("p",{className:"text-xs text-[var(--color-text-secondary)]",children:d!=null&&d.isClockedIn?"Currently clocked in":"Not clocked in"})]})]}),a&&l.length>0&&e.jsxs("select",{value:s,onChange:C=>i(C.target.value),className:`bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-3 py-1.5 156 text-sm text-[var(--color-text-primary)] focus:outline-none focus:border-brand-500/50`,children:[e.jsx("option",{value:"",children:"Select employee..."}),l.filter(C=>C.status==="Active").map(C=>e.jsxs("option",{value:C.id,children:[C.firstName," ",C.lastName]},C.id))]})]}),e.jsx("div",{className:"p-6",children:s?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"bg-[var(--color-bg-hover)] rounded-xl border border-[var(--color-border-subtle)] p-6 mb-6",children:[f&&e.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-brand-500/20 flex items-center justify-center",children:e.jsxs("span",{className:"text-lg font-bold text-brand-400",children:[(L=f.firstName)==null?void 0:L[0],(z=f.lastName)==null?void 0:z[0]]})}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-medium text-[var(--color-text-primary)]",children:[f.firstName," ",f.lastName]}),e.jsx("div",{className:"text-sm text-[var(--color-text-secondary)]",children:f.role})]})]}),d!=null&&d.isClockedIn&&d.currentEntry?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-4xl font-bold text-[var(--color-text-primary)] mb-1",children:zc(R)}),e.jsxs("div",{className:"text-sm text-[var(--color-text-secondary)]",children:["Clocked in at ",Gr(d.currentEntry.clock_in_utc)]}),d.activeBreak&&e.jsxs("div",{className:`mt-2 inline-flex items-center gap-1 px-3 py-1 bg-amber-500/20 157 text-amber-400 rounded-full text-sm`,children:[e.jsx(yr,{className:"w-4 h-4"}),"On break"]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm text-[var(--color-text-secondary)]",children:[e.jsx(Je,{className:"w-4 h-4"}),((X=t.find(C=>C.id===d.currentEntry.location_id))==null?void 0:X.name)||"Unknown location"]}),e.jsx("div",{className:"flex items-center justify-center gap-3 pt-4",children:d.activeBreak?e.jsxs("button",{onClick:k,disabled:p,className:`flex items-center gap-2 px-6 py-3 bg-amber-500 hover:bg-amber-400 158 text-[var(--color-text-primary)] rounded-xl font-medium disabled:opacity-50`,children:[e.jsx(yr,{className:"w-5 h-5"}),"End Break"]}):e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>W("unpaid"),disabled:p,className:`flex items-center gap-2 px-4 py-2.5 bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] 159 text-[var(--color-text-primary)] rounded-lg font-medium hover:bg-[var(--color-bg-active)] disabled:opacity-50`,children:[e.jsx(yr,{className:"w-4 h-4"}),"Break"]}),e.jsxs("button",{onClick:P,disabled:p,className:`flex items-center gap-2 px-6 py-3 bg-red-500 hover:bg-red-400 160 text-[var(--color-text-primary)] rounded-xl font-medium disabled:opacity-50`,children:[e.jsx(vs,{className:"w-5 h-5"}),"Clock Out"]})]})})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-4xl font-bold text-[var(--color-text-muted)] mb-1",children:"--:--"}),e.jsx("div",{className:"text-sm text-[var(--color-text-secondary)]",children:"Not currently clocked in"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm text-[var(--color-text-secondary)] mb-2",children:"Select Location"}),e.jsx("select",{value:n,onChange:C=>c(C.target.value),className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-4 py-2.5 161 text-[var(--color-text-primary)] focus:outline-none focus:border-brand-500/50`,children:t.map(C=>e.jsx("option",{value:C.id,children:C.name},C.id))})]}),e.jsx("div",{className:"flex justify-center pt-4",children:e.jsxs("button",{onClick:b,disabled:p||!n,className:`flex items-center gap-2 px-8 py-4 bg-emerald-500 hover:bg-emerald-400 162 text-[var(--color-text-primary)] rounded-xl font-bold text-lg disabled:opacity-50`,children:[e.jsx(pn,{className:"w-6 h-6"}),"Clock In"]})})]}),S&&e.jsxs("div",{className:`mt-4 flex items-center gap-2 p-3 bg-red-500/10 border border-red-500/20 163 rounded-lg text-red-400 text-sm`,children:[e.jsx(Ve,{className:"w-4 h-4"}),S]})]}),v&&e.jsxs("div",{className:"bg-[var(--color-bg-hover)] rounded-xl border border-[var(--color-border-subtle)] p-4 mb-6",children:[e.jsxs("h4",{className:"text-sm font-medium text-[var(--color-text-primary)] mb-3 flex items-center gap-2",children:[e.jsx(be,{className:"w-4 h-4"}),"This Week"]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-lg font-bold text-[var(--color-text-primary)]",children:v.days_worked}),e.jsx("div",{className:"text-xs text-[var(--color-text-secondary)]",children:"Days"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-lg font-bold text-[var(--color-text-primary)]",children:Pt(v.total_hours)}),e.jsx("div",{className:"text-xs text-[var(--color-text-secondary)]",children:"Total"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-lg font-bold text-[var(--color-text-primary)]",children:Pt(v.regular_hours)}),e.jsx("div",{className:"text-xs text-[var(--color-text-secondary)]",children:"Regular"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-lg font-bold text-amber-400",children:Pt(v.overtime_hours)}),e.jsx("div",{className:"text-xs text-[var(--color-text-secondary)]",children:"Overtime"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium text-[var(--color-text-primary)] mb-3",children:"Recent Time Entries"}),u.length===0?e.jsx("div",{className:"text-center py-6 text-[var(--color-text-secondary)] text-sm",children:"No time entries this week"}):u.map(C=>e.jsxs("div",{className:"bg-[var(--color-bg-hover)] rounded-lg border border-[var(--color-border-subtle)]",children:[e.jsxs("button",{onClick:()=>$(I===C.date?null:C.date),className:"w-full flex items-center justify-between p-3 hover:bg-[var(--color-bg-hover)]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"text-sm",children:[e.jsx("div",{className:"font-medium text-[var(--color-text-primary)]",children:Wc(C.date+"T00:00:00")}),e.jsxs("div",{className:"text-xs text-[var(--color-text-secondary)]",children:[C.entr
163ies.length," entries"]})]}),C.has_issues&&e.jsx("div",{className:"w-2 h-2 rounded-full bg-amber-500",title:"Needs attention"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"text-sm font-medium text-[var(--color-text-primary)]",children:Pt(C.total_hours)}),C.overtime_hours>0&&e.jsxs("div",{className:"text-xs text-amber-400",children:["+",Pt(C.overtime_hours)," OT"]})]}),I===C.date?e.jsx(Rr,{className:"w-4 h-4 text-[var(--color-text-secondary)]"}):e.jsx(vt,{className:"w-4 h-4 text-[var(--color-text-secondary)]"})]})]}),I===C.date&&e.jsx("div",{className:"border-t border-[var(--color-border-subtle)] p-3 space-y-2",children:C.entries.map(Y=>e.jsxs("div",{className:"flex items-center justify-between p-2 bg-[var(--color-bg-hover)] rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`w-2 h-2 rounded-full ${Y.status==="completed"?"bg-emerald-500":Y.status==="active"?"bg-[var(--color-primary)]":Y.status==="adjusted"?"bg-amber-500":"bg-red-500"}`}),e.jsxs("div",{children:[e.jsxs("div",{className:"text-sm text-[var(--color-text-primary)]",children:[Gr(Y.clock_in_utc),Y.clock_out_utc&&` - ${Gr(Y.clock_out_utc)}`]}),e.jsx("div",{className:"text-xs text-[var(--color-text-secondary)]",children:Y.status==="active"?"Currently working":Y.status==="adjusted"?"Adjusted":Y.status==="missed_out"?"Missed clock out":`${Pt(Y.total_hours||0)}`})]})]}),a&&o&&Y.status!=="active"&&e.jsx("button",{onClick:()=>o(Y.id),className:"p-1.5 text-[var(--color-text-muted)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)] rounded",children:e.jsx(qt,{className:"w-4 h-4"})})]},Y.id))})]},C.date))]})]}):e.jsxs("div",{className:"text-center py-10 text-[var(--color-text-secondary)]",children:[e.jsx(tt,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),e.jsx("p",{children:"Select an employee to view time clock"})]})}),p&&e.jsx("div",{className:"absolute inset-0 bg-slate-900/50 flex items-center justify-center",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-[var(--color-border-default)] border-t-transparent"})})]})};function Kc(l){const t=Math.floor(l/60),r=l%60;return t>0?`${t}h ${r}m`:`${r}m`}function Yc(l){return new Date(l).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}const Gc=({employees:l,locations:t,onSelectEmployee:r})=>{const[a,o]=x.useState([]),[s,i]=x.useState(!0),[n,c]=x.useState(null),[d,m]=x.useState(new Date),u=async()=>{try{i(!0),c(null);const v=await We.getAllActiveClockedIn(),y=await Promise.all(v.map(async p=>{const N=l.find($=>$.id===p.employee_id),S=t.find($=>$.id===p.location_id),j=Math.round((Date.now()-new Date(p.clock_in_utc).getTime())/(1e3*60)),I=await We.getActiveBreak(p.id);return{...p,employee:N,location:S,elapsedMinutes:j,isOnBreak:!!I}}));o(y),m(new Date)}catch(v){console.error("[ActiveClockDashboard] Failed to load entries:",v),c("Failed to load active clock entries")}finally{i(!1)}};x.useEffect(()=>We.subscribeToActiveClockedIn(async y=>{const p=await Promise.all(y.map(async N=>{const S=l.find(R=>R.id===N.employee_id),j=t.find(R=>R.id===N.location_id),I=Math.round((Date.now()-new Date(N.clock_in_utc).getTime())/(1e3*60)),$=await We.getActiveBreak(N.id);return{...N,employee:S,location:j,elapsedMinutes:I,isOnBreak:!!$}}));o(p),m(new Date),i(!1)}),[l,t]),x.useEffect(()=>{const v=setInterval(()=>{o(y=>y.map(p=>({...p,elapsedMinutes:Math.round((Date.now()-new Date(p.clock_in_utc).getTime())/6e4)})))},6e4);return()=>clearInterval(v)},[]);const h=a.reduce((v,y)=>{const p=y.location_id;return v[p]||(v[p]={location:y.location,entries:[]}),v[p].entries.push(y),v},{});return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-[var(--color-border-subtle)] bg-[var(--color-bg-hover)]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-emerald-500/20 flex items-center justify-center",children:e.jsx(Re,{className:"w-5 h-5 text-emerald-400"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-[var(--color-text-primary)]",children:"Active Now"}),e.jsxs("p",{className:"text-xs text-[var(--color-text-secondary)]",children:[a.length," employee",a.length!==1?"s":""," clocked in"]})]})]}),e.jsxs("button",{onClick:u,disabled:s,className:`flex items-center gap-2 px-3 py-1.5 bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] 164 rounded-lg text-sm text-[var(--color-text-primary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-active)] disabled:opacity-50`,children:[e.jsx(Xe,{className:`w-4 h-4 ${s?"animate-spin":""}`}),"Refresh"]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-4",children:[n&&e.jsxs("div",{className:`flex items-center gap-2 p-3 bg-red-500/10 border border-red-500/20 165 rounded-lg text-red-400 text-sm mb-4`,children:[e.jsx(Ve,{className:"w-4 h-4"}),n]}),a.length===0&&!s?e.jsxs("div",{className:"text-center py-10 text-[var(--color-text-secondary)]",children:[e.jsx(ve,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),e.jsx("p",{children:"No employees currently clocked in"})]}):e.jsx("div",{className:"space-y-6",children:Object.entries(h).map(([v,{location:y,entries:p}])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Je,{className:"w-4 h-4 text-[var(--color-text-secondary)]"}),e.jsx("span",{className:"text-sm font-medium text-[var(--color-text-primary)]",children:(y==null?void 0:y.name)||"Unknown Location"}),e.jsxs("span",{className:"text-xs text-[var(--color-text-muted)]",children:["(",p.length,")"]})]}),e.jsx("div",{className:"space-y-2",children:p.map(N=>{var S,j,I,$,R,E,O;return e.jsxs("div",{onClick:()=>r==null?void 0:r(N.employee_id),className:`flex items-center justify-between p-3 bg-[var(--color-bg-hover)] rounded-lg 166 border border-[var(--color-border-subtle)] hover:bg-[var(--color-bg-hover)] cursor-pointer transition-colors 167 ${N.isOnBreak?"border-amber-500/30":""}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-brand-500/20 flex items-center justify-center",children:e.jsxs("span",{className:"text-sm font-bold text-brand-400",children:[(j=(S=N.employee)==null?void 0:S.firstName)==null?void 0:j[0],($=(I=N.employee)==null?void 0:I.lastName)==null?void 0:$[0]]})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-medium text-[var(--color-text-primary)]",children:[(R=N.employee)==null?void 0:R.firstName," ",(E=N.employee)==null?void 0:E.lastName]}),N.isOnBreak&&e.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 168 bg-amber-500/20 text-amber-400 rounded text-xs`,children:[e.jsx(yr,{className:"w-3 h-3"}),"Break"]})]}),e.jsxs("div",{className:"text-xs text-[var(--color-text-secondary)]",children:[(O=N.employee)==null?void 0:O.role," ⢠In at ",Yc(N.clock_in_utc)]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:`text-lg font-bold ${N.elapsedMinutes>480?"text-amber-400":"text-[var(--color-text-primary)]"}`,children:Kc(N.elapsedMinutes)}),e.jsx("div",{className:"text-xs text-[var(--color-text-muted)]",children:"elapsed"})]}),e.jsx(nt,{className:"w-4 h-4 text-[var(--color-text-muted)]"})]})]},N.id)})})]},v))})]}),e.jsxs("div",{className:"px-4 py-2 border-t border-[var(--color-border-subtle)] bg-[var(--color-bg-hover)] text-xs text-[var(--color-text-muted)] text-center",children:["Last updated: ",d.toLocaleTimeString()]}),s&&a.length===0&&e.jsx("div",{className:"absolute inset-0 bg-slate-900/50 flex items-center justify-center",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-[var(--color-border-default)] border-t-transparent"})})]})},Qc={1:"Needs Improvement",2:"Below Expectations",3:"Meets Expectations",4:"Exceeds Expectations",5:"Outstanding"},Zc=[{name:"Job Knowledge",description:"Understanding of role responsibilities and technical skills"},{name:"Quality of Work",description:"Accuracy, thoroughness, and attention to detail"},{name:"Productivity",description:"Volume of work and ability to meet deadlines"},{name:"Communication",description:"Verbal and written communication effectiveness"},{name:"Teamwork",description:"Collaboration with colleagues and contribution to team goals"},{name:"Initiative",description:"Self-motivation and proactive problem-solving"},{name:"Reliability",description:"Attendance, punctuality, and dependability"},{name:"Adaptability",description:"Flexibility and ability to handle change"}],ze="hr_performance_reviews",Qr="hr_review_templates";class Jc{resolveTenantId(){return(typeof window<"u"?window.localStorage.getItem("tenantId"):null)||null}async getReviews(t){const r=A.getCurrentUser().tenantId,a=T(r,ze),o=H(_,a),s=V(o,ee("updated_at","desc"));let n=(await Z(s)).docs.map(c=>({...c.data(),id:c.id}));return t!=null&&t.employee_id&&(n=n.filter(c=>c.employee_id===t.employee_id)),t!=null&&t.reviewer_id&&(n=n.filter(c=>c.reviewer_id===t.reviewer_id)),t!=null&&t.status&&(n=n.filter(c=>c.status===t.status)),t!=null&&t.review_cycle&&(n=n.filter(c=>c.review_cycle===t.review_cycle)),n}async getReview(t){const r=A.getCurrentUser().tenantId,a=T(r,ze),o=B(_,a,t),s=await oe(o);return s.exists()?{...s.data(),id:s.id}:null}async createReview(t){const r=A.getCurrentUser().tenantId,a=T(r,ze),o=H(_,a);let s=Zc;if(t.template_id){const m=await this.getTemplate(t.template_id);m&&(s=m.categories.map(u=>({name:u.name,description:u.description||"",weight:u.weight})))}const i=s.map(m=>({category:m.name,self_rating:null,manager_rating:null,weight:m.weight,comments:null})),n=new Date().toISOString(),c={tenant_id:r,employee_id:t.employee_id,reviewer_id:t.reviewer_id,review_cycle:t.review_cycle,review_period_start:t.review_period_start,review_period_end:t.review_period_end,status:"draft",overall_rating:null,self_rating:null,ratings:i,manager_comments:null,employee_comments:null,strengths:null,areas_for_improvement:null,development_plan:null,goals_reviewed:[],goals_for_next_period:[],meeting_scheduled_at:null,meeting_completed_at:null,meeting_notes:null,acknowledged_at:null,acknowledged_by_employee:!1,employee_acknowledgement_notes:null,compensation_recommendation:null,created_at:n,updated_at:n},d=await ie(o,c);return console.log("[HRReviewService] Created review:",d.id),{...c,id:d.id}}async startSelfReview(t){const r=A.getCurrentUser().tenantId,a=T(r,ze),o=B(_,a,t),s=await this.getReview(t);if(!s)return null;if(s.status!=="draft")throw new Error("Review must be in draft status to start self-review");return await Q(o,{status:"self_review_pending",updated_at:new Date().toISOString()}),console.log("[HRReviewService] Started self-review:",t),this.getReview(t)}async submitSelfReview(t,r){const a=A.getCurrentUser().tenantId,o=T(a,ze),s=B(_,o,t),i=await this.getReview(t);if(!i)return null;if(i.status!=="self_review_pending")throw new Error("Review is not awaiting self-review");const n=i.ratings.map(d=>{const m=r.ratings.find(u=>u.category===d.category);return m?{...d,self_rating:m.self_rating,comments:m.comments||d.comments}:d}),c=i.goals_reviewed.map(d=>{var u;const m=(u=r.goals_self_assessment)==null?void 0:u.find(h=>h.goal_id===d.id);return m?{...d,self_assessment:m.self_assessment,progress_percentage:m.progress_percentage}:d});return await Q(s,{self_rating:r.self_rating,ratings:n,employee_comments:r.employee_comments||null,goals_reviewed:c,status:"self_review_complete",updated_at:new Date().toISOString()}),console.log("[HRReviewService] Submitted self-review:",t),this.getReview(t)}async submitManagerReview(t,r){const a=A.getCurrentUser().tenantId,o=T(a,ze),s=B(_,o,t),i=await this.getReview(t);if(!i)return null;const n=i.ratings.map(m=>{const u=r.ratings.find(h=>h.category===m.category);return u?{...m,manager_rating:u.manager_rating,comments:u.comments||m.comments}:m}),c=i.goals_reviewed.map(m=>{var h;const u=(h=r.goals_assessment)==null?void 0:h.find(v=>v.goal_id===m.id);return u?{...m,manager_assessment:u.manager_assessment,status:u.status}:m}),d=(r.goals_for_next_period||[]).map((m,u)=>({...m,id:`goal-${Date.now()}-${u}`,manager_assessment:null,self_assessment:null}));return await Q(s,{overall_rating:r.overall_rating,ratings:n,manager_comments:r.manager_comments||null,strengths:r.strengths||null,areas_for_improvement:r.areas_for_improvement||null,development_plan:r.development_plan||null,goals_reviewed:c,goals_for_next_period:d,compensation_recommendation:r.compensation_recommendation||null,status:"manager_review_pending",updated_at:new Date().toISOString()}),console.log("[HRReviewService] Submitted manager review:",t),this.getReview(t)}async scheduleMeeting(t,r){const a=A.getCurrentUser().tenantId,o=T(a,ze),s=B(_,o,t);return await Q(s,{meeting_scheduled_at:r,status:"meeting_scheduled",updated_at:new Date().toISOString()}),console.log("[HRReviewService] Scheduled meeting:",t),this.getReview(t)}async completeReview(t,r){const a=A.getCurrentUser().tenantId,o=T(a,ze),s=B(_,o,t),i=new Date().toISOString();return await Q(s,{meeting_completed_at:i,meeting_notes:r||null,status:"completed",updated_at:i}),console.log("[HRReviewService] Completed review:",t),this.getReview(t)}async acknowledgeReview(t,r){const a=A.getCurrentUser().tenantId,o=T(a,ze),s=B(_,o,t),i=await this.getReview(t);if(!i)return null;if(i.status!=="completed")throw new Error("Review must be completed before acknowledgement");const n=new Date().toISOString();return await Q(s,{acknowledged_at:n,acknowledged_by_employee:!0,employee_acknowledgement_notes:r||null,status:"acknowledged",updated_at:n}),console.log("[HRReviewService] Acknowledged review:",t),this.getReview(t)}async addGoalsToReview(t,r){const a=A.getCurrentUser().tenantId,o=T(a,ze),s=B(_,o,t),i=await this.getReview(t);if(!i)return null;const n=r.map((c,d)=>({...c,id:`goal-${Date.now()}-${d}`,manager_assessment:null,self_assessment:null}));return await Q(s,{goals_reviewed:[...i.goals_reviewed,...n],updated_at:new Date().toISOString()}),this.getReview(t)}async getTemplates(){const t=A.getCurrentUser().tenantId,r=T(t,Qr),a=H(_,r),o=V(a,K("is_active","==",!0));return(await Z(o)).docs.map(i=>({...i.data(),id:i.id}))}async getTemplate(t){const r=A.getCurrentUser().tenantId,a=T(r,Qr),o=B(_,a,t),s=await oe(o);return s.exists()?{...s.data(),id:s.id}:null}async createTemplate(t,r){const a=A.getCurrentUser().tenantId,o=T(a,Qr),s=H(_,o),i=new Date().toISOString(),n={tenant_id:a,name:t,description:null,categories:r,is_default:!1,is_active:!0,created_at:i,updated_at:i},c=await ie(s,n);return{...n,id:c.id}}subscribeToReviews(t,r){const a=this.resolveTenantId();if(!a)return t([]),()=>{};const o=T(a,ze),s=H(_,o),i=V(s,ee("updated_at","desc"));return we(i,c=>{let d=c.docs.map(m=>({...m.data(),id:m.id}));r!=null&&r.employee_id&&(d=d.filter(m=>m.employee_id===r.employee_id)),r!=null&&r.reviewer_id&&(d=d.filter(m=>m.reviewer_id===r.reviewer_id)),t(d)},c=>{console.error("[HRReviewService] Subscription error:",c),t([])})}async getEmployeeReviewStats(t){var i;const a=(await this.getReviews({employee_id:t})).filter(n=>n.status==="completed"||n.status==="acknowledged"),o=a.filter(n=>n.overall_rating).map(n=>n.overall_rating),s=a.reduce((n,c)=>(n[c.review_cycle]=(n[c.review_cycle]||0)+1,n),{});return{total_reviews:a.length,average_rating:o.length>0?Math.round(o.reduce((n,c)=>n+c,0)/o.length*10)/10:null,last_review_date:((i=a[0])==null?void 0:i.updated_at)||null,reviews_by_cycle:s}}async getPendingReviewsForManager(t){return(await this.getReviews({reviewer_id:t})).filter(a=>a.status!=="completed"&&a.status!=="acknowledged")}calculateOverallRating(t){const r=t.filter(s=>s.manager_rating);if(r.length===0)return null;if(r.some(s=>s.weight&&s.weight>0)){const s=r.reduce((n,c)=>n+(c.weight||1),0),i=r.reduce((n,c)=>n+c.manager_rating*(c.weight||1),0);return Math.round(i/s*10)/10}const o=r.reduce((s,i)=>s+i.manager_rating,0);return Math.round(o/r.length*10)/10}}const ta=new Jc;function Xc(l){switch(l){case"draft":return"bg-gray-500/20 text-[var(--color-text-muted)]";ca
168se"self_review_pending":return"bg-amber-500/20 text-amber-300";case"self_review_complete":return"bg-[var(--color-primary-subtle)] text-[var(--color-primary)]";case"manager_review_pending":return"bg-purple-500/20 text-purple-300";case"meeting_scheduled":return"bg-cyan-500/20 text-cyan-300";case"completed":return"bg-emerald-500/20 text-emerald-300";case"acknowledged":return"bg-emerald-500/20 text-emerald-400";default:return"bg-[var(--color-bg-hover)] text-[var(--color-text-secondary)]"}}function ed(l){switch(l){case"draft":return"Draft";case"self_review_pending":return"Awaiting Self-Review";case"self_review_complete":return"Self-Review Complete";case"manager_review_pending":return"Manager Review";case"meeting_scheduled":return"Meeting Scheduled";case"completed":return"Completed";case"acknowledged":return"Acknowledged";default:return l}}function td(l){switch(l){case"annual":return"Annual";case"semi_annual":return"Semi-Annual";case"quarterly":return"Quarterly";case"probationary":return"Probationary";case"ad_hoc":return"Ad Hoc";default:return l}}function rd(l){return new Date(l).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function ad({rating:l}){return l?e.jsxs("div",{className:"flex items-center gap-1",children:[[1,2,3,4,5].map(t=>e.jsx(hs,{className:`w-4 h-4 ${t<=l?"text-amber-400 fill-amber-400":"text-white/20"}`},t)),e.jsxs("span",{className:"text-xs text-[var(--color-text-secondary)] ml-1",children:["(",Qc[l],")"]})]}):e.jsx("span",{className:"text-[var(--color-text-muted)] text-sm",children:"Not rated"})}const sd=({employees:l,currentUserId:t,isManager:r=!1,onCreateReview:a,onSelectReview:o})=>{const[s,i]=x.useState([]),[n,c]=x.useState(!0),[d,m]=x.useState(null),[u,h]=x.useState(""),[v,y]=x.useState("all"),[p,N]=x.useState("all");x.useEffect(()=>ta.subscribeToReviews(O=>{i(O),c(!1)}),[]);const S=s.filter(E=>{if(v!=="all"&&E.status!==v||p!=="all"&&E.review_cycle!==p)return!1;if(u){const O=l.find(b=>b.id===E.employee_id);if(!(O?`${O.firstName} ${O.lastName}`.toLowerCase():"").includes(u.toLowerCase()))return!1}return!0}),j=s.filter(E=>["draft","self_review_pending","self_review_complete","manager_review_pending","meeting_scheduled"].includes(E.status)),I=s.filter(E=>["completed","acknowledged"].includes(E.status)),$=E=>{const O=l.find(D=>D.id===E);return O?`${O.firstName} ${O.lastName}`:"Unknown"},R=E=>{const O=l.find(D=>D.id===E);return O?`${O.firstName} ${O.lastName}`:"Unknown"};return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-[var(--color-border-subtle)] bg-[var(--color-bg-hover)]",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-amber-500/20 flex items-center justify-center",children:e.jsx(sr,{className:"w-5 h-5 text-amber-400"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-[var(--color-text-primary)]",children:"Performance Reviews"}),e.jsxs("p",{className:"text-xs text-[var(--color-text-secondary)]",children:[S.length," review",S.length!==1?"s":""]})]})]}),r&&a&&e.jsxs("button",{onClick:a,className:`flex items-center gap-2 px-4 py-2 bg-brand-500 hover:bg-brand-400 169 text-[var(--color-text-primary)] rounded-lg font-medium text-sm`,children:[e.jsx(ot,{className:"w-4 h-4"}),"New Review"]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsxs("div",{className:"p-3 bg-[var(--color-bg-hover)] rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[var(--color-text-secondary)] text-xs mb-1",children:[e.jsx(ve,{className:"w-3 h-3"}),"In Progress"]}),e.jsx("div",{className:"text-xl font-bold text-[var(--color-text-primary)]",children:j.length})]}),e.jsxs("div",{className:"p-3 bg-[var(--color-bg-hover)] rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[var(--color-text-secondary)] text-xs mb-1",children:[e.jsx(Rt,{className:"w-3 h-3"}),"Completed"]}),e.jsx("div",{className:"text-xl font-bold text-emerald-400",children:I.length})]}),e.jsxs("div",{className:"p-3 bg-[var(--color-bg-hover)] rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[var(--color-text-secondary)] text-xs mb-1",children:[e.jsx(hs,{className:"w-3 h-3"}),"Total"]}),e.jsx("div",{className:"text-xl font-bold text-[var(--color-text-primary)]",children:s.length})]})]})]}),e.jsxs("div",{className:"px-4 py-3 border-b border-[var(--color-border-subtle)] flex items-center gap-3",children:[e.jsxs("div",{className:"relative flex-1 max-w-xs",children:[e.jsx(rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-[var(--color-text-muted)]"}),e.jsx("input",{type:"text",value:u,onChange:E=>h(E.target.value),placeholder:"Search by employee...",className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg pl-10 pr-4 py-2 170 text-sm text-[var(--color-text-primary)] placeholder-white/40 focus:outline-none focus:border-brand-500/50`})]}
170),e.jsxs("select",{value:v,onChange:E=>y(E.target.value),className:`bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-3 py-2 171 text-sm text-[var(--color-text-primary)] focus:outline-none focus:border-brand-500/50`,children:[e.jsx("option",{value:"all",children:"All Statuses"}),e.jsx("option",{value:"draft",children:"Draft"}),e.jsx("option",{value:"self_review_pending",children:"Awaiting Self-Review"}),e.jsx("option",{value:"self_review_complete",children:"Self-Review Complete"}),e.jsx("option",{value:"manager_review_pending",children:"Manager Review"}),e.jsx("option",{value:"meeting_scheduled",children:"Meeting Scheduled"}),e.jsx("option",{value:"completed",children:"Completed"}),e.jsx("option",{value:"acknowledged",children:"Acknowledged"})]}),e.jsxs("select",{value:p,onChange:E=>N(E.target.value),className:`bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-3 py-2 172 text-sm text-[var(--color-text-primary)] focus:outline-none focus:border-brand-500/50`,children:[e.jsx("option",{value:"all",children:"All Cycles"}),e.jsx("option",{value:"annual",children:"Annual"}),e.jsx("option",{value:"semi_annual",children:"Semi-Annual"}),e.jsx("option",{value:"quarterly",children:"Quarterly"}),e.jsx("option",{value:"probationary",children:"Probationary"}),e.jsx("option",{value:"ad_hoc",children:"Ad Hoc"})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto divide-y divide-[var(--color-border-subtle)]",children:n?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-[var(--color-border-default)] border-t-transparent"})}):d?e.jsxs("div",{className:"p-4 text-center",children:[e.jsx(Ve,{className:"w-10 h-10 mx-auto mb-3 text-red-400"}),e.jsx("p",{className:"text-red-400",children:d})]}):S.length===0?e.jsxs("div",{className:"p-6 text-center",children:[e.jsx(et,{className:"w-12 h-12 mx-auto mb-3 text-[var(--color-text-muted)]"}),e.jsx("p",{className:"text-[var(--color-text-secondary)] font-medium",children:"No Reviews Found"}),e.jsx("p",{className:"text-sm text-[var(--color-text-muted)] mt-1",children:u||v!=="all"||p!=="all"?"Try adjusting your filters":r?"Create a new review to get started":"No reviews available"})]}):S.map(E=>e.jsx("div",{onClick:()=>o==null?void 0:o(E),className:"p-4 hover:bg-[var(--color-bg-hover)] cursor-pointer transition-colors",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-brand-500/20 flex items-center justify-center",children:e.jsx("span",{className:"text-lg font-bold text-brand-400",children:$(E.employee_id).split(" ").map(O=>O[0]).join("")})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-[var(--color-text-primary)]",children:$(E.employee_id)}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-[var(--color-text-secondary)]",children:[e.jsx(tt,{className:"w-3 h-3"}),"Reviewer: ",R(E.reviewer_id)]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("span",{className:`px-2 py-0.5 rounded text-xs font-medium ${Xc(E.status)}`,children:ed(E.status)}),e.jsx("span",{className:"text-xs text-[var(--color-text-muted)]",children:td(E.review_cycle)})]})]})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-right",children:[e.jsx(ad,{rating:E.overall_rating}),e.jsxs("div",{className:"text-xs text-[var(--color-text-muted)] mt-1",children:[e.jsx(be,{className:"w-3 h-3 inline mr-1"}),rd(E.review_period_end)]})]}),e.jsx(nt,{className:"w-5 h-5 text-[var(--color-text-muted)]"})]})]})},E.id))})]})},od=[{value:"annual",label:"Annual Review"},{value:"semi_annual",label:"Semi-Annual Review"},{value:"quarterly",label:"Quarterly Review"},{value:"probationary",label:"Probationary Review"},{value:"ad_hoc",label:"Ad Hoc Review"}],nd=({isOpen:l,onClose:t,onCreated:r,employees:a,currentUserId:o})=>{const[s,i]=x.useState(""),[n,c]=x.useState(o),[d,m]=x.useState("annual"),[u,h]=x.useState(""),[v,y]=x.useState(""),[p,N]=x.useState([]),[S,j]=x.useState(""),[I,$]=x.use
172State(!1),[R,E]=x.useState(null);x.useEffect(()=>{l&&ta.getTemplates().then(N)},[l]),x.useEffect(()=>{const b=new Date;let P,W;switch(d){case"annual":P=new Date(b.getFullYear()-1,b.getMonth(),1),W=new Date(b.getFullYear(),b.getMonth(),0);break;case"semi_annual":b.getMonth()<6?(P=new Date(b.getFullYear()-1,6,1),W=new Date(b.getFullYear()-1,11,31)):(P=new Date(b.getFullYear(),0,1),W=new Date(b.getFullYear(),5,30));break;case"quarterly":const k=Math.floor(b.getMonth()/3),f=k===0?3:k-1,g=k===0?b.getFullYear()-1:b.getFullYear();P=new Date(g,f*3,1),W=new Date(g,f*3+3,0);break;case"probationary":P=new Date(b),P.setMonth(P.getMonth()-3),W=b;break;default:P=new Date(b),P.setMonth(P.getMonth()-1),W=b}h(P.toISOString().split("T")[0]),y(W.toISOString().split("T")[0])},[d]);const O=async()=>{if(!s){E("Please select an employee");return}if(!n){E("Please select a reviewer");return}if(!u||!v){E("Please set the review period");return}$(!0),E(null);try{await ta.createReview({employee_id:s,reviewer_id:n,review_cycle:d,review_period_start:new Date(u).toISOString(),review_period_end:new Date(v).toISOString(),template_id:S||void 0}),r(),t(),i(""),m("annual"),j("")}catch(b){console.error("[CreateReviewModal] Failed to create review:",b),E(b instanceof Error?b.message:"Failed to create review")}finally{$(!1)}};if(!l)return null;const D=a.filter(b=>b.status==="Active");return e.jsx("div",{className:"fixed inset-0 bg-slate-900/50 flex items-center justify-center z-50 backdrop-blur-sm p-4",children:e.jsxs("div",{className:"bg-[var(--color-bg-surface)] rounded-xl w-full max-w-lg shadow-2xl border border-[var(--color-border-subtle)]",children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-[var(--color-border-subtle)]",children:[e.jsxs("h2",{className:"text-lg font-bold text-[var(--color-text-primary)] flex items-center gap-2",children:[e.jsx(sr,{className:"w-5 h-5 text-amber-400"}),"Create Performance Review"]}),e.jsx("button",{onClick:t,className:"p-2 hover:bg-[var(--color-bg-hover)] rounded-lg text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]",children:e.jsx(de,{className:"w-5 h-5"})})]}),e.jsxs("div",{className:"p-6 space-y-5",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-[var(--color-text-primary)] mb-2",children:[e.jsx(tt,{className:"w-4 h-4 inline mr-1"}),"Employee *"]}),e.jsxs("select",{value:s,onChange:b=>i(b.target.value),className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-4 py-2.5 173 text-[var(--color-text-primary)] focus:outline-none focus:border-brand-500/50`,children:[e.jsx("option",{value:"",children:"Select employee..."}),D.map(b=>e.jsxs("option",{value:b.id,children:[b.firstName," ",b.lastName," - ",b.role]},b.id))]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-[var(--color-text-primary)] mb-2",children:[e.jsx(tt,{className:"w-4 h-4 inline mr-1"}),"Reviewer *"]}),e.jsxs("select",{value:n,onChange:b=>c(b.target.value),className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-4 py-2.5 174 text-[var(--color-text-primary)] focus:outline-none focus:border-brand-500/50`,children:[e.jsx("option",{value:"",children:"Select reviewer..."}),D.map(b=>e.jsxs("option",{value:b.id,children:[b.firstName," ",b.lastName," - ",b.role]},b.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-[var(--color-text-primary)] mb-2",children:"Review Cycle *"}),e.jsx("select",{value:d,onChange:b=>m(b.target.value),className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-4 py-2.5 175 text-[var(--color-text-primary)] focus:outline-none focus:border-brand-500/50`,children:od.map(b=>e.jsx("option",{value:b.value,children:b.label},b.value))})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-[var(--color-text-primary)] mb-2",children:[e.jsx(be,{className:"w-4 h-4 inline mr-1"}),"Period Start *"]}),e.jsx("input",{type:"date",value:u,onChange:b=>h(b.target.value),className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-4 py-2.5 176 text-[var(--color-text-primary)] focus:outline-none focus:border-brand-500/50`})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-[var(--color-text-primary)] mb-2",children:[e.jsx(be,{className:"w-4 h-4 inline mr-1"}),"Period End *"]}
176),e.jsx("input",{type:"date",value:v,onChange:b=>y(b.target.value),className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-4 py-2.5 177 text-[var(--color-text-primary)] focus:outline-none focus:border-brand-500/50`})]})]}),p.length>0&&e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-[var(--color-text-primary)] mb-2",children:"Review Template (optional)"}),e.jsxs("select",{value:S,onChange:b=>j(b.target.value),className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-4 py-2.5 178 text-[var(--color-text-primary)] focus:outline-none focus:border-brand-500/50`,children:[e.jsx("option",{value:"",children:"Use default categories"}),p.map(b=>e.jsx("option",{value:b.id,children:b.name},b.id))]})]}),R&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-red-500/10 border border-red-500/20 rounded-lg",children:[e.jsx(Ve,{className:"w-4 h-4 text-red-400"}),e.jsx("span",{className:"text-sm text-red-300",children:R})]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-3 px-6 py-4 border-t border-[var(--color-border-subtle)] bg-[var(--color-bg-hover)]",children:[e.jsx("button",{onClick:t,disabled:I,className:"px-4 py-2 text-[var(--color-text-primary)] hover:text-[var(--color-text-primary)] font-medium",children:"Cancel"}),e.jsx("button",{onClick:O,disabled:I||!s||!n,className:`px-5 py-2 bg-brand-500 hover:bg-brand-400 text-[var(--color-text-primary)] rounded-lg 179 font-medium disabled:opacity-50 flex items-center gap-2`,children:I?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-2 border-[var(--color-border-default)] border-t-transparent"}),"Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Te,{className:"w-4 h-4"}),"Create Review"]})})]})]})})};function ld(l){const t=new Map,r=new Map;l.forEach(s=>{if(t.set(s.id,s),s.managerId){const i=r.get(s.managerId)||[];i.push(s),r.set(s.managerId,i)}});const a=l.filter(s=>!s.managerId||!t.has(s.managerId));function o(s,i){const n=r.get(s.id)||[];return{employee:s,children:n.sort((c,d)=>`${c.lastName}`.localeCompare(`${d.lastName}`)).map(c=>o(c,i+1)),level:i}}return a.sort((s,i)=>`${s.lastName}`.localeCompare(`${i.lastName}`)).map(s=>o(s,0))}function id(l){switch(l){case"Active":return"bg-emerald-500";case"Leave":return"bg-amber-500";case"Terminated":return"bg-red-500";default:return"bg-[var(--color-bg-active)]"}}function cd(l){return l&&{Engineering:"from-[var(--color-primary)] to-[var(--color-primary-active)]",Sales:"from-emerald-600 to-emerald-700",Marketing:"from-purple-600 to-purple-700",Operations:"from-amber-600 to-amber-700",Finance:"from-cyan-600 to-cyan-700",HR:"from-pink-600 to-pink-700",Executive:"from-brand-600 to-brand-700",Support:"from-orange-600 to-orange-700"}[l]||"from-slate-600 to-slate-700"}const Ms=({node:l,expanded:t,onToggle:r,onSelect:a,searchTerm:o})=>{var y,p,N,S;const{employee:s,children:i,level:n}=l,c=t.has(s.id),d=i.length>0,m=`${s.firstName} ${s.lastName}`,u=o?m.toLowerCase().includes(o.toLowerCase())||((y=s.role)==null?void 0:y.toLowerCase().includes(o.toLowerCase()))||((p=s.department)==null?void 0:p.toLowerCase().includes(o.toLowerCase())):!0,h=j=>{var $,R;return!o||`${j.employee.firstName} ${j.employee.lastName}`.toLowerCase().includes(o.toLowerCase())||($=j.employee.role)!=null&&$.toLowerCase().includes(o.toLowerCase())||(R=j.employee.department)!=null&&R.toLowerCase().includes(o.toLowerCase())?!0:j.children.some(h)};return u||h(l)?e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsxs("div",{onClick:()=>a==null?void 0:a(s),className:`relative w-56 bg-gradient-to-br ${cd(s.department)} 180 rounded-xl shadow-lg border border-[var(--color-border-default)] cursor-pointer 181 hover:scale-105 hover:shadow-xl transition-all duration-200 182 ${u&&o?"ring-2 ring-brand-400":""}`,children:[e.jsx("div",{className:`absolute -top-1 -right-1 w-3 h-3 rounded-full ${id(s.status||"Active")} ring-2 ring-slate-800`}),e.jsxs("div",{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-[var(--color-bg-active)] flex items-center justify-center",children:e.jsxs("span",{className:"text-lg font-bold text-[var(--color-text-primary)]",children:[(N=s.firstName)==null?void 0:N[0],(S=s.lastName)==null?void 0:S[0]]})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-semibold text-[var(--color-text-primary)] truncate",children:m}),e.jsx("div",{className:"text-xs text-[var(--color-text-primary)] truncate",children:s.role})]})]}),e.jsxs("div",{className:"space-y-1 text-xs text-[var(--color-text-secondary)]",children:[s.department&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Zr,{className:"w-3 h-3"}),e.jsx("span",{className:"truncate",children:s.department})]}),s.email&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(da,{className:"w-3 h-3"}),e.jsx("span",{className:"truncate",children:s.email})]})]}),d&&e.jsxs("div",{className:"mt-3 pt-3 border-t border-[var(--color-border-subtle)] flex items-center justify-between",children:[e.jsxs("span",{className:"text-xs text-[var(--color-text-secondary)]",children:[i.length," direct report",i.length!==1?"s":""]}),e.jsx("button",{onClick:j=>{j.stopPropagation(),r(s.id)},className:"p-1 rounded hover:bg-[var(--color-bg-active)] transition-colors",children:c?e.jsx(vt,{className:"w-4 h-4 text-[var(--color-text-primary)]"}):e.jsx(nt,{className:"w-4 h-4 text-[var(--color-text-primary)]"})})]})]})]}),d&&c&&e.jsx("div",{className:"w-px h-6 bg-[var(--color-bg-active)]"}),d&&c&&e.jsxs("div",{className:"relative",children:[i.length>1&&e.jsx("div",{className:"absolute top-0 h-px bg-[var(--color-bg-active)]",style:{left:"50%",transform:"translateX(-50%)",width:`calc(${(i.length-1)*280}px)`}}),e.jsx("div",{className:"flex gap-6 pt-0",children:i.map((j,I)=>e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsx("div",{className:"w-px h-6 bg-[var(--color-bg-active)]"}),e.jsx(Ms,{node:j,expanded:t,onToggle:r,onSelect:a,searchTerm:o})]},j.employee.id))})]})]}):null},dd=({employees:l,onSelectEmployee:t})=>{const[r,a]=x.useState(new Set),[o,s]=x.useState(100),[i,n]=x.useState(""),c=x.useMemo(()=>{const y=l.filter(p=>p.status!=="Terminated");return ld(y)},[l]);ms.useEffect(()=>{const y=new Set;
182function p(N,S){N.forEach(j=>{j.level<S&&(y.add(j.employee.id),p(j.children,S))})}p(c,2),a(y)},[c]);const d=y=>{a(p=>{const N=new Set(p);return N.has(y)?N.delete(y):N.add(y),N})},m=()=>{const y=new Set;function p(N){N.forEach(S=>{y.add(S.employee.id),p(S.children)})}p(c),a(y)},u=()=>{a(new Set)},h=l.filter(y=>y.status==="Active").length,v=new Set(l.map(y=>y.department).filter(Boolean));return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 bg-[var(--color-bg-hover)] border-b border-[var(--color-border-subtle)]",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Re,{className:"w-5 h-5 text-brand-400"}),e.jsx("span",{className:"font-semibold text-[var(--color-text-primary)]",children:"Organization Chart"})]}),e.jsxs("div",{className:"text-sm text-[var(--color-text-secondary)]",children:[h," employees ⢠",v.size," departments"]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-[var(--color-text-muted)]"}),e.jsx("input",{type:"text",value:i,onChange:y=>n(y.target.value),placeholder:"Search...",className:`w-48 bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg pl-10 pr-4 py-1.5 183 text-sm text-[var(--color-text-primary)] placeholder-white/40 focus:outline-none focus:border-brand-500/50`})]}),e.jsxs("div",{className:"flex items-center gap-1 bg-[var(--color-bg-hover)] rounded-lg p-1",children:[e.jsx("button",{onClick:m,className:"px-3 py-1 text-xs text-[var(--color-text-primary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)] rounded",title:"Expand All",children:"Expand All"}),e.jsx("button",{onClick:u,className:"px-3 py-1 text-xs text-[var(--color-text-primary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)] rounded",title:"Collapse All",children:"Collapse"})]}),e.jsxs("div",{className:"flex items-center gap-1 bg-[var(--color-bg-hover)] rounded-lg p-1",children:[e.jsx("button",{onClick:()=>s(Math.max(50,o-10)),className:"p-1 text-[var(--color-text-primary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)] rounded",title:"Zoom Out",children:e.jsx(Ol,{className:"w-4 h-4"})}),e.jsxs("span",{className:"px-2 text-xs text-[var(--color-text-secondary)] min-w-[3rem] text-center",children:[o,"%"]}),e.jsx("button",{onClick:()=>s(Math.min(150,o+10)),className:"p-1 text-[var(--color-text-primary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)] rounded",title:"Zoom In",children:e.jsx(vn,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>s(100),className:"p-1 text-[var(--color-text-primary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)] rounded",title:"Reset Zoom",children:e.jsx(fn,{className:"w-4 h-4"})})]})]})]}),e.jsx("div",{className:"flex-1 overflow-auto p-8",children:c.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-[var(--color-text-secondary)]",children:[e.jsx(Re,{className:"w-16 h-16 mb-4 opacity-50"}),e.jsx("p",{className:"text-lg font-medium",children:"No Organization Data"}),e.jsx("p",{className:"text-sm mt-1",children:"Add employees with manager relationships to see the org chart"})]}):e.jsx("div",{className:"min-w-max flex justify-center",style:{transform:`scale(${o/100})`,transformOrigin:"top center"},children:e.jsx("div",{className:"flex gap-12",children:c.map(y=>e.jsx(Ms,{node:y,expanded:r,onToggle:d,onSelect:t,searchTerm:i},y.employee.id))})})}),e.jsxs("div",{className:"px-4 py-2 bg-[var(--color-bg-hover)] border-t border-[var(--color-border-subtle)] flex items-center justify-center gap-6 text-xs text-[var(--color-text-secondary)]",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-emerald-500"}),e.jsx("span",{children:"Active"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-amber-500"}),e.jsx("span",{children:"On Leave"})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"text-[var(--color-text-muted)]",children:"Click card to view details"})})]})]})},ud=[{name:"W-4",category:"tax_form",requiresExpiration:!1,description:"Employee Withholding Certificate"},{name:"W-9",category:"tax_form",requiresExpiration:!1,description:"Request for Taxpayer ID"},{name:"State Tax Form",category:"tax_form",requiresExpiration:!1},{name:"I-9",category:"identification",requiresExpiration:!1,description:"Employment Eligibility Verification"},{name:"Driver's License",category:"identification",requiresExpiration:!0},{name:"Passport",category:"identification",requiresExpiration:!0},{name:"Work Visa",category:"identification",requiresExpiration:!0},{name:"Social Security Card",category:"identification",requiresExpiration:!1},{name:"Professional Certification",category:"certification",requiresExpiration:!0},{name:"Industry License",category:"license",requiresExpiration:!0},{name:"CPR Certification",category:"certification",requiresExpiration:!0},{name:"Food Handler Card",category:"certification",requiresExpiration:!0},{name:"Employee Handbook Acknowledgment",category:"policy",requiresExpiration:!1},{name:"Code of Conduct",category:"policy",requiresExpiration:!1},{name:"Non-Disclosure Agreement",category:"contract",requiresExpiration:!1},{name:"Non-Compete Agreement",category:"contract",requiresExpiration:!1}
183,{name:"Benefits Enrollment Form",category:"benefit",requiresExpiration:!1},{name:"Direct Deposit Authorization",category:"benefit",requiresExpiration:!1},{name:"Emergency Contact Form",category:"benefit",requiresExpiration:!1},{name:"Sexual Harassment Training",category:"training",requiresExpiration:!0},{name:"Safety Training",category:"training",requiresExpiration:!0},{name:"Onboarding Checklist",category:"training",requiresExpiration:!1}],ra={tax_form:"Tax Forms",identification:"Identification",certification:"Certifications",license:"Licenses",policy:"Policies",performance:"Performance",contract:"Contracts",benefit:"Benefits",medical:"Medical",training:"Training",other:"Other"};class md{getBasePath(){const t=De.getCurrentTenant();return t!=null&&t.id?`tenants/${t.id}`:(console.warn("[hrDocumentService] No tenant found"),"tenants/default")}getCurrentUserId(){var t;return((t=A.getCurrentUser())==null?void 0:t.id)||"system"}async uploadDocument(t,r){var h;const a=this.getBasePath(),o=`doc-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,s=B(_,`${a}/hr_employee_documents`,o);let i=t.file_url,n=t.file_name,c=t.file_type,d=t.file_size;if(r){const v=`${a}/hr_documents/${t.employee_id}/${o}-${r.name}`,y=Ma(Fa,v);await nn(y,r),i=await ln(y),n=r.name,c=r.type,d=r.size}let m="active";if(t.expiration_date){const v=new Date(t.expiration_date),y=new Date,p=Math.ceil((v.getTime()-y.getTime())/(1e3*60*60*24));p<0?m="expired":p<=30&&(m="expiring_soon")}const u={id:o,tenant_id:((h=De.getCurrentTenant())==null?void 0:h.id)||"",employee_id:t.employee_id,name:t.name,description:t.description||null,category:t.category,status:m,file_url:i||null,file_name:n||null,file_type:c||null,file_size:d||null,issue_date:t.issue_date||null,expiration_date:t.expiration_date||null,verified_at:null,verified_by_user_id:null,verification_notes:null,tags:t.tags||null,custom_fields:null,uploaded_by_user_id:this.getCurrentUserId(),created_at:new Date().toISOString(),updated_at:new Date().toISOString()};return await Lt(s,u),console.log("[hrDocumentService] Document uploaded:",o),u}async getDocument(t){const r=this.getBasePath(),a=B(_,`${r}/hr_employee_documents`,t),o=await oe(a);return o.exists()?o.data():null}async getEmployeeDocuments(t){const r=this.getBasePath(),a=V(H(_,`${r}/hr_employee_documents`),K("employee_id","==",t),ee("created_at","desc"));return(await Z(a)).docs.map(s=>s.data())}async getDocumentsByCategory(t){const r=this.getBasePath(),a=V(H(_,`${r}/hr_employee_documents`),K("category","==",t),ee("created_at","desc"));return(await Z(a)).docs.map(s=>s.data())}async getDocuments(t){const r=this.getBasePath();let a=V(H(_,`${r}/hr_employee_documents`),ee("created_at","desc"));return t!=null&&t.employee_id&&(a=V(a,K("employee_id","==",t.employee_id))),t!=null&&t.category&&(a=V(a,K("category","==",t.category))),t!=null&&t.status&&(a=V(a,K("status","==",t.status))),(await Z(a)).docs.map(s=>s.data())}async updateDocument(t,r){const a=this.getBasePath(),o=B(_,`${a}/hr_employee_documents`,t);let s=r.status;if(r.expiration_date&&!s){const i=new Date(r.expiration_date),n=new Date,c=Math.ceil((i.getTime()-n.getTime())/(1e3*60*60*24));c<0?s="expired":c<=30?s="expiring_soon":s="active"}await Q(o,{...r,...s&&{status:s},updated_at:new Date().toISOString()}),console.log("[hrDocumentService] Document updated:",t)}async verifyDocument(t,r){const a=this.getBasePath(),o=B(_,`${a}/hr_employee_documents`,t);await Q(o,{verified_at:new Date().toISOString(),verified_by_user_id:this.getCurrentUserId(),verification_notes:r||null,updated_at:new Date().toISOString()}),console.log("[hrDocumentService] Document verified:",t)}async archiveDocument(t){await this.updateDocument(t,{status:"archived"}),console.log("[hrDocumentService] Document archived:",t)}async deleteDocument(t){const r=this.getBasePath(),a=await this.getDocument(t);if(a!=null&&a.file_url)try{const s=Ma(Fa,a.file_url);await cn(s)}catch(s){console.warn("[hrDocumentService] Failed to delete file from storage:",s)}const o=B(_,`${r}/hr_employee_documents`,t);await ke(o),console.log("[hrDocumentService] Document deleted:",t)}async getRequirements(){const t=this.getBasePath(),r=V(H(_,`${t}/hr_document_requirements`),K("is_active","==",!0),ee("name"));return(await Z(r)).docs.map(o=>o.data())}
183async createRequirement(t){var i;const r=this.getBasePath(),a=`req-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,o=B(_,`${r}/hr_document_requirements`,a),s={id:a,tenant_id:((i=De.getCurrentTenant())==null?void 0:i.id)||"",...t,created_at:new Date().toISOString(),updated_at:new Date().toISOString()};return await Lt(o,s),console.log("[hrDocumentService] Requirement created:",a),s}async getEmployeeCompliance(t,r){const a=await this.getEmployeeDocuments(t),o=await this.getRequirements(),s=new Date;new Date(s.getTime()+720*60*60*1e3),new Set(a.map(u=>u.category));const i=o.filter(u=>u.is_required),n=[],c=[];let d=0;for(const u of i)a.some(v=>v.category===u.category&&v.status!=="archived")||n.push(u.name);for(const u of a)if(u.expiration_date&&u.status!=="archived"){const h=new Date(u.expiration_date),v=Math.ceil((h.getTime()-s.getTime())/(1e3*60*60*24));v<0?d++:v<=30&&c.push({document_id:u.id,name:u.name,expiration_date:u.expiration_date,days_until_expiration:v})}let m="compliant";return n.length>0||d>0?m="non_compliant":c.length>0&&(m="expiring"),{employee_id:t,employee_name:r,status:m,total_required:i.length,total_completed:i.length-n.length,total_missing:n.length,total_expiring:c.length,total_expired:d,missing_documents:n,expiring_documents:c}}async getAllEmployeesCompliance(t){return await Promise.all(t.map(a=>this.getEmployeeCompliance(a.id,a.name)))}async getExpiringDocuments(t=30){const r=await this.getDocuments(),a=new Date,o=new Date(a.getTime()+t*24*60*60*1e3);return r.filter(s=>{if(!s.expiration_date||s.status==="archived")return!1;const i=new Date(s.expiration_date);return i>=a&&i<=o})}async getExpiredDocuments(){const t=await this.getDocuments(),r=new Date;return t.filter(a=>!a.expiration_date||a.status==="archived"?!1:new Date(a.expiration_date)<r)}subscribeToEmployeeDocuments(t,r){const a=this.getBasePath(),o=V(H(_,`${a}/hr_employee_documents`),K("employee_id","==",t),ee("created_at","desc"));return we(o,s=>{const i=s.docs.map(n=>n.data());r(i)},s=>{console.error("[hrDocumentService] Subscription error:",s),r([])})}subscribeToDocuments(t){const r=this.getBasePath(),a=V(H(_,`${r}/hr_employee_documents`),ee("created_at","desc"));return we(a,o=>{const s=o.docs.map(i=>i.data());t(s)},o=>{console.error("[hrDocumentService] Subscription error:",o),t([])})}async refreshDocumentStatuses(){const t=await this.getDocuments(),r=new Date;for(const a of t){if(!a.expiration_date||a.status==="archived")continue;const o=new Date(a.expiration_date),s=Math.ceil((o.getTime()-r.getTime())/(1e3*60*60*24));let i=null;s<0&&a.status!=="expired"?i="expired":s>=0&&s<=30&&a.status!=="expiring_soon"?i="expiring_soon":s>30&&(a.status==="expired"||a.status==="expiring_soon")&&(i="active"),i&&await this.updateDocument(a.id,{status:i})}console.log("[hrDocumentService] Document statuses refreshed")}}const Qt=new md;function xd(l){switch(l){case"tax_form":return e.jsx(bn,{className:"w-4 h-4"});case"identification":return e.jsx(Al,{className:"w-4 h-4"});case"certification":return e.jsx(sr,{className:"w-4 h-4"});case"license":return e.jsx(gn,{className:"w-4 h-4"});case"training":return e.jsx(en,{className:"w-4 h-4"});case"benefit":return e.jsx(bs,{className:"w-4 h-4"});default:return e.jsx(et,{className:"w-4 h-4"})}}function hd(l){switch(l){case"active":return e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium bg-emerald-500/20 text-emerald-400",children:[e.jsx(Rt,{className:"w-3 h-3"}),"Active"]});case"expiring_soon":return e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium bg-amber-500/20 text-amber-400",children:[e.jsx(ve,{className:"w-3 h-3"}),"Expiring Soon"]});case"expired":return e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium bg-red-500/20 text-red-400",children:[e.jsx(Ve,{className:"w-3 h-3"}),"Expired"]});case"pending":return e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium bg-[var(--color-primary-subtle)] text-[var(--color-primary)]",children:[e.jsx(ve,{className:"w-3 h-3"}),"Pending"]});case"archived":return e.jsx("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium bg-gray-500/20 text-[var(--color-text-muted)]",children:"Archived"});default:return null}}function pd(l){switch(l){case"compliant":return e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium bg-emerald-500/20 text-emerald-400",children:[e.jsx(oa,{className:"w-3 h-3"}),"Compliant"]});case"expiring":return e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium bg-amber-500/20 text-amber-400",children:[e.jsx(Ee,{className:"w-3 h-3"}),"Expiring"]});case"non_compliant":return e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium bg-red-500/20 text-red-400",children:[e.jsx(Ve,{className:"w-3 h-3"}),"Non-Compliant"]});default:return e.jsx("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium bg-gray-500/20 text-[var(--color-text-muted)]",children:"Pending Review"})}}function vd(l){return l?new Date(l).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"-"}const fd=({employees:l,onUploadDocument:t,onViewDocument:r})=>{const[a,o]=x.useState([]),[s,i]=x.useState([]),[n,c]=x.useState(!0),[d,m]=x.useState("documents"),[u,h]=x.useState(""),[v,y]=x.useState("all"),[p,N]=x.useState("all"),[S,j]=x.useState("all");x.useEffect(()=>Qt.subscribeToDocuments(b=>{o(b),c(!1)}),[]),x.useEffect(()=>{(async()=>
183{if(l.length===0)return;const b=l.filter(W=>W.status==="Active").map(W=>({id:W.id,name:`${W.firstName} ${W.lastName}`})),P=await Qt.getAllEmployeesCompliance(b);i(P)})()},[l,a]);const I=D=>{const b=l.find(P=>P.id===D);return b?`${b.firstName} ${b.lastName}`:"Unknown"},$=x.useMemo(()=>a.filter(D=>{if(S!=="all"&&D.employee_id!==S||v!=="all"&&D.category!==v||p!=="all"&&D.status!==p)return!1;if(u){const b=I(D.employee_id).toLowerCase(),P=D.name.toLowerCase(),W=u.toLowerCase();if(!b.includes(W)&&!P.includes(W))return!1}return!0}),[a,S,v,p,u,l]),R=x.useMemo(()=>{const D=a.filter(f=>f.status!=="archived").length,b=a.filter(f=>f.status==="active").length,P=a.filter(f=>f.status==="expiring_soon").length,W=a.filter(f=>f.status==="expired").length,k=s.filter(f=>f.status==="compliant").length;return{total:D,active:b,expiringSoon:P,expired:W,compliantCount:k}},[a,s]),E=async D=>{if(confirm("Are you sure you want to delete this document?"))try{await Qt.deleteDocument(D)}catch(b){console.error("[DocumentsPanel] Failed to delete document:",b),alert("Failed to delete document")}},O=async D=>{try{await Qt.verifyDocument(D)}catch(b){console.error("[DocumentsPanel] Failed to verify document:",b),alert("Failed to verify document")}};return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"px-4 py-3 bg-[var(--color-bg-hover)] border-b border-[var(--color-border-subtle)]",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-[var(--color-primary-subtle)] flex items-center justify-center",children:e.jsx(et,{className:"w-5 h-5 text-[var(--color-primary)]"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-[var(--color-text-primary)]",children:"Documents & Compliance"}),e.jsxs("p",{className:"text-xs text-[var(--color-text-secondary)]",children:[R.total," documents ⢠",R.compliantCount,"/",s.length," employees compliant"]})]})]}),t&&e.jsxs("button",{onClick:t,className:`flex items-center gap-2 px-4 py-2 bg-brand-500 hover:bg-brand-400 184 text-[var(--color-text-primary)] rounded-lg font-medium text-sm`,children:[e.jsx(Ft,{className:"w-4 h-4"}),"Upload Document"]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3 mb-4",children:[e.jsxs("div",{className:"p-3 bg-[var(--color-bg-hover)] rounded-lg",children:[e.jsx("div",{className:"text-2xl font-bold text-[var(--color-text-primary)]",children:R.active}),e.jsx("div",{className:"text-xs text-[var(--color-text-secondary)]",children:"Active"})]}),e.jsxs("div",{className:"p-3 bg-[var(--color-bg-hover)] rounded-lg",children:[e.jsx("div",{className:"text-2xl font-bold text-amber-400",children:R.expiringSoon}),e.jsx("div",{className:"text-xs text-[var(--color-text-secondary)]",children:"Expiring Soon"})]}),e.jsxs("div",{className:"p-3 bg-[var(--color-bg-hover)] rounded-lg",children:[e.jsx("div",{className:"text-2xl font-bold text-red-400",children:R.expired}),e.jsx("div",{className:"text-xs text-[var(--color-text-secondary)]",children:"Expired"})]}),e.jsxs("div",{className:"p-3 bg-[var(--color-bg-hover)] rounded-lg",children:[e.jsx("div",{className:"text-2xl font-bold text-emerald-400",children:R.compliantCount}),e.jsx("div",{className:"text-xs text-[var(--color-text-secondary)]",children:"Compliant"})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center bg-[var(--color-bg-hover)] rounded-lg p-1",children:[e.jsx("button",{onClick:()=>m("documents"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors 185 ${d==="documents"?"bg-brand-500/20 text-brand-400":"text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"}`,children:"Documents"}),e.jsx("button",{onClick:()=>m("compliance"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors 186 ${d==="compliance"?"bg-brand-500/20 text-brand-400":"text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"}`,children:"Compliance"})]})})]}),d==="documents"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"px-4 py-3 border-b border-[var(--color-border-subtle)] flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 max-w-xs",children:[e.jsx(rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-[var(--color-text-muted)]"}),e.jsx("input",{type:"text",value:u,onChange:D=>h(D.target.value),placeholder:"Search documents...",className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg pl-10 pr-4 py-2 187 text-sm text-[var(--color-text-primary)] placeholder-white/40 focus:outline-none focus:border-brand-500/50`})]}),e.jsxs("select",{value:S,onChange:D=>j(D.target.value),className:`bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-3 py-2 188 text-sm text-[var(--color-text-primary)] focus:outline-none focus:border-brand-500/50`,children:[e.jsx("option",{value:"all",children:"All Employees"}),l.filter(D=>D.status==="Active").map(D=>e.jsxs("option",{value:D.id,children:[D.firstName," ",D.lastName]},D.id))]}
188),e.jsxs("select",{value:v,onChange:D=>y(D.target.value),className:`bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-3 py-2 189 text-sm text-[var(--color-text-primary)] focus:outline-none focus:border-brand-500/50`,children:[e.jsx("option",{value:"all",children:"All Categories"}),Object.entries(ra).map(([D,b])=>e.jsx("option",{value:D,children:b},D))]}),e.jsxs("select",{value:p,onChange:D=>N(D.target.value),className:`bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-3 py-2 190 text-sm text-[var(--color-text-primary)] focus:outline-none focus:border-brand-500/50`,children:[e.jsx("option",{value:"all",children:"All Statuses"}),e.jsx("option",{value:"active",children:"Active"}),e.jsx("option",{value:"expiring_soon",children:"Expiring Soon"}),e.jsx("option",{value:"expired",children:"Expired"}),e.jsx("option",{value:"pending",children:"Pending"})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:n?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-[var(--color-border-default)] border-t-transparent"})}):$.length===0?e.jsxs("div",{className:"p-6 text-center",children:[e.jsx(et,{className:"w-12 h-12 mx-auto mb-3 text-[var(--color-text-muted)]"}),e.jsx("p",{className:"text-[var(--color-text-secondary)] font-medium",children:"No Documents Found"}),e.jsx("p",{className:"text-sm text-[var(--color-text-muted)] mt-1",children:u||v!=="all"||p!=="all"?"Try adjusting your filters":"Upload documents to get started"})]}):e.jsx("div",{className:"divide-y divide-[var(--color-border-subtle)]",children:$.map(D=>e.jsx("div",{className:"p-4 hover:bg-[var(--color-bg-hover)] transition-colors",children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-[var(--color-bg-hover)] flex items-center justify-center text-[var(--color-text-secondary)]",children:xd(D.category)}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium text-[var(--color-text-primary)] truncate",children:D.name}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-[var(--color-text-secondary)]",children:[e.jsx(tt,{className:"w-3 h-3"}),I(D.employee_id),e.jsx("span",{children:"â¢"}),ra[D.category]]})]})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-right",children:[hd(D.status),D.expiration_date&&e.jsxs("div",{className:"text-xs text-[var(--color-text-muted)] mt-1",children:["Expires: ",vd(D.expiration_date)]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[D.file_url&&e.jsx("a",{href:D.file_url,target:"_blank",rel:"noopener noreferrer",className:"p-2 hover:bg-[var(--color-bg-hover)] rounded-lg text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]",title:"View Document",children:e.jsx(xs,{className:"w-4 h-4"})}),!D.verified_at&&e.jsx("button",{onClick:()=>O(D.id),className:"p-2 hover:bg-[var(--color-bg-hover)] rounded-lg text-[var(--color-text-secondary)] hover:text-emerald-400",title:"Verify Document",children:e.jsx(Rt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>E(D.id),className:"p-2 hover:bg-[var(--color-bg-hover)] rounded-lg text-[var(--color-text-secondary)] hover:text-red-400",title:"Delete Document",children:e.jsx(qe,{className:"w-4 h-4"})})]})]})]})},D.id))})})]}):e.jsx("div",{className:"flex-1 overflow-y-auto divide-y divide-[var(--color-border-subtle)]",children:s.length===0?e.jsxs("div",{className:"p-6 text-center",children:[e.jsx(oa,{className:"w-12 h-12 mx-auto mb-3 text-[var(--color-text-muted)]"}),e.jsx("p",{className:"text-[var(--color-text-secondary)] font-medium",children:"No Employees"}),e.jsx("p",{className:"text-sm text-[var(--color-text-muted)] mt-1",children:"Add employees to track compliance"})]}):s.map(D=>e.jsxs("div",{className:"p-4 hover:bg-[var(--color-bg-hover)] transition-colors",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-brand-500/20 flex items-center justify-center",children:e.jsx("span",{className:"text-sm font-bold text-brand-400",children:D.employee_name.split(" ").map(b=>b[0]).join("")})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-[var(--color-text-primary)]",children:D.employee_name}),e.jsxs("div",{className:"text-xs text-[var(--color-text-secondary)]",children:[D.total_completed,"/",D.total_required," documents"]})]})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[pd(D.status),(D.total_missing>0||D.total_expiring>0)&&e.jsxs("div",{className:"text-right text-xs",children:[D.total_missing>0&&e.jsxs("div",{className:"text-red-400",children:[D.total_missing," missing"]}),D.total_expiring>0&&e.jsxs("div",{className:"text-amber-400",children:[D.total_expiring," expiring"]})]}),e.jsx(nt,{className:"w-4 h-4 text-[var(--color-text-muted)]"})]})]}),(D.missing_documents.length>0||D.expiring_documents.length>0)&&e.jsxs("div",{className:"mt-3 pl-13 space-y-1",children:[D.missing_documents.map(b=>e.jsxs("div",{className:"flex items-center gap-2 text-xs text-red-400",children:[e.jsx(Ve,{className:"w-3 h-3"}),"Missing: ",b]},b)),D.expiring_documents.map(b=>e.jsxs("div",{className:"flex items-center gap-2 text-xs text-amber-400",children:[e.jsx(ve,{className:"w-3 h-3"}),b.name," expires in ",b.days_until_expiration," days"]},b.document_id))]})]},D.employee_id))})]})},gd=({isOpen:l,onClose:t,onUploaded:r,employees:a,preselectedEmployeeId:o})=>{const[s,i]=x.useState(o||""),[n,c]=x.useState(""),[d,m]=x.useState("other"),[u,h]=x.useState(""),[v,y]=x.useState(""),[p,N]=x.useState(""),[S,j]=x.useState(null),[I,$]=x.use
190State(!1),[R,E]=x.useState(null),O=x.useRef(null),D=k=>{var g;const f=(g=k.target.files)==null?void 0:g[0];if(f&&(j(f),!n)){const L=f.name.replace(/\.[^/.]+$/,"");c(L)}},b=k=>{c(k.name),m(k.category),k.description&&h(k.description)},P=async()=>{if(!s){E("Please select an employee");return}if(!n){E("Please enter a document name");return}$(!0),E(null);try{await Qt.uploadDocument({employee_id:s,name:n,category:d,description:u||void 0,issue_date:v||void 0,expiration_date:p||void 0},S||void 0),r(),t(),i(o||""),c(""),m("other"),h(""),y(""),N(""),j(null)}catch(k){console.error("[UploadDocumentModal] Failed to upload:",k),E(k instanceof Error?k.message:"Failed to upload document")}finally{$(!1)}};if(!l)return null;const W=a.filter(k=>k.status==="Active");return e.jsx("div",{className:"fixed inset-0 bg-slate-900/50 flex items-center justify-center z-50 backdrop-blur-sm p-4",children:e.jsxs("div",{className:"bg-[var(--color-bg-surface)] rounded-xl w-full max-w-lg shadow-2xl border border-[var(--color-border-subtle)] max-h-[90vh] overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-[var(--color-border-subtle)] sticky top-0 bg-[var(--color-bg-surface)]",children:[e.jsxs("h2",{className:"text-lg font-bold text-[var(--color-text-primary)] flex items-center gap-2",children:[e.jsx(Ft,{className:"w-5 h-5 text-[var(--color-primary)]"}),"Upload Document"]}),e.jsx("button",{onClick:t,className:"p-2 hover:bg-[var(--color-bg-hover)] rounded-lg text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]",children:e.jsx(de,{className:"w-5 h-5"})})]}),e.jsxs("div",{className:"p-6 space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-[var(--color-text-primary)] mb-2",children:"Quick Select"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:ud.slice(0,8).map(k=>e.jsx("button",{type:"button",onClick:()=>b(k),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors 191 ${n===k.name?"bg-brand-500/20 border-brand-500/50 text-brand-400":"bg-[var(--color-bg-hover)] border-[var(--color-border-default)] text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)]"}`,children:k.name},k.name))})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-[var(--color-text-primary)] mb-2",children:[e.jsx(tt,{className:"w-4 h-4 inline mr-1"}),"Employee *"]}),e.jsxs("select",{value:s,onChange:k=>i(k.target.value),className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-4 py-2.5 192 text-[var(--color-text-primary)] focus:outline-none focus:border-brand-500/50`,children:[e.jsx("option",{value:"",children:"Select employee..."}),W.map(k=>e.jsxs("option",{value:k.id,children:[k.firstName," ",k.lastName," - ",k.role]},k.id))]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-[var(--color-text-primary)] mb-2",children:[e.jsx(et,{className:"w-4 h-4 inline mr-1"}),"Document Name *"]}),e.jsx("input",{type:"text",value:n,onChange:k=>c(k.target.value),placeholder:"e.g., W-4 Form, Driver's License",className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-4 py-2.5 193 text-[var(--color-text-primary)] placeholder-white/40 focus:outline-none focus:border-brand-500/50`})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-[var(--color-text-primary)] mb-2",children:[e.jsx(yn,{className:"w-4 h-4 inline mr-1"}),"Category"]}),e.jsx("select",{value:d,onChange:k=>m(k.target.value),className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-4 py-2.5 194 text-[var(--color-text-primary)] focus:outline-none focus:border-brand-500/50`,children:Object.entries(ra).map(([k,f])=>e.jsx("option",{value:k,children:f},k))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-[var(--color-text-primary)] mb-2",children:"Description (optional)"}),e.jsx("textarea",{value:u,onChange:k=>h(k.target.value),rows:2,placeholder:"Additional notes about this document...",className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-4 py-2.5 195 text-[var(--color-text-primary)] placeholder-white/40 focus:outline-none focus:border-brand-500/50 resize-none`})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-[var(--color-text-primary)] mb-2",children:[e.jsx(be,{className:"w-4 h-4 inline mr-1"}),"Issue Date"]}
195),e.jsx("input",{type:"date",value:v,onChange:k=>y(k.target.value),className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-4 py-2.5 196 text-[var(--color-text-primary)] focus:outline-none focus:border-brand-500/50`})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-[var(--color-text-primary)] mb-2",children:[e.jsx(be,{className:"w-4 h-4 inline mr-1"}),"Expiration Date"]}),e.jsx("input",{type:"date",value:p,onChange:k=>N(k.target.value),className:`w-full bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg px-4 py-2.5 197 text-[var(--color-text-primary)] focus:outline-none focus:border-brand-500/50`})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-[var(--color-text-primary)] mb-2",children:[e.jsx(wn,{className:"w-4 h-4 inline mr-1"}),"Attach File (optional)"]}),e.jsx("input",{ref:O,type:"file",onChange:D,accept:".pdf,.doc,.docx,.jpg,.jpeg,.png",className:"hidden"}),e.jsx("button",{type:"button",onClick:()=>{var k;return(k=O.current)==null?void 0:k.click()},className:`w-full p-4 border-2 border-dashed border-[var(--color-border-default)] rounded-lg 198 text-center hover:border-brand-500/50 hover:bg-[var(--color-bg-hover)] transition-colors`,children:S?e.jsxs("div",{className:"flex items-center justify-center gap-2 text-emerald-400",children:[e.jsx(Te,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm",children:S.name}),e.jsxs("span",{className:"text-[var(--color-text-muted)] text-xs",children:["(",(S.size/1024).toFixed(1)," KB)"]})]}):e.jsxs("div",{className:"text-[var(--color-text-secondary)]",children:[e.jsx(Ft,{className:"w-6 h-6 mx-auto mb-1"}),e.jsx("span",{className:"text-sm",children:"Click to upload file"}),e.jsx("div",{className:"text-xs mt-1",children:"PDF, DOC, DOCX, JPG, PNG"})]})})]}),R&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-red-500/10 border border-red-500/20 rounded-lg",children:[e.jsx(Ve,{className:"w-4 h-4 text-red-400"}),e.jsx("span",{className:"text-sm text-red-300",children:R})]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-3 px-6 py-4 border-t border-[var(--color-border-subtle)] bg-[var(--color-bg-hover)]",children:[e.jsx("button",{onClick:t,disabled:I,className:"px-4 py-2 text-[var(--color-text-primary)] hover:text-[var(--color-text-primary)] font-medium",children:"Cancel"}),e.jsx("button",{onClick:P,disabled:I||!s||!n,className:`px-5 py-2 bg-brand-500 hover:bg-brand-400 text-[var(--color-text-primary)] rounded-lg 199 font-medium disabled:opacity-50 flex items-center gap-2`,children:I?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-2 border-[var(--color-border-default)] border-t-transparent"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ft,{className:"w-4 h-4"}),"Upload Document"]})})]})]})})};class bd{calculateAnalytics(t,r="1y"){const a=new Date,o=this.getPeriodDays(r),s=new Date(a.getTime()-o*24*60*60*1e3),i=t.length,n=t.filter($=>$.status==="Active").length,c=t.filter($=>$.status==="Leave").length,d=t.filter($=>$.status==="Terminated").length,m=t.filter($=>$.status==="Candidate").length,u=this.calculateDepartmentMetrics(t),{avgTenureMonths:h,tenureDistribution:v}=this.calculateTenureMetrics(t),{avgPerformanceRating:y,performanceDistribution:p}=this.calculatePerformanceMetrics(t),N=this.calculateRiskMetrics(t),S=this.calculateEmploymentTypeBreakdown(t),j=this.calculateTurnoverMetrics(t,s),I=this.calculateHeadcountTrend(t,r);return{totalHeadcount:i,activeEmployees:n,onLeave:c,terminated:d,candidates:m,headcountTrend:I,departmentMetrics:u,avgTenureMonths:h,tenureDistribution:v,avgPerformanceRating:y,performanceDistribution:p,riskMetrics:N,employmentTypes:S,turnoverMetrics:j,calculatedAt:a.toISOString()}}getPeriodDays(t){switch(t){case"7d":return 7;case"30d":return 30;case"90d":return 90;case"1y":return 365;case"all":return 365*10;default:return 365}}calculateDepartmentMetrics(t){const r=new Map;t.forEach(o=>{const s=o.department||"Unassigned",i=r.get(s)||[];
199i.push(o),r.set(s,i)});const a=[];return r.forEach((o,s)=>{const i=o.filter(v=>v.status==="Active"),n=o.filter(v=>v.status==="Terminated"),c=this.calculateAvgTenure(i),d=this.calculateAvg(i,"performanceRating"),m=this.calculateAvg(i,"flightRiskScore"),u=this.calculateAvg(i,"burnoutRiskScore"),h=o.length>0?n.length/o.length*100:0;a.push({department:s,headcount:i.length,avgTenure:c,avgPerformance:d,avgFlightRisk:m,avgBurnoutRisk:u,turnoverRate:h})}),a.sort((o,s)=>s.headcount-o.headcount)}calculateTenureMetrics(t){const r=t.filter(c=>c.status==="Active"),a=new Date,o=r.map(c=>{if(!c.hireDate)return 0;const d=new Date(c.hireDate);return Math.round((a.getTime()-d.getTime())/(1e3*60*60*24*30))}),s=o.length>0?Math.round(o.reduce((c,d)=>c+d,0)/o.length):0,n=[{label:"< 6 months",min:0,max:6},{label:"6-12 months",min:6,max:12},{label:"1-2 years",min:12,max:24},{label:"2-5 years",min:24,max:60},{label:"5+ years",min:60,max:1/0}].map(c=>{const d=o.filter(m=>m>=c.min&&m<c.max).length;return{label:c.label,range:`${c.min}-${c.max===1/0?"+":c.max}`,count:d,percentage:o.length>0?Math.round(d/o.length*100):0}});return{avgTenureMonths:s,tenureDistribution:n}}calculatePerformanceMetrics(t){const r=t.filter(i=>i.status==="Active"&&i.performanceRating),a=this.calculateAvg(r,"performanceRating"),o={1:"Needs Improvement",2:"Below Expectations",3:"Meets Expectations",4:"Exceeds Expectations",5:"Outstanding"},s=[1,2,3,4,5].map(i=>{const n=r.filter(c=>c.performanceRating===i).length;return{rating:i,label:o[i],count:n,percentage:r.length>0?Math.round(n/r.length*100):0}});return{avgPerformanceRating:a,performanceDistribution:s}}calculateRiskMetrics(t){const r=t.filter(a=>a.status==="Active");return{highFlightRisk:r.filter(a=>(a.flightRiskScore||0)>=70).length,mediumFlightRisk:r.filter(a=>(a.flightRiskScore||0)>=40&&(a.flightRiskScore||0)<70).length,lowFlightRisk:r.filter(a=>(a.flightRiskScore||0)<40).length,highBurnoutRisk:r.filter(a=>(a.burnoutRiskScore||0)>=70).length,mediumBurnoutRisk:r.filter(a=>(a.burnoutRiskScore||0)>=40&&(a.burnoutRiskScore||0)<70).length,lowBurnoutRisk:r.filter(a=>(a.burnoutRiskScore||0)<40).length}}calculateEmploymentTypeBreakdown(t){const r=t.filter(s=>s.status==="Active"),a=new Map;r.forEach(s=>{const i=s.employmentType||"Unknown";a.set(i,(a.get(i)||0)+1)});const o=[];return a.forEach((s,i)=>{o.push({type:i,count:s,percentage:r.length>0?Math.round(s/r.length*100):0})}),o.sort((s,i)=>i.count-s.count)}calculateTurnoverMetrics(t,r){const a=new Date,o=t.filter(m=>m.status==="Terminated"),s=t.filter(m=>m.status==="Active"),i=Math.round(o.length*.6),n=o.length-i,c=s.length+o.length/2,d=c>0?Math.round(o.length/c*100):0;return{period:`${r.toLocaleDateString()} - ${a.toLocaleDateString()}`,voluntary:i,involuntary:n,total:o.length,rate:d}}calculateHeadcountTrend(t,r){const a=this.getPeriodDays(r),o=new Date,s=[];let i,n;a<=30?(i=1,n=a):a<=90?(i=7,n=Math.ceil(a/7)):(i=30,n=Math.min(12,Math.ceil(a/30)));const c=t.filter(d=>d.status==="Active").length;for(let d=n-1;d>=0;d--){const m=new Date(o.getTime()-d*i*24*60*60*1e3),u=Math.floor(Math.random()*5)-2,h=Math.max(0,c+u-(n-1-d));s.push({date:m.toISOString().split("T")[0],count:h,hires:Math.floor(Math.random()*3),terminations:Math.floor(Math.random()*2)})}return s}calculateAvgTenure(t){const r=new Date,a=t.filter(o=>o.hireDate).map(o=>{const s=new Date(o.hireDate);return(r.getTime()-s.getTime())/(1e3*60*60*24*30)});return a.length===0?0:Math.round(a.reduce((o,s)=>o+s,0)/a.length)}calculateAvg(t,r){const a=t.map(o=>o[r]).filter(o=>typeof o=="number"&&!isNaN(o));return a.length===0?0:Math.round(a.reduce((o,s)=>o+s,0)/a.length*10)/10}getKPICards(t){var r,a;return{primary:[{label:"Total Headcount",value:t.activeEmployees,subtitle:`${t.onLeave} on leave`,trend:"neutral"},{label:"Avg Tenure",value:`${Math.round(t.avgTenureMonths/12*10)/10}y`,subtitle:`${t.avgTenureMonths} months`,trend:"neutral"},{label:"Avg Performance",value:t.avgPerformanceRating.toFixed(1),subtitle:"out of 5.0",trend:t.avgPerformanceRating>=3.5?"up":t.avgPerformanceRating<3?"down":"neutral"},{label:"Turnover Rate",value:`${t.turnoverMetrics.rate}%`,subtitle:`${t.turnoverMetrics.total} terminations`,trend:t.turnoverMetrics.rate>15?"down":"up"}
199],secondary:[{label:"High Flight Risk",value:t.riskMetrics.highFlightRisk,color:"red"},{label:"High Burnout Risk",value:t.riskMetrics.highBurnoutRisk,color:"amber"},{label:"Full Time",value:((r=t.employmentTypes.find(o=>o.type==="Full Time"))==null?void 0:r.count)||0},{label:"Part Time",value:((a=t.employmentTypes.find(o=>o.type==="Part Time"))==null?void 0:a.count)||0}]}}}const ds=new bd,yd=[{value:"7d",label:"7 Days"},{value:"30d",label:"30 Days"},{value:"90d",label:"90 Days"},{value:"1y",label:"1 Year"},{value:"all",label:"All Time"}],Ze={primary:"var(--color-primary)",success:"var(--color-success)",warning:"#F59E0B",info:"var(--color-info)",purple:"#8B5CF6",pink:"#EC4899"},br=[Ze.primary,Ze.info,Ze.success,Ze.purple,Ze.pink];function wd({trend:l}){return l==="up"?e.jsx(_r,{className:"w-4 h-4 text-emerald-400"}):l==="down"?e.jsx(bl,{className:"w-4 h-4 text-red-400"}):e.jsx(yl,{className:"w-4 h-4 text-[var(--color-text-muted)]"})}const jd=({employees:l})=>{const[t,r]=x.useState("1y"),[a,o]=x.useState(0),s=x.useMemo(()=>ds.calculateAnalytics(l,t),[l,t,a]),i=x.useMemo(()=>ds.getKPICards(s),[s]),n=()=>{o(c=>c+1)};return e.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 bg-[var(--color-bg-hover)] border-b border-[var(--color-border-subtle)]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-purple-500/20 flex items-center justify-center",children:e.jsx(jn,{className:"w-5 h-5 text-purple-400"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-[var(--color-text-primary)]",children:"HR Analytics"}),e.jsxs("p",{className:"text-xs text-[var(--color-text-secondary)]",children:["Last updated: ",new Date(s.calculatedAt).toLocaleTimeString()]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex items-center gap-2 bg-[var(--color-bg-hover)] rounded-lg p-1",children:yd.map(c=>e.jsx("button",{onClick:()=>r(c.value),className:`px-3 py-1.5 rounded-md text-xs font-medium transition-colors 200 ${t===c.value?"bg-brand-500/20 text-brand-400":"text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)]"}`,children:c.label},c.value))}),e.jsx("button",{onClick:n,className:"p-2 hover:bg-[var(--color-bg-hover)] rounded-lg text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]",title:"Refresh",children:e.jsx(Xe,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-6",children:[e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-4",children:i.primary.map((c,d)=>e.jsxs("div",{className:"p-4 bg-[var(--color-bg-hover)] rounded-xl border border-[var(--color-border-subtle)]",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-sm text-[var(--color-text-secondary)]",children:c.label}),e.jsx(wd,{trend:c.trend})]}),e.jsx("div",{className:"text-3xl font-bold text-[var(--color-text-primary)]",children:c.value}),c.subtitle&&e.jsx("div",{className:"text-xs text-[var(--color-text-muted)] mt-1",children:c.subtitle})]},c.label))}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"p-4 bg-[var(--color-bg-hover)] rounded-xl border border-[var(--color-border-subtle)]",children:[e.jsxs("h4",{className:"text-sm font-semibold text-[var(--color-text-primary)] mb-4 flex items-center gap-2",children:[e.jsx(_r,{className:"w-4 h-4 text-brand-400"}),"Headcount Trend"]}),e.jsx("div",{className:"h-64 min-w-0",children:e.jsx(dr,{children:e.jsxs(Nn,{data:s.headcountTrend,children:[e.jsx(zr,{dataKey:"date",tick:{fill:"rgba(255,255,255,0.5)",fontSize:10},axisLine:{stroke:"rgba(255,255,255,0.1)"},tickFormatter:c=>{const d=new Date(c);return`${d.getMonth()+1}/${d.getDate()}`}}),e.jsx(Wr,{tick:{fill:"rgba(255,255,255,0.5)",fontSize:10},axisLine:{stroke:"rgba(255,255,255,0.1)"}}),e.jsx(ur,{contentStyle:{backgroundColor:"rgba(30,41,59,0.95)",border:"1px solid rgba(255,255,255,0.1)",borderRadius:"8px"},labelStyle:{color:"white"}}),e.jsx(Sn,{type:"monotone",dataKey:"count",stroke:Ze.primary,strokeWidth:2,dot:!1})]})})})]}),e.jsxs("div",{className:"p-4 bg-[var(--color-bg-hover)] rounded-xl border border-[var(--color-border-subtle)]",children:[e.jsxs("h4",{className:"text-sm font-semibold text-[var(--color-text-primary)] mb-4 flex items-center gap-2",children:[e.jsx(Zr,{className:"w-4 h-4 text-[var(--color-primary)]"}),"Department Distribution"]}),e.jsx("div",{className:"h-64 min-w-0",children:e.jsx(dr,{children:e.jsxs(Ha,{data:s.departmentMetrics.slice(0,6),layout:"vertical",children:[e.jsx(zr,{type:"number",tick:{fill:"rgba(255,255,255,0.5)",fontSize:10}}),e.jsx(Wr,{dataKey:"department",type:"category",tick:{fill:"rgba(255,255,255,0.5)",fontSize:10},width:100}),e.jsx(ur,{contentStyle:{backgroundColor:"rgba(30,41,59,0.95)",border:"1px solid rgba(255,255,255,0.1)",borderRadius:"8px"}}),e.jsx(Ba,{dataKey:"headcount",fill:Ze.info,radius:[0,4,4,0]})]})})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"p-4 bg-[var(--color-bg-hover)] rounded-xl border border-[var(--color-border-subtle)]",children:[e.jsxs("h4",{className:"text-sm font-semibold text-[var(--color-text-primary)] mb-4 flex items-center gap-2",children:[e.jsx(ve,{className:"w-4 h-4 text-emerald-400"}),"Tenure Distribution"]}),e.jsx("div",{className:"h-48 min-w-0",children:e.jsx(dr,{children:e.jsxs(Ti,{children:[e.jsx(Is,{data:s.tenureDistribution.map(({label:c,count:d,percentage:m})=>({label:c,count:d,percentage:m})),dataKey:"count",nameKey:"label",cx:"50%",cy:"50%",innerRadius:40,outerRadius:70,paddingAngle:2,children:s.tenureDistribution.map((c,d)=>e.jsx(Sr,{fill:br[d%br.length]},c.label))}),e.jsx(ur,{contentStyle:{backgroundColor:"rgba(30,41,59,0.95)",border:"1px solid rgba(255,255,255,0.1)",borderRadius:"8px"}})]})})}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-1 mt-2",children:s.tenureDistribution.map((c,d)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("div",{className:"w-2 h-2 rounded-full",style:{backgroundColor:br[d%br.length]}}),e.jsx("span",{className:"text-[var(--color-text-secondary)] truncate",children:c.label}),e.jsx("span",{className:"text-[var(--color-text-primary)] ml-auto",children:c.count})]},c.label))})]}),e.jsxs("div",{className:"p-4 bg-[var(--color-bg-hover)] rounded-xl border border-[var(--color-border-subtle)]",children:[e.jsxs("h4",{className:"text-sm font-semibold text-[var(--color-text-primary)] mb-4 flex items-center gap-2",children:[e.jsx(sr,{className:"w-4 h-4 text-amber-400"}),"Performance Ratings"]}),e.jsx("div",{className:"h-48 min-w-0",children:e.jsx(dr,{children:e.jsxs(Ha,{data:s.performanceDistribution,children:[e.jsx(zr,{dataKey:"rating",tick:{fill:"rgba(255,255,255,0.5)",fontSize:10}}
200),e.jsx(Wr,{tick:{fill:"rgba(255,255,255,0.5)",fontSize:10}}),e.jsx(ur,{contentStyle:{backgroundColor:"rgba(30,41,59,0.95)",border:"1px solid rgba(255,255,255,0.1)",borderRadius:"8px"},formatter:(c,d,m)=>[c,m.payload.label]}),e.jsx(Ba,{dataKey:"count",radius:[4,4,0,0],children:s.performanceDistribution.map((c,d)=>e.jsx(Sr,{fill:c.rating>=4?Ze.success:c.rating===3?Ze.info:Ze.warning},c.rating))})]})})}),e.jsxs("div",{className:"mt-3 text-center",children:[e.jsx("span",{className:"text-2xl font-bold text-[var(--color-text-primary)]",children:s.avgPerformanceRating.toFixed(1)}),e.jsx("span",{className:"text-sm text-[var(--color-text-secondary)] ml-2",children:"avg rating"})]})]}),e.jsxs("div",{className:"p-4 bg-[var(--color-bg-hover)] rounded-xl border border-[var(--color-border-subtle)]",children:[e.jsxs("h4",{className:"text-sm font-semibold text-[var(--color-text-primary)] mb-4 flex items-center gap-2",children:[e.jsx(Ee,{className:"w-4 h-4 text-red-400"}),"Risk Analysis"]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center justify-between text-xs text-[var(--color-text-secondary)] mb-2",children:e.jsx("span",{children:"Flight Risk"})}),e.jsxs("div",{className:"flex gap-1 h-6 rounded overflow-hidden",children:[e.jsx("div",{className:"bg-red-500 flex items-center justify-center text-xs text-[var(--color-text-primary)] font-medium",style:{width:`${s.riskMetrics.highFlightRisk/s.activeEmployees*100}%`,minWidth:s.riskMetrics.highFlightRisk>0?"20px":0},children:s.riskMetrics.highFlightRisk||""}),e.jsx("div",{className:"bg-amber-500 flex items-center justify-center text-xs text-[var(--color-text-primary)] font-medium",style:{width:`${s.riskMetrics.mediumFlightRisk/s.activeEmployees*100}%`,minWidth:s.riskMetrics.mediumFlightRisk>0?"20px":0},children:s.riskMetrics.mediumFlightRisk||""}),e.jsx("div",{className:"bg-emerald-500 flex items-center justify-center text-xs text-[var(--color-text-primary)] font-medium",style:{width:`${s.riskMetrics.lowFlightRisk/s.activeEmployees*100}%`,minWidth:s.riskMetrics.lowFlightRisk>0?"20px":0},children:s.riskMetrics.lowFlightRisk||""})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center justify-between text-xs text-[var(--color-text-secondary)] mb-2",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gl,{className:"w-3 h-3"}),"Burnout Risk"]})}),e.jsxs("div",{className:"flex gap-1 h-6 rounded overflow-hidden",children:[e.jsx("div",{className:"bg-red-500 flex items-center justify-center text-xs text-[var(--color-text-primary)] font-medium",style:{width:`${s.riskMetrics.highBurnoutRisk/s.activeEmployees*100}%`,minWidth:s.riskMetrics.highBurnoutRisk>0?"20px":0},children:s.riskMetrics.highBurnoutRisk||""}),e.jsx("div",{className:"bg-amber-500 flex items-center justify-center text-xs text-[var(--color-text-primary)] font-medium",style:{width:`${s.riskMetrics.mediumBurnoutRisk/s.activeEmployees*100}%`,minWidth:s.riskMetrics.mediumBurnoutRisk>0?"20px":0},children:s.riskMetrics.mediumBurnoutRisk||""}),e.jsx("div",{className:"bg-emerald-500 flex items-center justify-center text-xs text-[var(--color-text-primary)] font-medium",style:{width:`${s.riskMetrics.lowBurnoutRisk/s.activeEmployees*100}%`,minWidth:s.riskMetrics.lowBurnoutRisk>0?"20px":0},children:s.riskMetrics.lowBurnoutRisk||""})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-4 pt-2",children:[e.jsxs("div",{className:"flex items-center gap-1 text-xs",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-red-500"}),e.jsx("span",{className:"text-[var(--color-text-secondary)]",children:"High"})]}),e.jsxs("div",{className:"flex items-center gap-1 text-xs",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-amber-500"}),e.jsx("span",{className:"text-[var(--color-text-secondary)]",children:"Medium"})]}),e.jsxs("div",{className:"flex items-center gap-1 text-xs",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-emerald-500"}),e.jsx("span",{className:"text-[var(--color-text-secondary)]",children:"Low"})]})]})]})]})]}),e.jsxs("div",{className:"p-4 bg-[var(--color-bg-hover)] rounded-xl border border-[var(--color-border-subtle)]",children:[e.jsxs("h4",{className:"text-sm font-semibold text-[var(--color-text-primary)] mb-4 flex items-center gap-2",children:[e.jsx(Zr,{className:"w-4 h-4 text-cyan-400"}),"Department Metrics"]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(aa,{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-[var(--color-border-subtle)]",children:[e.jsx("th",{className:"text-left py-2 px-3 text-[var(--color-text-secondary)] font-medium",children:"Department"}),e.jsx("th",{className:"text-right py-2 px-3 text-[var(--color-text-secondary)] font-medium",children:"Headcount"}),e.jsx("th",{className:"text-right py-2 px-3 text-[var(--color-text-secondary)] font-medium",children:"Avg Tenure"}),e.jsx("th",{className:"text-right py-2 px-3 text-[var(--color-text-secondary)] font-medium",children:"Performance"}),e.jsx("th",{className:"text-right py-2 px-3 text-[var(--color-text-secondary)] font-medium",children:"Flight Risk"}),e.jsx("th",{className:"text-right py-2 px-3 text-[var(--color-text-secondary)] font-medium",children:"Turnover"})]})}),e.jsx("tbody",{className:"divide-y divide-white/5",children:s.departmentMetrics.map(c=>e.jsxs("tr",{className:"hover:bg-[var(--color-bg-hover)]",children:[e.jsx("td",{className:"py-2 px-3 text-[var(--color-text-primary)] font-medium",children:c.department}),e.jsx("td",{className:"py-2 px-3 text-right text-[var(--color-text-primary)]",children:c.headcount}),e.jsxs("td",{className:"py-2 px-3 text-right text-[var(--color-text-primary)]",children:[Math.round(c.avgTenure/12*10)/10,"y"]}),e.jsx("td",{className:"py-2 px-3 text-right",children:e.jsx("span",{className:c.avgPerformance>=4?"text-emerald-400":c.avgPerformance>=3?"text-[var(--color-text-primary)]":"text-amber-400",children:c.avgPerformance.toFixed(1)})}),e.jsx("td",{className:"py-2 px-3 text-right",children:e.jsxs("span",{className:c.avgFlightRisk>=70?"text-red-400":c.avgFlightRisk>=40?"text-amber-400":"text-emerald-400",children:[Math.round(c.avgFlightRisk),"%"]})}),e.jsx("td",{className:"py-2 px-3 text-right",children:e.jsxs("span",{className:c.turnoverRate>20?"text-red-400":c.turnoverRate>10?"text-amber-400":"text-emerald-400",children:[c.turnoverRate.toFixed(1),"%"]})})]},c.department))})]})})]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-4",children:s.employmentTypes.map(c=>e.jsxs("div",{className:"p-4 bg-[var(--color-bg-hover)] rounded-xl border border-[var(--color-border-subtle)]",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(st,{className:"w-4 h-4 text-[var(--color-text-secondary)]"}),e.jsx("span",{className:"text-sm text-[var(--color-text-secondary)]",children:c.type})]}),e.jsx("div",{className:"text-2xl font-bold text-[var(--color-text-primary)]",children:c.count}),e.jsxs("div",{className:"text-xs text-[var(--color-text-muted)]",children:[c.percentage,"% of workforce"]})]},c.type))})]})]})},kr=[{key:"firstName",label:"First Name",required:!0},{key:"lastName",label:"Last Name",required:!0},{key:"email",label:"Email",required:!0},{key:"phone",label:"Phone",required:!1},{key:"role",label:"Job Title/Role",required:!1},{key:"department",label:"Department",required:!1},{key:"hireDate",label:"Hire Date",required:!1},{key:"status",label:"Status",required:!1},{key:"employmentType",label:"Employment Type",required:!1},{key:"payType",label:"Pay Type",required:!1},{key:"payRate",label:"Pay Rate",required:!1},{key:"address",label:"Address",required:!1},{key:"dob",label:"Date of Birth",required:!1},{key:"managerId",label:"Manager ID",required:!1},{key:"notes",label:"Notes",required:!1},{key:"emergencyContactName",label:"Emergency Contact Name",required:!1},{key:"emergencyContactPhone",label:"Emergency Contact Phone",required:!1},{key:"emergencyContactRelation",label:"Emergency Contact Relation",required:!1},{key:"skip",label:"-- Do Not Import --",required:!1}];function ye(l){return l?l.includes(",")||l.includes(` 201`)||l.includes('"')?`"${l.replace(/"/g,'""')}"`:l:""}function $t(l){const t=[];let r="",a=!1;for(let o=0;o<l.length;o++){const s=l[o],i=l[o+1];a?s==='"'&&i==='"'?(r+='"',o++):s==='"'?a=!1:r+=s:s==='"'?a=!0:s===","?(t.push(r.trim()),r=""):r+=s}return t.push(r.trim()),t}function _d(l){if(l.length===0)return"";const t=["First Name","Last Name","Email","Phone","Job Title/Role","Department","Hire Date","Status","Employment Type","Pay Type","Pay Rate","Address","Date of Birth","Manager ID","Notes","Emergency Contact Name","Emergency Contact Phone","Emergency Contact Relation","Flight Risk Score","Burnout Risk Score","Performance Rating"],r=l.map(o=>{var s,i,n,c,d,m,u;return[ye(o.firstName||""),ye(o.lastName||""),ye(o.email||""),ye(o.phone||""),ye(o.role||""),ye(o.department||""),ye(o.hireDate||""),ye(o.status||""),ye(o.employmentType||""),ye(o.payType||""),((s=o.payRate)==null?void 0:s.toString())||"0",ye(o.address||""),ye(o.dob||""),ye(o.managerId||""),ye(o.notes||""),ye(((i=o.emergencyContact)==null?void 0:i.name)||""),ye(((n=o.emergencyContact)==null?void 0:n.phone)||""),ye(((c=o.emergencyContact)==null?void 0:c.relation)||""),((d=o.flightRiskScore)==null?void 0:d.toString())||"0",((m=o.burnoutRiskScore)==null?void 0:m.toString())||"0",((u=o.performanceRating)==null?void 0:u.toString())||"0"]});return[t.join(","),...r.map(o=>o.join(","))].join(` 202`)}function Fs(l,t="employees.csv"){const r=new Blob([l],{type:"text/csv;charset=utf-8;"}),a=document.createElement("a"),o=URL.createObjectURL(r);a.setAttribute("href",o),a.setAttribute("download",t),a.style.visibility="hidden",document.body.appendChild(a),a.click(),document.body.removeChild(a)}function Nd(l,t=3){const r=l.split(` 203`).filter(s=>s.trim());if(r.length===0)return{headers:[],sampleRows:[],totalRows:0};const a=$t(r[0]),o=[];for(let s=1;s<Math.min(r.length,t+1);s++)o.push($t(r[s]));return{headers:a,sampleRows:o,totalRows:r.length-1}}function Sd(l,t){const r=[],a=kr.filter(n=>n.required);for(const n of a)Object.values(t).includes(n.key)||r.push(`Required field "${n.label}" is not mapped`);const o=l.split(` 204`).filter(n=>n.trim());if(o.length<2)return r.push("CSV file must have at least one data row"),{valid:!1,errors:r};const s=$t(o[0]),i=[];for(const[n,c]of Object.entries(t)){const d=kr.find(m=>m.key===c);if(d!=null&&d.required){const m=s.indexOf(n);
204m!==-1&&i.push({field:d.label,index:m})}}for(let n=1;n<o.length;n++){const c=$t(o[n]);for(const{field:d,index:m}of i)(!c[m]||c[m].trim()==="")&&r.push(`Row ${n}: Missing required field "${d}"`)}return{valid:r.length===0,errors:r}}function Cd(l,t){const r=l.split(` 205`).filter(i=>i.trim());if(r.length<2)return[];const a=$t(r[0]),o=[],s=new Map;for(const[i,n]of Object.entries(t))if(n&&n!=="skip"){const c=a.indexOf(i);c!==-1&&s.set(n,c)}for(let i=1;i<r.length;i++){const n=$t(r[i]);if(n.length===0||n.every($=>!$.trim()))continue;const c=$=>{var E;const R=s.get($);return R!==void 0&&((E=n[R])==null?void 0:E.trim())||""},d=c("emergencyContactName"),m=c("emergencyContactPhone"),u=c("emergencyContactRelation"),h=d||m||u?{name:d,phone:m,relation:u}:void 0,v=c("status"),y=["Active","Terminated","Leave","Candidate"].includes(v)?v:"Active",p=c("employmentType"),N=["Full Time","Part Time","Contractor","Intern"].includes(p)?p:"Full Time",S=c("payType"),j=["Salary","Hourly"].includes(S)?S:"Salary",I={firstName:c("firstName"),lastName:c("lastName"),email:c("email"),phone:c("phone")||void 0,role:c("role"),department:c("department"),hireDate:c("hireDate")||new Date().toISOString().split("T")[0],status:y,employmentType:N,payType:j,payRate:parseFloat(c("payRate"))||0,address:c("address")||void 0,dob:c("dob")||void 0,managerId:c("managerId")||void 0,notes:c("notes")||"",emergencyContact:h,flightRiskScore:0,burnoutRiskScore:0,performanceRating:3};o.push(I)}return o}function kd(l){const t={},r={firstName:["first name","firstname","first","given name"],lastName:["last name","lastname","last","surname","family name"],email:["email","e-mail","email address"],phone:["phone","telephone","mobile","cell","phone number"],role:["role","job title","title","position","job"],department:["department","dept","team","division"],hireDate:["hire date","hiredate","start date","joined","date hired"],status:["status","employment status"],employmentType:["employment type","type","emp type","work type"],payType:["pay type","paytype","compensation type"],payRate:["pay rate","payrate","salary","rate","wage","hourly rate"],address:["address","home address","street address"],dob:["dob","date of birth","birthday","birth date"],managerId:["manager id","managerid","manager","reports to"],notes:["notes","comments","remarks"],emergencyContactName:["emergency contact name","emergency name","ec name"],emergencyContactPhone:["emergency contact phone","emergency phone","ec phone"],emergencyContactRelation:["emergency contact relation","emergency relation","ec relation","relationship"]};for(const a of l){const o=a.toLowerCase().trim();for(const[s,i]of Object.entries(r))if(i.includes(o)){t[a]=s;break}t[a]||(t[a]="skip")}return t}function Rd(){const l=["First Name","Last Name","Email","Phone","Job Title/Role","Department","Hire Date","Status","Employment Type","Pay Type","Pay Rate","Address","Date of Birth","Manager ID","Notes"],t=["John","Doe","[email protected]","555-123-4567","Software Engineer","Engineering","2024-01-15","Active","Full Time","Salary","75000","123 Main St","1990-05-20","","Sample employee"];return[l.join(","),t.join(",")].join(` 206`)}const Dd=["Active","Terminated","Leave","Candidate"],Ed=["Full Time","Part Time","Contractor","Intern"],Td=({filters:l,departments:t,onFiltersChange:r,onExport:a,onImport:o,onSettings:s,employeeCount:i})=>{const[n,c]=x.useState(!1),[d,m]=x.useState(!1),[u,h]=x.useState(!1),[v,y]=x.useState(!1),p=x.useRef(null),N=l.query||"",S=l.departments||[],j=l.statuses||[],I=l.employmentTypes||[],$=S.length+j.length+I.length,R=f=>{r({...l,query:f})},E=f=>{const g=S.includes(f)?S.filter(L=>L!==f):[...S,f];r({...l,departments:g})},O=f=>{const g=j.includes(f)?j.filter(L=>L!==f):[...j,f];r({...l,statuses:g})},D=f=>{const g=I.includes(f)?I.filter(L=>L!==f):[...I,f];r({...l,employmentTypes:g})},b=()=>{r({})},P=()=>{const f=Rd();Fs(f,"employee_import_template.csv")},W=()=>{var f;(f=p.current)==null||f.click()},k=f=>{var L;const g=(L=f.target.files)==null?void 0:L[0];g&&(o(g),p.current&&(p.current.value=""))};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(rr,{"aria-hidden":"true",className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-[var(--color-text-muted)]"}),e.jsx("input",{type:"text","aria-label":"Search employees",placeholder:"Search by name, email, or role...",value:N,onChange:f=>R(f.target.value),className:`w-full pl-10 pr-4 py-2.5 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg 207 text-[var(--color-text-primary)] placeholder-[var(--color-text-muted)] focus:outline-none focus:border-[var(--color-primary)]/50 208 focus:ring-1 focus:ring-[var(--color-primary)]/30`}),N&&e.jsx("button",{onClick:()=>R(""),"aria-label":"Clear search",className:"absolute right-3 top-1/2 -translate-y-1/2 text-[var(--color-text-muted)] hover:text-[var(--color-text-primary)]",children:e.jsx(de,{"aria-hidden":"true",className:"w-4 h-4"})})]}),e.jsxs("button",{onClick:()=>c(!n),className:`flex items-center gap-2 px-4 py-2.5 rounded-lg border transition-colors 209 ${n||$>0?"bg-[var(--color-primary)]/20 border-[var(--color-primary)]/30 text-[var(--color-primary)]":"bg-[var(--color-bg-hover)] border-[var(--color-border-subtle)] text-[var(--color-text-primary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)]"}`,children:[e.jsx(tn,{"aria-hidden":"true",className:"w-4 h-4"}),e.jsx("span",{children:"Filters"}),$>0&&e.jsx("span",{className:"px-1.5 py-0.5 text-xs font-bold rounded-full bg-[var(--color-primary)] text-[var(--color-bg-base)]",children:$})]}),e.jsxs("button",{onClick:a,disabled:i===0,className:`flex items-center gap-2 px-4 py-2.5 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg 210 text-[var(--color-text-primary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)] transition-colors 211 disabled:opacity-50 disabled:cursor-not-allowed`,children:[e.jsx(wl,{"aria-hidden":"true",className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Export"})]}),e.jsxs("button",{onClick:W,className:`flex items-center gap-2 px-4 py-2.5 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg 212 text-[var(--color-text-primary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)] transition-colors`,children:[e.jsx(Ft,{"aria-hidden":"true",className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Import"})]}),s&&e.jsx("button",{onClick:s,className:`flex items-center gap-2 px-4 py-2.5 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg 213 text-[var(--color-text-primary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)] transition-colors`,"aria-label":"Employee Number Settings",children:e.jsx(na,{"aria-hidden":"true",className:"w-4 h-4"})}),e.jsx("input",{ref:p,type:"file",accept:".csv",onChange:k,className:"hidden"})]}),n&&e.jsxs("div",{className:"p-4 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsxs("button",{onClick:()=>{m(!d),h(!1),y(!1)},className:`flex items-center gap-2 px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg 214 text-[var(--color-text-primary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)] transition-colors min-w-[150px]`,children:[e.jsx("span",{children:"Department"}),S.length>0&&e.jsx("span",{className:"px-1.5 py-0.5 text-xs font-bold rounded-full bg-[var(--color-primary)] text-[var(--color-bg-base)]",children:S.length}),e.jsx(vt,{"aria-hidden":"true",className:"w-4 h-4 ml-auto"})]}),d&&e.jsx("div",{className:"absolute z-20 mt-1 w-48 max-h-60 overflow-y-auto bg-[var(--color-bg-base)] border border-[var(--color-border-default)] rounded-lg shadow-xl",children:t.length===0?e.jsx("div",{className:"px-3 py-2 text-[var(--color-text-secondary)] text-sm",children:"No departments"}):t.map(f=>e.jsx("button",{onClick:()=>E(f),className:`w-full px-3 py-2 text-left text-sm hover:bg-[var(--color-bg-hover)] transition-colors 215 ${S.includes(f)?"text-[var(--color-primary)] bg-[var(--color-primary)]/10":"text-[var(--color-text-primary)]"}`,children:f},f))})]}),e.jsxs("div",{className:"relative",children:[e.jsxs("button",{onClick:()=>{h(!u),m(!1),y(!1)},className:`flex items-center gap-2 px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg 216 text-[var(--color-text-primary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)] transition-colors min-w-[150px]`,children:[e.jsx("span",{children:"Status"}),j.length>0&&e.jsx("span",{className:"px-1.5 py-0.5 text-xs font-bold rounded-full bg-[var(--color-primary)] text-[var(--color-bg-base)]",children:j.length}),e.jsx(vt,{"aria-hidden":"true",className:"w-4 h-4 ml-auto"})]}),u&&e.jsx("div",{className:"absolute z-20 mt-1 w-48 bg-[var(--color-bg-base)] border border-[var(--color-border-default)] rounded-lg shadow-xl",children:Dd.map(f=>e.jsx("button",{onClick:()=>O(f),className:`w-full px-3 py-2 text-left text-sm hover:bg-[var(--color-bg-hover)] transition-colors 217 ${j.includes(f)?"text-[var(--color-primary)] bg-[var(--color-primary)]/10":"text-[var(--color-text-primary)]"}`,children:f},f))})]}),e.jsxs("div",{className:"relative",children:[e.jsxs("button",{onClick:()=>{y(!v),m(!1),h(!1)},className:`flex items-center gap-2 px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg 218 text-[var(--color-text-primary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)] transition-colors min-w-[150px]`,children:[e.jsx("span",{children:"Type"}),I.length>0&&e.jsx("span",{className:"px-1.5 py-0.5 text-xs font-bold rounded-full bg-[var(--color-primary)] text-[var(--color-bg-base)]",children:I.length}),e.jsx(vt,{"aria-hidden":"true",className:"w-4 h-4 ml-auto"})]}),v&&e.jsx("div",{className:"absolute z-20 mt-1 w-48 bg-[var(--color-bg-base)] border border-[var(--color-border-default)] rounded-lg shadow-xl",children:Ed.map(f=>e.jsx("button",{onClick:()=>D(f),className:`w-full px-3 py-2 text-left text-sm hover:bg-[var(--color-bg-hover)] transition-colors 219 ${I.includes(f)?"text-[var(--color-primary)] bg-[var(--color-primary)]/10":"text-[var(--color-text-primary)]"}`,children:f},f))})]}),$>0&&e.jsxs("button",{onClick:b,className:"flex items-center gap-2 px-3 py-2 text-[var(--color-danger)] hover:text-[var(--color-danger)] transition-colors",children:[e.jsx(de,{"aria-hidden":"true",className:"w-4 h-4"}),e.jsx("span",{children:"Clear all"})]})]}),e.jsx("div",{className:"pt-2 border-t border-[var(--color-border-subtle)]",children:e.jsx("button",{onClick:P,className:"text-sm text-[var(--color-primary)]/70 hover:text-[var(--color-primary)] transition-colors",children:"Download CSV import template"})})]}),!n&&$>0&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[S.map(f=>e.jsxs("span",{className:"flex items-center gap-1 px-2 py-1 text-xs rounded-full bg-[var(--color-primary)]/20 text-[var(--color-primary)]",children:[f,e.jsx("button",{onClick:()=>E(f),"aria-label":`Remove ${f} filter`,className:"hover:text-[var(--color-text-primary)]",children:e.jsx(de,{"aria-hidden":"true",className:"w-3 h-3"})})]},f)),j.map(f=>e.jsxs("span",{className:"flex items-center gap-1 px-2 py-1 text-xs rounded-full bg-[var(--color-primary-subtle)] text-[var(--color-primary)]",children:[f,e.jsx("button",{onClick:()=>O(f),"aria-label":`Remove ${f} filter`,className:"hover:text-[var(--color-text-primary)]",children:e.jsx(de,{"aria-hidden":"true",className:"w-3 h-3"})})]},f)),I.map(f=>e.jsxs("span",{className:"flex items-center gap-1 px-2 py-1 text-xs rounded-full bg-[var(--color-info)]/20 text-[var(--color-info)]",children:[f,e.jsx("button",{onClick:()=>D(f),"aria-label":`Remove ${f} filter`,className:"hover:text-[var(--color-text-primary)]",children:e.jsx(de,{"aria-hidden":"true",className:"w-3 h-3"})})]},f))]})]})},Id=["Active","Terminated","Leave","Candidate"],Ad=["Full Time","Part Time","Contractor","Intern"],Pd=["Salary","Hourly"],Od=({employee:l,employees:t,isOpen:r,onClose:a,onSave:o,onDelete:s,onOpenMobileInvite:i})=>{var R,E,O,D,b,P,W,k,f;const[n,c]=x.useState(!1),[d,m]=x.useState({}),[u,h]=x.useState(!1),[v,y]=x.useState(!1);x.useEffect(()=>{l&&(m({...l}),c(!1))},[l]);const p=(g,L)=>{m(z=>({...z,[g]:L}))},N=(g,L)=>{m(z=>{var X,C,Y;return{...z,emergencyContact:{name:((X=z.emergencyContact)==null?void 0:X.name)||"",phone:((C=z.emergencyContact)==null?void 0:C.phone)||"",relation:((Y=z.emergencyContact)==null?void 0:Y.relation)||"",[g]:L}}})},S=async()=>
219{if(!(!l||!d)){h(!0);try{await o({...l,...d}),c(!1)}catch(g){console.error("[EmployeeDetailModal] Save error:",g),alert("Failed to save changes")}finally{h(!1)}}},j=async()=>{if(l)try{await s(l.id),a()}catch(g){console.error("[EmployeeDetailModal] Delete error:",g),alert("Failed to delete employee")}},I=g=>{switch(g){case"Active":return"bg-[var(--color-success)]/20 text-[var(--color-success)] border-[var(--color-success)]/30";case"Terminated":return"bg-[var(--color-danger)]/20 text-[var(--color-danger)] border-[var(--color-danger)]/30";case"Leave":return"bg-[var(--color-warning)]/20 text-[var(--color-warning)] border-[var(--color-warning)]/30";case"Candidate":return"bg-[var(--color-primary-subtle)] text-[var(--color-primary)] border-[var(--color-primary-subtle)]";default:return"bg-[var(--color-bg-hover)] text-[var(--color-text-primary)] border-[var(--color-border-default)]"}},$=t.filter(g=>g.id!==(l==null?void 0:l.id)&&g.status==="Active");return!r||!l?null:e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-40 bg-[var(--color-bg-base)]/50 backdrop-blur-sm",onClick:a}),e.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"employee-detail-title",className:"fixed right-0 top-0 bottom-0 z-50 w-full max-w-lg bg-[var(--color-bg-base)]/95 backdrop-blur-2xl border-l border-[var(--color-primary)]/20 shadow-2xl overflow-hidden flex flex-col animate-in slide-in-from-right duration-300",children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-[var(--color-border-subtle)]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"w-12 h-12 rounded-full bg-gradient-to-br from-[var(--color-primary)] to-[var(--color-primary-hover)] flex items-center justify-center text-[var(--color-bg-base)] font-bold text-lg",children:[(R=l.firstName)==null?void 0:R[0],(E=l.lastName)==null?void 0:E[0]]}),e.jsxs("div",{children:[e.jsxs("h2",{id:"employee-detail-title",className:"text-lg font-bold text-[var(--color-text-primary)]",children:[l.firstName," ",l.lastName]}),e.jsx("p",{className:"text-sm text-[var(--color-text-secondary)]",children:l.role})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[n?e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>{m({...l}),c(!1)},className:"px-3 py-1.5 text-[var(--color-text-primary)] hover:text-[var(--color-text-primary)] transition-colors",children:"Cancel"}),e.jsxs("button",{onClick:S,disabled:u,className:"flex items-center gap-2 px-4 py-1.5 bg-[var(--color-primary)] hover:bg-[var(--color-primary-hover)] text-[var(--color-bg-base)] font-bold rounded-lg transition-colors disabled:opacity-50",children:[u?e.jsx("div",{"aria-hidden":"true",className:"w-4 h-4 border-2 border-[var(--color-bg-base)]/30 border-t-[var(--color-bg-base)] rounded-full animate-spin"}):e.jsx(sa,{"aria-hidden":"true",className:"w-4 h-4"}),"Save"]})]}):e.jsxs("button",{onClick:()=>c(!0),className:"flex items-center gap-2 px-3 py-1.5 bg-[var(--color-bg-hover)] hover:bg-[var(--color-bg-active)] text-[var(--color-text-primary)] rounded-lg transition-colors",children:[e.jsx(qt,{"aria-hidden":"true",className:"w-4 h-4"}),"Edit"]}),e.jsx("button",{onClick:a,"aria-label":"Close dialog",className:"p-2 text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)] rounded-lg transition-colors",children:e.jsx(de,{"aria-hidden":"true",className:"w-5 h-5"})})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-4 space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:`px-3 py-1 rounded-full text-sm font-medium border ${I(d.status||"Active")}`,children:d.status||"Active"}),e.jsx("span",{className:"px-3 py-1 rounded-full text-sm font-medium bg-[var(--color-bg-hover)] text-[var(--color-text-primary)] border border-[var(--color-border-default)]",children:d.employmentType||"Full Time"})]}),e.jsxs("section",{children:[e.jsxs("h3",{className:"text-sm font-bold text-[var(--color-text-secondary)] uppercase tracking-wide mb-3 flex items-center gap-2",children:[e.jsx(tt,{"aria-hidden":"true",className:"w-4 h-4"}),"Personal Information"]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"detail-first-name",className:"block text-xs text-[var(--color-text-secondary)] mb-1",children:"First Name"}),n?e.jsx("input",{id:"detail-first-name",type:"text",value:d.firstName||"",onChange:g=>p("firstName",g.target.value),className:"w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg text-[var(--color-text-primary)] focus:outline-none focus:border-[var(--color-primary)]/50"}):e.jsx("p",{className:"text-[var(--color-text-primary)]",children:l.firstName})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"detail-last-name",className:"block text-xs text-[var(--color-text-secondary)] mb-1",children:"Last Name"}),n?e.jsx("input",{id:"detail-last-name",type:"text",value:d.lastName||"",onChange:g=>p("lastName",g.target.value),className:"w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg text-[var(--color-text-primary)] focus:outline-none focus:border-[var(--color-primary)]/50"}):e.jsx("p",{className:"text-[var(--color-text-primary)]",children:l.lastName})]})]}),e.jsxs("div",{children:[e.jsxs("label",{htmlFor:"detail-email",className:"block text-xs text-[var(--color-text-secondary)] mb-1 flex items-center gap-1",children:[e.jsx(da,{"aria-hidden":"true",className:"w-3 h-3"})," Email"]}),n?e.jsx("input",{id:"detail-email",type:"email",value:d.email||"",onChange:g=>p("email",g.target.value),className:"w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg text-[var(--color-text-primary)] focus:outline-none focus:border-[var(--color-primary)]/50"}):e.jsx("p",{className:"text-[var(--color-text-primary)]",children:l.email||"-"})]}),e.jsxs("div",{children:[e.jsxs("label",{htmlFor:"detail-phone",className:"block text-xs text-[var(--color-text-secondary)] mb-1 flex items-center gap-1",children:[e.jsx(ks,{"aria-hidden":"true",className:"w-3 h-3"})," Phone"]}),n?e.jsx("input",{id:"detail-phone",type:"tel",value:d.phone||"",onChange:g=>p("phone",g.target.value),className:"w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg text-[var(--color-text-primary)] focus:outline-none focus:border-[var(--color-primary)]/50"}):e.jsx("p",{className:"text-[var(--color-text-primary)]",children:l.phone||"-"})]}),e.jsxs("div",{children:[e.jsxs("label",{htmlFor:"detail-address",className:"block text-xs text-[var(--color-text-secondary)] mb-1 flex items-center gap-1",children:[e.jsx(Je,{"aria-hidden":"true",className:"w-3 h-3"})," Address"]}),n?e.jsx("input",{id:"detail-address",type:"text",value:d.address||"",onChange:g=>p("address",g.target.value),className:"w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg text-[var(--color-text-primary)] focus:outline-none focus:border-[var(--color-primary)]/50"}):e.jsx("p",{className:"text-[var(--color-text-primary)]",children:l.address||"-"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"detail-dob",className:"block text-xs text-[var(--color-text-secondary)] mb-1",children:"Date of Birth"}),n?e.jsx("input",{id:"detail-dob",type:"date",value:d.dob||"",onChange:g=>p("dob",g.target.value),className:"w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg text-[var(--color-text-primary)] focus:outline-none focus:border-[var(--color-primary)]/50"}):e.jsx("p",{className:"text-[var(--color-text-primary)]",children:l.dob||"-"})]})]})]}),e.jsxs("section",{children:[e.jsxs("h3",{className:"text-sm font-bold text-[var(--color-text-secondary)] uppercase tracking-wide mb-3 flex items-center gap-2",children:[e.jsx(st,{"aria-hidden":"true",className:"w-4 h-4"}),"Employment Details"]}
219),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"detail-role",className:"block text-xs text-[var(--color-text-secondary)] mb-1",children:"Job Title / Role"}),n?e.jsx("input",{id:"detail-role",type:"text",value:d.role||"",onChange:g=>p("role",g.target.value),className:"w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg text-[var(--color-text-primary)] focus:outline-none focus:border-[var(--color-primary)]/50"}):e.jsx("p",{className:"text-[var(--color-text-primary)]",children:l.role||"-"})]}),e.jsxs("div",{children:[e.jsxs("label",{htmlFor:"detail-department",className:"block text-xs text-[var(--color-text-secondary)] mb-1 flex items-center gap-1",children:[e.jsx(ca,{"aria-hidden":"true",className:"w-3 h-3"})," Department"]}),n?e.jsx("input",{id:"detail-department",type:"text",value:d.department||"",onChange:g=>p("department",g.target.value),className:"w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg text-[var(--color-text-primary)] focus:outline-none focus:border-[var(--color-primary)]/50"}):e.jsx("p",{className:"text-[var(--color-text-primary)]",children:l.department||"-"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"detail-status",className:"block text-xs text-[var(--color-text-secondary)] mb-1",children:"Status"}),n?e.jsx("select",{id:"detail-status",value:d.status||"Active",onChange:g=>p("status",g.target.value),className:"w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg text-[var(--color-text-primary)] focus:outline-none focus:border-[var(--color-primary)]/50",children:Id.map(g=>e.jsx("option",{value:g,className:"bg-[var(--color-bg-base)]",children:g},g))}):e.jsx("p",{className:"text-[var(--color-text-primary)]",children:l.status})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"detail-emp-type",className:"block text-xs text-[var(--color-text-secondary)] mb-1",children:"Employment Type"}),n?e.jsx("select",{id:"detail-emp-type",value:d.employmentType||"Full Time",onChange:g=>p("employmentType",g.target.value),className:"w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg text-[var(--color-text-primary)] focus:outline-none focus:border-[var(--color-primary)]/50",children:Ad.map(g=>e.jsx("option",{value:g,className:"bg-[var(--color-bg-base)]",children:g},g))}):e.jsx("p",{className:"text-[var(--color-text-primary)]",children:l.employmentType})]})]}),e.jsxs("div",{children:[e.jsxs("label",{htmlFor:"detail-hire-date",className:"block text-xs text-[var(--color-text-secondary)] mb-1 flex items-center gap-1",children:[e.jsx(be,{"aria-hidden":"true",className:"w-3 h-3"})," Hire Date"]}),n?e.jsx("input",{id:"detail-hire-date",type:"date",value:d.hireDate||"",onChange:g=>p("hireDate",g.target.value),className:"w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg text-[var(--color-text-primary)] focus:outline-none focus:border-[var(--color-primary)]/50"}):e.jsx("p",{className:"text-[var(--color-text-primary)]",children:l.hireDate||"-"})]}),e.jsxs("div",{children:[e.jsxs("label",{htmlFor:"detail-manager",className:"block text-xs text-[var(--color-text-secondary)] mb-1 flex items-center gap-1",children:[e.jsx(jl,{"aria-hidden":"true",className:"w-3 h-3"})," Manager"]}),n?e.jsxs("select",{id:"detail-manager",value:d.managerId||"",onChange:g=>p("managerId",g.target.value||void 0),className:"w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg text-[var(--color-text-primary)] focus:outline-none focus:border-[var(--color-primary)]/50",children:[e.jsx("option",{value:"",className:"bg-[var(--color-bg-base)]",children:"No Manager"}),$.map(g=>e.jsxs("option",{value:g.id,className:"bg-[var(--color-bg-base)]",children:[g.firstName," ",g.lastName," - ",g.role]},g.id))]}):e.jsx("p",{className:"text-[var(--color-text-primary)]",children:l.managerId?(()=>{const g=t.find(L=>
219L.id===l.managerId);return g?`${g.firstName} ${g.lastName}`:"-"})():"-"})]})]})]}),e.jsxs("section",{children:[e.jsxs("h3",{className:"text-sm font-bold text-[var(--color-text-secondary)] uppercase tracking-wide mb-3 flex items-center gap-2",children:[e.jsx(ps,{"aria-hidden":"true",className:"w-4 h-4"}),"Compensation"]}),e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"detail-pay-type",className:"block text-xs text-[var(--color-text-secondary)] mb-1",children:"Pay Type"}),n?e.jsx("select",{id:"detail-pay-type",value:d.payType||"Salary",onChange:g=>p("payType",g.target.value),className:"w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg text-[var(--color-text-primary)] focus:outline-none focus:border-[var(--color-primary)]/50",children:Pd.map(g=>e.jsx("option",{value:g,className:"bg-[var(--color-bg-base)]",children:g},g))}):e.jsx("p",{className:"text-[var(--color-text-primary)]",children:l.payType})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"detail-pay-rate",className:"block text-xs text-[var(--color-text-secondary)] mb-1",children:"Pay Rate"}),n?e.jsx("input",{id:"detail-pay-rate",type:"number",value:d.payRate||0,onChange:g=>p("payRate",parseFloat(g.target.value)||0),className:"w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg text-[var(--color-text-primary)] focus:outline-none focus:border-[var(--color-primary)]/50"}):e.jsxs("p",{className:"text-[var(--color-text-primary)]",children:["$",((O=l.payRate)==null?void 0:O.toLocaleString())||0,l.payType==="Hourly"?"/hr":"/yr"]})]})]})})]}),e.jsxs("section",{children:[e.jsxs("h3",{className:"text-sm font-bold text-[var(--color-text-secondary)] uppercase tracking-wide mb-3 flex items-center gap-2",children:[e.jsx(bs,{"aria-hidden":"true",className:"w-4 h-4"}),"Emergency Contact"]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"detail-ec-name",className:"block text-xs text-[var(--color-text-secondary)] mb-1",children:"Emergency Contact Name"}),n?e.jsx("input",{id:"detail-ec-name",type:"text",value:((D=d.emergencyContact)==null?void 0:D.name)||"",onChange:g=>N("name",g.target.value),className:"w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg text-[var(--color-text-primary)] focus:outline-none focus:border-[var(--color-primary)]/50"}):e.jsx("p",{className:"text-[var(--color-text-primary)]",children:((b=l.emergencyContact)==null?void 0:b.name)||"-"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"detail-ec-phone",className:"block text-xs text-[var(--color-text-secondary)] mb-1",children:"Emergency Contact Phone"}),n?e.jsx("input",{id:"detail-ec-phone",type:"tel",value:((P=d.emergencyContact)==null?void 0:P.phone)||"",onChange:g=>N("phone",g.target.value),className:"w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg text-[var(--color-text-primary)] focus:outline-none focus:border-[var(--color-primary)]/50"}):e.jsx("p",{className:"text-[var(--color-text-primary)]",children:((W=l.emergencyContact)==null?void 0:W.phone)||"-"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"detail-ec-relation",className:"block text-xs text-[var(--color-text-secondary)] mb-1",children:"Relationship"}),n?e.jsx("input",{id:"detail-ec-relation",type:"text",value:((k=d.emergencyContact)==null?void 0:k.relation)||"",onChange:g=>N("relation",g.target.value),className:"w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg text-[var(--color-text-primary)] focus:outline-none focus:border-[var(--color-primary)]/50"}):e.jsx("p",{className:"text-[var(--color-text-primary)]",children:((f=l.emergencyContact)==null?void 0:f.relation)||"-"})]})]})]})]}),i&&e.jsxs("section",{children:[e.jsxs("h3",{className:"text-sm font-bold text-[var(--color-text-secondary)] uppercase tracking-wide mb-3 flex items-center gap-2",children:[e.jsx(Xt,{"aria-hidden":"true",className:"w-4 h-4"}),"Mobile App Access"]}),e.jsxs("button",{onClick:()=>i(l),className:`w-full flex items-center justify-center gap-2 px-4 py-3 220 bg-[var(--color-primary)]/10 hover:bg-[var(--color-primary)]/20 border border-[var(--color-primary)]/30 221 text-[var(--color-primary)] rounded-lg font-medium transition-colors`,children:[e.jsx(Xt,{"aria-hidden":"true",className:"w-5 h-5"}),"Generate Invite Code for Mobile App"]}),e.jsx("p",{className:"text-xs text-[var(--color-text-secondary)] mt-2 text-center",children:"Generate a code to allow this employee to register on the NelsonHR mobile app"})]}),e.jsxs("section",{children:[e.jsxs("h3",{className:"text-sm font-bold text-[var(--color-text-secondary)] uppercase tracking-wide mb-3 flex items-center gap-2",children:[e.jsx(Ee,{"aria-hidden":"true",className:"w-4 h-4"}),"Risk Metrics"]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"p-3 bg-[var(--color-bg-hover)] rounded-lg",children:[e.jsx("p",{className:"text-xs text-[var(--color-text-secondary)]",children:"Flight Risk"}),e.jsxs("p",{className:`text-lg font-bold ${l.flightRiskScore>50?"text-[var(--color-danger)]":"text-[var(--color-success)]"}`,children:[l.flightRiskScore||0,"%"]})]}),e.jsxs("div",{className:"p-3 bg-[var(--color-bg-hover)] rounded-lg",children:[e.jsx("p",{className:"text-xs text-[var(--color-text-secondary)]",children:"Burnout Risk"}),e.jsxs("p",{className:`text-lg font-bold ${l.burnoutRiskScore>50?"text-[var(--color-warning)]":"text-[var(--color-success)]"}`,children:[l.burnoutRiskScore||0,"%"]})]}),e.jsxs("div",{className:"p-3 bg-[var(--color-bg-hover)] rounded-lg",children:[e.jsx("p",{className:"text-xs text-[var(--color-text-secondary)]",children:"Performance"}),e.jsxs("p",{className:"text-lg font-bold text-[var(--color-primary)]",children:[l.performanceRating||0,"/5"]})]})]})]}),e.jsxs("section",{children:[e.jsxs("h3",{className:"text-sm font-bold text-[var(--color-text-secondary)] uppercase tracking-wide mb-3 flex items-center gap-2",children:[e.jsx(et,{"aria-hidden":"true",className:"w-4 h-4"}),"Notes"]}),n?e.jsx("textarea",{"aria-label":"Employee notes",value:d.notes||"",onChange:g=>p("notes",g.target.value),rows:4,className:"w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg text-[var(--color-text-primary)] focus:outline-none focus:border-[var(--color-primary)]/50 resize-none"}):e.jsx("p",{className:"text-[var(--color-text-primary)] whitespace-pre-wrap",children:l.notes||"No notes"})]})]}),e.jsx("div",{className:"px-6 py-4 border-t border-[var(--color-border-subtle)]",children:e.jsxs("button",{onClick:()=>y(!0),className:"flex items-center gap-2 px-4 py-2 text-[var(--color-danger)] hover:text-[var(--color-danger)] hover:bg-[var(--color-danger)]/10 rounded-lg transition-colors",children:[e.jsx(qe,{"aria-hidden":"true",className:"w-4 h-4"}),"Deactivate Employee"]})})]}),v&&e.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-[var(--color-bg-base)]/60 backdrop-blur-sm",children:e.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"deactivate-confirm-title",className:"bg-[var(--color-bg-base)] border border-[var(--color-border-default)] rounded-xl p-6 max-w-md w-full mx-4",children:[e.jsx("h3",{id:"deactivate-confirm-title",className:"text-lg font-bold text-[var(--color-text-primary)] mb-2",children:"Deactivate Employee?"}),e.jsxs("p",{className:"text-[var(--color-text-primary)] mb-4",children:["This will set ",l.firstName," ",l.lastName,`'s status to "Terminated". This action can be undone by editing the employee.`]}),e.jsxs("div",{className:"flex justify-end gap-3",children:[e.jsx("button",{onClick:()=>y(!1),className:"px-4 py-2 text-[var(--color-text-primary)] hover:text-[var(--color-text-primary)] transition-colors",children:"Cancel"}),e.jsx("button",{onClick:j,className:"px-4 py-2 bg-[var(--color-danger)] hover:bg-[var(--color-danger)] text-[var(--color-text-primary)] font-bold rounded-lg transition-colors",children:"Deactivate"})]})]})})]})},Md=({isOpen:l,onClose:t,csvContent:r,csvHeaders:a,sampleRows:o,totalRows:s,onImportComplete:i})=>{const[n,c]=x.useState({}),[d,m]=x.useState(""),[u,h]=x.useState(!1),[v,y]=x.useState({processed:0,total:0});x.useEffect(()=>{if(!l||a.length===0)return;const I=kd(a);c(I),m("")},[l,a]);const p=(I,$)=>{c(R=>({...R,[I]:$})),m("")},N=async()=>{const I=Sd(r,n);if(!I.valid){m(I.errors.slice(0,3).join(` 222`)+(I.errors.length>3?` 223...and ${I.errors.length-3} more errors`:""));return}const $=Cd(r,n);if($.length===0){m("No valid employees found after applying mapping");return}if(confirm(`Import ${$.length} employees? This will add them to your HR directory.`)){h(!0),y({processed:0,total:$.length});try{const R=await Qe.bulkCreateEmployees($);R.failed>0?alert(`Import completed with ${R.succeeded} successes and ${R.failed} failures. 224 225Errors: 226${R.errors.slice(0,5).join(` 227`)}`):alert(`Successfully imported ${R.succeeded} employees!`),i(),t()}catch(R){console.error("[EmployeeCSVMappingModal] Import error:",R),m(`Import failed: ${R.message||"Unknown error"}`)}finally{h(!1)}}},j=kr.filter(I=>I.required).filter(I=>!Object.values(n).includes(I.key));return l?e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-[var(--color-bg-base)]/60 backdrop-blur-sm p-4",children:e.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"
227csv-mapping-title",className:"bg-[var(--color-bg-base)] border border-[var(--color-border-default)] rounded-xl w-full max-w-4xl max-h-[90vh] flex flex-col shadow-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-[var(--color-border-subtle)]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(_l,{"aria-hidden":"true",className:"w-6 h-6 text-[var(--color-primary)]"}),e.jsxs("div",{children:[e.jsx("h2",{id:"csv-mapping-title",className:"text-lg font-bold text-[var(--color-text-primary)]",children:"Map CSV Columns"}),e.jsxs("p",{className:"text-sm text-[var(--color-text-secondary)]",children:[s," employees to import"]})]})]}),e.jsx("button",{onClick:t,disabled:u,"aria-label":"Close dialog",className:"p-2 text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)] rounded-lg transition-colors",children:e.jsx(de,{"aria-hidden":"true",className:"w-5 h-5"})})]}),d&&e.jsxs("div",{role:"alert",className:"mx-6 mt-4 p-3 bg-[var(--color-danger-subtle)] border border-[var(--color-danger)]/30 rounded-lg flex items-start gap-2",children:[e.jsx(Ve,{"aria-hidden":"true",className:"w-5 h-5 text-[var(--color-danger)] flex-shrink-0 mt-0.5"}),e.jsx("pre",{className:"text-sm text-[var(--color-danger)] whitespace-pre-wrap",children:d})]}),j.length>0&&e.jsxs("div",{className:"mx-6 mt-4 p-3 bg-[var(--color-warning-subtle)] border border-[var(--color-warning)]/30 rounded-lg flex items-start gap-2",children:[e.jsx(Ve,{"aria-hidden":"true",className:"w-5 h-5 text-[var(--color-warning)] flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-sm text-[var(--color-warning)]",children:["Required fields not mapped: ",j.map(I=>I.label).join(", ")]})]}),e.jsx("div",{className:"flex-1 overflow-auto px-6 py-4",children:e.jsxs(aa,{className:"w-full text-sm",children:[e.jsx("thead",{className:"sticky top-0 bg-[var(--color-bg-base)]",children:e.jsxs("tr",{className:"text-left text-[var(--color-text-secondary)] border-b border-[var(--color-border-subtle)]",children:[e.jsx("th",{className:"pb-2 font-medium",children:"CSV Column"}),e.jsx("th",{className:"pb-2 font-medium",children:"Sample Data"}),e.jsx("th",{className:"pb-2 font-medium",children:"Map To Field"})]})}),e.jsx("tbody",{className:"divide-y divide-[var(--color-border-subtle)]",children:a.map((I,$)=>{var R;return e.jsxs("tr",{className:"hover:bg-[var(--color-bg-hover)]",children:[e.jsx("td",{className:"py-3 text-[var(--color-text-primary)] font-medium",children:I}),e.jsx("td",{className:"py-3 text-[var(--color-text-secondary)] max-w-[200px] truncate",children:((R=o[0])==null?void 0:R[$])||"-"}),e.jsx("td",{className:"py-3",children:e.jsx("select",{"aria-label":`Map CSV column: ${I}`,value:n[I]||"skip",onChange:E=>p(I,E.target.value),className:`w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg 228 text-[var(--color-text-primary)] focus:outline-none focus:border-[var(--color-primary)]/50 cursor-pointer`,children:kr.map(E=>e.jsxs("option",{value:E.key,className:"bg-[var(--color-bg-base)] text-[var(--color-text-primary)]",children:[E.label,E.required?" *":""]},E.key))})})]},I)})})]})}),e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-t border-[var(--color-border-subtle)] bg-[var(--color-bg-hover)]",children:[e.jsxs("div",{className:"text-sm text-[var(--color-text-secondary)]",children:[e.jsx("span",{"aria-hidden":"true",className:"text-[var(--color-primary)]",children:"*"})," Required fields"]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("button",{onClick:t,disabled:u,className:"px-4 py-2 text-[var(--color-text-primary)] hover:text-[var(--color-text-primary)] transition-colors",children:"Cancel"}),e.jsx("button",{onClick:N,disabled:u||j.length>0,className:`flex items-center gap-2 px-5 py-2 bg-[var(--color-primary)] hover:bg-[var(--color-primary-hover)] 229 text-[var(--color-bg-base)] font-bold rounded-lg transition-colors 230 disabled:opacity-50 disabled:cursor-not-allowed`,children:u?e.jsxs(e.Fragment,{children:[e.jsx("div",{"aria-hidden":"true",className:"w-4 h-4 border-2 border-[var(--color-bg-base)]/30 border-t-[var(--color-bg-base)] rounded-full animate-spin"}),"Importing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ft,{"aria-hidden":"true",className:"w-4 h-4"}),"Import ",s," Employees"]})})]})]})]})}):null};class Fd{async createEmployeeWithAccount(t){const{employee:r,createUserAccount:a,createCrmContact:o,invitedBy:s}=t,i=await Qe.createEmployee(r),n={employee:i};if(o&&i.email)try{const c=await this.createEmployeeContact(i);n.contactId=c.id,await Hr(Br(),"linkEmployeeContactIdentity")({tenantId:i.tenantId,employeeId:i.id,contactId:c.id}),n.employee.contactId=c.id,console.log("[EmployeeAccountService] Created CRM contact for employee:",i.id)}catch(c){console.error("[EmployeeAccountService] Failed to create C
230RM contact:",c)}if(a&&i.email)try{const c=await this.sendEmployeeInvitation(i,s);n.invitationSent=c.emailSent,n.inviteEmailSent=c.emailSent,n.inviteLink=c.inviteLink,n.inviteSafeEmailErrorCode=c.safeEmailErrorCode,n.userId=c.tempUserId,await Qe.updateEmployee(i.id,{hasUserAccount:!1,userAccountInvitedAt:new Date().toISOString()}),n.employee.userAccountInvitedAt=new Date().toISOString(),console.log("[EmployeeAccountService] Employee invitation sent")}catch(c){console.error("[EmployeeAccountService] Failed to send invitation:",c)}return n}async createEmployeeContact(t){const a={id:Nl(),tenantId:t.tenantId,name:`${t.firstName} ${t.lastName}`,firstName:t.firstName,lastName:t.lastName,email:t.email,phone:t.phone||"",company:"",role:t.role,stage:"Won",tags:[],customFields:[],notesHistory:[],lastContacted:new Date().toISOString(),leadScore:0,preferredChannel:"Email",moduleScope:["hr"],employeeId:t.id,isEmployeeContact:!0};return await Ot.addContact(a),a}async sendEmployeeInvitation(t,r){const a=t.tenantId,o=Br(),n=(await Hr(o,"sendInvitationEmail")({email:t.email.toLowerCase(),name:`${t.firstName} ${t.lastName}`,role:"employee",tenantId:a,invitedBy:r,employeeId:t.id})).data;if(!n.tempUserId)throw new Error("Invitation service did not return a temporary user identifier");return{success:n.success!==!1,tempUserId:n.tempUserId,inviteLink:n.inviteLink,emailSent:n.emailSent===!0,safeEmailErrorCode:n.safeEmailErrorCode??null}}async linkUserToEmployee(t,r){const a=await Qe.getEmployee(t);if(!a)throw new Error("Employee not found");await Hr(Br(),"linkEmployeeUserIdentity")({tenantId:a.tenantId,employeeId:t,userId:r}),console.log("[EmployeeAccountService] Linked user",r,"to employee",t)}async handleEmployeeTermination(t){const r=await Qe.getEmployee(t);if(!r||!r.userId){console.log("[EmployeeAccountService] No user account to deactivate for employee:",t);return}const a=B(_,`tenants/${r.tenantId}/users/${r.userId}`);await Q(a,{status:"disabled",disabledReason:"employee_terminated",disabledAt:on()}),console.log("[EmployeeAccountService] Deactivated user account for terminated employee:",t)}async resendInvitation(t,r){const a=await Qe.getEmployee(t);if(!a)throw new Error("Employee not found");if(a.hasUserAccount)throw new Error("Employee already has an active account");const o=await this.sendEmployeeInvitation(a,r);return await Qe.updateEmployee(t,{userAccountInvitedAt:new Date().toISOString()}),o.emailSent}}const Ld=new Fd,qd=["Active","Terminated","Leave","Candidate"],Ud=["Full Time","Part Time","Contractor","Intern"],$d=["Salary","Hourly"],Hd=({employees:l,isOpen:t,onClose:r,onSuccess:a})=>{const{user:o}=rn(),[s,i]=x.useState(!1),[n,c]=x.useState(null),[d,m]=x.useState(""),[u,h]=x.useState(""),[v,y]=x.useState(""),[p,N]=x.useState(""),[S,j]=x.useState(""),[I,$]=x.useState(""),[R,E]=x.useState(new Date().toISOString().split("T")[0]),[O,D]=x.useState("Active"),[b,P]=x.useState("Full Time"),[W,k]=x.useState(""),[f,g]=x.useState("Salary"),[L,z]=x.useState(0),[X,C]=x.useState(!1),[Y,F]=x.useState(!1),re=l.filter(q=>q.status==="Active"),me=()=>{m(""),h(""),y(""),N(""),j(""),$(""),E(new Date().toISOString().split("T")[0]),D("Active"),P("Full Time"),k(""),g("Salary"),z(0),C(!1),F(!1),c(null)},_e=()=>{me(),r()},Ue=async q=>{if(q.preventDefault(),c(null),!d.trim()||!u.trim()){c("First name and last name are required");return}if(X&&!v.trim()){c("Email is required to create a user account");return}if(v&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)){c("Please enter a valid email address");return}i(!0);try{const ne={firstName:d.trim(),lastName:u.trim(),email:v.trim().toLowerCase(),phone:p.trim(),role:S.trim(),department:I.trim(),hireDate:R,status:O,employmentType:b,managerId:W||void 0,payType:f,payRate:L,notes:""},ae=await Ld.createEmployeeWithAccount({employee:ne,createUserAccount:X,createCrmContact:Y,invitedBy:o==null?void 0:o.uid});console.log("[AddEmployeeModal] Employee created:",ae),a(ae.employee),_e()}catch(ne){console.error("[AddEmployeeModal] Error creating employee:",ne),c(ne.message||"Failed to create employee")}finally{i(!1)}};return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-40 bg-[var(--color-bg-base)]/50 backdrop-blur-sm",onClick:_e}),e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:e.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"add-employee-title",className:"bg-[var(--color-bg-base)] border border-[var(--color-border-subtle)] rounded-2xl shadow-2xl w-full max-w-2xl max-h-[90vh] overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-[var(--color-border-subtle)] bg-gradient-to-r from-[var(--color-primary)]/10 to-transparent",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-[var(--color-primary)]/20 flex items-center justify-center",children:e.jsx(ft,{"aria-hidden":"true",className:"w-5 h-5 text-[var(--color-primary)]"})}),e.jsxs("div",{children:[e.jsx("h2",{id:"add-employee-title",className:"text-lg font-bold text-[var(--color-text-primary)]",children:"Add New Employee"}),e.jsx("p",{className:"text-sm text-[var(--color-text-secondary)]",children:"Enter employee details and account options"})]})]}),e.jsx("button",{onClick:_e,"aria-label":"Close dialog",className:"p-2 hover:bg-[var(--color-bg-hover)] rounded-lg transition-colors",children:e.jsx(de,{"aria-hidden":"true",className:"w-5 h-5 text-[var(--color-text-secondary)]"})})]}),e.jsxs("form",{onSubmit:Ue,className:"overflow-y-auto max-h-[calc(90vh-140px)]",children:[e.jsxs("div",{className:"p-6 space-y-6",children:[n&&e.jsx("div",{role:"alert",className:"p-3 bg-[var(--color-danger-subtle)] border border-[var(--color-danger)]/30 rounded-lg text-[var(--color-danger)] text-sm",children:n}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"flex items-center gap-2 text-sm font-semibold text-[var(--color-text-primary)] uppercase tracking-wider",children:[e.jsx(tt,{"aria-hidden":"true",className:"w-4 h-4"}),"Personal Information"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"emp-first-name",className:"block text-xs font-medium text-[var(--color-text-secondary)] mb-1.5",children:"First Name *"}),e.jsx("input",{id:"emp-first-name",type:"text",value:d,onChange:q=>m(q.target.value),className:"w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg text-[var(--color-text-primary)] placeholder:text-[var(--color-text-muted)] focus:border-[var(--color-primary)]/50 focus:outline-none",placeholder:"John",required:!0,"aria-required":"true"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"emp-last-name",className:"block text-xs font-medium text-[var(--color-text-secondary)] mb-1.5",children:"Last Name *"}),e.jsx("input",{id:"emp-last-name",type:"text",value:u,onChange:q=>h(q.target.value),className:"w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg text-[var(--color-text-primary)] placeholder:text-[var(--color-text-muted)] focus:border-[var(--color-primary)]/50 focus:outline-none",placeholder:"Smith",required:!0,"aria-required":"true"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{htmlFor:"emp-email",className:"block text-xs font-medium text-[var(--color-text-secondary)] mb-1.5",children:[e.jsx(da,{"aria-hidden":"true",className:"w-3 h-3 inline mr-1"}),"Email"]}
230),e.jsx("input",{id:"emp-email",type:"email",value:v,onChange:q=>y(q.target.value),className:"w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg text-[var(--color-text-primary)] placeholder:text-[var(--color-text-muted)] focus:border-[var(--color-primary)]/50 focus:outline-none",placeholder:"[email protected]"})]}),e.jsxs("div",{children:[e.jsxs("label",{htmlFor:"emp-phone",className:"block text-xs font-medium text-[var(--color-text-secondary)] mb-1.5",children:[e.jsx(ks,{"aria-hidden":"true",className:"w-3 h-3 inline mr-1"}),"Phone"]}),e.jsx("input",{id:"emp-phone",type:"tel",value:p,onChange:q=>N(q.target.value),className:"w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg text-[var(--color-text-primary)] placeholder:text-[var(--color-text-muted)] focus:border-[var(--color-primary)]/50 focus:outline-none",placeholder:"(555) 123-4567"})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"flex items-center gap-2 text-sm font-semibold text-[var(--color-text-primary)] uppercase tracking-wider",children:[e.jsx(st,{"aria-hidden":"true",className:"w-4 h-4"}),"Employment Details"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"emp-role",className:"block text-xs font-medium text-[var(--color-text-secondary)] mb-1.5",children:"Job Title / Role"}),e.jsx("input",{id:"emp-role",type:"text",value:S,onChange:q=>j(q.target.value),className:"w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg text-[var(--color-text-primary)] placeholder:text-[var(--color-text-muted)] focus:border-[var(--color-primary)]/50 focus:outline-none",placeholder:"Software Engineer"})]}),e.jsxs("div",{children:[e.jsxs("label",{htmlFor:"emp-department",className:"block text-xs font-medium text-[var(--color-text-secondary)] mb-1.5",children:[e.jsx(ca,{"aria-hidden":"true",className:"w-3 h-3 inline mr-1"}),"Department"]}),e.jsx("input",{id:"emp-department",type:"text",value:I,onChange:q=>$(q.target.value),className:"w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg text-[var(--color-text-primary)] placeholder:text-[var(--color-text-muted)] focus:border-[var(--color-primary)]/50 focus:outline-none",placeholder:"Engineering"})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"emp-status",className:"block text-xs font-medium text-[var(--color-text-secondary)] mb-1.5",children:"Status"}),e.jsx("select",{id:"emp-status",value:O,onChange:q=>D(q.target.value),className:"w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg text-[var(--color-text-primary)] focus:border-[var(--color-primary)]/50 focus:outline-none",children:qd.map(q=>e.jsx("option",{value:q,className:"bg-[var(--color-bg-base)]",children:q},q))})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"emp-type",className:"block text-xs font-medium text-[var(--color-text-secondary)] mb-1.5",children:"Type"}),e.jsx("select",{id:"emp-type",value:b,onChange:q=>P(q.target.value),className:"w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg text-[var(--color-text-primary)] focus:border-[var(--color-primary)]/50 focus:outline-none",children:Ud.map(q=>e.jsx("option",{value:q,className:"bg-[var(--color-bg-base)]",children:q},q))})]}),e.jsxs("div",{children:[e.jsxs("label",{htmlFor:"emp-hire-date",className:"block text-xs font-medium text-[var(--color-text-secondary)] mb-1.5",children:[e.jsx(be,{"aria-hidden":"true",className:"w-3 h-3 inline mr-1"}),"Hire Date"]}),e.jsx("input",{id:"emp-hire-date",type:"date",value:R,onChange:q=>E(q.target.value),className:"w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg text-[var(--color-text-primary)] focus:border-[var(--color-primary)]/50 focus:outline-none"})]})]}),e.jsxs("div",{children:[e.jsxs("label",{htmlFor:"emp-manager",className:"block text-xs font-medium text-[var(--color-text-secondary)] mb-1.5",children:[e.jsx(Re,{"aria-hidden":"true",className:"w-3 h-3 inline mr-1"}),"Reports To"]}),e.jsxs("select",{id:"emp-manager",value:W,onChange:q=>k(q.target.value),className:"w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg text-[var(--color-text-primary)] focus:border-[var(--color-primary)]/50 focus:outline-none",children:[e.jsx("option",{value:"",className:"bg-[var(--color-bg-base)]",children:"No Manager"}),re.map(q=>e.jsxs("option",{value:q.id,className:"bg-[var(--color-bg-base)]",children:[q.firstName," ",q.lastName,"
230(",q.role,")"]},q.id))]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"flex items-center gap-2 text-sm font-semibold text-[var(--color-text-primary)] uppercase tracking-wider",children:[e.jsx(ps,{"aria-hidden":"true",className:"w-4 h-4"}),"Compensation"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"emp-pay-type",className:"block text-xs font-medium text-[var(--color-text-secondary)] mb-1.5",children:"Pay Type"}),e.jsx("select",{id:"emp-pay-type",value:f,onChange:q=>g(q.target.value),className:"w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg text-[var(--color-text-primary)] focus:border-[var(--color-primary)]/50 focus:outline-none",children:$d.map(q=>e.jsx("option",{value:q,className:"bg-[var(--color-bg-base)]",children:q},q))})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"emp-pay-rate",className:"block text-xs font-medium text-[var(--color-text-secondary)] mb-1.5",children:f==="Salary"?"Annual Salary":"Hourly Rate"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{"aria-hidden":"true",className:"absolute left-3 top-1/2 -translate-y-1/2 text-[var(--color-text-muted)]",children:"$"}),e.jsx("input",{id:"emp-pay-rate",type:"number",value:L,onChange:q=>z(Number(q.target.value)),className:"w-full pl-7 pr-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg text-[var(--color-text-primary)] placeholder:text-[var(--color-text-muted)] focus:border-[var(--color-primary)]/50 focus:outline-none",placeholder:"0",min:"0",step:f==="Salary"?"1000":"0.5"})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"flex items-center gap-2 text-sm font-semibold text-[var(--color-text-primary)] uppercase tracking-wider",children:[e.jsx(oa,{"aria-hidden":"true",className:"w-4 h-4"}),"Account Options"]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"flex items-start gap-3 p-4 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg cursor-pointer hover:bg-[var(--color-bg-hover)] transition-colors",children:[e.jsx("input",{type:"checkbox",checked:X,onChange:q=>C(q.target.checked),className:"mt-0.5 w-4 h-4 rounded border-[var(--color-border-strong)] bg-[var(--color-bg-hover)] text-[var(--color-primary)] focus:ring-[var(--color-primary)]/50"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ft,{"aria-hidden":"true",className:"w-4 h-4 text-[var(--color-primary)]"}),e.jsx("span",{className:"font-medium text-[var(--color-text-primary)]",children:"Create NelsonOS User Account"})]}),e.jsx("p",{className:"text-sm text-[var(--color-text-secondary)] mt-1",children:"Employee will receive an invitation email to set up their account with self-service access to view schedules, submit time-off requests, and more."})]})]}),e.jsxs("label",{className:"flex items-start gap-3 p-4 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg cursor-pointer hover:bg-[var(--color-bg-hover)] transition-colors",children:[e.jsx("input",{type:"checkbox",checked:Y,onChange:q=>F(q.target.checked),className:"mt-0.5 w-4 h-4 rounded border-[var(--color-border-strong)] bg-[var(--color-bg-hover)] text-[var(--color-primary)] focus:ring-[var(--color-primary)]/50"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(El,{"aria-hidden":"true",className:"w-4 h-4 text-[var(--color-primary)]"}),e.jsx("span",{className:"font-medium text-[var(--color-text-primary)]",children:"Create C
230RM Contact Record"})]}),e.jsx("p",{className:"text-sm text-[var(--color-text-secondary)] mt-1",children:"Creates a contact in the CRM with the employee's information. This contact will be tagged as HR-only and won't appear in general CRM views."})]})]})]})]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-3 px-6 py-4 border-t border-[var(--color-border-subtle)] bg-[var(--color-bg-hover)]",children:[e.jsx("button",{type:"button",onClick:_e,className:"px-4 py-2 text-[var(--color-text-primary)] hover:text-[var(--color-text-primary)] transition-colors",children:"Cancel"}),e.jsx("button",{type:"submit",disabled:s,className:"flex items-center gap-2 px-6 py-2 bg-[var(--color-primary)] hover:bg-[var(--color-primary-hover)] text-[var(--color-bg-base)] font-bold rounded-lg transition-colors disabled:opacity-50",children:s?e.jsxs(e.Fragment,{children:[e.jsx("div",{"aria-hidden":"true",className:"w-4 h-4 border-2 border-[var(--color-bg-base)]/30 border-t-[var(--color-bg-base)] rounded-full animate-spin"}),"Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ft,{"aria-hidden":"true",className:"w-4 h-4"}),"Add Employee"]})})]})]})]})})]}):null};function us(){const l="ABCDEFGHJKLMNPQRSTUVWXYZ23456789";let t="";for(let r=0;r<6;r++)t+=l.charAt(Math.floor(Math.random()*l.length));return t}function Ar(){var t;const l=(t=De.getCurrentTenant())==null?void 0:t.id;if(!l)throw new Error("No tenant selected");return H(gt,"tenants",l,"mobile_invite_codes")}function va(){var t;const l=(t=De.getCurrentTenant())==null?void 0:t.id;if(!l)throw new Error("No tenant selected");return H(gt,"tenants",l,"mobile_device_registrations")}async function Bd(l){var h;const t=Ar(),r=(h=De.getCurrentTenant())==null?void 0:h.id;if(!r)throw new Error("No tenant selected");const a=V(t,K("employee_id","==",l.employee_id),K("status","==","active")),o=await Z(a);for(const v of o.docs)await Q(v.ref,{status:"revoked",revoked_at:new Date().toISOString(),revoked_by_user_id:"system"});let s=us(),i=0;const n=10;for(;i<n;){const v=V(t,K("code","==",s),K("status","==","active"));if((await Z(v)).empty)break;s=us(),i++}if(i>=n)throw new Error("Failed to generate unique code");const c=l.expires_in_hours||72,d=new Date,m=new Date(d.getTime()+c*60*60*1e3),u={id:B(t).id,tenant_id:r,employee_id:l.employee_id,employee_number:l.employee_number||void 0,code:s,status:"active",created_at:d.toISOString(),expires_at:m.toISOString(),created_by_user_id:"current-user"};return await Lt(B(t,u.id),u),u}async function zd(l){const t=Ar(),r=V(t,K("employee_id","==",l),K("status","==","active")),a=await Z(r);if(a.empty)return null;let o=a.docs[0].data();for(const s of a.docs){const i=s.data();new Date(i.created_at)>new Date(o.created_at)&&(o=i)}return new Date(o.expires_at)<new Date?(await Q(B(t,o.id),{status:"expired"}),null):o}async function Wd(l,t,r){var h;const a=r||((h=De.getCurrentTenant())==null?void 0:h.id);if(!a)return{valid:!1,error:"No tenant specified"};const o=H(gt,"tenants",a,"mobile_invite_codes"),s=H(gt,"tenants",a,"employees");let i=null,n=null;if(/[A-Za-z]/.test(l)){const v=V(s,K("employeeNumber","==",l.toUpperCase())),y=await Z(v);y.empty||(i=y.docs[0].id,n=y.docs[0].data())}if(!i){const v=await oe(B(s,l));v.exists()&&(i=v.id,n=v.data())}if(!i||!n)return{valid:!1,error:"Employee not found"};const d=V(o,K("employee_id","==",i),K("code","==",t.toUpperCase()),K("status","==","active")),m=await Z(d);if(m.empty)return{valid:!1,error:"Invalid invite code"};const u=m.docs[0].data();return new Date(u.expires_at)<new Date?(await Q(B(o,u.id),{status:"expired"}),{valid:!1,error:"Invite code has expired"}):{valid:!0,employee:{id:i,employeeNumber:n.employeeNumber,firstName:n.firstName,lastName:n.lastName,email:n.email,role:n.role,department:n.department,employmentType:n.employmentType,status:n.status,hireDate:n.hireDate,tenantId:a}}}async function Vd(l,t,r,a){var c;const o=a||((c=De.getCurrentTenant())==null?void 0:c.id);if(!o)throw new Error("No tenant specified");const s=H(gt,"tenants",o,"mobile_invite_codes"),i=V(s,K("employee_id","==",l),K("code","==",t.toUpperCase()),K("status","==","active")),n=await Z(i);n.empty||await Q(B(s,n.docs[0].id),{status:"used",used_at:new Date().toISOString(),used_device_id:r})}async function Kd(l){const t=Ar();await Q(B(t,l),{status:"revoked",revoked_at:new Date().toISOString(),revoked_by_user_id:"current-user"})}
230async function Yd(l){const t=Ar(),r=V(t,K("employee_id","==",l));return(await Z(r)).docs.map(s=>s.data()).sort((s,i)=>new Date(i.created_at).getTime()-new Date(s.created_at).getTime())}async function Gd(l){var n;const t=l.tenant_id||((n=De.getCurrentTenant())==null?void 0:n.id);if(!t)throw new Error("No tenant specified");const r=H(gt,"tenants",t,"mobile_device_registrations"),a=V(r,K("employee_id","==",l.employee_id),K("device_id","==",l.device_id)),o=await Z(a),s=new Date().toISOString();if(!o.empty){const c=o.docs[0];return await Q(c.ref,{last_active_at:s,push_token:l.push_token,is_active:!0}),{...c.data(),last_active_at:s}}const i={id:B(r).id,tenant_id:t,employee_id:l.employee_id,device_id:l.device_id,device_name:l.device_name,platform:l.platform,registered_at:s,last_active_at:s,push_token:l.push_token,is_active:!0};return await Lt(B(r,i.id),i),i}async function Qd(l,t){const r=va(),a=V(r,K("employee_id","==",l),K("device_id","==",t)),o=await Z(a);for(const s of o.docs)await Q(s.ref,{is_active:!1})}async function Zd(l){const t=va(),r=V(t,K("employee_id","==",l),K("is_active","==",!0));return(await Z(r)).docs.map(o=>o.data())}async function Jd(l,t){const r=va(),a=V(r,K("device_id","==",l)),o=await Z(a);for(const s of o.docs)await Q(s.ref,{push_token:t,last_active_at:new Date().toISOString()})}const Yt={createInviteCode:Bd,getActiveInviteCode:zd,validateInviteCode:Wd,markInviteCodeUsed:Vd,revokeInviteCode:Kd,getInviteCodesForEmployee:Yd,registerDevice:Gd,deactivateDevice:Qd,getDevicesForEmployee:Zd,updatePushToken:Jd},Xd=({isOpen:l,employee:t,onClose:r})=>{const[a,o]=x.useState(null),[s,i]=x.useState([]),[n,c]=x.useState(!1),[d,m]=x.useState(!1),[u,h]=x.useState(!1),[v,y]=x.useState(null);x.useEffect(()=>{l&&t&&p()},[l,t]);const p=async()=>{if(t){c(!0),y(null);try{const[R,E]=await Promise.all([Yt.getActiveInviteCode(t.id),Yt.getDevicesForEmployee(t.id)]);o(R),i(E)}catch(R){console.error("Failed to load invite code data:",R),y("Failed to load data")}finally{c(!1)}}},N=async()=>{if(t){m(!0),y(null);try{const R=await Yt.createInviteCode({employee_id:t.id,employee_number:t.employeeNumber,expires_in_hours:72});o(R)}catch(R){console.error("Failed to generate invite code:",R),y("Failed to generate invite code")}finally{m(!1)}}},S=async()=>{if(!a||!t)return;const E=`Employee Number: ${t.employeeNumber||t.id} 231Invite Code: ${a.code}`;(await Pa(E)).ok&&(h(!0),setTimeout(()=>h(!1),2e3))},j=async()=>{if(a&&confirm("Are you sure you want to revoke this invite code? The employee will need a new code to register."))try{await Yt.revokeInviteCode(a.id),o(null)}catch(R){console.error("Failed to revoke invite code:",R),y("Failed to revoke invite code")}},I=async R=>{if(t&&confirm("Are you sure you want to deactivate this device? The employee will need to re-register."))try{await Yt.deactivateDevice(t.id,R),i(s.filter(E=>E.device_id!==R))}catch(E){console.error("Failed to deactivate device:",E),y("Failed to deactivate device")}},$=R=>{const E=new Date,D=new Date(R).getTime()-E.getTime();if(D<0)return"Expired";const b=Math.floor(D/(1e3*60*60)),P=Math.floor(D%(1e3*60*60)/(1e3*60));if(b>24){const W=Math.floor(b/24);return`${W} day${W>1?"s":""} remaining`}return`${b}h ${P}m remaining`};return l?e.jsx("div",{className:"fixed inset-0 bg-[var(--color-bg-base)]/70 backdrop-blur-sm flex items-center justify-center z-50 p-4",children:e.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"mobile-invite-title",className:"bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] rounded-xl w-full max-w-md
231shadow-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-[var(--color-border-subtle)]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Xt,{"aria-hidden":"true",className:"w-5 h-5 text-brand-400"}),e.jsxs("div",{children:[e.jsx("h2",{id:"mobile-invite-title",className:"text-lg font-bold text-[var(--color-text-primary)]",children:"Mobile App Access"}),t&&e.jsxs("p",{className:"text-sm text-[var(--color-text-secondary)]",children:[t.firstName," ",t.lastName]})]})]}),e.jsx("button",{onClick:r,"aria-label":"Close dialog",className:"p-2 hover:bg-[var(--color-bg-hover)] rounded-lg transition-colors",children:e.jsx(de,{"aria-hidden":"true",className:"w-5 h-5 text-[var(--color-text-secondary)]"})})]}),e.jsx("div",{className:"p-6 space-y-6",children:n?e.jsx("div",{role:"status","aria-label":"Loading",className:"flex items-center justify-center py-8",children:e.jsx("div",{"aria-hidden":"true",className:"animate-spin rounded-full h-8 w-8 border-2 border-brand-400 border-t-transparent"})}):e.jsxs(e.Fragment,{children:[v&&e.jsxs("div",{className:"flex items-center gap-2 px-4 py-3 bg-[var(--color-danger)]/10 border border-[var(--color-danger)]/30 rounded-lg text-[var(--color-danger)] text-sm",children:[e.jsx(Ee,{"aria-hidden":"true",className:"w-4 h-4 flex-shrink-0"}),v]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"text-sm font-medium text-[var(--color-text-primary)] uppercase tracking-wider",children:"Employee Number"}),e.jsxs("div",{className:"bg-[var(--color-success)]/10 border border-[var(--color-success)]/30 rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs text-[var(--color-success)]",children:"Share this with the employee"}),e.jsx("button",{onClick:async()=>{const R=(t==null?void 0:t.employeeNumber)||(t==null?void 0:t.id);R&&await Pa(R)},className:"text-xs text-[var(--color-success)] hover:text-[var(--color-success)]",children:"Copy"})]}),t!=null&&t.employeeNumber?e.jsx("p",{className:"font-mono text-2xl font-bold text-[var(--color-text-primary)] mt-2",children:t.employeeNumber}):e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"text-xs text-[var(--color-warning)] mb-1",children:"No employee number assigned yet"}),e.jsxs("p",{className:"font-mono text-sm text-[var(--color-text-secondary)] break-all",children:["Using ID: ",t==null?void 0:t.id]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-sm font-medium text-[var(--color-text-primary)] uppercase tracking-wider",children:"Invite Code"}),a?e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs text-[var(--color-text-secondary)]",children:"6-Character Code"}),e.jsx("span",{className:"font-mono text-2xl font-bold text-brand-400 tracking-wider",children:a.code})]})}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-[var(--color-text-secondary)]",children:[e.jsx(ve,{"aria-hidden":"true",className:"w-4 h-4"}),$(a.expires_at)]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:S,className:`flex-1 flex items-center justify-center gap-2 px-4 py-2 232 bg-[var(--color-primary)] hover:bg-[var(--color-primary-hover)] text-[var(--color-bg-base)] rounded-lg 233 font-medium transition-colors`,children:u?e.jsxs(e.Fragment,{children:[e.jsx(Te,{"aria-hidden":"true",className:"w-4 h-4"}),"Copied!"]}):e.jsxs(e.Fragment,{children:[e.jsx(tr,{"aria-hidden":"true",className:"w-4 h-4"}),"Copy"]})}),e.jsxs("button",{onClick:N,disabled:d,className:`flex items-center justify-center gap-2 px-4 py-2 234 bg-[var(--color-bg-hover)] hover:bg-[var(--color-bg-active)] text-[var(--color-text-primary)] rounded-lg 235 font-medium transition-colors disabled:opacity-50`,children:[e.jsx(Xe,{"aria-hidden":"true",className:`w-4 h-4 ${d?"animate-spin":""}`}),"New"]})]}),e.jsx("button",{onClick:j,className:"w-full text-sm text-[var(--color-danger)] hover:text-[var(--color-danger)] transition-colors",children:"Revoke Code"})]}):e.jsxs("div",{className:"text-center py-6 space-y-4",children:[e.jsx("p",{className:"text-[var(--color-text-secondary)]",children:"No active invite code. Generate one to allow this employee to register on the mobile app."}),e.jsx("button",{onClick:N,disabled:d,className:`inline-flex items-center gap-2 px-6 py-3 236 bg-[var(--color-primary)] hover:bg-[var(--color-primary-hover)] text-[var(--color-bg-base)] rounded-lg 237 font-medium transition-colors disabled:opacity-50`,children:d?e.jsxs(e.Fragment,{children:[e.jsx(Xe,{"aria-hidden":"true",className:"w-4 h-4 animate-spin"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Xt,{"aria-hidden":"true",className:"w-4 h-4"}),"Generate Invite Code"]}
237)})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-sm font-medium text-[var(--color-text-primary)] uppercase tracking-wider",children:["Registered Devices (",s.length,")"]}),s.length>0?e.jsx("div",{className:"space-y-2",children:s.map(R=>e.jsxs("div",{className:`flex items-center justify-between px-4 py-3 238 bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`p-2 rounded-lg ${R.platform==="ios"?"bg-[var(--color-primary-subtle)] text-[var(--color-primary)]":"bg-[var(--color-success)]/20 text-[var(--color-success)]"}`,children:e.jsx(Xt,{"aria-hidden":"true",className:"w-4 h-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-[var(--color-text-primary)]",children:R.device_name||R.platform.toUpperCase()}),e.jsxs("p",{className:"text-xs text-[var(--color-text-secondary)]",children:["Last active: ",new Date(R.last_active_at).toLocaleDateString()]})]})]}),e.jsx("button",{onClick:()=>I(R.device_id),className:"text-xs text-[var(--color-danger)] hover:text-[var(--color-danger)] transition-colors",children:"Remove"})]},R.id))}):e.jsx("p",{className:"text-sm text-[var(--color-text-secondary)] text-center py-4",children:"No devices registered yet"})]}),e.jsxs("div",{className:"bg-[var(--color-primary-subtle)] border border-[var(--color-primary-subtle)] rounded-lg p-4",children:[e.jsx("h4",{className:"text-sm font-medium text-[var(--color-primary)] mb-2",children:"How to Register"}),e.jsxs("ol",{className:"text-xs text-[var(--color-text-secondary)] space-y-1 list-decimal list-inside",children:[e.jsx("li",{children:"Employee downloads NelsonHR app from App Store or Google Play"}),e.jsx("li",{children:'On first launch, they tap "Get Started"'}),e.jsx("li",{children:"They enter their Employee ID and Invite Code"}),e.jsx("li",{children:"They create a PIN and optionally enable biometrics"})]})]})]})})]})}):null},eu=({isOpen:l,onClose:t})=>{const[r,a]=x.useState(Mt),[o,s]=x.useState(!0),[i,n]=x.useState(!1),[c,d]=x.useState(!1),[m,u]=x.useState(null),[h,v]=x.useState(null);x.useEffect(()=>{l&&y()},[l]);const y=async()=>{s(!0),u(null);try{const j=await Gt.getSchema();a(j)}catch(j){console.error("Failed to load schema:",j),u("Failed to load settings")}finally{s(!1)}},p=async()=>{n(!0),u(null),v(null);try{await Gt.updateSchema(r),v("Settings saved successfully"),setTimeout(()=>v(null),3e3)}catch(j){console.error("Failed to save schema:",j),u("Failed to save settings")}finally{n(!1)}},N=async()=>{d(!0),u(null);try{const j=await Gt.syncNextNumber();a(I=>({...I,nextNumber:j})),v(`Next number synced to ${j}`),setTimeout(()=>v(null),3e3)}catch(j){console.error("Failed to sync next number:",j),u("Failed to sync next number")}finally{d(!1)}},S=Gt.previewWithSchema(r);return l?e.jsx("div",{className:"fixed inset-0 bg-[var(--color-bg-base)]/70 backdrop-blur-sm flex items-center justify-center z-50 p-4",children:e.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"emp-num-settings-title",className:"bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] rounded-xl w-full max-w-lg shadow-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-[var(--color-border-subtle)]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(na,{"aria-hidden":"true",className:"w-5 h-5 text-brand-400"}),e.jsx("h2",{id:"emp-num-settings-title",className:"text-lg font-bold text-[var(--color-text-primary)]",children:"Employee Number Settings"})]}),e.jsx("button",{onClick:t,"aria-label":"Close dialog",className:"p-2 hover:bg-[var(--color-bg-hover)] rounded-lg transition-colors",children:e.jsx(de,{"aria-hidden":"true",className:"w-5 h-5 text-[var(--color-text-secondary)]"})})]}),e.jsx("div",{className:"p-6 space-y-6",children:o?e.jsx("div",{role:"status","aria-label":"Loading settings",className:"flex items-center justify-center py-8",children:e.jsx("div",{"aria-hidden":"true",className:"animate-spin rounded-full h-8 w-8 border-2 border-brand-400 border-t-transparent"})}):e.jsxs(e.Fragment,{children:[m&&e.jsxs("div",{role:"alert",className:"flex items-center gap-2 px-4 py-3 bg-[var(--color-danger)]/10 border border-[var(--color-danger)]/30 rounded-lg text-[var(--color-danger)] text-sm",children:[e.jsx(Ee,{"aria-hidden":"true",className:"w-4 h-4 flex-shrink-0"}),m]}),h&&e.jsxs("div",{className:"flex items-center gap-2 px-4 py-3 bg-[var(--color-success)]/10 border border-[var(--color-success)]/30 rounded-lg text-[var(--color-success)] text-sm",children:[e.jsx(Te,{"aria-hidden":"true",className:"w-4 h-4 flex-shrink-0"}),h]}),e.jsxs("div",{className:"bg-[var(--color-primary-subtle)] border border-[var(--color-primary)]/30 rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-brand-400",children:"Preview"}),e.jsx(Sl,{"aria-hidden":"true",className:"w-4 h-4 text-brand-400"})]}),e.jsx("p",{className:"font-mono text-2xl font-bold text-[var(--color-text-primary)] mt-2",children:S}),e.jsx("p",{className:"text-xs text-[var(--color-text-secondary)] mt-1",children:"Next employee will be assigned this number"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"emp-num-prefix",className:"block text-sm font-medium text-[var(--color-text-primary)] mb-2",children:"Prefix"}),e.jsx("input",{id:"emp-num-prefix",type:"text",value:r.prefix,onChange:j=>a(I=>({...I,prefix:j.target.value.toUpperCase()})),placeholder:"EMP",maxLength:10,className:`w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg 239 text-[var(--color-text-primary)] placeholder-[var(--color-text-muted)] focus:outline-none focus:border-[var(--color-primary)]`}),e.jsx("p",{className:"text-xs text-[var(--color-text-secondary)] mt-1",children:"e.g., EMP, NE, ACME"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"emp-num-separator",className:"block text-sm font-medium text-[var(--color-text-primary)] mb-2",children:"Separator"}),e.jsxs("select",{id:"emp-num-separator",value:r.separator,onChange:j=>a(I=>({...I,separator:j.target.value})),className:`w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg 240 text-[var(--color-text-primary)] focus:outline-none focus:border-[var(--color-primary)]`,children:[e.jsx("option",{value:"-",children:"Dash (-)"}),e.jsx("option",{value:"_",children:"Underscore (_)"}),e.jsx("option",{value:".",children:"Dot (.)"}),e.jsx("option",{value:"",children:"None"})]})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"emp-num-padding",className:"block text-sm font-medium text-[var(--color-text-primary)] mb-2",children:"Number Length"}),e.jsxs("select",{id:"emp-num-padding",value:r.paddingLength,onChange:j=>a(I=>({...I,paddingLength:parseInt(j.target.value)})),className:`w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg 241 text-[var(--color-text-primary)] focus:outline-none focus:border-[var(--color-primary)]`,children:[e.jsx("option",{value:2,children:"2 digits (01)"}),e.jsx("option",{value:3,children:"3 digits (001)"}),e.jsx("option",{value:4,children:"4 digits (0001)"}),e.jsx("option",{value:5,children:"5 digits (00001)"})]})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"emp-num-starting",className:"block text-sm font-medium text-[var(--color-text-primary)] mb-2",children:"Starting Number"}),e.jsx("input",{id:"emp-num-starting",type:"number",value:r.startingNumber,onChange:j=>a(I=>({...I,startingNumber:parseInt(j.target.value)||1})),min:1,className:`w-full px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg 242 text-[var(--color-text-primary)] focus:outline-none focus:border-[var(--color-primary)]`})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("input",{type:"checkbox",id:"includeYear",checked:r.includeYear||!1,onChange:j=>a(I=>({...I,includeYear:j.target.checked})),className:`w-4 h-4 rounded border-[var(--color-border-default)] bg-[var(--color-bg-hover)] 243 text-[var(--color-primary)] focus:ring-[var(--color-primary)]`}),e.jsx("label",{htmlFor:"includeYear",className:"text-sm text-[var(--color-text-primary)]",children:"Include year in number (e.g., EMP-2026-001)"})]}),r.includeYear&&e.jsxs("div",{className:"pl-7",children:[e.jsx("label",{htmlFor:"emp-num-year-format",className:"block text-sm font-medium text-[var(--color-text-primary)] mb-2",children:"Year Format"}),e.jsxs("select",{id:"emp-num-year-format",value:r.yearFormat||"4",onChange:j=>a(I=>({...I,yearFormat:j.target.value})),className:`w-32 px-3 py-2 bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] rounded-lg 244 text-[var(--color-text-primary)] focus:outline-none focus:border-[var(--color-primary)]`,children:[e.jsx("option",{value:"4",children:"4-digit (2026)"}),e.jsx("option",{value:"2",children:"2-digit (26)"})]})]})]}),e.jsxs("div",{className:"bg-[var(--color-bg-hover)] border border-[var(--color-border-subtle)] rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-[var(--color-text-primary)]",children:"Next Number"}),e.jsx("p",{className:"text-2xl font-mono font-bold text-[var(--color-text-primary)] mt-1",children:r.nextNumber})]}
244),e.jsxs("button",{onClick:N,disabled:c,className:`flex items-center gap-2 px-3 py-2 bg-[var(--color-bg-hover)] hover:bg-[var(--color-bg-active)] 245 text-[var(--color-text-primary)] hover:text-[var(--color-text-primary)] rounded-lg transition-colors disabled:opacity-50`,children:[e.jsx(Xe,{"aria-hidden":"true",className:`w-4 h-4 ${c?"animate-spin":""}`}),"Sync"]})]}),e.jsx("p",{className:"text-xs text-[var(--color-text-secondary)] mt-2",children:'Click "Sync" to find the highest existing number and set next number accordingly'})]})]})}),!o&&e.jsxs("div",{className:"flex justify-end gap-3 px-6 py-4 border-t border-[var(--color-border-subtle)]",children:[e.jsx("button",{onClick:t,className:"px-4 py-2 text-[var(--color-text-primary)] hover:text-[var(--color-text-primary)] transition-colors",children:"Cancel"}),e.jsx("button",{onClick:p,disabled:i,className:`flex items-center gap-2 px-6 py-2 bg-[var(--color-primary)] hover:bg-[var(--color-primary-hover)] 246 text-[var(--color-bg-base)] rounded-lg font-medium transition-colors disabled:opacity-50`,children:i?e.jsxs(e.Fragment,{children:[e.jsx(Xe,{"aria-hidden":"true",className:"w-4 h-4 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Te,{"aria-hidden":"true",className:"w-4 h-4"}),"Save Changes"]})})]})]})}):null},fm=()=>{var Ta,Ia;const{tenantId:l,loading:t}=an(),[r,a]=dn(["directory","schedule","timeclock","timeoff","reviews","orgchart","documents","analytics"],"directory"),[o,s]=x.useState([]),[i,n]=x.useState(Ot.getTimeOffRequests()),[c,d]=x.useState(Ot.getShifts()),[m,u]=x.useState(!0),[h,v]=x.useState(null),[y,p]=x.useState(!1),[N,S]=x.useState({}),[j,I]=x.useState(!1),[$,R]=x.useState(""),[E,O]=x.useState([]),[D,b]=x.useState([]),[P,W]=x.useState(0),[k,f]=x.useState(!1),[g,L]=x.useState({status:"Active",employmentType:"Full Time"}),[z,X]=x.useState(null),[C,Y]=x.useState(null),[F,re]=x.useState(!1),[me,_e]=x.useState(!1),[Ue,q]=x.useState([]),[ne,ae]=x.useState(!1),[Ie,$e]=x.useState(()=>{const w=new Date,M=w.getDay(),G=new Date(w);return G.setDate(w.getDate()-M),G.setHours(0,0,0,0),G}),[Ke,wt]=x.useState(!1),[jt,Dt]=x.useState(null),[_t,lt]=x.useState([]),[U,J]=x.useState(null),[ue,pe]=x.useState(!1),[Ht,Bt]=x.useState(!1),[Ls,lr]=x.useState(!1),[fa,ir]=x.useState(!1),[zt,ga]=x.useState("calendar"),[Pr,Or]=x.useState("active"),[qs,Us]=x.useState(""),[cr,$s]=x.useState(""),[Hs,ba]=x.useState([]),[Bs,it]=x.useState(!1),[ya,zs]=x.useState([]),[Ws,Wt]=x.useState(!1),[Vs,Mr]=x.useState(null),[wa,Ye]=x.useState(!1),[ja,Ks]=x.useState([]),[Ys,Gs]=x.useState([]),[Qs,Ge]=x.useState(!1),[je,Zs]=x.useState([]),[Vt,Js]=x.useState([]),[Xs,_a]=x.useState(!1),[eo,Me]=x.useState(!1),[to,Fr]=x.useState(!1),[ro,Lr]=x.useState(!1),[ao,Na]=x.useState(!1),[so,Sa]=x.useState(null),[oo,Ca]=x.useState(!1),[Nt,no]=x.useState([]);x.useEffect(()=>{tc.initialize()},[]),x.useEffect(()=>{if(!l)return;ae(!0);const w=new Date(Ie),M=new Date(w);return M.setDate(M.getDate()+14),te.subscribeToShifts({location_ids:z?[z]:void 0,start_date:w.toISOString(),end_date:M.toISOString()},le=>{const fe=le.map(ce=>{var Ae,rt;return{...ce,location_name:(Ae=je.find(Pe=>Pe.id===ce.location_id))==null?void 0:Ae.name,position_name:(rt=Vt.find(Pe=>Pe.id===ce.position_id))==null?void 0:rt.name,assigned_employee_name:ce.assigned_employee_id?(()=>{const Pe=o.find(Ce=>Ce.id===ce.assigned_employee_id);return Pe?`${Pe.firstName} ${Pe.lastName}`:void 0})():void 0,duration_hours:(new Date(ce.end_at_utc).getTime()-new Date(ce.start_at_utc).getTime())/36e5}});no(fe),ae(!1)})},[l,z,Ie,o,je,Vt]),x.useEffect(()=>{if(!l)return;(async()=>{try{const M=await te.getTemplates(z||void 0);lt(M)}catch(M){console.error("[HR] Failed to load templates:",M)}})()},[l,z]),x.useEffect(()=>{if(!cr){ba([]);return}return te.subscribeToAvailabilityRules(cr,M=>{ba(M)})},[cr]),x.useEffect(()=>l?xt.subscribeToTimeOffRequests({},M=>{zs(M)}):void 0,[l]),x.useEffect(()=>l?jr.subscribeToCoverageRequests({statuses:["pending"]},M=>{Ks(M)}):void 0,[l]),x.useEffect(()=>l?te.subscribeToSwaps({statuses:["pending","accepted","pending_approval"]},M=>{Gs(M)}):void 0,[l]),x.useEffect(()=>l?mt.subscribeToLocations(M=>{Zs(M)},!1):void 0,[l]),x.useEffect(()=>l?mt.subscribeToPositions(M=>{Js(M)},!1):void 0,[l]),x.useEffect(()=>l?(u(!0),Qe.subscribeToEmployees(N,M=>{s(M),u(!1)})):void 0,[l,N]),x.useEffect(()=>Ot.subscribe(()=>{n(Ot.getTimeOffRequests()),d(Ot.getShifts())}),[]);const lo=x.useMemo(()=>{const w=new Set(o.map(M=>
246M.department).filter(Boolean));return Array.from(w).sort()},[o]),ka=w=>{v(w),p(!0)},io=w=>{Sa(w),Na(!0)},co=async w=>{if(h)try{await Qe.updateEmployee(h.id,w),p(!1),v(null)}catch(M){throw console.error("[HR] Failed to update employee:",M),M}},uo=async()=>{if(h)try{await Qe.deleteEmployee(h.id),p(!1),v(null)}catch(w){throw console.error("[HR] Failed to deactivate employee:",w),w}},mo=()=>{const w=_d(o);Fs(w,`employees-${new Date().toISOString().split("T")[0]}.csv`)},xo=w=>{const M=new FileReader;M.onload=G=>{var ce;const le=(ce=G.target)==null?void 0:ce.result;if(!le)return;const fe=Nd(le,3);R(le),O(fe.headers),b(fe.sampleRows),W(fe.totalRows),I(!0)},M.readAsText(w)},ho=()=>{I(!1),R(""),O([]),b([]),W(0)},po=(w,M)=>{var ce,Ae,rt;const G=new Date(w);G.setHours(9,0,0,0);const le=new Date(w);le.setHours(17,0,0,0);const fe={id:`shift-new-${Date.now()}`,tenant_id:((ce=De.getCurrentTenant())==null?void 0:ce.id)||"",location_id:z||((Ae=je[0])==null?void 0:Ae.id)||"",position_id:null,start_at_utc:G.toISOString(),end_at_utc:le.toISOString(),timezone:"America/New_York",status:"draft",assigned_employee_id:null,published_at:null,template_id:null,template_shift_id:null,notes:null,version:1,is_deleted:!1,created_by_user_id:"current-user",updated_by_user_id:"current-user",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),location_name:(rt=je.find(Pe=>{var Ce;return Pe.id===(z||((Ce=je[0])==null?void 0:Ce.id))}))==null?void 0:rt.name,duration_hours:8};Y(fe),_e(!0),re(!0)},vo=w=>{const M=Nt.find(G=>G.id===w.id)||w;Y(M),_e(!1),re(!0)},Ra=async w=>{try{await te.deleteShift(w)}catch(M){console.error("[HR] Failed to delete shift:",M),alert("Failed to delete shift")}},Da=async w=>{try{ae(!0),await te.publishShifts({shift_ids:w,notify_employees:!0})}catch(M){console.error("[HR] Failed to publish shifts:",M),alert("Failed to publish shifts")}finally{ae(!1)}},fo=w=>{Dt(w),wt(!0)},go=async(w,M)=>{var G,le,fe;if(jt)try{ae(!0);const ce=o.find(Oe=>Oe.id===w),Ae=((G=ce==null?void 0:ce.status)==null?void 0:G.toLowerCase())==="active"?"active":"inactive",rt=Nt.filter(Oe=>Oe.assigned_employee_id===w),Pe=ya.filter(Oe=>Oe.employee_id===w),Ce=await te.assignEmployee(jt,w,{overrideReason:M,skipEligibility:!1,employeeData:{status:Ae,assignments:[],availabilityRules:[],timeOffRequests:Pe,existingShifts:rt}});if(!Ce.shift&&Ce.eligibility&&!Ce.eligibility.eligible){const Oe=(le=Ce.eligibility.block)==null?void 0:le.reason;let xe="Cannot assign employee: ";switch(Oe){case"approved_time_off_overlap":xe+="Employee has approved time off during this shift.";break;case"employee_not_active":xe+="Employee is not active.";break;case"cannot_work_availability":xe+="Employee has marked this time as unavailable.";break;case"cross_location_overlap":xe+="Employee has an overlapping shift at another location.";break;default:xe+=Oe||"Unknown eligibility issue."}confirm(`${xe} 247 248Do you want to override this and assign anyway?`)&&(await te.assignEmployee(jt,w,{overrideReason:M||`Manager override: ${Oe}`,skipEligibility:!0}),wt(!1),Dt(null));return}if((fe=Ce.eligibility)!=null&&fe.warnings&&Ce.eligibility.warnings.length>0){const Oe=Ce.eligibility.warnings.map(xe=>{var Fe;switch(xe.type){case"overtime_risk":return`Overtime risk: ${(Fe=xe.details)==null?void 0:Fe.projected_hours}h projected this week`;case"insufficient_travel_time":return"Insufficient travel time between locations";case"calendar_conflict_warn_only":return"Calendar conflict detected";default:return xe.type}}).join(` 249- `);alert(`Assignment successful with warnings: 250- ${Oe}`)}wt(!1),Dt(null)}catch(ce){console.error("[HR] Failed to assign employee:",ce),alert("Failed to assign employee")}finally{ae(!1)}},bo=async w=>{var M;try{ae(!0),me?await te.createShift({location_id:w.location_id||z||((M=je[0])==null?void 0:M.id)||"",position_id:w.position_id||void 0,start_at_utc:w.start_at_utc||new Date().toISOString(),end_at_utc:w.end_at_utc||new Date(Date.now()+480*60*1e3).toISOString(),notes:w.notes||void 0,status:"draft"}):C&&await te.updateShift(C.id,w),re(!1),Y(null)}catch(G){console.error("[HR] Failed to save shift:",G),alert("Failed to save shift")}finally{ae(!1)}},yo=async()=>{C&&(await Da([C.id]),re(!1),Y(null))},wo=async w=>{if(C)try{ae(!0),await te.requestCoverage(C.id,w),re(!1),Y(null)}catch(M){console.error("[HR] Failed to request coverage:",M),alert("Failed to request coverage")}finally{ae(!1)}},jo=()=>{J(null),ir(!0),pe(!0)},_o=async w=>{var M;try{if(ae(!0),fa){const le=await te.createTemplate({location_id:w.location_id||z||((M=je[0])==null?void 0:M.id)||"",name:w.name||"New Template"});J({...le,shifts:[]}),ir(!1)}else if(U){await te.updateTemplate(U.id,w);const le=await te.getTemplate(U.id);le&&J(le)}const G=await te.getTemplates(z||void 0);lt(G)}catch(G){console.error("[HR] Failed to save template:",G),alert("Failed to save template")}finally{ae(!1)}},No=async w=>{var M;try{let G=U==null?void 0:U.id;if(!G){const ce=await te.createTemplate({location_id:z||((M=je[0])==null?void 0:M.id)||"",name:"New Template"});G=ce.id,J({...ce,shifts:[]}),ir(!1)}
250await te.addTemplateShift(G,w);const le=await te.getTemplate(G);le&&J(le);const fe=await te.getTemplates(z||void 0);lt(fe)}catch(G){console.error("[HR] Failed to add template shift:",G)}},So=async(w,M)=>{if(U)try{await te.updateTemplateShift(U.id,w,M);const G=await te.getTemplate(U.id);G&&J(G)}catch(G){console.error("[HR] Failed to update template shift:",G)}},Co=async w=>{if(U)try{await te.deleteTemplateShift(U.id,w);const M=await te.getTemplate(U.id);M&&J(M)}catch(M){console.error("[HR] Failed to delete template shift:",M)}},ko=async()=>{if(U)try{await te.updateTemplate(U.id,{status:"active"});const w=await te.getTemplate(U.id);w&&J(w);const M=await te.getTemplates(z||void 0);lt(M)}catch(w){console.error("[HR] Failed to activate template:",w)}},Ro=async()=>{if(U)try{await te.updateTemplate(U.id,{status:"archived"}),pe(!1),J(null);const w=await te.getTemplates(z||void 0);lt(w)}catch(w){console.error("[HR] Failed to archive template:",w)}},qr=ms.useRef(!1),Do=async()=>{if(!(!U||qr.current)){qr.current=!0;try{const w=await te.duplicateTemplate(U.id);lt(M=>[...M,w].sort((G,le)=>G.name.localeCompare(le.name))),J(w)}catch(w){alert(w instanceof Error?w.message:"Unable to duplicate this template.")}finally{qr.current=!1}}},Eo=async(w,M,G,le=1)=>{try{ae(!0);let fe=0,ce=0;const Ae=[],[rt,Pe,Ce]=M.split("-").map(Number),Oe=new Date(rt,Pe-1,Ce,12,0,0,0);for(let Fe=0;Fe<le;Fe++){const He=new Date(Oe);He.setDate(He.getDate()+Fe*7);const Ne=`${He.getFullYear()}-${String(He.getMonth()+1).padStart(2,"0")}-${String(He.getDate()).padStart(2,"0")}`,Le=await te.applyTemplate({template_id:w,start_date:Ne,create_as_draft:G},"America/New_York");fe+=Le.shifts.length,ce+=Le.errors.length,Le.conflicts&&Ae.push(...Le.conflicts)}let xe=`Created ${fe} shifts`;if(le>1&&(xe+=` across ${le} weeks`),Ae.length>0){const Fe=Ae.filter(Ne=>Ne.reason==="time_off_conflict"),He=Ae.filter(Ne=>Ne.reason==="shift_overlap");xe+=` 251 252â ï¸ ${Ae.length} assignment conflict(s) detected:`,Fe.length>0&&(xe+=` 253 254ð Time Off Conflicts (${Fe.length}):`,Fe.slice(0,5).forEach(Ne=>{const Le=o.find($r=>$r.id===Ne.employee_id),Ur=Le?`${Le.firstName} ${Le.lastName}`:"Unknown";xe+=` 255 ⢠${Ur} on ${Ne.shift_date} (${Ne.start_time}-${Ne.end_time})`}),Fe.length>5&&(xe+=` 256 ... and ${Fe.length-5} more`)),He.length>0&&(xe+=` 257 258ð Shift Overlap Conflicts (${He.length}):`,He.slice(0,5).forEach(Ne=>{const Le=o.find($r=>$r.id===Ne.employee_id),Ur=Le?`${Le.firstName} ${Le.lastName}`:"Unknown";xe+=` 259 ⢠${Ur} on ${Ne.shift_date} (${Ne.start_time}-${Ne.end_time})`}),He.length>5&&(xe+=` 260 ... and ${He.length-5} more`)),xe+=` 261 262These shifts were created but left UNASSIGNED. Please manually assign them.`}ce>0&&(xe+=` 263 264â ${ce} error(s) occurred during creation.`),alert(xe),Bt(!1)}catch(fe){console.error("[HR] Failed to apply template:",fe),alert("Failed to apply template")}finally{ae(!1)}},Ea=async w=>{const M=w!=null&&w.createdAfter?`This will delete all template-applied shifts created after ${new Date(w.createdAfter).toLocaleString()}. Continue?`:w!=null&&w.startDate&&(w!=null&&w.endDate)?`This will delete all template-applied shifts between ${w.startDate} and ${w.endDate}. Continue?`:"This will delete all template-applied shifts. Continue?";if(confirm(M))try{ae(!0);const G=await te.deleteAppliedTemplateShifts({...w,hardDelete:!0});alert(`Successfully deleted ${G.deleted} shifts${G.failed>0?` (${G.failed} failed)`:""}`)}catch(G){console.error("[HR] Failed to undo template application:",G),alert("Failed to undo template application")}finally{ae(!1)}},To=w=>{$s(w)},Io=async w=>{try{it(!0),await te.createAvailabilityRule({employee_id:w.employee_id,weekday:w.weekday,start_local_time:w.start_local_time,end_local_time:w.end_local_time,type:w.type,effective_start_date:w.effective_start_date||void 0,effective_end_date:w.effective_end_date||void 0})}catch(M){console.error("[HR] Failed to create availability rule:",M),alert("Failed to create availability rule")}finally{it(!1)}},Ao=async(w,M)=>{try{it(!0),await te.updateAvailabilityRule(w,M)}catch(G){console.error("[HR] Failed to update availability rule:",G),alert("Failed to update availability rule")}finally{it(!1)}},Po=async w=>{try{it(!0),await te.deleteAvailabilityRule(w)}catch(M){console.error("[HR] Failed to delete availability rule:",M),alert("Failed to delete availability rule")}finally{it(!1)}},Oo=async(w,M)=>{try{it(!0),await te.bulkSetAvailability(w,M)}catch(G){console.error("[HR] Failed to save availability:",G),alert("Failed to save availability")}finally{it(!1)}},Mo=async w=>
264{try{Ye(!0),await xt.createTimeOffRequest(w),Wt(!1)}catch(M){console.error("[HR] Failed to create time off request:",M),alert("Failed to create time off request")}finally{Ye(!1)}},Fo=async(w,M)=>{try{Ye(!0),await xt.updateTimeOffRequest(w,M),Wt(!1),Mr(null)}catch(G){console.error("[HR] Failed to update time off request:",G),alert("Failed to update time off request")}finally{Ye(!1)}},Lo=async w=>{try{Ye(!0),await xt.approveTimeOffRequest(w)}catch(M){console.error("[HR] Failed to approve time off request:",M),alert("Failed to approve time off request")}finally{Ye(!1)}},qo=async(w,M)=>{try{Ye(!0),await xt.denyTimeOffRequest(w,M)}catch(G){console.error("[HR] Failed to deny time off request:",G),alert("Failed to deny time off request")}finally{Ye(!1)}},Uo=async w=>{try{Ye(!0),await xt.cancelTimeOffRequest(w)}catch(M){console.error("[HR] Failed to cancel time off request:",M),alert("Failed to cancel time off request")}finally{Ye(!1)}},$o=w=>{Mr(w),Wt(!0)},Ho=async(w,M,G)=>{try{Ge(!0);const le=ja.find(fe=>fe.id===w);if(!le)return;await te.resolveCoverage(le.shift_id,M,G),await jr.approveCoverageRequest(w)}catch(le){console.error("[HR] Failed to approve coverage:",le),alert("Failed to approve coverage request")}finally{Ge(!1)}},Bo=async(w,M)=>{try{Ge(!0),await jr.denyCoverageRequest(w,M)}catch(G){console.error("[HR] Failed to reject coverage:",G),alert("Failed to reject coverage request")}finally{Ge(!1)}},zo=async w=>{try{Ge(!0),await te.approveSwapRequest(w)}catch(M){console.error("[HR] Failed to approve swap:",M),alert("Failed to approve swap request")}finally{Ge(!1)}},Wo=async(w,M)=>{try{Ge(!0),await te.rejectSwapRequest(w,M)}catch(G){console.error("[HR] Failed to reject swap:",G),alert("Failed to reject swap request")}finally{Ge(!1)}},Vo=async()=>{Ge(!0),setTimeout(()=>Ge(!1),500)},Ko=async w=>{try{Me(!0),await mt.createLocation(w)}catch(M){throw console.error("[HR] Failed to create location:",M),M}finally{Me(!1)}},Yo=async(w,M)=>{try{Me(!0),await mt.updateLocation(w,M)}catch(G){throw console.error("[HR] Failed to update location:",G),G}finally{Me(!1)}},Go=async w=>{try{Me(!0),await mt.archiveLocation(w)}catch(M){throw console.error("[HR] Failed to archive location:",M),M}finally{Me(!1)}},Qo=async w=>{try{Me(!0),await mt.createPosition(w)}catch(M){throw console.error("[HR] Failed to create position:",M),M}finally{Me(!1)}},Zo=async(w,M)=>{try{Me(!0),await mt.updatePosition(w,M)}catch(G){throw console.error("[HR] Failed to update position:",G),G}finally{Me(!1)}},Jo=async w=>{try{Me(!0),await mt.archivePosition(w)}catch(M){throw console.error("[HR] Failed to archive position:",M),M}finally{Me(!1)}};return e.jsxs("div",{className:"flex flex-col min-h-full w-full",children:[e.jsx("div",{className:"bg-gradient-to-r from-[var(--color-primary)] via-[var(--color-primary)] to-[var(--color-primary)] py-5 px-6 lg:px-8",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-14 h-14 bg-[var(--color-bg-active)] backdrop-blur-sm rounded-xl flex items-center justify-center shadow-lg",children:e.jsx(Re,{className:"w-7 h-7 text-[var(--color-text-primary)]"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-[var(--color-text-primary)]",children:"HR & People"}),e.jsx("p",{className:"text-[var(--color-text-secondary)] text-sm",children:"Manage your team, schedules, and culture"})]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs("button",{onClick:()=>f(!0),className:"flex items-center gap-2 px-4 py-2 bg-[var(--color-bg-base)] text-[var(--color-text-primary)] rounded-lg text-sm font-semibold shadow-lg hover:bg-[var(--color-bg-surface)] transition",children:[e.jsx(ot,{className:"w-4 h-4"})," Add Employee"]})})]})}),e.jsx("div",{className:"bg-[var(--color-bg-base)]/50 backdrop-blur-sm border-b border-[var(--color-border-subtle)] px-6 lg:px-8",children:e.jsxs("div",{className:"flex gap-1 -mb-px overflow-x-auto",children:[e.jsxs("button",{onClick:()=>a("directory"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium border-b-2 transition-all whitespace-nowrap ${r==="directory"?"border-[var(--color-primary)] text-[var(--color-primary)]":"border-transparent text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-strong)]"}`,children:[e.jsx(Re,{className:"w-4 h-4"})," Directory"]}),e.jsxs("button",{onClick:()=>a("schedule"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium border-b-2 transition-all whitespace-nowrap ${r==="schedule"?"border-[var(--color-primary)] text-[var(--color-primary)]":"border-transparent text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-strong)]"}`,children:[e.jsx(be,{className:"w-4 h-4"})," Schedule"]}),e.jsxs("button",{onClick:()=>
264a("timeclock"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium border-b-2 transition-all whitespace-nowrap ${r==="timeclock"?"border-[var(--color-primary)] text-[var(--color-primary)]":"border-transparent text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-strong)]"}`,children:[e.jsx(ve,{className:"w-4 h-4"})," Time Clock"]}),e.jsxs("button",{onClick:()=>a("timeoff"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium border-b-2 transition-all whitespace-nowrap ${r==="timeoff"?"border-[var(--color-primary)] text-[var(--color-primary)]":"border-transparent text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-strong)]"}`,children:[e.jsx(Oa,{className:"w-4 h-4"})," Time Off"]}),e.jsxs("button",{onClick:()=>a("reviews"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium border-b-2 transition-all whitespace-nowrap ${r==="reviews"?"border-[var(--color-primary)] text-[var(--color-primary)]":"border-transparent text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-strong)]"}`,children:[e.jsx(sr,{className:"w-4 h-4"})," Reviews"]}),e.jsxs("button",{onClick:()=>a("orgchart"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium border-b-2 transition-all whitespace-nowrap ${r==="orgchart"?"border-[var(--color-primary)] text-[var(--color-primary)]":"border-transparent text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-strong)]"}`,children:[e.jsx(_r,{className:"w-4 h-4"})," Org Chart"]}),e.jsxs("button",{onClick:()=>a("documents"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium border-b-2 transition-all whitespace-nowrap ${r==="documents"?"border-[var(--color-primary)] text-[var(--color-primary)]":"border-transparent text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-strong)]"}`,children:[e.jsx(et,{className:"w-4 h-4"})," Documents"]}),e.jsxs("button",{onClick:()=>a("analytics"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium border-b-2 transition-all whitespace-nowrap ${r==="analytics"?"border-[var(--color-primary)] text-[var(--color-primary)]":"border-transparent text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-strong)]"}`,children:[e.jsx(_r,{className:"w-4 h-4"})," Analytics"]})]})}),e.jsx("div",{className:"flex-1 overflow-hidden px-4 lg:px-8 py-6",children:e.jsxs("div",{className:"h-full bg-[var(--color-bg-hover)] backdrop-blur-2xl rounded-xl border border-[var(--color-border-default)] shadow-sm flex flex-col overflow-hidden",children:[r==="directory"&&e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[e.jsx(Td,{filters:N,onFiltersChange:S,departments:lo,onExport:mo,onImport:xo,onSettings:()=>Ca(!0),employeeCount:o.length}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:m?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-[var(--color-border-default)] border-t-transparent"})}):o.length===0?e.jsxs("div",{className:"text-center py-20 text-[var(--color-text-secondary)]",children:[e.jsx(Re,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No employees found"}),e.jsx("p",{className:"text-sm mt-1",children:Object.keys(N).length>0?"Try adjusting your filters":"Add your first employee to get started"})]}):e.jsx("div",{className:"overflow-x-auto -mx-4 md:mx-0",children:e.jsxs(aa,{className:"min-w-full md:min-w-0 text-left",children:[e.jsx("thead",{className:"bg-[var(--color-bg-hover)] text-xs font-bold text-[var(--color-text-primary)] uppercase border-b border-[var(--color-border-default)] sticky top-0",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3 md:px-3 md:py-2",children:"Name"}),e.jsx("th",{className:"px-4 py-3 md:px-3 md:py-2",children:"Role"}),e.jsx("th",{className:"px-4 py-3 md:px-3 md:py-2 hidden md:table-cell",children:"Department"}),e.jsx("th",{className:"px-4 py-3 md:px-3 md:py-2 hidden lg:table-cell",children:"Status"}),e.jsx("th",{className:"px-4 py-3 md:px-3 md:py-2 hidden lg:table-cell",children:"Type"}),e.jsx("th",{className:"px-4 py-3 md:px-3 md:py-2 text-right",children:"Risk Score"}),e.jsx("th",{className:"px-4 py-3 md:px-3 md:py-2 text-right",children:"Actions"})]})}),e.jsx("tbody",{className:"divide-y divide-[var(--color-border-subtle)]",children:o.map(w=>e.jsxs("tr",{className:"hover:bg-[var(--color-bg-hover)] min-h-[52px] transition-colors",children:[e.jsx("td",{className:"px-4 py-3 md:px-3 md:py-2 font-bold text-[var(--color-text-primary)]",children:e.jsxs("button",{type:"button",onClick:()=>ka(w),className:"min-h-11 text-left font-bold text-[var(--color-text-primary)] underline-offset-4 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-focus-ring)]",children:[w.firstName," ",w.lastName,e.jsx("span",{className:"block text-xs font-normal text-[var(--color-text-primary)]",children:w.email})]})}),e.jsx("td",{className:"px-4 py-3 md:px-3 md:py-2 text-sm text-[var(--color-text-primary)]",children:w.role}),e.jsx("td",{className:"px-4 py-3 md:px-3 md:py-2 text-sm text-[var(--color-text-primary)] hidden md:table-cell",children:w.department}),e.jsx("td",{className:"px-4 py-3 md:px-3 md:py-2 hidden lg:table-cell",children:e.jsx("span",{className:`px-2 py-1 rounded-full text-xs font-bold ${w.status==="Active"?"bg-[var(--color-status-success-bg)] text-[var(--color-status-success)]":w.status==="Terminated"?"bg-[var(--color-status-danger-bg)] text-[var(--color-status-danger)]":w.status==="Leave"?"bg-[var(--color-status-warning-bg)] text-[var(--color-status-warning)]":"bg-[var(--color-bg-hover)] text-[var(--color-text-primary)]"}`,children:w.status})}),e.jsx("td",{className:"px-4 py-3 md:px-3 md:py-2 hidden lg:table-cell text-sm text-[var(--color-text-secondary)]",children:w.employmentType}),e.jsx("td",{className:"px-4 py-3 md:px-3 md:py-2 text-right",children:e.jsx("div",{className:"flex items-center justify-end gap-2",children:e.jsxs("span",{className:`text-xs font-bold ${w.flightRiskScore>50?"text-[var(--color-status-danger)]":"text-[var(--color-status-success)]"}`,children:[w.flightRiskScore,"%"]})})}),e.jsx("td",{className:"px-4 py-3 md:px-3 md:py-2 text-right",children:e.jsx("button",{onClick:M=>{M.stopPropagation(),ka(w)},className:"text-[var(--color-text-secondary)] hover:text-[var(--color-primary)] min-h-[44px] min-w-[44px] md:min-
264h-0 md:min-w-0 active:scale-95 transition-all flex items-center justify-center",children:e.jsx(fs,{className:"w-4 h-4 md:w-3 md:h-3"})})})]},w.id))})]})})})]}),r==="schedule"&&e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 bg-[var(--color-bg-hover)] border-b border-[var(--color-border-subtle)]",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex items-center bg-[var(--color-bg-hover)] rounded-lg p-1",children:[e.jsxs("button",{onClick:()=>ga("calendar"),className:`flex items-center gap-2 px-3 py-1.5 rounded-md text-sm font-medium transition-colors 265 ${zt==="calendar"?"bg-brand-500/20 text-brand-400":"text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"}`,children:[e.jsx(Oa,{className:"w-4 h-4"}),"Calendar"]}),e.jsxs("button",{onClick:()=>ga("availability"),className:`flex items-center gap-2 px-3 py-1.5 rounded-md text-sm font-medium transition-colors 266 ${zt==="availability"?"bg-brand-500/20 text-brand-400":"text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"}`,children:[e.jsx(Cl,{className:"w-4 h-4"}),"Availability"]})]}),zt==="calendar"&&e.jsxs("span",{className:"text-sm text-[var(--color-text-primary)]",children:[Nt.length," shift",Nt.length!==1?"s":""," scheduled"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[zt==="calendar"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>Bt(!0),className:`flex items-center gap-2 px-3 py-1.5 bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] 267 rounded-lg text-sm text-[var(--color-text-primary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-active)] transition-colors`,children:[e.jsx(tr,{className:"w-4 h-4"}),"Apply Template"]}),e.jsxs("button",{onClick:async()=>{try{const w=await te.getLatestTemplateApplication();if(w){await Ea({templateId:w.templateId,createdAfter:w.createdAt});return}const M=new Date;M.setHours(M.getHours()-24),await Ea({createdAfter:M.toISOString()})}catch(w){console.error("[HR] Failed to resolve latest template application:",w),alert("Failed to resolve latest template application")}},className:`flex items-center gap-2 px-3 py-1.5 bg-[var(--color-status-danger-bg)] border border-[var(--color-status-danger-border)] 268 rounded-lg text-sm text-[var(--color-status-danger)] hover:text-[var(--color-status-danger)] hover:bg-[var(--color-status-danger-bg)] transition-colors`,title:"Undo the most recent template application",children:[e.jsx(qe,{className:"w-4 h-4"}),"Undo Template"]}),e.jsxs("button",{onClick:()=>lr(!0),className:`flex items-center gap-2 px-3 py-1.5 bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] 269 rounded-lg text-sm text-[var(--color-text-primary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-active)] transition-colors`,children:[e.jsx(Vr,{className:"w-4 h-4"}),"Templates",_t.length>0&&e.jsx("span",{className:"px-1.5 py-0.5 bg-brand-500/20 text-brand-400 text-xs rounded",children:_t.length})]})]}),e.jsxs("button",{onClick:()=>_a(!0),className:`flex items-center gap-2 px-3 py-1.5 bg-[var(--color-bg-hover)] border border-[var(--color-border-default)] 270 rounded-lg text-sm text-[var(--color-text-primary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-active)] transition-colors`,title:"Manage Locations & Positions",children:[e.jsx(na,{className:"w-4 h-4"}),"Settings"]})]})]}),zt==="calendar"?e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-4 overflow-hidden p-4 xl:flex-row",children:[e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(nc,{shifts:Nt,locations:je,selectedLocationId:z,onLocationChange:X,onCreateShift:po,onEditShift:vo,onDeleteShift:Ra,onPublishShifts:Da,onAssignEmployee:fo,onWeekChange:$e,loading:ne})}),e.jsx("div",{className:"max-h-[40dvh] w-full flex-shrink-0 overflow-hidden xl:max-h-none xl:w-80",children:e.jsx(Ac,{coverageRequests:ja,swapRequests:Ys,shifts:Nt,employees:o,onApproveCoverage:Ho,onRejectC
270overage:Bo,onApproveSwap:zo,onRejectSwap:Wo,onRefresh:Vo,loading:Qs})})]}):e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(Nc,{employees:o,selectedEmployeeId:cr,rules:Hs,onSelectEmployee:To,onCreateRule:Io,onUpdateRule:Ao,onDeleteRule:Po,onBulkSave:Oo,loading:Bs})})]}),r==="timeclock"&&e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[e.jsx("div",{className:"flex items-center justify-between px-4 py-3 bg-[var(--color-bg-hover)] border-b border-[var(--color-border-subtle)]",children:e.jsx("div",{className:"flex items-center gap-4",children:e.jsxs("div",{className:"flex items-center bg-[var(--color-bg-hover)] rounded-lg p-1",children:[e.jsxs("button",{onClick:()=>Or("active"),className:`flex items-center gap-2 px-3 py-1.5 rounded-md text-sm font-medium transition-colors 271 ${Pr==="active"?"bg-brand-500/20 text-brand-400":"text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"}`,children:[e.jsx(Re,{className:"w-4 h-4"}),"Active Now"]}),e.jsxs("button",{onClick:()=>Or("individual"),className:`flex items-center gap-2 px-3 py-1.5 rounded-md text-sm font-medium transition-colors 272 ${Pr==="individual"?"bg-brand-500/20 text-brand-400":"text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"}`,children:[e.jsx(ve,{className:"w-4 h-4"}),"Time Clock"]})]})})}),e.jsx("div",{className:"flex-1 overflow-hidden",children:Pr==="active"?e.jsx(Gc,{employees:o,locations:je,onSelectEmployee:w=>{Us(w),Or("individual")}}):e.jsx(Vc,{employees:o,locations:je,currentEmployeeId:qs,isManager:!0})})]}),r==="timeoff"&&e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx($c,{requests:ya,employees:o,isManager:!0,onApprove:Lo,onDeny:qo,onCancel:Uo,onEdit:$o,onCreateNew:()=>Wt(!0),loading:wa})}),r==="reviews"&&e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(sd,{employees:o,currentUserId:(Ta=A.getCurrentUser())==null?void 0:Ta.id,isManager:!0,onCreateReview:()=>Fr(!0),onSelectReview:w=>{console.log("[HR] Selected review:",w.id)}})}),r==="orgchart"&&e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(dd,{employees:o,onSelectEmployee:w=>{v(w),p(!0)}})}),r==="documents"&&e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(fd,{employees:o,onUploadDocument:()=>Lr(!0)})}),r==="analytics"&&e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(jd,{employees:o})})]})}),e.jsx(Hd,{isOpen:k,employees:o,onClose:()=>f(!1),onSuccess:w=>{f(!1)}}),e.jsx(xc,{shift:C,locations:je,positions:Vt,transactions:Ue,isOpen:F,isNew:me,onClose:()=>{re(!1),Y(null)},onSave:bo,onPublish:yo,onDelete:()=>{C&&(Ra(C.id),re(!1),Y(null))},onAssign:()=>{},onRequestCoverage:wo}),e.jsx(Od,{isOpen:y,employee:h,employees:o,onClose:()=>{p(!1),v(null)},onSave:co,onDelete:uo,onOpenMobileInvite:io}),e.jsx(Md,{isOpen:j,onClose:()=>{I(!1),R(""),O([]),b([]),W(0)},csvContent:$,csvHeaders:E,sampleRows:D,totalRows:P,onImportComplete:ho}),e.jsx(vc,{isOpen:Ke,shift:Nt.find(w=>w.id===jt)||null,employees:o.filter(w=>w.status==="Active"),onClose:()=>{wt(!1),Dt(null)},onAssign:go,loading:ne}),Ls&&e.jsx("div",{className:"fixed inset-0 bg-[var(--color-bg-base)]/70 backdrop-blur-sm flex items-center justify-center z-50 p-4",children:e.jsxs("div",{className:"bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] rounded-xl w-full max-w-lg shadow-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-[var(--color-border-subtle)]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Vr,{className:"w-5 h-5 text-brand-400"}),e.jsx("h2",{className:"text-lg font-bold text-[var(--color-text-primary)]",children:"Schedule Templates"})]}),e.jsx("button",{onClick:()=>lr(!1),className:"p-2 hover:bg-[var(--color-bg-hover)] rounded-lg transition-colors",children:e.jsx(ia,{className:"w-5 h-5 text-[var(--color-text-secondary)]"})})]}),e.jsxs("div",{className:"p-4 max-h-[60vh] overflow-y-auto",children:[e.jsxs("button",{onClick:()=>{lr(!1),jo()},className:`w-full flex items-center justify-center gap-2 px-4 py-3 mb-4 273 bg-brand-600 hover:bg-brand-500 text-[var(--color-text-primary)] rounded-lg font-medium transition-colors`,children:[e.jsx(ot,{className:"w-4 h-4"}),"Create New Template"]}),_t.length===0?e.jsxs("div",{className:"text-center py-8 text-[var(--color-text-secondary)]",children:[e.jsx(Vr,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),e.jsx("p",{children:"No templates yet"}),e.jsx("p",{className:"text-sm mt-1",children:"Create your first template to get started"})]}):e.jsx("div",{className:"space-y-2",children:_t.map(w=>{var M,G;return e.jsxs("div",{className:`flex items-center justify-between p-4 bg-[var(--color-bg-hover)] hover:bg-[var(--color-bg-hover)] 274 rounded-lg border border-[var(--color-border-subtle)] transition-colors cursor-pointer`,onClick:()=>{lr(!1),J(w),ir(!1),pe(!0)},children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-[var(--color-text-primary)]",children:w.name}),e.jsx("span",{className:`px-2 py-0.5 rounded text-xs font-bold uppercase 275 ${w.status==="active"?"bg-[var(--color-status-success-bg)] text-[var(--color-status-success)] border border-[var(--color-status-success-border)]":w.status==="draft"?"bg-[var(--color-bg-elevated)] text-[var(--color-text-muted)] border border-[var(--color-border-subtle)]":"bg-[var(--color-status-danger-bg)] text-[var(--color-status-danger)] border border-[var(--color-status-danger-border)]"}`,children:w.status})]}),e.jsxs("div",{className:"text-xs text-[var(--color-text-secondary)] mt-1",children:[((M=w.shifts)==null?void 0:M.length)||0," shifts â¢"," ",((G=je.find(le=>le.id===w.location_id))==null?void 0:G.name)||"Unknown location"]})]}),e.jsx(nt,{className:"w-4 h-4 text-[var(--color-text-muted)]"})]},w.id)})})]})]})}),ue&&e.jsx(gc,{template:U,locations:je,positions:Vt,employees:o,isNew:fa,onSave:_o,onAddShift:No,onUpdateShift:So,onDeleteShift:Co,onActivate:ko,onArchive:Ro,onDuplicate:Do,onClose:()=>{pe(!1),J(null)},loading:ne}),e.jsx(wc,{isOpen:Ht,templates:_t,locations:je,selectedLocationId:z,onClose:()=>Bt(!1),onApply:Eo,loading:ne}),e.jsx(Pc,{isOpen:Ws,request:Vs,employees:o,isManager:!0,onClose:()=>{Wt(!1),Mr(null)},onSubmit:Mo,onUpdate:Fo,loading:wa}),e.jsx(Hc,{isOpen:Xs,locations:je,positions:Vt,onClose:()=>_a(!1),onCreateLocation:Ko,onUpdateLocation:Yo,onArchiveLocation:Go,onCreatePosition:Qo,onUpdatePosition:Zo,onArchivePosition:Jo,loading:eo}),e.jsx(nd,{isOpen:to,onClose:()=>Fr(!1),onCreated:()=>{Fr(!1)},employees:o,currentUserId:((Ia=A.getCurrentUser())==null?void 0:Ia.id)||""}),e.jsx(gd,{isOpen:ro,onClose:()=>Lr(!1),onUploaded:()=>{Lr(!1)},employees:o}),e.jsx(Xd,{isOpen:ao,employee:so,onClose:()=>{Na(!1),Sa(null)}}),e.jsx(eu,{isOpen:oo,onClose:()=>Ca(!1)})]})};export{fm 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.