import{j as e,u as Ne,b as te,a as se}from"./query-PJ0ZdjbV.js";import{f as nl,a as i,O as ll,k as rl,u as qt,L as Aa,l as ra}from"./vendor-CWhr2lg4.js";import{a2 as Is,b0 as jn,aC as Pa,a as ss,U as Ms,b_ as il,T as os,bf as cl,ap as Et,p as T,a4 as b,l as we,d as ye,h as je,e as ks,f as Cs,B as y,P as ds,aa as He,ab as Ge,ac as Be,ad as We,ae as Ze,q as P,I as R,af as us,ag as fs,ah as vs,ai as _s,aj as Ce,y as Ts,a8 as yt,aU as ia,s as $e,t as Le,v as qe,w as Re,x as Z,L as Ks,av as ca,ax as oa,ay as gn,az as fn,a$ as vn,M as ol,z as Vs,ar as Wt,G as da,H as Fa,J as Es,K as Me,O as ma,a1 as he,C as Rt,ba as Ea,bb as Ma,bc as Fs,bd as Os,al as Ke,aL as Yt,c1 as Ga,c2 as Ba,b as Zt,aA as dl,au as $a,a9 as et,aM as ml,cd as Wa,ce as Ya,cf as Za,cg as Ja,ch as ya,ci as ot,am as xl,an as ul,ao as hl,Q as _n,V as bn,W as Nn,Y as wn,Z as Sn,_ as kn,$ as Cn,a0 as Dn,aT as xa,o as Mt,bY as pl,ak as yl,bz as jl,bU as gl,a5 as Jt,at as Ds,bZ as fl,r as Xa,a6 as vl,cj as _l}from"./index-BSPIaiZU.js";import{L as An}from"./layout-dashboard-pgzECxsO.js";import{T as rt}from"./timer-MJ1USQfz.js";import{F as ka}from"./file-chart-column-increasing-DonUpE5r.js";import{T as Pn,W as Xt,u as La}from"./leave.api-B_yRY25W.js";import{F as Fn}from"./file-text-BeBoTfpI.js";import{S as En}from"./smartphone-CjO1nI6k.js";import{M as jt}from"./map-pin-BhdxZDWP.js";import{I as Mn,U as bl}from"./user-minus-BKk56pZ7.js";import{B as qa}from"./briefcase-ChU_EMgZ.js";import{C as $n}from"./chart-column-DbfNf7gS.js";import{B as ee}from"./badge-C34iUAiA.js";import{U as $t}from"./user-check-B2v_CMeM.js";import{U as Nt}from"./user-x-DcOfmXgA.js";import{C as Nl}from"./calendar-off-CmZ2XSje.js";import{t as wl,c as Ln,n as Sl,f as ve}from"./format-Bw_hER4B.js";import{p as ws}from"./parseISO-CsaAlwIQ.js";import{u as hs,t as ps,o as ys,b as es,s as X,c as De,e as Ns,Z as en,g as kl}from"./date-range-picker-BB0TgAn8.js";import{D as rs}from"./data-table-D_-xOEqd.js";import{S as wt}from"./status-badge-DPaiL_rL.js";import{u as $s}from"./use-data-table-state-CKRg6qY2.js";import{E as Us}from"./ellipsis-DaNBIBaV.js";import{P as Ls}from"./pencil-Dl5fXQYl.js";import{E as ea}from"./employee-select-DtUobKxP.js";import{A as ge}from"./async-select-BUbwdJEZ.js";import{i as Ra,w as Cl}from"./date-validation-D9gNvaP9.js";import{u as Hs,e as ft,B as ct,i as Dl,J as Al,F as Ta,N as za,a6 as Pl,R as Fl,x as El}from"./system-admin.api-BT5u-_A_.js";import{S as st}from"./save-DGfbXnAg.js";import{R as Qs}from"./refresh-cw-DkxP9YPQ.js";import{S as Tt}from"./skeleton-CfUgaIb_.js";import{a as sa}from"./core-hr.api-MChaGqvv.js";import{A as ta}from"./arrow-right-Bmt6JCm_.js";import{C as it}from"./circle-check-Dgh1V3VA.js";import{C as bt}from"./circle-alert-9pjtMKqA.js";import{C as Oa}from"./chevron-left-DLFf1YD2.js";import{E as ua}from"./eye-DlIcvqP-.js";import{F as Ml}from"./file-up-ukT7RSqq.js";import{C as $l}from"./clipboard-list-DCTO70_z.js";import{F as aa}from"./file-spreadsheet-BN0hmWpo.js";import{E as Ll}from"./external-link-B0k2fwUi.js";import{F as qn}from"./file-pen-BsSJrcIJ.js";import{P as ja}from"./page-header-D8tSLbK0.js";import{a as ql,A as Rl,D as dt}from"./approval-detail-layout-CcJbUOlS.js";import{A as gt}from"./arrow-left-CtkbIigo.js";import{B as Rn}from"./building-2-boIK6K2k.js";import{G as Tn}from"./git-branch-DrD8zRaR.js";import{Z as pt}from"./zap-DzbXsdut.js";import{L as zn}from"./layers-DdTlMVfO.js";import{S as St}from"./shield-7SCLx_iT.js";import{R as Ca}from"./rotate-ccw-u1EtXcFp.js";import{H as Tl}from"./history-BtMjBzl1.js";import{C as ha}from"./calendar-clock-ZqVNPbD8.js";import{T as zl}from"./trending-down-BqIHipUb.js";import{B as On}from"./bell-off-WDg6Md43.js";import{P as sn}from"./play-N42nmD6a.js";import{A as Ol}from"./async-multi-select-B1EvM1kI.js";import{C as Vl}from"./circle-x-C0sF-Oht.js";import{T as Ql}from"./trending-up-Cognoqa9.js";import{C as Il}from"./calendar-BZ611BSN.js";import{L as Bt}from"./lock-mVL2BhFn.js";import{C as Kl}from"./circle-check-big-DY9NZlUS.js";import"./ui-aO-W1bxx.js";/**
 * @license lucide-react v0.469.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Ul=Is("ArrowDownRight",[["path",{d:"m7 7 10 10",key:"1fmybs"}],["path",{d:"M17 7v10H7",key:"6fjiku"}]]);/**
 * @license lucide-react v0.469.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Hl=Is("ArrowUpRight",[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]]);/**
 * @license lucide-react v0.469.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Gl=Is("CalendarCog",[["path",{d:"m15.2 16.9-.9-.4",key:"1r0w5f"}],["path",{d:"m15.2 19.1-.9.4",key:"j188fs"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"m16.9 15.2-.4-.9",key:"699xu"}],["path",{d:"m16.9 20.8-.4.9",key:"dfjc4z"}],["path",{d:"m19.5 14.3-.4.9",key:"1eb35c"}],["path",{d:"m19.5 21.7-.4-.9",key:"1tonu5"}],["path",{d:"M21 10.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h6",key:"11kmuh"}],["path",{d:"m21.7 16.5-.9.4",key:"1knoei"}],["path",{d:"m21.7 19.5-.9-.4",key:"q4dx6b"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 2v4",key:"1cmpym"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}]]);/**
 * @license lucide-react v0.469.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const nt=Is("CalendarRange",[["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M17 14h-6",key:"bkmgh3"}],["path",{d:"M13 18H7",key:"bb0bb7"}],["path",{d:"M7 14h.01",key:"1qa3f1"}],["path",{d:"M17 18h.01",key:"1bdyru"}]]);/**
 * @license lucide-react v0.469.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Bl=Is("CircleMinus",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}]]);/**
 * @license lucide-react v0.469.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Wl=Is("Fingerprint",[["path",{d:"M12 10a2 2 0 0 0-2 2c0 1.02-.1 2.51-.26 4",key:"1nerag"}],["path",{d:"M14 13.12c0 2.38 0 6.38-1 8.88",key:"o46ks0"}],["path",{d:"M17.29 21.02c.12-.6.43-2.3.5-3.02",key:"ptglia"}],["path",{d:"M2 12a10 10 0 0 1 18-6",key:"ydlgp0"}],["path",{d:"M2 16h.01",key:"1gqxmh"}],["path",{d:"M21.8 16c.2-2 .131-5.354 0-6",key:"drycrb"}],["path",{d:"M5 19.5C5.5 18 6 15 6 12a6 6 0 0 1 .34-2",key:"1tidbn"}],["path",{d:"M8.65 22c.21-.66.45-1.32.57-2",key:"13wd9y"}],["path",{d:"M9 6.8a6 6 0 0 1 9 5.2v2",key:"1fr1j5"}]]);/**
 * @license lucide-react v0.469.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Vn=Is("Grid3x3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
 * @license lucide-react v0.469.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Yl=Is("LockOpen",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 9.9-1",key:"1mm8w8"}]]);/**
 * @license lucide-react v0.469.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Zl=Is("Palette",[["circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor",key:"1okk4w"}],["circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor",key:"f64h9f"}],["circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor",key:"fotxhn"}],["circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor",key:"qy21gx"}],["path",{d:"M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z",key:"12rzf8"}]]);/**
 * @license lucide-react v0.469.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Jl=Is("UserPen",[["path",{d:"M11.5 15H7a4 4 0 0 0-4 4v2",key:"15lzij"}],["path",{d:"M21.378 16.626a1 1 0 0 0-3.004-3.004l-4.01 4.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"1817ys"}],["circle",{cx:"10",cy:"7",r:"4",key:"e45bow"}]]);function Xl(s,t,a){const l=wl(s,a==null?void 0:a.in);return isNaN(t)?Ln(s,NaN):(l.setDate(l.getDate()+t),l)}function er(s,t){const[a,l]=Sl(s,t.start,t.end);return{start:a,end:l}}function sr(s,t){const{start:a,end:l}=er(t==null?void 0:t.in,s);let c=+a>+l;const r=c?+a:+l,d=c?l:a;d.setHours(0,0,0,0);let h=1;const v=[];for(;+d<=r;)v.push(Ln(a,d)),d.setDate(d.getDate()+h),d.setHours(0,0,0,0);return c?v.reverse():v}const tr=[{heading:"Overview",items:[{to:"/attendance",label:"Dashboard",description:"Attendance overview",icon:An,permission:["attendance","dashboard","read"]}]},{heading:"Attendance",items:[{to:"/attendance/daily-timesheet",label:"Daily Timesheet",description:"Check-in & check-out",icon:rt,permission:["attendance","daily_timesheet","read"]},{to:"/attendance/daily",label:"Daily Attendance",description:"Today's records",icon:Pa,permission:["attendance","attendance","read"]},{to:"/attendance/monthly",label:"Monthly Attendance",description:"Monthly grid view",icon:nt,permission:["attendance","attendance","read"]},{to:"/attendance/monthly-summary",label:"Monthly Summary",description:"Aggregated monthly data",icon:ka,permission:["attendance","attendance","read"]}]},{heading:"Configuration",items:[{to:"/attendance/statuses",label:"Statuses",description:"Attendance status types",icon:Pn,permission:["attendance","attendance","read"]},{to:"/attendance/shifts",label:"Shifts",description:"Shift schedules",icon:ss,permission:["attendance","shift","read"]},{to:"/attendance/rosters",label:"Rosters",description:"Roster planning",icon:Gl,permission:["attendance","roster","read"]},{to:"/attendance/roster-grid",label:"Roster Grid",description:"Employee x date matrix",icon:Vn,permission:["attendance","roster","read"]},{to:"/attendance/shift-allocation",label:"Shift Allocation",description:"Bulk shift assignment",icon:Ms,permission:["attendance","roster","read"]},{to:"/attendance/policies",label:"Policies",description:"Attendance rules",icon:Fn,permission:["attendance","policy","read"]},{to:"/attendance/calendar",label:"Work Calendar",description:"Holidays & working days",icon:nt,permission:["attendance","attendance","read"]},{to:"/attendance/devices",label:"Devices",description:"Biometric devices",icon:En,permission:["attendance","device","read"]},{to:"/attendance/geofences",label:"Geofences",description:"Location zones",icon:jt,permission:["attendance","geofence","read"]},{to:"/attendance/pay-config",label:"Pay Config",description:"Payroll day rules",icon:Mn,permission:["attendance","pay_config","read"]}]},{heading:"Requests",items:[{to:"/attendance/regularizations",label:"Regularizations",description:"Correction requests",icon:il,permission:["attendance","attendance","read"]},{to:"/attendance/overtime",label:"Overtime",description:"OT records",icon:rt,permission:["attendance","attendance","read"]},{to:"/attendance/on-duty",label:"On-Duty",description:"On-duty & outdoor",icon:qa,permission:["attendance","attendance","read"]}]},{heading:"Insights",items:[{to:"/attendance/anomalies",label:"Anomalies",description:"Issues & alerts",icon:os,permission:["attendance","anomaly","read"]},{to:"/attendance/reports",label:"Reports",description:"Attendance reports",icon:ka,permission:["attendance","attendance","read"]},{to:"/attendance/analytics",label:"Analytics",description:"Trends & insights",icon:$n,permission:["attendance","attendance","read"]}]}];function ar({item:s,isActive:t}){const a=s.icon;return e.jsxs(rl,{to:s.to,end:s.to==="/attendance",className:Et("group relative flex items-center gap-3 rounded-lg px-3 py-2.5 transition-all duration-150",t?"bg-primary-subtle/70":"hover:bg-slate-50"),children:[t&&e.jsx("span",{className:"absolute left-0 top-2.5 bottom-2.5 w-[3px] rounded-r-full bg-primary"}),e.jsx("div",{className:Et("flex h-8 w-8 shrink-0 items-center justify-center rounded-lg transition-colors duration-150",t?"bg-primary/10 text-primary":"bg-slate-100 text-slate-400 group-hover:bg-slate-200/70 group-hover:text-slate-500"),children:e.jsx(a,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:Et("block text-[13px] truncate leading-tight",t?"font-medium text-primary":"font-medium text-slate-700 group-hover:text-slate-900"),children:s.label}),e.jsx("span",{className:Et("block text-[11px] truncate leading-tight mt-0.5",t?"text-primary/60":"text-slate-400"),children:s.description})]})]})}function ld(){const s=nl(),t=i.useRef(null),{hasPermission:a}=jn();i.useEffect(()=>{var c;(c=t.current)==null||c.scrollTo(0,0)},[s.pathname]);const l=i.useMemo(()=>tr.map(c=>({...c,items:c.items.filter(r=>a(r.permission[0],r.permission[1],r.permission[2]))})).filter(c=>c.items.length>0),[a]);return e.jsxs("div",{className:"-m-6 flex h-[calc(100%+48px)]",children:[e.jsxs("aside",{className:"w-[260px] shrink-0 border-r border-slate-200/60 bg-white flex flex-col",children:[e.jsxs("div",{className:"shrink-0 px-5 pt-6 pb-4 border-b border-slate-100",children:[e.jsx("h1",{className:"text-[15px] font-semibold text-slate-900 tracking-tight",children:"Attendance"}),e.jsx("p",{className:"mt-0.5 text-[11px] text-slate-400",children:"Shifts, rosters & time tracking"})]}),e.jsx("nav",{className:"flex-1 overflow-y-auto px-3 py-3 scrollbar-thin",children:l.map((c,r)=>e.jsxs("div",{className:Et(r>0&&"mt-6"),children:[e.jsx("p",{className:"mb-2 px-3 text-[11px] font-semibold uppercase tracking-[0.08em] text-slate-400",children:c.heading}),e.jsx("div",{className:"space-y-0.5",children:c.items.map(d=>{const h=cl(s.pathname,d.to,d.to==="/attendance");return e.jsx(ar,{item:d,isActive:h},d.to)})})]},c.heading))})]}),e.jsx("main",{ref:t,className:"flex-1 min-w-0 overflow-y-auto bg-background scrollbar-thin",children:e.jsx("div",{className:"px-8 py-6 w-full",children:e.jsx(ll,{})})})]})}const z="/attendance",f={statuses:["attendance","statuses"],shifts:["attendance","shifts"],shift:s=>["attendance","shifts",s],rosters:["attendance","rosters"],devices:["attendance","devices"],device:s=>["attendance","devices",s],dailyAttendance:["attendance","daily"],markingSheet:["attendance","marking-sheet"],monthlyMarkingSheet:["attendance","monthly-marking-sheet"],punches:["attendance","punches"],regularizations:["attendance","regularizations"],overtime:["attendance","overtime"],overtimeRecord:s=>["attendance","overtime",s],policies:["attendance","policies"],policy:s=>["attendance","policies",s],geofences:["attendance","geofences"],geofence:s=>["attendance","geofences",s],calendars:["attendance","calendars"],calendar:s=>["attendance","calendars",s],calendarHolidays:s=>["attendance","calendars",s,"holidays"],onDuty:["attendance","on-duty"],onDutyRequest:s=>["attendance","on-duty",s],outdoorDuty:["attendance","outdoor-duty"],anomalies:["attendance","anomalies"],dashboard:["attendance","dashboard"],reports:["attendance","reports"],analytics:["attendance","analytics"],monthlySummary:["attendance","monthly-summary"],lateComingRules:["attendance","late-coming-rules"],earlyExitRules:["attendance","early-exit-rules"],absenceRules:["attendance","absence-rules"],policyAssignments:["attendance","policy-assignments"],penalties:["attendance","penalties"],dailyTimesheet:["attendance","daily-timesheet"],punchLog:(s,t)=>["attendance","punch-log",s,t],payConfig:["attendance","pay-config"]};function zt(s){return Ne({queryKey:[...f.statuses,s],queryFn:()=>T.get(`${z}/statuses/`,{params:s}).then(t=>t.data)})}function nr(){const s=te();return se({mutationFn:t=>T.post(`${z}/statuses/`,t).then(a=>a.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.statuses}),b.success("Status type created")},onError:t=>b.error(we(t,"Failed to create status type"))})}function lr(){const s=te();return se({mutationFn:({id:t,...a})=>T.patch(`${z}/statuses/${t}/`,a).then(l=>l.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.statuses}),b.success("Status type updated")},onError:t=>b.error(we(t,"Failed to update status type"))})}function rr(){const s=te();return se({mutationFn:t=>T.delete(`${z}/statuses/${t}/`),onSuccess:()=>{s.invalidateQueries({queryKey:f.statuses}),b.success("Status type deleted")},onError:t=>b.error(we(t,"Failed to delete status type"))})}function pa(s){return Ne({queryKey:[...f.shifts,s],queryFn:()=>T.get(`${z}/shifts/`,{params:s}).then(t=>t.data)})}function rd(s){return Ne({queryKey:f.shift(s),queryFn:()=>T.get(`${z}/shifts/${s}/`).then(t=>t.data),enabled:!!s})}function ir(){const s=te();return se({mutationFn:t=>T.post(`${z}/shifts/`,t).then(a=>a.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.shifts}),b.success("Shift created")},onError:t=>b.error(we(t,"Failed to create shift"))})}function cr(){const s=te();return se({mutationFn:({id:t,...a})=>T.patch(`${z}/shifts/${t}/`,a).then(l=>l.data),onSuccess:(t,a)=>{s.invalidateQueries({queryKey:f.shifts}),s.invalidateQueries({queryKey:f.shift(a.id)}),b.success("Shift updated")},onError:t=>b.error(we(t,"Failed to update shift"))})}function or(){const s=te();return se({mutationFn:t=>T.delete(`${z}/shifts/${t}/`),onSuccess:()=>{s.invalidateQueries({queryKey:f.shifts}),b.success("Shift deleted")},onError:t=>b.error(we(t,"Failed to delete shift"))})}function dr(s){return Ne({queryKey:[...f.rosters,s],queryFn:()=>T.get(`${z}/rosters/`,{params:s}).then(t=>t.data)})}function mr(){const s=te();return se({mutationFn:t=>T.post(`${z}/rosters/`,t).then(a=>a.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.rosters}),b.success("Roster created")},onError:t=>b.error(we(t,"Failed to create roster"))})}function xr(){const s=te();return se({mutationFn:t=>T.post(`${z}/rosters/bulk-upload/`,t,{headers:{"Content-Type":void 0}}).then(a=>a.data),onSuccess:t=>{s.invalidateQueries({queryKey:f.rosters}),b.success(`Roster upload complete — ${t.created??0} created, ${t.updated??0} updated`)},onError:t=>{var l,c;const a=(c=(l=t==null?void 0:t.response)==null?void 0:l.data)==null?void 0:c.errors;if(a!=null&&a.length){const r=a.slice(0,3).map(h=>`Row ${h.row} (${h.column}): ${h.error}`).join("; "),d=a.length>3?` (+${a.length-3} more)`:"";b.error(`Upload rejected — ${r}${d}`)}else b.error(we(t,"Failed to upload rosters"))}})}function ur(){const s=te();return se({mutationFn:t=>T.post(`${z}/rosters/bulk-allocate/`,t).then(a=>a.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.rosters}),b.success("Shift allocated to employees")},onError:()=>b.error("Failed to allocate shift")})}function hr(){return se({mutationFn:s=>T.get(`${z}/rosters/download-template/`,{params:s,responseType:"blob"}).then(t=>t.data),onSuccess:()=>b.success("Template downloaded"),onError:s=>b.error(we(s,"Failed to download template"))})}function pr(s){return Ne({queryKey:[...f.rosters,"grid",s],queryFn:()=>T.get(`${z}/rosters/grid/`,{params:s}).then(t=>t.data),enabled:!!s.date_from&&!!s.date_to})}function yr(){const s=te();return se({mutationFn:t=>T.post(`${z}/rosters/grid/`,t).then(a=>a.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.rosters}),b.success("Roster grid saved")},onError:t=>b.error(we(t,"Failed to save roster grid"))})}function Qn(){const s=te();return se({mutationFn:t=>T.post(`${z}/daily/auto-generate/`,t).then(a=>a.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.dailyAttendance}),s.invalidateQueries({queryKey:f.markingSheet}),s.invalidateQueries({queryKey:f.monthlyMarkingSheet}),s.invalidateQueries({queryKey:f.dashboard}),b.success("Attendance auto-generated")},onError:()=>b.error("Failed to auto-generate attendance")})}function In(){const s=te();return se({mutationFn:t=>T.post(`${z}/daily/process-timesheet/`,t).then(a=>a.data),onSuccess:t=>{s.invalidateQueries({queryKey:f.dailyAttendance}),s.invalidateQueries({queryKey:f.markingSheet}),s.invalidateQueries({queryKey:f.monthlyMarkingSheet}),s.invalidateQueries({queryKey:f.monthlySummary}),s.invalidateQueries({queryKey:f.dailyTimesheet}),s.invalidateQueries({queryKey:f.dashboard}),b.success(t.detail)},onError:t=>b.error(we(t,"Failed to process attendance"))})}function Kn(){const s=te();return se({mutationFn:t=>T.post(`${z}/daily/process-timesheet-month/`,t).then(a=>a.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.dailyAttendance}),s.invalidateQueries({queryKey:f.markingSheet}),s.invalidateQueries({queryKey:f.monthlyMarkingSheet}),s.invalidateQueries({queryKey:f.monthlySummary}),s.invalidateQueries({queryKey:f.dailyTimesheet}),s.invalidateQueries({queryKey:f.dashboard})},onError:t=>b.error(we(t,"Failed to process month timesheet"))})}function jr(s){return Ne({queryKey:[...f.devices,s],queryFn:()=>T.get(`${z}/devices/`,{params:s}).then(t=>t.data)})}function gr(){const s=te();return se({mutationFn:t=>T.post(`${z}/devices/`,t).then(a=>a.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.devices}),b.success("Device registered")},onError:()=>b.error("Failed to register device")})}function fr(){const s=te();return se({mutationFn:({id:t,...a})=>T.patch(`${z}/devices/${t}/`,a).then(l=>l.data),onSuccess:(t,a)=>{s.invalidateQueries({queryKey:f.devices}),s.invalidateQueries({queryKey:f.device(a.id)}),b.success("Device updated")},onError:()=>b.error("Failed to update device")})}function vr(){const s=te();return se({mutationFn:t=>T.post(`${z}/devices/${t}/sync/`).then(a=>a.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.devices}),s.invalidateQueries({queryKey:f.punches}),b.success("Device sync initiated")},onError:()=>b.error("Failed to sync device")})}function id(s){return Ne({queryKey:[...f.dailyAttendance,s],queryFn:()=>T.get(`${z}/daily/`,{params:s}).then(t=>t.data)})}function _r(s){return Ne({queryKey:[...f.markingSheet,s],queryFn:()=>T.get(`${z}/daily/marking-sheet/`,{params:s}).then(t=>t.data),enabled:!!(s!=null&&s.date)})}function br(s){return Ne({queryKey:[...f.monthlyMarkingSheet,s],queryFn:()=>T.get(`${z}/daily/monthly-marking-sheet/`,{params:s}).then(t=>t.data),enabled:!!(s!=null&&s.month)})}function Va(){const s=te();return se({mutationFn:t=>T.post(`${z}/daily/bulk-mark/`,t).then(a=>a.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.dailyAttendance}),s.invalidateQueries({queryKey:f.markingSheet}),s.invalidateQueries({queryKey:f.monthlyMarkingSheet}),s.invalidateQueries({queryKey:f.monthlySummary}),s.invalidateQueries({queryKey:f.dashboard})},onError:()=>b.error("Failed to save attendance")})}function Un(){return se({mutationFn:s=>T.get(`${z}/daily/download-template/`,{params:s,responseType:"blob"}).then(t=>t.data),onSuccess:()=>b.success("Template downloaded"),onError:()=>b.error("Failed to download template")})}function cd(s){return Ne({queryKey:[...f.punches,s],queryFn:()=>T.get(`${z}/punches/`,{params:s}).then(t=>t.data)})}function od(){const s=te();return se({mutationFn:t=>T.post(`${z}/punches/`,t).then(a=>a.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.punches}),s.invalidateQueries({queryKey:f.dailyAttendance}),s.invalidateQueries({queryKey:f.dashboard}),b.success("Punch recorded")},onError:()=>b.error("Failed to record punch")})}function Nr(s){return Ne({queryKey:[...f.regularizations,s],queryFn:()=>T.get(`${z}/regularizations/`,{params:s}).then(t=>t.data)})}function wr(){const s=te();return se({mutationFn:t=>T.post(`${z}/regularizations/`,t).then(a=>a.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.regularizations}),b.success("Regularization request submitted")},onError:()=>b.error("Failed to submit regularization")})}function Sr(){const s=te();return se({mutationFn:({id:t,action:a,rejection_reason:l})=>T.post(`${z}/regularizations/${t}/${a}/`,{rejection_reason:l}).then(c=>c.data),onSuccess:(t,a)=>{s.invalidateQueries({queryKey:f.regularizations}),s.invalidateQueries({queryKey:f.dailyAttendance}),b.success(a.action==="approve"?"Regularization approved":"Regularization rejected")},onError:()=>b.error("Failed to process regularization")})}function kr(s){return Ne({queryKey:f.overtimeRecord(s),queryFn:()=>T.get(`${z}/overtime/${s}/`).then(t=>t.data),enabled:!!s})}function Cr(s){return Ne({queryKey:[...f.overtime,s],queryFn:()=>T.get(`${z}/overtime/`,{params:s}).then(t=>t.data)})}function Dr(){const s=te();return se({mutationFn:t=>T.post(`${z}/overtime/`,t).then(a=>a.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.overtime}),b.success("Overtime request created")},onError:t=>b.error(we(t,"Failed to create overtime request"))})}function Ar(){const s=te();return se({mutationFn:({id:t,action:a,approved_hours:l})=>T.post(`${z}/overtime/${t}/${a}/`,{approved_hours:l}).then(c=>c.data),onSuccess:(t,a)=>{s.invalidateQueries({queryKey:f.overtime}),b.success(a.action==="approve"?"Overtime approved":"Overtime rejected")},onError:()=>b.error("Failed to process overtime")})}function Pr(s){return Ne({queryKey:[...f.policies,s],queryFn:()=>T.get(`${z}/policies/`,{params:s}).then(t=>t.data)})}function Hn(s){return Ne({queryKey:f.policy(s),queryFn:()=>T.get(`${z}/policies/${s}/`).then(t=>t.data),enabled:!!s})}function Fr(){const s=te();return se({mutationFn:t=>T.post(`${z}/policies/`,t).then(a=>a.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.policies}),b.success("Policy created")},onError:()=>b.error("Failed to create policy")})}function Er(){const s=te();return se({mutationFn:({id:t,...a})=>T.patch(`${z}/policies/${t}/`,a).then(l=>l.data),onSuccess:(t,a)=>{s.invalidateQueries({queryKey:f.policies}),s.invalidateQueries({queryKey:f.policy(a.id)}),b.success("Policy updated")},onError:()=>b.error("Failed to update policy")})}function Mr(){const s=te();return se({mutationFn:t=>T.delete(`${z}/policies/${t}/`),onSuccess:()=>{s.invalidateQueries({queryKey:f.policies}),b.success("Policy deleted")},onError:()=>b.error("Failed to delete policy")})}function $r(s){return Ne({queryKey:[...f.lateComingRules,s],queryFn:()=>T.get(`${z}/late-coming-rules/`,{params:s?{policy:s}:void 0}).then(t=>t.data),enabled:!!s})}function Lr(){const s=te();return se({mutationFn:t=>T.post(`${z}/late-coming-rules/`,t).then(a=>a.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.lateComingRules}),s.invalidateQueries({queryKey:f.policies}),b.success("Late coming rule created")},onError:t=>b.error(we(t,"Failed to create rule"))})}function qr(){const s=te();return se({mutationFn:({id:t,...a})=>T.patch(`${z}/late-coming-rules/${t}/`,a).then(l=>l.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.lateComingRules}),s.invalidateQueries({queryKey:f.policies}),b.success("Late coming rule updated")},onError:t=>b.error(we(t,"Failed to update rule"))})}function Rr(){const s=te();return se({mutationFn:t=>T.delete(`${z}/late-coming-rules/${t}/`),onSuccess:()=>{s.invalidateQueries({queryKey:f.lateComingRules}),s.invalidateQueries({queryKey:f.policies}),b.success("Late coming rule deleted")},onError:t=>b.error(we(t,"Failed to delete rule"))})}function Tr(s){return Ne({queryKey:[...f.earlyExitRules,s],queryFn:()=>T.get(`${z}/early-exit-rules/`,{params:s?{policy:s}:void 0}).then(t=>t.data),enabled:!!s})}function zr(){const s=te();return se({mutationFn:t=>T.post(`${z}/early-exit-rules/`,t).then(a=>a.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.earlyExitRules}),s.invalidateQueries({queryKey:f.policies}),b.success("Early exit rule created")},onError:t=>b.error(we(t,"Failed to create rule"))})}function Or(){const s=te();return se({mutationFn:({id:t,...a})=>T.patch(`${z}/early-exit-rules/${t}/`,a).then(l=>l.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.earlyExitRules}),s.invalidateQueries({queryKey:f.policies}),b.success("Early exit rule updated")},onError:t=>b.error(we(t,"Failed to update rule"))})}function Vr(){const s=te();return se({mutationFn:t=>T.delete(`${z}/early-exit-rules/${t}/`),onSuccess:()=>{s.invalidateQueries({queryKey:f.earlyExitRules}),s.invalidateQueries({queryKey:f.policies}),b.success("Early exit rule deleted")},onError:t=>b.error(we(t,"Failed to delete rule"))})}function Qr(s){return Ne({queryKey:[...f.absenceRules,s],queryFn:()=>T.get(`${z}/absence-rules/`,{params:s?{policy:s}:void 0}).then(t=>t.data),enabled:!!s})}function Ir(){const s=te();return se({mutationFn:t=>T.post(`${z}/absence-rules/`,t).then(a=>a.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.absenceRules}),s.invalidateQueries({queryKey:f.policies}),b.success("Absence rule created")},onError:t=>b.error(we(t,"Failed to create rule"))})}function Kr(){const s=te();return se({mutationFn:({id:t,...a})=>T.patch(`${z}/absence-rules/${t}/`,a).then(l=>l.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.absenceRules}),s.invalidateQueries({queryKey:f.policies}),b.success("Absence rule updated")},onError:t=>b.error(we(t,"Failed to update rule"))})}function Ur(){const s=te();return se({mutationFn:t=>T.delete(`${z}/absence-rules/${t}/`),onSuccess:()=>{s.invalidateQueries({queryKey:f.absenceRules}),s.invalidateQueries({queryKey:f.policies}),b.success("Absence rule deleted")},onError:t=>b.error(we(t,"Failed to delete rule"))})}function Hr(s){return Ne({queryKey:[...f.policyAssignments,s],queryFn:()=>T.get(`${z}/policy-assignments/`,{params:s}).then(t=>t.data)})}function Gr(){const s=te();return se({mutationFn:t=>T.post(`${z}/policy-assignments/`,t).then(a=>a.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.policyAssignments}),s.invalidateQueries({queryKey:f.policies}),b.success("Assignment created")},onError:t=>b.error(we(t,"Failed to create assignment"))})}function Br(){const s=te();return se({mutationFn:({id:t,...a})=>T.patch(`${z}/policy-assignments/${t}/`,a).then(l=>l.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.policyAssignments}),s.invalidateQueries({queryKey:f.policies}),b.success("Assignment updated")},onError:t=>b.error(we(t,"Failed to update assignment"))})}function Wr(){const s=te();return se({mutationFn:t=>T.delete(`${z}/policy-assignments/${t}/`),onSuccess:()=>{s.invalidateQueries({queryKey:f.policyAssignments}),s.invalidateQueries({queryKey:f.policies}),b.success("Assignment deleted")},onError:t=>b.error(we(t,"Failed to delete assignment"))})}function Yr(s){return Ne({queryKey:[...f.penalties,s],queryFn:()=>T.get(`${z}/penalties/`,{params:s}).then(t=>t.data)})}function Zr(){const s=te();return se({mutationFn:({id:t,reason:a})=>T.post(`${z}/penalties/${t}/reverse/`,{reason:a}).then(l=>l.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.penalties}),b.success("Penalty reversed")},onError:t=>b.error(we(t,"Failed to reverse penalty"))})}function Jr(){const s=te();return se({mutationFn:t=>T.post(`${z}/penalties/process-month/`,t).then(a=>a.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.penalties}),b.success("Penalties processed")},onError:t=>b.error(we(t,"Failed to process penalties"))})}function Xr(s){return Ne({queryKey:[...f.geofences,s],queryFn:()=>T.get(`${z}/geofences/`,{params:s}).then(t=>t.data)})}function ei(){const s=te();return se({mutationFn:t=>T.post(`${z}/geofences/`,t).then(a=>a.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.geofences}),b.success("Geofence zone created")},onError:()=>b.error("Failed to create geofence zone")})}function si(){const s=te();return se({mutationFn:({id:t,...a})=>T.patch(`${z}/geofences/${t}/`,a).then(l=>l.data),onSuccess:(t,a)=>{s.invalidateQueries({queryKey:f.geofences}),s.invalidateQueries({queryKey:f.geofence(a.id)}),b.success("Geofence zone updated")},onError:()=>b.error("Failed to update geofence zone")})}function ti(){const s=te();return se({mutationFn:t=>T.delete(`${z}/geofences/${t}/`),onSuccess:()=>{s.invalidateQueries({queryKey:f.geofences}),b.success("Geofence zone deleted")},onError:()=>b.error("Failed to delete geofence zone")})}function ai(s){return Ne({queryKey:[...f.calendars,s],queryFn:()=>T.get(`${z}/calendars/`,{params:s}).then(t=>t.data)})}function ni(){const s=te();return se({mutationFn:t=>T.post(`${z}/calendars/`,t).then(a=>a.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.calendars}),b.success("Work calendar created")},onError:()=>b.error("Failed to create work calendar")})}function li(){const s=te();return se({mutationFn:({id:t,...a})=>T.patch(`${z}/calendars/${t}/`,a).then(l=>l.data),onSuccess:(t,a)=>{s.invalidateQueries({queryKey:f.calendars}),s.invalidateQueries({queryKey:f.calendar(a.id)}),b.success("Work calendar updated")},onError:()=>b.error("Failed to update work calendar")})}function ri(){const s=te();return se({mutationFn:t=>T.delete(`${z}/calendars/${t}/`),onSuccess:()=>{s.invalidateQueries({queryKey:f.calendars}),b.success("Work calendar deleted")},onError:()=>b.error("Failed to delete work calendar")})}function ii(s){return Ne({queryKey:f.calendarHolidays(s),queryFn:()=>T.get(`${z}/calendars/${s}/holidays/`).then(t=>t.data),enabled:!!s})}function ci(s){const t=te();return se({mutationFn:a=>T.post(`${z}/calendars/${s}/holidays/`,a).then(l=>l.data),onSuccess:()=>{t.invalidateQueries({queryKey:f.calendarHolidays(s)}),t.invalidateQueries({queryKey:f.calendars}),b.success("Holiday added")},onError:()=>b.error("Failed to add holiday")})}function oi(s){const t=te();return se({mutationFn:a=>T.delete(`${z}/calendars/${s}/holidays/${a}/`),onSuccess:()=>{t.invalidateQueries({queryKey:f.calendarHolidays(s)}),t.invalidateQueries({queryKey:f.calendars}),b.success("Holiday removed")},onError:()=>b.error("Failed to remove holiday")})}function di(s){const t=te();return se({mutationFn:()=>T.post(`${z}/calendars/${s}/seed-holidays/`).then(a=>a.data),onSuccess:a=>{t.invalidateQueries({queryKey:f.calendarHolidays(s)}),t.invalidateQueries({queryKey:f.calendars}),b.success(`${a.created_count} Indian holidays added`)},onError:()=>b.error("Failed to seed holidays")})}function mi(s){return Ne({queryKey:f.onDutyRequest(s),queryFn:()=>T.get(`${z}/on-duty/${s}/`).then(t=>t.data),enabled:!!s})}function xi(s){return Ne({queryKey:[...f.onDuty,s],queryFn:()=>T.get(`${z}/on-duty/`,{params:s}).then(t=>t.data)})}function ui(){const s=te();return se({mutationFn:t=>T.post(`${z}/on-duty/`,t).then(a=>a.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.onDuty}),b.success("On-duty request submitted")},onError:()=>b.error("Failed to submit on-duty request")})}function dd(){const s=te();return se({mutationFn:({id:t,action:a})=>T.post(`${z}/on-duty/${t}/${a}/`).then(l=>l.data),onSuccess:(t,a)=>{s.invalidateQueries({queryKey:f.onDuty}),b.success(a.action==="approve"?"On-duty request approved":"On-duty request rejected")},onError:()=>b.error("Failed to process on-duty request")})}function hi(s){return Ne({queryKey:[...f.outdoorDuty,s],queryFn:()=>T.get(`${z}/outdoor-duty/`,{params:s}).then(t=>t.data)})}function pi(){const s=te();return se({mutationFn:t=>T.post(`${z}/outdoor-duty/`,t).then(a=>a.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.outdoorDuty}),b.success("Outdoor duty request submitted")},onError:()=>b.error("Failed to submit outdoor duty request")})}function yi(){const s=te();return se({mutationFn:({id:t,action:a})=>T.post(`${z}/outdoor-duty/${t}/${a}/`).then(l=>l.data),onSuccess:(t,a)=>{s.invalidateQueries({queryKey:f.outdoorDuty}),b.success(a.action==="approve"?"Outdoor duty request approved":"Outdoor duty request rejected")},onError:()=>b.error("Failed to process outdoor duty request")})}function ji(s){return Ne({queryKey:[...f.anomalies,s],queryFn:()=>T.get(`${z}/anomalies/`,{params:s}).then(t=>t.data)})}function gi(){const s=te();return se({mutationFn:({id:t,resolution:a,resolution_notes:l})=>T.post(`${z}/anomalies/${t}/resolve/`,{resolution:a,resolution_notes:l}).then(c=>c.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.anomalies}),b.success("Anomaly resolved")},onError:()=>b.error("Failed to resolve anomaly")})}function fi(s){return Ne({queryKey:[...f.dashboard,s],queryFn:()=>T.get(`${z}/dashboard/`,{params:s}).then(t=>t.data)})}function md(s){return Ne({queryKey:[...f.reports,s],queryFn:()=>T.get(`${z}/reports/`,{params:s}).then(t=>t.data),enabled:!!s})}function vi(){return se({mutationFn:({format:s,...t})=>T.get(`${z}/reports/export/`,{params:{...t,file_format:s},responseType:"blob"}).then(a=>a.data),onSuccess:()=>b.success("Report exported"),onError:()=>b.error("Failed to export report")})}function _i(s){return Ne({queryKey:[...f.analytics,s],queryFn:()=>T.get(`${z}/analytics/`,{params:s}).then(t=>t.data)})}function bi(s,t){return Ne({queryKey:[...f.monthlySummary,s],queryFn:()=>T.get(`${z}/monthly-summary/`,{params:s}).then(a=>a.data),refetchInterval:(t==null?void 0:t.refetchInterval)??!1})}function Ni(){const s=te();return se({mutationFn:({id:t,...a})=>T.patch(`${z}/monthly-summary/${t}/`,a).then(l=>l.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.monthlySummary})},onError:()=>b.error("Failed to save attendance changes")})}function wi(){const s=te();return se({mutationFn:t=>T.post(`${z}/monthly-summary/freeze/`,t).then(a=>a.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.monthlySummary}),b.success("Attendance frozen for month")},onError:()=>b.error("Failed to freeze attendance")})}function Si(){const s=te();return se({mutationFn:t=>T.post(`${z}/monthly-summary/unfreeze/`,t).then(a=>a.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.monthlySummary}),b.success("Attendance unfrozen for month")},onError:()=>b.error("Failed to unfreeze attendance")})}function ki(){const s=te();return se({mutationFn:t=>T.post(`${z}/monthly-summary/recalculate/`,t).then(a=>a.data),onSuccess:t=>{t.mode==="sync"?(s.invalidateQueries({queryKey:f.monthlySummary}),b.success(`Recalculated ${t.recomputed_count} employee(s)`)):(s.invalidateQueries({queryKey:f.monthlySummary}),b.success(`Recalculation queued for ${t.queued_count} employee(s). Refreshing shortly...`))},onError:()=>b.error("Failed to queue recalculation")})}function Ci(s){return Ne({queryKey:[...f.dailyTimesheet,s],queryFn:()=>T.get(`${z}/daily-timesheet/`,{params:s}).then(t=>t.data),enabled:!!(s!=null&&s.date)})}function Di(){const s=te();return se({mutationFn:t=>T.post(`${z}/daily-timesheet/bulk-entry/`,t).then(a=>a.data),onSuccess:t=>{s.invalidateQueries({queryKey:f.dailyTimesheet}),s.invalidateQueries({queryKey:f.dailyAttendance}),b.success(t.detail)},onError:t=>b.error(we(t,"Failed to save timesheet entries"))})}function Ai(){const s=te();return se({mutationFn:t=>T.post(`${z}/daily-timesheet/single-entry/`,t).then(a=>a.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.dailyTimesheet}),s.invalidateQueries({queryKey:f.dailyAttendance}),b.success("Entry saved")},onError:t=>b.error(we(t,"Failed to save entry"))})}function Pi(s,t){return Ne({queryKey:f.punchLog(s,t),queryFn:()=>T.get(`${z}/daily-timesheet/punch-log/`,{params:{employee:s,date:t}}).then(a=>a.data),enabled:!!s&&!!t})}function Gn(s){return Ne({queryKey:[...f.payConfig,s],queryFn:()=>T.get(`${z}/pay-config/`,{params:s}).then(t=>t.data)})}function Fi(){const s=te();return se({mutationFn:t=>T.post(`${z}/pay-config/`,t).then(a=>a.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.payConfig}),b.success("Pay config created")},onError:t=>b.error(we(t,"Failed to create pay config"))})}function Ei(){const s=te();return se({mutationFn:({id:t,...a})=>T.patch(`${z}/pay-config/${t}/`,a).then(l=>l.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.payConfig}),b.success("Pay config updated")},onError:t=>b.error(we(t,"Failed to update pay config"))})}function Mi(){const s=te();return se({mutationFn:t=>T.delete(`${z}/pay-config/${t}/`).then(a=>a.data),onSuccess:()=>{s.invalidateQueries({queryKey:f.payConfig}),b.success("Pay config deleted")},onError:t=>b.error(we(t,"Failed to delete pay config"))})}function xd(){const{data:s,isLoading:t}=fi(),a=s==null?void 0:s.summary,l=(s==null?void 0:s.recent_punches)??[],c=(s==null?void 0:s.weekly_trend)??[],r=[{label:"Total Employees",value:(a==null?void 0:a.total_employees)??0,icon:Ms,color:"text-slate-600"},{label:"Present",value:(a==null?void 0:a.present)??0,icon:$t,color:"text-emerald-600"},{label:"Absent",value:(a==null?void 0:a.absent)??0,icon:Nt,color:"text-red-500"},{label:"Late",value:(a==null?void 0:a.late)??0,icon:ss,color:"text-amber-500"},{label:"On Leave",value:(a==null?void 0:a.on_leave)??0,icon:Nl,color:"text-blue-500"},{label:"Half Day",value:(a==null?void 0:a.half_day)??0,icon:bl,color:"text-orange-500"}];return e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center justify-between mb-6",children:e.jsxs("div",{children:[e.jsxs("h2",{className:"text-[16px] font-semibold text-slate-900 flex items-center gap-2",children:[e.jsx(An,{className:"h-5 w-5 text-primary"})," Attendance Dashboard"]}),e.jsx("p",{className:"mt-0.5 text-[13px] text-slate-400",children:"Real-time attendance overview"})]})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4 mb-6",children:r.map(d=>e.jsx(ye,{children:e.jsxs(je,{className:"pt-5 pb-4 px-4",children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsx(d.icon,{className:`h-4 w-4 ${d.color}`})}),e.jsx("p",{className:"text-2xl font-semibold text-slate-900",children:t?"—":d.value}),e.jsx("p",{className:"text-[12px] text-slate-400 mt-0.5",children:d.label})]})},d.label))}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(ye,{children:[e.jsx(ks,{className:"pb-3",children:e.jsx(Cs,{className:"text-[14px] font-semibold",children:"Recent Punches"})}),e.jsx(je,{children:t?e.jsx("p",{className:"text-[13px] text-slate-400",children:"Loading..."}):l.length===0?e.jsx("p",{className:"text-[13px] text-slate-400",children:"No recent punches"}):e.jsx("div",{className:"space-y-3",children:l.slice(0,10).map((d,h)=>e.jsxs("div",{className:"flex items-center justify-between text-[13px]",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[d.punch_type==="in"?e.jsx(Ul,{className:"h-3.5 w-3.5 text-emerald-500"}):e.jsx(Hl,{className:"h-3.5 w-3.5 text-red-400"}),e.jsx("span",{className:"font-medium text-slate-700",children:d.employee_name})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ee,{variant:d.punch_type==="in"?"success":"secondary",className:"text-[10px]",children:d.punch_type.toUpperCase()}),e.jsx("span",{className:"text-slate-400 text-[11px]",children:ve(ws(d.punch_time),"hh:mm a")})]})]},h))})})]}),e.jsxs(ye,{children:[e.jsx(ks,{className:"pb-3",children:e.jsx(Cs,{className:"text-[14px] font-semibold",children:"Weekly Trend"})}),e.jsx(je,{children:t?e.jsx("p",{className:"text-[13px] text-slate-400",children:"Loading..."}):c.length===0?e.jsx("p",{className:"text-[13px] text-slate-400",children:"No trend data available"}):e.jsx("div",{className:"space-y-2",children:c.map((d,h)=>e.jsxs("div",{className:"flex items-center justify-between text-[13px] py-1.5 border-b border-slate-50 last:border-0",children:[e.jsx("span",{className:"text-slate-600 font-medium w-24",children:ve(ws(d.date),"EEE, MMM d")}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("span",{className:"flex items-center gap-1 text-emerald-600",children:[e.jsx($t,{className:"h-3 w-3"})," ",d.present]}),e.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[e.jsx(Nt,{className:"h-3 w-3"})," ",d.absent]}),e.jsxs("span",{className:"flex items-center gap-1 text-amber-500",children:[e.jsx(ss,{className:"h-3 w-3"})," ",d.late]})]})]},h))})})]})]})]})}function Qe(){const{hasPermission:s,requirePermission:t}=jn();return{can:(c,r)=>s("attendance",c,r),must:(c,r)=>t("attendance",c,r)}}const tn=ys({name:X().min(1,"Shift name is required"),code:X().min(1,"Code is required"),is_week_off_type:es().default(!1),start_time:X().optional(),end_time:X().optional(),break_duration_minutes:De.number().min(0).default(60),min_hours_half_day:De.number().min(0).default(4),min_hours_full_day:De.number().min(0).default(8),effective_from:X().min(1,"Effective date is required"),is_active:es().default(!0)}).refine(s=>s.is_week_off_type||!!s.start_time,{message:"Start time is required for a working shift",path:["start_time"]}).refine(s=>s.is_week_off_type||!!s.end_time,{message:"End time is required for a working shift",path:["end_time"]});function ud(){const[s,t]=i.useState(!1),[a,l]=i.useState(null),{pagination:c,setPagination:r,sorting:d,setSorting:h,globalFilter:v,setGlobalFilter:A,queryParams:u}=$s(),{data:p,isLoading:F}=pa(u),O=(p==null?void 0:p.results)??[],m=ir(),_=cr(),q=or(),{can:k,must:x}=Qe(),Y=k("shift","create"),H=k("shift","update"),C=k("shift","delete"),N=hs({resolver:ps(tn),mode:"onSubmit",defaultValues:{name:"",code:"",is_week_off_type:!1,start_time:"",end_time:"",break_duration_minutes:60,min_hours_half_day:4,min_hours_full_day:8,effective_from:new Date().toISOString().split("T")[0],is_active:!0}}),E=N.watch("is_week_off_type");function n(){l(null),N.reset({name:"",code:"",is_week_off_type:!1,start_time:"",end_time:"",break_duration_minutes:60,min_hours_half_day:4,min_hours_full_day:8,effective_from:new Date().toISOString().split("T")[0],is_active:!0}),t(!0)}function K(V){var j,$;l(V),N.reset({name:V.name,code:V.code,is_week_off_type:V.is_week_off_type,start_time:((j=V.start_time)==null?void 0:j.slice(0,5))??"",end_time:(($=V.end_time)==null?void 0:$.slice(0,5))??"",break_duration_minutes:V.break_duration_minutes??60,min_hours_half_day:V.min_hours_half_day??4,min_hours_full_day:V.min_hours_full_day??8,effective_from:V.effective_from??new Date().toISOString().split("T")[0],is_active:V.is_active}),t(!0)}function M(){if(!x("shift",a?"update":"create"))return;const V=N.getValues(),j=tn.safeParse(V);if(!j.success){const J=j.error.formErrors.fieldErrors,B=Object.entries(J).map(([ne,D])=>`${ne}: ${D[0]}`).join("; ");b.error(B||"Validation failed");return}const $={...j.data,start_time:j.data.is_week_off_type?null:j.data.start_time,end_time:j.data.is_week_off_type?null:j.data.end_time};a?_.mutate({id:a.id,...$},{onSuccess:()=>t(!1)}):m.mutate($,{onSuccess:()=>t(!1)})}function o(V){x("shift","delete")&&q.mutate(V)}const L=[{key:"name",header:"Shift Name",render:V=>e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-slate-900",children:V.name}),e.jsx("span",{className:"ml-2 text-[11px] text-slate-400",children:V.code})]})},{key:"timing",header:"Timing",render:V=>{var j,$;return V.is_week_off_type?e.jsx(ee,{variant:"warning",children:"Week Off"}):e.jsxs("span",{className:"text-[13px] text-slate-600",children:[(j=V.start_time)==null?void 0:j.slice(0,5)," - ",($=V.end_time)==null?void 0:$.slice(0,5)]})}},{key:"hours",header:"Hours (Half/Full)",render:V=>e.jsxs("span",{className:"text-[13px] text-slate-500",children:[V.min_hours_half_day,"h / ",V.min_hours_full_day,"h"]})},{key:"status",header:"Status",render:V=>e.jsx(wt,{status:V.is_active?"active":"inactive"})},{key:"actions",header:"",className:"w-10",render:V=>!H&&!C?null:e.jsxs(fs,{children:[e.jsx(vs,{asChild:!0,children:e.jsx(y,{variant:"ghost",size:"icon-sm",children:e.jsx(Us,{className:"h-4 w-4"})})}),e.jsxs(_s,{align:"end",children:[H&&e.jsxs(Ce,{onClick:()=>K(V),children:[e.jsx(Ls,{className:"mr-2 h-3.5 w-3.5"})," Edit"]}),C&&e.jsxs(Ce,{className:"text-red-600",onClick:()=>o(V.id),children:[e.jsx(Ts,{className:"mr-2 h-3.5 w-3.5"})," Delete"]})]})]})}];return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-[16px] font-semibold text-slate-900 flex items-center gap-2",children:[e.jsx(ss,{className:"h-5 w-5 text-primary"})," Shifts"]}),e.jsx("p",{className:"mt-0.5 text-[13px] text-slate-400",children:"Manage shift configurations and timings"})]}),Y&&e.jsxs(y,{size:"sm",onClick:n,children:[e.jsx(ds,{className:"mr-1.5 h-3.5 w-3.5"})," Add Shift"]})]}),e.jsx(rs,{columns:L,data:O,isLoading:F,searchPlaceholder:"Search shifts...",emptyMessage:"No shifts configured",emptyDescription:"Add your first shift to get started.",totalCount:(p==null?void 0:p.count)??0,pagination:c,onPaginationChange:r,sorting:d,onSortingChange:h,globalFilter:v,onGlobalFilterChange:A}),e.jsx(He,{open:s,onOpenChange:t,children:e.jsxs(Ge,{size:"lg",children:[e.jsxs(Be,{children:[e.jsx(We,{children:a?"Edit Shift":"Add Shift"}),e.jsx(Ze,{children:a?"Update shift configuration.":"Create a new shift."})]}),e.jsxs("form",{onSubmit:V=>{V.preventDefault(),M()},className:"flex-1 overflow-y-auto px-6 py-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(P,{children:"Shift Name *"}),e.jsx(R,{...N.register("name"),className:"mt-1.5"}),N.formState.errors.name&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:N.formState.errors.name.message})]}),e.jsxs("div",{children:[e.jsx(P,{children:"Code *"}),e.jsx(R,{...N.register("code"),className:"mt-1.5"}),N.formState.errors.code&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:N.formState.errors.code.message})]})]}),e.jsxs("label",{className:"flex items-center gap-2 text-[13px] text-slate-600",children:[e.jsx("input",{type:"checkbox",...N.register("is_week_off_type"),className:"rounded border-slate-300"}),"This shift represents a week off (no working hours)"]}),!E&&e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(P,{children:"Start Time *"}),e.jsx(R,{type:"time",...N.register("start_time"),className:"mt-1.5"}),N.formState.errors.start_time&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:N.formState.errors.start_time.message})]}),e.jsxs("div",{children:[e.jsx(P,{children:"End Time *"}),e.jsx(R,{type:"time",...N.register("end_time"),className:"mt-1.5"}),N.formState.errors.end_time&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:N.formState.errors.end_time.message})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(P,{children:"Effective From *"}),e.jsx(R,{type:"date",...N.register("effective_from"),className:"mt-1.5"}),N.formState.errors.effective_from&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:N.formState.errors.effective_from.message})]}),e.jsxs("div",{children:[e.jsx(P,{children:"Break Duration (min)"}),e.jsx(R,{type:"number",...N.register("break_duration_minutes"),className:"mt-1.5"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(P,{children:"Min Hours - Half Day"}),e.jsx(R,{type:"number",step:"0.5",...N.register("min_hours_half_day"),className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(P,{children:"Min Hours - Full Day"}),e.jsx(R,{type:"number",step:"0.5",...N.register("min_hours_full_day"),className:"mt-1.5"})]})]}),e.jsx("div",{className:"flex items-center gap-6 pt-2",children:e.jsxs("label",{className:"flex items-center gap-2 text-[13px] text-slate-600",children:[e.jsx("input",{type:"checkbox",...N.register("is_active"),className:"rounded border-slate-300"}),"Active"]})})]}),e.jsxs(us,{children:[e.jsx(y,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(y,{onClick:M,disabled:m.isPending||_.isPending,children:a?"Save Changes":"Create Shift"})]})]})})]})}const $i=ys({employee:X().min(1,"Employee is required"),shift:X().min(1,"Shift is required"),roster_date:Ra("Date is required"),status:Ns(["draft","published","archived"]).default("draft"),remarks:X().optional()}),Li={draft:"secondary",published:"success",archived:"default"};function hd(){const[s,t]=i.useState(!1),[a,l]=i.useState(""),c=i.useRef(null),{pagination:r,setPagination:d,sorting:h,setSorting:v,globalFilter:A,setGlobalFilter:u,queryParams:p}=$s(),F={...p,...a&&{roster_date:a}},{data:O,isLoading:m}=dr(F),_=(O==null?void 0:O.results)??[],q=mr(),k=xr(),x=hr(),{can:Y,must:H}=Qe(),C=Y("roster","create"),{data:N}=pa({page_size:100}),E=(N==null?void 0:N.results)??[],n=hs({resolver:ps($i),defaultValues:{status:"draft"}});function K(){n.reset({status:"draft"}),t(!0)}function M(j){if(!H("roster","create"))return;const $={...j,remarks:j.remarks??""};q.mutate($,{onSuccess:()=>t(!1)})}function o(){const j={};a&&(j.date_from=a,j.date_to=a),x.mutate(j,{onSuccess:$=>{const J=URL.createObjectURL($),B=document.createElement("a");B.href=J,B.download="roster_template.csv",B.click(),URL.revokeObjectURL(J)}})}function L(j){var B;const $=(B=j.target.files)==null?void 0:B[0];if(!$)return;if(!H("roster","create")){j.target.value="";return}const J=new FormData;J.append("file",$),k.mutate(J),j.target.value=""}const V=[{key:"employee",header:"Employee",render:j=>e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-slate-900",children:j.employee_name}),j.employee_id_display&&e.jsx("span",{className:"ml-2 text-[11px] text-slate-400",children:j.employee_id_display})]})},{key:"shift",header:"Shift",render:j=>j.shift_name??"—"},{key:"roster_date",header:"Date",render:j=>ve(ws(j.roster_date),"dd MMM yyyy")},{key:"week_off",header:"Week Off",render:j=>j.week_off?e.jsx(ee,{variant:"warning",children:"Yes"}):e.jsx("span",{className:"text-slate-400",children:"No"})},{key:"status",header:"Status",render:j=>e.jsx(ee,{variant:Li[j.status],children:j.status})},{key:"remarks",header:"Remarks",render:j=>e.jsx("span",{className:"text-[12px] text-slate-500 truncate max-w-[200px] block",children:j.remarks||"—"})}];return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-[16px] font-semibold text-slate-900 flex items-center gap-2",children:[e.jsx(nt,{className:"h-5 w-5 text-primary"})," Rosters"]}),e.jsx("p",{className:"mt-0.5 text-[13px] text-slate-400",children:"Employee shift rosters and scheduling"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{ref:c,type:"file",accept:".csv,.xlsx",onChange:L,className:"hidden"}),C&&e.jsxs(e.Fragment,{children:[e.jsxs(y,{size:"sm",variant:"outline",onClick:o,disabled:x.isPending,children:[e.jsx(yt,{className:"mr-1.5 h-3.5 w-3.5"})," Download Template"]}),e.jsxs(y,{size:"sm",variant:"outline",onClick:()=>{var j;return(j=c.current)==null?void 0:j.click()},disabled:k.isPending,children:[e.jsx(ia,{className:"mr-1.5 h-3.5 w-3.5"})," Bulk Upload"]}),e.jsxs(y,{size:"sm",onClick:K,children:[e.jsx(ds,{className:"mr-1.5 h-3.5 w-3.5"})," Add Roster"]})]})]})]}),e.jsx(rs,{actions:e.jsx("div",{className:"flex gap-2",children:e.jsx(R,{type:"date",value:a,onChange:j=>{l(j.target.value),d($=>({...$,pageIndex:0}))},className:"w-[160px] h-9",placeholder:"Filter by date"})}),columns:V,data:_,isLoading:m,searchPlaceholder:"Search rosters...",emptyMessage:"No rosters found",emptyDescription:"Create a roster or use bulk upload.",totalCount:(O==null?void 0:O.count)??0,pagination:r,onPaginationChange:d,sorting:h,onSortingChange:v,globalFilter:A,onGlobalFilterChange:u}),e.jsx(He,{open:s,onOpenChange:t,children:e.jsxs(Ge,{size:"md",children:[e.jsxs(Be,{children:[e.jsx(We,{children:"Add Roster Entry"}),e.jsx(Ze,{children:"Assign a shift to an employee for a specific date."})]}),e.jsxs("form",{onSubmit:n.handleSubmit(M),className:"flex-1 overflow-y-auto px-6 py-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx(P,{children:"Employee *"}),e.jsx(ea,{value:n.watch("employee")??"",onValueChange:j=>n.setValue("employee",j,{shouldValidate:!0}),className:"mt-1.5"}),n.formState.errors.employee&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:n.formState.errors.employee.message})]}),e.jsxs("div",{children:[e.jsx(P,{children:"Shift *"}),e.jsx("div",{className:"mt-1.5",children:e.jsx(ge,{value:n.watch("shift")??null,onValueChange:j=>n.setValue("shift",j,{shouldValidate:!0}),options:E.map(j=>{var $,J;return{value:j.id,label:j.name,hint:j.is_week_off_type?"Week Off":`${($=j.start_time)==null?void 0:$.slice(0,5)} - ${(J=j.end_time)==null?void 0:J.slice(0,5)}`}}),placeholder:"Select shift",searchPlaceholder:"Search shifts..."})}),n.formState.errors.shift&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:n.formState.errors.shift.message})]}),e.jsxs("div",{children:[e.jsx(P,{children:"Date *"}),e.jsx(R,{type:"date",...n.register("roster_date"),className:"mt-1.5"}),n.formState.errors.roster_date&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:n.formState.errors.roster_date.message})]}),e.jsxs("div",{children:[e.jsx(P,{children:"Status"}),e.jsxs($e,{value:n.watch("status"),onValueChange:j=>n.setValue("status",j),children:[e.jsx(Le,{className:"mt-1.5",children:e.jsx(qe,{})}),e.jsxs(Re,{children:[e.jsx(Z,{value:"draft",children:"Draft"}),e.jsx(Z,{value:"published",children:"Published"})]})]})]}),e.jsxs("div",{children:[e.jsx(P,{children:"Remarks"}),e.jsx(R,{...n.register("remarks"),className:"mt-1.5",placeholder:"Optional remarks"})]})]}),e.jsxs(us,{children:[e.jsx(y,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),C&&e.jsx(y,{onClick:n.handleSubmit(M),disabled:q.isPending,children:"Create Roster"})]})]})})]})}function qi(){return ve(new Date,"yyyy-MM-dd")}const ga="__none__";function mt({label:s,value:t,onChange:a,options:l,isLoading:c,onSearch:r,placeholder:d}){return e.jsxs("div",{className:"w-[190px]",children:[e.jsx(P,{className:"text-[12px]",children:s}),e.jsx("div",{className:"mt-1.5",children:e.jsx(ge,{value:t||"__all__",onValueChange:h=>a(h==="__all__"?"":h),onSearch:r,isLoading:c,options:[{value:"__all__",label:d},...l.map(h=>({value:h.id,label:h.name,hint:h.code}))],placeholder:d,searchPlaceholder:`Search ${s.toLowerCase()}...`})})]})}function pd(){const{can:s,must:t}=Qe(),a=s("roster","update")||s("roster","create"),[l,c]=i.useState(qi()),[r,d]=i.useState(ve(Xl(new Date,6),"yyyy-MM-dd")),[h,v]=i.useState(""),[A,u]=i.useState(""),[p,F]=i.useState(""),[O,m]=i.useState(""),[_,q]=i.useState(""),[k,x]=i.useState(""),[Y,H]=i.useState(""),[C,N]=i.useState(""),[E,n]=i.useState(""),[K,M]=i.useState(""),[o,L]=i.useState(""),[V,j]=i.useState(""),[$,J]=i.useState(""),[B,ne]=i.useState(""),{data:D,isLoading:fe}=Hs({page_size:100,is_active:!0,search:A||void 0}),{data:Q,isLoading:oe}=ft({page_size:100,is_active:!0,search:O||void 0}),{data:Se,isLoading:Te}=ct({page_size:100,is_active:!0,search:k||void 0}),{data:I,isLoading:S}=Dl({page_size:100,is_active:!0,search:C||void 0}),{data:de,isLoading:ze}=Al({page_size:100,is_active:!0,search:K||void 0}),{data:Oe,isLoading:U}=Ta({page_size:100,is_active:!0,search:V||void 0}),{data:me,isLoading:Je}=za({page_size:100,is_active:!0,search:B||void 0}),{data:ms}=pa({page_size:100,is_active:!0}),qs=(ms==null?void 0:ms.results)??[],{data:ts,isLoading:G}=pr({date_from:l,date_to:r,...h&&{company:h},...p&&{branch:p},..._&&{department:_},...Y&&{work_location:Y},...E&&{designation:E},...o&&{grade:o},...$&&{category:$}}),xe=(ts==null?void 0:ts.employees)??[],ue=i.useMemo(()=>!l||!r||l>r?[]:sr({start:ws(l),end:ws(r)}),[l,r]),[Ae,Ie]=i.useState({}),pe=yr();function Fe(re,as){var ls,is,cs;const ns=(ls=Ae[re])==null?void 0:ls[as];return ns!==void 0?ns:((cs=(is=xe.find(Gs=>Gs.id===re))==null?void 0:is.cells[as])==null?void 0:cs.shift_id)??ga}function Ye(re,as,ns){Ie(ls=>({...ls,[re]:{...ls[re],[as]:ns}}))}const js=Object.values(Ae).reduce((re,as)=>re+Object.keys(as).length,0);function gs(){if(!t("roster","update"))return;const re=[];for(const[as,ns]of Object.entries(Ae))for(const[ls,is]of Object.entries(ns))is!==ga&&re.push({employee_id:as,roster_date:ls,shift_id:is});re.length&&pe.mutate({cells:re},{onSuccess:()=>Ie({})})}return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-[16px] font-semibold text-slate-900 flex items-center gap-2",children:[e.jsx(Vn,{className:"h-5 w-5 text-primary"})," Roster Grid"]}),e.jsx("p",{className:"mt-0.5 text-[13px] text-slate-400",children:"Assign a shift per employee per day. Pick a Week Off shift for non-working days."})]}),a&&e.jsxs(y,{size:"sm",onClick:gs,disabled:!js||pe.isPending,children:[pe.isPending?e.jsx(Ks,{className:"mr-1.5 h-3.5 w-3.5 animate-spin"}):e.jsx(st,{className:"mr-1.5 h-3.5 w-3.5"}),"Save ",js>0?`(${js})`:""]})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3 mb-4",children:[e.jsx(mt,{label:"Company",value:h,onChange:v,options:(D==null?void 0:D.results)??[],isLoading:fe,onSearch:u,placeholder:"All Companies"}),e.jsx(mt,{label:"Branch",value:p,onChange:F,options:(Q==null?void 0:Q.results)??[],isLoading:oe,onSearch:m,placeholder:"All Branches"}),e.jsx(mt,{label:"Department",value:_,onChange:q,options:(Se==null?void 0:Se.results)??[],isLoading:Te,onSearch:x,placeholder:"All Departments"}),e.jsx(mt,{label:"Location",value:Y,onChange:H,options:(I==null?void 0:I.results)??[],isLoading:S,onSearch:N,placeholder:"All Locations"}),e.jsx(mt,{label:"Designation",value:E,onChange:n,options:(de==null?void 0:de.results)??[],isLoading:ze,onSearch:M,placeholder:"All Designations"}),e.jsx(mt,{label:"Grade",value:o,onChange:L,options:(Oe==null?void 0:Oe.results)??[],isLoading:U,onSearch:j,placeholder:"All Grades"}),e.jsx(mt,{label:"Category",value:$,onChange:J,options:(me==null?void 0:me.results)??[],isLoading:Je,onSearch:ne,placeholder:"All Categories"}),e.jsxs("div",{children:[e.jsx(P,{className:"text-[12px]",children:"Start Date"}),e.jsx(R,{type:"date",value:l,max:r||void 0,onChange:re=>c(re.target.value),className:"mt-1.5 w-[150px]"})]}),e.jsxs("div",{children:[e.jsx(P,{className:"text-[12px]",children:"End Date"}),e.jsx(R,{type:"date",value:r,min:l||void 0,onChange:re=>d(re.target.value),className:"mt-1.5 w-[150px]"})]})]}),e.jsx("div",{className:"rounded-lg border border-slate-200 overflow-x-auto",children:G?e.jsx("div",{className:"p-8 text-center text-[13px] text-slate-400",children:"Loading roster grid..."}):ue.length?xe.length?e.jsxs("table",{className:"w-full text-[12px] border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"sticky left-0 z-20 bg-slate-50 border-b border-r border-slate-200 px-3 py-2 text-left font-medium text-slate-500 w-[220px] min-w-[220px]",children:"Employee"}),ue.map(re=>{const as=ve(re,"yyyy-MM-dd");return e.jsxs("th",{className:"bg-slate-50 border-b border-slate-200 px-2 py-2 text-center font-medium text-slate-500 w-[110px] min-w-[110px]",children:[e.jsx("div",{children:ve(re,"EEE")}),e.jsx("div",{className:"text-slate-400 font-normal",children:ve(re,"dd MMM")})]},as)})]})}),e.jsx("tbody",{children:xe.map((re,as)=>{const ns=as%2===0?"bg-white":"bg-slate-50/50";return e.jsxs("tr",{children:[e.jsxs("td",{className:`sticky left-0 z-10 ${ns} border-b border-r border-slate-100 px-3 py-1.5`,children:[e.jsx("div",{className:"font-medium text-slate-900",children:re.name}),re.employee_id&&e.jsx("div",{className:"text-[10px] text-slate-400",children:re.employee_id})]}),ue.map(ls=>{var Ss;const is=ve(ls,"yyyy-MM-dd"),cs=Fe(re.id,is),Gs=((Ss=Ae[re.id])==null?void 0:Ss[is])!==void 0;return e.jsx("td",{className:`border-b border-slate-100 px-1 py-1 text-center ${Gs?"bg-blue-50":ns}`,children:e.jsxs($e,{value:cs,onValueChange:Ue=>Ye(re.id,is,Ue),disabled:!a,children:[e.jsx(Le,{className:"h-7 text-[11px] px-1.5",children:e.jsx(qe,{placeholder:"—"})}),e.jsxs(Re,{children:[e.jsx(Z,{value:ga,children:"—"}),qs.map(Ue=>e.jsx(Z,{value:Ue.id,children:Ue.code},Ue.id))]})]})},is)})]},re.id)})})]}):e.jsx("div",{className:"p-8 text-center text-[13px] text-slate-400",children:"No employees found for this filter."}):e.jsx("div",{className:"p-8 text-center text-[13px] text-slate-400",children:"Choose a valid date range."})})]})}const Ri=ys({name:X().min(1,"Device name is required"),device_type:Ns(["fingerprint","rfid","face_recognition","mobile"]),serial_number:X().min(1,"Serial number is required"),ip_address:X().optional(),location:X().optional(),branch:X().optional().nullable()}),Ti={online:"success",offline:"warning",disconnected:"secondary"},zi={fingerprint:"Fingerprint",rfid:"RFID",face_recognition:"Face Recognition",mobile:"Mobile"};function yd(){const[s,t]=i.useState(!1),[a,l]=i.useState(null),{pagination:c,setPagination:r,sorting:d,setSorting:h,globalFilter:v,setGlobalFilter:A,queryParams:u}=$s(),{data:p,isLoading:F}=jr(u),O=(p==null?void 0:p.results)??[],m=gr(),_=fr(),q=vr(),{can:k,must:x}=Qe(),Y=k("device","create"),H=k("device","update"),C=hs({resolver:ps(Ri),defaultValues:{device_type:"fingerprint"}});function N(){l(null),C.reset({device_type:"fingerprint"}),t(!0)}function E(o){l(o),C.reset({name:o.name,device_type:o.device_type,serial_number:o.serial_number,ip_address:o.ip_address,location:o.location,branch:o.branch}),t(!0)}function n(o){if(!x("device",a?"update":"create"))return;const L={...o,branch:o.branch||null};a?_.mutate({id:a.id,...L},{onSuccess:()=>t(!1)}):m.mutate(L,{onSuccess:()=>t(!1)})}function K(o){x("device","update")&&q.mutate(o)}const M=[{key:"name",header:"Device",render:o=>e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-slate-900",children:o.name}),e.jsx("p",{className:"text-[11px] text-slate-400",children:o.serial_number})]})},{key:"device_type",header:"Type",render:o=>e.jsx(ee,{variant:"default",children:zi[o.device_type]})},{key:"location",header:"Location",render:o=>e.jsxs("div",{className:"text-[13px]",children:[e.jsx("span",{className:"text-slate-600",children:o.location||"—"}),o.branch_name&&e.jsx("p",{className:"text-[11px] text-slate-400",children:o.branch_name})]})},{key:"ip_address",header:"IP Address",render:o=>e.jsx("span",{className:"text-[13px] text-slate-500 font-mono",children:o.ip_address||"—"})},{key:"enrollments",header:"Enrollments",render:o=>e.jsx("span",{className:"text-[13px] text-slate-600",children:o.total_enrollments})},{key:"last_sync",header:"Last Sync",render:o=>e.jsx("span",{className:"text-[12px] text-slate-500",children:o.last_sync?ve(ws(o.last_sync),"dd MMM yyyy, hh:mm a"):"Never"})},{key:"status",header:"Status",render:o=>e.jsx(ee,{variant:Ti[o.status],children:o.status})},{key:"actions",header:"",className:"w-10",render:o=>H?e.jsxs(fs,{children:[e.jsx(vs,{asChild:!0,children:e.jsx(y,{variant:"ghost",size:"icon-sm",children:e.jsx(Us,{className:"h-4 w-4"})})}),e.jsxs(_s,{align:"end",children:[e.jsxs(Ce,{onClick:()=>E(o),children:[e.jsx(Ls,{className:"mr-2 h-3.5 w-3.5"})," Edit"]}),e.jsxs(Ce,{onClick:()=>K(o.id),children:[e.jsx(Qs,{className:"mr-2 h-3.5 w-3.5"})," Sync Now"]})]})]}):null}];return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-[16px] font-semibold text-slate-900 flex items-center gap-2",children:[e.jsx(Wl,{className:"h-5 w-5 text-primary"})," Biometric Devices"]}),e.jsx("p",{className:"mt-0.5 text-[13px] text-slate-400",children:"Manage attendance capture devices"})]}),Y&&e.jsxs(y,{size:"sm",onClick:N,children:[e.jsx(ds,{className:"mr-1.5 h-3.5 w-3.5"})," Add Device"]})]}),e.jsx(rs,{columns:M,data:O,isLoading:F,searchPlaceholder:"Search devices...",emptyMessage:"No devices registered",emptyDescription:"Register your first biometric device.",totalCount:(p==null?void 0:p.count)??0,pagination:c,onPaginationChange:r,sorting:d,onSortingChange:h,globalFilter:v,onGlobalFilterChange:A}),e.jsx(He,{open:s,onOpenChange:t,children:e.jsxs(Ge,{size:"md",children:[e.jsxs(Be,{children:[e.jsx(We,{children:a?"Edit Device":"Add Device"}),e.jsx(Ze,{children:a?"Update device details.":"Register a new attendance device."})]}),e.jsxs("form",{onSubmit:C.handleSubmit(n),className:"flex-1 overflow-y-auto px-6 py-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx(P,{children:"Device Name *"}),e.jsx(R,{...C.register("name"),className:"mt-1.5"}),C.formState.errors.name&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:C.formState.errors.name.message})]}),e.jsxs("div",{children:[e.jsx(P,{children:"Device Type *"}),e.jsxs($e,{value:C.watch("device_type"),onValueChange:o=>C.setValue("device_type",o),children:[e.jsx(Le,{className:"mt-1.5",children:e.jsx(qe,{})}),e.jsxs(Re,{children:[e.jsx(Z,{value:"fingerprint",children:"Fingerprint"}),e.jsx(Z,{value:"rfid",children:"RFID"}),e.jsx(Z,{value:"face_recognition",children:"Face Recognition"}),e.jsx(Z,{value:"mobile",children:"Mobile"})]})]})]}),e.jsxs("div",{children:[e.jsx(P,{children:"Serial Number *"}),e.jsx(R,{...C.register("serial_number"),className:"mt-1.5"}),C.formState.errors.serial_number&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:C.formState.errors.serial_number.message})]}),e.jsxs("div",{children:[e.jsx(P,{children:"IP Address"}),e.jsx(R,{...C.register("ip_address"),className:"mt-1.5",placeholder:"e.g. 192.168.1.100"})]}),e.jsxs("div",{children:[e.jsx(P,{children:"Location"}),e.jsx(R,{...C.register("location"),className:"mt-1.5",placeholder:"e.g. Main Entrance"})]})]}),e.jsxs(us,{children:[e.jsx(y,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(y,{onClick:C.handleSubmit(n),disabled:m.isPending||_.isPending,children:a?"Save Changes":"Register Device"})]})]})})]})}function na(s){return s?s.replace(/^0/,""):"—"}function Bn(s){if(s<=0)return"—";const t=Math.floor(s/60),a=s%60;return t>0?`${t}h ${a}m`:`${a}m`}function an(s){switch(s){case"device":return e.jsx(ol,{className:"h-3 w-3"});case"mobile":return e.jsx(En,{className:"h-3 w-3"});case"manual":return e.jsx(Jl,{className:"h-3 w-3"});default:return null}}function nn(s){switch(s){case"device":return"Device";case"mobile":return"Mobile";case"manual":return"Manual";default:return"—"}}function Oi({session:s,index:t}){const a=!!s.deviation;return e.jsxs("div",{className:`flex items-center gap-3 rounded-lg px-3 py-2.5 ${a?"bg-amber-50/80 border border-amber-200":"bg-slate-50/80"}`,children:[e.jsx("span",{className:"text-[11px] font-medium text-slate-400 w-4 shrink-0",children:t+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:`text-[13px] font-medium tabular-nums ${s.check_in?"text-emerald-700":"text-slate-300"}`,children:na(s.check_in)}),s.check_in_source&&e.jsxs("span",{className:"flex items-center gap-0.5 text-[10px] text-slate-400",children:[an(s.check_in_source),nn(s.check_in_source)]})]}),s.check_in_device&&e.jsx("span",{className:"text-[10px] text-slate-400",children:s.check_in_device})]}),e.jsx(ta,{className:"h-3.5 w-3.5 text-slate-300 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:`text-[13px] font-medium tabular-nums ${s.check_out?"text-rose-700":"text-slate-300"}`,children:na(s.check_out)}),s.check_out_source&&e.jsxs("span",{className:"flex items-center gap-0.5 text-[10px] text-slate-400",children:[an(s.check_out_source),nn(s.check_out_source)]})]}),s.check_out_device&&e.jsx("span",{className:"text-[10px] text-slate-400",children:s.check_out_device})]}),e.jsx("span",{className:"text-[12px] font-medium text-slate-600 tabular-nums w-14 text-right shrink-0",children:Bn(s.duration_minutes)}),e.jsxs("div",{className:"w-20 shrink-0 text-right",children:[s.deviation==="missing_checkout"&&e.jsxs(ee,{variant:"warning",className:"text-[9px] gap-0.5",children:[e.jsx(os,{className:"h-2.5 w-2.5"})," No Out"]}),s.deviation==="missing_checkin"&&e.jsxs(ee,{variant:"warning",className:"text-[9px] gap-0.5",children:[e.jsx(os,{className:"h-2.5 w-2.5"})," No In"]})]})]})}function Vi(){return e.jsx("div",{className:"space-y-2",children:Array.from({length:3}).map((s,t)=>e.jsx(Tt,{className:"h-12 w-full rounded-lg"},t))})}function Wn({open:s,onOpenChange:t,employeeId:a,employeeName:l,employeeCode:c,date:r}){const{data:d,isLoading:h}=Pi(s?a:"",s?r:""),v=(d==null?void 0:d.sessions)??[],A=d==null?void 0:d.summary;return e.jsx(ca,{open:s,onOpenChange:t,children:e.jsxs(oa,{className:"sm:max-w-[560px]",children:[e.jsxs(gn,{children:[e.jsxs(fn,{className:"flex items-center gap-2 text-[15px]",children:[e.jsx(ss,{className:"h-4 w-4 text-primary"}),"Punch Log"]}),e.jsxs(vn,{className:"text-[12px]",children:[l," (",c,") — ",r]})]}),e.jsxs("div",{className:"mt-2 space-y-3",children:[A&&!h&&e.jsxs("div",{className:"flex items-center gap-4 rounded-lg bg-slate-50 px-3 py-2 text-[11px] text-slate-500",children:[e.jsxs("span",{children:[e.jsx("span",{className:"font-medium text-slate-700",children:A.total_punches})," punches"]}),e.jsxs("span",{children:[e.jsx("span",{className:"font-medium text-slate-700",children:A.total_sessions})," sessions"]}),e.jsxs("span",{children:["First in: ",e.jsx("span",{className:"font-medium text-emerald-700 tabular-nums",children:na(A.first_in)})]}),e.jsxs("span",{children:["Last out: ",e.jsx("span",{className:"font-medium text-rose-700 tabular-nums",children:na(A.last_out)})]}),e.jsxs("span",{children:["Total: ",e.jsx("span",{className:"font-medium text-slate-700",children:Bn(A.total_working_minutes)})]}),A.deviations>0&&e.jsxs(ee,{variant:"warning",className:"text-[9px] ml-auto",children:[A.deviations," deviation",A.deviations>1?"s":""]})]}),!h&&v.length>0&&e.jsxs("div",{className:"flex items-center gap-3 px-3 text-[10px] font-medium text-slate-400 uppercase tracking-wide",children:[e.jsx("span",{className:"w-4 shrink-0",children:"#"}),e.jsx("span",{className:"flex-1",children:"Check In"}),e.jsx("span",{className:"w-3.5 shrink-0"}),e.jsx("span",{className:"flex-1",children:"Check Out"}),e.jsx("span",{className:"w-14 text-right shrink-0",children:"Duration"}),e.jsx("span",{className:"w-20 text-right shrink-0",children:"Status"})]}),h?e.jsx(Vi,{}):v.length===0?e.jsx("div",{className:"py-8 text-center text-[12px] text-slate-400",children:"No punch records found for this date."}):e.jsx("div",{className:"space-y-1.5 max-h-[320px] overflow-y-auto",children:v.map((u,p)=>e.jsx(Oi,{session:u,index:p},p))})]})]})})}function fa(s){if(s<=0)return"—";const t=Math.floor(s/60),a=s%60;return t>0?`${t}h ${a}m`:`${a}m`}function Qi(s){switch(s){case"P":return e.jsx(ee,{variant:"success",className:"text-[11px]",children:"Present"});case"HD":return e.jsx(ee,{variant:"warning",className:"text-[11px]",children:"Half Day"});case"A":return e.jsx(ee,{variant:"destructive",className:"text-[11px]",children:"Absent"});case"L":return e.jsx(ee,{variant:"secondary",className:"text-[11px]",children:"Leave"});case"H":return e.jsx(ee,{variant:"outline",className:"text-[11px]",children:"Holiday"});case"WO":return e.jsx(ee,{variant:"outline",className:"text-[11px]",children:"Week Off"});case"DV":return e.jsx(ee,{variant:"destructive",className:"text-[11px] bg-rose-600",children:"Deviation"});default:return e.jsx(ee,{variant:"outline",className:"text-[11px]",children:s})}}function va(s){if(!s)return null;const t=new Date(`${s}T00:00:00`);return Number.isNaN(t.getTime())?null:t}const ln=()=>ve(new Date,"yyyy-MM-dd");function jd(){const[s,t]=i.useState(ln),[a,l]=i.useState(""),[c,r]=i.useState(""),[d,h]=i.useState({}),[v,A]=i.useState(null),[u,p]=i.useState(!1),[F,O]=i.useState(""),[m,_]=i.useState(""),[q,k]=i.useState(""),[x,Y]=i.useState(""),H=i.useMemo(()=>({date:s,...a&&{department:a},...c&&{search:c}}),[s,a,c]),{data:C,isLoading:N}=Ci(H),E=Di(),n=Ai(),[K,M]=i.useState(""),{data:o,isLoading:L}=ct({search:K||void 0}),{data:V}=sa({page_size:500,status:"active"}),j=(C==null?void 0:C.results)??[],$=i.useCallback(S=>{const de=va(s)??new Date;de.setDate(de.getDate()+S),t(ve(de,"yyyy-MM-dd")),h({})},[s]),J=i.useCallback(()=>$(-1),[$]),B=i.useCallback(()=>$(1),[$]),ne=i.useCallback((S,de,ze)=>{h(Oe=>{const U=Oe[S],me=j.find(Je=>Je.employee===S);return{...Oe,[S]:{check_in:de==="check_in"?ze:(U==null?void 0:U.check_in)??(me==null?void 0:me.check_in)??"",check_out:de==="check_out"?ze:(U==null?void 0:U.check_out)??(me==null?void 0:me.check_out)??"",dirty:!0}}})},[j]),D=i.useMemo(()=>Object.entries(d).filter(([,S])=>S.dirty).map(([S,de])=>({employee:S,check_in:de.check_in||null,check_out:de.check_out||null})),[d]),fe=i.useCallback(()=>{D.length!==0&&E.mutate({date:s,entries:D},{onSuccess:()=>h({})})},[D,s,E]),Q=i.useCallback(()=>{O(""),_(""),k(""),Y("")},[]),oe=i.useCallback(()=>{!F||!m&&!q||n.mutate({date:s,employee:F,check_in:m||null,check_out:q||null},{onSuccess:()=>{Q(),p(!1)}})},[F,m,q,s,n,Q]),Se=i.useMemo(()=>{const S=(V==null?void 0:V.results)??[];if(!x)return S;const de=x.toLowerCase();return S.filter(ze=>`${ze.first_name} ${ze.last_name}`.toLowerCase().includes(de)||ze.employee_id.toLowerCase().includes(de))},[V,x]),Te=i.useMemo(()=>{const S=j.length,de=j.filter(me=>me.status==="P").length,ze=j.filter(me=>me.status==="HD").length,Oe=j.filter(me=>me.status==="A").length,U=j.filter(me=>me.check_in).length;return{total:S,present:de,halfDay:ze,absent:Oe,hasCheckIn:U}},[j]),I=i.useMemo(()=>{const S=va(s);return S?ve(S,"EEEE, dd MMM yyyy"):""},[s]);return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-[16px] font-semibold text-slate-900 flex items-center gap-2",children:[e.jsx(rt,{className:"h-5 w-5 text-primary"})," Daily Timesheet"]}),e.jsxs("p",{className:"mt-0.5 text-[13px] text-slate-400",children:["Enter employee check-in and check-out times for ",I]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(y,{size:"sm",variant:"outline",onClick:()=>{Q(),p(!0)},children:[e.jsx(ds,{className:"h-4 w-4 mr-1"}),"Add Entry"]}),e.jsxs(y,{size:"sm",onClick:fe,disabled:D.length===0||E.isPending,children:[e.jsx(st,{className:"h-4 w-4 mr-1"}),E.isPending?"Saving...":`Save Changes (${D.length})`]})]})]}),e.jsxs("div",{className:"grid grid-cols-5 gap-3",children:[e.jsx(ye,{className:"bg-white",children:e.jsx(je,{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-slate-100",children:e.jsx(ss,{className:"h-4 w-4 text-slate-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-slate-400",children:"Total Employees"}),e.jsx("p",{className:"text-[15px] font-semibold text-slate-900",children:Te.total})]})]})})}),e.jsx(ye,{className:"bg-white",children:e.jsx(je,{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-emerald-50",children:e.jsx(it,{className:"h-4 w-4 text-emerald-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-slate-400",children:"Present"}),e.jsx("p",{className:"text-[15px] font-semibold text-emerald-600",children:Te.present})]})]})})}),e.jsx(ye,{className:"bg-white",children:e.jsx(je,{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-amber-50",children:e.jsx(Bl,{className:"h-4 w-4 text-amber-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-slate-400",children:"Half Day"}),e.jsx("p",{className:"text-[15px] font-semibold text-amber-600",children:Te.halfDay})]})]})})}),e.jsx(ye,{className:"bg-white",children:e.jsx(je,{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-red-50",children:e.jsx(bt,{className:"h-4 w-4 text-red-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-slate-400",children:"Absent"}),e.jsx("p",{className:"text-[15px] font-semibold text-red-600",children:Te.absent})]})]})})}),e.jsx(ye,{className:"bg-white",children:e.jsx(je,{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-blue-50",children:e.jsx(rt,{className:"h-4 w-4 text-blue-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-slate-400",children:"Checked In"}),e.jsx("p",{className:"text-[15px] font-semibold text-blue-600",children:Te.hasCheckIn})]})]})})})]}),e.jsx(ye,{className:"bg-white",children:e.jsx(je,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(y,{variant:"outline",size:"icon-sm",onClick:J,children:e.jsx(Oa,{className:"h-4 w-4"})}),e.jsx(R,{type:"date",value:s,onChange:S=>{t(S.target.value),h({})},onBlur:S=>{va(S.target.value)||t(ln())},className:"h-9 w-[160px]"}),e.jsx(y,{variant:"outline",size:"icon-sm",onClick:B,children:e.jsx(Vs,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"w-[180px]",children:e.jsx(ge,{value:a||null,onValueChange:S=>l(S),onSearch:M,isLoading:L,options:((o==null?void 0:o.results)??[]).map(S=>({value:S.id,label:S.name,hint:S.code})),placeholder:"All Departments",searchPlaceholder:"Search departments..."})}),e.jsxs("div",{className:"relative flex-1 max-w-[280px]",children:[e.jsx(Wt,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(R,{placeholder:"Search employees...",value:c,onChange:S=>r(S.target.value),className:"h-9 pl-9"})]})]})})}),e.jsx(ye,{className:"bg-white",children:e.jsx(je,{className:"p-0",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(da,{children:[e.jsx(Fa,{children:e.jsxs(Es,{className:"bg-slate-50/60",children:[e.jsx(Me,{className:"w-[50px] text-center",children:"#"}),e.jsx(Me,{className:"min-w-[140px]",children:"Employee"}),e.jsx(Me,{className:"w-[120px]",children:"Department"}),e.jsx(Me,{className:"w-[100px]",children:"Shift"}),e.jsx(Me,{className:"w-[120px] text-center",children:"Check In"}),e.jsx(Me,{className:"w-[120px] text-center",children:"Check Out"}),e.jsx(Me,{className:"w-[90px] text-center",children:"Working"}),e.jsx(Me,{className:"w-[80px] text-center",children:"Late"}),e.jsx(Me,{className:"w-[80px] text-center",children:"OT"}),e.jsx(Me,{className:"w-[80px] text-center",children:"Status"}),e.jsx(Me,{className:"w-[70px] text-center",children:"Source"}),e.jsx(Me,{className:"w-[50px] text-center"})]})}),e.jsx(ma,{children:N?Array.from({length:8}).map((S,de)=>e.jsx(Es,{children:Array.from({length:12}).map((ze,Oe)=>e.jsx(he,{children:e.jsx(Tt,{className:"h-5 w-full"})},Oe))},de)):j.length===0?e.jsx(Es,{children:e.jsx(he,{colSpan:12,className:"text-center py-12 text-slate-400",children:"No employees found for the selected date and filters."})}):j.map((S,de)=>e.jsx(Ii,{row:S,index:de,edited:d[S.employee],onChange:ne,onViewLog:A},S.employee))})]})})})}),e.jsx(He,{open:u,onOpenChange:S=>{S||Q(),p(S)},children:e.jsxs(Ge,{size:"sm",className:"flex flex-col",children:[e.jsxs(Be,{children:[e.jsx(We,{children:"Add Timesheet Entry"}),e.jsxs(Ze,{className:"text-[12px]",children:["Record check-in / check-out for ",I]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-5 space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(P,{className:"text-[12px] font-normal text-slate-500",children:"Employee"}),e.jsxs("div",{className:"relative",children:[e.jsx(Wt,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-slate-400"}),e.jsx(R,{placeholder:"Search by name or ID...",value:x,onChange:S=>Y(S.target.value),className:"h-8 pl-8 text-[12px]"})]}),e.jsx("div",{className:"max-h-[180px] overflow-y-auto rounded-md border",children:Se.length===0?e.jsx("p",{className:"py-6 text-[11px] text-slate-400 text-center",children:"No employees found"}):Se.map(S=>{const de=F===S.id;return e.jsxs("button",{type:"button",onClick:()=>O(S.id),className:`w-full text-left px-3 py-2 text-[12px] flex items-center justify-between border-l-2 transition-colors ${de?"border-l-primary bg-primary/5":"border-l-transparent hover:bg-slate-50"}`,children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("span",{className:`block truncate ${de?"font-medium text-slate-900":"text-slate-700"}`,children:[S.first_name," ",S.last_name]}),e.jsx("span",{className:"text-[10px] text-slate-400",children:S.employee_id})]}),de&&e.jsx(Rt,{className:"h-3.5 w-3.5 text-primary shrink-0"})]},S.id)})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(P,{className:"text-[12px] font-normal text-slate-500",children:"Date"}),e.jsx(R,{type:"date",value:s,disabled:!0,className:"h-8 text-[12px] bg-slate-50"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(P,{className:"text-[12px] font-normal text-slate-500",children:"Check In"}),e.jsx(R,{type:"time",value:m,onChange:S=>_(S.target.value),className:"h-8 text-[12px]"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(P,{className:"text-[12px] font-normal text-slate-500",children:"Check Out"}),e.jsx(R,{type:"time",value:q,onChange:S=>k(S.target.value),className:"h-8 text-[12px]"})]})]})]}),e.jsxs(us,{children:[e.jsx(y,{size:"sm",variant:"outline",onClick:()=>{Q(),p(!1)},children:"Cancel"}),e.jsx(y,{size:"sm",onClick:oe,disabled:!F||!m&&!q||n.isPending,children:n.isPending?"Saving...":"Save Entry"})]})]})}),v&&e.jsx(Wn,{open:!!v,onOpenChange:S=>{S||A(null)},employeeId:v.employee,employeeName:v.employee_name,employeeCode:v.employee_code,date:s})]})}function Ii({row:s,index:t,edited:a,onChange:l,onViewLog:c}){const r=(a==null?void 0:a.check_in)??s.check_in??"",d=(a==null?void 0:a.check_out)??s.check_out??"",h=(a==null?void 0:a.dirty)??!1,v=s.source==="punch";return e.jsxs(Es,{className:h?"bg-blue-50/40":void 0,children:[e.jsx(he,{className:"text-center text-[12px] text-slate-400",children:t+1}),e.jsx(he,{children:e.jsxs("div",{children:[e.jsx("span",{className:"text-[13px] font-medium text-slate-800",children:s.employee_name}),e.jsx("span",{className:"block text-[11px] text-slate-400",children:s.employee_code})]})}),e.jsx(he,{className:"text-[12px] text-slate-600",children:s.department??"—"}),e.jsx(he,{children:s.shift_name?e.jsxs("div",{children:[e.jsx("span",{className:"text-[12px] text-slate-700",children:s.shift_name}),s.shift_start&&s.shift_end&&e.jsxs("span",{className:"block text-[10px] text-slate-400",children:[s.shift_start.slice(0,5),"–",s.shift_end.slice(0,5)]})]}):e.jsx("span",{className:"text-[12px] text-slate-400",children:"—"})}),e.jsx(he,{className:"text-center",children:e.jsx(R,{type:"time",value:r?r.slice(0,5):"",onChange:A=>l(s.employee,"check_in",A.target.value),className:"h-8 w-[100px] text-[12px] mx-auto",disabled:v,title:v?"Device-recorded — cannot edit":"Enter check-in time"})}),e.jsx(he,{className:"text-center",children:e.jsx(R,{type:"time",value:d?d.slice(0,5):"",onChange:A=>l(s.employee,"check_out",A.target.value),className:"h-8 w-[100px] text-[12px] mx-auto",disabled:v,title:v?"Device-recorded — cannot edit":"Enter check-out time"})}),e.jsx(he,{className:"text-center text-[12px] text-slate-700",children:fa(s.working_minutes)}),e.jsx(he,{className:"text-center",children:s.late_by_minutes>0?e.jsx("span",{className:"text-[12px] text-red-600 font-medium",children:fa(s.late_by_minutes)}):e.jsx("span",{className:"text-[12px] text-slate-400",children:"—"})}),e.jsx(he,{className:"text-center",children:s.overtime_minutes>0?e.jsx("span",{className:"text-[12px] text-blue-600 font-medium",children:fa(s.overtime_minutes)}):e.jsx("span",{className:"text-[12px] text-slate-400",children:"—"})}),e.jsx(he,{className:"text-center",children:Qi(s.status)}),e.jsxs(he,{className:"text-center",children:[s.source==="punch"&&e.jsx(ee,{variant:"outline",className:"text-[10px]",children:"Device"}),s.source==="manual"&&e.jsx(ee,{variant:"secondary",className:"text-[10px]",children:"Manual"}),s.source==="integration"&&e.jsx(ee,{variant:"outline",className:"text-[10px]",children:"App"}),!s.source&&e.jsx("span",{className:"text-[10px] text-slate-300",children:"—"})]}),e.jsx(he,{className:"text-center",children:e.jsx(y,{variant:"ghost",size:"icon-sm",onClick:()=>c(s),title:"View punch log",children:e.jsx(ua,{className:"h-3.5 w-3.5 text-slate-400"})})})]})}function Yn(s){const t=[];let a=[],l="",c=!1,r=0;const d=s.charCodeAt(0)===65279?s.slice(1):s,h=()=>{a.push(l),l=""},v=()=>{h(),a.some(A=>A.trim()!=="")&&t.push(a),a=[]};for(;r<d.length;){const A=d[r];if(c){if(A==='"'){if(d[r+1]==='"'){l+='"',r+=2;continue}c=!1,r++;continue}l+=A,r++;continue}if(A==='"'){c=!0,r++;continue}if(A===","){h(),r++;continue}if(A==="\r"){r++;continue}if(A===`
`){v(),r++;continue}l+=A,r++}return(l!==""||a.length>0)&&v(),t.map(A=>A.map(u=>u.trim()))}function Qa(s){return s.trim().toLowerCase()}function Zn(s){const t=new Map;for(const a of s)a.employee_code&&t.set(Qa(a.employee_code),a);return t}const Ki=/^\d{4}-\d{2}-\d{2}$/,Da=/^\d{1,2}:\d{2}(:\d{2})?$/;function rn(s){const t=s.trim();if(!t)return"";if(!Da.test(t))return t;const[a="0",l="00"]=t.split(":");return`${a.padStart(2,"0")}:${l}`}function ht(s,...t){const a=s.map(l=>l.trim().toLowerCase());for(const l of t){const c=a.indexOf(l);if(c!==-1)return c}return-1}function Ui(s,t,a){const l=Yn(s);if(l.length===0)return{rows:[],validRows:[],errorRows:[],fatal:"The file is empty."};const c=l[0],r=ht(c,"employee_id","employee_code"),d=ht(c,"attendance_date","date"),h=ht(c,"status"),v=ht(c,"first_in"),A=ht(c,"last_out"),u=ht(c,"remarks");if(r===-1||d===-1||h===-1)return{rows:[],validRows:[],errorRows:[],fatal:"Missing required columns. Expected employee_id, attendance_date and status."};const p=Zn(t),F=[],O=new Set;for(let m=1;m<l.length;m++){const _=l[m],q=(_[r]??"").trim(),k=(_[d]??"").trim(),x=(_[h]??"").trim().toUpperCase(),Y=v===-1?"":rn(_[v]??""),H=A===-1?"":rn(_[A]??""),C=u===-1?"":(_[u]??"").trim(),N=[],E=q?p.get(Qa(q)):void 0;if(q?E||N.push(`Unknown employee code "${q}".`):N.push("Employee code is required."),k?Ki.test(k)||N.push(`Invalid date "${k}". Use YYYY-MM-DD.`):N.push("Date is required."),x?a.has(x)||N.push(`Unknown status "${x}".`):N.push("Status is required."),Y&&!Da.test(Y)&&N.push(`Invalid in-time "${Y}".`),H&&!Da.test(H)&&N.push(`Invalid out-time "${H}".`),E&&k&&N.length===0){const n=`${k}|${E.employee_id}`;O.has(n)?N.push(`Duplicate row for this employee on ${k}.`):O.add(n)}F.push({line:m+1,employeeCode:q,employeeName:(E==null?void 0:E.employee_name)??"",date:k,status:x,first_in:Y,last_out:H,remarks:C,employeeId:(E==null?void 0:E.employee_id)??null,errors:N})}return Jn(F)}function Hi(s,t,a,l){const c=Yn(s);if(c.length===0)return{rows:[],validRows:[],errorRows:[],fatal:"The file is empty."};if(l.length===0)return{rows:[],validRows:[],errorRows:[],fatal:"The monthly sheet has not loaded yet. Wait for the grid, then re-select the file."};const r=c[0],d=ht(r,"employee_id","employee_code");if(d===-1)return{rows:[],validRows:[],errorRows:[],fatal:"Missing required column: employee_id."};const h=[];for(let p=0;p<r.length;p++){const F=(r[p]??"").trim(),O=Number(F);!F||!Number.isInteger(O)||O<1||O>l.length||h.push({idx:p,date:l[O-1],label:F})}if(h.length===0)return{rows:[],validRows:[],errorRows:[],fatal:"No day columns found. Expected numbered columns 1, 2, 3, … for each day of the month."};const v=Zn(t),A=[],u=new Set;for(let p=1;p<c.length;p++){const F=c[p],O=(F[d]??"").trim(),m=O?v.get(Qa(O)):void 0,_=[];if(O?m||_.push(`Unknown employee code "${O}".`):_.push("Employee code is required."),!m){A.push({line:p+1,employeeCode:O,employeeName:"",date:"",status:"",first_in:"",last_out:"",remarks:"",employeeId:null,errors:_});continue}for(const q of h){const k=(F[q.idx]??"").trim().toUpperCase();if(!k)continue;const x=[];a.has(k)||x.push(`Unknown status "${k}" on day ${q.label}.`);const Y=`${q.date}|${m.employee_id}`;x.length===0&&(u.has(Y)?x.push(`Duplicate entry for this employee on ${q.date}.`):u.add(Y)),A.push({line:p+1,employeeCode:O,employeeName:m.employee_name,date:q.date,status:k,first_in:"",last_out:"",remarks:"",employeeId:m.employee_id,errors:x})}}return Jn(A)}function Jn(s){const t=s.filter(l=>l.errors.length===0),a=s.filter(l=>l.errors.length>0);return{rows:s,validRows:t,errorRows:a,fatal:s.length===0?"No data rows found in the file.":null}}function Gi(s){const t=new Map;for(const a of s){if(!a.employeeId)continue;const l=t.get(a.date)??[];l.push({employee:a.employeeId,status:a.status,first_in:a.first_in||null,last_out:a.last_out||null,remarks:a.remarks}),t.set(a.date,l)}return[...t.entries()].sort(([a],[l])=>a.localeCompare(l)).map(([a,l])=>({date:a,records:l}))}function Xn({open:s,onOpenChange:t,defaultTab:a,employees:l,dates:c,onDownloadTemplate:r}){const d=Va(),{can:h,must:v}=Qe(),A=h("attendance","create"),{data:u}=zt({is_active:!0,page_size:50}),p=i.useMemo(()=>new Set(((u==null?void 0:u.results)??[]).map(j=>j.code.toUpperCase())),[u]),F=i.useRef(null),[O,m]=i.useState(a),[_,q]=i.useState(null),[k,x]=i.useState(null),[Y,H]=i.useState(!1),[C,N]=i.useState(null),E=i.useCallback(()=>{q(null),x(null),N(null),F.current&&(F.current.value="")},[]);function n(j){m(j),E()}function K(j){var B;const $=(B=j.target.files)==null?void 0:B[0];if(!$)return;if(!v("attendance","create")){j.target.value="";return}q($),N(null);const J=new FileReader;J.onload=ne=>{var fe;const D=((fe=ne.target)==null?void 0:fe.result)??"";x(O==="monthly"?Hi(D,l,p,c):Ui(D,l,p))},J.onerror=()=>{x({rows:[],validRows:[],errorRows:[],fatal:"Could not read the file."})},J.readAsText($)}function M(){if(!v("attendance","create")||!k||k.validRows.length===0)return;const j=Gi(k.validRows);if(j.length===0)return;H(!0),N(null);let $=0,J=0;const B=[];let ne=0;function D(){if(ne>=j.length){H(!1),N({created:$,updated:J,errors:B}),B.length===0?(b.success(`Import complete — ${$} created, ${J} updated`),E(),t(!1)):b.error(`Import finished with ${B.length} issue(s) — see details below.`);return}const fe=j[ne];d.mutate({attendance_date:fe.date,records:fe.records},{onSuccess:Q=>{$+=Q.created,J+=Q.updated,B.push(...Q.errors),ne++,D()},onError:()=>{H(!1),N({created:$,updated:J,errors:B})}})}D()}const o=(k==null?void 0:k.validRows.length)??0,L=(k==null?void 0:k.errorRows.length)??0,V=A&&!Y&&!(k!=null&&k.fatal)&&o>0;return e.jsx(He,{open:s,onOpenChange:j=>{j||E(),t(j)},children:e.jsxs(Ge,{size:"lg",children:[e.jsxs(Be,{children:[e.jsx(We,{children:"Import Attendance"}),e.jsx(Ze,{children:"Upload a CSV file to import attendance records in bulk."})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-5",children:[e.jsxs(Ea,{value:O,onValueChange:n,children:[e.jsx(Ma,{className:"w-full",children:a==="monthly"?e.jsxs(e.Fragment,{children:[e.jsx(Fs,{value:"monthly",className:"flex-1",children:"Monthly Import"}),e.jsx(Fs,{value:"daily",className:"flex-1",children:"Daily Import"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Fs,{value:"daily",className:"flex-1",children:"Daily Import"}),e.jsx(Fs,{value:"monthly",className:"flex-1",children:"Monthly Import"})]})}),e.jsxs(Os,{value:"daily",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"text-[13px] text-slate-600",children:[e.jsx("p",{className:"font-medium mb-1",children:"Expected CSV columns:"}),e.jsx("code",{className:"text-[11px] bg-slate-100 px-2 py-1 rounded block",children:"employee_id, attendance_date, status, first_in, last_out, remarks"}),e.jsx("p",{className:"mt-2 text-[12px] text-slate-400",children:"Each row sets one employee's status for one date. Employees are matched on their employee code against the marking sheet currently loaded."})]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>r("daily"),children:[e.jsx(yt,{className:"h-3.5 w-3.5 mr-1.5"})," Download Daily Template"]})]}),e.jsxs(Os,{value:"monthly",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"text-[13px] text-slate-600",children:[e.jsx("p",{className:"font-medium mb-1",children:"Expected CSV columns:"}),e.jsx("code",{className:"text-[11px] bg-slate-100 px-2 py-1 rounded block",children:"employee_id, employee_name, 1, 2, 3, ... 28, 29, 30, 31"}),e.jsx("p",{className:"mt-2 text-[12px] text-slate-400",children:"Day columns map onto the month currently shown in the grid. Blank cells are skipped — only days with a status code are imported."})]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>r("monthly"),children:[e.jsx(yt,{className:"h-3.5 w-3.5 mr-1.5"})," Download Monthly Template"]})]})]}),e.jsx(Ke,{className:"my-4"}),p.size>0&&e.jsxs("p",{className:"text-[12px] text-slate-400 mb-3",children:["Valid status codes:"," ",e.jsx("span",{className:"font-mono text-slate-500",children:[...p].sort().join(", ")})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"border-2 border-dashed border-slate-200 rounded-lg p-6 text-center cursor-pointer hover:border-primary/40 transition-colors",onClick:()=>{var j;return(j=F.current)==null?void 0:j.click()},children:[e.jsx(ia,{className:"h-8 w-8 text-slate-300 mx-auto mb-2"}),e.jsx("p",{className:"text-[13px] text-slate-600",children:_?_.name:"Click to select CSV file"}),_&&e.jsxs(ee,{variant:"secondary",className:"mt-2 text-[11px]",children:[(_.size/1024).toFixed(1)," KB"]}),e.jsx("input",{ref:F,type:"file",accept:".csv",className:"hidden",onChange:K})]}),(k==null?void 0:k.fatal)&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-red-100 bg-red-50/60 px-3 py-2",children:[e.jsx(bt,{className:"h-4 w-4 text-red-500 mt-0.5 shrink-0"}),e.jsx("p",{className:"text-[12px] text-red-600",children:k.fatal})]}),k&&!k.fatal&&!C&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[12px] text-emerald-600 font-medium",children:[e.jsx(it,{className:"h-3.5 w-3.5"})," ",o," ready to import"]}),L>0&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[12px] text-amber-600 font-medium",children:[e.jsx(bt,{className:"h-3.5 w-3.5"})," ",L," will be skipped (not sent)"]})]}),C&&e.jsxs("div",{className:"rounded-lg border border-slate-200 bg-slate-50/60 px-3 py-2.5 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[12px] text-emerald-600 font-medium",children:[e.jsx(it,{className:"h-3.5 w-3.5"}),C.created," created, ",C.updated," updated"]}),C.errors.length>0&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[12px] text-red-600 font-medium",children:[e.jsx(bt,{className:"h-3.5 w-3.5"})," ",C.errors.length," issue(s) after saving"]})]}),C.errors.length>0&&e.jsx("ul",{className:"text-[11px] text-red-600 space-y-0.5",children:C.errors.map((j,$)=>e.jsxs("li",{children:["Employee ",j.employee,": ",j.error]},$))})]}),k&&!k.fatal&&!C&&k.rows.length>0&&e.jsxs("div",{children:[e.jsxs("p",{className:"text-[12px] font-medium text-slate-600 mb-1",children:["Preview (",Math.min(k.rows.length,50)," of ",k.rows.length," rows):"]}),e.jsx("div",{className:"overflow-x-auto border rounded-lg max-h-[280px] overflow-y-auto",children:e.jsx(da,{children:e.jsxs(ma,{children:[e.jsxs(Es,{className:"bg-slate-50 font-medium",children:[e.jsx(he,{className:"text-[11px] py-1 px-2",children:"Line"}),e.jsx(he,{className:"text-[11px] py-1 px-2",children:"Employee"}),e.jsx(he,{className:"text-[11px] py-1 px-2",children:"Date"}),e.jsx(he,{className:"text-[11px] py-1 px-2",children:"Status"}),e.jsx(he,{className:"text-[11px] py-1 px-2",children:"Skip Reason"})]}),k.rows.slice(0,50).map((j,$)=>{const J=j.errors.length>0;return e.jsxs(Es,{className:J?"bg-red-50/50":void 0,children:[e.jsx(he,{className:"text-[11px] py-1 px-2 text-slate-400 font-mono",children:j.line}),e.jsxs(he,{className:"text-[11px] py-1 px-2 whitespace-nowrap",children:[e.jsx("span",{className:"font-mono text-slate-500",children:j.employeeCode||"—"}),j.employeeName&&e.jsx("span",{className:"ml-1.5 text-slate-700",children:j.employeeName})]}),e.jsx(he,{className:"text-[11px] py-1 px-2 whitespace-nowrap text-slate-600",children:j.date||"—"}),e.jsx(he,{className:"text-[11px] py-1 px-2 font-medium text-slate-700",children:j.status||"—"}),e.jsx(he,{className:"text-[11px] py-1 px-2 text-red-600",children:j.errors.join(" ")||""})]},$)})]})})})]})]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 px-6 py-4 border-t",children:[e.jsx(y,{variant:"outline",size:"sm",onClick:()=>t(!1),children:"Cancel"}),A&&e.jsxs(y,{size:"sm",disabled:!V,onClick:M,children:[e.jsx(Ml,{className:"h-3.5 w-3.5 mr-1.5"}),Y?"Importing...":o>0?`Import ${o} record${o===1?"":"s"}`:"Import"]})]})]})})}function gd(){const[s,t]=i.useState(ve(new Date,"yyyy-MM-dd")),[a,l]=i.useState(""),[c,r]=i.useState(""),[d,h]=i.useState(!1),[v,A]=i.useState(!1),[u,p]=i.useState(""),F=i.useMemo(()=>({date:s,...a&&{department:a}}),[s,a]),{data:O,isLoading:m}=_r(F),_=Va(),q=Un(),k=Qn(),x=In(),{can:Y,must:H}=Qe(),C=Y("attendance","create"),[N,E]=i.useState(""),{data:n,isLoading:K}=ct({page_size:100,search:N||void 0}),M=(n==null?void 0:n.results)??[],[o,L]=i.useState(""),{data:V,isLoading:j}=Hs({page_size:100,search:o||void 0}),$=(V==null?void 0:V.results)??[],{data:J}=zt({is_active:!0,page_size:50}),B=i.useMemo(()=>((J==null?void 0:J.results)??[]).filter(G=>G.code).map(G=>({value:G.code,label:G.name,color:G.color})),[J]),ne=i.useMemo(()=>{const G={};for(const xe of(J==null?void 0:J.results)??[])G[xe.code]=xe.color;return G},[J]),[D,fe]=i.useState({}),Q=i.useRef(""),oe=`${s}-${a}`;oe!==Q.current&&(Q.current=oe,Object.keys(D).length>0&&fe({}));const Se=(O==null?void 0:O.employees)??[],Te=(O==null?void 0:O.summary)??{total:0,marked:0,unmarked:0},I=i.useMemo(()=>{if(!c)return Se;const G=c.toLowerCase();return Se.filter(xe=>xe.employee_name.toLowerCase().includes(G)||xe.employee_code.toLowerCase().includes(G)||(xe.department_name??"").toLowerCase().includes(G))},[Se,c]);function S(G){const xe=D[G.employee_id];return xe||{status:G.existing_status??"P",first_in:G.existing_first_in??"",last_out:G.existing_last_out??"",remarks:G.existing_remarks??"",dirty:!1}}const de=i.useCallback((G,xe,ue,Ae)=>{fe(Ie=>{const pe=Ie[G]??{status:xe.existing_status??"P",first_in:xe.existing_first_in??"",last_out:xe.existing_last_out??"",remarks:xe.existing_remarks??"",dirty:!1};return{...Ie,[G]:{...pe,[ue]:Ae,dirty:!0}}})},[]);function ze(G){if(!H("attendance","create"))return;const xe={};for(const ue of Se){const Ae=D[ue.employee_id]??{status:ue.existing_status??"P",first_in:ue.existing_first_in??"",last_out:ue.existing_last_out??"",remarks:ue.existing_remarks??"",dirty:!1};xe[ue.employee_id]={...Ae,status:G,dirty:!0}}fe(xe)}const Oe=i.useMemo(()=>{const G={};for(const xe of Se){const ue=S(xe);G[ue.status]=(G[ue.status]??0)+1}return G},[Se,D]),U=i.useMemo(()=>Object.values(D).filter(G=>G.dirty).length,[D]);function me(){if(!H("attendance","create"))return;const G=[];for(const xe of Se){const ue=D[xe.employee_id];ue!=null&&ue.dirty&&G.push({employee:xe.employee_id,status:ue.status,first_in:ue.first_in||null,last_out:ue.last_out||null,remarks:ue.remarks})}G.length!==0&&_.mutate({attendance_date:s,records:G},{onSuccess:()=>fe({})})}function Je(){H("attendance","create")&&x.mutate({date:s,...a&&{department:a}})}function ms(){H("attendance","create")&&k.mutate({start_date:s,end_date:s,company:u},{onSuccess:()=>A(!1)})}const qs=i.useMemo(()=>{const[G=0,xe=1]=s.split("-").map(Number),ue=new Date(G,xe,0).getDate();return Array.from({length:ue},(Ae,Ie)=>`${G}-${String(xe).padStart(2,"0")}-${String(Ie+1).padStart(2,"0")}`)},[s]);function ts(G){const xe={template_format:G};G==="monthly"&&(xe.month=s.slice(0,7)),q.mutate(xe,{onSuccess:ue=>{const Ae=URL.createObjectURL(ue),Ie=document.createElement("a");Ie.href=Ae,Ie.download=G==="monthly"?`attendance_monthly_${s.slice(0,7)}.csv`:"attendance_daily_template.csv",Ie.click(),URL.revokeObjectURL(Ae)}})}return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-5",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-[16px] font-semibold text-slate-900 flex items-center gap-2",children:[e.jsx($l,{className:"h-5 w-5 text-primary"})," Daily Attendance"]}),e.jsxs("p",{className:"mt-0.5 text-[13px] text-slate-400",children:["Mark and manage employee attendance for ",s?ve(new Date(s+"T00:00:00"),"dd MMM yyyy"):"today"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[C&&e.jsxs(e.Fragment,{children:[e.jsxs(y,{variant:"outline",size:"sm",disabled:x.isPending,onClick:Je,children:[e.jsx(Qs,{className:`h-3.5 w-3.5 mr-1.5 ${x.isPending?"animate-spin":""}`}),x.isPending?"Processing...":"Process Timesheet"]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>A(!0),children:[e.jsx(Xt,{className:"h-3.5 w-3.5 mr-1.5"})," Auto-Generate"]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>h(!0),children:[e.jsx(ia,{className:"h-3.5 w-3.5 mr-1.5"})," Import"]})]}),e.jsxs(fs,{children:[e.jsx(vs,{asChild:!0,children:e.jsxs(y,{variant:"outline",size:"sm",children:[e.jsx(yt,{className:"h-3.5 w-3.5 mr-1.5"})," Export",e.jsx(Yt,{className:"h-3 w-3 ml-1"})]})}),e.jsxs(_s,{align:"end",children:[e.jsxs(Ce,{onClick:()=>ts("daily"),children:[e.jsx(aa,{className:"h-3.5 w-3.5 mr-2"})," Daily CSV Template"]}),e.jsxs(Ce,{onClick:()=>ts("monthly"),children:[e.jsx(aa,{className:"h-3.5 w-3.5 mr-2"})," Monthly CSV Template"]})]})]}),C&&e.jsxs(y,{size:"sm",disabled:U===0||_.isPending,onClick:me,children:[e.jsx(st,{className:"h-3.5 w-3.5 mr-1.5"}),_.isPending?"Saving...":`Save Changes${U>0?` (${U})`:""}`]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx(R,{type:"date",value:s,onChange:G=>t(G.target.value),className:"w-[160px] h-9"}),e.jsx("div",{className:"w-[180px]",children:e.jsx(ge,{value:a||null,onValueChange:G=>l(G),onSearch:E,isLoading:K,options:M.map(G=>({value:G.id,label:G.name,hint:G.code})),placeholder:"All departments",searchPlaceholder:"Search departments..."})}),e.jsx(R,{placeholder:"Search employee...",value:c,onChange:G=>r(G.target.value),className:"w-[220px] h-9"}),C&&e.jsx("div",{className:"ml-auto",children:e.jsxs(fs,{children:[e.jsx(vs,{asChild:!0,children:e.jsxs(y,{variant:"outline",size:"sm",children:[e.jsx(Ms,{className:"h-3.5 w-3.5 mr-1.5"})," Mark All",e.jsx(Yt,{className:"h-3 w-3 ml-1"})]})}),e.jsx(_s,{align:"end",children:B.map(G=>e.jsx(Ce,{onClick:()=>ze(G.value),children:G.label},G.value))})]})})]}),e.jsxs("div",{className:"grid grid-cols-4 gap-3 mb-4",children:[e.jsx(It,{icon:e.jsx(Ms,{className:"h-4 w-4 text-blue-500"}),label:"Total",value:Te.total}),e.jsx(It,{icon:e.jsx($t,{className:"h-4 w-4 text-emerald-500"}),label:"Present",value:Oe.P??0}),e.jsx(It,{icon:e.jsx(Nt,{className:"h-4 w-4 text-red-500"}),label:"Absent",value:Oe.A??0}),e.jsx(It,{icon:e.jsx(ss,{className:"h-4 w-4 text-amber-500"}),label:"Half Day",value:Oe.HD??0})]}),e.jsx(ye,{children:e.jsxs(je,{className:"p-0",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(da,{children:[e.jsx(Fa,{children:e.jsxs(Es,{className:"bg-slate-50/80",children:[e.jsx(Me,{className:"w-[60px] text-[11px]",children:"#"}),e.jsx(Me,{className:"w-[80px] text-[11px]",children:"Emp ID"}),e.jsx(Me,{className:"min-w-[160px] text-[11px]",children:"Employee"}),e.jsx(Me,{className:"w-[120px] text-[11px]",children:"Department"}),e.jsx(Me,{className:"w-[140px] text-[11px]",children:"Status"}),e.jsx(Me,{className:"w-[110px] text-[11px]",children:"In Time"}),e.jsx(Me,{className:"w-[110px] text-[11px]",children:"Out Time"}),e.jsx(Me,{className:"min-w-[140px] text-[11px]",children:"Remarks"})]})}),e.jsx(ma,{children:m?Array.from({length:8}).map((G,xe)=>e.jsx(Es,{children:Array.from({length:8}).map((ue,Ae)=>e.jsx(he,{children:e.jsx(Tt,{className:"h-5 w-full"})},Ae))},xe)):I.length===0?e.jsx(Es,{children:e.jsx(he,{colSpan:8,className:"text-center py-12 text-slate-400",children:Se.length===0?"No active employees found. Select a date to load the marking sheet.":"No employees match your search."})}):I.map((G,xe)=>{var Ie;const ue=S(G),Ae=(Ie=D[G.employee_id])==null?void 0:Ie.dirty;return e.jsxs(Es,{className:Ae?"bg-blue-50/40":void 0,children:[e.jsx(he,{className:"text-[12px] text-slate-400 font-mono",children:xe+1}),e.jsx(he,{className:"text-[12px] text-slate-500 font-mono",children:G.employee_code}),e.jsxs(he,{children:[e.jsx("span",{className:"text-[13px] font-medium text-slate-800",children:G.employee_name}),G.is_on_leave&&e.jsx(ee,{variant:"secondary",className:"ml-1.5 text-[9px] px-1.5 py-0",children:G.leave_type_name??"On Leave"})]}),e.jsx(he,{className:"text-[12px] text-slate-500",children:G.department_name??"—"}),e.jsx(he,{children:e.jsxs($e,{value:ue.status,onValueChange:pe=>de(G.employee_id,G,"status",pe),children:[e.jsx(Le,{className:"h-7 text-[12px] border",style:{borderColor:ne[ue.status]?`${ne[ue.status]}50`:void 0,color:ne[ue.status]??void 0},children:e.jsx(qe,{})}),e.jsx(Re,{children:B.map(pe=>e.jsx(Z,{value:pe.value,className:"text-[12px]",children:pe.label},pe.value))})]})}),e.jsx(he,{children:e.jsx(R,{type:"time",value:ue.first_in,onChange:pe=>de(G.employee_id,G,"first_in",pe.target.value),className:"h-7 text-[12px] w-[95px]"})}),e.jsx(he,{children:e.jsx(R,{type:"time",value:ue.last_out,onChange:pe=>de(G.employee_id,G,"last_out",pe.target.value),className:"h-7 text-[12px] w-[95px]"})}),e.jsx(he,{children:e.jsx(R,{value:ue.remarks,onChange:pe=>de(G.employee_id,G,"remarks",pe.target.value),placeholder:"—",className:"h-7 text-[12px]"})})]},G.employee_id)})})]})}),I.length>0&&e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-t border-slate-100 bg-slate-50/50",children:[e.jsxs("p",{className:"text-[12px] text-slate-500",children:[Te.total," employees · ",Te.marked," marked · ",Te.unmarked," unmarked",U>0&&e.jsxs("span",{className:"text-blue-600 font-medium ml-2",children:["· ",U," unsaved changes"]})]}),C&&e.jsxs(y,{size:"sm",disabled:U===0||_.isPending,onClick:me,children:[e.jsx(st,{className:"h-3.5 w-3.5 mr-1.5"}),_.isPending?"Saving...":"Save All Changes"]})]})]})}),e.jsx(Xn,{open:d,onOpenChange:h,defaultTab:"daily",employees:Se,dates:qs,onDownloadTemplate:ts}),e.jsx(He,{open:v,onOpenChange:A,children:e.jsxs(Ge,{size:"md",children:[e.jsxs(Be,{children:[e.jsx(We,{children:"Auto-Generate Attendance"}),e.jsx(Ze,{children:"Pre-fill weekends and holidays based on shift schedules and work calendars."})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[13px] font-medium text-slate-700",children:"Company *"}),e.jsx("div",{className:"mt-1.5",children:e.jsx(ge,{value:u||null,onValueChange:G=>p(G),onSearch:L,isLoading:j,options:$.map(G=>({value:G.id,label:G.name,hint:G.code})),placeholder:"Select company",searchPlaceholder:"Search companies..."})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[13px] font-medium text-slate-700",children:"Date"}),e.jsx(R,{type:"date",value:s,disabled:!0,className:"mt-1.5"}),e.jsx("p",{className:"mt-1 text-[11px] text-slate-400",children:"Uses the currently selected date as both start and end date."})]}),e.jsx(Ke,{}),e.jsx("p",{className:"text-[12px] text-slate-500",children:"This will create attendance records for employees who are on week-off or holiday on this date. Existing records will not be overwritten."})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 px-6 py-4 border-t",children:[e.jsx(y,{variant:"outline",size:"sm",onClick:()=>A(!1),children:"Cancel"}),C&&e.jsxs(y,{size:"sm",disabled:!u||k.isPending,onClick:ms,children:[e.jsx(Xt,{className:"h-3.5 w-3.5 mr-1.5"}),k.isPending?"Generating...":"Generate"]})]})]})})]})}function It({icon:s,label:t,value:a}){return e.jsx(ye,{className:"border border-slate-100",children:e.jsxs(je,{className:"flex items-center gap-3 py-3 px-4",children:[e.jsx("div",{className:"h-8 w-8 rounded-lg bg-slate-50 flex items-center justify-center",children:s}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[20px] font-semibold text-slate-800 leading-none",children:a}),e.jsx("p",{className:"text-[11px] text-slate-400 mt-0.5",children:t})]})]})})}const _a=[{text:"Processing attendance records...",emoji:"📅"},{text:"Computing attendance from timesheets...",emoji:"🔢"},{text:"Crunching numbers day by day...",emoji:"📊"},{text:"Your HR efficiency is off the charts!",emoji:"🚀"},{text:"Making sense of all those punches...",emoji:"👊"},{text:"Almost there, keep the faith!",emoji:"✨"},{text:"Syncing records across all days...",emoji:"🔄"},{text:"Building the perfect attendance record...",emoji:"🏗️"},{text:"Attendance hero mode: activated!",emoji:"🦸"},{text:"Every day counts, literally!",emoji:"🎯"}],cn=[{text:"Processed successfully!",subtitle:"All timesheets are up to date."},{text:"Mission accomplished!",subtitle:"Every record has been computed."},{text:"Perfectly synced!",subtitle:"The attendance data is now accurate."},{text:"Nailed it!",subtitle:"All attendance records processed."}],Bi=["January","February","March","April","May","June","July","August","September","October","November","December"];function Wi(s,t){return new Date(s,t,0).getDate()}function ba(s){return String(s).padStart(2,"0")}function Yi({open:s,onOpenChange:t,month:a,year:l,monthNum:c}){const[r,d]=i.useState("filters"),[h,v]=i.useState(0),A=Wi(l,c),u=`${l}-${ba(c)}-01`,p=`${l}-${ba(c)}-${ba(A)}`,[F,O]=i.useState(u),[m,_]=i.useState(p);i.useEffect(()=>{O(u),_(p)},[u,p]);const[q,k]=i.useState(""),[x,Y]=i.useState(""),[H,C]=i.useState(""),[N,E]=i.useState(""),[n,K]=i.useState(""),[M,o]=i.useState(!0),[L,V]=i.useState(new Set),[j,$]=i.useState(""),[J,B]=i.useState(null),[ne,D]=i.useState(""),[fe,Q]=i.useState(""),[oe,Se]=i.useState(""),[Te,I]=i.useState(""),[S,de]=i.useState(""),[ze,Oe]=i.useState(""),{data:U,isLoading:me}=Hs({search:fe||void 0}),Je=(U==null?void 0:U.results)??[],{data:ms,isLoading:qs}=ct({search:oe||void 0,...q?{company:q}:{}}),ts=(ms==null?void 0:ms.results)??[],{data:G,isLoading:xe}=ft({search:Te||void 0,...q?{company:q}:{}}),ue=(G==null?void 0:G.results)??[],{data:Ae,isLoading:Ie}=Ta({search:S||void 0}),pe=(Ae==null?void 0:Ae.results)??[],{data:Fe,isLoading:Ye}=za({search:ze||void 0}),js=(Fe==null?void 0:Fe.results)??[],gs=i.useMemo(()=>{const W={page_size:200,status:"active"};return q&&(W.company=q),x&&(W.department=x),H&&(W.branch=H),N&&(W.grade=N),n&&(W.category=n),W},[q,x,H,N,n]),{data:re,isLoading:as}=sa(gs),ns=(re==null?void 0:re.results)??[],ls=i.useMemo(()=>{if(!j)return ns;const W=j.toLowerCase();return ns.filter(Ee=>Ee.first_name.toLowerCase().includes(W)||Ee.last_name.toLowerCase().includes(W)||Ee.email.toLowerCase().includes(W))},[ns,j]),is=Kn();i.useEffect(()=>{if(r!=="processing")return;const W=setInterval(()=>{v(Ee=>(Ee+1)%_a.length)},2500);return()=>clearInterval(W)},[r]),i.useEffect(()=>{if(r!=="success")return;const W=setTimeout(()=>{t(!1),cs()},4e3);return()=>clearTimeout(W)},[r,t]);function cs(){d("filters"),v(0),B(null),D("")}function Gs(W){r!=="processing"&&(W||cs(),t(W))}const Ss=F===u&&m===p,Ue=i.useMemo(()=>{if(!F||!m)return 0;const W=new Date(F),Ee=new Date(m);return Math.max(0,Math.floor((Ee.getTime()-W.getTime())/864e5)+1)},[F,m]);function zs(){d("processing"),v(0);const W={month:a,...!Ss&&F&&{from_date:F},...!Ss&&m&&{to_date:m},...q&&{company:q},...x&&{department:x},...H&&{branch:H},...N&&{grade:N},...n&&{category:n},...M?{process_all:!0}:{employee_ids:Array.from(L)}};is.mutate(W,{onSuccess:Ee=>{B(Ee),d("success")},onError:Ee=>{D(Ee instanceof Error?Ee.message:"Processing failed"),d("error")}})}function As(W){V(Ee=>{const Ys=new Set(Ee);return Ys.has(W)?Ys.delete(W):Ys.add(W),Ys})}function Bs(){V(W=>{const Ee=new Set(W);return ls.forEach(Ys=>Ee.add(Ys.id)),Ee})}function w(){V(new Set)}const ie=(M||L.size>0)&&F&&m&&F<=m,le=`${Bi[c-1]} ${l}`,Ve=_a[h%_a.length],Rs=cn[Math.floor(Math.random()*cn.length)],Ws=Ss?le:`${F} to ${m}`;return e.jsx(ca,{open:s,onOpenChange:Gs,children:e.jsxs(oa,{className:`sm:max-w-[620px] ${r!=="filters"?"p-0 overflow-hidden border-0 shadow-2xl [&>button]:hidden":""}`,onPointerDownOutside:W=>r==="processing"&&W.preventDefault(),onEscapeKeyDown:W=>r==="processing"&&W.preventDefault(),children:[r==="filters"&&e.jsxs(e.Fragment,{children:[e.jsxs(gn,{children:[e.jsxs(fn,{className:"flex items-center gap-2 text-[15px]",children:[e.jsx(nt,{className:"h-4.5 w-4.5 text-primary"}),"Process Timesheet"]}),e.jsxs(vn,{className:"text-[12px]",children:["Recompute attendance from punch records for ",e.jsx("span",{className:"font-medium text-slate-700",children:le})]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-slate-400 mb-2",children:"Date Range"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(P,{className:"text-[11px] text-slate-500",children:"From Date"}),e.jsx("input",{type:"date",value:F,min:Ba,max:m||Ga,onChange:W=>O(W.target.value),className:"mt-1 flex h-8 w-full rounded-md border border-input bg-white px-3 py-1 text-[12px] text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500/30 focus-visible:border-blue-400 transition-colors duration-150"})]}),e.jsxs("div",{children:[e.jsx(P,{className:"text-[11px] text-slate-500",children:"To Date"}),e.jsx("input",{type:"date",value:m,min:F||Ba,max:Ga,onChange:W=>_(W.target.value),className:"mt-1 flex h-8 w-full rounded-md border border-input bg-white px-3 py-1 text-[12px] text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500/30 focus-visible:border-blue-400 transition-colors duration-150"})]})]}),e.jsx("p",{className:"mt-1.5 text-[11px] text-slate-400",children:Ss?`Full month — ${A} days`:`${Ue} day${Ue!==1?"s":""} selected`})]}),e.jsx(Ke,{}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-slate-400 mb-2",children:"Filters"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(P,{className:"text-[11px] text-slate-500",children:"Company"}),e.jsx("div",{className:"mt-1",children:e.jsx(ge,{value:q||null,onValueChange:W=>{k(W),Y(""),C("")},onSearch:Q,isLoading:me,options:Je.map(W=>({value:W.id,label:W.name,hint:W.code})),placeholder:"All companies",searchPlaceholder:"Search companies..."})})]}),e.jsxs("div",{children:[e.jsx(P,{className:"text-[11px] text-slate-500",children:"Department"}),e.jsx("div",{className:"mt-1",children:e.jsx(ge,{value:x||null,onValueChange:W=>Y(W),onSearch:Se,isLoading:qs,disabled:!q,options:ts.map(W=>({value:W.id,label:W.name,hint:W.code})),placeholder:q?"All departments":"Select a company first",searchPlaceholder:"Search departments..."})})]}),e.jsxs("div",{children:[e.jsx(P,{className:"text-[11px] text-slate-500",children:"Branch"}),e.jsx("div",{className:"mt-1",children:e.jsx(ge,{value:H||null,onValueChange:W=>C(W),onSearch:I,isLoading:xe,disabled:!q,options:ue.map(W=>({value:W.id,label:W.name,hint:W.code})),placeholder:q?"All branches":"Select a company first",searchPlaceholder:"Search branches..."})})]}),e.jsxs("div",{children:[e.jsx(P,{className:"text-[11px] text-slate-500",children:"Grade"}),e.jsx("div",{className:"mt-1",children:e.jsx(ge,{value:N||null,onValueChange:W=>E(W),onSearch:de,isLoading:Ie,options:pe.map(W=>({value:W.id,label:W.name,hint:W.code})),placeholder:"All grades",searchPlaceholder:"Search grades..."})})]}),e.jsxs("div",{children:[e.jsx(P,{className:"text-[11px] text-slate-500",children:"Category"}),e.jsx("div",{className:"mt-1",children:e.jsx(ge,{value:n||null,onValueChange:W=>K(W),onSearch:Oe,isLoading:Ye,options:js.map(W=>({value:W.id,label:W.name,hint:W.code})),placeholder:"All categories",searchPlaceholder:"Search categories..."})})]})]})]}),e.jsx(Ke,{}),e.jsxs("label",{className:"flex items-center gap-2.5 cursor-pointer",children:[e.jsx(Zt,{checked:M,onCheckedChange:W=>{o(!!W),W&&w()}}),e.jsxs("div",{children:[e.jsx("span",{className:"text-[13px] font-medium text-slate-800",children:"Process for all employees"}),e.jsx("p",{className:"text-[11px] text-slate-400",children:ns.length>0?`${ns.length} active employees match current filters`:"Loading..."})]})]}),!M&&e.jsxs("div",{className:"rounded-lg border border-slate-200 bg-slate-50/50",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-slate-200",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Wt,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-slate-400"}),e.jsx(R,{className:"h-7 pl-7 text-[12px] bg-white",placeholder:"Search employees...",value:j,onChange:W=>$(W.target.value)})]}),e.jsx(y,{variant:"ghost",size:"sm",className:"h-7 text-[11px]",onClick:Bs,children:"Select All"}),e.jsx(y,{variant:"ghost",size:"sm",className:"h-7 text-[11px]",onClick:w,children:"Clear"}),L.size>0&&e.jsxs(ee,{variant:"secondary",className:"text-[10px]",children:[L.size," selected"]})]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:as?e.jsxs("div",{className:"flex items-center justify-center py-6 text-[12px] text-slate-400",children:[e.jsx(Ks,{className:"h-4 w-4 mr-2 animate-spin"})," Loading employees..."]}):ls.length===0?e.jsx("div",{className:"py-6 text-center text-[12px] text-slate-400",children:"No employees found"}):ls.map(W=>e.jsxs("label",{className:"flex items-center gap-2.5 px-3 py-1.5 hover:bg-white cursor-pointer transition-colors",children:[e.jsx(Zt,{checked:L.has(W.id),onCheckedChange:()=>As(W.id)}),e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[e.jsxs("div",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-primary/10 text-primary text-[9px] font-semibold",children:[W.first_name[0],W.last_name[0]]}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("span",{className:"text-[12px] font-medium text-slate-800 truncate block",children:[W.first_name," ",W.last_name]}),e.jsx("span",{className:"text-[10px] text-slate-400",children:W.employee_id})]})]})]},W.id))})]})]}),e.jsxs(dl,{children:[e.jsx(y,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(y,{onClick:zs,disabled:!ie||is.isPending,children:[e.jsx(Ms,{className:"h-3.5 w-3.5 mr-1.5"}),"Process ",Ss?"Month":`${Ue} Day${Ue!==1?"s":""}`]})]})]}),r==="processing"&&e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"h-2 bg-gradient-to-r from-blue-500 via-primary to-violet-500 animate-gradient-x"}),e.jsxs("div",{className:"px-8 py-10 text-center",children:[e.jsxs("div",{className:"relative mx-auto mb-6 h-20 w-20",children:[e.jsxs("svg",{className:"animate-spin-slow h-20 w-20",viewBox:"0 0 80 80",children:[e.jsx("circle",{cx:"40",cy:"40",r:"34",fill:"none",stroke:"#e2e8f0",strokeWidth:"6"}),e.jsx("circle",{cx:"40",cy:"40",r:"34",fill:"none",stroke:"url(#month-spinner-gradient)",strokeWidth:"6",strokeLinecap:"round",strokeDasharray:"107 214",className:"animate-spin"}),e.jsx("defs",{children:e.jsxs("linearGradient",{id:"month-spinner-gradient",x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[e.jsx("stop",{offset:"0%",stopColor:"#5eead4"}),e.jsx("stop",{offset:"50%",stopColor:"#0d9488"}),e.jsx("stop",{offset:"100%",stopColor:"#0f766e"})]})})]}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx(nt,{className:"h-6 w-6 text-primary"})})]}),e.jsxs("h3",{className:"text-[15px] font-semibold text-slate-800 mb-1",children:["Processing ",Ws]}),e.jsxs("p",{className:"text-[13px] text-slate-500 mb-4",children:["Computing attendance for ",Ue," day",Ue!==1?"s":"","..."]}),e.jsx("div",{className:"mb-5",children:e.jsx($a,{className:"h-2 bg-slate-100"})}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-[13px] text-slate-600 animate-fade-in",children:[e.jsx("span",{className:"text-[18px]",children:Ve.emoji}),e.jsx("span",{className:"font-medium",children:Ve.text})]},h)]})]}),r==="success"&&J&&e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"h-2 bg-gradient-to-r from-emerald-400 via-green-500 to-teal-400"}),e.jsxs("div",{className:"px-8 py-10 text-center",children:[e.jsxs("div",{className:"relative mx-auto mb-5 h-20 w-20",children:[e.jsx("div",{className:"absolute inset-0 rounded-full bg-emerald-100 animate-ping-once"}),e.jsx("div",{className:"relative h-20 w-20 rounded-full bg-gradient-to-br from-emerald-400 to-green-500 flex items-center justify-center animate-scale-in shadow-lg shadow-emerald-200",children:e.jsx(it,{className:"h-10 w-10 text-white",strokeWidth:2.5})}),e.jsx(et,{className:"absolute -top-1 -right-1 h-5 w-5 text-amber-400 animate-sparkle-1"}),e.jsx(et,{className:"absolute -bottom-1 -left-2 h-4 w-4 text-violet-400 animate-sparkle-2"}),e.jsx(et,{className:"absolute top-0 -left-3 h-3 w-3 text-blue-400 animate-sparkle-3"})]}),e.jsx("h3",{className:"text-[16px] font-bold text-slate-800 mb-1 animate-fade-in-up",children:Rs.text}),e.jsx("p",{className:"text-[13px] text-slate-500 mb-4 animate-fade-in-up-delay",children:Rs.subtitle}),e.jsxs("div",{className:"inline-flex items-center gap-3 bg-slate-50 rounded-xl px-5 py-3 animate-fade-in-up-delay-2",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-[18px] font-bold text-primary",children:J.days_processed??J.days_queued??0}),e.jsx("p",{className:"text-[10px] text-slate-400 uppercase tracking-wider",children:"Days"})]}),e.jsx("div",{className:"w-px h-8 bg-slate-200"}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-[18px] font-bold text-emerald-600",children:J.employee_count}),e.jsx("p",{className:"text-[10px] text-slate-400 uppercase tracking-wider",children:"Employees"})]}),J.total_records!=null&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-px h-8 bg-slate-200"}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-[18px] font-bold text-slate-700",children:J.total_records}),e.jsx("p",{className:"text-[10px] text-slate-400 uppercase tracking-wider",children:"Records"})]})]})]}),J.mode==="async"&&e.jsx("p",{className:"mt-3 text-[11px] text-amber-600 font-medium",children:"Processing queued in background — results will update automatically."}),e.jsx("p",{className:"mt-4 text-[11px] text-slate-400 animate-fade-in-up-delay-2",children:"Closing automatically..."})]})]}),r==="error"&&e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"h-2 bg-gradient-to-r from-red-400 via-rose-500 to-red-400"}),e.jsxs("div",{className:"px-8 py-10 text-center",children:[e.jsx("div",{className:"mx-auto mb-5 h-16 w-16 rounded-full bg-red-100 flex items-center justify-center",children:e.jsx(bt,{className:"h-8 w-8 text-red-500"})}),e.jsx("h3",{className:"text-[15px] font-semibold text-slate-800 mb-2",children:"Processing Failed"}),e.jsx("p",{className:"text-[13px] text-slate-500 mb-5",children:ne||"An error occurred while processing."}),e.jsxs("div",{className:"flex justify-center gap-2",children:[e.jsx(y,{variant:"outline",size:"sm",onClick:()=>{cs()},children:"Try Again"}),e.jsx(y,{variant:"outline",size:"sm",onClick:()=>t(!1),children:"Close"})]})]})]})]})})}const Na=[{text:"Crunching attendance numbers...",emoji:"🔢"},{text:"Making sure everyone is accounted for...",emoji:"📋"},{text:"Your HR game is on point today!",emoji:"💪"},{text:"Syncing records across the cosmos...",emoji:"🚀"},{text:"Almost there, attendance hero!",emoji:"🦸"},{text:"Dotting the i's and crossing the t's...",emoji:"✍️"},{text:"Building the perfect attendance sheet...",emoji:"🏗️"},{text:"Every record counts, literally!",emoji:"🎯"},{text:"Turning chaos into order...",emoji:"✨"},{text:"You're doing great, keep going!",emoji:"🌟"}],on=[{text:"All attendance records saved!",subtitle:"You're an attendance wizard!"},{text:"Mission accomplished!",subtitle:"Every record is safe and sound."},{text:"Perfectly synced!",subtitle:"Your team's attendance is up to date."},{text:"Nailed it!",subtitle:"All changes saved successfully."}];function Zi({progress:s,onClose:t}){const[a,l]=i.useState(0);if(i.useEffect(()=>{if(!s||s.phase!=="saving")return;const h=setInterval(()=>{l(v=>(v+1)%Na.length)},2500);return()=>clearInterval(h)},[s==null?void 0:s.phase]),i.useEffect(()=>{if((s==null?void 0:s.phase)==="success"){const h=setTimeout(t,3e3);return()=>clearTimeout(h)}},[s==null?void 0:s.phase,t]),!s)return null;const c=s.total>0?Math.round(s.current/s.total*100):0,r=Na[a%Na.length],d=on[Math.floor(Math.random()*on.length)];return e.jsx(ca,{open:!!s,onOpenChange:()=>{},children:e.jsx(oa,{className:"sm:max-w-[420px] p-0 overflow-hidden border-0 shadow-2xl [&>button]:hidden",onPointerDownOutside:h=>h.preventDefault(),onEscapeKeyDown:h=>h.preventDefault(),children:s.phase==="saving"?e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"h-2 bg-gradient-to-r from-blue-500 via-primary to-violet-500 animate-gradient-x"}),e.jsxs("div",{className:"px-8 py-10 text-center",children:[e.jsxs("div",{className:"relative mx-auto mb-6 h-20 w-20",children:[e.jsxs("svg",{className:"animate-spin-slow h-20 w-20",viewBox:"0 0 80 80",children:[e.jsx("circle",{cx:"40",cy:"40",r:"34",fill:"none",stroke:"#e2e8f0",strokeWidth:"6"}),e.jsx("circle",{cx:"40",cy:"40",r:"34",fill:"none",stroke:"url(#spinner-gradient)",strokeWidth:"6",strokeLinecap:"round",strokeDasharray:`${c*2.14} 214`,className:"transition-all duration-500 ease-out"}),e.jsx("defs",{children:e.jsxs("linearGradient",{id:"spinner-gradient",x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[e.jsx("stop",{offset:"0%",stopColor:"#5eead4"}),e.jsx("stop",{offset:"50%",stopColor:"#0d9488"}),e.jsx("stop",{offset:"100%",stopColor:"#0f766e"})]})})]}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsxs("span",{className:"text-[18px] font-bold text-slate-700",children:[c,"%"]})})]}),e.jsx("h3",{className:"text-[15px] font-semibold text-slate-800 mb-1",children:"Saving Attendance"}),e.jsxs("p",{className:"text-[13px] text-slate-500 mb-4",children:["Processing day ",s.current," of ",s.total,e.jsx("span",{className:"mx-1.5 text-slate-300",children:"|"}),s.totalRecords," records"]}),e.jsx("div",{className:"mb-5",children:e.jsx($a,{value:c,className:"h-2 bg-slate-100"})}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-[13px] text-slate-600 animate-fade-in",children:[e.jsx("span",{className:"text-[18px]",children:r.emoji}),e.jsx("span",{className:"font-medium",children:r.text})]},a),(s.created>0||s.updated>0)&&e.jsxs("div",{className:"mt-4 flex items-center justify-center gap-4 text-[11px]",children:[e.jsxs("span",{className:"text-emerald-600 font-medium",children:["+",s.created," created"]}),e.jsxs("span",{className:"text-blue-600 font-medium",children:["~",s.updated," updated"]})]})]})]}):e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"h-2 bg-gradient-to-r from-emerald-400 via-green-500 to-teal-400"}),e.jsxs("div",{className:"px-8 py-10 text-center",children:[e.jsxs("div",{className:"relative mx-auto mb-5 h-20 w-20",children:[e.jsx("div",{className:"absolute inset-0 rounded-full bg-emerald-100 animate-ping-once"}),e.jsx("div",{className:"relative h-20 w-20 rounded-full bg-gradient-to-br from-emerald-400 to-green-500 flex items-center justify-center animate-scale-in shadow-lg shadow-emerald-200",children:e.jsx(it,{className:"h-10 w-10 text-white",strokeWidth:2.5})}),e.jsx(et,{className:"absolute -top-1 -right-1 h-5 w-5 text-amber-400 animate-sparkle-1"}),e.jsx(et,{className:"absolute -bottom-1 -left-2 h-4 w-4 text-violet-400 animate-sparkle-2"}),e.jsx(et,{className:"absolute top-0 -left-3 h-3 w-3 text-blue-400 animate-sparkle-3"})]}),e.jsx("h3",{className:"text-[16px] font-bold text-slate-800 mb-1 animate-fade-in-up",children:d.text}),e.jsx("p",{className:"text-[13px] text-slate-500 mb-4 animate-fade-in-up-delay",children:d.subtitle}),e.jsxs("div",{className:"inline-flex items-center gap-3 bg-slate-50 rounded-xl px-5 py-3 animate-fade-in-up-delay-2",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-[18px] font-bold text-emerald-600",children:s.created}),e.jsx("p",{className:"text-[10px] text-slate-400 uppercase tracking-wider",children:"Created"})]}),e.jsx("div",{className:"w-px h-8 bg-slate-200"}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-[18px] font-bold text-blue-600",children:s.updated}),e.jsx("p",{className:"text-[10px] text-slate-400 uppercase tracking-wider",children:"Updated"})]}),e.jsx("div",{className:"w-px h-8 bg-slate-200"}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-[18px] font-bold text-slate-700",children:s.totalRecords}),e.jsx("p",{className:"text-[10px] text-slate-400 uppercase tracking-wider",children:"Total"})]})]}),e.jsx("p",{className:"mt-4 text-[11px] text-slate-400 animate-fade-in-up-delay-2",children:"Closing automatically..."})]})]})})})}const wa=[{text:"Recomputing timesheet records...",emoji:"🔄"},{text:"Scanning punch logs...",emoji:"📡"},{text:"Matching shifts and schedules...",emoji:"🗓️"},{text:"Crunching the numbers...",emoji:"🔢"},{text:"Almost there, hang tight!",emoji:"⚡"},{text:"Syncing attendance data...",emoji:"🚀"}];function Ji({state:s,monthLabel:t,onConfirm:a,onClose:l}){const[c,r]=i.useState(0);if(i.useEffect(()=>{if(!s.open||s.phase!=="processing")return;r(0);const h=setInterval(()=>{r(v=>(v+1)%wa.length)},2500);return()=>clearInterval(h)},[s.open,s.phase]),i.useEffect(()=>{if(s.phase==="success"){const h=setTimeout(l,4e3);return()=>clearTimeout(h)}},[s.phase,l]),!s.open)return null;const d=wa[c%wa.length];return s.phase==="confirm"?e.jsx(_n,{open:!0,onOpenChange:h=>{h||l()},children:e.jsxs(bn,{children:[e.jsxs(Nn,{children:[e.jsx(wn,{children:"Refresh Month Timesheet"}),e.jsxs(Sn,{children:["This will recompute attendance from punch records for"," ",e.jsx("span",{className:"font-semibold text-slate-700",children:s.employeeName})," for the entire month of ",e.jsx("span",{className:"font-semibold text-slate-700",children:t}),". Existing attendance records will be overwritten."]})]}),e.jsxs(kn,{children:[e.jsx(Cn,{children:"Cancel"}),e.jsxs(Dn,{onClick:a,children:[e.jsx(Qs,{className:"h-3.5 w-3.5 mr-1.5"})," Refresh Month"]})]})]})}):e.jsx(ca,{open:!0,onOpenChange:()=>{},children:e.jsx(oa,{className:"sm:max-w-[420px] p-0 overflow-hidden border-0 shadow-2xl [&>button]:hidden",onPointerDownOutside:h=>h.preventDefault(),onEscapeKeyDown:h=>h.preventDefault(),children:s.phase==="processing"?e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"h-2 bg-gradient-to-r from-orange-400 via-amber-500 to-yellow-400 animate-gradient-x"}),e.jsxs("div",{className:"px-8 py-10 text-center",children:[e.jsxs("div",{className:"relative mx-auto mb-6 h-20 w-20",children:[e.jsxs("svg",{className:"animate-spin-slow h-20 w-20",viewBox:"0 0 80 80",children:[e.jsx("circle",{cx:"40",cy:"40",r:"34",fill:"none",stroke:"#e2e8f0",strokeWidth:"6"}),e.jsx("circle",{cx:"40",cy:"40",r:"34",fill:"none",stroke:"url(#refresh-spinner-gradient)",strokeWidth:"6",strokeLinecap:"round",strokeDasharray:"80 214",className:"transition-all duration-500 ease-out"}),e.jsx("defs",{children:e.jsxs("linearGradient",{id:"refresh-spinner-gradient",x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[e.jsx("stop",{offset:"0%",stopColor:"#f97316"}),e.jsx("stop",{offset:"50%",stopColor:"#eab308"}),e.jsx("stop",{offset:"100%",stopColor:"#0f766e"})]})})]}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx(Qs,{className:"h-6 w-6 text-orange-500 animate-spin"})})]}),e.jsx("h3",{className:"text-[15px] font-semibold text-slate-800 mb-1",children:"Refreshing Timesheet"}),e.jsxs("p",{className:"text-[13px] text-slate-500 mb-4",children:[s.employeeName," · ",t]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-[13px] text-slate-600 animate-fade-in",children:[e.jsx("span",{className:"text-[18px]",children:d.emoji}),e.jsx("span",{className:"font-medium",children:d.text})]},c)]})]}):s.phase==="success"?e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"h-2 bg-gradient-to-r from-emerald-400 via-green-500 to-teal-400"}),e.jsxs("div",{className:"px-8 py-10 text-center",children:[e.jsxs("div",{className:"relative mx-auto mb-5 h-20 w-20",children:[e.jsx("div",{className:"absolute inset-0 rounded-full bg-emerald-100 animate-ping-once"}),e.jsx("div",{className:"relative h-20 w-20 rounded-full bg-gradient-to-br from-emerald-400 to-green-500 flex items-center justify-center animate-scale-in shadow-lg shadow-emerald-200",children:e.jsx(it,{className:"h-10 w-10 text-white",strokeWidth:2.5})}),e.jsx(et,{className:"absolute -top-1 -right-1 h-5 w-5 text-amber-400 animate-sparkle-1"}),e.jsx(et,{className:"absolute -bottom-1 -left-2 h-4 w-4 text-violet-400 animate-sparkle-2"})]}),e.jsx("h3",{className:"text-[16px] font-bold text-slate-800 mb-1 animate-fade-in-up",children:"Timesheet Refreshed!"}),e.jsxs("p",{className:"text-[13px] text-slate-500 mb-4 animate-fade-in-up-delay",children:[s.employeeName,"'s attendance is up to date."]}),s.result&&e.jsxs("div",{className:"inline-flex items-center gap-3 bg-slate-50 rounded-xl px-5 py-3 animate-fade-in-up-delay-2",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-[18px] font-bold text-blue-600",children:s.result.days_processed??s.result.days_queued??0}),e.jsx("p",{className:"text-[10px] text-slate-400 uppercase tracking-wider",children:"Days"})]}),s.result.total_records!=null&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-px h-8 bg-slate-200"}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-[18px] font-bold text-emerald-600",children:s.result.total_records}),e.jsx("p",{className:"text-[10px] text-slate-400 uppercase tracking-wider",children:"Records"})]})]})]}),e.jsx("p",{className:"mt-4 text-[11px] text-slate-400 animate-fade-in-up-delay-2",children:"Closing automatically..."})]})]}):e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"h-2 bg-gradient-to-r from-red-400 via-rose-500 to-pink-400"}),e.jsxs("div",{className:"px-8 py-10 text-center",children:[e.jsx("div",{className:"mx-auto mb-5 h-16 w-16 rounded-full bg-red-100 flex items-center justify-center",children:e.jsx(bt,{className:"h-8 w-8 text-red-500"})}),e.jsx("h3",{className:"text-[15px] font-semibold text-slate-800 mb-1",children:"Refresh Failed"}),e.jsx("p",{className:"text-[13px] text-slate-500 mb-4",children:s.errorMsg}),e.jsx(y,{size:"sm",variant:"outline",onClick:l,children:"Close"})]})]})})})}function Xi(s){const t=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(s);return t?{r:parseInt(t[1],16),g:parseInt(t[2],16),b:parseInt(t[3],16)}:null}function kt(s){const t=Xi(s);return t?{backgroundColor:`rgba(${t.r}, ${t.g}, ${t.b}, 0.15)`,color:s}:{}}function Ct(s,t){return ve(new Date(s,t-1,1),"MMMM yyyy")}function ec(s,t,a){return ve(new Date(s,t-1,a,12,0,0),"EEE")}function dn(s,t,a){return new Date(s,t-1,a,12,0,0).getDay()===0}function sc(s){const[t=0,a=1,l=1]=s.split("-").map(Number);return ve(new Date(t,a-1,l,12,0,0),"EEE")}function mn(s){const[t=0,a=1,l=1]=s.split("-").map(Number);return new Date(t,a-1,l,12,0,0).getDay()===0}function xt(s){const[t=0,a=1,l=1]=s.split("-").map(Number);return{y:t,m:a,d:l}}function fd(){const s=new Date,[t,a]=i.useState(s.getFullYear()),[l,c]=i.useState(s.getMonth()+1),r=`${t}-${String(l).padStart(2,"0")}`,[d,h]=i.useState(""),[v,A]=i.useState(""),[u,p]=i.useState(""),[F,O]=i.useState(""),[m,_]=i.useState(!1),[q,k]=i.useState(!1),[x,Y]=i.useState(!1),[H,C]=i.useState({open:!1,employeeId:"",employeeName:"",employeeCode:"",date:""}),[N,E]=i.useState({open:!1,phase:"confirm",employeeId:"",employeeName:"",result:null,errorMsg:""}),n=qt(),{data:K}=Pl(d||null),M=(K==null?void 0:K.results)??[],o=i.useMemo(()=>M.length?M.find(g=>{const ae=new Date(g.end_date);return ae.getUTCMonth()+1===l&&ae.getUTCFullYear()===t})??null:null,[M,l,t]),L=i.useMemo(()=>({month:r,...d&&{company:d},...v&&{department:v},...u&&{branch:u},...o&&{from_date:o.start_date,to_date:o.end_date}}),[r,d,v,u,o]),{data:V,isLoading:j}=br(L),$=Va(),J=Un(),B=Qn(),ne=In(),D=Kn(),{can:fe,must:Q}=Qe(),oe=fe("attendance","create"),[Se,Te]=i.useState(""),[I,S]=i.useState(""),[de,ze]=i.useState(""),{data:Oe,isLoading:U}=Hs({page_size:100,search:Se||void 0}),{data:me,isLoading:Je}=ct({page_size:100,search:I||void 0,...d?{company:d}:{}}),{data:ms,isLoading:qs}=ft({page_size:100,search:de||void 0,...d?{company:d}:{}}),{data:ts}=zt({is_active:!0,page_size:50}),G=(Oe==null?void 0:Oe.results)??[],xe=(me==null?void 0:me.results)??[],ue=(ms==null?void 0:ms.results)??[],Ae=i.useMemo(()=>((ts==null?void 0:ts.results)??[]).map(g=>({value:g.code,label:g.name,shortCode:g.code,color:g.color})),[ts]),Ie=i.useMemo(()=>{const g={};for(const ae of(ts==null?void 0:ts.results)??[])g[ae.code]=ae.color;return g},[ts]),pe=(V==null?void 0:V.days_in_month)??0,Fe=i.useMemo(()=>{var g;return(g=V==null?void 0:V.dates)!=null&&g.length?V.dates:Array.from({length:pe},(ae,_e)=>{const be=_e+1;return`${t}-${String(l).padStart(2,"0")}-${String(be).padStart(2,"0")}`})},[V==null?void 0:V.dates,pe,t,l]),Ye=(V==null?void 0:V.employees)??[],js=V==null?void 0:V.summary,[gs,re]=i.useState({}),as=i.useRef(""),ns=`${r}-${d}-${v}-${u}`;ns!==as.current&&(as.current=ns,Object.keys(gs).length>0&&re({}));const ls=i.useMemo(()=>{if(!F)return Ye;const g=F.toLowerCase();return Ye.filter(ae=>ae.employee_name.toLowerCase().includes(g)||ae.employee_code.toLowerCase().includes(g)||(ae.department_name??"").toLowerCase().includes(g))},[Ye,F]);function is(g,ae){var be,ce;const _e=(be=gs[g.employee_id])==null?void 0:be[ae];return _e?_e.status:((ce=g.days[ae])==null?void 0:ce.status)??null}const cs=i.useCallback((g,ae,_e)=>{re(be=>({...be,[g]:{...be[g]??{},[ae]:{status:_e,dirty:!0}}}))},[]);function Gs(g,ae){Q("attendance","create")&&re(_e=>{const be={..._e};for(const ce of Ye)be[ce.employee_id]={...be[ce.employee_id]??{},[g]:{status:ae,dirty:!0}};return be})}function Ss(g,ae){Q("attendance","create")&&re(_e=>{const be={..._e[g]??{}};for(let ce=1;ce<=pe;ce++)be[String(ce)]={status:ae,dirty:!0};return{..._e,[g]:be}})}const Ue=i.useMemo(()=>{const g={};let ae=0;for(const _e of Ye)for(let be=1;be<=pe;be++){const ce=is(_e,String(be));ce&&(g[ce]=(g[ce]??0)+1,ae++)}return{counts:g,marked:ae,total:Ye.length*pe}},[Ye,pe,gs]),zs=i.useMemo(()=>{let g=0;for(const ae of Object.values(gs))for(const _e of Object.values(ae))_e.dirty&&g++;return g},[gs]),[As,Bs]=i.useState(null);function w(){if(!Q("attendance","create"))return;const g={};let ae=0;for(const Zs of Object.keys(gs)){const ke=gs[Zs];if(ke)for(const[Vt,Qt]of Object.entries(ke)){if(!Qt.dirty)continue;const vt=Fe[Number(Vt)-1]??`${t}-${String(l).padStart(2,"0")}-${Vt.padStart(2,"0")}`;g[vt]||(g[vt]=[]),g[vt].push({employee:Zs,status:Qt.status}),ae++}}const _e=Object.keys(g).sort();if(_e.length===0)return;let be=0,ce=0;Bs({phase:"saving",current:0,total:_e.length,totalRecords:ae,created:0,updated:0});let bs=0;function Ps(){if(bs>=_e.length){Bs(ke=>ke?{...ke,phase:"success",current:_e.length,created:be,updated:ce}:null),re({});return}Bs(ke=>ke?{...ke,current:bs+1,created:be,updated:ce}:null);const Zs=_e[bs];$.mutate({attendance_date:Zs,records:g[Zs]},{onSuccess:ke=>{be+=ke.created,ce+=ke.updated,bs++,Ps()},onError:()=>{Bs(null)}})}Ps()}const ie=i.useCallback(()=>{Bs(null)},[]);function le(){l===1?(a(g=>g-1),c(12)):c(g=>g-1)}function Ve(){l===12?(a(g=>g+1),c(1)):c(g=>g+1)}function Rs(){if(!Q("attendance","create"))return;const g=(o==null?void 0:o.start_date)??`${t}-${String(l).padStart(2,"0")}-01`,ae=new Date(t,l,0).getDate(),_e=(o==null?void 0:o.end_date)??`${t}-${String(l).padStart(2,"0")}-${String(ae).padStart(2,"0")}`;B.mutate({start_date:g,end_date:_e,company:d},{onSuccess:()=>k(!1)})}function Ws(g){const ae={template_format:g};g==="monthly"&&(ae.month=r),J.mutate(ae,{onSuccess:_e=>{const be=URL.createObjectURL(_e),ce=document.createElement("a");ce.href=be,ce.download=g==="monthly"?`attendance_monthly_${r}.csv`:"attendance_daily_template.csv",ce.click(),URL.revokeObjectURL(be)}})}function W(g,ae,_e,be){const ce=be??`${t}-${String(l).padStart(2,"0")}-01`;C({open:!0,employeeId:g,employeeName:ae,employeeCode:_e,date:ce})}const[Ee,Ys]=i.useState(null);function tl(g,ae,_e){Q("attendance","create")&&(Ys({empId:g,day:ae}),ne.mutate({date:_e,employee_ids:[g]},{onSettled:()=>Ys(null)}))}function al(){Q("attendance","create")&&N.employeeId&&(E(g=>({...g,phase:"processing"})),D.mutate({month:r,employee_ids:[N.employeeId]},{onSuccess:g=>{E(ae=>({...ae,phase:"success",result:g}))},onError:g=>{E(ae=>({...ae,phase:"error",errorMsg:g instanceof Error?g.message:"Refresh failed"}))}}))}const[Ot,Ka]=i.useState(null);return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-5",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-[16px] font-semibold text-slate-900 flex items-center gap-2",children:[e.jsx(nt,{className:"h-5 w-5 text-primary"})," Monthly Attendance"]}),e.jsxs("p",{className:"mt-0.5 text-[13px] text-slate-400",children:["Mark and view attendance for ",Ct(t,l),o&&e.jsxs("span",{className:"ml-2 inline-flex items-center text-[11px] text-primary font-medium bg-primary/8 px-2 py-0.5 rounded-full",children:[o.start_date," → ",o.end_date]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[oe&&e.jsxs(e.Fragment,{children:[e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>Y(!0),children:[e.jsx(nt,{className:"h-3.5 w-3.5 mr-1.5"})," Month Process"]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>k(!0),children:[e.jsx(Xt,{className:"h-3.5 w-3.5 mr-1.5"})," Auto-Generate"]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>_(!0),children:[e.jsx(ia,{className:"h-3.5 w-3.5 mr-1.5"})," Import"]})]}),e.jsxs(fs,{children:[e.jsx(vs,{asChild:!0,children:e.jsxs(y,{variant:"outline",size:"sm",children:[e.jsx(yt,{className:"h-3.5 w-3.5 mr-1.5"})," Export",e.jsx(Yt,{className:"h-3 w-3 ml-1"})]})}),e.jsxs(_s,{align:"end",children:[e.jsxs(Ce,{onClick:()=>Ws("monthly"),children:[e.jsx(aa,{className:"h-3.5 w-3.5 mr-2"})," Monthly CSV Template"]}),e.jsxs(Ce,{onClick:()=>Ws("daily"),children:[e.jsx(aa,{className:"h-3.5 w-3.5 mr-2"})," Daily CSV Template"]})]})]}),oe&&e.jsxs(y,{size:"sm",disabled:zs===0||!!As,onClick:w,children:[e.jsx(st,{className:"h-3.5 w-3.5 mr-1.5"}),As?"Saving...":`Save Changes${zs>0?` (${zs})`:""}`]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 mb-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(y,{variant:"outline",size:"icon-sm",onClick:le,children:e.jsx(Oa,{className:"h-4 w-4"})}),e.jsx("div",{className:"px-3 py-1.5 text-[13px] font-medium text-slate-800 min-w-[140px] text-center",children:Ct(t,l)}),e.jsx(y,{variant:"outline",size:"icon-sm",onClick:Ve,children:e.jsx(Vs,{className:"h-4 w-4"})})]}),e.jsx(Ke,{orientation:"vertical",className:"h-6"}),e.jsx("div",{className:"w-[160px]",children:e.jsx(ge,{value:d||null,onValueChange:g=>{h(g),A(""),p("")},onSearch:Te,isLoading:U,options:G.map(g=>({value:g.id,label:g.name,hint:g.code})),placeholder:"All companies",searchPlaceholder:"Search companies..."})}),e.jsx("div",{className:"w-[160px]",children:e.jsx(ge,{value:v||null,onValueChange:g=>A(g),onSearch:S,isLoading:Je,disabled:!d,options:xe.map(g=>({value:g.id,label:g.name,hint:g.code})),placeholder:d?"All departments":"Select a company first",searchPlaceholder:"Search departments..."})}),e.jsx("div",{className:"w-[150px]",children:e.jsx(ge,{value:u||null,onValueChange:g=>p(g),onSearch:ze,isLoading:qs,disabled:!d,options:ue.map(g=>({value:g.id,label:g.name,hint:g.code})),placeholder:d?"All branches":"Select a company first",searchPlaceholder:"Search branches..."})}),e.jsx(R,{placeholder:"Search employee...",value:F,onChange:g=>O(g.target.value),className:"w-[200px] h-9"})]}),e.jsxs("div",{className:"grid grid-cols-5 gap-3 mb-4",children:[e.jsx(Dt,{icon:e.jsx(Ms,{className:"h-4 w-4 text-blue-500"}),label:"Employees",value:(js==null?void 0:js.total_employees)??0}),e.jsx(Dt,{icon:e.jsx($t,{className:"h-4 w-4 text-emerald-500"}),label:"Present",value:Ue.counts.P??0}),e.jsx(Dt,{icon:e.jsx(Nt,{className:"h-4 w-4 text-red-500"}),label:"Absent",value:Ue.counts.A??0}),e.jsx(Dt,{icon:e.jsx(ss,{className:"h-4 w-4 text-amber-500"}),label:"Half Day",value:Ue.counts.HD??0}),e.jsx(Dt,{icon:e.jsx(nt,{className:"h-4 w-4 text-slate-500"}),label:"Unmarked",value:Ue.total-Ue.marked})]}),e.jsxs("div",{className:"flex items-center gap-2 mb-3 flex-wrap",children:[e.jsx("span",{className:"text-[11px] text-slate-400 mr-1",children:"Legend:"}),Ae.map(g=>e.jsxs("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium",style:kt(g.color),children:[g.shortCode," = ",g.label]},g.value))]}),e.jsx(ye,{children:e.jsxs(je,{className:"p-0",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsx(ml,{delayDuration:200,children:e.jsxs("table",{className:"w-full border-collapse text-[11px]",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-slate-50/80",children:[e.jsx("th",{className:"sticky left-0 z-20 bg-slate-50 border-b border-r border-slate-200 px-2 py-2 text-left font-medium text-slate-500 w-[50px] min-w-[50px] max-w-[50px]",children:"#"}),e.jsx("th",{className:"sticky left-[50px] z-20 bg-slate-50 border-b border-r border-slate-200 px-2 py-2 text-left font-medium text-slate-500 w-[70px] min-w-[70px] max-w-[70px]",children:"Code"}),e.jsx("th",{className:"sticky left-[120px] z-20 bg-slate-50 border-b border-r border-slate-200 px-2 py-2 text-left font-medium text-slate-500 w-[140px] min-w-[140px] max-w-[140px]",children:"Employee"}),e.jsx("th",{className:"sticky left-[260px] z-20 bg-slate-50 border-b border-r border-slate-200 px-2 py-2 text-left font-medium text-slate-500 w-[80px] min-w-[80px] max-w-[80px] shadow-[2px_0_4px_-1px_rgba(0,0,0,0.08)]",children:"Dept"}),pe>0&&Array.from({length:pe},(g,ae)=>ae+1).map(g=>{const ae=Fe[g-1],_e=ae?sc(ae):ec(t,l,g),be=ae?mn(ae):dn(t,l,g),{y:ce,m:bs,d:Ps}=ae?xt(ae):{y:t,m:l,d:g},Zs=bs!==l;return e.jsx("th",{className:`border-b border-r border-slate-200 px-0.5 py-1 text-center font-medium w-[38px] min-w-[38px] ${be?"bg-red-50/60 text-red-400":"text-slate-500"}`,children:e.jsxs(fs,{children:[e.jsx(vs,{asChild:!0,children:e.jsxs("button",{className:"w-full cursor-pointer hover:bg-slate-100 rounded px-1 py-0.5",children:[Zs&&e.jsx("div",{className:"text-[8px] leading-tight text-slate-400",children:ve(new Date(ce,bs-1,1),"MMM")}),e.jsx("div",{className:"text-[10px] leading-tight",children:_e}),e.jsx("div",{className:"text-[11px] leading-tight font-semibold",children:Ps})]})}),e.jsxs(_s,{align:"center",className:"min-w-[120px]",children:[e.jsxs("p",{className:"px-2 py-1 text-[11px] text-slate-400 font-medium",children:["Mark All — ",ae??`Day ${g}`]}),e.jsx(Ke,{className:"my-1"}),Ae.map(ke=>e.jsxs(Ce,{onClick:()=>Gs(String(g),ke.value),className:"text-[12px]",children:[e.jsx("span",{className:"inline-block w-5 h-4 rounded text-center text-[10px] font-semibold leading-4 mr-2",style:kt(ke.color),children:ke.shortCode}),ke.label]},ke.value))]})]})},g)}),e.jsx("th",{className:"border-b border-slate-200 px-1 py-2 text-center font-medium text-slate-500 w-[40px] min-w-[40px]",children:e.jsx("span",{className:"text-[10px]",children:"All"})})]})}),e.jsx("tbody",{children:j?Array.from({length:6}).map((g,ae)=>e.jsx("tr",{children:e.jsx("td",{colSpan:4+pe+1,className:"p-2",children:e.jsx(Tt,{className:"h-6 w-full"})})},ae)):ls.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:4+(pe||28)+1,className:"text-center py-12 text-slate-400",children:Ye.length===0?"No active employees found. Adjust filters or select a different month.":"No employees match your search."})}):ls.map((g,ae)=>{const _e=!!gs[g.employee_id]&&Object.values(gs[g.employee_id]).some(ce=>ce.dirty),be=_e?"bg-blue-50":ae%2===0?"bg-white":"bg-slate-50";return e.jsxs("tr",{className:_e?"bg-blue-50/30":ae%2===0?"bg-white":"bg-slate-50/30",children:[e.jsx("td",{className:`sticky left-0 z-10 ${be} border-b border-r border-slate-100 px-2 py-1.5 text-slate-400 font-mono text-[10px] w-[50px] min-w-[50px] max-w-[50px]`,children:ae+1}),e.jsx("td",{className:`sticky left-[50px] z-10 ${be} border-b border-r border-slate-100 px-2 py-1.5 text-slate-500 font-mono text-[10px] w-[70px] min-w-[70px] max-w-[70px]`,children:g.employee_code}),e.jsx("td",{className:`sticky left-[120px] z-10 ${be} border-b border-r border-slate-100 px-0 py-0 w-[140px] min-w-[140px] max-w-[140px]`,children:e.jsxs(Wa,{children:[e.jsx(Ya,{asChild:!0,children:e.jsx("div",{className:"px-2 py-1.5 cursor-default",children:e.jsx("span",{className:"text-[11px] font-medium text-slate-800 truncate block max-w-[130px]",children:g.employee_name})})}),e.jsxs(Za,{className:"min-w-[180px]",children:[e.jsx(Ja,{className:"text-[11px] text-slate-400",children:g.employee_name}),e.jsx(ya,{}),e.jsxs(ot,{onClick:()=>W(g.employee_id,g.employee_name,g.employee_code,null),className:"text-[12px]",children:[e.jsx(ss,{className:"h-3.5 w-3.5 mr-2 text-blue-500"}),"View Punch Log"]}),e.jsxs(ot,{onClick:()=>n(`/core-hr/employees/${g.employee_id}`),className:"text-[12px]",children:[e.jsx(Ll,{className:"h-3.5 w-3.5 mr-2 text-slate-500"}),"View Profile"]}),e.jsxs(ot,{onClick:()=>E({open:!0,phase:"confirm",employeeId:g.employee_id,employeeName:g.employee_name,result:null,errorMsg:""}),className:"text-[12px]",children:[e.jsx(Qs,{className:"h-3.5 w-3.5 mr-2 text-orange-500"}),"Refresh Month"]}),e.jsx(ya,{}),e.jsxs(ot,{onClick:()=>Ss(g.employee_id,"P"),className:"text-[12px]",children:[e.jsx($t,{className:"h-3.5 w-3.5 mr-2 text-green-500"}),"Mark All Present"]}),e.jsxs(ot,{onClick:()=>Ss(g.employee_id,"A"),className:"text-[12px]",children:[e.jsx(Nt,{className:"h-3.5 w-3.5 mr-2 text-red-500"}),"Mark All Absent"]})]})]})}),e.jsx("td",{className:`sticky left-[260px] z-10 ${be} border-b border-r border-slate-100 px-2 py-1.5 text-[10px] text-slate-500 truncate w-[80px] min-w-[80px] max-w-[80px] shadow-[2px_0_4px_-1px_rgba(0,0,0,0.08)]`,children:g.department_name??"—"}),Array.from({length:pe},(ce,bs)=>bs+1).map(ce=>{var vt,Ua,Ha;const bs=String(ce),Ps=is(g,bs),Zs=(Ua=(vt=gs[g.employee_id])==null?void 0:vt[bs])==null?void 0:Ua.dirty,ke=Fe[ce-1],Vt=ke?mn(ke):dn(t,l,ce),Qt=(Ee==null?void 0:Ee.empId)===g.employee_id&&Ee.day===ce;return e.jsxs("td",{className:`border-b border-r border-slate-100 px-0 py-0 text-center relative ${Vt?"bg-red-50/30":""} ${Zs?"ring-1 ring-inset ring-blue-300":""}`,children:[Qt&&e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-white/80 backdrop-blur-[1px]",children:e.jsx(Ks,{className:"h-3.5 w-3.5 text-orange-500 animate-spin"})}),e.jsxs(Wa,{children:[e.jsx(Ya,{asChild:!0,children:e.jsx("div",{children:e.jsxs(xl,{children:[e.jsx(ul,{asChild:!0,children:e.jsxs(fs,{open:((Ot==null?void 0:Ot.empId)===g.employee_id&&Ot.day===bs,void 0),children:[e.jsx(vs,{asChild:!0,children:e.jsx("button",{className:"w-full h-[28px] text-[10px] font-semibold rounded-none cursor-pointer transition-colors",style:Ps&&Ie[Ps]?kt(Ie[Ps]):Ps?{backgroundColor:"#f1f5f9",color:"#475569"}:{color:"#cbd5e1"},onClick:()=>Ka({empId:g.employee_id,day:bs}),children:Ps??"·"})}),e.jsx(_s,{align:"center",className:"min-w-[110px]",children:Ae.map(Js=>e.jsxs(Ce,{onClick:()=>{cs(g.employee_id,bs,Js.value),Ka(null)},className:"text-[12px]",children:[e.jsx("span",{className:"inline-block w-5 h-4 rounded text-center text-[10px] font-semibold leading-4 mr-2",style:kt(Js.color),children:Js.shortCode}),Js.label]},Js.value))})]})}),e.jsxs(hl,{side:"top",className:"text-[11px]",children:[e.jsxs("p",{children:[g.employee_name," — ",ke?ve(new Date(xt(ke).y,xt(ke).m-1,xt(ke).d,12,0,0),"dd MMM"):ve(new Date(t,l-1,ce,12,0,0),"dd MMM")]}),e.jsx("p",{className:"text-slate-400",children:Ps?((Ha=Ae.find(Js=>Js.value===Ps))==null?void 0:Ha.label)??Ps:"Not marked"})]})]})})}),e.jsxs(Za,{className:"min-w-[160px]",children:[e.jsxs(Ja,{className:"text-[11px] text-slate-400",children:[g.employee_name," — ",ke?ve(new Date(xt(ke).y,xt(ke).m-1,xt(ke).d,12,0,0),"dd MMM"):ve(new Date(t,l-1,ce,12,0,0),"dd MMM")]}),e.jsx(ya,{}),e.jsxs(ot,{className:"text-[12px]",onClick:()=>{const Js=ke??`${t}-${String(l).padStart(2,"0")}-${String(ce).padStart(2,"0")}`;W(g.employee_id,g.employee_name,g.employee_code,Js)},children:[e.jsx(ss,{className:"h-3.5 w-3.5 mr-2 text-slate-500"}),"View Day Log"]}),e.jsxs(ot,{className:"text-[12px]",onClick:()=>tl(g.employee_id,ce,ke??`${t}-${String(l).padStart(2,"0")}-${String(ce).padStart(2,"0")}`),children:[e.jsx(Qs,{className:"h-3.5 w-3.5 mr-2 text-slate-500"}),"Refresh Day"]})]})]})]},ce)}),e.jsx("td",{className:"border-b border-slate-100 px-0 py-0 text-center",children:e.jsxs(fs,{children:[e.jsx(vs,{asChild:!0,children:e.jsx("button",{className:"w-full h-[28px] text-[10px] text-slate-400 hover:bg-slate-100 cursor-pointer",children:e.jsx(Yt,{className:"h-3 w-3 mx-auto"})})}),e.jsxs(_s,{align:"end",className:"min-w-[120px]",children:[e.jsx("p",{className:"px-2 py-1 text-[11px] text-slate-400 font-medium",children:"Mark All Days"}),e.jsx(Ke,{className:"my-1"}),Ae.map(ce=>e.jsxs(Ce,{onClick:()=>Ss(g.employee_id,ce.value),className:"text-[12px]",children:[e.jsx("span",{className:"inline-block w-5 h-4 rounded text-center text-[10px] font-semibold leading-4 mr-2",style:kt(ce.color),children:ce.shortCode}),ce.label]},ce.value))]})]})})]},g.employee_id)})})]})})}),ls.length>0&&e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-t border-slate-100 bg-slate-50/50",children:[e.jsxs("p",{className:"text-[12px] text-slate-500",children:[(js==null?void 0:js.total_employees)??0," employees · ",Ue.marked," marked · ",Ue.total-Ue.marked," unmarked",zs>0&&e.jsxs("span",{className:"text-blue-600 font-medium ml-2",children:["· ",zs," unsaved changes"]})]}),oe&&e.jsxs(y,{size:"sm",disabled:zs===0||!!As,onClick:w,children:[e.jsx(st,{className:"h-3.5 w-3.5 mr-1.5"}),As?"Saving...":"Save All Changes"]})]})]})}),e.jsx(Zi,{progress:As,onClose:ie}),e.jsx(Xn,{open:m,onOpenChange:_,defaultTab:"monthly",employees:Ye,dates:Fe,onDownloadTemplate:Ws}),e.jsx(Wn,{open:H.open,onOpenChange:g=>C(ae=>({...ae,open:g})),employeeId:H.employeeId,employeeName:H.employeeName,employeeCode:H.employeeCode,date:H.date}),e.jsx(Yi,{open:x,onOpenChange:Y,month:r,year:t,monthNum:l}),e.jsx(Ji,{state:N,monthLabel:Ct(t,l),onConfirm:al,onClose:()=>E(g=>({...g,open:!1}))}),e.jsx(He,{open:q,onOpenChange:k,children:e.jsxs(Ge,{size:"md",children:[e.jsxs(Be,{children:[e.jsx(We,{children:"Auto-Generate Attendance"}),e.jsx(Ze,{children:"Pre-fill weekends and holidays for the entire month based on shift schedules and work calendars."})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[13px] font-medium text-slate-700",children:"Company *"}),e.jsx("div",{className:"mt-1.5",children:e.jsx(ge,{value:d||null,onValueChange:g=>h(g),onSearch:Te,isLoading:U,options:G.map(g=>({value:g.id,label:g.name,hint:g.code})),placeholder:"Select company",searchPlaceholder:"Search companies..."})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[13px] font-medium text-slate-700",children:"Month"}),e.jsx(R,{type:"text",value:Ct(t,l),disabled:!0,className:"mt-1.5"})]}),e.jsx(Ke,{}),e.jsxs("p",{className:"text-[12px] text-slate-500",children:["This will create attendance records for all employees for ",Ct(t,l),". Weekends and holidays will be automatically pre-filled. Existing records will not be overwritten."]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 px-6 py-4 border-t",children:[e.jsx(y,{variant:"outline",size:"sm",onClick:()=>k(!1),children:"Cancel"}),oe&&e.jsxs(y,{size:"sm",disabled:!d||B.isPending,onClick:Rs,children:[e.jsx(Xt,{className:"h-3.5 w-3.5 mr-1.5"}),B.isPending?"Generating...":"Generate"]})]})]})})]})}function Dt({icon:s,label:t,value:a}){return e.jsx(ye,{className:"border border-slate-100",children:e.jsxs(je,{className:"flex items-center gap-3 py-3 px-4",children:[e.jsx("div",{className:"h-8 w-8 rounded-lg bg-slate-50 flex items-center justify-center",children:s}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[20px] font-semibold text-slate-800 leading-none",children:a}),e.jsx("p",{className:"text-[11px] text-slate-400 mt-0.5",children:t})]})]})})}const tc=ys({attendance_date:Ra("Date is required"),regularization_type:Ns(["late_coming","early_going","short_day","missed_punch"]),requested_in:X().min(1,"Check-in time is required"),requested_out:X().min(1,"Check-out time is required"),reason:X().min(1,"Reason is required")}),ac={pending:"warning",approved:"success",rejected:"destructive"},nc={late_coming:"Late Coming",early_going:"Early Going",short_day:"Short Day",missed_punch:"Missed Punch"};function vd(){const[s,t]=i.useState(!1),[a,l]=i.useState(""),{pagination:c,setPagination:r,sorting:d,setSorting:h,globalFilter:v,setGlobalFilter:A,queryParams:u}=$s(),p={...u,...a&&{status:a}},{data:F,isLoading:O}=Nr(p),m=(F==null?void 0:F.results)??[],_=wr(),q=Sr(),{can:k,must:x}=Qe(),Y=k("regularization","create"),H=k("regularization","approve"),C=hs({resolver:ps(tc),defaultValues:{regularization_type:"missed_punch"}});function N(){C.reset({regularization_type:"missed_punch"}),t(!0)}function E(o){if(!x("regularization","create"))return;const L={...o};_.mutate(L,{onSuccess:()=>t(!1)})}function n(o,L){x("regularization","approve")&&q.mutate({id:o,action:L})}function K(o){l(o==="__all__"?"":o),r(L=>({...L,pageIndex:0}))}const M=[{key:"employee",header:"Employee",render:o=>e.jsx("span",{className:"font-medium text-slate-900",children:o.employee_name})},{key:"attendance_date",header:"Date",render:o=>ve(ws(o.attendance_date),"dd MMM yyyy")},{key:"type",header:"Type",render:o=>e.jsx(ee,{variant:"default",children:nc[o.regularization_type]})},{key:"original",header:"Original (In/Out)",render:o=>{var L,V;return e.jsxs("span",{className:"text-[13px] text-slate-500",children:[((L=o.original_in)==null?void 0:L.slice(0,5))??"—"," / ",((V=o.original_out)==null?void 0:V.slice(0,5))??"—"]})}},{key:"requested",header:"Requested (In/Out)",render:o=>e.jsxs("span",{className:"text-[13px] text-slate-700 font-medium",children:[o.requested_in.slice(0,5)," / ",o.requested_out.slice(0,5)]})},{key:"reason",header:"Reason",render:o=>e.jsx("span",{className:"text-[12px] text-slate-500 truncate max-w-[200px] block",children:o.reason})},{key:"status",header:"Status",render:o=>e.jsxs("div",{children:[e.jsx(ee,{variant:ac[o.status],children:o.status}),o.approved_by_name&&e.jsxs("p",{className:"text-[10px] text-slate-400 mt-0.5",children:["by ",o.approved_by_name]})]})},{key:"actions",header:"",className:"w-10",render:o=>o.status==="pending"&&H?e.jsxs(fs,{children:[e.jsx(vs,{asChild:!0,children:e.jsx(y,{variant:"ghost",size:"icon-sm",children:e.jsx(Us,{className:"h-4 w-4"})})}),e.jsxs(_s,{align:"end",children:[e.jsxs(Ce,{onClick:()=>n(o.id,"approve"),children:[e.jsx(Rt,{className:"mr-2 h-3.5 w-3.5 text-emerald-600"})," Approve"]}),e.jsxs(Ce,{onClick:()=>n(o.id,"reject"),children:[e.jsx(xa,{className:"mr-2 h-3.5 w-3.5 text-red-500"})," Reject"]})]})]}):null}];return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-[16px] font-semibold text-slate-900 flex items-center gap-2",children:[e.jsx(qn,{className:"h-5 w-5 text-primary"})," Regularizations"]}),e.jsx("p",{className:"mt-0.5 text-[13px] text-slate-400",children:"Attendance regularization requests"})]}),Y&&e.jsxs(y,{size:"sm",onClick:N,children:[e.jsx(ds,{className:"mr-1.5 h-3.5 w-3.5"})," New Request"]})]}),e.jsx(rs,{actions:e.jsx("div",{className:"flex gap-2",children:e.jsxs($e,{value:a,onValueChange:K,children:[e.jsx(Le,{className:"w-[140px] h-9",children:e.jsx(qe,{placeholder:"All statuses"})}),e.jsxs(Re,{children:[e.jsx(Z,{value:"__all__",children:"All"}),e.jsx(Z,{value:"pending",children:"Pending"}),e.jsx(Z,{value:"approved",children:"Approved"}),e.jsx(Z,{value:"rejected",children:"Rejected"})]})]})}),columns:M,data:m,isLoading:O,searchPlaceholder:"Search regularizations...",emptyMessage:"No regularization requests",emptyDescription:"Submit a regularization when attendance needs correction.",totalCount:(F==null?void 0:F.count)??0,pagination:c,onPaginationChange:r,sorting:d,onSortingChange:h,globalFilter:v,onGlobalFilterChange:A}),e.jsx(He,{open:s,onOpenChange:t,children:e.jsxs(Ge,{size:"md",children:[e.jsxs(Be,{children:[e.jsx(We,{children:"New Regularization Request"}),e.jsx(Ze,{children:"Submit a request to correct your attendance record."})]}),e.jsxs("form",{onSubmit:C.handleSubmit(E),className:"flex-1 overflow-y-auto px-6 py-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx(P,{children:"Attendance Date *"}),e.jsx(R,{type:"date",...C.register("attendance_date"),className:"mt-1.5"}),C.formState.errors.attendance_date&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:C.formState.errors.attendance_date.message})]}),e.jsxs("div",{children:[e.jsx(P,{children:"Type *"}),e.jsxs($e,{value:C.watch("regularization_type"),onValueChange:o=>C.setValue("regularization_type",o),children:[e.jsx(Le,{className:"mt-1.5",children:e.jsx(qe,{})}),e.jsxs(Re,{children:[e.jsx(Z,{value:"late_coming",children:"Late Coming"}),e.jsx(Z,{value:"early_going",children:"Early Going"}),e.jsx(Z,{value:"short_day",children:"Short Day"}),e.jsx(Z,{value:"missed_punch",children:"Missed Punch"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(P,{children:"Requested In *"}),e.jsx(R,{type:"time",...C.register("requested_in"),className:"mt-1.5"}),C.formState.errors.requested_in&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:C.formState.errors.requested_in.message})]}),e.jsxs("div",{children:[e.jsx(P,{children:"Requested Out *"}),e.jsx(R,{type:"time",...C.register("requested_out"),className:"mt-1.5"}),C.formState.errors.requested_out&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:C.formState.errors.requested_out.message})]})]}),e.jsxs("div",{children:[e.jsx(P,{children:"Reason *"}),e.jsx(R,{...C.register("reason"),className:"mt-1.5",placeholder:"Explain why regularization is needed"}),C.formState.errors.reason&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:C.formState.errors.reason.message})]})]}),e.jsxs(us,{children:[e.jsx(y,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(y,{onClick:C.handleSubmit(E),disabled:_.isPending,children:"Submit Request"})]})]})})]})}const lc=ys({employee:X().min(1,"Employee is required"),overtime_date:Ra("Date is required"),overtime_type:Ns(["regular","holiday","weekend"]),planned_hours:X().min(1,"Hours are required"),reason:X().min(1,"Reason is required")}),rc={pending:"warning",approved:"success",rejected:"destructive",paid:"default"},ic={regular:"Regular",holiday:"Holiday",weekend:"Weekend"};function _d(){const[s,t]=i.useState(!1),[a,l]=i.useState(""),{pagination:c,setPagination:r,sorting:d,setSorting:h,globalFilter:v,setGlobalFilter:A,queryParams:u}=$s(),p={...u,...a&&{status:a}},{data:F,isLoading:O}=Cr(p),m=(F==null?void 0:F.results)??[],_=Dr(),q=Ar(),{can:k,must:x}=Qe(),Y=k("overtime","create"),H=k("overtime","approve"),C=hs({resolver:ps(lc),defaultValues:{overtime_type:"regular"}});function N(){C.reset({overtime_type:"regular"}),t(!0)}function E(o){if(!x("overtime","create"))return;const L={...o};_.mutate(L,{onSuccess:()=>t(!1)})}function n(o,L){x("overtime","approve")&&q.mutate({id:o,action:L})}function K(o){l(o==="__all__"?"":o),r(L=>({...L,pageIndex:0}))}const M=[{key:"employee",header:"Employee",render:o=>e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-slate-900",children:o.employee_name}),o.employee_id_display&&e.jsx("span",{className:"ml-2 text-[11px] text-slate-400",children:o.employee_id_display}),o.department_name&&e.jsx("p",{className:"text-[11px] text-slate-400",children:o.department_name})]})},{key:"overtime_date",header:"Date",render:o=>e.jsx(Aa,{to:`/attendance/overtime/${o.id}`,className:"font-medium text-primary hover:underline",children:ve(ws(o.overtime_date),"dd MMM yyyy")})},{key:"overtime_type",header:"Type",render:o=>e.jsx(ee,{variant:"default",children:ic[o.overtime_type]})},{key:"hours",header:"Planned / Actual / Approved",render:o=>e.jsxs("span",{className:"text-[13px] text-slate-600",children:[o.planned_hours,"h / ",o.actual_hours,"h / ",o.approved_hours,"h"]})},{key:"rate",header:"Rate",render:o=>e.jsxs("span",{className:"text-[13px] text-slate-500",children:[o.rate_multiplier,"x"]})},{key:"reason",header:"Reason",render:o=>e.jsx("span",{className:"text-[12px] text-slate-500 truncate max-w-[180px] block",children:o.reason})},{key:"status",header:"Status",render:o=>e.jsxs("div",{children:[e.jsx(ee,{variant:rc[o.status],children:o.status}),o.approved_by_name&&e.jsxs("p",{className:"text-[10px] text-slate-400 mt-0.5",children:["by ",o.approved_by_name]})]})},{key:"actions",header:"",className:"w-10",render:o=>o.status==="pending"&&H?e.jsxs(fs,{children:[e.jsx(vs,{asChild:!0,children:e.jsx(y,{variant:"ghost",size:"icon-sm",children:e.jsx(Us,{className:"h-4 w-4"})})}),e.jsxs(_s,{align:"end",children:[e.jsxs(Ce,{onClick:()=>n(o.id,"approve"),children:[e.jsx(Rt,{className:"mr-2 h-3.5 w-3.5 text-emerald-600"})," Approve"]}),e.jsxs(Ce,{onClick:()=>n(o.id,"reject"),children:[e.jsx(xa,{className:"mr-2 h-3.5 w-3.5 text-red-500"})," Reject"]})]})]}):null}];return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-[16px] font-semibold text-slate-900 flex items-center gap-2",children:[e.jsx(rt,{className:"h-5 w-5 text-primary"})," Overtime"]}),e.jsx("p",{className:"mt-0.5 text-[13px] text-slate-400",children:"Overtime records and approvals"})]}),Y&&e.jsxs(y,{size:"sm",onClick:N,children:[e.jsx(ds,{className:"mr-1.5 h-3.5 w-3.5"})," Log Overtime"]})]}),e.jsx(rs,{actions:e.jsx("div",{className:"flex gap-2",children:e.jsxs($e,{value:a,onValueChange:K,children:[e.jsx(Le,{className:"w-[140px] h-9",children:e.jsx(qe,{placeholder:"All statuses"})}),e.jsxs(Re,{children:[e.jsx(Z,{value:"__all__",children:"All"}),e.jsx(Z,{value:"pending",children:"Pending"}),e.jsx(Z,{value:"approved",children:"Approved"}),e.jsx(Z,{value:"rejected",children:"Rejected"}),e.jsx(Z,{value:"paid",children:"Paid"})]})]})}),columns:M,data:m,isLoading:O,searchPlaceholder:"Search overtime records...",emptyMessage:"No overtime records",emptyDescription:"Overtime records will appear here.",totalCount:(F==null?void 0:F.count)??0,pagination:c,onPaginationChange:r,sorting:d,onSortingChange:h,globalFilter:v,onGlobalFilterChange:A}),e.jsx(He,{open:s,onOpenChange:t,children:e.jsxs(Ge,{size:"md",children:[e.jsxs(Be,{children:[e.jsx(We,{children:"Log Overtime"}),e.jsx(Ze,{children:"Create an overtime record for approval."})]}),e.jsxs("form",{onSubmit:C.handleSubmit(E),className:"flex-1 overflow-y-auto px-6 py-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx(P,{children:"Employee *"}),e.jsx(ea,{value:C.watch("employee")??"",onValueChange:o=>C.setValue("employee",o,{shouldValidate:!0}),className:"mt-1.5"}),C.formState.errors.employee&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:C.formState.errors.employee.message})]}),e.jsxs("div",{children:[e.jsx(P,{children:"Date *"}),e.jsx(R,{type:"date",...C.register("overtime_date"),className:"mt-1.5"}),C.formState.errors.overtime_date&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:C.formState.errors.overtime_date.message})]}),e.jsxs("div",{children:[e.jsx(P,{children:"Overtime Type *"}),e.jsxs($e,{value:C.watch("overtime_type"),onValueChange:o=>C.setValue("overtime_type",o),children:[e.jsx(Le,{className:"mt-1.5",children:e.jsx(qe,{})}),e.jsxs(Re,{children:[e.jsx(Z,{value:"regular",children:"Regular"}),e.jsx(Z,{value:"holiday",children:"Holiday"}),e.jsx(Z,{value:"weekend",children:"Weekend"})]})]})]}),e.jsxs("div",{children:[e.jsx(P,{children:"Planned Hours *"}),e.jsx(R,{type:"number",step:"0.5",...C.register("planned_hours"),className:"mt-1.5",placeholder:"e.g. 2.5"}),C.formState.errors.planned_hours&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:C.formState.errors.planned_hours.message})]}),e.jsxs("div",{children:[e.jsx(P,{children:"Reason *"}),e.jsx(R,{...C.register("reason"),className:"mt-1.5",placeholder:"Reason for overtime"}),C.formState.errors.reason&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:C.formState.errors.reason.message})]})]}),e.jsxs(us,{children:[e.jsx(y,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(y,{onClick:C.handleSubmit(E),disabled:_.isPending,children:"Submit"})]})]})})]})}const cc={pending:"warning",approved:"success",rejected:"destructive"};function tt({label:s,value:t}){return e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-slate-400",children:s}),e.jsx("p",{className:"mt-0.5 text-[13.5px] text-slate-800",children:t??"—"})]})}function bd(){const{id:s}=ra(),t=qt(),[a,l]=i.useState(!1),{data:c,isLoading:r,refetch:d}=kr(s??"");if(r)return e.jsxs("div",{children:[e.jsx(ja,{title:"Overtime Record"}),e.jsx(ye,{children:e.jsxs(je,{className:"pt-6 pb-4 space-y-3",children:[e.jsx("div",{className:"h-4 w-48 animate-pulse rounded bg-slate-100"}),e.jsx("div",{className:"h-4 w-32 animate-pulse rounded bg-slate-100"})]})})]});if(!c)return e.jsxs("div",{children:[e.jsx(ja,{title:"Not Found",actions:e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>t("/attendance/overtime"),children:[e.jsx(gt,{className:"mr-1.5 h-3.5 w-3.5"})," Back"]})}),e.jsx(ye,{children:e.jsx(je,{className:"py-16 text-center",children:e.jsx("p",{className:"text-[14px] text-slate-500",children:"Overtime record not found."})})})]});const h=`Overtime — ${ve(ws(c.overtime_date),"dd MMM yyyy")}`;return e.jsxs("div",{children:[e.jsx(ja,{title:h,description:c.employee_name??void 0,actions:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>l(!0),className:"border-[#0d9488] text-[#0d9488] hover:bg-[#f0fdfa]",children:[e.jsx(Mt,{className:"mr-1.5 h-3.5 w-3.5"})," Approvals"]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>t("/attendance/overtime"),children:[e.jsx(gt,{className:"mr-1.5 h-3.5 w-3.5"})," Back"]})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-6",children:[e.jsx("div",{className:"col-span-2 space-y-4",children:e.jsxs(ye,{children:[e.jsx(ks,{className:"pb-3",children:e.jsxs(Cs,{className:"flex items-center gap-2 text-[14px]",children:[e.jsx(ss,{className:"h-4 w-4 text-slate-400"})," Overtime Details"]})}),e.jsxs(je,{className:"grid grid-cols-2 gap-4",children:[e.jsx(tt,{label:"Date",value:ve(ws(c.overtime_date),"dd MMM yyyy")}),e.jsx(tt,{label:"Type",value:c.overtime_type}),e.jsx(tt,{label:"Planned Hours",value:c.planned_hours}),e.jsx(tt,{label:"Approved Hours",value:c.approved_hours}),e.jsx(tt,{label:"Reason",value:c.reason||"—"})]})]})}),e.jsx("div",{className:"space-y-4",children:e.jsxs(ye,{children:[e.jsx(ks,{className:"pb-3",children:e.jsxs(Cs,{className:"flex items-center gap-2 text-[14px]",children:[e.jsx(pl,{className:"h-4 w-4 text-slate-400"})," Employee"]})}),e.jsxs(je,{className:"space-y-3",children:[e.jsx(tt,{label:"Name",value:c.employee_name}),e.jsx(tt,{label:"Employee ID",value:c.employee_id_display}),e.jsx(tt,{label:"Department",value:c.department_name}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-slate-400",children:"Status"}),e.jsx(ee,{variant:cc[c.status]??"secondary",className:"mt-1",children:c.status})]})]})]})})]}),e.jsx(He,{open:a,onOpenChange:l,children:e.jsxs(Ge,{size:"sm",dismissible:!0,className:"flex flex-col gap-0 overflow-hidden p-0",children:[e.jsxs(Be,{children:[e.jsx(We,{className:"text-[16px]",children:"Approvals"}),e.jsx(Ze,{className:"text-[12.5px]",children:h})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-6 py-5",children:a&&e.jsx(ql,{recordId:c.id,recordLabel:h,onDecided:()=>{d(),l(!1)}})})]})})]})}const Kt=({label:s,icon:t,enabled:a})=>a?e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md bg-primary/8 px-2 py-0.5 text-[10px] font-medium text-primary",children:[e.jsx(t,{className:"h-2.5 w-2.5"}),s]}):null;function Nd(){const s=qt(),{data:t,isLoading:a}=Pr({page_size:50}),l=(t==null?void 0:t.results)??[],c=Mr(),[r,d]=i.useState(""),{can:h,must:v}=Qe(),A=h("policy","create"),u=h("policy","update"),p=h("policy","delete"),F=m=>{v("policy","delete")&&confirm(`Delete "${m.name}"?`)&&c.mutate(m.id)},O=r?l.filter(m=>m.name.toLowerCase().includes(r.toLowerCase())||m.company_name.toLowerCase().includes(r.toLowerCase())):l;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-[16px] font-semibold text-slate-900 flex items-center gap-2",children:[e.jsx(Mt,{className:"h-5 w-5 text-primary"})," Attendance Policies"]}),e.jsx("p",{className:"mt-0.5 text-[13px] text-slate-400",children:"Configure attendance rules, late penalties, and absence escalations"})]}),A&&e.jsxs(y,{size:"sm",onClick:()=>s("/attendance/policies/new"),children:[e.jsx(ds,{className:"mr-1.5 h-3.5 w-3.5"})," Add Policy"]})]}),e.jsxs("div",{className:"relative mb-4 max-w-sm",children:[e.jsx(Wt,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-slate-400"}),e.jsx(R,{placeholder:"Search policies...",value:r,onChange:m=>d(m.target.value),className:"pl-9 h-9"})]}),a&&e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[1,2,3,4].map(m=>e.jsx("div",{className:"h-48 rounded-lg bg-slate-200 animate-pulse"},m))}),!a&&O.length===0&&e.jsxs("div",{className:"text-center py-16",children:[e.jsx(Mt,{className:"h-10 w-10 text-slate-300 mx-auto mb-3"}),e.jsx("p",{className:"text-[14px] font-medium text-slate-600",children:r?"No policies match your search":"No policies configured"}),e.jsx("p",{className:"text-[12px] text-slate-400 mt-1",children:r?"Try a different search term.":"Create your first attendance policy to get started."}),!r&&A&&e.jsxs(y,{size:"sm",className:"mt-4",onClick:()=>s("/attendance/policies/new"),children:[e.jsx(ds,{className:"mr-1.5 h-3.5 w-3.5"})," Create Policy"]})]}),!a&&O.length>0&&e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:O.map(m=>e.jsx(oc,{policy:m,canUpdate:u,canDelete:p,onView:()=>s(`/attendance/policies/${m.id}`),onEdit:()=>s(`/attendance/policies/${m.id}/edit`),onDelete:()=>F(m)},m.id))})]})}function oc({policy:s,canUpdate:t,canDelete:a,onView:l,onEdit:c,onDelete:r}){return e.jsx(ye,{className:"group hover:border-primary/30 hover:shadow-md transition-all duration-200 cursor-pointer",onClick:l,children:e.jsxs(je,{className:"p-5",children:[e.jsxs("div",{className:"flex items-start justify-between mb-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"text-[14px] font-semibold text-slate-900 truncate",children:s.name}),e.jsx(wt,{status:s.is_active?"active":"inactive",className:"text-[9px] shrink-0"})]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-[11px] text-slate-400",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Rn,{className:"h-3 w-3"}),s.company_name]}),s.branch_name&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Tn,{className:"h-3 w-3"}),s.branch_name]})]})]}),e.jsxs(fs,{children:[e.jsx(vs,{asChild:!0,onClick:d=>d.stopPropagation(),children:e.jsx(y,{variant:"ghost",size:"icon-sm",className:"opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(Us,{className:"h-4 w-4"})})}),e.jsxs(_s,{align:"end",onClick:d=>d.stopPropagation(),children:[e.jsxs(Ce,{onClick:l,children:[e.jsx(ua,{className:"mr-2 h-3.5 w-3.5"})," View Details"]}),t&&e.jsxs(Ce,{onClick:c,children:[e.jsx(Ls,{className:"mr-2 h-3.5 w-3.5"})," Edit"]}),a&&e.jsxs(e.Fragment,{children:[e.jsx(yl,{}),e.jsxs(Ce,{className:"text-red-600",onClick:r,children:[e.jsx(Ts,{className:"mr-2 h-3.5 w-3.5"})," Delete"]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-4 gap-3 mb-3",children:[e.jsxs("div",{className:"rounded-md bg-slate-50 px-3 py-2 text-center",children:[e.jsx("p",{className:"text-[10px] text-slate-400",children:"Grace"}),e.jsxs("p",{className:"text-[14px] font-semibold text-slate-900",children:[s.grace_period_minutes,"m"]})]}),e.jsxs("div",{className:"rounded-md bg-slate-50 px-3 py-2 text-center",children:[e.jsx("p",{className:"text-[10px] text-slate-400",children:"Late"}),e.jsxs("p",{className:"text-[14px] font-semibold text-slate-900",children:[s.late_threshold_minutes,"m"]})]}),e.jsxs("div",{className:"rounded-md bg-slate-50 px-3 py-2 text-center",children:[e.jsx("p",{className:"text-[10px] text-slate-400",children:"Half-Day"}),e.jsxs("p",{className:"text-[14px] font-semibold text-slate-900",children:[s.half_day_min_minutes,"m"]})]}),e.jsxs("div",{className:"rounded-md bg-slate-50 px-3 py-2 text-center",children:[e.jsx("p",{className:"text-[10px] text-slate-400",children:"Penalty"}),e.jsx("p",{className:`text-[12px] font-semibold capitalize ${s.penalty_processing_mode==="auto"?"text-blue-600":"text-slate-600"}`,children:s.penalty_processing_mode})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-3",children:[e.jsx(Kt,{label:"Overtime",icon:pt,enabled:s.overtime_eligible}),e.jsx(Kt,{label:"Flexi",icon:rt,enabled:s.flexi_time_enabled}),e.jsx(Kt,{label:"Geofencing",icon:jt,enabled:s.geofencing_enabled}),e.jsx(Kt,{label:"Short Leave",icon:ss,enabled:s.short_leave_enabled})]}),e.jsxs("div",{className:"flex items-center justify-between pt-3 border-t border-slate-100",children:[e.jsxs("div",{className:"flex items-center gap-4 text-[11px] text-slate-400",children:[s.late_rule_count>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(zn,{className:"h-3 w-3"})," ",s.late_rule_count," late rule",s.late_rule_count!==1?"s":""]}),s.absence_rule_count>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(os,{className:"h-3 w-3"})," ",s.absence_rule_count," absence rule",s.absence_rule_count!==1?"s":""]}),s.assignment_count>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ms,{className:"h-3 w-3"})," ",s.assignment_count," segment",s.assignment_count!==1?"s":""]})]}),e.jsxs("span",{className:"text-[11px] text-primary font-medium flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:["View ",e.jsx(Vs,{className:"h-3 w-3"})]})]})]})})}const dc=ys({instance_number:De.number().min(1),action:Ns(["auto_approve","warning","salary_deduction","leave_deduction","final_warning"]),deduction_amount:X().optional(),deduction_type:Ns(["fixed","percentage","daily_rate"]).optional(),leave_type:X().optional(),leave_days:X().optional(),notify_employee:es().optional(),notify_manager:es().optional()}),mc=ys({instance_number:De.number().min(1),action:Ns(["warning","salary_deduction","leave_deduction","final_warning"]),deduction_amount:X().optional(),deduction_type:Ns(["fixed","percentage","daily_rate"]).optional(),leave_type:X().optional(),leave_days:X().optional(),notify_employee:es().optional(),notify_manager:es().optional()}),xc=ys({trigger_type:Ns(["consecutive","total"]),threshold_days:De.number().min(1),action:Ns(["warning","leave_deduction","salary_deduction","disciplinary"]),leave_type:X().optional(),leave_days:X().optional(),deduction_amount:X().optional(),deduction_type:Ns(["fixed","percentage","daily_rate"]).optional(),notify_employee:es().optional(),notify_manager:es().optional()}),uc=Cl(ys({company:X().min(1,"Company is required"),department:X().optional(),branch:X().optional(),grade:X().optional(),category:X().optional(),effective_from:X().min(1,"Required"),effective_to:X().optional(),priority:De.number().optional(),is_active:es().optional()}),"effective_from","effective_to"),hc=ys({month:De.number().min(1).max(12),year:De.number().min(2020)}),at=({label:s,value:t,icon:a,color:l="slate"})=>{const c={slate:"bg-slate-100 text-slate-600",blue:"bg-blue-100 text-blue-600",emerald:"bg-emerald-100 text-emerald-600",amber:"bg-amber-100 text-amber-600",red:"bg-red-100 text-red-600",violet:"bg-violet-100 text-violet-600"};return e.jsx("div",{className:"rounded-lg border border-slate-200 p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`h-9 w-9 rounded-lg flex items-center justify-center ${c[l]}`,children:e.jsx(a,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-slate-400",children:s}),e.jsx("p",{className:"text-[15px] font-semibold text-slate-900",children:t})]})]})})},Xe=({label:s,value:t})=>e.jsxs("div",{children:[e.jsx("span",{className:"text-[11px] text-slate-400",children:s}),e.jsx("p",{className:"text-[13px] font-medium text-slate-900 mt-0.5",children:t??"—"})]}),At=({label:s,enabled:t,icon:a})=>e.jsxs("div",{className:`inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-[11px] font-medium ${t?"bg-primary/10 text-primary":"bg-slate-100 text-slate-400"}`,children:[e.jsx(a,{className:"h-3 w-3"}),s]}),lt={auto_approve:{label:"Auto Approve",color:"text-emerald-700",bg:"bg-emerald-50 border-emerald-200",icon:St},warning:{label:"Warning",color:"text-amber-700",bg:"bg-amber-50 border-amber-200",icon:os},salary_deduction:{label:"Salary Deduction",color:"text-red-700",bg:"bg-red-50 border-red-200",icon:zl},leave_deduction:{label:"Leave Deduction",color:"text-blue-700",bg:"bg-blue-50 border-blue-200",icon:ha},final_warning:{label:"Final Warning",color:"text-red-800",bg:"bg-red-100 border-red-300",icon:os},disciplinary:{label:"Disciplinary",color:"text-red-800",bg:"bg-red-100 border-red-300",icon:os}},Ia=s=>{const t=lt[s]??{label:s,color:"text-slate-600",bg:"bg-slate-50 border-slate-200",icon:St};return e.jsxs("span",{className:`inline-flex items-center gap-1.5 rounded-md border px-2 py-1 text-[11px] font-medium ${t.color} ${t.bg}`,children:[e.jsx(t.icon,{className:"h-3 w-3"}),t.label]})},pc=s=>{const t={applied:"success",reversed:"secondary",waived:"destructive"};return e.jsx(ee,{variant:t[s]??"secondary",children:s})};function wd(){const{id:s}=ra(),t=qt(),{data:a,isLoading:l}=Hn(s),{data:c,isLoading:r}=$r(s),{data:d,isLoading:h}=Tr(s),{data:v,isLoading:A}=Qr(s),{data:u,isLoading:p}=Hr({policy:s}),{data:F,isLoading:O}=Yr({policy:s}),m=(c==null?void 0:c.results)??[],_=(d==null?void 0:d.results)??[],q=(v==null?void 0:v.results)??[],k=(u==null?void 0:u.results)??[],x=(F==null?void 0:F.results)??[],[Y,H]=i.useState({open:!1}),[C,N]=i.useState({open:!1}),[E,n]=i.useState({open:!1}),[K,M]=i.useState({open:!1}),[o,L]=i.useState(!1);return l?e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"h-9 w-64 rounded bg-slate-200 animate-pulse"}),e.jsx("div",{className:"h-48 rounded-lg bg-slate-200 animate-pulse"}),e.jsx("div",{className:"h-64 rounded-lg bg-slate-200 animate-pulse"})]}):a?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(y,{variant:"ghost",size:"icon-sm",className:"mt-0.5",onClick:()=>t("/attendance/policies"),children:e.jsx(gt,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("h1",{className:"text-[18px] font-semibold text-slate-900",children:a.name}),e.jsx(wt,{status:a.is_active?"active":"inactive",className:"text-[10px]"}),a.penalty_processing_mode==="auto"&&e.jsx(ee,{variant:"default",className:"text-[10px]",children:"Auto Penalty"})]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-[12px] text-slate-400",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Rn,{className:"h-3 w-3"}),a.company_name]}),a.branch_name&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Tn,{className:"h-3 w-3"}),a.branch_name]})]})]})]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>t(`/attendance/policies/${s}/edit`),children:[e.jsx(Ls,{className:"h-3.5 w-3.5 mr-1.5"})," Edit Policy"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(At,{label:"Overtime",enabled:a.overtime_eligible,icon:pt}),e.jsx(At,{label:"Flexi-Time",enabled:a.flexi_time_enabled,icon:rt}),e.jsx(At,{label:"Geofencing",enabled:a.geofencing_enabled,icon:jt}),e.jsx(At,{label:"Short Leave",enabled:a.short_leave_enabled,icon:ss}),e.jsx(At,{label:`Late Reset: ${a.late_reset_period}`,enabled:!0,icon:Ca})]}),e.jsxs("div",{className:"grid grid-cols-5 gap-3",children:[e.jsx(at,{label:"Grace Period",value:`${a.grace_period_minutes} min`,icon:ss,color:"emerald"}),e.jsx(at,{label:"Late Threshold",value:`${a.late_threshold_minutes} min`,icon:os,color:"amber"}),e.jsx(at,{label:"Half-Day Min",value:`${a.half_day_min_minutes} min`,icon:rt,color:"blue"}),e.jsx(at,{label:"Late Rules",value:a.late_rule_count,icon:zn,color:"violet"}),e.jsx(at,{label:"Assignments",value:a.assignment_count,icon:Ms,color:"slate"})]}),e.jsxs(Ea,{defaultValue:"general",children:[e.jsxs(Ma,{children:[e.jsxs(Fs,{value:"general",children:[e.jsx(jl,{className:"h-3.5 w-3.5 mr-1.5"}),"General"]}),e.jsxs(Fs,{value:"late",children:[e.jsx(ss,{className:"h-3.5 w-3.5 mr-1.5"}),"Late Rules",m.length>0&&e.jsx(ee,{variant:"secondary",className:"ml-1.5 text-[9px] px-1.5",children:m.length})]}),e.jsxs(Fs,{value:"early",children:[e.jsx(gl,{className:"h-3.5 w-3.5 mr-1.5"}),"Early Exit Rules",_.length>0&&e.jsx(ee,{variant:"secondary",className:"ml-1.5 text-[9px] px-1.5",children:_.length})]}),e.jsxs(Fs,{value:"absence",children:[e.jsx(os,{className:"h-3.5 w-3.5 mr-1.5"}),"Absence Rules",q.length>0&&e.jsx(ee,{variant:"secondary",className:"ml-1.5 text-[9px] px-1.5",children:q.length})]}),e.jsxs(Fs,{value:"assignments",children:[e.jsx(Ms,{className:"h-3.5 w-3.5 mr-1.5"}),"Assignments",k.length>0&&e.jsx(ee,{variant:"secondary",className:"ml-1.5 text-[9px] px-1.5",children:k.length})]}),e.jsxs(Fs,{value:"penalties",children:[e.jsx(Tl,{className:"h-3.5 w-3.5 mr-1.5"}),"Penalties"]})]}),e.jsx(Os,{value:"general",children:e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(ye,{children:[e.jsx(ks,{className:"pb-3",children:e.jsxs(Cs,{className:"text-[13px] flex items-center gap-2",children:[e.jsx(ss,{className:"h-4 w-4 text-primary"})," Time Thresholds"]})}),e.jsx(je,{className:"space-y-3",children:e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Xe,{label:"Grace Period",value:`${a.grace_period_minutes} min`}),e.jsx(Xe,{label:"Late Threshold",value:`${a.late_threshold_minutes} min`}),e.jsx(Xe,{label:"Early Threshold",value:`${a.early_threshold_minutes} min`}),e.jsx(Xe,{label:"Half-Day Min",value:`${a.half_day_min_minutes} min (${Math.floor(a.half_day_min_minutes/60)}h ${a.half_day_min_minutes%60}m)`}),e.jsx(Xe,{label:"Absent Threshold",value:a.absent_max_minutes===0?"Shift default":`${a.absent_max_minutes} min`})]})})]}),e.jsxs(ye,{children:[e.jsx(ks,{className:"pb-3",children:e.jsxs(Cs,{className:"text-[13px] flex items-center gap-2",children:[e.jsx(pt,{className:"h-4 w-4 text-amber-500"})," Overtime"]})}),e.jsx(je,{className:"space-y-3",children:a.overtime_eligible?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Xe,{label:"Min Minutes",value:a.overtime_min_minutes}),e.jsx(Xe,{label:"Daily Max",value:`${a.overtime_daily_max_minutes} min`}),e.jsx(Xe,{label:"Weekly Max",value:`${a.overtime_weekly_max_minutes} min`}),e.jsx(Xe,{label:"Multipliers",value:`${a.ot_multiplier_regular}x / ${a.ot_multiplier_weekend}x / ${a.ot_multiplier_holiday}x`})]}):e.jsxs("div",{className:"text-center py-4",children:[e.jsx(pt,{className:"h-5 w-5 text-slate-300 mx-auto mb-1"}),e.jsx("p",{className:"text-[12px] text-slate-400",children:"OT disabled"})]})})]}),e.jsxs(ye,{children:[e.jsx(ks,{className:"pb-3",children:e.jsxs(Cs,{className:"text-[13px] flex items-center gap-2",children:[e.jsx(ha,{className:"h-4 w-4 text-blue-500"})," Comp-Off & Regularization"]})}),e.jsx(je,{children:e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Xe,{label:"Hours per Day",value:a.compoff_hours_per_day}),e.jsx(Xe,{label:"Validity",value:`${a.compoff_validity_days} days`}),e.jsx(Xe,{label:"Carry Forward",value:a.compoff_carry_forward_limit}),e.jsx(Xe,{label:"Reg. Window",value:`${a.regularization_window_days} days`}),e.jsx(Xe,{label:"Auto-Approve Late",value:`${a.auto_approve_late_minutes} min`})]})})]}),e.jsxs(ye,{children:[e.jsx(ks,{className:"pb-3",children:e.jsxs(Cs,{className:"text-[13px] flex items-center gap-2",children:[e.jsx(jt,{className:"h-4 w-4 text-emerald-500"})," Flexi-Time & Geofencing"]})}),e.jsxs(je,{children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Xe,{label:"Flexi-Time",value:a.flexi_time_enabled?"Enabled":"Disabled"}),a.flexi_time_enabled&&e.jsxs(e.Fragment,{children:[e.jsx(Xe,{label:"Core Hours",value:`${a.flexi_core_start} – ${a.flexi_core_end}`}),e.jsx(Xe,{label:"Flexi Window",value:`${a.flexi_window_minutes} min`})]}),e.jsx(Xe,{label:"Geofencing",value:a.geofencing_enabled?`Enabled (${a.geofence_tolerance_meters}m)`:"Disabled"})]}),a.short_leave_enabled&&e.jsxs(e.Fragment,{children:[e.jsx(Ke,{className:"my-3"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Xe,{label:"Short Leave",value:"Enabled"}),e.jsx(Xe,{label:"Max Hours",value:`${a.short_leave_max_hours}h`}),e.jsx(Xe,{label:"Max per Month",value:a.short_leave_max_per_month})]})]})]})]})]})}),e.jsx(Os,{value:"late",children:e.jsx(yc,{policyId:s,rules:m,loading:r,sheet:Y,setSheet:H})}),e.jsx(Os,{value:"early",children:e.jsx(jc,{policyId:s,rules:_,loading:h,sheet:C,setSheet:N})}),e.jsx(Os,{value:"absence",children:e.jsx(gc,{policyId:s,rules:q,loading:A,sheet:E,setSheet:n})}),e.jsx(Os,{value:"assignments",children:e.jsx(fc,{policyId:s,companyId:a.company,assignments:k,loading:p,sheet:K,setSheet:M})}),e.jsx(Os,{value:"penalties",children:e.jsx(vc,{penalties:x,loading:O,processSheet:o,setProcessSheet:L})})]})]}):e.jsxs("div",{className:"text-center py-16",children:[e.jsx(St,{className:"h-10 w-10 text-slate-300 mx-auto mb-3"}),e.jsx("p",{className:"text-[14px] font-medium text-slate-600",children:"Policy not found"}),e.jsx(Aa,{to:"/attendance/policies",className:"text-[13px] text-primary hover:underline mt-2 inline-block",children:"Back to policies"})]})}function yc({policyId:s,rules:t,loading:a,sheet:l,setSheet:c}){var E;const r=Lr(),d=qr(),h=Rr(),{can:v,must:A}=Qe(),u=v("policy","create"),p=v("policy","update"),F=v("policy","delete"),[O,m]=i.useState(""),{data:_,isLoading:q}=La({search:O||void 0}),k=(_==null?void 0:_.results)??[],x=hs({resolver:ps(dc),defaultValues:{instance_number:1,action:"warning",notify_employee:!0,notify_manager:!1}}),Y=x.watch("action"),H=()=>{x.reset({instance_number:(t.length||0)+1,action:"warning",notify_employee:!0,notify_manager:!1}),c({open:!0})},C=n=>{x.reset({instance_number:n.instance_number,action:n.action,deduction_amount:n.deduction_amount??void 0,deduction_type:n.deduction_type,leave_type:n.leave_type??void 0,leave_days:n.leave_days??void 0,notify_employee:n.notify_employee,notify_manager:n.notify_manager}),c({open:!0,rule:n})},N=n=>{if(!A("policy",l.rule?"update":"create"))return;const K={policy:s,instance_number:n.instance_number,action:n.action,deduction_amount:n.deduction_amount,deduction_type:n.deduction_type,leave_type:n.leave_type,leave_days:n.leave_days,notify_employee:n.notify_employee,notify_manager:n.notify_manager};(l.rule?d.mutateAsync({id:l.rule.id,...K}):r.mutateAsync(K)).then(()=>c({open:!1}))};return e.jsxs(e.Fragment,{children:[t.length>0&&e.jsx(ye,{className:"mb-4",children:e.jsxs(je,{className:"p-5",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-slate-400 mb-4",children:"Escalation Timeline"}),e.jsx("div",{className:"flex items-start gap-0",children:t.map((n,K)=>{const M=lt[n.action]??lt.warning;return e.jsxs("div",{className:"flex items-start",children:[e.jsxs("div",{className:"flex flex-col items-center min-w-[120px]",children:[e.jsx("div",{className:`h-10 w-10 rounded-full border-2 flex items-center justify-center ${M.bg}`,children:e.jsx(M.icon,{className:`h-4 w-4 ${M.color}`})}),e.jsxs("div",{className:"text-center mt-2",children:[e.jsxs("p",{className:"text-[12px] font-semibold text-slate-900",children:["#",n.instance_number]}),e.jsx("p",{className:`text-[10px] font-medium ${M.color}`,children:M.label}),n.action==="leave_deduction"&&e.jsxs("p",{className:"text-[10px] text-slate-400",children:[n.leave_days,"d ",n.leave_type_name??""]}),n.action==="salary_deduction"&&e.jsxs("p",{className:"text-[10px] text-slate-400",children:[n.deduction_amount," (",n.deduction_type,")"]})]})]}),K<t.length-1&&e.jsx("div",{className:"flex-shrink-0 mt-5 w-12",children:e.jsx("div",{className:"h-0.5 w-full bg-slate-200 relative",children:e.jsx(Vs,{className:"h-3 w-3 text-slate-300 absolute -right-1.5 -top-[5px]"})})})]},n.id)})})]})}),e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsxs("h3",{className:"text-[13px] font-medium text-slate-700",children:[t.length," late coming rule",t.length!==1?"s":""]}),u&&e.jsxs(y,{size:"sm",onClick:H,children:[e.jsx(ds,{className:"h-3.5 w-3.5 mr-1.5"}),"Add Rule"]})]}),e.jsx(rs,{columns:[{key:"instance_number",header:"#",className:"w-12",render:n=>e.jsx("span",{className:"inline-flex items-center justify-center h-7 w-7 rounded-full bg-slate-100 text-[12px] font-semibold text-slate-700",children:n.instance_number})},{key:"action",header:"Action",render:n=>Ia(n.action)},{key:"details",header:"Details",render:n=>e.jsx("span",{className:"text-[13px] text-slate-600",children:n.action==="leave_deduction"?`${n.leave_days??0} day(s) — ${n.leave_type_name||"Any"}`:n.action==="salary_deduction"?`${n.deduction_amount??0} (${(n.deduction_type??"fixed").replace(/_/g," ")})`:"—"})},{key:"notify",header:"Notifications",render:n=>e.jsxs("div",{className:"flex items-center gap-2",children:[n.notify_employee&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] text-slate-500 bg-slate-100 rounded px-1.5 py-0.5",children:[e.jsx(Jt,{className:"h-2.5 w-2.5"})," Employee"]}),n.notify_manager&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] text-slate-500 bg-slate-100 rounded px-1.5 py-0.5",children:[e.jsx(Jt,{className:"h-2.5 w-2.5"})," Manager"]}),!n.notify_employee&&!n.notify_manager&&e.jsx("span",{className:"text-[10px] text-slate-300",children:e.jsx(On,{className:"h-3 w-3"})})]})},{key:"actions",header:"",className:"w-20",render:n=>e.jsxs("div",{className:"flex gap-1",children:[p&&e.jsx(y,{variant:"ghost",size:"icon-sm",onClick:()=>C(n),children:e.jsx(Ls,{className:"h-3.5 w-3.5"})}),F&&e.jsx(y,{variant:"ghost",size:"icon-sm",onClick:()=>{confirm("Delete this rule?")&&h.mutate(n.id)},children:e.jsx(Ts,{className:"h-3.5 w-3.5 text-red-500"})})]})}],data:t,isLoading:a,emptyMessage:"No late coming rules",emptyDescription:"Add escalation rules for repeated late arrivals."}),e.jsx(He,{open:l.open,onOpenChange:n=>c({...l,open:n}),children:e.jsxs(Ge,{size:"lg",children:[e.jsxs(Be,{children:[e.jsxs(We,{children:[l.rule?"Edit":"Add"," Late Coming Rule"]}),e.jsx(Ze,{children:"Define what happens at each late occurrence."})]}),e.jsxs("form",{onSubmit:x.handleSubmit(N),className:"space-y-4 p-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(P,{className:"text-[12px]",children:"Instance #"}),e.jsx(R,{type:"number",...x.register("instance_number")}),e.jsx("p",{className:"text-[10px] text-slate-400 mt-1",children:"1st, 2nd, 3rd... late in the period"})]}),e.jsxs("div",{children:[e.jsx(P,{className:"text-[12px]",children:"Action"}),e.jsxs($e,{value:Y,onValueChange:n=>x.setValue("action",n),children:[e.jsx(Le,{children:e.jsx(qe,{})}),e.jsx(Re,{children:Object.entries(lt).filter(([n])=>n!=="disciplinary").map(([n,K])=>e.jsx(Z,{value:n,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(K.icon,{className:`h-3 w-3 ${K.color}`}),K.label]})},n))})]})]})]}),Y==="leave_deduction"&&e.jsxs("div",{className:"rounded-lg border border-blue-200 bg-blue-50/50 p-4 space-y-3",children:[e.jsx("p",{className:"text-[11px] font-medium text-blue-700",children:"Leave Deduction Settings"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(P,{className:"text-[12px]",children:"Leave Type"}),e.jsx(ge,{value:x.watch("leave_type")??null,onValueChange:n=>x.setValue("leave_type",n),onSearch:m,isLoading:q,selectedLabel:((E=l.rule)==null?void 0:E.leave_type_name)??void 0,options:k.map(n=>({value:n.id,label:n.name,hint:n.code})),placeholder:"Select leave type",searchPlaceholder:"Search leave types..."})]}),e.jsxs("div",{children:[e.jsx(P,{className:"text-[12px]",children:"Days to Deduct"}),e.jsx(R,{type:"number",step:"0.5",...x.register("leave_days")}),e.jsx("p",{className:"text-[10px] text-slate-400 mt-1",children:"0.5 = half day, 1.0 = full day"})]})]})]}),Y==="salary_deduction"&&e.jsxs("div",{className:"rounded-lg border border-red-200 bg-red-50/50 p-4 space-y-3",children:[e.jsx("p",{className:"text-[11px] font-medium text-red-700",children:"Salary Deduction Settings"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(P,{className:"text-[12px]",children:"Deduction Type"}),e.jsxs($e,{value:x.watch("deduction_type")??"fixed",onValueChange:n=>x.setValue("deduction_type",n),children:[e.jsx(Le,{children:e.jsx(qe,{})}),e.jsxs(Re,{children:[e.jsx(Z,{value:"fixed",children:"Fixed Amount"}),e.jsx(Z,{value:"percentage",children:"Percentage of Salary"}),e.jsx(Z,{value:"daily_rate",children:"Daily Rate (days)"})]})]})]}),e.jsxs("div",{children:[e.jsx(P,{className:"text-[12px]",children:"Amount"}),e.jsx(R,{type:"number",step:"0.01",...x.register("deduction_amount")})]})]})]}),e.jsx(Ke,{}),e.jsx("p",{className:"text-[11px] font-medium text-slate-500",children:"Notifications"}),e.jsxs("div",{className:"flex items-center gap-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ds,{checked:x.watch("notify_employee"),onCheckedChange:n=>x.setValue("notify_employee",n)}),e.jsx(P,{className:"text-[12px]",children:"Notify Employee"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ds,{checked:x.watch("notify_manager"),onCheckedChange:n=>x.setValue("notify_manager",n)}),e.jsx(P,{className:"text-[12px]",children:"Notify Manager"})]})]}),e.jsxs(us,{className:"mt-6",children:[e.jsx(y,{type:"button",variant:"outline",onClick:()=>c({open:!1}),children:"Cancel"}),e.jsxs(y,{type:"submit",disabled:r.isPending||d.isPending,children:[(r.isPending||d.isPending)&&e.jsx(Ks,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),l.rule?"Update Rule":"Add Rule"]})]})]})]})})]})}function jc({policyId:s,rules:t,loading:a,sheet:l,setSheet:c}){var E;const r=zr(),d=Or(),h=Vr(),{can:v,must:A}=Qe(),u=v("policy","create"),p=v("policy","update"),F=v("policy","delete"),[O,m]=i.useState(""),{data:_,isLoading:q}=La({search:O||void 0}),k=(_==null?void 0:_.results)??[],x=hs({resolver:ps(mc),defaultValues:{instance_number:1,action:"warning",notify_employee:!0,notify_manager:!1}}),Y=x.watch("action"),H=()=>{x.reset({instance_number:(t.length||0)+1,action:"warning",notify_employee:!0,notify_manager:!1}),c({open:!0})},C=n=>{x.reset({instance_number:n.instance_number,action:n.action,deduction_amount:n.deduction_amount??void 0,deduction_type:n.deduction_type,leave_type:n.leave_type??void 0,leave_days:n.leave_days??void 0,notify_employee:n.notify_employee,notify_manager:n.notify_manager}),c({open:!0,rule:n})},N=n=>{if(!A("policy",l.rule?"update":"create"))return;const K={policy:s,instance_number:n.instance_number,action:n.action,deduction_amount:n.deduction_amount,deduction_type:n.deduction_type,leave_type:n.leave_type,leave_days:n.leave_days,notify_employee:n.notify_employee,notify_manager:n.notify_manager};(l.rule?d.mutateAsync({id:l.rule.id,...K}):r.mutateAsync(K)).then(()=>c({open:!1}))};return e.jsxs(e.Fragment,{children:[t.length>0&&e.jsx(ye,{className:"mb-4",children:e.jsxs(je,{className:"p-5",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-slate-400 mb-4",children:"Escalation Timeline"}),e.jsx("div",{className:"flex items-start gap-0",children:t.map((n,K)=>{const M=lt[n.action]??lt.warning;return e.jsxs("div",{className:"flex items-start",children:[e.jsxs("div",{className:"flex flex-col items-center min-w-[120px]",children:[e.jsx("div",{className:`h-10 w-10 rounded-full border-2 flex items-center justify-center ${M.bg}`,children:e.jsx(M.icon,{className:`h-4 w-4 ${M.color}`})}),e.jsxs("div",{className:"text-center mt-2",children:[e.jsxs("p",{className:"text-[12px] font-semibold text-slate-900",children:["#",n.instance_number]}),e.jsx("p",{className:`text-[10px] font-medium ${M.color}`,children:M.label}),n.action==="leave_deduction"&&e.jsxs("p",{className:"text-[10px] text-slate-400",children:[n.leave_days,"d ",n.leave_type_name??""]}),n.action==="salary_deduction"&&e.jsxs("p",{className:"text-[10px] text-slate-400",children:[n.deduction_amount," (",n.deduction_type,")"]})]})]}),K<t.length-1&&e.jsx("div",{className:"flex-shrink-0 mt-5 w-12",children:e.jsx("div",{className:"h-0.5 w-full bg-slate-200 relative",children:e.jsx(Vs,{className:"h-3 w-3 text-slate-300 absolute -right-1.5 -top-[5px]"})})})]},n.id)})})]})}),e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-[13px] font-medium text-slate-700",children:[t.length," early exit rule",t.length!==1?"s":""]}),e.jsx("p",{className:"text-[11px] text-slate-400 mt-0.5",children:"Counted only when the employee leaves before completing the required hours — not merely before the shift ends."})]}),u&&e.jsxs(y,{size:"sm",onClick:H,children:[e.jsx(ds,{className:"h-3.5 w-3.5 mr-1.5"}),"Add Rule"]})]}),e.jsx(rs,{columns:[{key:"instance_number",header:"#",className:"w-12",render:n=>e.jsx("span",{className:"inline-flex items-center justify-center h-7 w-7 rounded-full bg-slate-100 text-[12px] font-semibold text-slate-700",children:n.instance_number})},{key:"action",header:"Action",render:n=>Ia(n.action)},{key:"details",header:"Details",render:n=>e.jsx("span",{className:"text-[13px] text-slate-600",children:n.action==="leave_deduction"?`${n.leave_days??0} day(s) — ${n.leave_type_name||"Any"}`:n.action==="salary_deduction"?`${n.deduction_amount??0} (${(n.deduction_type??"fixed").replace(/_/g," ")})`:"—"})},{key:"notify",header:"Notifications",render:n=>e.jsxs("div",{className:"flex items-center gap-2",children:[n.notify_employee&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] text-slate-500 bg-slate-100 rounded px-1.5 py-0.5",children:[e.jsx(Jt,{className:"h-2.5 w-2.5"})," Employee"]}),n.notify_manager&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] text-slate-500 bg-slate-100 rounded px-1.5 py-0.5",children:[e.jsx(Jt,{className:"h-2.5 w-2.5"})," Manager"]}),!n.notify_employee&&!n.notify_manager&&e.jsx("span",{className:"text-[10px] text-slate-300",children:e.jsx(On,{className:"h-3 w-3"})})]})},{key:"actions",header:"",className:"w-20",render:n=>e.jsxs("div",{className:"flex gap-1",children:[p&&e.jsx(y,{variant:"ghost",size:"icon-sm",onClick:()=>C(n),children:e.jsx(Ls,{className:"h-3.5 w-3.5"})}),F&&e.jsx(y,{variant:"ghost",size:"icon-sm",onClick:()=>{confirm("Delete this rule?")&&h.mutate(n.id)},children:e.jsx(Ts,{className:"h-3.5 w-3.5 text-red-500"})})]})}],data:t,isLoading:a,emptyMessage:"No early exit rules",emptyDescription:"Add escalation rules for employees who leave before completing their required hours."}),e.jsx(He,{open:l.open,onOpenChange:n=>c({...l,open:n}),children:e.jsxs(Ge,{size:"lg",children:[e.jsxs(Be,{children:[e.jsxs(We,{children:[l.rule?"Edit":"Add"," Early Exit Rule"]}),e.jsx(Ze,{children:"Define what happens at each early exit occurrence."})]}),e.jsxs("form",{onSubmit:x.handleSubmit(N),className:"space-y-4 p-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(P,{className:"text-[12px]",children:"Instance #"}),e.jsx(R,{type:"number",...x.register("instance_number")}),e.jsx("p",{className:"text-[10px] text-slate-400 mt-1",children:"1st, 2nd, 3rd... early exit in the period"})]}),e.jsxs("div",{children:[e.jsx(P,{className:"text-[12px]",children:"Action"}),e.jsxs($e,{value:Y,onValueChange:n=>x.setValue("action",n),children:[e.jsx(Le,{children:e.jsx(qe,{})}),e.jsx(Re,{children:Object.entries(lt).filter(([n])=>["warning","salary_deduction","leave_deduction","final_warning"].includes(n)).map(([n,K])=>e.jsx(Z,{value:n,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(K.icon,{className:`h-3 w-3 ${K.color}`}),K.label]})},n))})]})]})]}),Y==="leave_deduction"&&e.jsxs("div",{className:"rounded-lg border border-blue-200 bg-blue-50/50 p-4 space-y-3",children:[e.jsx("p",{className:"text-[11px] font-medium text-blue-700",children:"Leave Deduction Settings"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(P,{className:"text-[12px]",children:"Leave Type"}),e.jsx(ge,{value:x.watch("leave_type")??null,onValueChange:n=>x.setValue("leave_type",n),onSearch:m,isLoading:q,selectedLabel:((E=l.rule)==null?void 0:E.leave_type_name)??void 0,options:k.map(n=>({value:n.id,label:n.name,hint:n.code})),placeholder:"Select leave type",searchPlaceholder:"Search leave types..."})]}),e.jsxs("div",{children:[e.jsx(P,{className:"text-[12px]",children:"Days to Deduct"}),e.jsx(R,{type:"number",step:"0.5",...x.register("leave_days")}),e.jsx("p",{className:"text-[10px] text-slate-400 mt-1",children:"0.5 = half day, 1.0 = full day"})]})]})]}),Y==="salary_deduction"&&e.jsxs("div",{className:"rounded-lg border border-red-200 bg-red-50/50 p-4 space-y-3",children:[e.jsx("p",{className:"text-[11px] font-medium text-red-700",children:"Salary Deduction Settings"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(P,{className:"text-[12px]",children:"Deduction Type"}),e.jsxs($e,{value:x.watch("deduction_type")??"fixed",onValueChange:n=>x.setValue("deduction_type",n),children:[e.jsx(Le,{children:e.jsx(qe,{})}),e.jsxs(Re,{children:[e.jsx(Z,{value:"fixed",children:"Fixed Amount"}),e.jsx(Z,{value:"percentage",children:"Percentage of Salary"}),e.jsx(Z,{value:"daily_rate",children:"Daily Rate (days)"})]})]})]}),e.jsxs("div",{children:[e.jsx(P,{className:"text-[12px]",children:"Amount"}),e.jsx(R,{type:"number",step:"0.01",...x.register("deduction_amount")})]})]})]}),e.jsx(Ke,{}),e.jsx("p",{className:"text-[11px] font-medium text-slate-500",children:"Notifications"}),e.jsxs("div",{className:"flex items-center gap-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ds,{checked:x.watch("notify_employee"),onCheckedChange:n=>x.setValue("notify_employee",n)}),e.jsx(P,{className:"text-[12px]",children:"Notify Employee"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ds,{checked:x.watch("notify_manager"),onCheckedChange:n=>x.setValue("notify_manager",n)}),e.jsx(P,{className:"text-[12px]",children:"Notify Manager"})]})]}),e.jsxs(us,{className:"mt-6",children:[e.jsx(y,{type:"button",variant:"outline",onClick:()=>c({open:!1}),children:"Cancel"}),e.jsxs(y,{type:"submit",disabled:r.isPending||d.isPending,children:[(r.isPending||d.isPending)&&e.jsx(Ks,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),l.rule?"Update Rule":"Add Rule"]})]})]})]})})]})}function gc({policyId:s,rules:t,loading:a,sheet:l,setSheet:c}){var E;const r=Ir(),d=Kr(),h=Ur(),{can:v,must:A}=Qe(),u=v("policy","create"),p=v("policy","update"),F=v("policy","delete"),[O,m]=i.useState(""),{data:_,isLoading:q}=La({search:O||void 0}),k=(_==null?void 0:_.results)??[],x=hs({resolver:ps(xc),defaultValues:{trigger_type:"consecutive",threshold_days:3,action:"warning",notify_employee:!0,notify_manager:!1}}),Y=x.watch("action"),H=()=>{x.reset({trigger_type:"consecutive",threshold_days:3,action:"warning",notify_employee:!0,notify_manager:!1}),c({open:!0})},C=n=>{x.reset({trigger_type:n.trigger_type,threshold_days:n.threshold_days,action:n.action,leave_type:n.leave_type??void 0,leave_days:n.leave_days??void 0,deduction_amount:n.deduction_amount??void 0,deduction_type:n.deduction_type,notify_employee:n.notify_employee,notify_manager:n.notify_manager}),c({open:!0,rule:n})},N=n=>{if(!A("policy",l.rule?"update":"create"))return;const K={policy:s,trigger_type:n.trigger_type,threshold_days:n.threshold_days,action:n.action,leave_type:n.leave_type,leave_days:n.leave_days,deduction_amount:n.deduction_amount,deduction_type:n.deduction_type,notify_employee:n.notify_employee,notify_manager:n.notify_manager};(l.rule?d.mutateAsync({id:l.rule.id,...K}):r.mutateAsync(K)).then(()=>c({open:!1}))};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsxs("h3",{className:"text-[13px] font-medium text-slate-700",children:[t.length," absence rule",t.length!==1?"s":""]}),u&&e.jsxs(y,{size:"sm",onClick:H,children:[e.jsx(ds,{className:"h-3.5 w-3.5 mr-1.5"}),"Add Rule"]})]}),e.jsx(rs,{columns:[{key:"trigger_type",header:"Trigger",render:n=>e.jsx(ee,{variant:n.trigger_type==="consecutive"?"default":"secondary",className:"text-[10px]",children:n.trigger_type==="consecutive"?"Consecutive":"Total in Month"})},{key:"threshold_days",header:"Threshold",render:n=>e.jsxs("span",{className:"text-[13px] font-semibold text-slate-900",children:[n.threshold_days," day",n.threshold_days!==1?"s":""]})},{key:"action",header:"Action",render:n=>Ia(n.action)},{key:"details",header:"Details",render:n=>e.jsx("span",{className:"text-[13px] text-slate-600",children:n.action==="leave_deduction"?`${n.leave_days??0} day(s) — ${n.leave_type_name||"Any"}`:n.action==="salary_deduction"?`${n.deduction_amount??0} (${(n.deduction_type??"fixed").replace(/_/g," ")})`:"—"})},{key:"actions",header:"",className:"w-20",render:n=>e.jsxs("div",{className:"flex gap-1",children:[p&&e.jsx(y,{variant:"ghost",size:"icon-sm",onClick:()=>C(n),children:e.jsx(Ls,{className:"h-3.5 w-3.5"})}),F&&e.jsx(y,{variant:"ghost",size:"icon-sm",onClick:()=>{confirm("Delete?")&&h.mutate(n.id)},children:e.jsx(Ts,{className:"h-3.5 w-3.5 text-red-500"})})]})}],data:t,isLoading:a,emptyMessage:"No absence rules",emptyDescription:"Add rules for consecutive or total absences."}),e.jsx(He,{open:l.open,onOpenChange:n=>c({...l,open:n}),children:e.jsxs(Ge,{size:"lg",children:[e.jsxs(Be,{children:[e.jsxs(We,{children:[l.rule?"Edit":"Add"," Absence Rule"]}),e.jsx(Ze,{children:"Define what happens when absence thresholds are reached."})]}),e.jsxs("form",{onSubmit:x.handleSubmit(N),className:"space-y-4 p-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(P,{className:"text-[12px]",children:"Trigger Type"}),e.jsxs($e,{value:x.watch("trigger_type"),onValueChange:n=>x.setValue("trigger_type",n),children:[e.jsx(Le,{children:e.jsx(qe,{})}),e.jsxs(Re,{children:[e.jsx(Z,{value:"consecutive",children:"Consecutive Absences"}),e.jsx(Z,{value:"total",children:"Total Absences in Month"})]})]})]}),e.jsxs("div",{children:[e.jsx(P,{className:"text-[12px]",children:"Threshold (days)"}),e.jsx(R,{type:"number",...x.register("threshold_days")})]})]}),e.jsxs("div",{children:[e.jsx(P,{className:"text-[12px]",children:"Action"}),e.jsxs($e,{value:Y,onValueChange:n=>x.setValue("action",n),children:[e.jsx(Le,{children:e.jsx(qe,{})}),e.jsx(Re,{children:Object.entries(lt).filter(([n])=>["warning","leave_deduction","salary_deduction","disciplinary"].includes(n)).map(([n,K])=>e.jsx(Z,{value:n,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(K.icon,{className:`h-3 w-3 ${K.color}`}),K.label]})},n))})]})]}),Y==="leave_deduction"&&e.jsxs("div",{className:"rounded-lg border border-blue-200 bg-blue-50/50 p-4 space-y-3",children:[e.jsx("p",{className:"text-[11px] font-medium text-blue-700",children:"Leave Deduction Settings"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(P,{className:"text-[12px]",children:"Leave Type"}),e.jsx(ge,{value:x.watch("leave_type")??null,onValueChange:n=>x.setValue("leave_type",n),onSearch:m,isLoading:q,selectedLabel:((E=l.rule)==null?void 0:E.leave_type_name)??void 0,options:k.map(n=>({value:n.id,label:n.name,hint:n.code})),placeholder:"Select leave type",searchPlaceholder:"Search leave types..."})]}),e.jsxs("div",{children:[e.jsx(P,{className:"text-[12px]",children:"Days"}),e.jsx(R,{type:"number",step:"0.5",...x.register("leave_days")})]})]})]}),Y==="salary_deduction"&&e.jsxs("div",{className:"rounded-lg border border-red-200 bg-red-50/50 p-4 space-y-3",children:[e.jsx("p",{className:"text-[11px] font-medium text-red-700",children:"Salary Deduction Settings"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(P,{className:"text-[12px]",children:"Type"}),e.jsxs($e,{value:x.watch("deduction_type")??"fixed",onValueChange:n=>x.setValue("deduction_type",n),children:[e.jsx(Le,{children:e.jsx(qe,{})}),e.jsxs(Re,{children:[e.jsx(Z,{value:"fixed",children:"Fixed Amount"}),e.jsx(Z,{value:"percentage",children:"Percentage"}),e.jsx(Z,{value:"daily_rate",children:"Daily Rate"})]})]})]}),e.jsxs("div",{children:[e.jsx(P,{className:"text-[12px]",children:"Amount"}),e.jsx(R,{type:"number",step:"0.01",...x.register("deduction_amount")})]})]})]}),e.jsx(Ke,{}),e.jsxs("div",{className:"flex items-center gap-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ds,{checked:x.watch("notify_employee"),onCheckedChange:n=>x.setValue("notify_employee",n)}),e.jsx(P,{className:"text-[12px]",children:"Notify Employee"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ds,{checked:x.watch("notify_manager"),onCheckedChange:n=>x.setValue("notify_manager",n)}),e.jsx(P,{className:"text-[12px]",children:"Notify Manager"})]})]}),e.jsxs(us,{className:"mt-6",children:[e.jsx(y,{type:"button",variant:"outline",onClick:()=>c({open:!1}),children:"Cancel"}),e.jsxs(y,{type:"submit",disabled:r.isPending||d.isPending,children:[(r.isPending||d.isPending)&&e.jsx(Ks,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),l.rule?"Update Rule":"Add Rule"]})]})]})]})})]})}function fc({policyId:s,companyId:t,assignments:a,loading:l,sheet:c,setSheet:r}){var $,J,B,ne;const d=Gr(),h=Br(),v=Wr(),{can:A,must:u}=Qe(),p=A("policy","create"),F=A("policy","update"),O=A("policy","delete"),[m,_]=i.useState(""),{data:q,isLoading:k}=Hs({search:m||void 0}),x=hs({resolver:ps(uc),defaultValues:{company:t,effective_from:new Date().toISOString().slice(0,10),priority:10,is_active:!0}}),Y=x.watch("company"),{data:H}=ct(Y?{company:Y,page_size:100}:{page_size:100}),C=(H==null?void 0:H.results)??[],{data:N}=ft(Y?{company:Y,page_size:100}:{page_size:100}),E=(N==null?void 0:N.results)??[],{data:n}=Ta({page_size:100}),K=(n==null?void 0:n.results)??[],{data:M}=za({page_size:100}),o=(M==null?void 0:M.results)??[],L=()=>{x.reset({company:t,effective_from:new Date().toISOString().slice(0,10),priority:10,is_active:!0}),r({open:!0})},V=D=>{x.reset({company:D.company,department:D.department??void 0,branch:D.branch??void 0,grade:D.grade??void 0,category:D.category??void 0,effective_from:D.effective_from,effective_to:D.effective_to??void 0,priority:D.priority,is_active:D.is_active}),r({open:!0,item:D})},j=D=>{if(!u("policy",c.item?"update":"create"))return;const fe={policy:s,...D};(c.item?h.mutateAsync({id:c.item.id,...fe}):d.mutateAsync(fe)).then(()=>r({open:!1}))};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-[13px] font-medium text-slate-700",children:[a.length," assignment",a.length!==1?"s":""]}),e.jsx("p",{className:"text-[11px] text-slate-400 mt-0.5",children:"Define which employee segments this policy applies to. Lower priority number = higher precedence."})]}),p&&e.jsxs(y,{size:"sm",onClick:L,children:[e.jsx(ds,{className:"h-3.5 w-3.5 mr-1.5"}),"Add Assignment"]})]}),e.jsx(rs,{columns:[{key:"company",header:"Company",render:D=>e.jsx("span",{className:"text-[13px] font-medium",children:D.company_name})},{key:"segment",header:"Segment",render:D=>e.jsxs("div",{className:"flex flex-wrap gap-1",children:[D.department_name&&e.jsx(ee,{variant:"secondary",className:"text-[10px]",children:D.department_name}),D.branch_name&&e.jsx(ee,{variant:"secondary",className:"text-[10px]",children:D.branch_name}),D.grade_name&&e.jsx(ee,{variant:"secondary",className:"text-[10px]",children:D.grade_name}),D.category_name&&e.jsx(ee,{variant:"secondary",className:"text-[10px]",children:D.category_name}),!D.department_name&&!D.branch_name&&!D.grade_name&&!D.category_name&&e.jsx("span",{className:"text-[11px] text-slate-400",children:"All employees"})]})},{key:"priority",header:"Priority",className:"w-20",render:D=>e.jsxs("span",{className:"inline-flex items-center justify-center h-6 min-w-[24px] rounded bg-slate-100 text-[11px] font-semibold text-slate-700 px-1.5",children:["P",D.priority]})},{key:"effective",header:"Effective",render:D=>e.jsxs("span",{className:"text-[12px] text-slate-500",children:[D.effective_from,D.effective_to?` → ${D.effective_to}`:" onwards"]})},{key:"is_active",header:"Status",className:"w-20",render:D=>e.jsx(wt,{status:D.is_active?"active":"inactive",className:"text-[10px]"})},{key:"actions",header:"",className:"w-20",render:D=>e.jsxs("div",{className:"flex gap-1",children:[F&&e.jsx(y,{variant:"ghost",size:"icon-sm",onClick:()=>V(D),children:e.jsx(Ls,{className:"h-3.5 w-3.5"})}),O&&e.jsx(y,{variant:"ghost",size:"icon-sm",onClick:()=>{confirm("Delete?")&&v.mutate(D.id)},children:e.jsx(Ts,{className:"h-3.5 w-3.5 text-red-500"})})]})}],data:a,isLoading:l,emptyMessage:"No assignments",emptyDescription:"Assign this policy to employee segments (company, department, grade, etc.)"}),e.jsx(He,{open:c.open,onOpenChange:D=>r({...c,open:D}),children:e.jsxs(Ge,{size:"lg",children:[e.jsxs(Be,{children:[e.jsxs(We,{children:[c.item?"Edit":"Add"," Policy Assignment"]}),e.jsx(Ze,{children:"Target this policy to specific employee segments."})]}),e.jsxs("form",{onSubmit:x.handleSubmit(j),className:"space-y-4 p-4",children:[e.jsxs("div",{children:[e.jsx(P,{className:"text-[12px]",children:"Company"}),e.jsx(ge,{value:x.watch("company"),onValueChange:D=>{x.setValue("company",D),x.setValue("department",void 0),x.setValue("branch",void 0)},onSearch:_,isLoading:k,options:((q==null?void 0:q.results)??[]).map(D=>({value:D.id,label:D.name,hint:D.code})),placeholder:"Select company",searchPlaceholder:"Search companies..."})]}),e.jsx(Ke,{}),e.jsx("p",{className:"text-[11px] font-medium text-slate-500",children:"Segment Filters (leave empty = all)"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(P,{className:"text-[12px]",children:"Department"}),e.jsx(ge,{value:x.watch("department")??null,onValueChange:D=>x.setValue("department",D||void 0),selectedLabel:(($=c.item)==null?void 0:$.department_name)??void 0,options:C.map(D=>({value:D.id,label:D.name,hint:D.code})),placeholder:"All departments",searchPlaceholder:"Search departments..."})]}),e.jsxs("div",{children:[e.jsx(P,{className:"text-[12px]",children:"Branch"}),e.jsx(ge,{value:x.watch("branch")??null,onValueChange:D=>x.setValue("branch",D||void 0),selectedLabel:((J=c.item)==null?void 0:J.branch_name)??void 0,options:E.map(D=>({value:D.id,label:D.name,hint:D.code})),placeholder:"All branches",searchPlaceholder:"Search branches..."})]}),e.jsxs("div",{children:[e.jsx(P,{className:"text-[12px]",children:"Grade"}),e.jsx(ge,{value:x.watch("grade")??null,onValueChange:D=>x.setValue("grade",D||void 0),selectedLabel:((B=c.item)==null?void 0:B.grade_name)??void 0,options:K.map(D=>({value:D.id,label:D.name,hint:D.code})),placeholder:"All grades",searchPlaceholder:"Search grades..."})]}),e.jsxs("div",{children:[e.jsx(P,{className:"text-[12px]",children:"Category"}),e.jsx(ge,{value:x.watch("category")??null,onValueChange:D=>x.setValue("category",D||void 0),selectedLabel:((ne=c.item)==null?void 0:ne.category_name)??void 0,options:o.map(D=>({value:D.id,label:D.name,hint:D.code})),placeholder:"All categories",searchPlaceholder:"Search categories..."})]})]}),e.jsx(Ke,{}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(P,{className:"text-[12px]",children:"Effective From"}),e.jsx(R,{type:"date",...x.register("effective_from"),max:x.watch("effective_to")||void 0})]}),e.jsxs("div",{children:[e.jsx(P,{className:"text-[12px]",children:"Effective To"}),e.jsx(R,{type:"date",...x.register("effective_to"),min:x.watch("effective_from")||void 0}),e.jsx("p",{className:"text-[10px] text-slate-400 mt-1",children:"Leave empty for indefinite"})]}),e.jsxs("div",{children:[e.jsx(P,{className:"text-[12px]",children:"Priority"}),e.jsx(R,{type:"number",...x.register("priority")}),e.jsx("p",{className:"text-[10px] text-slate-400 mt-1",children:"Lower = higher priority"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ds,{checked:x.watch("is_active")??!0,onCheckedChange:D=>x.setValue("is_active",D)}),e.jsx(P,{className:"text-[12px]",children:"Active"})]}),e.jsxs(us,{className:"mt-6",children:[e.jsx(y,{type:"button",variant:"outline",onClick:()=>r({open:!1}),children:"Cancel"}),e.jsxs(y,{type:"submit",disabled:d.isPending||h.isPending,children:[(d.isPending||h.isPending)&&e.jsx(Ks,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),c.item?"Update":"Add Assignment"]})]})]})]})})]})}function vc({penalties:s,loading:t,processSheet:a,setProcessSheet:l}){const c=Zr(),r=Jr(),{can:d,must:h}=Qe(),v=d("penalty","create"),A=d("penalty","approve"),u=hs({resolver:ps(hc),defaultValues:{month:new Date().getMonth()+1,year:new Date().getFullYear()}}),p=_=>{h("penalty","create")&&r.mutateAsync(_).then(()=>l(!1))},F=_=>{if(!h("penalty","approve"))return;const q=prompt("Reversal reason:");q&&c.mutate({id:_.id,reason:q})},O=s.filter(_=>_.status==="applied").length,m=s.filter(_=>_.status==="reversed").length;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[e.jsx(at,{label:"Total Penalties",value:s.length,icon:os,color:"slate"}),e.jsx(at,{label:"Applied",value:O,icon:St,color:"emerald"}),e.jsx(at,{label:"Reversed",value:m,icon:Ca,color:"amber"})]}),e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsx("h3",{className:"text-[13px] font-medium text-slate-700",children:"Penalty History"}),v&&e.jsxs(y,{size:"sm",onClick:()=>{u.reset(),l(!0)},children:[e.jsx(sn,{className:"h-3.5 w-3.5 mr-1.5"}),"Process Month"]})]}),e.jsx(rs,{columns:[{key:"employee",header:"Employee",render:_=>e.jsxs("div",{children:[e.jsx("span",{className:"text-[13px] font-medium text-slate-900",children:_.employee_name}),_.employee_code&&e.jsx("p",{className:"text-[10px] text-slate-400",children:_.employee_code})]})},{key:"period",header:"Period",render:_=>e.jsxs("span",{className:"text-[12px] text-slate-600",children:[String(_.month).padStart(2,"0"),"/",_.year]})},{key:"penalty_type",header:"Type",render:_=>e.jsx(ee,{variant:"default",className:"text-[10px]",children:_.penalty_type.replace(/_/g," ")})},{key:"description",header:"Description",render:_=>e.jsx("span",{className:"text-[12px] text-slate-600 max-w-[200px] truncate block",children:_.description})},{key:"deductions",header:"Deducted",render:_=>e.jsxs("div",{className:"text-[12px]",children:[Number(_.leave_days_deducted)>0&&e.jsxs("span",{className:"text-blue-600",children:[_.leave_days_deducted,"d leave"]}),Number(_.leave_days_deducted)>0&&Number(_.salary_amount_deducted)>0&&" + ",Number(_.salary_amount_deducted)>0&&e.jsxs("span",{className:"text-red-600",children:[_.salary_amount_deducted," salary"]}),!Number(_.leave_days_deducted)&&!Number(_.salary_amount_deducted)&&e.jsx("span",{className:"text-slate-400",children:"—"})]})},{key:"status",header:"Status",render:_=>pc(_.status)},{key:"actions",header:"",className:"w-24",render:_=>A&&_.status==="applied"?e.jsxs(y,{variant:"ghost",size:"sm",className:"text-[11px] text-amber-600",onClick:()=>F(_),disabled:c.isPending,children:[e.jsx(Ca,{className:"h-3 w-3 mr-1"})," Reverse"]}):null}],data:s,isLoading:t,emptyMessage:"No penalties",emptyDescription:"Penalties appear here after monthly processing."}),e.jsx(He,{open:a,onOpenChange:l,children:e.jsxs(Ge,{size:"lg",children:[e.jsxs(Be,{children:[e.jsx(We,{children:"Process Monthly Penalties"}),e.jsx(Ze,{children:"Apply late/absence penalties based on this policy's rules for a specific month."})]}),e.jsxs("form",{onSubmit:u.handleSubmit(p),className:"space-y-4 p-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(P,{className:"text-[12px]",children:"Month"}),e.jsxs($e,{value:String(u.watch("month")),onValueChange:_=>u.setValue("month",Number(_)),children:[e.jsx(Le,{children:e.jsx(qe,{})}),e.jsx(Re,{children:["January","February","March","April","May","June","July","August","September","October","November","December"].map((_,q)=>e.jsx(Z,{value:String(q+1),children:_},q))})]})]}),e.jsxs("div",{children:[e.jsx(P,{className:"text-[12px]",children:"Year"}),e.jsx(R,{type:"number",...u.register("year")})]})]}),e.jsx("div",{className:"rounded-lg border border-amber-200 bg-amber-50/50 p-4",children:e.jsx("p",{className:"text-[11px] text-amber-700",children:"This will process attendance records for the selected month and apply penalties based on the late coming and absence rules configured for this policy."})}),e.jsxs(us,{children:[e.jsx(y,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(y,{type:"submit",disabled:r.isPending,children:[r.isPending&&e.jsx(Ks,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),e.jsx(sn,{className:"h-3.5 w-3.5 mr-1.5"})," Process"]})]})]})]})})]})}const Ut=X().regex(/^\d+(\.\d+)?$/,"Enter a valid number"),_c=ys({name:X().min(1,"Policy name is required"),company:X().min(1,"Company is required"),branch:X().optional().nullable(),is_active:es(),grace_period_minutes:De.number().min(0).max(120),grace_counts_as_worked:es(),late_threshold_minutes:De.number().min(0).max(240),early_threshold_minutes:De.number().min(0).max(120),half_day_min_minutes:De.number().min(0).max(480),absent_max_minutes:De.number().min(0).max(240),overtime_eligible:es(),overtime_min_minutes:De.number().min(0),overtime_daily_max_minutes:De.number().min(0),overtime_weekly_max_minutes:De.number().min(0),ot_multiplier_regular:Ut,ot_multiplier_weekend:Ut,ot_multiplier_holiday:Ut,compoff_hours_per_day:De.number().min(0),compoff_validity_days:De.number().min(0),compoff_carry_forward_limit:De.number().min(0),regularization_window_days:De.number().min(0),auto_approve_late_minutes:De.number().min(0),flexi_time_enabled:es(),flexi_core_start:X().optional().nullable(),flexi_core_end:X().optional().nullable(),flexi_window_minutes:De.number().min(0),geofencing_enabled:es(),geofence_tolerance_meters:De.number().min(0),penalty_processing_mode:Ns(["manual","auto"]),late_reset_period:Ns(["monthly","quarterly"]),short_leave_enabled:es(),short_leave_max_hours:Ut,short_leave_max_per_month:De.number().min(0)}).superRefine((s,t)=>{s.flexi_time_enabled&&(s.flexi_core_start||t.addIssue({code:en.custom,path:["flexi_core_start"],message:"Core start time is required when flexi-time is enabled"}),s.flexi_core_end||t.addIssue({code:en.custom,path:["flexi_core_end"],message:"Core end time is required when flexi-time is enabled"}))}),Ht=[{label:"Basic Info",description:"Name & company",icon:St},{label:"Thresholds",description:"Grace & late",icon:ss},{label:"Overtime",description:"OT rules",icon:pt},{label:"Comp-Off",description:"Regularization",icon:ha},{label:"Flexi & Geo",description:"Location",icon:jt},{label:"Penalties",description:"Short leave",icon:os}],bc={name:"",company:"",branch:null,is_active:!0,grace_period_minutes:15,grace_counts_as_worked:!1,late_threshold_minutes:30,early_threshold_minutes:15,half_day_min_minutes:240,absent_max_minutes:60,overtime_eligible:!0,overtime_min_minutes:30,overtime_daily_max_minutes:180,overtime_weekly_max_minutes:600,ot_multiplier_regular:"1.5",ot_multiplier_weekend:"2.0",ot_multiplier_holiday:"2.5",compoff_hours_per_day:8,compoff_validity_days:90,compoff_carry_forward_limit:3,regularization_window_days:7,auto_approve_late_minutes:10,flexi_time_enabled:!1,flexi_core_start:null,flexi_core_end:null,flexi_window_minutes:120,geofencing_enabled:!1,geofence_tolerance_meters:100,penalty_processing_mode:"manual",late_reset_period:"monthly",short_leave_enabled:!1,short_leave_max_hours:"2.0",short_leave_max_per_month:2},_t=({icon:s,children:t})=>e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx("div",{className:"h-8 w-8 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(s,{className:"h-4 w-4 text-primary"})}),e.jsx("h3",{className:"text-[14px] font-semibold text-slate-900",children:t})]}),Pe=({label:s,description:t,children:a})=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(P,{className:"text-[13px] font-medium text-slate-700",children:s}),t&&e.jsx("p",{className:"text-[11px] text-slate-400 -mt-0.5",children:t}),a]}),Pt=({label:s,description:t,checked:a,onChange:l})=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-slate-200 px-4 py-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[13px] font-medium text-slate-700",children:s}),t&&e.jsx("p",{className:"text-[11px] text-slate-400 mt-0.5",children:t})]}),e.jsx(Ds,{checked:a,onCheckedChange:l})]});function Sd(){const{id:s}=ra(),t=!!s&&s!=="new",a=qt(),[l,c]=i.useState(0),{data:r,isLoading:d}=Hn(t?s:""),h=Fr(),v=Er(),{must:A}=Qe(),[u,p]=i.useState(""),{data:F,isLoading:O}=Hs({search:u||void 0}),m=hs({resolver:ps(_c),defaultValues:bc,mode:"onTouched"}),_=m.watch("company"),{data:q}=ft(_?{company:_,page_size:100}:void 0),k=(q==null?void 0:q.results)??[];i.useEffect(()=>{r&&t&&m.reset({name:r.name,company:r.company,branch:r.branch,is_active:r.is_active,grace_period_minutes:r.grace_period_minutes,grace_counts_as_worked:r.grace_counts_as_worked??!1,late_threshold_minutes:r.late_threshold_minutes,early_threshold_minutes:r.early_threshold_minutes,half_day_min_minutes:r.half_day_min_minutes,absent_max_minutes:r.absent_max_minutes,overtime_eligible:r.overtime_eligible,overtime_min_minutes:r.overtime_min_minutes,overtime_daily_max_minutes:r.overtime_daily_max_minutes,overtime_weekly_max_minutes:r.overtime_weekly_max_minutes,ot_multiplier_regular:r.ot_multiplier_regular,ot_multiplier_weekend:r.ot_multiplier_weekend,ot_multiplier_holiday:r.ot_multiplier_holiday,compoff_hours_per_day:r.compoff_hours_per_day,compoff_validity_days:r.compoff_validity_days,compoff_carry_forward_limit:r.compoff_carry_forward_limit,regularization_window_days:r.regularization_window_days,auto_approve_late_minutes:r.auto_approve_late_minutes,flexi_time_enabled:r.flexi_time_enabled,flexi_core_start:r.flexi_core_start,flexi_core_end:r.flexi_core_end,flexi_window_minutes:r.flexi_window_minutes,geofencing_enabled:r.geofencing_enabled,geofence_tolerance_meters:r.geofence_tolerance_meters,penalty_processing_mode:r.penalty_processing_mode,late_reset_period:r.late_reset_period,short_leave_enabled:r.short_leave_enabled,short_leave_max_hours:r.short_leave_max_hours,short_leave_max_per_month:r.short_leave_max_per_month})},[r,t,m]);const x=h.isPending||v.isPending,Y=[["name","company"],["grace_period_minutes","late_threshold_minutes","early_threshold_minutes","half_day_min_minutes"],["overtime_eligible"],["compoff_hours_per_day","regularization_window_days"],["flexi_time_enabled","geofencing_enabled"],["penalty_processing_mode","late_reset_period"]],H=async()=>{const L=Y[l];await m.trigger(L)&&l<Ht.length-1&&c(l+1)},C=()=>{l>0&&c(l-1)},N=L=>{if(!A("policy",t?"update":"create"))return;const V={...L,branch:L.branch||void 0,flexi_core_start:L.flexi_time_enabled?L.flexi_core_start:null,flexi_core_end:L.flexi_time_enabled?L.flexi_core_end:null};t?v.mutateAsync({id:s,...V}).then(()=>a(`/attendance/policies/${s}`)):h.mutateAsync(V).then(j=>a(`/attendance/policies/${j.id}`))};if(t&&d)return e.jsxs("div",{className:"p-6 space-y-4",children:[e.jsx("div",{className:"h-9 w-48 rounded bg-slate-200 animate-pulse"}),e.jsx("div",{className:"h-64 rounded bg-slate-200 animate-pulse"})]});const E=m.watch("flexi_time_enabled"),n=m.watch("geofencing_enabled"),K=m.watch("overtime_eligible"),M=m.watch("short_leave_enabled"),o=m.formState.errors;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(y,{variant:"ghost",size:"icon-sm",onClick:()=>a("/attendance/policies"),children:e.jsx(gt,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-[16px] font-semibold text-slate-900",children:t?"Edit Policy":"Create Attendance Policy"}),e.jsx("p",{className:"text-[11px] text-slate-400",children:t?`Editing ${(r==null?void 0:r.name)??""}`:"Configure a new attendance policy for your organization"})]})]}),e.jsx(ye,{children:e.jsx(je,{className:"p-5",children:e.jsx(fl,{steps:Ht,currentStep:l,onStepClick:L=>L<l&&c(L)})})}),e.jsxs("form",{onSubmit:m.handleSubmit(N),children:[e.jsx(ye,{children:e.jsxs(je,{className:"p-6",children:[l===0&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(_t,{icon:St,children:"Basic Information"}),e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs(Pe,{label:"Policy Name",description:"A descriptive name for this policy",children:[e.jsx(R,{...m.register("name"),placeholder:"e.g. Standard Office Policy",className:o.name?"border-red-400":""}),o.name&&e.jsx("p",{className:"text-[11px] text-red-500 mt-1",children:o.name.message})]}),e.jsxs(Pe,{label:"Company",description:"Which company this policy belongs to",children:[e.jsx(ge,{value:m.watch("company"),onValueChange:L=>{m.setValue("company",L),m.setValue("branch",null)},onSearch:p,isLoading:O,options:((F==null?void 0:F.results)??[]).map(L=>({value:L.id,label:L.name,hint:L.code})),placeholder:"Select company",searchPlaceholder:"Search companies...",className:o.company?"border-red-400":""}),o.company&&e.jsx("p",{className:"text-[11px] text-red-500 mt-1",children:o.company.message})]}),e.jsx(Pe,{label:"Branch",description:"Optional — leave empty for all branches",children:e.jsx(ge,{value:m.watch("branch")??null,onValueChange:L=>m.setValue("branch",L||null),selectedLabel:(r==null?void 0:r.branch_name)??void 0,options:k.map(L=>({value:L.id,label:L.name,hint:L.code})),placeholder:"All branches",searchPlaceholder:"Search branches..."})}),e.jsx(Pe,{label:"Status",children:e.jsxs("div",{className:"flex items-center gap-3 mt-2",children:[e.jsx(Ds,{checked:m.watch("is_active"),onCheckedChange:L=>m.setValue("is_active",L)}),e.jsx(ee,{variant:m.watch("is_active")?"success":"secondary",children:m.watch("is_active")?"Active":"Inactive"})]})})]})]}),l===1&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(_t,{icon:ss,children:"Time Thresholds"}),e.jsx("p",{className:"text-[12px] text-slate-500 -mt-3 mb-4",children:"Define grace periods and thresholds for marking attendance status."}),e.jsxs("div",{className:"rounded-xl border border-slate-200 bg-slate-50/50 p-5",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-slate-400 mb-3",children:"How It Works"}),e.jsxs("div",{className:"flex items-center gap-2 text-[12px]",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"h-3 w-3 rounded-full bg-emerald-500"}),e.jsx("span",{className:"text-slate-600",children:"On Time"})]}),e.jsx(Vs,{className:"h-3 w-3 text-slate-300"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"h-3 w-3 rounded-full bg-amber-500"}),e.jsxs("span",{className:"text-slate-600",children:["Grace (",m.watch("grace_period_minutes"),"m)"]})]}),e.jsx(Vs,{className:"h-3 w-3 text-slate-300"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"h-3 w-3 rounded-full bg-orange-500"}),e.jsxs("span",{className:"text-slate-600",children:["Late (",m.watch("late_threshold_minutes"),"m)"]})]}),e.jsx(Vs,{className:"h-3 w-3 text-slate-300"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"h-3 w-3 rounded-full bg-blue-500"}),e.jsxs("span",{className:"text-slate-600",children:["Half-Day (<",m.watch("half_day_min_minutes"),"m)"]})]}),e.jsx(Vs,{className:"h-3 w-3 text-slate-300"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"h-3 w-3 rounded-full bg-red-500"}),e.jsxs("span",{className:"text-slate-600",children:["Absent (<",m.watch("absent_max_minutes"),"m)"]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-6",children:[e.jsx(Pe,{label:"Grace Period (minutes)",description:"Time after shift start before marking late",children:e.jsx(R,{type:"number",...m.register("grace_period_minutes")})}),e.jsx(Pe,{label:"Late Threshold (minutes)",description:"Minutes late to be marked as Late",children:e.jsx(R,{type:"number",...m.register("late_threshold_minutes")})}),e.jsx(Pe,{label:"Early Exit Threshold (minutes)",description:"Minutes before shift end for early exit",children:e.jsx(R,{type:"number",...m.register("early_threshold_minutes")})})]}),e.jsx(Pt,{label:"Count grace period as worked time",description:"Credits minutes forgiven by the grace period toward the day, so an arrival within grace cannot reduce it to a half day. Off: grace only prevents the late mark, and the minutes still count against required hours.",checked:m.watch("grace_counts_as_worked"),onChange:L=>m.setValue("grace_counts_as_worked",L)}),e.jsx(Ke,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs(Pe,{label:"Half-Day Minimum (minutes)",description:"Minimum working minutes to get half-day credit",children:[e.jsx(R,{type:"number",...m.register("half_day_min_minutes")}),e.jsxs("p",{className:"text-[11px] text-slate-400 mt-1",children:["= ",Math.floor(m.watch("half_day_min_minutes")/60),"h ",m.watch("half_day_min_minutes")%60,"m"]})]}),e.jsx(Pe,{label:"Absent Threshold (minutes)",description:"Below this = marked absent (0 = use shift default)",children:e.jsx(R,{type:"number",...m.register("absent_max_minutes")})})]})]}),l===2&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(_t,{icon:pt,children:"Overtime Settings"}),e.jsx(Pt,{label:"Overtime Eligible",description:"Enable overtime tracking and calculations for employees under this policy",checked:K,onChange:L=>m.setValue("overtime_eligible",L)}),K&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 gap-6",children:[e.jsx(Pe,{label:"Minimum OT (minutes)",description:"Minimum minutes to qualify for OT",children:e.jsx(R,{type:"number",...m.register("overtime_min_minutes")})}),e.jsx(Pe,{label:"Daily Max OT (minutes)",description:"Maximum OT allowed per day",children:e.jsx(R,{type:"number",...m.register("overtime_daily_max_minutes")})}),e.jsx(Pe,{label:"Weekly Max OT (minutes)",description:"Maximum OT allowed per week",children:e.jsx(R,{type:"number",...m.register("overtime_weekly_max_minutes")})})]}),e.jsx(Ke,{}),e.jsx("p",{className:"text-[12px] font-medium text-slate-600",children:"OT Rate Multipliers"}),e.jsxs("div",{className:"grid grid-cols-3 gap-6",children:[e.jsx(Pe,{label:"Regular Day",description:"e.g. 1.5 = 150% pay",children:e.jsxs("div",{className:"relative",children:[e.jsx(R,{...m.register("ot_multiplier_regular"),className:"pr-6"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-[11px] text-slate-400",children:"x"})]})}),e.jsx(Pe,{label:"Weekend",description:"e.g. 2.0 = 200% pay",children:e.jsxs("div",{className:"relative",children:[e.jsx(R,{...m.register("ot_multiplier_weekend"),className:"pr-6"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-[11px] text-slate-400",children:"x"})]})}),e.jsx(Pe,{label:"Holiday",description:"e.g. 2.5 = 250% pay",children:e.jsxs("div",{className:"relative",children:[e.jsx(R,{...m.register("ot_multiplier_holiday"),className:"pr-6"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-[11px] text-slate-400",children:"x"})]})})]})]}),!K&&e.jsxs("div",{className:"rounded-lg border border-dashed border-slate-300 bg-slate-50 p-6 text-center",children:[e.jsx(pt,{className:"h-6 w-6 text-slate-300 mx-auto mb-2"}),e.jsx("p",{className:"text-[13px] text-slate-500",children:"Overtime tracking is disabled for this policy."}),e.jsx("p",{className:"text-[11px] text-slate-400 mt-1",children:"Employees won't accrue overtime hours or compensation."})]})]}),l===3&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(_t,{icon:ha,children:"Comp-Off & Regularization"}),e.jsxs("div",{className:"grid grid-cols-3 gap-6",children:[e.jsx(Pe,{label:"Comp-Off Hours/Day",description:"Hours worked = 1 comp-off day",children:e.jsx(R,{type:"number",...m.register("compoff_hours_per_day")})}),e.jsx(Pe,{label:"Validity (days)",description:"Days before comp-off expires",children:e.jsx(R,{type:"number",...m.register("compoff_validity_days")})}),e.jsx(Pe,{label:"Carry Forward Limit",description:"Max comp-offs carried to next period",children:e.jsx(R,{type:"number",...m.register("compoff_carry_forward_limit")})})]}),e.jsx(Ke,{}),e.jsx("p",{className:"text-[12px] font-medium text-slate-600",children:"Regularization Settings"}),e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsx(Pe,{label:"Regularization Window (days)",description:"Days after attendance date to submit regularization",children:e.jsx(R,{type:"number",...m.register("regularization_window_days")})}),e.jsx(Pe,{label:"Auto-Approve Late (minutes)",description:"Late entries below this are auto-approved",children:e.jsx(R,{type:"number",...m.register("auto_approve_late_minutes")})})]})]}),l===4&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(_t,{icon:jt,children:"Flexi-Time & Geofencing"}),e.jsx(Pt,{label:"Flexible Working Hours",description:"Allow employees to choose their check-in/out times within a window",checked:E,onChange:L=>m.setValue("flexi_time_enabled",L)}),E&&e.jsxs("div",{className:"rounded-lg border border-blue-200 bg-blue-50/50 p-5 space-y-4",children:[e.jsx("p",{className:"text-[12px] font-medium text-blue-700",children:"Core Hours Configuration"}),e.jsxs("div",{className:"grid grid-cols-3 gap-6",children:[e.jsx(Pe,{label:"Core Start Time",description:"Mandatory start time",children:e.jsx(R,{type:"time",...m.register("flexi_core_start")})}),e.jsx(Pe,{label:"Core End Time",description:"Mandatory end time",children:e.jsx(R,{type:"time",...m.register("flexi_core_end")})}),e.jsx(Pe,{label:"Flexi Window (minutes)",description:"Allowed flexibility around core hours",children:e.jsx(R,{type:"number",...m.register("flexi_window_minutes")})})]})]}),e.jsx(Ke,{}),e.jsx(Pt,{label:"Geofencing",description:"Restrict check-in/out to specific geographic locations",checked:n,onChange:L=>m.setValue("geofencing_enabled",L)}),n&&e.jsx("div",{className:"rounded-lg border border-emerald-200 bg-emerald-50/50 p-5",children:e.jsx(Pe,{label:"Tolerance Radius (meters)",description:"How far from the geofence center a punch is accepted",children:e.jsx(R,{type:"number",...m.register("geofence_tolerance_meters"),className:"max-w-[200px]"})})})]}),l===5&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(_t,{icon:os,children:"Penalty Processing & Short Leave"}),e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsx(Pe,{label:"Penalty Processing Mode",description:"How late/absence penalties are applied",children:e.jsxs($e,{value:m.watch("penalty_processing_mode"),onValueChange:L=>m.setValue("penalty_processing_mode",L),children:[e.jsx(Le,{children:e.jsx(qe,{})}),e.jsxs(Re,{children:[e.jsx(Z,{value:"manual",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:"Manual"}),e.jsx("span",{className:"text-[10px] text-slate-400",children:"HR reviews and applies penalties"})]})}),e.jsx(Z,{value:"auto",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:"Automatic"}),e.jsx("span",{className:"text-[10px] text-slate-400",children:"System auto-applies at month end"})]})})]})]})}),e.jsx(Pe,{label:"Late Count Reset Period",description:"When the late count resets to zero",children:e.jsxs($e,{value:m.watch("late_reset_period"),onValueChange:L=>m.setValue("late_reset_period",L),children:[e.jsx(Le,{children:e.jsx(qe,{})}),e.jsxs(Re,{children:[e.jsx(Z,{value:"monthly",children:"Monthly"}),e.jsx(Z,{value:"quarterly",children:"Quarterly"})]})]})})]}),e.jsx(Ke,{}),e.jsx(Pt,{label:"Short Leave",description:"Allow employees to take short leaves (1-4 hours) without full leave deduction",checked:M,onChange:L=>m.setValue("short_leave_enabled",L)}),M&&e.jsx("div",{className:"rounded-lg border border-violet-200 bg-violet-50/50 p-5",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsx(Pe,{label:"Max Hours per Short Leave",children:e.jsx(R,{...m.register("short_leave_max_hours"),className:"max-w-[200px]"})}),e.jsx(Pe,{label:"Max Short Leaves per Month",children:e.jsx(R,{type:"number",...m.register("short_leave_max_per_month"),className:"max-w-[200px]"})})]})}),e.jsxs("div",{className:"rounded-xl border border-slate-200 bg-slate-50/50 p-5 mt-6",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-slate-400 mb-3",children:"Policy Preview"}),e.jsxs("div",{className:"grid grid-cols-4 gap-4 text-[12px]",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-slate-400",children:"Grace"}),e.jsxs("p",{className:"font-semibold text-slate-900",children:[m.watch("grace_period_minutes")," min"]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-slate-400",children:"Late"}),e.jsxs("p",{className:"font-semibold text-slate-900",children:[m.watch("late_threshold_minutes")," min"]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-slate-400",children:"Half-Day"}),e.jsxs("p",{className:"font-semibold text-slate-900",children:[m.watch("half_day_min_minutes")," min"]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-slate-400",children:"OT"}),e.jsx("p",{className:"font-semibold text-slate-900",children:m.watch("overtime_eligible")?"Yes":"No"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-slate-400",children:"Flexi"}),e.jsx("p",{className:"font-semibold text-slate-900",children:m.watch("flexi_time_enabled")?"Yes":"No"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-slate-400",children:"Geofencing"}),e.jsx("p",{className:"font-semibold text-slate-900",children:m.watch("geofencing_enabled")?"Yes":"No"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-slate-400",children:"Penalty"}),e.jsx("p",{className:"font-semibold text-slate-900 capitalize",children:m.watch("penalty_processing_mode")})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-slate-400",children:"Reset"}),e.jsx("p",{className:"font-semibold text-slate-900 capitalize",children:m.watch("late_reset_period")})]})]})]})]})]})}),e.jsxs("div",{className:"flex items-center justify-between mt-4",children:[e.jsxs(y,{type:"button",variant:"outline",size:"sm",onClick:C,disabled:l===0,children:[e.jsx(gt,{className:"h-3.5 w-3.5 mr-1.5"})," Previous"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-[11px] text-slate-400",children:["Step ",l+1," of ",Ht.length]}),l<Ht.length-1?e.jsxs(y,{type:"button",size:"sm",onClick:H,children:["Next ",e.jsx(ta,{className:"h-3.5 w-3.5 ml-1.5"})]}):e.jsxs(y,{type:"submit",size:"sm",disabled:x,children:[x&&e.jsx(Ks,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),e.jsx(st,{className:"h-3.5 w-3.5 mr-1.5"}),t?"Update Policy":"Create Policy"]})]})]})]})]})}const Nc=ys({name:X().min(1,"Name is required"),company:X().min(1,"Company is required"),latitude:De.number().min(-90).max(90),longitude:De.number().min(-180).max(180),radius_meters:De.number().min(10,"Minimum 10 meters"),address:X().optional(),branch:X().optional().nullable(),is_active:es().default(!0)});function kd(){const[s,t]=i.useState(!1),[a,l]=i.useState(null),{pagination:c,setPagination:r,sorting:d,setSorting:h,globalFilter:v,setGlobalFilter:A,queryParams:u}=$s(),{data:p,isLoading:F}=Xr(u),O=(p==null?void 0:p.results)??[],m=ei(),_=si(),q=ti(),{can:k,must:x}=Qe(),Y=k("geofence","create"),H=k("geofence","update"),C=k("geofence","delete"),[N,E]=i.useState(""),{data:n,isLoading:K}=Hs({search:N||void 0}),M=(n==null?void 0:n.results)??[],o=hs({resolver:ps(Nc),defaultValues:{radius_meters:100,is_active:!0}});function L(){l(null),o.reset({radius_meters:100,is_active:!0,company:""}),t(!0)}function V(B){l(B),o.reset({name:B.name,company:B.company??"",latitude:B.latitude,longitude:B.longitude,radius_meters:B.radius_meters,address:B.address,branch:B.branch,is_active:B.is_active}),t(!0)}function j(B){if(!x("geofence",a?"update":"create"))return;const ne={...B,address:B.address??"",branch:B.branch||null,company:B.company};a?_.mutate({id:a.id,...ne},{onSuccess:()=>t(!1)}):m.mutate(ne,{onSuccess:()=>t(!1)})}function $(B){x("geofence","delete")&&q.mutate(B)}const J=[{key:"name",header:"Zone Name",render:B=>e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-slate-900",children:B.name}),B.address&&e.jsx("p",{className:"text-[11px] text-slate-400 mt-0.5 truncate max-w-[250px]",children:B.address})]})},{key:"coordinates",header:"Coordinates",render:B=>e.jsxs("span",{className:"text-[12px] text-slate-500 font-mono",children:[B.latitude.toFixed(6),", ",B.longitude.toFixed(6)]})},{key:"radius",header:"Radius",render:B=>e.jsxs("span",{className:"text-[13px] text-slate-600",children:[B.radius_meters,"m"]})},{key:"branch",header:"Branch",render:B=>e.jsx("span",{className:"text-[13px] text-slate-500",children:B.branch_name??"—"})},{key:"employees",header:"Employees",render:B=>e.jsx("span",{className:"text-[13px] text-slate-600",children:B.employee_count})},{key:"status",header:"Status",render:B=>e.jsx(wt,{status:B.is_active?"active":"inactive"})},{key:"actions",header:"",className:"w-10",render:B=>!H&&!C?null:e.jsxs(fs,{children:[e.jsx(vs,{asChild:!0,children:e.jsx(y,{variant:"ghost",size:"icon-sm",children:e.jsx(Us,{className:"h-4 w-4"})})}),e.jsxs(_s,{align:"end",children:[H&&e.jsxs(Ce,{onClick:()=>V(B),children:[e.jsx(Ls,{className:"mr-2 h-3.5 w-3.5"})," Edit"]}),C&&e.jsxs(Ce,{className:"text-red-600",onClick:()=>$(B.id),children:[e.jsx(Ts,{className:"mr-2 h-3.5 w-3.5"})," Delete"]})]})]})}];return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-[16px] font-semibold text-slate-900 flex items-center gap-2",children:[e.jsx(jt,{className:"h-5 w-5 text-primary"})," Geofence Zones"]}),e.jsx("p",{className:"mt-0.5 text-[13px] text-slate-400",children:"Define geofence boundaries for location-based attendance"})]}),Y&&e.jsxs(y,{size:"sm",onClick:L,children:[e.jsx(ds,{className:"mr-1.5 h-3.5 w-3.5"})," Add Zone"]})]}),e.jsx(rs,{columns:J,data:O,isLoading:F,searchPlaceholder:"Search geofence zones...",emptyMessage:"No geofence zones",emptyDescription:"Create your first geofence zone.",totalCount:(p==null?void 0:p.count)??0,pagination:c,onPaginationChange:r,sorting:d,onSortingChange:h,globalFilter:v,onGlobalFilterChange:A}),e.jsx(He,{open:s,onOpenChange:t,children:e.jsxs(Ge,{size:"md",children:[e.jsxs(Be,{children:[e.jsx(We,{children:a?"Edit Zone":"Add Geofence Zone"}),e.jsx(Ze,{children:a?"Update zone details.":"Define a new geofence boundary."})]}),e.jsxs("form",{onSubmit:o.handleSubmit(j),className:"flex-1 overflow-y-auto px-6 py-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx(P,{children:"Zone Name *"}),e.jsx(R,{...o.register("name"),className:"mt-1.5"}),o.formState.errors.name&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:o.formState.errors.name.message})]}),e.jsxs("div",{children:[e.jsx(P,{children:"Company *"}),e.jsx("div",{className:"mt-1.5",children:e.jsx(ge,{value:o.watch("company"),onValueChange:B=>o.setValue("company",B,{shouldValidate:!0}),onSearch:E,isLoading:K,options:M.map(B=>({value:B.id,label:B.name,hint:B.code})),placeholder:"Select company",searchPlaceholder:"Search companies..."})}),o.formState.errors.company&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:o.formState.errors.company.message})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(P,{children:"Latitude *"}),e.jsx(R,{type:"number",step:"any",...o.register("latitude"),className:"mt-1.5",placeholder:"e.g. 12.971599"}),o.formState.errors.latitude&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:o.formState.errors.latitude.message})]}),e.jsxs("div",{children:[e.jsx(P,{children:"Longitude *"}),e.jsx(R,{type:"number",step:"any",...o.register("longitude"),className:"mt-1.5",placeholder:"e.g. 77.594566"}),o.formState.errors.longitude&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:o.formState.errors.longitude.message})]})]}),e.jsxs("div",{children:[e.jsx(P,{children:"Radius (meters) *"}),e.jsx(R,{type:"number",...o.register("radius_meters"),className:"mt-1.5"}),o.formState.errors.radius_meters&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:o.formState.errors.radius_meters.message})]}),e.jsxs("div",{children:[e.jsx(P,{children:"Address"}),e.jsx(R,{...o.register("address"),className:"mt-1.5",placeholder:"Optional address description"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-[13px] text-slate-600",children:[e.jsx("input",{type:"checkbox",...o.register("is_active"),className:"rounded border-slate-300"}),"Active"]})]}),e.jsxs(us,{children:[e.jsx(y,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(y,{onClick:o.handleSubmit(j),disabled:m.isPending||_.isPending,children:a?"Save Changes":"Create Zone"})]})]})})]})}const wc=ys({company:X().min(1,"Company is required"),branch:X().optional().nullable(),fiscal_year:X().min(1,"Fiscal year is required"),is_published:es().default(!1)}),Sc=ys({date:X().min(1,"Date is required"),name:X().min(1,"Holiday name is required"),holiday_type:Ns(["national","company","regional","optional","festival"]),states:kl(X()).default([]),is_restricted:es().default(!1),is_floating:es().default(!1)}),kc={national:"National",company:"Company",regional:"Regional",optional:"Optional",festival:"Festival"},Cc={national:"default",company:"success",regional:"secondary",optional:"warning",festival:"warning"};function el(s){const t=[];return s.company_name&&t.push(s.company_name),s.branch_name&&t.push(s.branch_name),t.push(s.fiscal_year_name),t.join(" — ")}function Cd(){const[s,t]=i.useState(!1),[a,l]=i.useState(null),[c,r]=i.useState(null),[d,h]=i.useState(!1),{pagination:v,setPagination:A,sorting:u,setSorting:p,globalFilter:F,setGlobalFilter:O,queryParams:m}=$s(),{data:_,isLoading:q}=ai(m),k=(_==null?void 0:_.results)??[],x=ni(),Y=li(),H=ri(),{can:C,must:N}=Qe(),E=C("attendance","create"),n=C("attendance","update"),K=C("attendance","delete"),M=hs({resolver:ps(wc),defaultValues:{company:"",branch:null,fiscal_year:"",is_published:!1}}),o=M.watch("company"),[L,V]=i.useState(""),{data:j,isLoading:$}=Hs({is_active:!0,search:L||void 0}),{data:J}=ft(o?{company:o,is_active:!0}:{is_active:!0}),B=(J==null?void 0:J.results)??[],{data:ne,isLoading:D}=Fl(o?{company:o}:void 0),fe=(ne==null?void 0:ne.results)??[];function Q(){l(null),M.reset({is_published:!1,company:"",branch:null,fiscal_year:""}),t(!0)}function oe(S){l(S),M.reset({company:S.company??"",branch:S.branch,fiscal_year:S.fiscal_year,is_published:S.is_published}),t(!0)}function Se(S){if(!N("attendance",a?"update":"create"))return;const de={...S,branch:S.branch||null};a?Y.mutate({id:a.id,...de},{onSuccess:()=>t(!1)}):x.mutate(de,{onSuccess:()=>t(!1)})}function Te(S){N("attendance","delete")&&H.mutate(S)}const I=[{key:"calendar",header:"Calendar",render:S=>e.jsx("span",{className:"font-medium text-slate-900",children:el(S)})},{key:"company",header:"Company",render:S=>e.jsx("span",{className:"text-[13px] text-slate-600",children:S.company_name??"—"})},{key:"branch",header:"Branch",render:S=>e.jsx("span",{className:"text-[13px] text-slate-500",children:S.branch_name??"—"})},{key:"fiscal_year",header:"Fiscal Year",render:S=>e.jsx("span",{className:"text-[13px] text-slate-700 font-medium",children:S.fiscal_year_name})},{key:"holiday_count",header:"Holidays",render:S=>e.jsxs(ee,{variant:"secondary",children:[S.holiday_count??0," holidays"]})},{key:"is_published",header:"Published",render:S=>e.jsx(ee,{variant:S.is_published?"success":"secondary",children:S.is_published?"Published":"Draft"})},{key:"actions",header:"",className:"w-10",render:S=>e.jsxs(fs,{children:[e.jsx(vs,{asChild:!0,children:e.jsx(y,{variant:"ghost",size:"icon-sm",children:e.jsx(Us,{className:"h-4 w-4"})})}),e.jsxs(_s,{align:"end",children:[e.jsxs(Ce,{onClick:()=>{r(S),h(!1)},children:[e.jsx(ua,{className:"mr-2 h-3.5 w-3.5"})," Manage Holidays"]}),n&&e.jsxs(Ce,{onClick:()=>oe(S),children:[e.jsx(Ls,{className:"mr-2 h-3.5 w-3.5"})," Edit"]}),K&&e.jsxs(Ce,{className:"text-red-600",onClick:()=>Te(S.id),children:[e.jsx(Ts,{className:"mr-2 h-3.5 w-3.5"})," Delete"]})]})]})}];return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-[16px] font-semibold text-slate-900 flex items-center gap-2",children:[e.jsx(Pa,{className:"h-5 w-5 text-primary"})," Work Calendar"]}),e.jsx("p",{className:"mt-0.5 text-[13px] text-slate-400",children:"Manage work calendars and holiday schedules"})]}),E&&e.jsxs(y,{size:"sm",onClick:Q,children:[e.jsx(ds,{className:"mr-1.5 h-3.5 w-3.5"})," New Calendar"]})]}),e.jsx(rs,{columns:I,data:k,isLoading:q,searchPlaceholder:"Search calendars...",emptyMessage:"No work calendars",emptyDescription:"Create your first work calendar to define working days and holidays.",totalCount:(_==null?void 0:_.count)??0,pagination:v,onPaginationChange:A,sorting:u,onSortingChange:p,globalFilter:F,onGlobalFilterChange:O}),e.jsx(He,{open:s,onOpenChange:t,children:e.jsxs(Ge,{size:"md",children:[e.jsxs(Be,{children:[e.jsx(We,{children:a?"Edit Work Calendar":"New Work Calendar"}),e.jsx(Ze,{children:a?"Update calendar configuration.":"Create a new work calendar."})]}),e.jsxs("form",{onSubmit:M.handleSubmit(Se),className:"flex-1 overflow-y-auto px-6 py-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(P,{children:"Company *"}),e.jsx("div",{className:"mt-1.5",children:e.jsx(ge,{value:o??"",onValueChange:S=>{M.setValue("company",S),M.setValue("branch",null),M.setValue("fiscal_year","")},onSearch:V,isLoading:$,options:((j==null?void 0:j.results)??[]).map(S=>({value:S.id,label:S.name,hint:S.code})),placeholder:"Select company",searchPlaceholder:"Search companies..."})}),M.formState.errors.company&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:M.formState.errors.company.message})]}),e.jsxs("div",{children:[e.jsx(P,{children:"Branch"}),e.jsx("div",{className:"mt-1.5",children:e.jsx(ge,{value:M.watch("branch")??null,onValueChange:S=>M.setValue("branch",S||null),selectedLabel:(a==null?void 0:a.branch_name)??void 0,options:B.map(S=>({value:S.id,label:S.name,hint:S.code})),placeholder:"All branches",searchPlaceholder:"Search branches..."})})]})]}),e.jsxs("div",{children:[e.jsx(P,{children:"Fiscal Year *"}),e.jsx("div",{className:"mt-1.5",children:e.jsx(ge,{value:M.watch("fiscal_year")||null,onValueChange:S=>M.setValue("fiscal_year",S,{shouldValidate:!0}),selectedLabel:(a==null?void 0:a.fiscal_year_name)??void 0,isLoading:D,options:fe.map(S=>({value:S.id,label:S.name})),placeholder:o?"Select fiscal year":"Select a company first",searchPlaceholder:"Search fiscal years...",disabled:!o})}),M.formState.errors.fiscal_year&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:M.formState.errors.fiscal_year.message}),o&&!D&&fe.length===0&&e.jsx("p",{className:"mt-1 text-[11px] text-amber-600",children:"No fiscal years for this company yet — create one under System Admin → Fiscal Years first."})]}),e.jsx("div",{className:"flex items-center gap-6 pt-2",children:e.jsxs("label",{className:"flex items-center gap-2 text-[13px] text-slate-600",children:[e.jsx("input",{type:"checkbox",...M.register("is_published"),className:"rounded border-slate-300"}),"Published"]})})]}),e.jsxs(us,{children:[e.jsx(y,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(y,{onClick:M.handleSubmit(Se),disabled:x.isPending||Y.isPending,children:a?"Save Changes":"Create Calendar"})]})]})}),c&&e.jsx(Dc,{calendar:c,open:!!c,onClose:()=>{r(null),h(!1)},showAddHoliday:d,setShowAddHoliday:h})]})}function Dc({calendar:s,open:t,onClose:a,showAddHoliday:l,setShowAddHoliday:c}){const{data:r,isLoading:d}=ii(s.id),h=ci(s.id),v=oi(s.id),A=di(s.id),{can:u,must:p}=Qe(),F=u("attendance","create"),O=u("attendance","delete"),m=!!s.branch,[_,q]=i.useState(""),{data:k,isLoading:x}=El("all",_),Y=(k==null?void 0:k.results)??[],H=hs({resolver:ps(Sc),defaultValues:{holiday_type:"national",states:[],is_restricted:!1,is_floating:!1}});function C(n){p("attendance","create")&&h.mutate({...n,states:m?[]:n.states},{onSuccess:()=>{c(!1),H.reset({holiday_type:"national",states:[],is_restricted:!1,is_floating:!1})}})}function N(){p("attendance","create")&&A.mutate()}function E(n){p("attendance","delete")&&v.mutate(n)}return e.jsx(He,{open:t,onOpenChange:n=>!n&&a(),children:e.jsxs(Ge,{size:"xl",children:[e.jsxs(Be,{children:[e.jsxs(We,{children:["Holidays \\u2014 ",el(s)]}),e.jsxs(Ze,{children:[(r==null?void 0:r.length)??0," holidays"]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-4",children:[F&&e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsxs(y,{size:"sm",onClick:()=>c(!0),disabled:l,children:[e.jsx(ds,{className:"mr-1.5 h-3.5 w-3.5"})," Add Holiday"]}),e.jsxs(y,{size:"sm",variant:"outline",onClick:N,disabled:A.isPending,children:[e.jsx(et,{className:"mr-1.5 h-3.5 w-3.5"}),A.isPending?"Seeding...":"Seed Indian Holidays"]})]}),l&&F&&e.jsxs("div",{className:"mb-4 rounded-lg border border-primary/20 bg-primary/5 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("p",{className:"text-[13px] font-medium text-slate-700",children:"Add New Holiday"}),e.jsx(y,{variant:"ghost",size:"icon-sm",onClick:()=>{c(!1),H.reset()},children:e.jsx(xa,{className:"h-4 w-4"})})]}),e.jsxs("form",{onSubmit:H.handleSubmit(C),className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[e.jsxs("div",{children:[e.jsx(P,{className:"text-[11px]",children:"Date *"}),e.jsx(R,{type:"date",...H.register("date"),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(P,{className:"text-[11px]",children:"Holiday Name *"}),e.jsx(R,{...H.register("name"),className:"mt-1",placeholder:"e.g. Republic Day"})]}),e.jsxs("div",{children:[e.jsx(P,{className:"text-[11px]",children:"Type *"}),e.jsxs($e,{value:H.watch("holiday_type"),onValueChange:n=>H.setValue("holiday_type",n),children:[e.jsx(Le,{className:"mt-1",children:e.jsx(qe,{})}),e.jsxs(Re,{children:[e.jsx(Z,{value:"national",children:"National"}),e.jsx(Z,{value:"company",children:"Company"}),e.jsx(Z,{value:"regional",children:"Regional"}),e.jsx(Z,{value:"optional",children:"Optional"}),e.jsx(Z,{value:"festival",children:"Festival"})]})]})]}),e.jsxs("div",{children:[e.jsx(P,{className:"text-[11px]",children:"States"}),m?e.jsx("div",{className:"mt-1 flex h-9 items-center rounded-md border border-slate-200 bg-slate-50 px-3 text-[13px] text-slate-500",children:s.branch_state_name??"Not set on branch"}):e.jsx("div",{className:"mt-1",children:e.jsx(Ol,{value:H.watch("states")??[],onValueChange:n=>H.setValue("states",n),onSearch:q,isLoading:x,options:Y.map(n=>({value:n.id,label:n.name,hint:n.code})),placeholder:"All states (national)",searchPlaceholder:"Search states..."})})]})]}),e.jsx("p",{className:"text-[11px] text-slate-400",children:m?e.jsxs(e.Fragment,{children:["This calendar is for the ",s.branch_name," branch, so every holiday on it applies to that branch only — the state is already implied."]}):e.jsx(e.Fragment,{children:"Leave States empty for a holiday that applies to every employee on this calendar. Pick one or more to apply it only to employees whose branch is in those states — Ugadi, for example, takes Karnataka, Andhra Pradesh and Telangana on one entry."})}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-[12px] text-slate-600",children:[e.jsx("input",{type:"checkbox",...H.register("is_restricted"),className:"rounded border-slate-300"}),"Restricted"]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-[12px] text-slate-600",children:[e.jsx("input",{type:"checkbox",...H.register("is_floating"),className:"rounded border-slate-300"}),"Floating"]}),e.jsx(y,{type:"submit",size:"sm",disabled:h.isPending,className:"ml-auto",children:"Add"})]})]})]}),d?e.jsx("div",{className:"flex items-center justify-center py-12 text-[13px] text-slate-400",children:"Loading holidays..."}):r!=null&&r.length?e.jsxs(da,{children:[e.jsx(Fa,{children:e.jsxs(Es,{children:[e.jsx(Me,{className:"w-[120px]",children:"Date"}),e.jsx(Me,{children:"Holiday"}),e.jsx(Me,{className:"w-[100px]",children:"Type"}),!m&&e.jsx(Me,{className:"w-[160px]",children:"States"}),e.jsx(Me,{className:"w-[80px]",children:"Restricted"}),e.jsx(Me,{className:"w-[80px]",children:"Floating"}),e.jsx(Me,{className:"w-[60px]"})]})}),e.jsx(ma,{children:r.map(n=>{var K;return e.jsxs(Es,{children:[e.jsx(he,{className:"text-[13px] text-slate-600 font-medium",children:new Date(n.date+"T00:00:00").toLocaleDateString("en-IN",{day:"2-digit",month:"short",year:"numeric"})}),e.jsx(he,{className:"text-[13px] text-slate-900 font-medium",children:n.name}),e.jsx(he,{children:e.jsx(ee,{variant:Cc[n.holiday_type],children:kc[n.holiday_type]})}),!m&&e.jsx(he,{children:(K=n.state_names)!=null&&K.length?e.jsx("span",{className:"text-[12px] text-slate-700",children:n.state_names.join(", ")}):e.jsx("span",{className:"text-[12px] text-slate-400",children:"All states"})}),e.jsx(he,{children:n.is_restricted?e.jsx(ee,{variant:"warning",children:"Restricted"}):e.jsx("span",{className:"text-[12px] text-slate-400",children:"No"})}),e.jsx(he,{children:n.is_floating?e.jsx(ee,{variant:"secondary",children:"Floating"}):e.jsx("span",{className:"text-[12px] text-slate-400",children:"No"})}),e.jsx(he,{children:O&&e.jsx(y,{variant:"ghost",size:"icon-sm",className:"text-red-500 hover:text-red-700",onClick:()=>E(n.id),disabled:v.isPending,children:e.jsx(Ts,{className:"h-3.5 w-3.5"})})})]},n.id)})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(Pa,{className:"h-10 w-10 text-slate-300 mb-3"}),e.jsx("p",{className:"text-[13px] text-slate-500",children:"No holidays defined"}),e.jsx("p",{className:"text-[11px] text-slate-400 mt-1",children:'Add holidays manually or use "Seed Indian Holidays" to auto-populate'})]})]}),e.jsx(us,{children:e.jsx(y,{variant:"outline",onClick:a,children:"Close"})})]})})}const Ac=ys({employee:X().min(1,"Employee is required"),date:X().min(1,"Date is required"),from_time:X().min(1,"From time is required"),to_time:X().min(1,"To time is required"),purpose:X().min(1,"Purpose is required"),location:X().optional()}),Pc=ys({employee:X().min(1,"Employee is required"),date:X().min(1,"Date is required"),from_time:X().min(1,"From time is required"),to_time:X().min(1,"To time is required"),location_name:X().min(1,"Location is required"),purpose:X().min(1,"Purpose is required")}),xn={pending:"warning",approved:"success",rejected:"destructive"};function Dd(){const[s,t]=i.useState("on-duty"),[a,l]=i.useState(!1),[c,r]=i.useState("on-duty"),[d,h]=i.useState(""),v=$s(),A={...v.queryParams,...d&&s==="on-duty"?{status:d}:{}},{data:u,isLoading:p}=xi(A),F=(u==null?void 0:u.results)??[],O=ui(),m=$s(),_={...m.queryParams,...d&&s==="outdoor-duty"?{status:d}:{}},{data:q,isLoading:k}=hi(_),x=(q==null?void 0:q.results)??[],Y=pi(),H=yi(),{can:C,must:N}=Qe(),E=C("on_duty","create"),n=C("on_duty","approve"),K=hs({resolver:ps(Ac)}),M=hs({resolver:ps(Pc)});function o(){r("on-duty"),K.reset({}),l(!0)}function L(){r("outdoor-duty"),M.reset({}),l(!0)}function V(Q){if(!N("on_duty","create"))return;const oe={...Q,location:Q.location??""};O.mutate(oe,{onSuccess:()=>l(!1)})}function j(Q){if(!N("on_duty","create"))return;const oe={...Q};Y.mutate(oe,{onSuccess:()=>l(!1)})}function $(Q,oe){N("on_duty","approve")&&H.mutate({id:Q,action:oe})}function J(Q){h(Q==="__all__"?"":Q),s==="on-duty"?v.setPagination(oe=>({...oe,pageIndex:0})):m.setPagination(oe=>({...oe,pageIndex:0}))}function B(Q){t(Q),h("")}const ne=[{key:"employee",header:"Employee",render:Q=>e.jsx("span",{className:"font-medium text-slate-900",children:Q.employee_name})},{key:"date",header:"Date",render:Q=>e.jsx(Aa,{to:`/attendance/on-duty/${Q.id}`,className:"font-medium text-primary hover:underline",children:ve(ws(Q.date),"dd MMM yyyy")})},{key:"from_time",header:"From",render:Q=>e.jsx("span",{className:"text-[13px] text-slate-600",children:Q.from_time.slice(0,5)})},{key:"to_time",header:"To",render:Q=>e.jsx("span",{className:"text-[13px] text-slate-600",children:Q.to_time.slice(0,5)})},{key:"purpose",header:"Purpose",render:Q=>e.jsx("span",{className:"text-[12px] text-slate-500 truncate max-w-[200px] block",children:Q.purpose})},{key:"location",header:"Location",render:Q=>e.jsx("span",{className:"text-[13px] text-slate-500",children:Q.location||"—"})},{key:"status",header:"Status",render:Q=>e.jsxs("div",{children:[e.jsx(ee,{variant:xn[Q.status],children:Q.status}),Q.approved_by_name&&e.jsxs("p",{className:"text-[10px] text-slate-400 mt-0.5",children:["by ",Q.approved_by_name]})]})}],D=[{key:"employee",header:"Employee",render:Q=>e.jsx("span",{className:"font-medium text-slate-900",children:Q.employee_name})},{key:"date",header:"Date",render:Q=>ve(ws(Q.date),"dd MMM yyyy")},{key:"from_time",header:"From",render:Q=>e.jsx("span",{className:"text-[13px] text-slate-600",children:Q.from_time.slice(0,5)})},{key:"to_time",header:"To",render:Q=>e.jsx("span",{className:"text-[13px] text-slate-600",children:Q.to_time.slice(0,5)})},{key:"location_name",header:"Location",render:Q=>e.jsx("span",{className:"text-[13px] text-slate-600",children:Q.location_name})},{key:"purpose",header:"Purpose",render:Q=>e.jsx("span",{className:"text-[12px] text-slate-500 truncate max-w-[200px] block",children:Q.purpose})},{key:"status",header:"Status",render:Q=>e.jsxs("div",{children:[e.jsx(ee,{variant:xn[Q.status],children:Q.status}),Q.approved_by_name&&e.jsxs("p",{className:"text-[10px] text-slate-400 mt-0.5",children:["by ",Q.approved_by_name]})]})},{key:"actions",header:"",className:"w-10",render:Q=>Q.status==="pending"&&n?e.jsxs(fs,{children:[e.jsx(vs,{asChild:!0,children:e.jsx(y,{variant:"ghost",size:"icon-sm",children:e.jsx(Us,{className:"h-4 w-4"})})}),e.jsxs(_s,{align:"end",children:[e.jsxs(Ce,{onClick:()=>$(Q.id,"approve"),children:[e.jsx(Rt,{className:"mr-2 h-3.5 w-3.5 text-emerald-600"})," Approve"]}),e.jsxs(Ce,{onClick:()=>$(Q.id,"reject"),children:[e.jsx(xa,{className:"mr-2 h-3.5 w-3.5 text-red-500"})," Reject"]})]})]}):null}],fe=e.jsx("div",{className:"flex gap-2",children:e.jsxs($e,{value:d,onValueChange:J,children:[e.jsx(Le,{className:"w-[140px] h-9",children:e.jsx(qe,{placeholder:"All statuses"})}),e.jsxs(Re,{children:[e.jsx(Z,{value:"__all__",children:"All"}),e.jsx(Z,{value:"pending",children:"Pending"}),e.jsx(Z,{value:"approved",children:"Approved"}),e.jsx(Z,{value:"rejected",children:"Rejected"})]})]})});return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-[16px] font-semibold text-slate-900 flex items-center gap-2",children:[e.jsx(qa,{className:"h-5 w-5 text-primary"})," On-Duty Requests"]}),e.jsx("p",{className:"mt-0.5 text-[13px] text-slate-400",children:"Manage on-duty and outdoor duty requests"})]}),E&&e.jsxs(y,{size:"sm",onClick:s==="on-duty"?o:L,children:[e.jsx(ds,{className:"mr-1.5 h-3.5 w-3.5"})," New Request"]})]}),e.jsxs(Ea,{value:s,onValueChange:B,children:[e.jsxs(Ma,{className:"mb-4",children:[e.jsx(Fs,{value:"on-duty",children:"On-Duty"}),e.jsx(Fs,{value:"outdoor-duty",children:"Outdoor Duty"})]}),e.jsx(Os,{value:"on-duty",children:e.jsx(rs,{actions:fe,columns:ne,data:F,isLoading:p,searchPlaceholder:"Search on-duty requests...",emptyMessage:"No on-duty requests",emptyDescription:"Submit an on-duty request when employees work at the office outside normal hours.",totalCount:(u==null?void 0:u.count)??0,pagination:v.pagination,onPaginationChange:v.setPagination,sorting:v.sorting,onSortingChange:v.setSorting,globalFilter:v.globalFilter,onGlobalFilterChange:v.setGlobalFilter})}),e.jsx(Os,{value:"outdoor-duty",children:e.jsx(rs,{actions:fe,columns:D,data:x,isLoading:k,searchPlaceholder:"Search outdoor duty requests...",emptyMessage:"No outdoor duty requests",emptyDescription:"Submit an outdoor duty request for field work or client visits.",totalCount:(q==null?void 0:q.count)??0,pagination:m.pagination,onPaginationChange:m.setPagination,sorting:m.sorting,onSortingChange:m.setSorting,globalFilter:m.globalFilter,onGlobalFilterChange:m.setGlobalFilter})})]}),e.jsx(He,{open:a&&c==="on-duty",onOpenChange:l,children:e.jsxs(Ge,{size:"md",children:[e.jsxs(Be,{children:[e.jsx(We,{children:"New On-Duty Request"}),e.jsx(Ze,{children:"Submit a request for on-duty attendance."})]}),e.jsxs("form",{onSubmit:K.handleSubmit(V),className:"flex-1 overflow-y-auto px-6 py-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx(P,{children:"Employee *"}),e.jsx(ea,{value:K.watch("employee")??"",onValueChange:Q=>K.setValue("employee",Q,{shouldValidate:!0}),className:"mt-1.5"}),K.formState.errors.employee&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:K.formState.errors.employee.message})]}),e.jsxs("div",{children:[e.jsx(P,{children:"Date *"}),e.jsx(R,{type:"date",...K.register("date"),className:"mt-1.5"}),K.formState.errors.date&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:K.formState.errors.date.message})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(P,{children:"From Time *"}),e.jsx(R,{type:"time",...K.register("from_time"),className:"mt-1.5"}),K.formState.errors.from_time&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:K.formState.errors.from_time.message})]}),e.jsxs("div",{children:[e.jsx(P,{children:"To Time *"}),e.jsx(R,{type:"time",...K.register("to_time"),className:"mt-1.5"}),K.formState.errors.to_time&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:K.formState.errors.to_time.message})]})]}),e.jsxs("div",{children:[e.jsx(P,{children:"Purpose *"}),e.jsx(Xa,{...K.register("purpose"),className:"mt-1.5",placeholder:"Describe the purpose of on-duty",rows:3}),K.formState.errors.purpose&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:K.formState.errors.purpose.message})]}),e.jsxs("div",{children:[e.jsx(P,{children:"Location"}),e.jsx(R,{...K.register("location"),className:"mt-1.5",placeholder:"Optional location"})]})]}),e.jsxs(us,{children:[e.jsx(y,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(y,{onClick:K.handleSubmit(V),disabled:O.isPending,children:"Submit Request"})]})]})}),e.jsx(He,{open:a&&c==="outdoor-duty",onOpenChange:l,children:e.jsxs(Ge,{size:"md",children:[e.jsxs(Be,{children:[e.jsx(We,{children:"New Outdoor Duty Request"}),e.jsx(Ze,{children:"Submit a request for outdoor duty attendance."})]}),e.jsxs("form",{onSubmit:M.handleSubmit(j),className:"flex-1 overflow-y-auto px-6 py-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx(P,{children:"Employee *"}),e.jsx(ea,{value:M.watch("employee")??"",onValueChange:Q=>M.setValue("employee",Q,{shouldValidate:!0}),className:"mt-1.5"}),M.formState.errors.employee&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:M.formState.errors.employee.message})]}),e.jsxs("div",{children:[e.jsx(P,{children:"Date *"}),e.jsx(R,{type:"date",...M.register("date"),className:"mt-1.5"}),M.formState.errors.date&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:M.formState.errors.date.message})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(P,{children:"From Time *"}),e.jsx(R,{type:"time",...M.register("from_time"),className:"mt-1.5"}),M.formState.errors.from_time&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:M.formState.errors.from_time.message})]}),e.jsxs("div",{children:[e.jsx(P,{children:"To Time *"}),e.jsx(R,{type:"time",...M.register("to_time"),className:"mt-1.5"}),M.formState.errors.to_time&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:M.formState.errors.to_time.message})]})]}),e.jsxs("div",{children:[e.jsx(P,{children:"Location *"}),e.jsx(R,{...M.register("location_name"),className:"mt-1.5",placeholder:"e.g. Client Office, Site Name"}),M.formState.errors.location_name&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:M.formState.errors.location_name.message})]}),e.jsxs("div",{children:[e.jsx(P,{children:"Purpose *"}),e.jsx(Xa,{...M.register("purpose"),className:"mt-1.5",placeholder:"Describe the purpose of outdoor duty",rows:3}),M.formState.errors.purpose&&e.jsx("p",{className:"mt-1 text-[12px] text-red-500",children:M.formState.errors.purpose.message})]})]}),e.jsxs(us,{children:[e.jsx(y,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(y,{onClick:M.handleSubmit(j),disabled:Y.isPending,children:"Submit Request"})]})]})})]})}const Fc={pending:"warning",approved:"success",rejected:"destructive"};function Ad(){var c,r;const{id:s}=ra(),{data:t,isLoading:a,refetch:l}=mi(s??"");return e.jsx(Rl,{recordId:t==null?void 0:t.id,title:t?`On Duty — ${ve(ws(t.date),"dd MMM yyyy")}`:"On Duty Request",subtitle:t==null?void 0:t.employee_name,backTo:"/attendance/on-duty",notFoundText:"On-duty request not found.",isLoading:a,found:!!t,onDecided:()=>l(),children:t&&e.jsxs("div",{className:"grid grid-cols-3 gap-6",children:[e.jsx("div",{className:"col-span-2 space-y-4",children:e.jsxs(ye,{children:[e.jsx(ks,{className:"pb-3",children:e.jsx(Cs,{className:"text-[14px]",children:"Request Details"})}),e.jsxs(je,{className:"grid grid-cols-2 gap-4",children:[e.jsx(dt,{label:"Date",value:ve(ws(t.date),"dd MMM yyyy")}),e.jsx(dt,{label:"From",value:(c=t.from_time)==null?void 0:c.slice(0,5)}),e.jsx(dt,{label:"To",value:(r=t.to_time)==null?void 0:r.slice(0,5)}),e.jsx(dt,{label:"Location",value:t.location}),e.jsx(dt,{label:"Purpose",value:t.purpose})]})]})}),e.jsx("div",{className:"space-y-4",children:e.jsxs(ye,{children:[e.jsx(ks,{className:"pb-3",children:e.jsx(Cs,{className:"text-[14px]",children:"Summary"})}),e.jsxs(je,{className:"space-y-3",children:[e.jsx(dt,{label:"Employee",value:t.employee_name}),e.jsx(dt,{label:"Approved By",value:t.approved_by_name}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-slate-400",children:"Status"}),e.jsx(ee,{variant:Fc[t.status]??"secondary",className:"mt-1",children:t.status.replace(/_/g," ")})]})]})]})})]})})}const Ec={pattern_break:"Pattern Break",unusual_hours:"Unusual Hours",frequent_regularization:"Frequent Regularization",buddy_punching:"Buddy Punching",ghost_employee:"Ghost Employee"},Mc={low:"secondary",medium:"warning",high:"destructive",critical:"destructive"},$c={pending:"warning",reviewed:"default",resolved:"success",dismissed:"secondary"};function Pd(){const[s,t]=i.useState(""),[a,l]=i.useState(""),{pagination:c,setPagination:r,sorting:d,setSorting:h,globalFilter:v,setGlobalFilter:A,queryParams:u}=$s(),p={...u,...s&&{severity:s},...a&&{resolution:a}},{data:F,isLoading:O}=ji(p),m=(F==null?void 0:F.results)??[],_=gi(),{can:q,must:k}=Qe(),x=q("anomaly","update");function Y(E,n){k("anomaly","update")&&_.mutate({id:E,resolution:n})}function H(E){t(E==="__all__"?"":E),r(n=>({...n,pageIndex:0}))}function C(E){l(E==="__all__"?"":E),r(n=>({...n,pageIndex:0}))}const N=[{key:"employee",header:"Employee",render:E=>e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-slate-900",children:E.employee_name}),E.employee_id_display&&e.jsx("span",{className:"ml-2 text-[11px] text-slate-400",children:E.employee_id_display}),E.department_name&&e.jsx("p",{className:"text-[11px] text-slate-400",children:E.department_name})]})},{key:"anomaly_date",header:"Date",render:E=>ve(ws(E.anomaly_date),"dd MMM yyyy")},{key:"anomaly_type",header:"Type",render:E=>e.jsx(ee,{variant:"default",children:Ec[E.anomaly_type]})},{key:"severity",header:"Severity",render:E=>e.jsx(ee,{variant:Mc[E.severity],children:E.severity})},{key:"description",header:"Description",render:E=>e.jsx("span",{className:"text-[12px] text-slate-500 truncate max-w-[250px] block",children:E.description})},{key:"resolution",header:"Resolution",render:E=>e.jsxs("div",{children:[e.jsx(ee,{variant:$c[E.resolution],children:E.resolution}),E.resolved_by_name&&e.jsxs("p",{className:"text-[10px] text-slate-400 mt-0.5",children:["by ",E.resolved_by_name]})]})},{key:"actions",header:"",className:"w-10",render:E=>E.resolution==="pending"&&x?e.jsxs(fs,{children:[e.jsx(vs,{asChild:!0,children:e.jsx(y,{variant:"ghost",size:"icon-sm",children:e.jsx(Us,{className:"h-4 w-4"})})}),e.jsxs(_s,{align:"end",children:[e.jsxs(Ce,{onClick:()=>Y(E.id,"resolved"),children:[e.jsx(Rt,{className:"mr-2 h-3.5 w-3.5 text-emerald-600"})," Resolve"]}),e.jsxs(Ce,{onClick:()=>Y(E.id,"dismissed"),children:[e.jsx(Vl,{className:"mr-2 h-3.5 w-3.5 text-slate-400"})," Dismiss"]})]})]}):null}];return e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center justify-between mb-6",children:e.jsxs("div",{children:[e.jsxs("h2",{className:"text-[16px] font-semibold text-slate-900 flex items-center gap-2",children:[e.jsx(os,{className:"h-5 w-5 text-primary"})," Anomalies"]}),e.jsx("p",{className:"mt-0.5 text-[13px] text-slate-400",children:"Detected attendance anomalies for review"})]})}),e.jsx(rs,{actions:e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($e,{value:s,onValueChange:H,children:[e.jsx(Le,{className:"w-[130px] h-9",children:e.jsx(qe,{placeholder:"Severity"})}),e.jsxs(Re,{children:[e.jsx(Z,{value:"__all__",children:"All"}),e.jsx(Z,{value:"low",children:"Low"}),e.jsx(Z,{value:"medium",children:"Medium"}),e.jsx(Z,{value:"high",children:"High"}),e.jsx(Z,{value:"critical",children:"Critical"})]})]}),e.jsxs($e,{value:a,onValueChange:C,children:[e.jsx(Le,{className:"w-[130px] h-9",children:e.jsx(qe,{placeholder:"Resolution"})}),e.jsxs(Re,{children:[e.jsx(Z,{value:"__all__",children:"All"}),e.jsx(Z,{value:"pending",children:"Pending"}),e.jsx(Z,{value:"reviewed",children:"Reviewed"}),e.jsx(Z,{value:"resolved",children:"Resolved"}),e.jsx(Z,{value:"dismissed",children:"Dismissed"})]})]})]}),columns:N,data:m,isLoading:O,searchPlaceholder:"Search anomalies...",emptyMessage:"No anomalies detected",emptyDescription:"The system will flag anomalies automatically.",totalCount:(F==null?void 0:F.count)??0,pagination:c,onPaginationChange:r,sorting:d,onSortingChange:h,globalFilter:v,onGlobalFilterChange:A})]})}function Fd(){const{data:s,isLoading:t}=_i(),a=[{label:"Attendance Rate",value:s?`${s.attendance_rate.toFixed(1)}%`:"—",icon:Ms,color:"text-emerald-600"},{label:"Avg Working Hours",value:(s==null?void 0:s.avg_working_hours)??"—",icon:ss,color:"text-blue-600"},{label:"Late Percentage",value:s?`${s.late_percentage.toFixed(1)}%`:"—",icon:Ql,color:"text-amber-500"},{label:"Total OT Hours",value:(s==null?void 0:s.overtime_hours_total)??"—",icon:ss,color:"text-purple-600"},{label:"Regularizations",value:(s==null?void 0:s.regularization_count)??"—",icon:qn,color:"text-orange-500"}],l=(s==null?void 0:s.department_wise)??[],c=(s==null?void 0:s.monthly_trend)??[];return e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center justify-between mb-6",children:e.jsxs("div",{children:[e.jsxs("h2",{className:"text-[16px] font-semibold text-slate-900 flex items-center gap-2",children:[e.jsx($n,{className:"h-5 w-5 text-primary"})," Analytics"]}),e.jsx("p",{className:"mt-0.5 text-[13px] text-slate-400",children:"Attendance analytics and insights"})]})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4 mb-6",children:a.map(r=>e.jsx(ye,{children:e.jsxs(je,{className:"pt-5 pb-4 px-4",children:[e.jsx("div",{className:"flex items-center gap-2 mb-2",children:e.jsx(r.icon,{className:`h-4 w-4 ${r.color}`})}),e.jsx("p",{className:"text-2xl font-semibold text-slate-900",children:t?"—":r.value}),e.jsx("p",{className:"text-[12px] text-slate-400 mt-0.5",children:r.label})]})},r.label))}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(ye,{children:[e.jsx(ks,{className:"pb-3",children:e.jsx(Cs,{className:"text-[14px] font-semibold",children:"Department-Wise Attendance"})}),e.jsx(je,{children:t?e.jsx("p",{className:"text-[13px] text-slate-400",children:"Loading..."}):l.length===0?e.jsx("p",{className:"text-[13px] text-slate-400",children:"No department data available"}):e.jsx("div",{className:"space-y-3",children:l.map((r,d)=>e.jsxs("div",{className:"flex items-center justify-between text-[13px] py-2 border-b border-slate-50 last:border-0",children:[e.jsx("span",{className:"text-slate-700 font-medium",children:r.department_name}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-24 h-2 bg-slate-100 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-emerald-500 rounded-full",style:{width:`${r.attendance_rate}%`}})}),e.jsxs("span",{className:"text-slate-600 text-[12px] w-12 text-right",children:[r.attendance_rate.toFixed(1),"%"]})]}),e.jsxs("span",{className:"text-slate-400 text-[11px] w-14 text-right",children:[r.avg_hours,"h avg"]})]})]},d))})})]}),e.jsxs(ye,{children:[e.jsx(ks,{className:"pb-3",children:e.jsx(Cs,{className:"text-[14px] font-semibold",children:"Monthly Trend"})}),e.jsx(je,{children:t?e.jsx("p",{className:"text-[13px] text-slate-400",children:"Loading..."}):c.length===0?e.jsx("p",{className:"text-[13px] text-slate-400",children:"No monthly trend data available"}):e.jsx("div",{className:"space-y-3",children:c.map((r,d)=>e.jsxs("div",{className:"flex items-center justify-between text-[13px] py-2 border-b border-slate-50 last:border-0",children:[e.jsx("span",{className:"text-slate-700 font-medium w-20",children:r.month}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-24 h-2 bg-slate-100 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary rounded-full",style:{width:`${r.attendance_rate}%`}})}),e.jsxs("span",{className:"text-slate-600 text-[12px] w-12 text-right",children:[r.attendance_rate.toFixed(1),"%"]})]}),e.jsxs("span",{className:"text-amber-500 text-[11px] w-16 text-right",children:[r.late_count," late"]}),e.jsxs("span",{className:"text-red-400 text-[11px] w-16 text-right",children:[r.absent_count," absent"]})]})]},d))})})]})]})]})}const un=[{value:"daily",label:"Daily Attendance",description:"Day-wise attendance summary for all employees"},{value:"monthly",label:"Monthly Summary",description:"Month-wise attendance summary with totals"},{value:"employee_wise",label:"Employee Wise",description:"Detailed attendance report for a specific employee"},{value:"department_wise",label:"Department Wise",description:"Department-level attendance analysis"},{value:"late_comers",label:"Late Comers",description:"Report of employees who arrived late"},{value:"absentees",label:"Absentees",description:"Report of absent employees in the selected period"}];function Ed(){const[s,t]=i.useState("daily"),[a,l]=i.useState(""),[c,r]=i.useState(""),[d,h]=i.useState("xlsx"),v=vi();function A(){!a||!c||v.mutate({report_type:s,start_date:a,end_date:c,format:d},{onSuccess:p=>{const F=window.URL.createObjectURL(p),O=document.createElement("a");O.href=F,O.download=`attendance_${s}_${a}_${c}.${d}`,document.body.appendChild(O),O.click(),window.URL.revokeObjectURL(F),O.remove()}})}const u=un.find(p=>p.value===s);return e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center justify-between mb-6",children:e.jsxs("div",{children:[e.jsxs("h2",{className:"text-[16px] font-semibold text-slate-900 flex items-center gap-2",children:[e.jsx(Fn,{className:"h-5 w-5 text-primary"})," Reports"]}),e.jsx("p",{className:"mt-0.5 text-[13px] text-slate-400",children:"Generate and export attendance reports"})]})}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsx("div",{className:"lg:col-span-2",children:e.jsxs(ye,{children:[e.jsx(ks,{className:"pb-3",children:e.jsx(Cs,{className:"text-[14px] font-semibold",children:"Select Report Type"})}),e.jsx(je,{children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:un.map(p=>e.jsxs("button",{type:"button",onClick:()=>t(p.value),className:`text-left p-3 rounded-lg border transition-colors ${s===p.value?"border-primary bg-primary/5 ring-1 ring-primary/20":"border-slate-200 hover:border-slate-300 hover:bg-slate-50"}`,children:[e.jsx("p",{className:"text-[13px] font-medium text-slate-900",children:p.label}),e.jsx("p",{className:"text-[11px] text-slate-400 mt-0.5",children:p.description})]},p.value))})})]})}),e.jsx("div",{children:e.jsxs(ye,{children:[e.jsx(ks,{className:"pb-3",children:e.jsx(Cs,{className:"text-[14px] font-semibold",children:"Filters & Export"})}),e.jsxs(je,{className:"space-y-4",children:[e.jsx("div",{children:e.jsxs("p",{className:"text-[12px] text-slate-500 mb-2",children:["Selected: ",e.jsx("span",{className:"font-medium text-slate-700",children:u==null?void 0:u.label})]})}),e.jsxs("div",{children:[e.jsx(P,{children:"Start Date *"}),e.jsx(R,{type:"date",value:a,onChange:p=>l(p.target.value),className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(P,{children:"End Date *"}),e.jsx(R,{type:"date",value:c,onChange:p=>r(p.target.value),className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(P,{children:"Export Format"}),e.jsxs($e,{value:d,onValueChange:p=>h(p),children:[e.jsx(Le,{className:"mt-1.5",children:e.jsx(qe,{})}),e.jsxs(Re,{children:[e.jsx(Z,{value:"xlsx",children:"Excel (.xlsx)"}),e.jsx(Z,{value:"csv",children:"CSV (.csv)"})]})]})]}),e.jsxs(y,{className:"w-full",onClick:A,disabled:!a||!c||v.isPending,children:[e.jsx(yt,{className:"mr-1.5 h-3.5 w-3.5"}),v.isPending?"Exporting...":"Export Report"]})]})]})})]})]})}const Lc=[{number:1,label:"Select Shift",icon:Il},{number:2,label:"Select Employees",icon:vl},{number:3,label:"Review & Submit",icon:it}];function qc({current:s}){return e.jsx("div",{className:"flex items-center justify-center gap-0 mb-8",children:Lc.map((t,a)=>{const l=t.icon,c=t.number===s,r=t.number<s;return e.jsxs("div",{className:"flex items-center",children:[a>0&&e.jsx("div",{className:`h-[2px] w-16 sm:w-24 ${r?"bg-primary":"bg-slate-200"}`}),e.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[e.jsx("div",{className:`flex h-10 w-10 items-center justify-center rounded-full border-2 transition-colors ${c?"border-primary bg-primary text-white":r?"border-primary bg-primary/10 text-primary":"border-slate-200 bg-white text-slate-400"}`,children:r?e.jsx(it,{className:"h-5 w-5"}):e.jsx(l,{className:"h-5 w-5"})}),e.jsx("span",{className:`text-[11px] font-medium ${c?"text-primary":r?"text-slate-600":"text-slate-400"}`,children:t.label})]})]},t.number)})})}function Md(){var ze,Oe;const[s,t]=i.useState(1),[a,l]=i.useState(""),[c,r]=i.useState(""),[d,h]=i.useState(""),[v,A]=i.useState([]),[u,p]=i.useState(""),[F,O]=i.useState(""),[m,_]=i.useState(""),{data:q}=pa({page_size:100,is_active:!0}),k=(q==null?void 0:q.results)??[],[x,Y]=i.useState(""),{data:H,isLoading:C}=ct({page_size:100,is_active:!0,search:x||void 0}),N=(H==null?void 0:H.results)??[],E={page_size:100,status:"active",...u&&{department:u}},{data:n,isLoading:K}=sa(E),M=(n==null?void 0:n.results)??[],o=i.useMemo(()=>F?M.filter(U=>U.id===F):M,[M,F]),{data:L,isLoading:V}=sa({page_size:50,status:"active",...u&&{department:u},...m&&{search:m}}),j=(L==null?void 0:L.results)??[],$=ur(),{can:J,must:B}=Qe(),ne=J("roster","create"),D=i.useMemo(()=>k.find(U=>U.id===a),[k,a]),fe=i.useMemo(()=>M.filter(U=>v.includes(U.id)),[M,v]),Q=[{key:"select",header:"",className:"w-10",render:U=>e.jsx(Zt,{checked:v.includes(U.id),onCheckedChange:me=>{A(Je=>me?[...Je,U.id]:Je.filter(ms=>ms!==U.id))}})},{key:"name",header:"Employee",render:U=>e.jsxs("div",{children:[e.jsxs("span",{className:"font-medium text-slate-900",children:[U.first_name," ",U.last_name]}),e.jsx("span",{className:"ml-2 text-[11px] text-slate-400",children:U.employee_id})]})},{key:"department_name",header:"Department",render:U=>e.jsx("span",{className:"text-[13px] text-slate-600",children:U.department_name??"-"})},{key:"designation_name",header:"Designation",render:U=>e.jsx("span",{className:"text-[13px] text-slate-600",children:U.designation_name??"-"})},{key:"status",header:"Status",render:U=>e.jsx(ee,{variant:U.status==="active"?"success":"secondary",children:U.status})}],oe=o.length>0&&o.every(U=>v.includes(U.id)),Se=o.some(U=>v.includes(U.id))&&!oe;function Te(){if(oe){const U=new Set(o.map(me=>me.id));A(me=>me.filter(Je=>!U.has(Je)))}else{const U=o.map(me=>me.id);A(me=>[...new Set([...me,...U])])}}const I=a&&c&&d&&c<=d,S=v.length>0;function de(){B("roster","create")&&$.mutate({employee_ids:v,shift_id:a,start_date:c,end_date:d},{onSuccess:()=>{t(1),l(""),r(""),h(""),A([]),p(""),O(""),_("")}})}return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-6",children:[e.jsxs("h2",{className:"text-[16px] font-semibold text-slate-900 flex items-center gap-2",children:[e.jsx(Ms,{className:"h-5 w-5 text-primary"})," Shift Allocation"]}),e.jsx("p",{className:"mt-0.5 text-[13px] text-slate-400",children:"Assign a shift to multiple employees across a date range"})]}),e.jsx(qc,{current:s}),s===1&&e.jsx(ye,{children:e.jsx(je,{className:"pt-6",children:e.jsxs("div",{className:"space-y-5 max-w-lg mx-auto",children:[e.jsxs("div",{children:[e.jsx(P,{children:"Shift *"}),e.jsx("div",{className:"mt-1.5",children:e.jsx(ge,{value:a||null,onValueChange:U=>l(U),options:k.map(U=>{var me,Je;return{value:U.id,label:U.name,hint:U.is_week_off_type?"Week Off":`${(me=U.start_time)==null?void 0:me.slice(0,5)} - ${(Je=U.end_time)==null?void 0:Je.slice(0,5)}`}}),placeholder:"Select a shift",searchPlaceholder:"Search shifts..."})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(P,{children:"Start Date *"}),e.jsx(R,{type:"date",value:c,max:d||void 0,onChange:U=>r(U.target.value),className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(P,{children:"End Date *"}),e.jsx(R,{type:"date",value:d,min:c||void 0,onChange:U=>h(U.target.value),className:"mt-1.5"})]})]}),e.jsx(Ke,{}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(y,{onClick:()=>t(2),disabled:!I,children:["Next",e.jsx(ta,{className:"ml-1.5 h-4 w-4"})]})})]})})}),s===2&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("div",{className:"w-[220px]",children:e.jsx(ge,{value:u||"__all__",onValueChange:U=>{p(U==="__all__"?"":U),O("")},onSearch:Y,isLoading:C,options:[{value:"__all__",label:"All Departments"},...N.map(U=>({value:U.id,label:U.name,hint:U.code}))],placeholder:"All Departments",searchPlaceholder:"Search departments..."})}),e.jsx("div",{className:"w-[260px]",children:e.jsx(ge,{value:F||"__all__",onValueChange:U=>O(U==="__all__"?"":U),onSearch:_,isLoading:V,options:[{value:"__all__",label:"All Employees"},...j.map(U=>({value:U.id,label:`${U.first_name} ${U.last_name}`.trim(),hint:U.employee_id}))],placeholder:"All Employees",searchPlaceholder:"Search employees..."})}),e.jsxs("div",{className:"ml-auto flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zt,{checked:oe||Se&&"indeterminate",onCheckedChange:Te}),e.jsx("span",{className:"text-[13px] text-slate-500",children:"Select all"})]}),e.jsxs(ee,{variant:"secondary",className:"text-[12px]",children:[v.length," employee",v.length!==1?"s":""," selected"]})]})]}),e.jsx(rs,{columns:Q,data:o,isLoading:K,emptyMessage:"No employees found",emptyDescription:"Try adjusting your filters.",enablePagination:!1,hideSearch:!0}),e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsxs(y,{variant:"outline",onClick:()=>t(1),children:[e.jsx(gt,{className:"mr-1.5 h-4 w-4"}),"Back"]}),e.jsxs(y,{onClick:()=>t(3),disabled:!S,children:["Next",e.jsx(ta,{className:"ml-1.5 h-4 w-4"})]})]})]}),s===3&&e.jsxs("div",{className:"space-y-5 max-w-2xl mx-auto",children:[e.jsx(ye,{children:e.jsxs(je,{className:"pt-6",children:[e.jsx("h3",{className:"text-[14px] font-semibold text-slate-900 mb-4",children:"Allocation Summary"}),e.jsxs("div",{className:"grid grid-cols-2 gap-y-3 gap-x-8 text-[13px]",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-slate-400",children:"Shift"}),e.jsxs("p",{className:"mt-0.5 font-medium text-slate-900",children:[(D==null?void 0:D.name)??"-",D&&e.jsx("span",{className:"ml-2 text-[11px] text-slate-400 font-normal",children:D.is_week_off_type?"Week Off":`${(ze=D.start_time)==null?void 0:ze.slice(0,5)} - ${(Oe=D.end_time)==null?void 0:Oe.slice(0,5)}`})]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-slate-400",children:"Date Range"}),e.jsxs("p",{className:"mt-0.5 font-medium text-slate-900",children:[c," to ",d]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-slate-400",children:"Employees"}),e.jsxs("p",{className:"mt-0.5 font-medium text-slate-900",children:[v.length," employee",v.length!==1?"s":""]})]})]})]})}),e.jsx(ye,{children:e.jsxs(je,{className:"pt-6",children:[e.jsx("h3",{className:"text-[14px] font-semibold text-slate-900 mb-3",children:"Selected Employees"}),e.jsx("div",{className:"space-y-2 max-h-64 overflow-y-auto",children:fe.length>0?fe.map(U=>e.jsxs("div",{className:"flex items-center justify-between rounded-md border border-slate-100 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-[13px] font-medium text-slate-900",children:[U.first_name," ",U.last_name]}),e.jsx("span",{className:"text-[11px] text-slate-400",children:U.employee_id})]}),e.jsx("span",{className:"text-[12px] text-slate-400",children:U.department_name??"-"})]},U.id)):e.jsxs("p",{className:"text-[13px] text-slate-400 py-4 text-center",children:[v.length," employee",v.length!==1?"s":""," selected (some may not be visible in the current filter)"]})})]})}),e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsxs(y,{variant:"outline",onClick:()=>t(2),children:[e.jsx(gt,{className:"mr-1.5 h-4 w-4"}),"Back"]}),ne&&e.jsxs(y,{onClick:de,disabled:$.isPending,children:[$.isPending&&e.jsx(Ks,{className:"mr-1.5 h-4 w-4 animate-spin"}),"Allocate"]})]})]})]})}function Rc(s,t){return ve(new Date(s,t-1,1),"MMMM yyyy")}function Xs(s){const t=Math.floor(s/60),a=s%60;return`${t}h ${String(a).padStart(2,"0")}m`}const Tc={present_days:"present",paid_leave_days:"paid_leave",unpaid_leave_days:"unpaid_leave",half_days:"half_day",holiday_days:"holiday",weekend_days:"weekend",absent_days:"absent",on_duty_days:"on_duty",comp_off_days:"comp_off"};function Lt(s,t,a){if(!t&&s.paid_days!=null)return Math.round(Number(s.paid_days)*10)/10;if(a&&Object.keys(a).length>0){let v=0;for(const[A,u]of Object.entries(Tc)){const p=a[u];if(p!=null&&p.is_paid_day){const F=(t==null?void 0:t[A])??s[A]??0;v+=F*Number(p.paid_day_weight)}}if(!a.half_day){const A=(t==null?void 0:t.half_days)??s.half_days??0;v+=A*.5}return Math.round(v*10)/10}const l=(t==null?void 0:t.present_days)??s.present_days??0,c=(t==null?void 0:t.paid_leave_days)??s.paid_leave_days??0,r=(t==null?void 0:t.on_duty_days)??s.on_duty_days??0,d=(t==null?void 0:t.comp_off_days)??s.comp_off_days??0,h=(t==null?void 0:t.half_days)??s.half_days??0;return l+c+r+d+h*.5}function la(s,t,a){if(!t&&s.lop_days!=null)return Math.round(Number(s.lop_days)*10)/10;const l=Lt(s,t,a);return Math.max(0,Math.round((s.working_days-l)*10)/10)}const sl={open:{label:"Open",variant:"success"},frozen:{label:"Frozen",variant:"default"},payroll_locked:{label:"Payroll Locked",variant:"warning"}};function ut({value:s,originalValue:t,onChange:a,disabled:l,colorClass:c}){const r=s!==t,d=i.useRef(null);return l?e.jsx("span",{className:`text-[13px] font-medium ${c??"text-slate-500"}`,children:s}):e.jsx("input",{ref:d,type:"number",min:0,max:31,value:s,onChange:h=>{const v=Math.max(0,Math.min(31,Number(h.target.value)||0));a(v)},className:`w-12 h-7 rounded border text-center text-[13px] font-medium outline-none transition-colors
        ${r?"border-amber-400 bg-amber-50 text-amber-800 ring-1 ring-amber-300":"border-slate-200 bg-white text-slate-700 hover:border-slate-300 focus:border-primary focus:ring-1 focus:ring-primary/30"}`})}function Ft({icon:s,label:t,value:a,suffix:l}){return e.jsx(ye,{children:e.jsxs(je,{className:"flex items-center gap-3 p-4",children:[e.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-slate-100",children:s}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-[20px] font-bold text-slate-900 leading-tight",children:[typeof a=="number"?a.toLocaleString():a,l&&e.jsx("span",{className:"text-[12px] font-medium text-slate-400 ml-0.5",children:l})]}),e.jsx("p",{className:"text-[11px] text-slate-400",children:t})]})]})})}function zc({frozenCount:s,total:t}){const a=t>0?Math.round(s/t*100):0,l=a===100?"text-emerald-600":a>0?"text-amber-600":"text-slate-400",c=a===100?"[&>div]:bg-emerald-500":a>0?"[&>div]:bg-amber-500":"";return e.jsx(ye,{children:e.jsxs(je,{className:"flex items-center gap-3 p-4",children:[e.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-slate-100",children:e.jsx(Mt,{className:"h-4 w-4 text-blue-500"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:`text-[20px] font-bold leading-tight ${l}`,children:[a,"%"]}),e.jsx($a,{value:a,className:`h-1.5 mt-1 ${c}`}),e.jsx("p",{className:"text-[11px] text-slate-400 mt-0.5",children:"Payroll Ready"})]})]})})}function xs({label:s,value:t,color:a}){return e.jsxs("div",{className:"flex items-center justify-between py-2 border-b border-slate-100 last:border-0",children:[e.jsx("span",{className:"text-[13px] text-slate-500",children:s}),e.jsx("span",{className:`text-[13px] font-medium ${a??"text-slate-800"}`,children:t})]})}function Sa({title:s,children:t}){return e.jsxs("div",{className:"rounded-lg border border-slate-200 bg-white",children:[e.jsx("div",{className:"px-4 py-2.5 border-b border-slate-100 bg-slate-50/60 rounded-t-lg",children:e.jsx("h4",{className:"text-[12px] font-semibold text-slate-500 uppercase tracking-wide",children:s})}),e.jsx("div",{className:"px-4 py-1",children:t})]})}function Gt({label:s,value:t,bgColor:a,textColor:l}){return e.jsxs("div",{className:`flex flex-col items-center justify-center rounded-lg px-4 py-3 ${a}`,children:[e.jsx("span",{className:`text-[20px] font-bold leading-tight ${l}`,children:t}),e.jsx("span",{className:"text-[11px] text-slate-500 mt-0.5",children:s})]})}function Oc({employee:s,open:t,onClose:a,monthLabel:l,onRecalculate:c,isRecalculating:r,configMap:d}){if(!s)return null;const h=Lt(s,void 0,d),v=la(s,void 0,d),A=sl[s.freeze_status];return e.jsx(He,{open:t,onOpenChange:u=>{u||a()},children:e.jsxs(Ge,{size:"lg",className:"overflow-y-auto",children:[e.jsxs(Be,{children:[e.jsxs(We,{className:"flex items-center gap-2 text-[16px]",children:[s.employee_name,e.jsx(ee,{variant:A.variant,className:"text-[10px]",children:A.label}),s.is_stale&&e.jsxs(ee,{variant:"warning",className:"text-[10px]",children:[e.jsx(os,{className:"h-3 w-3 mr-1"})," Out of Sync"]})]}),e.jsxs("p",{className:"text-[12px] text-slate-400",children:[s.employee_id_display," · ",l]})]}),c&&e.jsxs("div",{className:`mt-4 flex items-center gap-2 px-3 py-2 rounded-lg ${s.is_stale?"bg-amber-50 border border-amber-200":"bg-slate-50 border border-slate-200"}`,children:[s.is_stale&&e.jsx(os,{className:"h-3.5 w-3.5 text-amber-600 shrink-0"}),e.jsx("span",{className:`text-[12px] flex-1 ${s.is_stale?"text-amber-700":"text-slate-500"}`,children:s.is_stale?"Daily attendance was modified since last computation.":"Recompute summary from daily attendance records."}),e.jsxs(y,{variant:"outline",size:"sm",disabled:r||s.freeze_status==="payroll_locked",onClick:()=>c(s.employee),children:[e.jsx(Qs,{className:`h-3 w-3 mr-1.5 ${r?"animate-spin":""}`})," Recalculate"]})]}),e.jsxs("div",{className:"mt-5 grid grid-cols-4 gap-3",children:[e.jsx(Gt,{label:"Paid Days",value:h,bgColor:"bg-emerald-50",textColor:"text-emerald-700"}),e.jsx(Gt,{label:"LOP Days",value:v,bgColor:v>0?"bg-red-50":"bg-slate-50",textColor:v>0?"text-red-700":"text-slate-500"}),e.jsx(Gt,{label:"Working Days",value:s.working_days,bgColor:"bg-blue-50",textColor:"text-blue-700"}),e.jsx(Gt,{label:"Total Hours",value:Xs(s.total_working_minutes),bgColor:"bg-slate-50",textColor:"text-slate-700"})]}),e.jsx("div",{className:"mt-5",children:e.jsx(Sa,{title:"Days Breakdown",children:e.jsxs("div",{className:"grid grid-cols-2 gap-x-6",children:[e.jsxs("div",{children:[e.jsx(xs,{label:"Present",value:s.present_days,color:"text-emerald-600"}),e.jsx(xs,{label:"Absent",value:s.absent_days,color:s.absent_days>0?"text-red-600":void 0}),e.jsx(xs,{label:"Paid Leave",value:s.paid_leave_days,color:"text-blue-600"}),e.jsx(xs,{label:"Unpaid Leave",value:s.unpaid_leave_days,color:s.unpaid_leave_days>0?"text-red-500":void 0}),e.jsx(xs,{label:"Half Days",value:s.half_days,color:"text-amber-600"}),e.jsx(xs,{label:"Late Count",value:s.late_count,color:s.late_count>0?"text-orange-600":void 0})]}),e.jsxs("div",{children:[e.jsx(xs,{label:"On Duty",value:s.on_duty_days,color:"text-teal-600"}),e.jsx(xs,{label:"Comp Off",value:s.comp_off_days,color:"text-violet-600"}),e.jsx(xs,{label:"Holidays",value:s.holiday_days}),e.jsx(xs,{label:"Weekends",value:s.weekend_days})]})]})})}),e.jsx("div",{className:"mt-4",children:e.jsx(Sa,{title:"Time Summary",children:e.jsxs("div",{className:"grid grid-cols-2 gap-x-6",children:[e.jsxs("div",{children:[e.jsx(xs,{label:"Total Hours",value:Xs(s.total_working_minutes)}),e.jsx(xs,{label:"Overtime",value:Xs(s.total_overtime_minutes),color:"text-violet-600"})]}),e.jsxs("div",{children:[e.jsx(xs,{label:"Late Minutes",value:Xs(s.total_late_minutes),color:s.total_late_minutes>0?"text-orange-600":void 0}),e.jsx(xs,{label:"Early Departure",value:Xs(s.total_early_minutes),color:s.total_early_minutes>0?"text-amber-600":void 0})]})]})})}),(s.frozen_at||s.last_computed_at)&&e.jsx("div",{className:"mt-4",children:e.jsxs(Sa,{title:"Metadata",children:[s.frozen_at&&e.jsx(xs,{label:"Frozen At",value:ve(new Date(s.frozen_at),"dd MMM yyyy, HH:mm")}),s.frozen_at&&s.frozen_by&&e.jsx(xs,{label:"Frozen By",value:s.frozen_by}),s.last_computed_at&&e.jsx(xs,{label:"Last Computed",value:ve(new Date(s.last_computed_at),"dd MMM yyyy, HH:mm")})]})})]})})}function Vc(s,t,a,l){const c=["Employee Name","Employee ID","Working Days","Present","Absent","Leave (Paid)","Leave (Unpaid)","Late","Half Days","On Duty","Comp Off","Holidays","Weekends","OT Hours","Total Hours","Paid Days","LOP Days","Status"],r=s.map(u=>[u.employee_name,u.employee_id_display,u.working_days,u.present_days,u.absent_days,u.paid_leave_days,u.unpaid_leave_days,u.late_count,u.half_days,u.on_duty_days,u.comp_off_days,u.holiday_days,u.weekend_days,Xs(u.total_overtime_minutes),Xs(u.total_working_minutes),Lt(u,void 0,l),la(u,void 0,l),u.freeze_status]),d=[c,...r].map(u=>u.map(p=>`"${p}"`).join(",")).join(`
`),h=new Blob([d],{type:"text/csv;charset=utf-8;"}),v=URL.createObjectURL(h),A=document.createElement("a");A.href=v,A.download=`monthly-summary-${t}-${String(a).padStart(2,"0")}.csv`,A.click(),URL.revokeObjectURL(v)}function $d(){const s=new Date,[t,a]=i.useState(s.getFullYear()),[l,c]=i.useState(s.getMonth()+1),[r,d]=i.useState(""),[h,v]=i.useState(""),[A,u]=i.useState(""),[p,F]=i.useState("");i.useEffect(()=>{C(w=>({...w,pageIndex:0}))},[r,h,A,p,l,t]);const[O,m]=i.useState(null),[_,q]=i.useState(!1),[k,x]=i.useState({}),Y=Object.keys(k).length,{pagination:H,setPagination:C,sorting:N,setSorting:E,globalFilter:n,setGlobalFilter:K,queryParams:M}=$s(),o=i.useMemo(()=>({...M,month:l,year:t,...r&&{company:r},...h&&{department:h},...A&&{branch:A},...p&&{freeze_status:p}}),[M,l,t,r,h,A,p]),{data:L,isLoading:V}=bi(o,{refetchInterval:_?3e3:!1}),j=(L==null?void 0:L.results)??[],$=(L==null?void 0:L.count)??0;i.useEffect(()=>{x({})},[l,t]);const J=wi(),B=Si(),ne=ki(),D=Ni(),{can:fe,must:Q}=Qe(),oe=fe("attendance","update"),Se=fe("attendance","export"),[Te,I]=i.useState(""),[S,de]=i.useState(""),[ze,Oe]=i.useState(""),{data:U,isLoading:me}=Hs({page_size:100,search:Te||void 0}),{data:Je,isLoading:ms}=ct({page_size:100,search:S||void 0,...r?{company:r}:{}}),{data:qs,isLoading:ts}=ft({page_size:100,search:ze||void 0,...r?{company:r}:{}}),G=(U==null?void 0:U.results)??[],xe=(Je==null?void 0:Je.results)??[],ue=(qs==null?void 0:qs.results)??[],Ae=i.useMemo(()=>({page_size:50,...r&&{company:r}}),[r]),{data:Ie}=Gn(Ae),pe=i.useMemo(()=>{const w={};for(const ie of(Ie==null?void 0:Ie.results)??[])ie.is_active&&(w[ie.status_code]=ie);return w},[Ie]),Fe=i.useMemo(()=>{const w={employees:j.length,paidDays:0,lopDays:0,otMinutes:0,odDays:0};for(const ie of j){const le=k[ie.id];w.paidDays+=Lt(ie,le,pe),w.lopDays+=la(ie,le,pe),w.otMinutes+=ie.total_overtime_minutes,w.odDays+=(le==null?void 0:le.on_duty_days)??ie.on_duty_days}return w},[j,k,pe]),Ye=i.useMemo(()=>{const w={open:0,frozen:0,payroll_locked:0};for(const ie of j)w[ie.freeze_status]++;return w},[j]),js=Ye.frozen+Ye.payroll_locked,gs=Fe.employees>0?(Fe.paidDays/Fe.employees).toFixed(1):"0",re=i.useMemo(()=>j.filter(w=>w.is_stale&&w.freeze_status!=="payroll_locked").length,[j]);i.useEffect(()=>{if(!_)return;if(re===0){q(!1);return}const w=setTimeout(()=>q(!1),3e4);return()=>clearTimeout(w)},[_,re]);const as=i.useCallback(()=>{Q("attendance","update")&&ne.mutate({month:l,year:t,...r&&{company:r}},{onSuccess:w=>{w.mode==="async"&&q(!0)}})},[ne,l,t,r,Q]),ns=i.useCallback(w=>{Q("attendance","update")&&ne.mutate({month:l,year:t,employee_ids:[w]})},[ne,l,t,Q]),ls=i.useCallback(()=>{Q("attendance","update")&&J.mutate({month:l,year:t,...r&&{company:r}})},[J,l,t,r,Q]),is=i.useCallback(()=>{Q("attendance","update")&&B.mutate({month:l,year:t,...r&&{company:r}})},[B,l,t,r,Q]);function cs(w,ie,le){x(Ve=>{const Ws={...Ve[w]??{},[ie]:le},W=j.find(Ee=>Ee.id===w);if(W&&le===W[ie]&&delete Ws[ie],Object.keys(Ws).length===0){const Ee={...Ve};return delete Ee[w],Ee}return{...Ve,[w]:Ws}})}async function Gs(){if(!Q("attendance","update"))return;const w=Object.keys(k);if(w.length===0)return;const ie=w.map(le=>D.mutateAsync({id:le,...k[le]}));try{await Promise.all(ie),x({})}catch{}}function Ss(){l===1?(a(w=>w-1),c(12)):c(w=>w-1)}function Ue(){l===12?(a(w=>w+1),c(1)):c(w=>w+1)}const zs=i.useCallback(()=>Vc(j,t,l,pe),[j,t,l,pe]),As=Rc(t,l),Bs=[{key:"employee",header:"Employee",render:w=>{const ie=!!k[w.id];return e.jsxs("div",{children:[e.jsxs("p",{className:"text-[13px] font-medium text-slate-800 flex items-center gap-1.5",children:[w.employee_name,ie&&e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-amber-400 inline-block",title:"Unsaved changes"})]}),e.jsx("p",{className:"text-[11px] text-slate-400",children:w.employee_id_display})]})}},{key:"working_days",header:"Working",render:w=>e.jsx("span",{className:"text-[13px] text-slate-600",children:w.working_days})},{key:"present_days",header:"Present",render:w=>{const ie=w.freeze_status==="payroll_locked"||!oe,le=k[w.id];return e.jsx(ut,{value:(le==null?void 0:le.present_days)??w.present_days,originalValue:w.present_days,onChange:Ve=>cs(w.id,"present_days",Ve),disabled:ie,colorClass:"text-emerald-600"})}},{key:"absent_days",header:"Absent",render:w=>{const ie=w.freeze_status==="payroll_locked"||!oe,le=k[w.id],Ve=(le==null?void 0:le.absent_days)??w.absent_days;return e.jsx(ut,{value:Ve,originalValue:w.absent_days,onChange:Rs=>cs(w.id,"absent_days",Rs),disabled:ie,colorClass:Ve>0?"text-red-600":"text-slate-400"})}},{key:"leave_days",header:"PL / UPL",render:w=>{const ie=w.freeze_status==="payroll_locked"||!oe,le=k[w.id];return e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ut,{value:(le==null?void 0:le.paid_leave_days)??w.paid_leave_days,originalValue:w.paid_leave_days,onChange:Ve=>cs(w.id,"paid_leave_days",Ve),disabled:ie,colorClass:"text-blue-600"}),e.jsx("span",{className:"text-slate-300",children:"/"}),e.jsx(ut,{value:(le==null?void 0:le.unpaid_leave_days)??w.unpaid_leave_days,originalValue:w.unpaid_leave_days,onChange:Ve=>cs(w.id,"unpaid_leave_days",Ve),disabled:ie,colorClass:"text-red-500"})]})}},{key:"late_count",header:"Late",render:w=>{const ie=w.freeze_status==="payroll_locked"||!oe,le=k[w.id],Ve=(le==null?void 0:le.late_count)??w.late_count;return e.jsx(ut,{value:Ve,originalValue:w.late_count,onChange:Rs=>cs(w.id,"late_count",Rs),disabled:ie,colorClass:Ve>0?"text-orange-600":"text-slate-400"})}},{key:"half_days",header:"Half",render:w=>{const ie=w.freeze_status==="payroll_locked"||!oe,le=k[w.id];return e.jsx(ut,{value:(le==null?void 0:le.half_days)??w.half_days,originalValue:w.half_days,onChange:Ve=>cs(w.id,"half_days",Ve),disabled:ie,colorClass:"text-amber-600"})}},{key:"on_duty_days",header:"OD",render:w=>{const ie=w.freeze_status==="payroll_locked"||!oe,le=k[w.id],Ve=(le==null?void 0:le.on_duty_days)??w.on_duty_days;return e.jsx(ut,{value:Ve,originalValue:w.on_duty_days,onChange:Rs=>cs(w.id,"on_duty_days",Rs),disabled:ie,colorClass:Ve>0?"text-teal-600":"text-slate-400"})}},{key:"we_hol",header:"WE/Hol",render:w=>e.jsxs("span",{className:"text-[13px] text-slate-500",children:[w.weekend_days,e.jsx("span",{className:"text-slate-300",children:"/"}),w.holiday_days]})},{key:"total_overtime_minutes",header:"OT",render:w=>e.jsx("span",{className:"text-[13px] text-violet-600",children:w.total_overtime_minutes>0?Xs(w.total_overtime_minutes):"—"})},{key:"computed_paid_days",header:"Paid Days",render:w=>{const ie=k[w.id];return e.jsx("span",{className:"text-[13px] font-bold text-emerald-700",children:Lt(w,ie,pe)})}},{key:"computed_lop_days",header:"LOP",render:w=>{const ie=k[w.id],le=la(w,ie,pe);return e.jsx("span",{className:`text-[13px] font-bold ${le>0?"text-red-700":"text-slate-400"}`,children:le})}},{key:"freeze_status",header:"Status",render:w=>{const ie=sl[w.freeze_status];return e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs(ee,{variant:ie.variant,className:"text-[11px]",children:[w.freeze_status==="payroll_locked"&&e.jsx(Bt,{className:"h-3 w-3 mr-1"}),w.freeze_status==="frozen"&&e.jsx(Mt,{className:"h-3 w-3 mr-1"}),ie.label]}),w.is_stale&&e.jsx("span",{title:"Data modified since last computation",children:e.jsx(os,{className:"h-3.5 w-3.5 text-amber-500"})})]})}},{key:"actions",header:"",render:w=>e.jsx(y,{variant:"ghost",size:"icon-sm",onClick:()=>m(w),title:"View details",children:e.jsx(ua,{className:"h-4 w-4 text-slate-400"})})}];return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-5",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-[16px] font-semibold text-slate-900 flex items-center gap-2",children:[e.jsx(ka,{className:"h-5 w-5 text-primary"})," Monthly Summary"]}),e.jsxs("p",{className:"mt-0.5 text-[13px] text-slate-400",children:["Payroll-ready attendance aggregates for ",As]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[Y>0&&oe&&e.jsxs(y,{size:"sm",disabled:D.isPending,onClick:Gs,className:"bg-amber-500 hover:bg-amber-600 text-white border-0",children:[e.jsx(st,{className:"h-3.5 w-3.5 mr-1.5"}),D.isPending?"Saving...":`Save Changes (${Y})`]}),oe&&e.jsxs(y,{variant:"outline",size:"sm",disabled:ne.isPending,onClick:as,children:[e.jsx(Qs,{className:`h-3.5 w-3.5 mr-1.5 ${ne.isPending?"animate-spin":""}`}),ne.isPending?"Recalculating...":re>0?`Recalculate (${re})`:"Recalculate"]}),Se&&e.jsxs(y,{variant:"outline",size:"sm",onClick:zs,disabled:j.length===0,children:[e.jsx(yt,{className:"h-3.5 w-3.5 mr-1.5"})," Export CSV"]}),oe&&Ye.open>0&&e.jsxs(y,{variant:"outline",size:"sm",disabled:J.isPending,onClick:ls,children:[e.jsx(Bt,{className:"h-3.5 w-3.5 mr-1.5"}),J.isPending?"Freezing...":"Freeze Month"]}),oe&&Ye.frozen>0&&e.jsxs(y,{variant:"outline",size:"sm",disabled:B.isPending,onClick:is,children:[e.jsx(Yl,{className:"h-3.5 w-3.5 mr-1.5"}),B.isPending?"Unfreezing...":"Unfreeze Month"]})]})]}),Y>0&&e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2.5 mb-4 rounded-lg bg-amber-50 border border-amber-200",children:[e.jsx(st,{className:"h-4 w-4 text-amber-600 shrink-0"}),e.jsxs("span",{className:"text-[13px] font-medium text-amber-700",children:[Y," employee",Y!==1?"s have":" has",' unsaved changes. Click "Save Changes" to apply.']}),e.jsx("button",{type:"button",className:"ml-auto text-[12px] text-amber-600 hover:underline",onClick:()=>x({}),children:"Discard"})]}),e.jsxs("div",{className:"flex items-center gap-3 mb-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(y,{variant:"outline",size:"icon-sm",onClick:Ss,children:e.jsx(Oa,{className:"h-4 w-4"})}),e.jsx("div",{className:"px-3 py-1.5 text-[13px] font-medium text-slate-800 min-w-[140px] text-center",children:As}),e.jsx(y,{variant:"outline",size:"icon-sm",onClick:Ue,children:e.jsx(Vs,{className:"h-4 w-4"})})]}),e.jsx(Ke,{orientation:"vertical",className:"h-6"}),e.jsx("div",{className:"w-[160px]",children:e.jsx(ge,{value:r||null,onValueChange:w=>{d(w),v(""),u("")},onSearch:I,isLoading:me,options:G.map(w=>({value:w.id,label:w.name,hint:w.code})),placeholder:"All companies",searchPlaceholder:"Search companies..."})}),e.jsx("div",{className:"w-[160px]",children:e.jsx(ge,{value:h||null,onValueChange:w=>v(w),onSearch:de,isLoading:ms,disabled:!r,options:xe.map(w=>({value:w.id,label:w.name,hint:w.code})),placeholder:r?"All departments":"Select a company first",searchPlaceholder:"Search departments..."})}),e.jsx("div",{className:"w-[150px]",children:e.jsx(ge,{value:A||null,onValueChange:w=>u(w),onSearch:Oe,isLoading:ts,disabled:!r,options:ue.map(w=>({value:w.id,label:w.name,hint:w.code})),placeholder:r?"All branches":"Select a company first",searchPlaceholder:"Search branches..."})}),e.jsxs($e,{value:p||"__all__",onValueChange:w=>F(w==="__all__"?"":w),children:[e.jsx(Le,{className:"w-[150px] h-9",children:e.jsx(qe,{placeholder:"All statuses"})}),e.jsxs(Re,{children:[e.jsx(Z,{value:"__all__",children:"All Statuses"}),e.jsx(Z,{value:"open",children:"Open"}),e.jsx(Z,{value:"frozen",children:"Frozen"}),e.jsx(Z,{value:"payroll_locked",children:"Payroll Locked"})]})]})]}),V?e.jsx("div",{className:"grid grid-cols-6 gap-3 mb-4",children:Array.from({length:6}).map((w,ie)=>e.jsx(ye,{children:e.jsx(je,{className:"p-4",children:e.jsx(Tt,{className:"h-12 w-full"})})},ie))}):e.jsxs("div",{className:"grid grid-cols-6 gap-3 mb-4",children:[e.jsx(Ft,{icon:e.jsx(Ms,{className:"h-4 w-4 text-blue-500"}),label:"Employees",value:Fe.employees}),e.jsx(Ft,{icon:e.jsx(_l,{className:"h-4 w-4 text-emerald-500"}),label:"Avg Paid Days",value:gs,suffix:"days"}),e.jsx(Ft,{icon:e.jsx(Nt,{className:"h-4 w-4 text-red-500"}),label:"Total LOP Days",value:Fe.lopDays}),e.jsx(Ft,{icon:e.jsx(ss,{className:"h-4 w-4 text-violet-500"}),label:"Total OT Hours",value:Xs(Fe.otMinutes)}),e.jsx(Ft,{icon:e.jsx(qa,{className:"h-4 w-4 text-amber-500"}),label:"Total OD Days",value:Fe.odDays}),e.jsx(zc,{frozenCount:js,total:Fe.employees})]}),!V&&Fe.employees>0&&e.jsxs(e.Fragment,{children:[Ye.payroll_locked===Fe.employees&&e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2.5 mb-4 rounded-lg bg-blue-50 border border-blue-200",children:[e.jsx(Bt,{className:"h-4 w-4 text-blue-600"}),e.jsxs("span",{className:"text-[13px] font-medium text-blue-700",children:["Payroll locked for ",As,". No further changes allowed."]})]}),Ye.payroll_locked!==Fe.employees&&js===Fe.employees&&e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2.5 mb-4 rounded-lg bg-emerald-50 border border-emerald-200",children:[e.jsx(Kl,{className:"h-4 w-4 text-emerald-600"}),e.jsxs("span",{className:"text-[13px] font-medium text-emerald-700",children:["All ",Fe.employees," employees frozen. Ready for payroll processing."]})]}),Ye.open>0&&js>0&&e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2.5 mb-4 rounded-lg bg-amber-50 border border-amber-200",children:[e.jsx(os,{className:"h-4 w-4 text-amber-600"}),e.jsxs("span",{className:"text-[13px] font-medium text-amber-700",children:[Ye.open," of ",Fe.employees," employees still open. Freeze all before running payroll."]})]}),re>0&&e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2.5 mb-4 rounded-lg bg-orange-50 border border-orange-200",children:[e.jsx(Qs,{className:"h-4 w-4 text-orange-600"}),e.jsxs("span",{className:"text-[13px] font-medium text-orange-700 flex-1",children:[re," employee ",re===1?"summary is":"summaries are"," out of sync with daily attendance."]}),e.jsxs(y,{variant:"outline",size:"sm",disabled:ne.isPending,onClick:as,className:"shrink-0",children:[e.jsx(Qs,{className:`h-3 w-3 mr-1.5 ${ne.isPending?"animate-spin":""}`}),"Recalculate All"]})]})]}),!V&&Fe.employees===0&&e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2.5 mb-4 rounded-lg bg-slate-50 border border-slate-200",children:[e.jsx(os,{className:"h-4 w-4 text-slate-400"}),e.jsxs("span",{className:"text-[13px] text-slate-500",children:["No attendance data for ",As,". Use the « arrow to navigate to a previous month."]})]}),!V&&Fe.employees>0&&Y===0&&e.jsx("p",{className:"text-[12px] text-slate-400 mb-3",children:"Click any value in the table to edit it. Changes are highlighted in amber. Save when done."}),e.jsx(rs,{columns:Bs,data:j,totalCount:$,pagination:H,onPaginationChange:C,sorting:N,onSortingChange:E,globalFilter:n,onGlobalFilterChange:K,isLoading:V,searchPlaceholder:"Search employees...",emptyMessage:"No monthly summaries found",emptyDescription:"Summaries are generated when daily attendance is processed. Navigate to a month that has attendance data."}),e.jsx(Oc,{employee:O,open:O!==null,onClose:()=>m(null),monthLabel:As,onRecalculate:oe?ns:void 0,isRecalculating:ne.isPending,configMap:pe})]})}const Qc={present_type:"Present",absent_type:"Absent",non_working_type:"Non-Working"},Ic={present_type:"success",absent_type:"destructive",non_working_type:"secondary"},Kc=ys({code:X().min(1,"Code is required").max(10),name:X().min(1,"Name is required").max(50),category:Ns(["present_type","absent_type","non_working_type"]),color:X().regex(/^#[0-9a-fA-F]{6}$/,"Must be a valid hex color"),is_paid:es().default(!0),sort_order:De.number().int().min(0).default(0),is_active:es().default(!0)});function Uc(s){const t=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(s);return t?{r:parseInt(t[1],16),g:parseInt(t[2],16),b:parseInt(t[3],16)}:null}function hn(s,t=.12){const a=Uc(s);return a?{backgroundColor:`rgba(${a.r}, ${a.g}, ${a.b}, ${t})`,color:s}:{}}function Ld(){const[s,t]=i.useState(!1),[a,l]=i.useState(null),{pagination:c,setPagination:r,sorting:d,setSorting:h,globalFilter:v,setGlobalFilter:A,queryParams:u}=$s(),{data:p,isLoading:F}=zt({...u,page_size:50}),O=(p==null?void 0:p.results)??[],m=nr(),_=lr(),q=rr(),{can:k,must:x}=Qe(),Y=k("attendance","create"),H=k("attendance","update"),C=k("attendance","delete"),N=hs({resolver:ps(Kc),defaultValues:{code:"",name:"",category:"present_type",color:"#64748b",is_paid:!0,sort_order:0,is_active:!0}}),E=N.watch("color"),n=i.useMemo(()=>/^#[0-9a-fA-F]{6}$/.test(E)?E:"#64748b",[E]);function K(){l(null),N.reset({code:"",name:"",category:"present_type",color:"#64748b",is_paid:!0,sort_order:(O.length+1)*10,is_active:!0}),t(!0)}function M($){l($),N.reset({code:$.code,name:$.name,category:$.category,color:$.color,is_paid:$.is_paid,sort_order:$.sort_order,is_active:$.is_active}),t(!0)}function o($){if(!x("attendance",a?"update":"create"))return;const J={...$};a?_.mutate({id:a.id,...J},{onSuccess:()=>t(!1)}):m.mutate(J,{onSuccess:()=>t(!1)})}const L=(a==null?void 0:a.is_system)??!1;function V($){x("attendance","delete")&&q.mutate($)}const j=[{key:"color",header:"",className:"w-10",render:$=>e.jsx("div",{className:"h-6 w-6 rounded-md border border-slate-200",style:{backgroundColor:$.color}})},{key:"code",header:"Code",className:"w-[100px]",render:$=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-flex items-center justify-center h-6 min-w-[32px] px-1.5 rounded text-[11px] font-bold",style:hn($.color,.15),children:$.code}),$.is_system&&e.jsx(Bt,{className:"h-3 w-3 text-slate-400"})]})},{key:"name",header:"Name",render:$=>e.jsx("span",{className:"text-[13px] font-medium text-slate-800",children:$.name})},{key:"category",header:"Category",className:"w-[130px]",render:$=>e.jsx(ee,{variant:Ic[$.category],children:Qc[$.category]})},{key:"is_paid",header:"Paid",className:"w-20",render:$=>e.jsx(ee,{variant:$.is_paid?"success":"secondary",children:$.is_paid?"Paid":"Unpaid"})},{key:"sort_order",header:"Order",className:"w-[70px]",render:$=>e.jsx("span",{className:"text-[12px] text-slate-500 font-mono",children:$.sort_order})},{key:"is_active",header:"Active",className:"w-20",render:$=>e.jsx(wt,{status:$.is_active?"active":"inactive"})},{key:"actions",header:"",className:"w-10",render:$=>{const J=C&&!$.is_system;return!H&&!J?null:e.jsxs(fs,{children:[e.jsx(vs,{asChild:!0,children:e.jsx(y,{variant:"ghost",size:"icon-sm",children:e.jsx(Us,{className:"h-4 w-4"})})}),e.jsxs(_s,{align:"end",children:[H&&e.jsxs(Ce,{onClick:()=>M($),children:[e.jsx(Ls,{className:"mr-2 h-3.5 w-3.5"})," Edit"]}),J&&e.jsxs(Ce,{className:"text-destructive",onClick:()=>V($.id),children:[e.jsx(Ts,{className:"mr-2 h-3.5 w-3.5"})," Delete"]})]})]})}}];return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-[16px] font-semibold text-slate-900 flex items-center gap-2",children:[e.jsx(Pn,{className:"h-5 w-5 text-primary"})," Attendance Statuses"]}),e.jsx("p",{className:"mt-0.5 text-[13px] text-slate-400",children:"Manage attendance status types. System statuses cannot be deleted."})]}),Y&&e.jsxs(y,{size:"sm",onClick:K,children:[e.jsx(ds,{className:"mr-1.5 h-3.5 w-3.5"})," Add Status"]})]}),e.jsx(rs,{columns:j,data:O,isLoading:F,totalCount:(p==null?void 0:p.count)??0,pagination:c,onPaginationChange:r,sorting:d,onSortingChange:h,globalFilter:v,onGlobalFilterChange:A,searchPlaceholder:"Search statuses...",emptyMessage:"No statuses found",emptyDescription:"Status types will appear here."}),e.jsx(He,{open:s,onOpenChange:t,children:e.jsxs(Ge,{children:[e.jsxs(Be,{children:[e.jsxs(We,{className:"flex items-center gap-2",children:[e.jsx(Zl,{className:"h-4 w-4 text-primary"}),a?"Edit Status":"Add Status"]}),e.jsx(Ze,{children:a!=null&&a.is_system?"System status — only name, color, and active state can be changed.":a?"Update this attendance status type.":"Create a new custom attendance status."})]}),e.jsxs("form",{onSubmit:N.handleSubmit(o),className:"flex flex-col h-[calc(100%-80px)]",children:[e.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-slate-50 border border-slate-100",children:[e.jsx("div",{className:"h-8 w-8 rounded-md border border-slate-200 shrink-0",style:{backgroundColor:n}}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-[13px] font-semibold text-slate-800 truncate",children:N.watch("name")||"Status Name"}),e.jsx("p",{className:"text-[11px] text-slate-400 font-mono",children:N.watch("code")||"CODE"})]}),e.jsx("div",{className:"ml-auto",children:e.jsx("span",{className:"inline-flex items-center justify-center h-7 min-w-[36px] px-2 rounded text-[11px] font-bold",style:hn(n,.15),children:N.watch("code")||"?"})})]}),e.jsx(Ke,{}),e.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(P,{className:"text-[12px] text-slate-600",children:"Code *"}),e.jsx(R,{placeholder:"TR",...N.register("code"),disabled:L,className:"h-9 font-mono uppercase text-[13px]"}),N.formState.errors.code&&e.jsx("p",{className:"text-[11px] text-destructive",children:N.formState.errors.code.message})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(P,{className:"text-[12px] text-slate-600",children:"Name *"}),e.jsx(R,{placeholder:"Training",...N.register("name"),className:"h-9 text-[13px]"}),N.formState.errors.name&&e.jsx("p",{className:"text-[11px] text-destructive",children:N.formState.errors.name.message})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(P,{className:"text-[12px] text-slate-600",children:"Category *"}),e.jsxs($e,{value:N.watch("category"),onValueChange:$=>N.setValue("category",$),disabled:L,children:[e.jsx(Le,{className:"h-9 text-[13px]",children:e.jsx(qe,{})}),e.jsxs(Re,{children:[e.jsx(Z,{value:"present_type",children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-emerald-500"}),"Present Type"]})}),e.jsx(Z,{value:"absent_type",children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-red-500"}),"Absent Type"]})}),e.jsx(Z,{value:"non_working_type",children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-slate-400"}),"Non-Working Type"]})})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(P,{className:"text-[12px] text-slate-600",children:"Color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"relative",children:e.jsx("input",{type:"color",...N.register("color"),className:"h-9 w-9 cursor-pointer rounded-lg border border-slate-200 p-0.5"})}),e.jsx(R,{placeholder:"#64748b",...N.register("color"),className:"h-9 font-mono text-[13px] flex-1"})]}),N.formState.errors.color&&e.jsx("p",{className:"text-[11px] text-destructive",children:N.formState.errors.color.message})]}),e.jsx(Ke,{}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between py-1",children:[e.jsxs("div",{children:[e.jsx(P,{className:"text-[13px] text-slate-700",children:"Paid Status"}),e.jsx("p",{className:"text-[11px] text-slate-400 mt-0.5",children:"Whether this status counts as paid attendance"})]}),e.jsx(Ds,{checked:N.watch("is_paid"),onCheckedChange:$=>N.setValue("is_paid",$),disabled:L})]}),e.jsxs("div",{className:"flex items-center justify-between py-1",children:[e.jsxs("div",{children:[e.jsx(P,{className:"text-[13px] text-slate-700",children:"Active"}),e.jsx("p",{className:"text-[11px] text-slate-400 mt-0.5",children:"Inactive statuses won't appear in marking sheets"})]}),e.jsx(Ds,{checked:N.watch("is_active"),onCheckedChange:$=>N.setValue("is_active",$)})]})]}),e.jsx(Ke,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(P,{className:"text-[12px] text-slate-600",children:"Sort Order"}),e.jsx(R,{type:"number",...N.register("sort_order"),className:"h-9 text-[13px] w-[120px]"}),e.jsx("p",{className:"text-[11px] text-slate-400",children:"Lower numbers appear first in dropdowns"})]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 px-6 py-4 border-t border-slate-100",children:[e.jsx(y,{type:"button",variant:"outline",size:"sm",onClick:()=>t(!1),children:"Cancel"}),e.jsx(y,{type:"submit",size:"sm",disabled:m.isPending||_.isPending,children:m.isPending||_.isPending?"Saving...":a?"Update Status":"Create Status"})]})]})]})})]})}const Hc=[{value:"0",label:"None (0)"},{value:"0.5",label:"Half (0.5)"},{value:"1",label:"Full (1.0)"}];function Gc(s){return s.category==="present_type"?{is_paid_day:!0,is_working_day:!0,paid_day_weight:1,working_day_weight:1}:s.category==="non_working_type"?{is_paid_day:!0,is_working_day:!1,paid_day_weight:1,working_day_weight:0}:{is_paid_day:!1,is_working_day:!1,paid_day_weight:0,working_day_weight:0}}function pn({value:s,onChange:t}){return e.jsxs($e,{value:String(s),onValueChange:a=>t(parseFloat(a)),children:[e.jsx(Le,{className:"h-8 w-[110px]",children:e.jsx(qe,{})}),e.jsx(Re,{children:Hc.map(a=>e.jsx(Z,{value:a.value,children:a.label},a.value))})]})}const yn=()=>({company:"",status_code:"",label:"",is_paid_day:!1,is_working_day:!1,paid_day_weight:1,working_day_weight:1,is_active:!0});function qd(){var Te;const[s,t]=i.useState(""),[a,l]=i.useState(""),[c,r]=i.useState(!1),[d,h]=i.useState(null),[v,A]=i.useState(void 0),[u,p]=i.useState(yn()),[F,O]=i.useState(null),m={page_size:200};s&&(m.company=s);const{data:_,isLoading:q}=Gn(m),k=(_==null?void 0:_.results)??[],{data:x,isLoading:Y}=Hs({page_size:100,search:a||void 0}),H=(x==null?void 0:x.results)??[],{data:C}=zt({page_size:200,is_active:!0}),N=(C==null?void 0:C.results)??[],E=new Set(k.filter(I=>!s||I.company===s).map(I=>I.status_code)),n=N.filter(I=>!E.has(I.code)||d&&u.status_code===I.code),K=Fi(),M=Ei(),o=Mi(),{can:L,must:V}=Qe(),j=L("pay_config","create"),$=L("pay_config","update"),J=L("pay_config","delete");function B(){h(null),A(void 0),p(yn()),r(!0)}function ne(I){h(I.id),A(I.company_name),p({company:I.company,status_code:I.status_code,label:I.label,is_paid_day:I.is_paid_day,is_working_day:I.is_working_day,paid_day_weight:I.paid_day_weight,working_day_weight:I.working_day_weight,is_active:I.is_active}),r(!0)}function D(I){const S=N.find(ze=>ze.code===I),de=S?Gc(S):{};p(ze=>({...ze,status_code:I,label:(S==null?void 0:S.name)??"",...de}))}function fe(){if(!V("pay_config",d?"update":"create")||!u.company||!u.status_code)return;const I={company:u.company,status_code:u.status_code,label:u.label,is_paid_day:u.is_paid_day,is_working_day:u.is_working_day,paid_day_weight:u.paid_day_weight,working_day_weight:u.working_day_weight,is_active:u.is_active};d?M.mutate({id:d,...I},{onSuccess:()=>r(!1)}):K.mutate(I,{onSuccess:()=>r(!1)})}const Q=[{key:"company_name",header:"Company",render:I=>e.jsx("span",{className:"font-medium text-slate-800",children:I.company_name})},{key:"status_code",header:"Attendance Status",render:I=>e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-slate-700",children:I.label||I.status_code}),e.jsx("span",{className:"ml-1.5 text-[11px] text-slate-400",children:I.status_code})]})},{key:"is_paid_day",header:"Paid Day",render:I=>I.is_paid_day?e.jsxs(ee,{variant:"success",children:["Yes (",I.paid_day_weight,"×)"]}):e.jsx(ee,{variant:"secondary",children:"No"})},{key:"is_working_day",header:"Working Day",render:I=>I.is_working_day?e.jsxs(ee,{variant:"default",children:["Yes (",I.working_day_weight,"×)"]}):e.jsx(ee,{variant:"secondary",children:"No"})},{key:"is_active",header:"Active",render:I=>I.is_active?e.jsx(ee,{variant:"success",children:"Active"}):e.jsx(ee,{variant:"secondary",children:"Inactive"})},{key:"actions",header:"",className:"w-20",render:I=>e.jsxs("div",{className:"flex gap-1",children:[$&&e.jsx(y,{size:"sm",variant:"ghost",onClick:()=>ne(I),children:e.jsx(Ls,{className:"h-3.5 w-3.5"})}),J&&e.jsx(y,{size:"sm",variant:"ghost",className:"text-red-500 hover:text-red-600",onClick:()=>O(I.id),children:e.jsx(Ts,{className:"h-3.5 w-3.5"})})]})}],oe=K.isPending||M.isPending,Se=d?N:n;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-[16px] font-semibold text-slate-900 flex items-center gap-2",children:[e.jsx(Mn,{className:"h-5 w-5 text-primary"})," Attendance Pay Config"]}),e.jsx("p",{className:"mt-0.5 text-[13px] text-slate-400",children:"Configure which attendance statuses count as Paid Days and Working Days for payroll"})]}),j&&e.jsxs(y,{size:"sm",onClick:B,children:[e.jsx(ds,{className:"mr-1.5 h-3.5 w-3.5"})," Add Config"]})]}),e.jsx(rs,{actions:e.jsx("div",{className:"w-[180px]",children:e.jsx(ge,{value:s||null,onValueChange:I=>t(I),onSearch:l,isLoading:Y,options:H.map(I=>({value:I.id,label:I.name,hint:I.code})),placeholder:"All companies",searchPlaceholder:"Search companies..."})}),columns:Q,data:k,isLoading:q,searchPlaceholder:"Search statuses...",emptyMessage:"No pay configs found",emptyDescription:"Add configurations to define payroll day calculation rules.",totalCount:k.length}),e.jsx(He,{open:c,onOpenChange:r,children:e.jsxs(Ge,{size:"md",children:[e.jsxs(Be,{children:[e.jsx(We,{children:d?"Edit Pay Config":"Add Pay Config"}),e.jsx(Ze,{children:"Define how this attendance status maps to Paid Days and Working Days in payroll."})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-5 space-y-5",children:[e.jsxs("div",{children:[e.jsx(P,{children:"Company *"}),e.jsx("div",{className:"mt-1.5",children:e.jsx(ge,{value:u.company||null,onValueChange:I=>p(S=>({...S,company:I})),onSearch:l,isLoading:Y,selectedLabel:d?v:void 0,options:H.map(I=>({value:I.id,label:I.name,hint:I.code})),placeholder:"Select company",searchPlaceholder:"Search companies..."})})]}),e.jsxs("div",{children:[e.jsx(P,{children:"Attendance Status *"}),e.jsxs($e,{value:u.status_code,onValueChange:D,disabled:!!d,children:[e.jsx(Le,{className:"mt-1.5",children:e.jsx(qe,{placeholder:"Select status"})}),e.jsxs(Re,{children:[Se.map(I=>e.jsx(Z,{value:I.code,children:e.jsxs("span",{className:"flex items-center gap-2",children:[I.color&&e.jsx("span",{className:"inline-block h-2 w-2 rounded-full shrink-0",style:{backgroundColor:I.color}}),I.name,e.jsxs("span",{className:"text-[11px] text-slate-400",children:["(",I.code,")"]})]})},I.code)),Se.length===0&&e.jsx("div",{className:"px-3 py-2 text-[12px] text-slate-400",children:"All statuses are already configured for this company."})]})]}),d&&e.jsx("p",{className:"mt-1 text-[11px] text-slate-400",children:"Status cannot be changed after creation."})]}),e.jsxs("div",{className:"rounded-lg border border-slate-200 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[13px] font-medium text-slate-800",children:"Paid Day"}),e.jsx("p",{className:"text-[11px] text-slate-400",children:"Counts toward employee's paid days for salary"})]}),e.jsx(Ds,{checked:u.is_paid_day,onCheckedChange:I=>p(S=>({...S,is_paid_day:I}))})]}),u.is_paid_day&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(P,{className:"text-[12px] text-slate-600 whitespace-nowrap",children:"Weight per day"}),e.jsx(pn,{value:u.paid_day_weight,onChange:I=>p(S=>({...S,paid_day_weight:I}))}),e.jsx("span",{className:"text-[11px] text-slate-400",children:u.paid_day_weight===.5?"Half-day pay":u.paid_day_weight===1?"Full-day pay":"No pay"})]})]}),e.jsxs("div",{className:"rounded-lg border border-slate-200 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[13px] font-medium text-slate-800",children:"Working Day"}),e.jsx("p",{className:"text-[11px] text-slate-400",children:"Counts toward employee's working days count"})]}),e.jsx(Ds,{checked:u.is_working_day,onCheckedChange:I=>p(S=>({...S,is_working_day:I}))})]}),u.is_working_day&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(P,{className:"text-[12px] text-slate-600 whitespace-nowrap",children:"Weight per day"}),e.jsx(pn,{value:u.working_day_weight,onChange:I=>p(S=>({...S,working_day_weight:I}))}),e.jsx("span",{className:"text-[11px] text-slate-400",children:u.working_day_weight===.5?"Half-day":u.working_day_weight===1?"Full day":"Not counted"})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ds,{checked:u.is_active,onCheckedChange:I=>p(S=>({...S,is_active:I}))}),e.jsx(P,{children:"Active"})]}),u.status_code&&e.jsxs("div",{className:"rounded-lg bg-slate-50 border border-slate-200 p-4 text-[12px] space-y-1",children:[e.jsx("p",{className:"font-medium text-slate-700 mb-2",children:"Payroll Effect Preview"}),e.jsxs("div",{className:"flex justify-between",children:[e.jsxs("span",{className:"text-slate-500",children:[((Te=N.find(I=>I.code===u.status_code))==null?void 0:Te.name)??u.status_code," day"]}),e.jsxs("span",{className:"font-medium text-slate-700",children:[u.is_paid_day?`${u.paid_day_weight} paid day`:"LWP (no pay)",u.is_working_day?` · ${u.working_day_weight} working day`:""]})]})]})]}),e.jsxs(us,{children:[e.jsx(y,{variant:"outline",onClick:()=>r(!1),children:"Cancel"}),e.jsx(y,{disabled:!u.company||!u.status_code||oe,onClick:fe,children:oe?"Saving...":d?"Save Changes":"Add Config"})]})]})}),e.jsx(_n,{open:!!F,onOpenChange:I=>{I||O(null)},children:e.jsxs(bn,{children:[e.jsxs(Nn,{children:[e.jsx(wn,{children:"Delete Pay Config"}),e.jsx(Sn,{children:"This will remove the pay configuration. Payroll calculations will revert to the default formula for this status."})]}),e.jsxs(kn,{children:[e.jsx(Cn,{children:"Cancel"}),e.jsx(Dn,{className:"bg-red-600 hover:bg-red-700",onClick:()=>{V("pay_config","delete")&&F&&o.mutate(F,{onSuccess:()=>O(null)})},children:"Delete"})]})]})})]})}export{Pd as AnomaliesPage,Fd as AttendanceAnalyticsPage,ld as AttendanceLayout,qd as AttendancePayConfigPage,Nd as AttendancePoliciesPage,wd as AttendancePolicyDetailPage,Sd as AttendancePolicyFormPage,Ed as AttendanceReportsPage,Cd as CalendarPage,gd as DailyAttendancePage,jd as DailyTimesheetPage,xd as DashboardPage,yd as DevicesPage,kd as GeofencesPage,fd as MonthlyAttendancePage,$d as MonthlySummaryPage,Ad as OnDutyDetailPage,Dd as OnDutyPage,bd as OvertimeDetailPage,_d as OvertimePage,vd as RegularizationsPage,pd as RosterGridPage,hd as RostersPage,Md as ShiftAllocationPage,ud as ShiftsPage,Ld as StatusesPage,f as attendanceKeys,Qr as useAbsenceRules,_i as useAnalytics,ji as useAnomalies,dd as useApproveOnDutyRequest,yi as useApproveOutdoorDutyRequest,Ar as useApproveOvertime,Sr as useApproveRegularization,zt as useAttendanceStatuses,Qn as useAutoGenerateAttendance,ur as useBulkAllocateShift,xr as useBulkUploadRosters,ii as useCalendarHolidays,Ir as useCreateAbsenceRule,nr as useCreateAttendanceStatus,ci as useCreateCalendarHoliday,gr as useCreateDevice,ei as useCreateGeofence,Lr as useCreateLateComingRule,ui as useCreateOnDutyRequest,pi as useCreateOutdoorDutyRequest,Dr as useCreateOvertime,Fr as useCreatePolicy,Gr as useCreatePolicyAssignment,wr as useCreateRegularization,mr as useCreateRoster,ir as useCreateShift,ni as useCreateWorkCalendar,id as useDailyAttendance,Ci as useDailyTimesheet,Di as useDailyTimesheetBulkEntry,Ai as useDailyTimesheetSingleEntry,fi as useDashboard,Ur as useDeleteAbsenceRule,rr as useDeleteAttendanceStatus,oi as useDeleteCalendarHoliday,ti as useDeleteGeofence,Rr as useDeleteLateComingRule,Mr as useDeletePolicy,Wr as useDeletePolicyAssignment,or as useDeleteShift,ri as useDeleteWorkCalendar,jr as useDevices,hr as useDownloadRosterTemplate,vi as useExportReport,wi as useFreezeAttendance,Xr as useGeofences,$r as useLateComingRules,bi as useMonthlyAttendanceSummary,xi as useOnDutyRequests,hi as useOutdoorDutyRequests,Cr as useOvertimeRecords,Yr as usePenalties,Pr as usePolicies,Hn as usePolicy,Hr as usePolicyAssignments,Jr as useProcessPenalties,od as usePunch,cd as usePunches,ki as useRecalculateAttendance,Nr as useRegularizations,md as useReports,gi as useResolveAnomaly,Zr as useReversePenalty,pr as useRosterGrid,dr as useRosters,yr as useSaveRosterGrid,di as useSeedHolidays,rd as useShift,pa as useShifts,vr as useSyncDevice,Si as useUnfreezeAttendance,Kr as useUpdateAbsenceRule,lr as useUpdateAttendanceStatus,fr as useUpdateDevice,si as useUpdateGeofence,qr as useUpdateLateComingRule,Er as useUpdatePolicy,Br as useUpdatePolicyAssignment,cr as useUpdateShift,li as useUpdateWorkCalendar,ai as useWorkCalendars};
