const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/conclusionApi-Dp5idKr8.js","assets/radix-vendor-C2EbRL2a.js","assets/charts-vendor-Cji9-Yri.js","assets/utils-vendor-DHm03ykU.js","assets/ui-vendor-CFl7S1sk.js","assets/socket-vendor-TjCxX7sJ.js","assets/redux-vendor-tbZCm13o.js","assets/router-vendor-1fSSvDCY.js"])))=>i.map(i=>d[i]); var kh=Object.defineProperty;var Rh=(t,s,a)=>s in t?kh(t,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[s]=a;var an=(t,s,a)=>Rh(t,typeof s!="symbol"?s+"":s,a);import{j as e,S as Bc,R as zc,I as Hc,F as qc,a as Dh,T as Ph,P as Eh,C as Mh,b as Ih,O as Wc,c as Kc,d as _h,e as Lh,f as Fh,D as Oh,g as $h,A as Uh,h as Vh,i as Bh,k as zh,l as Hh,m as qh,n as Wh,V as Kh,o as Gh,p as Yh,q as Zh,r as Xh,s as Qh,t as Jh,u as ep,v as tp,w as sp,x as ap,y as rp,z as np,B as ip,E as op,G as lp,H as cp,L as dp,J as mp,K as up,M as Gc,N as Yc,Q as hp,U as Zc,W as Xc,X as pp,Y as xp,Z as gp,_ as fp,$ as yp,a0 as vp,a1 as bp,a2 as jp,a3 as Np,a4 as wp,a5 as Cp,a6 as Sp,a7 as Ap,a8 as Tp,a9 as kp,aa as Rp,ab as Dp}from"./radix-vendor-C2EbRL2a.js";import{a as Pp,r as g,c as Qc,d as Ni,B as Ep,C as Jc,X as ed,Y as td,T as wi,L as sd,e as rn,P as Mp,f as Ip,g as _p,h as Lp,i as zo,j as _r,k as Lr,b as Fp}from"./charts-vendor-Cji9-Yri.js";import{a as ad,f as rd,b as pe,d as Op,c as $p,e as Up,s as Kt,g as Ci,h as Ho,i as Vp,j as us,k as Ha,l as Si,m as nd,n as $t,o as Ht,p as nn,q as vs,r as Bp,t as Bn,u as zp,v as zn,w as Hp,x as qp,y as Wp,z as Kp,A as on,B as qo,C as Gp,D as id,E as od,F as Ai,G as Ti,H as Yp,I as Zp,J as ld}from"./utils-vendor-DHm03ykU.js";import{L as Xp,C as Re,a as Hn,b as Le,X as ft,H as Qp,c as cd,U as rt,F as Te,d as ve,S as wa,P as Is,e as Jp,f as ex,B as Ut,g as la,h as ln,i as dd,j as md,k as Ca,l as tx,m as Qa,n as qe,R as Lt,I as Fr,T as it,o as De,p as ls,q as sx,A as wt,r as is,M as ws,s as Or,t as as,u as ax,D as ns,Z as ki,v as at,w as Yt,x as ud,y as hd,z as Ze,E as fe,G as $r,J as qn,O as Wn,K as _s,N as rx,Q as nx,V as ix,W as ox,Y as lx,_ as cx,$ as dx,a0 as mx,a1 as ux,a2 as hx,a3 as pd,a4 as xd,a5 as Ls,a6 as gd,a7 as Wo,a8 as dr,a9 as fd,aa as px,ab as Us,ac as At,ad as ba,ae as xx,af as gx,ag as fx,ah as Ri,ai as Ur,aj as Gt,ak as yx,al as vx,am as bx,an as jx,ao as Nx,ap as wx,aq as yd,ar as fr,as as Vr,at as Kn,au as Cx,av as vd,aw as Sx,ax as Ax,ay as Tx,az as Di,aA as bd,aB as kx,aC as Rx,aD as Br,aE as zr,aF as Pi,aG as Dx,aH as jd,aI as Ko,aJ as Vs,aK as Px,aL as Ex,aM as Ei,aN as Mx,aO as ua,aP as Nd,aQ as Go,aR as Ix,aS as _x,aT as Lx,aU as wd,aV as Fx,aW as Ox,aX as $x,aY as Ux,aZ as Vx}from"./ui-vendor-CFl7S1sk.js";import{l as Bx}from"./socket-vendor-TjCxX7sJ.js";import{c as Cd,a as zx}from"./redux-vendor-tbZCm13o.js";import{u as Hr,a as Ja,b as Bs,B as Hx,R as qx,c as ut}from"./router-vendor-1fSSvDCY.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))r(n);new MutationObserver(n=>{for(const i of n)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function a(n){const i={};return n.integrity&&(i.integrity=n.integrity),n.referrerPolicy&&(i.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?i.credentials="include":n.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(n){if(n.ep)return;n.ep=!0;const i=a(n);fetch(n.href,i)}})();var Gn={},Yo=Pp;Gn.createRoot=Yo.createRoot,Gn.hydrateRoot=Yo.hydrateRoot;var Sd={exports:{}},Ad={};/** * @license React * use-sync-external-store-with-selector.production.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var er=g;function Wx(t,s){return t===s&&(t!==0||1/t===1/s)||t!==t&&s!==s}var Kx=typeof Object.is=="function"?Object.is:Wx,Gx=er.useSyncExternalStore,Yx=er.useRef,Zx=er.useEffect,Xx=er.useMemo,Qx=er.useDebugValue;Ad.useSyncExternalStoreWithSelector=function(t,s,a,r,n){var i=Yx(null);if(i.current===null){var o={hasValue:!1,value:null};i.current=o}else o=i.current;i=Xx(function(){function c(x){if(!d){if(d=!0,m=x,x=r(x),n!==void 0&&o.hasValue){var p=o.value;if(n(p,x))return u=p}return u=x}if(p=u,Kx(m,x))return p;var y=r(x);return n!==void 0&&n(p,y)?(m=x,p):(m=x,u=y)}var d=!1,m,u,h=a===void 0?null:a;return[function(){return c(s())},h===null?void 0:function(){return c(h())}]},[s,a,r,n]);var l=Gx(t,i[0],i[1]);return Zx(function(){o.hasValue=!0,o.value=l},[l]),Qx(l),l};Sd.exports=Ad;var Jx=Sd.exports;function eg(t){t()}function tg(){let t=null,s=null;return{clear(){t=null,s=null},notify(){eg(()=>{let a=t;for(;a;)a.callback(),a=a.next})},get(){const a=[];let r=t;for(;r;)a.push(r),r=r.next;return a},subscribe(a){let r=!0;const n=s={callback:a,next:null,prev:s};return n.prev?n.prev.next=n:t=n,function(){!r||t===null||(r=!1,n.next?n.next.prev=n.prev:s=n.prev,n.prev?n.prev.next=n.next:t=n.next)}}}}var Zo={notify(){},get:()=>[]};function sg(t,s){let a,r=Zo,n=0,i=!1;function o(y){m();const v=r.subscribe(y);let N=!1;return()=>{N||(N=!0,v(),u())}}function l(){r.notify()}function c(){p.onStateChange&&p.onStateChange()}function d(){return i}function m(){n++,a||(a=t.subscribe(c),r=tg())}function u(){n--,a&&n===0&&(a(),a=void 0,r.clear(),r=Zo)}function h(){i||(i=!0,m())}function x(){i&&(i=!1,u())}const p={addNestedSub:o,notifyNestedSubs:l,handleChangeWrapper:c,isSubscribed:d,trySubscribe:h,tryUnsubscribe:x,getListeners:()=>r};return p}var ag=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",rg=ag(),ng=()=>typeof navigator<"u"&&navigator.product==="ReactNative",ig=ng(),og=()=>rg||ig?g.useLayoutEffect:g.useEffect,lg=og(),cn=Symbol.for("react-redux-context"),dn=typeof globalThis<"u"?globalThis:{};function cg(){if(!g.createContext)return{};const t=dn[cn]??(dn[cn]=new Map);let s=t.get(g.createContext);return s||(s=g.createContext(null),t.set(g.createContext,s)),s}var Fs=cg();function dg(t){const{children:s,context:a,serverState:r,store:n}=t,i=g.useMemo(()=>{const c=sg(n);return{store:n,subscription:c,getServerState:r?()=>r:void 0}},[n,r]),o=g.useMemo(()=>n.getState(),[n]);lg(()=>{const{subscription:c}=i;return c.onStateChange=c.notifyNestedSubs,c.trySubscribe(),o!==n.getState()&&c.notifyNestedSubs(),()=>{c.tryUnsubscribe(),c.onStateChange=void 0}},[i,o]);const l=a||Fs;return g.createElement(l.Provider,{value:i},s)}var mg=dg;function Mi(t=Fs){return function(){return g.useContext(t)}}var Td=Mi();function kd(t=Fs){const s=t===Fs?Td:Mi(t),a=()=>{const{store:r}=s();return r};return Object.assign(a,{withTypes:()=>a}),a}var ug=kd();function hg(t=Fs){const s=t===Fs?ug:kd(t),a=()=>s().dispatch;return Object.assign(a,{withTypes:()=>a}),a}var pg=hg(),xg=(t,s)=>t===s;function gg(t=Fs){const s=t===Fs?Td:Mi(t),a=(r,n={})=>{const{equalityFn:i=xg}=typeof n=="function"?{equalityFn:n}:n,o=s(),{store:l,subscription:c,getServerState:d}=o;g.useRef(!0);const m=g.useCallback({[r.name](h){return r(h)}}[r.name],[r]),u=Jx.useSyncExternalStoreWithSelector(c.addNestedSub,l.getState,d||l.getState,m,i);return g.useDebugValue(u),u};return Object.assign(a,{withTypes:()=>a}),a}var fg=gg(),Yn=function(t,s){return Yn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(a,r){a.__proto__=r}||function(a,r){for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(a[n]=r[n])},Yn(t,s)};function yg(t,s){if(typeof s!="function"&&s!==null)throw new TypeError("Class extends value "+String(s)+" is not a constructor or null");Yn(t,s);function a(){this.constructor=t}t.prototype=s===null?Object.create(s):(a.prototype=s.prototype,new a)}var Sr=function(){return Sr=Object.assign||function(s){for(var a,r=1,n=arguments.length;r0&&p[p.length-1])||j[0]!==6&&j[0]!==2)){v=0;continue}if(j[0]===3&&(!p||j[1]>p[0]&&j[1]0?setTimeout(x,b):x(null)}}window.addEventListener("storage",N),m.addToWaiting(N);var f=setTimeout(N,Math.max(0,u-Date.now()))})];case 1:return h.sent(),[2]}})})},m.addToWaiting=function(u){this.removeFromWaiting(u),m.waiters!==void 0&&m.waiters.push(u)},m.removeFromWaiting=function(u){m.waiters!==void 0&&(m.waiters=m.waiters.filter(function(h){return h!==u}))},m.notifyWaiters=function(){m.waiters!==void 0&&m.waiters.slice().forEach(function(u){return u()})},m.prototype.releaseLock=function(u){return a(this,void 0,void 0,function(){return r(this,function(h){switch(h.label){case 0:return[4,this.releaseLock__private__(u)];case 1:return[2,h.sent()]}})})},m.prototype.releaseLock__private__=function(u){return a(this,void 0,void 0,function(){var h,x,p,y;return r(this,function(v){switch(v.label){case 0:return h=this.storageHandler===void 0?o:this.storageHandler,x=i+"-"+u,(p=h.getItemSync(x))===null?[2]:(y=JSON.parse(p)).id!==this.id?[3,2]:[4,Ks.default().lock(y.iat)];case 1:v.sent(),this.acquiredIatSet.delete(y.iat),h.removeItemSync(x),Ks.default().unlock(y.iat),m.notifyWaiters(),v.label=2;case 2:return[2]}})})},m.lockCorrector=function(u){for(var h=Date.now()-5e3,x=u,p=[],y=0;;){var v=x.keySync(y);if(v===null)break;p.push(v),y++}for(var N=!1,f=0;f.")},jg=Sr(Sr({},bg),{buildAuthorizeUrl:Ft,buildLogoutUrl:Ft,getAccessTokenSilently:Ft,getAccessTokenWithPopup:Ft,getIdTokenClaims:Ft,loginWithRedirect:Ft,loginWithPopup:Ft,connectAccountWithRedirect:Ft,logout:Ft,handleRedirectCallback:Ft,getDpopNonce:Ft,setDpopNonce:Ft,generateDpopProof:Ft,createFetcher:Ft}),Ng=g.createContext(jg);(function(t){yg(s,t);function s(a,r){var n=t.call(this,r??a)||this;return n.error=a,n.error_description=r,Object.setPrototypeOf(n,s.prototype),n}return s})(Error);var wg=function(t){return t===void 0&&(t=Ng),g.useContext(t)};const mn="idToken",un="userData",Cg=()=>!0;class Be{static setAccessToken(s){}static getAccessToken(){return null}static setRefreshToken(s){}static getRefreshToken(){return null}static setIdToken(s){sessionStorage.setItem(mn,s)}static getIdToken(){return sessionStorage.getItem(mn)}static setUserData(s){localStorage.setItem(un,JSON.stringify(s))}static getUserData(){const s=localStorage.getItem(un);if(!s)return null;try{return JSON.parse(s)}catch{return null}}static clearAll(){try{sessionStorage.setItem("__logout_in_progress__","true"),sessionStorage.setItem("__force_logout__","true")}catch(s){console.warn("Could not set logout flags:",s)}try{localStorage.removeItem(un),sessionStorage.removeItem(mn)}catch(s){console.warn("Error clearing user data:",s)}{try{sessionStorage.setItem("__logout_in_progress__","true"),sessionStorage.setItem("__force_logout__","true")}catch{}return}}static hasAccessToken(){return!!this.getUserData()}static hasRefreshToken(){return!!this.getUserData()}static isLocalhost(){return window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"||window.location.hostname===""}static isProduction(){return Cg()}}function mr(t,s=5){if(!t)return!0;try{const a=t.split(".");if(a.length!==3||!a[1])return!0;const n=JSON.parse(atob(a[1])).exp*1e3,i=Date.now(),o=s*60*1e3;return n-it,t=>Promise.reject(t));ie.interceptors.response.use(t=>t,async t=>{var a,r;const s=t.config;if(t.code==="ERR_NETWORK"||t.code==="ECONNREFUSED"||(a=t.message)!=null&&a.includes("ERR_CONNECTION_REFUSED"),((r=t.response)==null?void 0:r.status)===401&&!s._retry){s._retry=!0;const n=!0;try{const i=Be.getRefreshToken(),o=await ad.post(`${Rd}/auth/refresh`,n?{}:{refreshToken:i},{withCredentials:!0}),c=(o.data.data||o.data).accessToken;return c&&(Be.setAccessToken(c),s.headers.Authorization=`Bearer ${c}`),ie(s)}catch(i){return Be.clearAll(),window.location.href="/",Promise.reject(i)}}return Promise.reject(t)});async function Sg(t,s){var a,r;try{const n=await ie.post("/auth/token-exchange",{code:t,redirectUri:s},{responseType:"json",headers:{"Content-Type":"application/json",Accept:"application/json"}});if(Array.isArray(n.data))throw console.error("❌ Response is an array (buffer issue):",{arrayLength:n.data.length,firstFew:n.data.slice(0,10),rawResponse:n}),new Error("Invalid response format: received array instead of JSON. Check Content-Type header.");const i=n.data,o=i.data||i;return o.user&&Be.setUserData(o.user),o.idToken&&Be.setIdToken(o.idToken),o.accessToken&&o.refreshToken&&(Be.setAccessToken(o.accessToken),Be.setRefreshToken(o.refreshToken)),o}catch(n){throw console.error("❌ Token exchange failed:",{message:n.message,response:(a=n.response)==null?void 0:a.data,status:(r=n.response)==null?void 0:r.status,code:t?`${t.substring(0,10)}...`:"MISSING",redirectUri:s}),n}}async function Ag(){var n;const t=Be.getRefreshToken();if(!t)throw new Error("No refresh token available");const a=(await ie.post("/auth/refresh",{refreshToken:t})).data,r=((n=a.data)==null?void 0:n.accessToken)||a.accessToken;if(r)return r;throw new Error("Failed to refresh token")}async function Jo(){const s=(await ie.get("/auth/me")).data;return s.data||s}async function Tg(){var t,s;try{await ie.post("/auth/logout",{},{withCredentials:!0})}catch(a){console.error("📡 Logout API error:",a),console.error("📡 Error details:",{message:a.message,status:(t=a.response)==null?void 0:t.status,data:(s=a.response)==null?void 0:s.data})}}const Dd=g.createContext(void 0);function kg({children:t}){const[s,a]=g.useState(!1),[r,n]=g.useState(!0),[i,o]=g.useState(null),[l,c]=g.useState(null),[d,m]=g.useState(!1);g.useEffect(()=>{const f=sessionStorage.getItem("__logout_in_progress__"),b=sessionStorage.getItem("__force_logout__");if(f==="true"||b==="true"){sessionStorage.removeItem("__logout_in_progress__"),sessionStorage.removeItem("__force_logout__"),Be.clearAll();try{localStorage.clear(),sessionStorage.clear()}catch(E){console.error("Error clearing storage:",E)}a(!1),o(null),n(!1),c(null);return}const j=new URLSearchParams(window.location.search);if(j.has("logout")||j.has("okta_logged_out")){Be.clearAll(),localStorage.clear(),sessionStorage.clear(),a(!1),o(null),n(!1);const E=new URLSearchParams;j.has("okta_logged_out")&&E.set("okta_logged_out","true");const w=E.toString()?`/?${E.toString()}`:"/";window.history.replaceState({},document.title,w);return}const C=Be.getAccessToken(),R=Be.getRefreshToken(),I=Be.getUserData();if(!(C||R||I)){a(!1),o(null),n(!1);return}d?n(!1):h()},[d]),g.useEffect(()=>{if(!s)return;const b=setInterval(async()=>{const j=Be.getAccessToken();if(j&&mr(j,5))try{await v()}catch(C){console.error("Silent refresh failed:",C)}},5*60*1e3);return()=>clearInterval(b)},[s]);const u=g.useRef(!1);g.useEffect(()=>{if(u.current||window.location.pathname!=="/login/callback")return;(async()=>{u.current=!0;const b=new URLSearchParams(window.location.search),j=b.get("code"),C=b.get("error");if(window.history.replaceState({},document.title,"/login/callback"),C){c(new Error(`Authentication error: ${C}`)),n(!1);return}if(!j){n(!1);return}try{n(!0),a(!1),c(null);const R=`${window.location.origin}/login/callback`,I=await Sg(j,R);o(I.user),a(!0),c(null),window.history.replaceState({},document.title,"/")}catch(R){console.error("❌ Token exchange error in AuthContext:",R),c(R),a(!1),o(null),u.current=!1}finally{n(!1)}})()},[]);const h=async()=>{if(d){n(!1);return}try{n(!0);const f=Be.getAccessToken(),b=Be.getUserData();if(!f){a(!1),o(null),n(!1);return}if(mr(f))try{await v();const j=Be.getAccessToken();if(j&&!mr(j)){const C=Be.getUserData();if(C)o(C),a(!0);else try{const R=await Jo();o(R),Be.setUserData(R),a(!0)}catch{Be.clearAll(),a(!1),o(null)}}else Be.clearAll(),a(!1),o(null)}catch{Be.clearAll(),a(!1),o(null)}else if(b)o(b),a(!0);else try{const j=await Jo();o(j),Be.setUserData(j),a(!0)}catch{Be.clearAll(),a(!1),o(null)}}catch(f){console.error("Error checking auth status:",f),c(f),Be.clearAll(),a(!1),o(null)}finally{n(!1)}},x=async()=>{try{c(null);const f="https://dev-830839.oktapreview.com",b="0oa2j8slwj5S4bG5k0h8",j=`${window.location.origin}/login/callback`,C="code",R="openid profile email",I=Math.random().toString(36).substring(7),T=new URLSearchParams(window.location.search),E=T.has("logout")||T.has("okta_logged_out");let w=`${f}/oauth2/default/v1/authorize?client_id=${b}&redirect_uri=${encodeURIComponent(j)}&response_type=${C}&scope=${encodeURIComponent(R)}&state=${I}`;E&&(w+="&prompt=login"),window.location.href=w}catch(f){throw c(f),f}},p=async()=>{try{Be.getIdToken(),sessionStorage.setItem("__logout_in_progress__","true"),sessionStorage.setItem("__force_logout__","true"),m(!0),a(!1),o(null),c(null),n(!0);try{await Tg()}catch(C){console.error("🚪 Logout API error:",C),console.warn("🚪 Backend logout failed - httpOnly cookies may not be cleared")}const f=sessionStorage.getItem("__logout_in_progress__"),b=sessionStorage.getItem("__force_logout__");Be.clearAll(),f&&sessionStorage.setItem("__logout_in_progress__",f),b&&sessionStorage.setItem("__force_logout__",b),await new Promise(C=>setTimeout(C,100));const j=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(j)}catch(f){console.error("🚪 Logout error:",f);try{localStorage.clear(),sessionStorage.clear(),sessionStorage.setItem("__logout_in_progress__","true");const b=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(b)}catch{window.location.replace("/?logout="+Date.now())}}},y=async()=>{const f=Be.getAccessToken();if(f&&!mr(f))return f;try{return await v(),Be.getAccessToken()}catch{return null}},v=async()=>{try{if(await Ag())return;throw new Error("Failed to refresh token")}catch(f){throw Be.clearAll(),a(!1),o(null),f}},N={isAuthenticated:s,isLoading:r,user:i,error:l,login:x,logout:p,getAccessTokenSilently:y,refreshTokenSilently:v};return e.jsx(Dd.Provider,{value:N,children:t})}function Rg({children:t}){return e.jsx(kg,{children:t})}function Bt(){const t=g.useContext(Dd);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t}function Gs(t){return(t==null?void 0:t.role)==="ADMIN"}function Ma(t){return(t==null?void 0:t.role)==="MANAGEMENT"}function qr(t){return(t==null?void 0:t.role)==="MANAGEMENT"||(t==null?void 0:t.role)==="ADMIN"}const el=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,tl=Qc,Pd=(t,s)=>a=>{var r;if((s==null?void 0:s.variants)==null)return tl(t,a==null?void 0:a.class,a==null?void 0:a.className);const{variants:n,defaultVariants:i}=s,o=Object.keys(n).map(d=>{const m=a==null?void 0:a[d],u=i==null?void 0:i[d];if(m===null)return null;const h=el(m)||el(u);return n[d][h]}),l=a&&Object.entries(a).reduce((d,m)=>{let[u,h]=m;return h===void 0||(d[u]=h),d},{}),c=s==null||(r=s.compoundVariants)===null||r===void 0?void 0:r.reduce((d,m)=>{let{class:u,className:h,...x}=m;return Object.entries(x).every(p=>{let[y,v]=p;return Array.isArray(v)?v.includes({...i,...l}[y]):{...i,...l}[y]===v})?[...d,u,h]:d},[]);return tl(t,o,c,a==null?void 0:a.class,a==null?void 0:a.className)},Li="-",Dg=t=>{const s=Eg(t),{conflictingClassGroups:a,conflictingClassGroupModifiers:r}=t;return{getClassGroupId:o=>{const l=o.split(Li);return l[0]===""&&l.length!==1&&l.shift(),Ed(l,s)||Pg(o)},getConflictingClassGroupIds:(o,l)=>{const c=a[o]||[];return l&&r[o]?[...c,...r[o]]:c}}},Ed=(t,s)=>{var o;if(t.length===0)return s.classGroupId;const a=t[0],r=s.nextPart.get(a),n=r?Ed(t.slice(1),r):void 0;if(n)return n;if(s.validators.length===0)return;const i=t.join(Li);return(o=s.validators.find(({validator:l})=>l(i)))==null?void 0:o.classGroupId},sl=/^\[(.+)\]$/,Pg=t=>{if(sl.test(t)){const s=sl.exec(t)[1],a=s==null?void 0:s.substring(0,s.indexOf(":"));if(a)return"arbitrary.."+a}},Eg=t=>{const{theme:s,prefix:a}=t,r={nextPart:new Map,validators:[]};return Ig(Object.entries(t.classGroups),a).forEach(([i,o])=>{Zn(o,r,i,s)}),r},Zn=(t,s,a,r)=>{t.forEach(n=>{if(typeof n=="string"){const i=n===""?s:al(s,n);i.classGroupId=a;return}if(typeof n=="function"){if(Mg(n)){Zn(n(r),s,a,r);return}s.validators.push({validator:n,classGroupId:a});return}Object.entries(n).forEach(([i,o])=>{Zn(o,al(s,i),a,r)})})},al=(t,s)=>{let a=t;return s.split(Li).forEach(r=>{a.nextPart.has(r)||a.nextPart.set(r,{nextPart:new Map,validators:[]}),a=a.nextPart.get(r)}),a},Mg=t=>t.isThemeGetter,Ig=(t,s)=>s?t.map(([a,r])=>{const n=r.map(i=>typeof i=="string"?s+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([o,l])=>[s+o,l])):i);return[a,n]}):t,_g=t=>{if(t<1)return{get:()=>{},set:()=>{}};let s=0,a=new Map,r=new Map;const n=(i,o)=>{a.set(i,o),s++,s>t&&(s=0,r=a,a=new Map)};return{get(i){let o=a.get(i);if(o!==void 0)return o;if((o=r.get(i))!==void 0)return n(i,o),o},set(i,o){a.has(i)?a.set(i,o):n(i,o)}}},Md="!",Lg=t=>{const{separator:s,experimentalParseClassName:a}=t,r=s.length===1,n=s[0],i=s.length,o=l=>{const c=[];let d=0,m=0,u;for(let v=0;vm?u-m:void 0;return{modifiers:c,hasImportantModifier:x,baseClassName:p,maybePostfixModifierPosition:y}};return a?l=>a({className:l,parseClassName:o}):o},Fg=t=>{if(t.length<=1)return t;const s=[];let a=[];return t.forEach(r=>{r[0]==="["?(s.push(...a.sort(),r),a=[]):a.push(r)}),s.push(...a.sort()),s},Og=t=>({cache:_g(t.cacheSize),parseClassName:Lg(t),...Dg(t)}),$g=/\s+/,Ug=(t,s)=>{const{parseClassName:a,getClassGroupId:r,getConflictingClassGroupIds:n}=s,i=[],o=t.trim().split($g);let l="";for(let c=o.length-1;c>=0;c-=1){const d=o[c],{modifiers:m,hasImportantModifier:u,baseClassName:h,maybePostfixModifierPosition:x}=a(d);let p=!!x,y=r(p?h.substring(0,x):h);if(!y){if(!p){l=d+(l.length>0?" "+l:l);continue}if(y=r(h),!y){l=d+(l.length>0?" "+l:l);continue}p=!1}const v=Fg(m).join(":"),N=u?v+Md:v,f=N+y;if(i.includes(f))continue;i.push(f);const b=n(y,p);for(let j=0;j0?" "+l:l)}return l};function Vg(){let t=0,s,a,r="";for(;t{if(typeof t=="string")return t;let s,a="";for(let r=0;ru(m),t());return a=Og(d),r=a.cache.get,n=a.cache.set,i=l,l(c)}function l(c){const d=r(c);if(d)return d;const m=Ug(c,a);return n(c,m),m}return function(){return i(Vg.apply(null,arguments))}}const Ge=t=>{const s=a=>a[t]||[];return s.isThemeGetter=!0,s},_d=/^\[(?:([a-z-]+):)?(.+)\]$/i,zg=/^\d+\/\d+$/,Hg=new Set(["px","full","screen"]),qg=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Wg=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Kg=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,Gg=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Yg=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,gs=t=>ya(t)||Hg.has(t)||zg.test(t),As=t=>Sa(t,"length",af),ya=t=>!!t&&!Number.isNaN(Number(t)),hn=t=>Sa(t,"number",ya),Ia=t=>!!t&&Number.isInteger(Number(t)),Zg=t=>t.endsWith("%")&&ya(t.slice(0,-1)),Me=t=>_d.test(t),Ts=t=>qg.test(t),Xg=new Set(["length","size","percentage"]),Qg=t=>Sa(t,Xg,Ld),Jg=t=>Sa(t,"position",Ld),ef=new Set(["image","url"]),tf=t=>Sa(t,ef,nf),sf=t=>Sa(t,"",rf),_a=()=>!0,Sa=(t,s,a)=>{const r=_d.exec(t);return r?r[1]?typeof s=="string"?r[1]===s:s.has(r[1]):a(r[2]):!1},af=t=>Wg.test(t)&&!Kg.test(t),Ld=()=>!1,rf=t=>Gg.test(t),nf=t=>Yg.test(t),of=()=>{const t=Ge("colors"),s=Ge("spacing"),a=Ge("blur"),r=Ge("brightness"),n=Ge("borderColor"),i=Ge("borderRadius"),o=Ge("borderSpacing"),l=Ge("borderWidth"),c=Ge("contrast"),d=Ge("grayscale"),m=Ge("hueRotate"),u=Ge("invert"),h=Ge("gap"),x=Ge("gradientColorStops"),p=Ge("gradientColorStopPositions"),y=Ge("inset"),v=Ge("margin"),N=Ge("opacity"),f=Ge("padding"),b=Ge("saturate"),j=Ge("scale"),C=Ge("sepia"),R=Ge("skew"),I=Ge("space"),T=Ge("translate"),E=()=>["auto","contain","none"],w=()=>["auto","hidden","clip","visible","scroll"],S=()=>["auto",Me,s],D=()=>[Me,s],H=()=>["",gs,As],L=()=>["auto",ya,Me],F=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],A=()=>["solid","dashed","dotted","double","none"],k=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],P=()=>["start","end","center","between","around","evenly","stretch"],_=()=>["","0",Me],W=()=>["auto","avoid","all","avoid-page","page","left","right","column"],Z=()=>[ya,Me];return{cacheSize:500,separator:":",theme:{colors:[_a],spacing:[gs,As],blur:["none","",Ts,Me],brightness:Z(),borderColor:[t],borderRadius:["none","","full",Ts,Me],borderSpacing:D(),borderWidth:H(),contrast:Z(),grayscale:_(),hueRotate:Z(),invert:_(),gap:D(),gradientColorStops:[t],gradientColorStopPositions:[Zg,As],inset:S(),margin:S(),opacity:Z(),padding:D(),saturate:Z(),scale:Z(),sepia:_(),skew:Z(),space:D(),translate:D()},classGroups:{aspect:[{aspect:["auto","square","video",Me]}],container:["container"],columns:[{columns:[Ts]}],"break-after":[{"break-after":W()}],"break-before":[{"break-before":W()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...F(),Me]}],overflow:[{overflow:w()}],"overflow-x":[{"overflow-x":w()}],"overflow-y":[{"overflow-y":w()}],overscroll:[{overscroll:E()}],"overscroll-x":[{"overscroll-x":E()}],"overscroll-y":[{"overscroll-y":E()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[y]}],"inset-x":[{"inset-x":[y]}],"inset-y":[{"inset-y":[y]}],start:[{start:[y]}],end:[{end:[y]}],top:[{top:[y]}],right:[{right:[y]}],bottom:[{bottom:[y]}],left:[{left:[y]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",Ia,Me]}],basis:[{basis:S()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Me]}],grow:[{grow:_()}],shrink:[{shrink:_()}],order:[{order:["first","last","none",Ia,Me]}],"grid-cols":[{"grid-cols":[_a]}],"col-start-end":[{col:["auto",{span:["full",Ia,Me]},Me]}],"col-start":[{"col-start":L()}],"col-end":[{"col-end":L()}],"grid-rows":[{"grid-rows":[_a]}],"row-start-end":[{row:["auto",{span:[Ia,Me]},Me]}],"row-start":[{"row-start":L()}],"row-end":[{"row-end":L()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Me]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Me]}],gap:[{gap:[h]}],"gap-x":[{"gap-x":[h]}],"gap-y":[{"gap-y":[h]}],"justify-content":[{justify:["normal",...P()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...P(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...P(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[f]}],px:[{px:[f]}],py:[{py:[f]}],ps:[{ps:[f]}],pe:[{pe:[f]}],pt:[{pt:[f]}],pr:[{pr:[f]}],pb:[{pb:[f]}],pl:[{pl:[f]}],m:[{m:[v]}],mx:[{mx:[v]}],my:[{my:[v]}],ms:[{ms:[v]}],me:[{me:[v]}],mt:[{mt:[v]}],mr:[{mr:[v]}],mb:[{mb:[v]}],ml:[{ml:[v]}],"space-x":[{"space-x":[I]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[I]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",Me,s]}],"min-w":[{"min-w":[Me,s,"min","max","fit"]}],"max-w":[{"max-w":[Me,s,"none","full","min","max","fit","prose",{screen:[Ts]},Ts]}],h:[{h:[Me,s,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[Me,s,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[Me,s,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[Me,s,"auto","min","max","fit"]}],"font-size":[{text:["base",Ts,As]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",hn]}],"font-family":[{font:[_a]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",Me]}],"line-clamp":[{"line-clamp":["none",ya,hn]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",gs,Me]}],"list-image":[{"list-image":["none",Me]}],"list-style-type":[{list:["none","disc","decimal",Me]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[t]}],"placeholder-opacity":[{"placeholder-opacity":[N]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[t]}],"text-opacity":[{"text-opacity":[N]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...A(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",gs,As]}],"underline-offset":[{"underline-offset":["auto",gs,Me]}],"text-decoration-color":[{decoration:[t]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:D()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Me]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Me]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[N]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...F(),Jg]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",Qg]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},tf]}],"bg-color":[{bg:[t]}],"gradient-from-pos":[{from:[p]}],"gradient-via-pos":[{via:[p]}],"gradient-to-pos":[{to:[p]}],"gradient-from":[{from:[x]}],"gradient-via":[{via:[x]}],"gradient-to":[{to:[x]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[N]}],"border-style":[{border:[...A(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[N]}],"divide-style":[{divide:A()}],"border-color":[{border:[n]}],"border-color-x":[{"border-x":[n]}],"border-color-y":[{"border-y":[n]}],"border-color-s":[{"border-s":[n]}],"border-color-e":[{"border-e":[n]}],"border-color-t":[{"border-t":[n]}],"border-color-r":[{"border-r":[n]}],"border-color-b":[{"border-b":[n]}],"border-color-l":[{"border-l":[n]}],"divide-color":[{divide:[n]}],"outline-style":[{outline:["",...A()]}],"outline-offset":[{"outline-offset":[gs,Me]}],"outline-w":[{outline:[gs,As]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:H()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[N]}],"ring-offset-w":[{"ring-offset":[gs,As]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",Ts,sf]}],"shadow-color":[{shadow:[_a]}],opacity:[{opacity:[N]}],"mix-blend":[{"mix-blend":[...k(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":k()}],filter:[{filter:["","none"]}],blur:[{blur:[a]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",Ts,Me]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[m]}],invert:[{invert:[u]}],saturate:[{saturate:[b]}],sepia:[{sepia:[C]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[a]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[m]}],"backdrop-invert":[{"backdrop-invert":[u]}],"backdrop-opacity":[{"backdrop-opacity":[N]}],"backdrop-saturate":[{"backdrop-saturate":[b]}],"backdrop-sepia":[{"backdrop-sepia":[C]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[o]}],"border-spacing-x":[{"border-spacing-x":[o]}],"border-spacing-y":[{"border-spacing-y":[o]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",Me]}],duration:[{duration:Z()}],ease:[{ease:["linear","in","out","in-out",Me]}],delay:[{delay:Z()}],animate:[{animate:["none","spin","ping","pulse","bounce",Me]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[j]}],"scale-x":[{"scale-x":[j]}],"scale-y":[{"scale-y":[j]}],rotate:[{rotate:[Ia,Me]}],"translate-x":[{"translate-x":[T]}],"translate-y":[{"translate-y":[T]}],"skew-x":[{"skew-x":[R]}],"skew-y":[{"skew-y":[R]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Me]}],accent:[{accent:["auto",t]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Me]}],"caret-color":[{caret:[t]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":D()}],"scroll-mx":[{"scroll-mx":D()}],"scroll-my":[{"scroll-my":D()}],"scroll-ms":[{"scroll-ms":D()}],"scroll-me":[{"scroll-me":D()}],"scroll-mt":[{"scroll-mt":D()}],"scroll-mr":[{"scroll-mr":D()}],"scroll-mb":[{"scroll-mb":D()}],"scroll-ml":[{"scroll-ml":D()}],"scroll-p":[{"scroll-p":D()}],"scroll-px":[{"scroll-px":D()}],"scroll-py":[{"scroll-py":D()}],"scroll-ps":[{"scroll-ps":D()}],"scroll-pe":[{"scroll-pe":D()}],"scroll-pt":[{"scroll-pt":D()}],"scroll-pr":[{"scroll-pr":D()}],"scroll-pb":[{"scroll-pb":D()}],"scroll-pl":[{"scroll-pl":D()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Me]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[gs,As,hn]}],stroke:[{stroke:[t,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}},lf=Bg(of);function oe(...t){return lf(Qc(t))}const qa=Pd("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background text-foreground hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9 rounded-md"}},defaultVariants:{variant:"default",size:"default"}}),M=g.forwardRef(({className:t,variant:s,size:a,asChild:r=!1,...n},i)=>{const o=r?Bc:"button";return e.jsx(o,{"data-slot":"button",className:oe(qa({variant:s,size:a,className:t})),ref:i,...n})});M.displayName="Button";function G({className:t,...s}){return e.jsx("div",{"data-slot":"card",className:oe("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border",t),...s})}function te({className:t,...s}){return e.jsx("div",{"data-slot":"card-header",className:oe("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 pt-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",t),...s})}function se({className:t,...s}){return e.jsx("h4",{"data-slot":"card-title",className:oe("leading-none",t),...s})}function he({className:t,...s}){return e.jsx("p",{"data-slot":"card-description",className:oe("text-muted-foreground",t),...s})}function Y({className:t,...s}){return e.jsx("div",{"data-slot":"card-content",className:oe("px-6 [&:last-child]:pb-6",t),...s})}const Fi="/assets/Re_Logo-By51taPS.png";function cf(){const{login:t,isLoading:s,error:a}=Bt(),r=async()=>{localStorage.clear(),sessionStorage.clear();try{await t()}catch(n){console.error("========================================"),console.error("LOGIN ERROR"),console.error("Error details:",n),console.error("Error message:",n==null?void 0:n.message),console.error("Error stack:",n==null?void 0:n.stack),console.error("========================================")}};return a&&console.error("Auth0 Error in Auth Component:",{message:a.message,error:a}),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 to-slate-100 p-4",children:e.jsxs(G,{className:"w-full max-w-md shadow-xl",children:[e.jsx(te,{className:"space-y-1 text-center pb-6",children:e.jsxs("div",{className:"flex flex-col items-center justify-center mb-4",children:[e.jsx("img",{src:Fi,alt:"Royal Enfield Logo",className:"h-10 w-auto max-w-[168px] object-contain mb-2"}),e.jsx("p",{className:"text-xs text-gray-400 text-center truncate",children:"Approval Portal"})]})}),e.jsxs(Y,{className:"space-y-4",children:[a&&e.jsxs("div",{className:"bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg",children:[e.jsx("p",{className:"text-sm font-medium",children:"Authentication Error"}),e.jsx("p",{className:"text-sm",children:a.message})]}),e.jsx(M,{onClick:r,disabled:s,className:"w-full h-12 text-base font-semibold bg-re-red hover:bg-re-red/90 text-white",size:"lg",children:s?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"}),"Logging in..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Xp,{className:"mr-2 h-5 w-5"}),"SSO Login"]})}),e.jsxs("div",{className:"text-center text-sm text-gray-500 mt-4",children:[e.jsx("p",{children:"Secure Single Sign-On"}),e.jsx("p",{className:"text-xs mt-1",children:"Powered by Auth0"})]})]})]})})}function Fd(){const{isAuthenticated:t,isLoading:s,error:a,user:r}=Bt(),[n,i]=g.useState("exchanging");g.useEffect(()=>{if(a){i("error");return}if(s){const c=new URLSearchParams(window.location.search).get("code");i(c&&!r?"exchanging":r&&!t?"fetching":"exchanging")}else if(r&&t){i("complete");const l=setTimeout(()=>{window.location.href="/"},1500);return()=>clearTimeout(l)}},[t,s,a,r]);const o=()=>{switch(n){case"exchanging":return"Exchanging authorization code...";case"fetching":return"Fetching your profile...";case"complete":return"Authentication successful!";case"error":return"Authentication failed";default:return"Completing authentication..."}};return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900",children:[e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiMxZTIxMmQiIGZpbGwtb3BhY2l0eT0iMC4wNSI+PGNpcmNsZSBjeD0iMzAiIGN5PSIzMCIgcj0iMzAiLz48L2c+PC9nPjwvc3ZnPg==')] opacity-20"}),e.jsxs("div",{className:"relative z-10 text-center px-4 max-w-md w-full",children:[e.jsx("div",{className:"mb-8",children:e.jsxs("div",{className:"flex flex-col items-center justify-center",children:[e.jsx("img",{src:Fi,alt:"Royal Enfield Logo",className:"h-10 w-auto max-w-[168px] object-contain mb-2"}),e.jsx("p",{className:"text-xs text-gray-400 text-center truncate",children:"Approval Portal"})]})}),e.jsxs("div",{className:"bg-white/10 backdrop-blur-xl rounded-2xl p-8 shadow-2xl border border-white/20",children:[e.jsx("div",{className:"mb-6 flex justify-center",children:n==="error"?e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 animate-ping opacity-75",children:e.jsx(Re,{className:"w-16 h-16 text-red-500"})}),e.jsx(Re,{className:"w-16 h-16 text-red-500 relative"})]}):n==="complete"?e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 animate-ping opacity-75",children:e.jsx(Hn,{className:"w-16 h-16 text-green-500"})}),e.jsx(Hn,{className:"w-16 h-16 text-green-500 relative"})]}):e.jsxs("div",{className:"relative",children:[e.jsx(Le,{className:"w-16 h-16 animate-spin text-re-red"}),e.jsx("div",{className:"absolute inset-0 border-4 rounded-full border-re-red/20"}),e.jsx("div",{className:"absolute inset-0 border-4 border-transparent border-t-re-red rounded-full animate-spin"})]})}),e.jsxs("div",{className:"mb-6",children:[e.jsx("h2",{className:"text-xl font-semibold text-white mb-2",children:n==="complete"?"Welcome Back!":n==="error"?"Authentication Error":"Authenticating"}),e.jsx("p",{className:"text-slate-300 text-sm",children:o()})]}),n!=="error"&&e.jsxs("div",{className:"space-y-3 mb-6",children:[e.jsxs("div",{className:`flex items-center gap-3 text-sm transition-all duration-500 ${n==="exchanging"?"text-white":"text-slate-400"}`,children:[e.jsx("div",{className:`w-2 h-2 rounded-full transition-all duration-500 ${n==="exchanging"?"bg-re-red animate-pulse":"bg-slate-600"}`}),e.jsx("span",{children:"Validating credentials"})]}),e.jsxs("div",{className:`flex items-center gap-3 text-sm transition-all duration-500 ${n==="fetching"?"text-white":"text-slate-400"}`,children:[e.jsx("div",{className:`w-2 h-2 rounded-full transition-all duration-500 ${n==="fetching"?"bg-re-red animate-pulse":"bg-slate-600"}`}),e.jsx("span",{children:"Loading your profile"})]}),n==="complete"&&e.jsxs("div",{className:"flex items-center gap-3 text-sm transition-all duration-500 text-white",children:[e.jsx("div",{className:"w-2 h-2 rounded-full transition-all duration-500 bg-green-500"}),e.jsx("span",{children:"Setting up your session"})]})]}),n==="error"&&a&&e.jsxs("div",{className:"mt-6 p-4 bg-red-500/10 border border-red-500/20 rounded-lg",children:[e.jsx("p",{className:"text-red-400 text-sm",children:a.message||"An error occurred during authentication"}),e.jsx("button",{onClick:()=>{window.location.href="/"},className:"mt-4 text-sm text-red-400 hover:text-red-300 underline",children:"Return to login"})]}),n!=="error"&&n!=="complete"&&e.jsxs("div",{className:"mt-6",children:[e.jsx("div",{className:"h-1.5 bg-slate-700/50 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-re-red rounded-full animate-pulse",style:{animation:"progress 2s ease-in-out infinite"}})}),e.jsx("style",{children:` @keyframes progress { 0%, 100% { width: 20%; } 50% { width: 80%; } } `})]})]}),e.jsx("p",{className:"mt-6 text-slate-500 text-xs",children:n==="complete"?"Redirecting to dashboard...":"Please wait while we secure your session"})]}),e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute top-1/4 left-1/4 w-96 h-96 bg-re-red/5 rounded-full blur-3xl animate-pulse"}),e.jsx("div",{className:"absolute bottom-1/4 right-1/4 w-96 h-96 bg-re-red/5 rounded-full blur-3xl animate-pulse delay-1000"})]})]})}const df=Pd("inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",secondary:"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",destructive:"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"}},defaultVariants:{variant:"default"}});function Q({className:t,variant:s,asChild:a=!1,...r}){const n=a?Bc:"span";return e.jsx(n,{"data-slot":"badge",className:oe(df({variant:s}),t),...r})}function mf({isOpen:t,onClose:s}){const{user:a,isAuthenticated:r,isLoading:n,error:i}=wg();return g.useEffect(()=>{},[a,r,n,i]),t?e.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4",children:e.jsxs(G,{className:"w-full max-w-2xl max-h-[90vh] overflow-auto",children:[e.jsx(te,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Authentication Debug Information"}),e.jsx(M,{variant:"ghost",size:"icon",onClick:s,children:e.jsx(ft,{className:"h-4 w-4"})})]})}),e.jsxs(Y,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold",children:"Status:"}),e.jsx(Q,{variant:r?"default":"destructive",children:n?"Loading...":r?"Authenticated":"Not Authenticated"})]}),i&&e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded p-3",children:[e.jsx("p",{className:"text-sm text-red-700 font-semibold",children:"Error:"}),e.jsx("p",{className:"text-sm text-red-600",children:i.message})]}),a&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-semibold",children:"User Information:"}),e.jsx("pre",{className:"bg-gray-50 p-3 rounded text-xs overflow-auto",children:JSON.stringify(a,null,2)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-semibold",children:"All Auth Claims:"}),e.jsx("pre",{className:"bg-gray-50 p-3 rounded text-xs overflow-auto",children:JSON.stringify({isAuthenticated:r,isLoading:n,error:(i==null?void 0:i.message)||null,hasUser:!!a},null,2)})]})]})]})}):null}const jt=g.forwardRef(({className:t,...s},a)=>e.jsx(zc,{ref:a,"data-slot":"avatar",className:oe("relative flex size-10 shrink-0 overflow-hidden rounded-full",t),...s}));jt.displayName=zc.displayName;const Wr=g.forwardRef(({className:t,...s},a)=>e.jsx(Hc,{ref:a,"data-slot":"avatar-image",className:oe("aspect-square size-full",t),...s}));Wr.displayName=Hc.displayName;const Nt=g.forwardRef(({className:t,...s},a)=>e.jsx(qc,{ref:a,"data-slot":"avatar-fallback",className:oe("bg-muted flex size-full items-center justify-center rounded-full",t),...s}));Nt.displayName=qc.displayName;function rl({...t}){return e.jsx(Dh,{"data-slot":"dropdown-menu",...t})}function nl({...t}){return e.jsx(Ph,{"data-slot":"dropdown-menu-trigger",...t})}function il({className:t,sideOffset:s=4,...a}){return e.jsx(Eh,{children:e.jsx(Mh,{"data-slot":"dropdown-menu-content",sideOffset:s,className:oe("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",t),...a})})}function pn({className:t,inset:s,variant:a="default",...r}){return e.jsx(Ih,{"data-slot":"dropdown-menu-item","data-inset":s,"data-variant":a,className:oe("focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...r})}function uf({...t}){return e.jsx(Lh,{"data-slot":"alert-dialog",...t})}function hf({...t}){return e.jsx(_h,{"data-slot":"alert-dialog-portal",...t})}const Od=g.forwardRef(({className:t,...s},a)=>e.jsx(Wc,{"data-slot":"alert-dialog-overlay",className:oe("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",t),...s,ref:a}));Od.displayName=Wc.displayName;const $d=g.forwardRef(({className:t,...s},a)=>e.jsxs(hf,{children:[e.jsx(Od,{}),e.jsx(Kc,{"data-slot":"alert-dialog-content",ref:a,className:oe("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",t),...s})]}));$d.displayName=Kc.displayName;function pf({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-header",className:oe("flex flex-col gap-2 text-center sm:text-left",t),...s})}function xf({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-footer",className:oe("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s})}function gf({className:t,...s}){return e.jsx(Fh,{"data-slot":"alert-dialog-title",className:oe("text-lg font-semibold",t),...s})}function ff({className:t,...s}){return e.jsx(Oh,{"data-slot":"alert-dialog-description",className:oe("text-muted-foreground text-sm",t),...s})}function yf({className:t,...s}){return e.jsx(Uh,{className:oe(qa(),t),...s})}function vf({className:t,...s}){return e.jsx($h,{className:oe(qa({variant:"outline"}),t),...s})}class bf{async list(s){return(await ie.get("/notifications",{params:s})).data}async getUnreadCount(){return(await ie.get("/notifications/unread-count")).data.data.unreadCount}async markAsRead(s){return(await ie.patch(`/notifications/${s}/read`)).data}async markAllAsRead(){return(await ie.post("/notifications/mark-all-read")).data}async delete(s){return(await ie.delete(`/notifications/${s}`)).data}}const Js=new bf;let qs=null;function jf(){return"https://re-workflow-nt-dev.siplsolutions.com"}function Ar(t){const s=jf();return qs||(qs=Bx(s,{withCredentials:!0,transports:["websocket","polling"],path:"/socket.io",reconnection:!0,reconnectionDelay:1e3,reconnectionAttempts:5}),qs.on("connect",()=>{}),qs.on("connect_error",a=>{console.error("[Socket] Connection error:",a.message)}),qs.on("disconnect",a=>{}),qs)}function Xn(t,s,a){a?t.emit("join:request",{requestId:s,userId:a}):t.emit("join:request",s)}function Ud(t,s){t.emit("leave:request",s)}function Nf(t,s){t.emit("join:user",{userId:s})}function Et({children:t,currentPage:s="dashboard",onNavigate:a,onNewRequest:r,onLogout:n}){const[i,o]=g.useState(!1),[l,c]=g.useState(!1),[d,m]=g.useState([]),[u,h]=g.useState(0),[x,p]=g.useState(!1),{user:y}=Bt(),v=()=>{var C,R;try{if(y!=null&&y.displayName&&typeof y.displayName=="string"){const I=y.displayName.split(" ").filter(Boolean);return I.length>=2?`${((C=I[0])==null?void 0:C[0])||""}${((R=I[I.length-1])==null?void 0:R[0])||""}`.toUpperCase():y.displayName.substring(0,2).toUpperCase()}return y!=null&&y.email&&typeof y.email=="string"?y.email.substring(0,2).toUpperCase():"U"}catch(I){return console.error("[PageLayout] Error getting user initials:",I),"U"}},N=g.useMemo(()=>{const C=[{id:"dashboard",label:"Dashboard",icon:Qp},{id:"requests",label:"All Requests",icon:cd}];return C.push({id:"my-requests",label:"My Requests",icon:rt},{id:"open-requests",label:"Open Requests",icon:Te},{id:"closed-requests",label:"Closed Requests",icon:ve},{id:"shared-summaries",label:"Shared Summary",icon:wa}),C},[]),f=()=>{o(!i)},b=async C=>{var R;try{if(C.isRead||(await Js.markAsRead(C.notificationId),m(I=>I.map(T=>T.notificationId===C.notificationId?{...T,isRead:!0}:T)),h(I=>Math.max(0,I-1))),C.actionUrl&&a){const I=(R=C.metadata)==null?void 0:R.requestNumber;if(I){let T=`request/${I}`;(C.notificationType==="mention"||C.notificationType==="comment"||C.notificationType==="worknote")&&(T+="?tab=worknotes"),a(T)}}p(!1)}catch(I){console.error("[PageLayout] Error handling notification click:",I)}},j=async()=>{try{await Js.markAllAsRead(),m(C=>C.map(R=>({...R,isRead:!0}))),h(0)}catch(C){console.error("[PageLayout] Error marking all as read:",C)}};return g.useEffect(()=>{const C=y==null?void 0:y.userId;if(!C)return;let R=!0;(async()=>{var E,w;try{const S=await Js.list({page:1,limit:4,unreadOnly:!1});if(!R)return;const D=((E=S.data)==null?void 0:E.notifications)||[];m(D),h(((w=S.data)==null?void 0:w.unreadCount)||0)}catch(S){console.error("[PageLayout] Failed to fetch notifications:",S)}})();const T=Ar();if(T){Nf(T,C);const E=w=>{R&&(m(S=>[w.notification,...S].slice(0,4)),h(S=>S+1))};return T.on("notification:new",E),()=>{R=!1,T.off("notification:new",E)}}return()=>{R=!1}},[y]),g.useEffect(()=>{const C=()=>{window.innerWidth>=768?o(!0):o(!1)};return C(),window.addEventListener("resize",C),()=>window.removeEventListener("resize",C)},[]),e.jsxs("div",{className:"min-h-screen flex w-full bg-background",children:[i&&e.jsx("div",{className:"fixed inset-0 bg-black/50 z-40 md:hidden",onClick:()=>o(!1)}),e.jsx("aside",{className:` fixed md:relative inset-y-0 left-0 w-64 transform transition-transform duration-300 ease-in-out ${i?"translate-x-0":"-translate-x-full"} md:translate-x-0 ${i?"md:w-64":"md:w-0"} z-50 md:z-auto flex-shrink-0 border-r border-gray-800 bg-black flex flex-col overflow-hidden `,children:e.jsxs("div",{className:`w-64 h-full flex flex-col overflow-hidden ${i?"":"md:hidden"}`,children:[e.jsx("div",{className:"p-4 border-b border-gray-800 flex-shrink-0",children:e.jsxs("div",{className:"flex flex-col items-center justify-center",children:[e.jsx("img",{src:Fi,alt:"Royal Enfield Logo",className:"h-10 w-auto max-w-[168px] object-contain"}),e.jsx("p",{className:"text-xs text-gray-400 text-center mt-1 truncate",children:"RE Flow"})]})}),e.jsxs("div",{className:"p-3 flex-1 overflow-y-auto",children:[e.jsx("div",{className:"space-y-2",children:N.map(C=>e.jsxs("button",{onClick:()=>{a==null||a(C.id),window.innerWidth<768&&o(!1)},className:`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-colors ${s===C.id?"bg-re-green text-white font-medium":"text-gray-300 hover:bg-gray-900 hover:text-white"}`,children:[e.jsx(C.icon,{className:"w-4 h-4 shrink-0"}),e.jsx("span",{className:"truncate",children:C.label})]},C.id))}),e.jsx("div",{className:"mt-6 pt-6 border-t border-gray-800 px-3",children:e.jsxs(M,{onClick:r,className:"w-full bg-re-green hover:bg-re-green/90 text-white text-sm font-medium",size:"sm",children:[e.jsx(Is,{className:"w-4 h-4 mr-2"}),"Raise New Request"]})})]})]})}),e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsxs("header",{className:"h-16 border-b border-gray-200 bg-white flex items-center justify-between px-6 shrink-0",children:[e.jsx("div",{className:"flex items-center gap-4 min-w-0 flex-1",children:e.jsx(M,{variant:"ghost",size:"icon",onClick:f,className:"shrink-0 h-10 w-10 sidebar-toggle",children:i?e.jsx(Jp,{className:"w-5 h-5 text-gray-600"}):e.jsx(ex,{className:"w-5 h-5 text-gray-600"})})}),e.jsxs("div",{className:"flex items-center gap-4 shrink-0",children:[e.jsxs(M,{onClick:r,className:"bg-re-green hover:bg-re-green/90 text-white gap-2 hidden md:flex text-sm",size:"sm",children:[e.jsx(Is,{className:"w-4 h-4"}),"New Request"]}),e.jsxs(rl,{open:x,onOpenChange:p,children:[e.jsx(nl,{asChild:!0,children:e.jsxs(M,{variant:"ghost",size:"icon",className:"relative shrink-0 h-10 w-10",children:[e.jsx(Ut,{className:"w-5 h-5"}),u>0&&e.jsx(Q,{className:"absolute -top-1 -right-1 w-5 h-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center p-0",children:u>9?"9+":u})]})}),e.jsxs(il,{align:"end",className:"w-96 max-h-[500px]",children:[e.jsxs("div",{className:"p-3 border-b flex items-center justify-between sticky top-0 bg-white z-10",children:[e.jsx("h4",{className:"font-semibold text-base",children:"Notifications"}),u>0&&e.jsx(M,{variant:"ghost",size:"sm",className:"text-xs text-blue-600 hover:text-blue-700 h-auto p-1",onClick:C=>{C.stopPropagation(),j()},children:"Mark all as read"})]}),e.jsx("div",{className:"max-h-[400px] overflow-y-auto",children:d.length===0?e.jsxs("div",{className:"p-6 text-center",children:[e.jsx(Ut,{className:"w-12 h-12 text-gray-300 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-gray-500",children:"No notifications yet"})]}):e.jsx("div",{className:"divide-y",children:d.map(C=>e.jsx("div",{className:`p-3 hover:bg-gray-50 cursor-pointer transition-colors ${C.isRead?"":"bg-blue-50"}`,onClick:()=>b(C),children:e.jsxs("div",{className:"flex gap-2",children:[!C.isRead&&e.jsx("div",{className:"w-2 h-2 rounded-full bg-blue-600 mt-1.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`text-sm ${C.isRead?"font-medium":"font-semibold"}`,children:C.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-2",children:C.message}),e.jsx("p",{className:"text-xs text-gray-400 mt-1",children:rd(new Date(C.createdAt),{addSuffix:!0})})]})]})},C.notificationId))})}),d.length>0&&e.jsx("div",{className:"p-2 border-t",children:e.jsx(M,{variant:"ghost",className:"w-full text-sm text-blue-600 hover:text-blue-700",onClick:()=>{p(!1),a==null||a("notifications")},children:"View all notifications"})})]})]}),e.jsxs(rl,{children:[e.jsx(nl,{asChild:!0,children:e.jsxs(jt,{className:"cursor-pointer shrink-0 h-10 w-10",children:[e.jsx(Wr,{src:(y==null?void 0:y.picture)||""}),e.jsx(Nt,{className:"bg-re-green text-white text-sm",children:v()})]})}),e.jsxs(il,{align:"end",children:[e.jsxs(pn,{onClick:()=>a==null?void 0:a("profile"),children:[e.jsx(rt,{className:"w-4 h-4 mr-2"}),"Profile"]}),e.jsxs(pn,{onClick:()=>a==null?void 0:a("settings"),children:[e.jsx(la,{className:"w-4 h-4 mr-2"}),"Settings"]}),e.jsxs(pn,{onClick:()=>c(!0),className:"text-red-600 focus:text-red-600",children:[e.jsx(ln,{className:"w-4 h-4 mr-2"}),"Logout"]})]})]})]})]}),e.jsx("main",{className:"flex-1 p-2 sm:p-4 lg:p-6 overflow-auto min-w-0",children:t})]}),e.jsx(uf,{open:l,onOpenChange:c,children:e.jsxs($d,{children:[e.jsxs(pf,{children:[e.jsxs(gf,{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"w-5 h-5 text-red-600"}),"Confirm Logout"]}),e.jsx(ff,{className:"pt-2",children:"Are you sure you want to logout? You will need to sign in again to access your account."})]}),e.jsxs(xf,{children:[e.jsx(vf,{onClick:()=>c(!1),children:"Cancel"}),e.jsxs(yf,{onClick:async()=>{if(c(!1),n)try{await n()}catch(C){console.error("🔴 Error calling onLogout:",C)}else console.error("🔴 ERROR: onLogout is undefined!")},className:"bg-red-600 hover:bg-red-700 text-white focus:ring-red-600",children:[e.jsx(ln,{className:"w-4 h-4 mr-2"}),"Logout"]})]})]})})]})}const wf=()=>pg(),Vd=fg,Cf=()=>{try{const t=localStorage.getItem("dashboard_viewAsUser");return t?JSON.parse(t):!1}catch{return!1}},Sf={viewAsUser:Cf()},Bd=Cd({name:"dashboard",initialState:Sf,reducers:{setViewAsUser:(t,s)=>{t.viewAsUser=s.payload,localStorage.setItem("dashboard_viewAsUser",JSON.stringify(s.payload))}}}),{setViewAsUser:Af}=Bd.actions;function Tf(){const[t,s]=g.useState("month"),[a,r]=g.useState(void 0),[n,i]=g.useState(void 0),[o,l]=g.useState(!1),c=g.useCallback(u=>{const h=u;s(h),h!=="custom"?(r(void 0),i(void 0),l(!1)):l(!0)},[]),d=g.useCallback(u=>{if(a&&n){if(a>n){const h=a;r(n),i(h),u(n,h)}else u(a,n);l(!1)}},[a,n]),m=g.useCallback(()=>{r(void 0),i(void 0),l(!1),s("month")},[]);return{dateRange:t,customStartDate:a,customEndDate:n,showCustomDatePicker:o,setDateRange:s,setCustomStartDate:r,setCustomEndDate:i,setShowCustomDatePicker:l,handleDateRangeChange:c,handleApplyCustomDate:d,resetCustomDates:m}}function kf(){const[t,s]=g.useState({page:1,totalPages:1,totalRecords:0}),[a,r]=g.useState({page:1,totalPages:1,totalRecords:0}),[n,i]=g.useState({page:1,totalPages:1,totalRecords:0}),[o,l]=g.useState({page:1,totalPages:1,totalRecords:0}),c=g.useCallback((v,N,f)=>{s({page:v,totalPages:N,totalRecords:f})},[]),d=g.useCallback((v,N,f)=>{r({page:v,totalPages:N,totalRecords:f})},[]),m=g.useCallback((v,N,f)=>{i({page:v,totalPages:N,totalRecords:f})},[]),u=g.useCallback((v,N,f)=>{l({page:v,totalPages:N,totalRecords:f})},[]),h=g.useCallback((v,N)=>{v>=1&&v<=t.totalPages&&(s(f=>({...f,page:v})),N(v))},[t.totalPages]),x=g.useCallback((v,N)=>{v>=1&&v<=a.totalPages&&(r(f=>({...f,page:v})),N(v))},[a.totalPages]),p=g.useCallback((v,N)=>{v>=1&&v<=n.totalPages&&(i(f=>({...f,page:v})),N(v))},[n.totalPages]),y=g.useCallback((v,N)=>{v>=1&&v<=o.totalPages&&(l(f=>({...f,page:v})),N(v))},[o.totalPages]);return{activity:t,critical:a,deadlines:n,approver:o,updateActivityPagination:c,updateCriticalPagination:d,updateDeadlinesPagination:m,updateApproverPagination:u,handleActivityPageChange:h,handleCriticalPageChange:x,handleDeadlinesPageChange:p,handleApproverPageChange:y}}class Rf{async getKPIs(s,a,r,n){try{const i={dateRange:s};return s==="custom"&&a&&r&&(i.startDate=a.toISOString(),i.endDate=r.toISOString()),n&&(i.viewAsUser="true"),(await ie.get("/dashboard/kpis",{params:i})).data.data}catch(i){throw console.error("Failed to fetch KPIs:",i),i}}async getRequestStats(s,a,r,n,i,o,l,c,d,m,u,h){try{const x={dateRange:s};return s==="custom"&&a&&r&&(x.startDate=a,x.endDate=r),n&&n!=="all"&&(x.status=n),i&&i!=="all"&&(x.priority=i),o&&o!=="all"&&(x.department=o),l&&l!=="all"&&(x.initiator=l),c&&c!=="all"&&(x.approver=c),d&&(x.approverType=d),m&&(x.search=m),u&&u!=="all"&&(x.slaCompliance=u),h&&(x.viewAsUser="true"),(await ie.get("/dashboard/stats/requests",{params:x})).data.data}catch(x){throw console.error("Failed to fetch request stats:",x),x}}async getTATEfficiency(s){try{return(await ie.get("/dashboard/stats/tat-efficiency",{params:{dateRange:s}})).data.data}catch(a){throw console.error("Failed to fetch TAT efficiency:",a),a}}async getApproverLoad(s){try{return(await ie.get("/dashboard/stats/approver-load",{params:{dateRange:s}})).data.data}catch(a){throw console.error("Failed to fetch approver load:",a),a}}async getEngagementStats(s){try{return(await ie.get("/dashboard/stats/engagement",{params:{dateRange:s}})).data.data}catch(a){throw console.error("Failed to fetch engagement stats:",a),a}}async getAIInsights(s){try{return(await ie.get("/dashboard/stats/ai-insights",{params:{dateRange:s}})).data.data}catch(a){throw console.error("Failed to fetch AI insights:",a),a}}async getRecentActivity(s=1,a=10,r){try{const n={page:s,limit:a};r&&(n.viewAsUser="true");const i=await ie.get("/dashboard/activity/recent",{params:n});return{activities:i.data.data,pagination:i.data.pagination}}catch(n){throw console.error("Failed to fetch recent activity:",n),n}}async getCriticalRequests(s=1,a=10,r){try{const n={page:s,limit:a};r&&(n.viewAsUser="true");const i=await ie.get("/dashboard/requests/critical",{params:n});return{criticalRequests:i.data.data,pagination:i.data.pagination}}catch(n){throw console.error("Failed to fetch critical requests:",n),n}}async getUpcomingDeadlines(s=1,a=10,r){try{const n={page:s,limit:a};r&&(n.viewAsUser="true");const i=await ie.get("/dashboard/deadlines/upcoming",{params:n});return{deadlines:i.data.data,pagination:i.data.pagination}}catch(n){throw console.error("Failed to fetch upcoming deadlines:",n),n}}async getDepartmentStats(s,a,r){try{const n={dateRange:s};return s==="custom"&&a&&r&&(n.startDate=a.toISOString(),n.endDate=r.toISOString()),(await ie.get("/dashboard/stats/by-department",{params:n})).data.data}catch(n){throw console.error("Failed to fetch department stats:",n),n}}async getPriorityDistribution(s,a,r){try{const n={dateRange:s};return s==="custom"&&a&&r&&(n.startDate=a.toISOString(),n.endDate=r.toISOString()),(await ie.get("/dashboard/stats/priority-distribution",{params:n})).data.data}catch(n){throw console.error("Failed to fetch priority distribution:",n),n}}async getAIRemarkUtilization(s,a,r){try{const n={dateRange:s};return s==="custom"&&a&&r&&(n.startDate=a.toISOString(),n.endDate=r.toISOString()),(await ie.get("/dashboard/stats/ai-remark-utilization",{params:n})).data.data}catch(n){throw console.error("Failed to fetch AI remark utilization:",n),n}}async getApproverPerformance(s,a=1,r=10,n,i){try{const o={dateRange:s,page:a,limit:r};s==="custom"&&n&&i&&(o.startDate=n.toISOString(),o.endDate=i.toISOString());const l=await ie.get("/dashboard/stats/approver-performance",{params:o});return{performance:l.data.data,pagination:l.data.pagination}}catch(o){throw console.error("Failed to fetch approver performance:",o),o}}async getLifecycleReport(s=1,a=50,r,n,i){try{const o={page:s,limit:a};r&&(o.dateRange=r),r==="custom"&&n&&i&&(o.startDate=n.toISOString(),o.endDate=i.toISOString());const l=await ie.get("/dashboard/reports/lifecycle",{params:o});return{lifecycleData:l.data.data,pagination:l.data.pagination}}catch(o){throw console.error("Failed to fetch lifecycle report:",o),o}}async getActivityLogReport(s=1,a=50,r,n,i,o,l,c,d){try{const m={page:s,limit:a,filterUserId:n,filterType:i,filterCategory:o,filterSeverity:l};r&&(m.dateRange=r),r==="custom"&&c&&d&&(m.startDate=c.toISOString(),m.endDate=d.toISOString());const u=await ie.get("/dashboard/reports/activity-log",{params:m});return{activities:u.data.data,pagination:u.data.pagination}}catch(m){throw console.error("Failed to fetch activity log report:",m),m}}async getDepartments(){try{return(await ie.get("/dashboard/metadata/departments")).data.data.departments||[]}catch(s){throw console.error("Failed to fetch departments:",s),s}}async getWorkflowAgingReport(s=7,a=1,r=50,n,i,o){try{const l={threshold:s,page:a,limit:r};n&&(l.dateRange=n),n==="custom"&&i&&o&&(l.startDate=i.toISOString(),l.endDate=o.toISOString());const c=await ie.get("/dashboard/reports/workflow-aging",{params:l});return{agingData:c.data.data,pagination:c.data.pagination}}catch(l){throw console.error("Failed to fetch workflow aging report:",l),l}}async getRequestsByApprover(s,a=1,r=50,n,i,o,l,c,d,m){try{const u={approverId:s,page:a,limit:r};n&&(u.dateRange=n),n==="custom"&&i&&o&&(u.startDate=i.toISOString(),u.endDate=o.toISOString()),l&&(u.status=l),c&&(u.priority=c),d&&(u.slaCompliance=d),m&&(u.search=m);const h=await ie.get("/dashboard/requests/by-approver",{params:u});return{requests:h.data.data,pagination:h.data.pagination}}catch(u){throw console.error("Failed to fetch requests by approver:",u),u}}}const He=new Rf;function Df({isAdmin:t,viewAsUser:s=!1,userId:a,dateRange:r,customStartDate:n,customEndDate:i,onPaginationUpdate:o}){const[l,c]=g.useState(null),[d,m]=g.useState([]),[u,h]=g.useState([]),[x,p]=g.useState([]),[y,v]=g.useState([]),[N,f]=g.useState([]),[b,j]=g.useState(null),[C,R]=g.useState([]),[I,T]=g.useState(!0),[E,w]=g.useState(!1),S=g.useRef(o);S.current=o;const D=g.useCallback(async(k=!1)=>{try{k?w(!0):T(!0);const P=[He.getKPIs(r,n,i,s),He.getRecentActivity(1,10,s),He.getCriticalRequests(1,10,s),He.getUpcomingDeadlines(1,10,s)],_=t?[He.getDepartmentStats(r,n,i),He.getPriorityDistribution(r,n,i),He.getAIRemarkUtilization(r,n,i),He.getApproverPerformance(r,1,10,n,i)]:[],W=await Promise.all([...P,..._]),Z=W[0],ae=W[1],$=W[2],ne=W[3];if(c(Z),m(ae.activities),S.current.activity(ae.pagination.currentPage,ae.pagination.totalPages,ae.pagination.totalRecords),h($.criticalRequests),S.current.critical($.pagination.currentPage,$.pagination.totalPages,$.pagination.totalRecords),f(ne.deadlines),S.current.deadlines(ne.pagination.currentPage,ne.pagination.totalPages,ne.pagination.totalRecords),t&&W.length>=8){const me=W[4],q=W[5],z=W[6],re=W[7];p(me),v(q),j(z),R(re.performance),S.current.approver(re.pagination.currentPage,re.pagination.totalPages,re.pagination.totalRecords)}else t||(p([]),v([]),j(null),R([]))}catch(P){console.error("Failed to fetch dashboard data:",P)}finally{T(!1),w(!1)}},[t,s,r,n,i]),H=g.useCallback(async(k=1)=>{try{const P=await He.getRecentActivity(k,10,s);m(P.activities),S.current.activity(P.pagination.currentPage,P.pagination.totalPages,P.pagination.totalRecords)}catch(P){console.error("Failed to fetch recent activities:",P)}},[s]),L=g.useCallback(async(k=1)=>{try{const P=await He.getCriticalRequests(k,10,s);h(P.criticalRequests),S.current.critical(P.pagination.currentPage,P.pagination.totalPages,P.pagination.totalRecords)}catch(P){console.error("Failed to fetch critical requests:",P)}},[s]),F=g.useCallback(async(k=1)=>{try{const P=await He.getUpcomingDeadlines(k,10,s);f(P.deadlines),S.current.deadlines(P.pagination.currentPage,P.pagination.totalPages,P.pagination.totalRecords)}catch(P){console.error("Failed to fetch upcoming deadlines:",P)}},[s]),A=g.useCallback(async(k=1)=>{try{const P=await He.getApproverPerformance(r,k,10,n,i);R(P.performance),S.current.approver(P.pagination.currentPage,P.pagination.totalPages,P.pagination.totalRecords)}catch(P){console.error("Failed to fetch approver performance:",P)}},[r,n,i]);return{kpis:l,recentActivity:d,criticalRequests:u,departmentStats:x,priorityDistribution:y,upcomingDeadlines:N,aiRemarkUtilization:b,approverPerformance:C,loading:I,refreshing:E,fetchDashboardData:D,fetchRecentActivities:H,fetchCriticalRequests:L,fetchUpcomingDeadlines:F,fetchApproverPerformance:A}}const fs={appName:"Royal Enfield Workflow Management",appVersion:"1.2.0",workingHours:{START_HOUR:9,END_HOUR:18,START_DAY:1,END_DAY:5,TIMEZONE:"Asia/Kolkata"},tat:{thresholds:{warning:50,critical:75,breach:100},testMode:!1},upload:{maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"],maxFilesPerRequest:10},workflow:{maxApprovalLevels:10,maxParticipants:50,maxSpectators:20},workNotes:{maxMessageLength:2e3,maxAttachmentsPerNote:5,enableReactions:!0,enableMentions:!0},features:{ENABLE_AI_CONCLUSION:!0,ENABLE_TEMPLATES:!1,ENABLE_ANALYTICS:!0,ENABLE_EXPORT:!0},ui:{DEFAULT_THEME:"light",DEFAULT_LANGUAGE:"en",DATE_FORMAT:"DD/MM/YYYY",TIME_FORMAT:"12h",CURRENCY:"INR",CURRENCY_SYMBOL:"₹"}};class Pf{constructor(){an(this,"config",null);an(this,"loading",null)}async getConfig(){return this.config?this.config:this.loading?this.loading:(this.loading=this.fetchConfig(),this.config=await this.loading,this.loading=null,this.config)}async fetchConfig(){var s;try{const a=await ie.get("/config"),r=((s=a.data)==null?void 0:s.data)||a.data;return{...fs,...r,workingHours:{...fs.workingHours,...r.workingHours},tat:{...fs.tat,...r.tat},upload:{...fs.upload,...r.upload},workflow:{...fs.workflow,...r.workflow},workNotes:{...fs.workNotes,...r.workNotes},features:{...fs.features,...r.features},ui:{...fs.ui,...r.ui}}}catch(a){return console.error("[ConfigService] ⚠️ Failed to fetch config from server, using defaults:",a),fs}}async refreshConfig(){return this.config=null,this.loading=null,this.getConfig()}getCachedConfig(){return this.config}isLoaded(){return this.config!==null}}const Ef=new Pf;let Mf=9,If=18,_f=1,Lf=5,ol=!1;async function Ff(){if(!ol)try{const t=await Ef.getConfig();Mf=t.workingHours.START_HOUR,If=t.workingHours.END_HOUR,_f=t.workingHours.START_DAY,Lf=t.workingHours.END_DAY,ol=!0}catch{console.warn("[SLA Tracker] ⚠️ Using default working hours (9 AM - 6 PM)")}}Ff().catch(()=>{});function nt(t){if(t==null||t<0||t===0)return"0 hours";const s=8;if(t<1){const l=Math.round(t*60);return l>0?`${l}m`:"0 hours"}const a=Math.floor(t/s),r=Math.floor(t%s),n=Math.round(t%1*60);if(a>0){const l=a===1?"day":"days",c=r===1?"hour":"hours",d=n===1?"min":"m";return n>0?`${a} ${l} ${r} ${c} ${n}${d}`:`${a} ${l} ${r} ${c}`}const i=r===1?"hour":"hours",o=n===1?"min":"m";return n>0?`${r} ${i} ${n}${o}`:`${r} ${i}`}async function Of(t,s,a){const r=[];let n=1,i=!0;const o=100;for(;i&&n<=o;){const h=await He.getApproverPerformance(t,n,100,s,a);h.performance&&h.performance.length>0?(r.push(...h.performance),n++,i=n<=h.pagination.totalPages):i=!1}const l=[["Approver Name","Total Approved","TAT Compliance (%)","Avg Response Time","Pending Count"].join(",")];r.forEach(h=>{const x=[`"${(h.approverName||"Unknown").replace(/"/g,'""')}"`,h.totalApproved||0,h.tatCompliancePercent||0,nt(h.avgResponseHours),h.pendingCount||0];l.push(x.join(","))});const c=l.join(` `),d=new Blob([c],{type:"text/csv;charset=utf-8;"}),m=document.createElement("a"),u=URL.createObjectURL(d);m.setAttribute("href",u),m.setAttribute("download",`approver-performance-report-${new Date().toISOString().split("T")[0]}.csv`),m.style.visibility="hidden",document.body.appendChild(m),m.click(),document.body.removeChild(m),URL.revokeObjectURL(u)}async function $f(t,s,a){const r=await He.getDepartmentStats(t,s,a),n=[["Department","Total Requests","Approved","Rejected","In Progress","Approval Rate (%)"].join(",")];r.forEach(d=>{const m=[`"${(d.department||"Unknown").replace(/"/g,'""')}"`,d.totalRequests||0,d.approved||0,d.rejected||0,d.inProgress||0,d.approvalRate||0];n.push(m.join(","))});const i=n.join(` `),o=new Blob([i],{type:"text/csv;charset=utf-8;"}),l=document.createElement("a"),c=URL.createObjectURL(o);l.setAttribute("href",c),l.setAttribute("download",`department-workflow-summary-${new Date().toISOString().split("T")[0]}.csv`),l.style.visibility="hidden",document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(c)}function Uf(){const[t,s]=g.useState(!1),[a,r]=g.useState(!1),n=g.useCallback(async(o,l,c)=>{try{s(!0),await $f(o,l,c)}catch(d){console.error("Failed to export department stats:",d),alert("Failed to export department statistics. Please try again.")}finally{s(!1)}},[]),i=g.useCallback(async(o,l,c)=>{try{r(!0),await Of(o,l,c)}catch(d){console.error("Failed to export approver performance:",d),alert("Failed to export approver performance data. Please try again.")}finally{r(!1)}},[]);return{exportingDeptStats:t,exportingApproverPerformance:a,handleExportDepartmentStats:n,handleExportApproverPerformance:i}}function ts({className:t,...s}){return e.jsx(Vh,{"data-slot":"switch",className:oe("peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-switch-background focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",t),...s,children:e.jsx(Bh,{"data-slot":"switch-thumb",className:oe("bg-card dark:data-[state=unchecked]:bg-card-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0")})})}function X({className:t,...s}){return e.jsx(zh,{"data-slot":"label",className:oe("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",t),...s})}function Vf({isAdmin:t,effectiveIsAdmin:s,viewAsUser:a,onToggleView:r,quickActions:n,userDisplayName:i,userEmail:o}){const l=i||(o==null?void 0:o.split("@")[0])||"User";return e.jsxs(G,{className:"relative overflow-hidden shadow-xl border-0","data-testid":"dashboard-hero",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900"}),e.jsxs(Y,{className:"relative z-10 p-4 sm:p-6 lg:p-12",children:[t&&e.jsx("div",{className:"absolute top-4 right-4 sm:top-6 sm:right-6 z-20","data-testid":"view-toggle",children:e.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-2 p-1.5 sm:p-2 bg-white/10 backdrop-blur-sm rounded-lg border border-white/20 shadow-lg",children:[e.jsxs("div",{className:`flex items-center gap-1 sm:gap-1.5 px-1.5 sm:px-2 py-0.5 sm:py-1 rounded transition-all cursor-pointer ${a?"opacity-60 hover:opacity-80":"bg-red-600/20 border border-red-600/50"}`,onClick:()=>r(!1),children:[e.jsx(dd,{className:`w-3 h-3 sm:w-3.5 sm:h-3.5 ${a?"text-gray-300":"text-red-600"}`}),e.jsx(X,{htmlFor:"view-toggle-switch",className:`text-[10px] sm:text-xs font-medium cursor-pointer whitespace-nowrap ${a?"text-gray-300":"text-red-600"}`,children:"Org"})]}),e.jsx(ts,{id:"view-toggle-switch",checked:a,onCheckedChange:r,className:"data-[state=checked]:bg-red-600 data-[state=unchecked]:bg-gray-600 shrink-0 scale-90 sm:scale-100","data-testid":"view-toggle-switch"}),e.jsxs("div",{className:`flex items-center gap-1 sm:gap-1.5 px-1.5 sm:px-2 py-0.5 sm:py-1 rounded transition-all cursor-pointer ${a?"bg-red-600/20 border border-red-600/50":"opacity-60 hover:opacity-80"}`,onClick:()=>r(!0),children:[e.jsx(rt,{className:`w-3 h-3 sm:w-3.5 sm:h-3.5 ${a?"text-red-600":"text-gray-300"}`}),e.jsx(X,{htmlFor:"view-toggle-switch",className:`text-[10px] sm:text-xs font-medium cursor-pointer whitespace-nowrap ${a?"text-red-600":"text-gray-300"}`,children:"Personal"})]})]})}),e.jsx("div",{className:"flex flex-col lg:flex-row items-start lg:items-center justify-between gap-4 sm:gap-6",children:e.jsxs("div",{className:`text-white w-full lg:w-auto ${t?"pt-12 sm:pt-0":""}`,children:[e.jsx("div",{className:"flex items-center gap-3 sm:gap-4 mb-4 sm:mb-6",children:e.jsxs("div",{className:"pr-2 sm:pr-0",children:[e.jsxs("h1",{className:"text-2xl sm:text-3xl lg:text-4xl font-bold mb-1 sm:mb-2 text-white","data-testid":"hero-title",children:["Welcome, ",l,"!"]}),e.jsx("p",{className:"text-sm sm:text-lg lg:text-xl text-gray-200","data-testid":"hero-subtitle",children:s?"Organization-wide analytics and insights":"Track your requests and approvals"})]})}),e.jsx("div",{className:"flex flex-wrap gap-2 sm:gap-4 mt-4 sm:mt-8","data-testid":"quick-actions",children:n.map((c,d)=>e.jsxs(M,{onClick:c.action,className:`${c.color} text-white border-0 shadow-lg hover:shadow-xl transition-all duration-200`,size:window.innerWidth<640?"sm":"lg","data-testid":`quick-action-${c.label.toLowerCase().replace(/\s+/g,"-")}`,children:[e.jsx(c.icon,{className:"w-4 h-4 sm:w-5 sm:h-5 mr-1 sm:mr-2"}),c.label]},d))})]})})]})]})}function we({...t}){return e.jsx(Hh,{"data-slot":"select",...t})}function Ce({...t}){return e.jsx(Kh,{"data-slot":"select-value",...t})}function Se({className:t,size:s="default",children:a,...r}){return e.jsxs(qh,{"data-slot":"select-trigger","data-size":s,className:oe("border-gray-400 data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground bg-white text-gray-900 flex w-full items-center justify-between gap-2 rounded-md border px-3 py-2 text-sm whitespace-nowrap transition-all outline-none disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4","hover:border-gray-500","focus-visible:border-re-light-green focus-visible:ring-0 focus-visible:outline-none","aria-invalid:ring-destructive/20 aria-invalid:border-destructive",t),...r,children:[a,e.jsx(Wh,{asChild:!0,children:e.jsx(md,{className:"size-4 opacity-50"})})]})}function Ae({className:t,children:s,position:a="popper",...r}){return e.jsx(Gh,{children:e.jsxs(Yh,{"data-slot":"select-content",className:oe("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",a==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:a,...r,children:[e.jsx(Bf,{}),e.jsx(Zh,{className:oe("p-1",a==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:s}),e.jsx(zf,{})]})})}function V({className:t,children:s,...a}){return e.jsxs(Xh,{"data-slot":"select-item",className:oe("focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",t),...a,children:[e.jsx("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:e.jsx(Qh,{children:e.jsx(Ca,{className:"size-4"})})}),e.jsx(Jh,{children:s})]})}function Bf({className:t,...s}){return e.jsx(ep,{"data-slot":"select-scroll-up-button",className:oe("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(tx,{className:"size-4"})})}function zf({className:t,...s}){return e.jsx(tp,{"data-slot":"select-scroll-down-button",className:oe("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(md,{className:"size-4"})})}function yt({className:t,orientation:s="horizontal",decorative:a=!0,...r}){return e.jsx(sp,{"data-slot":"separator-root",decorative:a,orientation:s,className:oe("bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",t),...r})}function Ds({...t}){return e.jsx(ap,{"data-slot":"popover",...t})}function Ps({...t}){return e.jsx(rp,{"data-slot":"popover-trigger",...t})}function Es({className:t,align:s="center",sideOffset:a=4,...r}){return e.jsx(np,{children:e.jsx(ip,{"data-slot":"popover-content",align:s,sideOffset:a,className:oe("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",t),...r})})}function xe({className:t,type:s,...a}){return e.jsx("input",{type:s,"data-slot":"input",className:oe("file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground flex h-9 w-full min-w-0 rounded-md border border-gray-400 bg-white px-3 py-1 text-base text-gray-900 transition-all outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm","focus-visible:border-re-light-green focus-visible:ring-0 focus-visible:outline-none","hover:border-gray-500","aria-invalid:ring-destructive/20 aria-invalid:border-destructive",t),...a})}function Hf({isAdmin:t,dateRange:s,customStartDate:a,customEndDate:r,showCustomDatePicker:n,refreshing:i,onDateRangeChange:o,onCustomStartDateChange:l,onCustomEndDateChange:c,onShowCustomDatePickerChange:d,onApplyCustomDate:m,onResetCustomDates:u,onRefresh:h}){return e.jsx(G,{className:"shadow-md","data-testid":"dashboard-filters-bar",children:e.jsx(Y,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qa,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Filters"}),t&&e.jsx(Q,{variant:"outline",className:"bg-purple-50 text-purple-700 border-purple-200","data-testid":"management-badge",children:"Management View"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 w-full sm:w-auto",children:[t?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qe,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(we,{value:s,onValueChange:o,"data-testid":"date-range-select",children:[e.jsx(Se,{className:"w-[140px]",children:e.jsx(Ce,{placeholder:"Select period"})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"today",children:"Today"}),e.jsx(V,{value:"week",children:"This Week"}),e.jsx(V,{value:"month",children:"This Month"}),e.jsx(V,{value:"custom",children:"Custom Range"})]})]}),s==="custom"&&e.jsxs(Ds,{open:n,onOpenChange:d,children:[e.jsx(Ps,{asChild:!0,children:e.jsxs(M,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(qe,{className:"w-4 h-4"}),a&&r?`${pe(a,"MMM d, yyyy")} - ${pe(r,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Es,{className:"w-auto p-4",align:"start",sideOffset:8,"data-testid":"custom-date-picker",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(xe,{id:"start-date",type:"date",value:a?pe(a,"yyyy-MM-dd"):"",onChange:x=>{const p=x.target.value?new Date(x.target.value):void 0;p?(l(p),r&&p>r&&c(p)):l(void 0)},max:pe(new Date,"yyyy-MM-dd"),className:"w-full","data-testid":"start-date-input"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(xe,{id:"end-date",type:"date",value:r?pe(r,"yyyy-MM-dd"):"",onChange:x=>{const p=x.target.value?new Date(x.target.value):void 0;p?(c(p),a&&po(x),"data-testid":"date-range-select-user",children:[e.jsx(Se,{className:"w-[140px]",children:e.jsx(Ce,{placeholder:"Select period"})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"today",children:"Today"}),e.jsx(V,{value:"week",children:"This Week"}),e.jsx(V,{value:"month",children:"This Month"})]})]})]}),e.jsx(yt,{orientation:"vertical",className:"h-6 hidden sm:block"}),e.jsxs(M,{variant:"outline",size:"sm",onClick:h,disabled:i,className:"gap-2 min-w-[110px]","data-testid":"refresh-button",children:[e.jsx(Lt,{className:`w-4 h-4 ${i?"animate-spin":""}`}),e.jsx("span",{className:"inline-block w-[60px] text-center",children:i?"Refreshing...":"Refresh"})]})]})]})})})}function ea({title:t,value:s,icon:a,iconBgColor:r,iconColor:n,subtitle:i,children:o,testId:l="kpi-card",onClick:c,onJustifyClick:d,showJustifyButton:m=!1}){const u=h=>{h.stopPropagation(),d==null||d()};return e.jsxs(G,{className:"hover:shadow-lg transition-all duration-200 shadow-md cursor-pointer h-full flex flex-col",onClick:c,"data-testid":l,children:[e.jsxs(te,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(se,{className:"text-sm font-medium text-muted-foreground","data-testid":`${l}-title`,children:t}),e.jsxs("div",{className:"flex items-center gap-2",children:[m&&d&&e.jsx("button",{type:"button",onClick:u,className:"p-1.5 rounded-md text-gray-500 hover:text-gray-700 hover:bg-gray-100 transition-colors","data-testid":`${l}-justify-button`,title:"View detailed breakdown of numbers","aria-label":"View detailed breakdown",children:e.jsx(Fr,{className:"h-4 w-4"})}),e.jsx("div",{className:`p-1.5 sm:p-2 rounded-lg ${r}`,"data-testid":`${l}-icon-wrapper`,children:e.jsx(a,{className:`h-4 w-4 sm:h-4 sm:w-4 ${n}`,"data-testid":`${l}-icon`})})]})]}),e.jsxs(Y,{className:"flex flex-col flex-1 py-3",children:[e.jsx("div",{className:"text-xl sm:text-2xl font-bold text-gray-900 mb-2","data-testid":`${l}-value`,children:s}),i&&e.jsx("div",{className:"text-xs text-muted-foreground mb-2","data-testid":`${l}-subtitle`,children:i}),o&&e.jsx("div",{className:"flex-1 flex flex-col","data-testid":`${l}-children`,children:o})]})]})}function Rt({label:t,value:s,bgColor:a,textColor:r,testId:n="stat-card",children:i,onClick:o}){return e.jsxs("div",{className:`${a} rounded-lg p-2 sm:p-3 ${o?"cursor-pointer hover:shadow-md transition-shadow":""}`,"data-testid":n,onClick:o,children:[e.jsx("p",{className:"text-xs text-gray-600 mb-1 leading-tight","data-testid":`${n}-label`,children:t}),e.jsx("p",{className:`text-lg sm:text-xl font-bold ${r}`,"data-testid":`${n}-value`,children:s}),i]})}function hs({className:t,value:s,indicatorClassName:a,...r}){return e.jsx(op,{"data-slot":"progress",className:oe("bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",t),...r,children:e.jsx(lp,{"data-slot":"progress-indicator",className:oe("bg-primary h-full w-full flex-1 transition-all",a),style:{transform:`translateX(-${100-(s||0)}%)`}})})}function qf({kpis:t,priorityDistribution:s,dateRange:a,customStartDate:r,customEndDate:n,onKPIClick:i}){const o=()=>({dateRange:a,startDate:r,endDate:n});return e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6","data-testid":"admin-kpi-cards",children:[e.jsxs(ea,{title:"Total Requests",value:(t==null?void 0:t.requestVolume.totalRequests)||0,icon:Te,iconBgColor:"bg-blue-50",iconColor:"text-blue-600",testId:"kpi-total-requests",onClick:()=>i(o()),children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-2",children:[e.jsx(Rt,{label:"Approved",value:(t==null?void 0:t.requestVolume.approvedRequests)||0,bgColor:"bg-green-50",textColor:"text-green-600",testId:"stat-approved",onClick:l=>{l.stopPropagation(),i({...o(),status:"approved"})}}),e.jsx(Rt,{label:"Rejected",value:(t==null?void 0:t.requestVolume.rejectedRequests)||0,bgColor:"bg-red-50",textColor:"text-red-600",testId:"stat-rejected",onClick:l=>{l.stopPropagation(),i({...o(),status:"rejected"})}})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-2",children:[e.jsx(Rt,{label:"Pending",value:(t==null?void 0:t.requestVolume.openRequests)||0,bgColor:"bg-orange-50",textColor:"text-orange-600",testId:"stat-pending",onClick:l=>{l.stopPropagation(),i({...o(),status:"pending"})}}),e.jsx(Rt,{label:"Closed",value:(t==null?void 0:t.requestVolume.closedRequests)||0,bgColor:"bg-gray-50",textColor:"text-gray-600",testId:"stat-closed",onClick:l=>{l.stopPropagation(),i({...o(),status:"closed"})}})]}),(t==null?void 0:t.requestVolume.pausedRequests)!==void 0&&e.jsx("div",{className:"grid grid-cols-2 gap-2",children:e.jsx(Rt,{label:"Paused",value:t.requestVolume.pausedRequests||0,bgColor:"bg-orange-100",textColor:"text-orange-700",testId:"stat-paused",onClick:l=>{l.stopPropagation(),i({...o(),status:"paused"})}})})]}),e.jsx(ea,{title:"SLA Compliance",value:`${(t==null?void 0:t.tatEfficiency.avgTATCompliance)||0}%`,icon:it,iconBgColor:"bg-green-50",iconColor:"text-green-600",testId:"kpi-sla-compliance",onClick:()=>i(o()),children:e.jsxs("div",{className:"flex flex-col flex-1",children:[e.jsx(hs,{value:(t==null?void 0:t.tatEfficiency.avgTATCompliance)||0,className:"h-2 mb-2","data-testid":"sla-progress-bar"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-auto",children:[e.jsx(Rt,{label:"Compliant",value:(t==null?void 0:t.tatEfficiency.compliantWorkflows)||0,bgColor:"bg-green-50",textColor:"text-green-600",testId:"stat-compliant",onClick:l=>{l.stopPropagation(),i({...o(),slaCompliance:"compliant"})}}),e.jsx(Rt,{label:"Breached",value:(t==null?void 0:t.tatEfficiency.delayedWorkflows)||0,bgColor:"bg-red-50",textColor:"text-red-600",testId:"stat-breached",onClick:l=>{l.stopPropagation(),i({...o(),slaCompliance:"breached"})}})]})]})}),e.jsx(ea,{title:"Avg Cycle Time",value:t!=null&&t.tatEfficiency.avgCycleTimeHours?nt(t.tatEfficiency.avgCycleTimeHours):"0 hours",icon:De,iconBgColor:"bg-purple-50",iconColor:"text-purple-600",subtitle:`≈ ${(t==null?void 0:t.tatEfficiency.avgCycleTimeDays.toFixed(1))||0} working days`,testId:"kpi-avg-cycle-time",onClick:()=>i(o()),children:e.jsx("div",{className:"flex flex-col flex-1",children:e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-auto",children:[e.jsx(Rt,{label:"Express",value:(()=>{const l=s.find(d=>d.priority==="express"),c=l?Number(l.avgCycleTimeHours):0;return c>0?nt(c):"N/A"})(),bgColor:"bg-orange-50",textColor:"text-orange-600",testId:"stat-express-time",onClick:l=>{l.stopPropagation(),i({...o(),priority:"express"})}}),e.jsx(Rt,{label:"Standard",value:(()=>{const l=s.find(d=>d.priority==="standard"),c=l?Number(l.avgCycleTimeHours):0;return c>0?nt(c):"N/A"})(),bgColor:"bg-blue-50",textColor:"text-blue-600",testId:"stat-standard-time",onClick:l=>{l.stopPropagation(),i({...o(),priority:"standard"})}})]})})})]})}function Wf({kpis:t,criticalRequests:s,dateRange:a,customStartDate:r,customEndDate:n,onKPIClick:i,onNavigate:o,userId:l,userDisplayName:c}){const d=()=>({dateRange:a,startDate:r,endDate:n}),m=()=>{if(!l)return;const h=new URLSearchParams;h.set("approverId",l),h.set("approverName",c||"My Performance"),h.set("dateRange",a),a==="custom"&&r&&n&&(h.set("startDate",r.toISOString()),h.set("endDate",n.toISOString())),o==null||o(`/approver-performance?${h.toString()}`)},u=t&&t.requestVolume.totalRequests>0?t.requestVolume.approvedRequests/t.requestVolume.totalRequests*100:0;return e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4 items-stretch","data-testid":"user-kpi-cards",children:[e.jsx(ea,{title:"My Requests (Submitted)",value:(t==null?void 0:t.requestVolume.totalRequests)||0,icon:Te,iconBgColor:"bg-blue-50",iconColor:"text-blue-600",testId:"kpi-my-requests",onClick:()=>i(d()),children:e.jsxs("div",{className:"grid grid-cols-2 gap-1.5 sm:gap-2",children:[e.jsx(Rt,{label:"Approved",value:(t==null?void 0:t.requestVolume.approvedRequests)||0,bgColor:"bg-green-50",textColor:"text-green-600",testId:"stat-user-approved",onClick:h=>{h.stopPropagation(),i({...d(),status:"approved"})}}),e.jsx(Rt,{label:"Pending",value:(t==null?void 0:t.requestVolume.openRequests)||0,bgColor:"bg-orange-50",textColor:"text-orange-600",testId:"stat-user-pending",onClick:h=>{h.stopPropagation(),i({...d(),status:"pending"})}}),e.jsx(Rt,{label:"Rejected",value:(t==null?void 0:t.requestVolume.rejectedRequests)||0,bgColor:"bg-red-50",textColor:"text-red-600",testId:"stat-user-rejected",onClick:h=>{h.stopPropagation(),i({...d(),status:"rejected"})}}),e.jsx(Rt,{label:"Closed",value:(t==null?void 0:t.requestVolume.closedRequests)||0,bgColor:"bg-blue-50",textColor:"text-blue-600",testId:"stat-user-closed",onClick:h=>{h.stopPropagation(),i({...d(),status:"closed"})}})]})}),e.jsx(ea,{title:"Awaiting My Approval",value:(t==null?void 0:t.approverLoad.pendingActions)||0,icon:De,iconBgColor:"bg-orange-50",iconColor:"text-orange-600",subtitle:"at current level",testId:"kpi-pending-actions",onClick:()=>i({...d(),targetPage:"open-requests",status:"pending"}),onJustifyClick:m,showJustifyButton:!!l,children:e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-auto",children:[e.jsx(Rt,{label:"Approved Today",value:(t==null?void 0:t.approverLoad.completedToday)||0,bgColor:"bg-blue-50",textColor:"text-blue-600",testId:"stat-today",onClick:h=>{h.stopPropagation(),i({...d(),targetPage:"open-requests",status:"pending"})}}),e.jsx(Rt,{label:"This Week",value:(t==null?void 0:t.approverLoad.completedThisWeek)||0,bgColor:"bg-green-50",textColor:"text-green-600",testId:"stat-week",onClick:h=>{h.stopPropagation(),i({...d(),targetPage:"open-requests",status:"pending"})}})]})}),e.jsx(ea,{title:"Critical Alerts",value:s.length,icon:ls,iconBgColor:"bg-red-50",iconColor:"text-red-600",testId:"kpi-user-critical",onClick:()=>i({...d(),targetPage:"open-requests"}),onJustifyClick:m,showJustifyButton:!!l,children:e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-auto",children:[e.jsx(Rt,{label:"Breached",value:s.filter(h=>h.breachCount>0).length,bgColor:"bg-orange-50",textColor:"text-red-600",testId:"stat-user-breached",onClick:h=>{h.stopPropagation(),i({...d(),targetPage:"open-requests"})}}),e.jsx(Rt,{label:"Warning",value:s.filter(h=>h.breachCount===0).length,bgColor:"bg-yellow-50",textColor:"text-orange-600",testId:"stat-user-warning",onClick:h=>{h.stopPropagation(),i({...d(),targetPage:"open-requests"})}})]})}),e.jsx(ea,{title:"Success Rate",value:`${u.toFixed(0)}%`,icon:ve,iconBgColor:"bg-green-50",iconColor:"text-green-600",subtitle:`of ${(t==null?void 0:t.requestVolume.totalRequests)||0} requests approved`,testId:"kpi-success-rate",children:e.jsxs("div",{className:"space-y-4 mt-3 flex flex-col flex-1",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(hs,{value:u,className:"h-4 bg-gray-200 [&>div]:bg-green-600","data-testid":"success-rate-progress"}),e.jsxs("div",{className:"flex justify-between items-center text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Rejected"}),e.jsx("span",{className:"font-semibold text-red-600",children:(t==null?void 0:t.requestVolume.rejectedRequests)||0})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-auto",children:[e.jsxs("div",{className:"bg-green-50 rounded-lg p-2 text-center",children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Approved"}),e.jsx("div",{className:"text-lg font-semibold text-green-600",children:(t==null?void 0:t.requestVolume.approvedRequests)||0})]}),e.jsxs("div",{className:"bg-red-50 rounded-lg p-2 text-center",children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Rejected"}),e.jsx("div",{className:"text-lg font-semibold text-red-600",children:(t==null?void 0:t.requestVolume.rejectedRequests)||0})]})]})]})})]})}const Kf=t=>{if(!t.originalTATHours||t.originalTATHours===0)return 0;const s=t.originalTATHours,a=t.totalTATHours;if(a<=0)return 100;const n=(s-a)/s*100;return Math.min(100,Math.max(0,Math.round(n)))},Gf=t=>{if(t.totalTATHours===void 0||t.totalTATHours===null)return"N/A";const s=t.totalTATHours;if(s<=0){const a=Math.abs(s);return a<1?"Breached":a<24?`${Math.round(a)}h overdue`:`${Math.round(a/24)}d overdue`}return s<1?`${Math.round(s*60)}min left`:s<24?`${Math.round(s)}h left`:`${Math.round(s/24)}d left`};function Yf({alert:t,onNavigate:s,testId:a="critical-alert-card"}){const r=Kf(t);return e.jsxs("div",{className:"p-3 sm:p-4 bg-red-50 rounded-lg sm:rounded-xl border border-red-100 hover:shadow-md transition-all duration-200 cursor-pointer",onClick:()=>s==null?void 0:s(t.requestNumber),"data-testid":`${a}-${t.requestId}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-2 sm:mb-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 mb-1 flex-wrap",children:[e.jsx("p",{className:"font-semibold text-xs sm:text-sm text-gray-900","data-testid":`${a}-request-number`,children:t.requestNumber}),t.priority==="express"&&e.jsx(sx,{className:"h-3 w-3 text-red-500 flex-shrink-0","data-testid":`${a}-priority-icon`}),t.breachCount>0&&e.jsx(Q,{variant:"destructive",className:"text-xs","data-testid":`${a}-breach-count`,children:t.breachCount})]}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-700 line-clamp-2","data-testid":`${a}-title`,children:t.title})]}),e.jsx(Q,{variant:"outline",className:"text-xs bg-white border-red-200 text-red-700 font-medium whitespace-nowrap","data-testid":`${a}-remaining-time`,children:Gf(t)})]}),e.jsxs("div",{className:"space-y-1 sm:space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-xs text-gray-600",children:[e.jsx("span",{children:"TAT Used"}),e.jsxs("span",{className:"font-medium","data-testid":`${a}-progress-percentage`,children:[r,"%"]})]}),e.jsx(hs,{value:r,className:`h-1.5 sm:h-2 ${r>=80?"[&>div]:bg-red-600":r>=50?"[&>div]:bg-orange-500":"[&>div]:bg-green-600"}`,"data-testid":`${a}-progress-bar`})]})]})}function Zf(t){return t.filter(s=>{const a=(s.breachCount||0)>0,r=s.isCritical===!0,n=s.status;return n?(a||r)&&(n==="pending"||n==="in-progress"||n==="PENDING"||n==="IN_PROGRESS"):a||r})}function Xf(t){return t.filter(s=>{const a=Number(s.tatPercentageUsed)||0;return(Number(s.remainingHours)||0)>0&&a<100})}function Qf(t){if(t<=0)return"Just breached";if(t<1)return`${Math.round(t*60)} min`;const s=8;if(t0?`${n}h ${i}m`:`${n}h`}const a=Math.floor(t/s),r=t%s;if(r>0){const n=Math.floor(r),i=Math.round((r-n)*60);return i>0?`${a}d ${n}h ${i}m`:`${a}d ${n}h`}return`${a}d`}function Jf(t){return t>=95?"bg-green-100 text-green-700":t>=90?"bg-blue-100 text-blue-700":t>=85?"bg-orange-100 text-orange-700":"bg-red-100 text-red-700"}function zd(t,s,a=3){const r=[];let n=Math.max(1,t-Math.floor(a/2)),i=Math.min(s,n+a-1);i-n0?"animate-pulse":""}`,"data-testid":"critical-count-badge",children:a.totalRecords})]})}),e.jsx(Y,{className:"overflow-y-auto flex-1 p-4",style:{maxHeight:a.totalPages>1?"calc(100% - 140px)":"calc(100% - 80px)"},children:e.jsx("div",{className:"space-y-3 sm:space-y-4",children:s.length===0?e.jsxs("div",{className:"text-center py-6 sm:py-8 text-muted-foreground","data-testid":"no-critical-alerts",children:[e.jsx(ve,{className:"w-10 h-10 sm:w-12 sm:h-12 mx-auto mb-2 text-green-500"}),e.jsx("p",{className:"text-sm",children:"No critical alerts"}),e.jsx("p",{className:"text-xs",children:"All requests are within TAT"})]}):s.map(i=>e.jsx(Yf,{alert:i,onNavigate:o=>n==null?void 0:n(`request/${o}`),testId:"dashboard-critical-alert"},i.requestId))})}),a.totalPages>1&&s.length>0&&e.jsx("div",{className:"border-t bg-gray-50 px-4 py-2 flex-shrink-0",children:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["Page ",a.page," of ",a.totalPages," (",a.totalRecords," total)"]}),e.jsxs("div",{className:"flex items-center justify-center gap-1 flex-wrap",children:[e.jsx(M,{variant:"outline",size:"sm",onClick:()=>r(a.page-1),disabled:a.page===1,className:"h-7 w-7 p-0","data-testid":"critical-pagination-prev",children:e.jsx(wt,{className:"h-3 w-3 rotate-180"})}),zd(a.page,a.totalPages,3).map(i=>e.jsx(M,{variant:i===a.page?"default":"outline",size:"sm",onClick:()=>r(i),className:`h-7 w-7 p-0 text-xs ${i===a.page?"bg-red-600 text-white hover:bg-red-700":""}`,"data-testid":`critical-pagination-page-${i}`,children:i},i)),e.jsx(M,{variant:"outline",size:"sm",onClick:()=>r(a.page+1),disabled:a.page===a.totalPages,className:"h-7 w-7 p-0","data-testid":"critical-pagination-next",children:e.jsx(wt,{className:"h-3 w-3"})})]})]})})]})}const t0=t=>{switch(t.toLowerCase()){case"express":return"bg-orange-100 text-orange-800 border-orange-200";case"standard":return"bg-blue-100 text-blue-800 border-blue-200";case"high":return"bg-red-100 text-red-800 border-red-200";case"medium":return"bg-orange-100 text-orange-800 border-orange-200";case"low":return"bg-green-100 text-green-800 border-green-200";default:return"bg-gray-100 text-gray-800 border-gray-200"}},s0=t=>{const s=new Date,a=new Date(t),r=Op(s,a);if(r<1)return"just now";if(r<60)return`${r} minute${r>1?"s":""} ago`;const n=$p(s,a);if(n<24)return`${n} hour${n>1?"s":""} ago`;const i=Up(s,a);return`${i} day${i>1?"s":""} ago`},a0=t=>{if(!t)return t;let s=t.replace(/\s*\([^)]*@[^)]*\)/g,"");return s=s.replace(/\s+by\s+.+$/i,""),s=s.replace(/has been added as approver/gi,"added as approver"),s=s.replace(/has been added as spectator/gi,"added as spectator"),s=s.replace(/has been/gi,""),s=s.replace(/with TAT of (\d+) hours?/gi,"(TAT: $1h)"),s=s.replace(/with TAT of (\d+) days?/gi,"(TAT: $1d)"),s=s.replace(/\s+/g," "),s.trim()},r0=t=>{const s=t.toLowerCase();return s.includes("approv")?e.jsx(ve,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-green-600"}):s.includes("reject")?e.jsx(is,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-red-600"}):s.includes("comment")?e.jsx(ws,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-blue-600"}):s.includes("escalat")?e.jsx(ls,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-orange-600"}):s.includes("submit")?e.jsx(Te,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-purple-600"}):s.includes("document")?e.jsx(Or,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-indigo-600"}):e.jsx(as,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-gray-600"})};function n0({activity:t,currentUserId:s,currentUserDisplayName:a,currentUserEmail:r,onNavigate:n,testId:i="activity-feed-item"}){const o=t.userId===s,l=o?"You":t.userName||"System",c=o?(a||r||"ME").split(" ").map(d=>d[0]).join("").toUpperCase().substring(0,2):t.userName?t.userName.split(" ").map(d=>d[0]).join("").toUpperCase().substring(0,2):"SY";return e.jsxs("div",{className:"flex items-start gap-2 sm:gap-3 p-3 sm:p-4 rounded-lg hover:bg-gray-50 transition-all duration-200 cursor-pointer border border-gray-100 hover:border-gray-300",onClick:()=>n==null?void 0:n(t.requestNumber),"data-testid":`${i}-${t.activityId}`,children:[e.jsxs("div",{className:"relative flex-shrink-0 mt-0.5",children:[e.jsxs(jt,{className:`h-8 w-8 sm:h-10 sm:w-10 ring-2 shadow-sm ${o?"ring-blue-200":"ring-white"}`,"data-testid":`${i}-avatar`,children:[e.jsx(Wr,{src:""}),e.jsx(Nt,{className:`text-white font-semibold text-xs sm:text-sm ${o?"bg-blue-600":"bg-slate-700"}`,children:c})]}),e.jsx("div",{className:"absolute -bottom-0.5 -right-0.5 sm:-bottom-1 sm:-right-1 w-4 h-4 sm:w-5 sm:h-5 bg-white rounded-full flex items-center justify-center shadow-sm border border-gray-200",children:r0(t.action)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"flex items-center justify-between gap-2 mb-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold text-xs sm:text-sm text-gray-900","data-testid":`${i}-request-number`,children:t.requestNumber}),e.jsx(Q,{variant:"outline",className:`text-xs ${t0(t.priority)} font-medium flex-shrink-0`,"data-testid":`${i}-priority`,children:t.priority})]})}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1 line-clamp-2",children:e.jsx("span",{className:`font-medium ${t.action.toLowerCase().includes("approv")?"text-green-600":t.action.toLowerCase().includes("reject")?"text-red-600":t.action.toLowerCase().includes("submit")?"text-blue-600":t.action.toLowerCase().includes("add")?"text-indigo-600":"text-gray-700"}`,"data-testid":`${i}-action`,children:a0(t.action)})}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-700 line-clamp-1 mb-1","data-testid":`${i}-request-title`,children:t.requestTitle}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx("span",{className:`font-medium truncate max-w-[150px] sm:max-w-[200px] ${o?"text-blue-600":"text-gray-900"}`,"data-testid":`${i}-user-name`,children:l}),e.jsx("span",{children:"•"}),e.jsx("span",{className:"whitespace-nowrap","data-testid":`${i}-timestamp`,children:s0(t.timestamp)})]})]}),e.jsx(wt,{className:"h-4 w-4 text-gray-400 hover:text-blue-600 transition-colors flex-shrink-0 hidden sm:block mt-1","data-testid":`${i}-arrow`})]})}function i0({isAdmin:t,recentActivity:s,pagination:a,refreshing:r,onPageChange:n,onRefresh:i,onNavigate:o,currentUserId:l,currentUserDisplayName:c,currentUserEmail:d}){return e.jsxs(G,{className:"lg:col-span-1 shadow-md hover:shadow-lg transition-shadow flex flex-col overflow-hidden",style:{height:"100%"},"data-testid":"recent-activity-section",children:[e.jsx(te,{className:"pb-3 sm:pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-1 min-w-0",children:[e.jsx("div",{className:"p-2 sm:p-3 bg-blue-100 rounded-lg",children:e.jsx(as,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx(se,{className:"text-base sm:text-lg text-gray-900",children:"Recent Activity"}),e.jsx(he,{className:"text-xs sm:text-sm text-gray-600 truncate",children:t?"All workflow updates":"My workflow updates"})]})]}),e.jsxs(M,{variant:"ghost",size:"sm",className:"text-blue-600 hover:bg-blue-50 font-medium flex-shrink-0 h-8 sm:h-9 px-2 sm:px-3 sm:min-w-[100px]",onClick:i,disabled:r,"data-testid":"activity-refresh-button",children:[e.jsx(Lt,{className:`w-3 h-3 sm:w-4 sm:h-4 ${r?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline ml-2 sm:w-[60px] sm:text-center",children:r?"Refreshing...":"Refresh"})]})]})}),e.jsx(Y,{className:"overflow-y-auto flex-1 p-4",style:{maxHeight:a.totalPages>1?"calc(100% - 140px)":"calc(100% - 80px)"},children:e.jsx("div",{className:"space-y-2 sm:space-y-3",children:s.length===0?e.jsxs("div",{className:"text-center py-6 sm:py-8 text-muted-foreground","data-testid":"no-recent-activity",children:[e.jsx(as,{className:"w-10 h-10 sm:w-12 sm:h-12 mx-auto mb-2 text-gray-400"}),e.jsx("p",{className:"text-sm",children:"No recent activity"}),e.jsx("p",{className:"text-xs",children:"Activity will appear here once requests are processed"})]}):s.map(m=>e.jsx(n0,{activity:m,currentUserId:l,currentUserDisplayName:c,currentUserEmail:d,onNavigate:u=>o==null?void 0:o(`request/${u}`),testId:"dashboard-activity"},m.activityId))})}),a.totalPages>1&&s.length>0&&e.jsx("div",{className:"border-t bg-gray-50 px-4 py-2 flex-shrink-0",children:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["Page ",a.page," of ",a.totalPages," (",a.totalRecords," total)"]}),e.jsxs("div",{className:"flex items-center justify-center gap-1 flex-wrap",children:[e.jsx(M,{variant:"outline",size:"sm",onClick:()=>n(a.page-1),disabled:a.page===1,className:"h-7 w-7 p-0","data-testid":"activity-pagination-prev",children:e.jsx(wt,{className:"h-3 w-3 rotate-180"})}),zd(a.page,a.totalPages,3).map(m=>e.jsx(M,{variant:m===a.page?"default":"outline",size:"sm",onClick:()=>n(m),className:`h-7 w-7 p-0 text-xs ${m===a.page?"bg-re-green text-white hover:bg-re-green/90":""}`,"data-testid":`activity-pagination-page-${m}`,children:m},m)),e.jsx(M,{variant:"outline",size:"sm",onClick:()=>n(a.page+1),disabled:a.page===a.totalPages,className:"h-7 w-7 p-0","data-testid":"activity-pagination-next",children:e.jsx(wt,{className:"h-3 w-3"})})]})]})})]})}function o0({kpis:t,upcomingDeadlines:s,criticalRequests:a,departmentStats:r,dateRange:n,customStartDate:i,customEndDate:o,exportingDeptStats:l,onKPIClick:c,onExportDepartmentStats:d}){if(!t)return null;const m=()=>({dateRange:n,startDate:i,endDate:o});return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4 sm:gap-6","data-testid":"admin-analytics-section",children:[e.jsxs("div",{className:"flex flex-col gap-4 sm:gap-6 lg:col-span-1",children:[e.jsxs(G,{className:"shadow-md hover:shadow-lg transition-shadow flex-1","data-testid":"active-levels-card",children:[e.jsx(te,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-2 bg-blue-100 rounded-lg",children:e.jsx(as,{className:"h-4 w-4 text-blue-600"})}),e.jsx(se,{className:"text-sm",children:"Active Levels"})]})}),e.jsx(Y,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:"text-2xl sm:text-3xl font-bold text-blue-600",children:s.length}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"levels"})]}),e.jsx(yt,{}),e.jsxs("div",{className:"space-y-1 text-xs",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-muted-foreground",children:"Avg Time/Level"}),e.jsxs("span",{className:"font-semibold",children:[s.length>0?(t.tatEfficiency.avgCycleTimeHours/s.length).toFixed(1):"0","h"]})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-muted-foreground",children:"At Risk"}),e.jsx("span",{className:"font-semibold text-red-600",children:a.filter(u=>u.breachCount>0).length})]})]})]})})]}),e.jsxs(G,{className:"shadow-md hover:shadow-lg transition-shadow flex-1","data-testid":"collaboration-card",children:[e.jsx(te,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-2 bg-indigo-100 rounded-lg",children:e.jsx(ws,{className:"h-4 w-4 text-indigo-600"})}),e.jsx(se,{className:"text-sm",children:"Collaboration"})]})}),e.jsx(Y,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"text-center p-2 bg-indigo-50 rounded",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Notes"}),e.jsx("p",{className:"text-lg sm:text-xl font-bold text-indigo-600",children:t.engagement.workNotesAdded})]}),e.jsxs("div",{className:"text-center p-2 bg-purple-50 rounded",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Files"}),e.jsx("p",{className:"text-lg sm:text-xl font-bold text-purple-600",children:t.engagement.attachmentsUploaded})]})]}),e.jsx(yt,{}),e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:[t.requestVolume.totalRequests>0?(t.engagement.workNotesAdded/t.requestVolume.totalRequests).toFixed(1):"0"," ","avg notes per request"]})]})})]})]}),r.length>0&&e.jsxs(G,{className:"shadow-md hover:shadow-lg transition-shadow lg:col-span-2","data-testid":"department-stats-card",children:[e.jsx(te,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"bg-blue-50 p-2 sm:p-3 rounded-lg",children:e.jsx(ax,{className:"h-5 w-5 sm:h-6 sm:w-6 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(se,{className:"text-base sm:text-lg lg:text-xl",children:"Department-wise Workflow Summary"}),e.jsx(he,{className:"text-xs sm:text-sm",children:"Workflow distribution across departments"})]})]}),e.jsxs(M,{variant:"outline",size:"sm",className:"gap-2 self-start sm:self-auto",onClick:()=>d(n,i,o),disabled:l,"data-testid":"export-dept-stats-button",children:[e.jsx(ns,{className:`w-3 h-3 sm:w-4 sm:h-4 ${l?"animate-pulse":""}`}),e.jsx("span",{className:"text-xs sm:text-sm",children:l?"Exporting...":"Export"})]})]})}),e.jsx(Y,{children:e.jsx(Ni,{width:"100%",height:400,children:e.jsxs(Ep,{data:r,children:[e.jsx(Jc,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(ed,{dataKey:"department",stroke:"#999",tick:u=>{const{x:h,y:x,payload:p}=u;return e.jsx("g",{transform:`translate(${h},${x})`,children:e.jsx("text",{x:0,y:0,dy:16,textAnchor:"middle",fill:"#999",fontSize:11,className:"cursor-pointer hover:text-blue-600 hover:underline",onClick:()=>{c({...m(),department:p.value})},children:p.value})})}}),e.jsx(td,{stroke:"#999",tick:{fontSize:11}}),e.jsx(wi,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(sd,{verticalAlign:"bottom",height:36,iconType:"square",wrapperStyle:{fontSize:"12px",paddingTop:"10px"}}),e.jsx(rn,{dataKey:"approved",fill:"#10b981",name:"Approved"}),e.jsx(rn,{dataKey:"inProgress",fill:"#f59e0b",name:"Pending"}),e.jsx(rn,{dataKey:"rejected",fill:"#ef4444",name:"Rejected"})]})})})]})]})}function l0({kpis:t}){return t?e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-6","data-testid":"user-metrics-section",children:[e.jsxs(G,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"user-activity-card",children:[e.jsx(te,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-2 bg-indigo-100 rounded-lg",children:e.jsx(ws,{className:"h-4 w-4 text-indigo-600"})}),e.jsx(se,{className:"text-sm",children:"My Activity"})]})}),e.jsx(Y,{children:e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"text-center p-3 bg-indigo-50 rounded",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Work Notes"}),e.jsx("p",{className:"text-xl sm:text-2xl font-bold text-indigo-600",children:t.engagement.workNotesAdded})]}),e.jsxs("div",{className:"text-center p-3 bg-purple-50 rounded",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Attachments"}),e.jsx("p",{className:"text-xl sm:text-2xl font-bold text-purple-600",children:t.engagement.attachmentsUploaded})]})]})})})]}),e.jsxs(G,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"user-response-time-card",children:[e.jsx(te,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-2 bg-purple-100 rounded-lg",children:e.jsx(De,{className:"h-4 w-4 text-purple-600"})}),e.jsx(se,{className:"text-sm",children:"Avg Response Time"})]})}),e.jsx(Y,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex items-baseline gap-2",children:e.jsx("span",{className:"text-2xl sm:text-3xl font-bold text-purple-600",children:nt(t.tatEfficiency.avgCycleTimeHours)})}),e.jsx(yt,{}),e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["≈ ",t.tatEfficiency.avgCycleTimeDays.toFixed(1)," working days"]})]})})]})]}):null}function c0({priorityDistribution:t,onNavigate:s}){return t.length===0?null:e.jsxs(G,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"priority-distribution-report",children:[e.jsx(te,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"bg-green-50 p-2 sm:p-3 rounded-lg",children:e.jsx(it,{className:"h-5 w-5 sm:h-6 sm:w-6 text-green-600"})}),e.jsxs("div",{children:[e.jsx(se,{className:"text-base sm:text-lg lg:text-xl",children:"Priority Distribution Report"}),e.jsx(he,{className:"text-xs sm:text-sm",children:"Express vs Standard workflow analysis"})]})]})}),e.jsxs(Y,{children:[e.jsx("div",{className:"grid grid-cols-2 gap-4 mb-6",children:t.map((a,r)=>{const n=Number(a.avgCycleTimeHours)||0,i=a.priority==="express",o=i?"bg-red-50":"bg-blue-50",l=i?"bg-red-500":"bg-blue-500";return e.jsxs("div",{className:`${o} p-4 rounded-lg`,"data-testid":`priority-card-${a.priority}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("div",{className:`w-3 h-3 ${l} rounded-full`}),e.jsx("span",{className:"text-sm text-gray-600 capitalize",children:a.priority})]}),e.jsx("div",{className:"text-2xl sm:text-3xl font-bold text-gray-900 mb-1",children:a.totalCount}),e.jsxs("div",{className:"text-xs text-gray-500",children:["Avg: ",nt(n)," cycle"]})]},r)})}),e.jsx("div",{className:"flex justify-center",children:e.jsx(Ni,{width:"100%",height:300,children:e.jsxs(Mp,{children:[e.jsx(Ip,{data:t.map(a=>({name:a.priority.charAt(0).toUpperCase()+a.priority.slice(1),value:a.totalCount,priority:a.priority,percentage:Math.round(a.totalCount/t.reduce((r,n)=>r+n.totalCount,0)*100)})),cx:"50%",cy:"50%",labelLine:!0,label:({cx:a,cy:r,midAngle:n,outerRadius:i,name:o,percentage:l})=>{const c=Math.PI/180,d=i+35,m=a+d*Math.cos(-n*c),u=r+d*Math.sin(-n*c);return e.jsx("text",{x:m,y:u,fill:"#1f2937",textAnchor:m>a?"start":"end",dominantBaseline:"central",style:{fontSize:"14px",fontWeight:"600",pointerEvents:"none"},children:`${o}: ${l}%`})},outerRadius:90,fill:"#8884d8",dataKey:"value",onClick:a=>{a&&a.priority&&s&&s(`requests?priority=${a.priority}`)},style:{cursor:"pointer"},children:t.map((a,r)=>e.jsx(_p,{fill:a.priority==="express"?"#ef4444":"#3b82f6",style:{cursor:"pointer"}},`cell-${r}`))}),e.jsx(wi,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"},formatter:(a,r,n)=>{var o;const i=((o=n.payload)==null?void 0:o.priority)||"";return[`${a} requests`,`Click for ${i}`]}})]})})})]})]})}function ca({currentPage:t,totalPages:s,itemsPerPage:a,totalRecords:r,onPageChange:n,loading:i=!1,itemLabel:o="items",testIdPrefix:l="pagination"}){const c=()=>{const u=[];let x=Math.max(1,t-Math.floor(2.5)),p=Math.min(s,x+5-1);p-x<4&&(x=Math.max(1,p-5+1));for(let y=x;y<=p;y++)u.push(y);return u},d=r>0?(t-1)*a+1:0,m=Math.min(t*a,r);return s<=1?e.jsx(G,{className:"shadow-md border-gray-200","data-testid":`${l}-container`,children:e.jsx(Y,{className:"p-4",children:e.jsx("div",{className:"flex items-center justify-center",children:e.jsx("div",{className:"text-sm sm:text-base font-medium text-gray-700","data-testid":`${l}-info`,children:i?`Loading ${o}...`:r===0?`No ${o} found`:r===1?`Showing 1 ${o.slice(0,-1)}`:d===m?`Showing ${d} of ${r} ${o}`:`Showing ${d} to ${m} of ${r} ${o}`})})})}):e.jsx(G,{className:"shadow-md border-gray-200","data-testid":`${l}-container`,children:e.jsx(Y,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-between gap-3",children:[e.jsxs("div",{className:"text-sm sm:text-base font-medium text-gray-700","data-testid":`${l}-info`,children:["Showing ",d," to ",m," of ",r," ",o]}),e.jsxs("div",{className:"flex items-center gap-2","data-testid":`${l}-controls`,children:[e.jsx(M,{variant:"outline",size:"sm",onClick:()=>n(t-1),disabled:t===1,className:"h-8 w-8 p-0","data-testid":`${l}-prev-btn`,"aria-label":"Previous page",children:e.jsx(wt,{className:"h-4 w-4 rotate-180"})}),t>3&&s>5&&e.jsxs(e.Fragment,{children:[e.jsx(M,{variant:"outline",size:"sm",onClick:()=>n(1),className:"h-8 w-8 p-0","data-testid":`${l}-page-1`,children:"1"}),e.jsx("span",{className:"text-muted-foreground","data-testid":`${l}-ellipsis-start`,children:"..."})]}),c().map(u=>e.jsx(M,{variant:u===t?"default":"outline",size:"sm",onClick:()=>n(u),className:`h-8 w-8 p-0 ${u===t?"bg-re-green text-white hover:bg-re-green/90":""}`,"data-testid":`${l}-page-${u}`,"aria-current":u===t?"page":void 0,children:u},u)),t5&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground","data-testid":`${l}-ellipsis-end`,children:"..."}),e.jsx(M,{variant:"outline",size:"sm",onClick:()=>n(s),className:"h-8 w-8 p-0","data-testid":`${l}-page-${s}`,children:s})]}),e.jsx(M,{variant:"outline",size:"sm",onClick:()=>n(t+1),disabled:t===s,className:"h-8 w-8 p-0","data-testid":`${l}-next-btn`,"aria-label":"Next page",children:e.jsx(wt,{className:"h-4 w-4"})})]})]})})})}function d0({breachedRequests:t,pagination:s,dateRange:a,customStartDate:r,customEndDate:n,onPageChange:i,onKPIClick:o,onNavigate:l}){if(t.length===0)return null;const c=()=>({dateRange:a,startDate:r,endDate:n});return e.jsxs(G,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"tat-breach-report",children:[e.jsx(te,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"bg-red-50 p-2 sm:p-3 rounded-lg",children:e.jsx(is,{className:"h-5 w-5 sm:h-6 sm:w-6 text-red-600"})}),e.jsxs("div",{children:[e.jsx(se,{className:"text-base sm:text-lg lg:text-xl",children:"TAT Breach Report"}),e.jsx(he,{className:"text-xs sm:text-sm",children:"Requests that breached defined turnaround time"})]})]}),e.jsxs(Q,{variant:"destructive",className:"text-sm font-medium self-start sm:self-auto",children:[t.length," ",t.length===1?"Breach":"Breaches"]})]})}),e.jsxs(Y,{children:[e.jsx("div",{className:"overflow-x-auto -mx-4 sm:mx-0",children:e.jsxs("table",{className:"w-full min-w-[1000px]",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-gray-200 bg-gray-50",children:[e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700",children:"Request ID"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700 w-[250px]",children:"Title"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700",children:"Department"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700",children:"Approver"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700",children:"Level"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700 w-[140px]",children:"Breach Time"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700 w-[300px]",children:"Reason"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700",children:"Priority"})]})}),e.jsx("tbody",{children:t.map((d,m)=>{const u=d.breachTime||0;return e.jsxs("tr",{className:"border-b border-gray-100 hover:bg-gray-50 transition-colors",children:[e.jsx("td",{className:"py-3 px-4 text-sm font-medium text-blue-600 cursor-pointer hover:underline",onClick:()=>l==null?void 0:l(`request/${d.requestNumber}`),"data-testid":`breach-request-${d.requestNumber}`,children:d.requestNumber}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-900 w-[250px]",children:e.jsx("p",{className:"break-words leading-relaxed",children:d.title})}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-700 cursor-pointer hover:text-blue-600 hover:underline",onClick:()=>{d.department&&d.department!=="Unknown"&&o({...c(),department:d.department})},children:d.department||"Unknown"}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-700",children:d.approverId?e.jsx("span",{className:"cursor-pointer hover:text-blue-600 hover:underline",onClick:()=>{if(l){const h=new URLSearchParams;h.set("approver",d.approverId),h.set("approverType","current"),h.set("slaCompliance","breached"),l(`requests?${h.toString()}`)}},title:"Click to view all requests for this approver",children:d.approver||"N/A"}):d.approver||"N/A"}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-700",children:d.currentLevel&&d.totalLevels?e.jsxs("span",{className:"font-medium",children:[d.currentLevel,"/",d.totalLevels]}):d.currentLevel?e.jsxs("span",{className:"font-medium",children:[d.currentLevel,"/—"]}):e.jsx("span",{className:"text-gray-400",children:"—"})}),e.jsx("td",{className:"py-3 px-4 w-[140px]",children:e.jsx("span",{className:"bg-red-500 text-white px-2 py-1 rounded text-xs font-medium whitespace-nowrap",children:Qf(u)})}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-700 w-[300px]",children:e.jsx("div",{className:"max-h-32 overflow-y-auto",children:e.jsx("p",{className:"whitespace-pre-line break-words leading-relaxed",children:d.breachReason||"TAT Exceeded"})})}),e.jsx("td",{className:"py-3 px-4",children:e.jsx(Q,{variant:"outline",className:`text-xs font-medium ${d.priority==="express"?"bg-orange-100 text-orange-800 border-orange-200":"bg-blue-100 text-blue-800 border-blue-200"}`,children:d.priority})})]},m)})})]})}),e.jsx("div",{className:"mt-4",children:e.jsx(ca,{currentPage:s.page,totalPages:s.totalPages,totalRecords:s.totalRecords,itemsPerPage:10,onPageChange:i,itemLabel:"critical requests",testIdPrefix:"dashboard-critical-pagination"})})]})]})}function m0({isAdmin:t,upcomingDeadlines:s,pagination:a,onPageChange:r,onNavigate:n}){return s.length===0?null:e.jsxs(G,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"upcoming-deadlines-section",children:[e.jsx(te,{children:e.jsx("div",{className:"flex items-center justify-between gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qe,{className:"h-4 w-4 sm:h-5 sm:w-5 text-orange-600"}),e.jsxs("div",{children:[e.jsx(se,{className:"text-base sm:text-lg",children:"Upcoming Deadlines"}),e.jsx(he,{className:"text-xs sm:text-sm",children:t?"Current active levels organization-wide":"Requests awaiting your approval"})]})]})})}),e.jsxs(Y,{children:[e.jsx("div",{className:"space-y-2 sm:space-y-3",children:s.map((i,o)=>{const l=Number(i.tatPercentageUsed)||0,c=Number(i.elapsedHours)||0,d=Number(i.remainingHours)||0;return e.jsxs("div",{className:"p-3 sm:p-4 border rounded-lg hover:shadow-md transition-all cursor-pointer",onClick:()=>n==null?void 0:n(`request/${i.requestNumber}`),"data-testid":`deadline-item-${i.requestNumber}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 mb-1 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-xs sm:text-sm",children:i.requestNumber}),e.jsx(Q,{variant:"outline",className:`text-xs ${i.priority==="express"?"bg-orange-50 text-orange-700":"bg-blue-50 text-blue-700"}`,children:i.priority})]}),e.jsx("p",{className:"text-xs sm:text-sm text-muted-foreground truncate",children:i.requestTitle}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 text-xs text-muted-foreground flex-wrap",children:[e.jsxs(Q,{variant:"outline",className:"text-xs bg-blue-50 text-blue-700 border-blue-200",children:["Level ",i.levelNumber||"?","/",i.totalLevels||"?"]}),e.jsx("span",{className:"truncate",children:i.approverName})]})]}),e.jsxs("div",{className:"text-right flex-shrink-0",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"TAT Used"}),e.jsxs("p",{className:`text-base sm:text-lg font-bold ${l>=80?"text-red-600":l>=50?"text-orange-600":"text-green-600"}`,children:[l.toFixed(0),"%"]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(hs,{value:l,className:`h-1.5 sm:h-2 ${l>=80?"bg-red-100":l>=50?"bg-orange-100":"bg-green-100"}`}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[nt(c)," elapsed"]}),e.jsxs("span",{children:[nt(d)," left"]})]})]})]},o)})}),e.jsx("div",{className:"mt-4",children:e.jsx(ca,{currentPage:a.page,totalPages:a.totalPages,totalRecords:a.totalRecords,itemsPerPage:10,onPageChange:r,itemLabel:"deadlines",testIdPrefix:"dashboard-deadlines-pagination"})})]})]})}function u0({aiRemarkUtilization:t}){return t?e.jsxs(G,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"ai-remark-utilization-report",children:[e.jsx(te,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"bg-purple-50 p-2 sm:p-3 rounded-lg",children:e.jsx(ki,{className:"h-5 w-5 sm:h-6 sm:w-6 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(se,{className:"text-base sm:text-lg lg:text-xl",children:"AI Remark Utilization Report"}),e.jsx(he,{className:"text-xs sm:text-sm",children:"AI-generated remarks usage and edits"})]})]})}),e.jsxs(Y,{children:[e.jsxs("div",{className:"grid grid-cols-3 gap-4 mb-6",children:[e.jsxs("div",{className:"bg-purple-50 p-4 rounded-lg text-center","data-testid":"ai-total-usage",children:[e.jsx("div",{className:"text-sm text-gray-600 mb-1",children:"Total Usage"}),e.jsx("div",{className:"text-2xl font-bold text-gray-900",children:t.totalUsage})]}),e.jsxs("div",{className:"bg-pink-50 p-4 rounded-lg text-center","data-testid":"ai-total-edits",children:[e.jsx("div",{className:"text-sm text-gray-600 mb-1",children:"Total Edits"}),e.jsx("div",{className:"text-2xl font-bold text-gray-900",children:t.totalEdits})]}),e.jsxs("div",{className:"bg-purple-50 p-4 rounded-lg text-center","data-testid":"ai-edit-rate",children:[e.jsx("div",{className:"text-sm text-gray-600 mb-1",children:"Edit Rate"}),e.jsxs("div",{className:"text-2xl font-bold text-gray-900",children:[t.editRate,"%"]})]})]}),t.monthlyTrends&&t.monthlyTrends.length>0&&e.jsx(Ni,{width:"100%",height:250,children:e.jsxs(Lp,{data:t.monthlyTrends,children:[e.jsx(Jc,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(ed,{dataKey:"month",stroke:"#999",tick:{fontSize:11}}),e.jsx(td,{stroke:"#999",tick:{fontSize:11}}),e.jsx(wi,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(sd,{verticalAlign:"bottom",height:36,iconType:"circle",wrapperStyle:{fontSize:"12px",paddingTop:"10px"}}),e.jsx(zo,{type:"monotone",dataKey:"aiUsage",stroke:"#8b5cf6",strokeWidth:2,name:"AI Usage",dot:{fill:"#8b5cf6",r:4}}),e.jsx(zo,{type:"monotone",dataKey:"manualEdits",stroke:"#ec4899",strokeWidth:2,name:"Manual Edits",dot:{fill:"#ec4899",r:4}})]})})]})]}):null}function h0({approverPerformance:t,pagination:s,dateRange:a,customStartDate:r,customEndDate:n,loading:i,exportingApproverPerformance:o,onPageChange:l,onExport:c,onNavigate:d}){return t.length===0?null:e.jsxs(G,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"approver-performance-report",children:[e.jsx(te,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"bg-yellow-50 p-2 sm:p-3 rounded-lg",children:e.jsx(at,{className:"h-5 w-5 sm:h-6 sm:w-6 text-yellow-600"})}),e.jsxs("div",{children:[e.jsx(se,{className:"text-base sm:text-lg lg:text-xl",children:"Approver Performance Report"}),e.jsx(he,{className:"text-xs sm:text-sm",children:"Response time & TAT compliance tracking"})]})]}),e.jsx(M,{onClick:()=>c(a,r,n),disabled:o||i,className:"bg-re-green hover:bg-re-green/90 text-white shrink-0",size:"sm","data-testid":"export-approver-performance-button",children:o?e.jsxs(e.Fragment,{children:[e.jsx(Lt,{className:"w-4 h-4 mr-2 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ns,{className:"w-4 h-4 mr-2"}),"Export"]})})]})}),e.jsxs(Y,{children:[e.jsx("div",{className:"space-y-3",children:t.map((m,u)=>{const h=m.tatCompliancePercent;return e.jsxs("div",{className:"border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer",onClick:()=>{const x=new URLSearchParams;x.set("approverId",m.approverId),x.set("approverName",m.approverName),x.set("dateRange",a),a==="custom"&&r&&n&&(x.set("startDate",r.toISOString()),x.set("endDate",n.toISOString())),d==null||d(`/approver-performance?${x.toString()}`)},"data-testid":`approver-item-${m.approverId}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 bg-orange-500 rounded-full flex items-center justify-center text-white font-semibold text-sm flex-shrink-0",children:u+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium text-gray-900 truncate",children:m.approverName}),e.jsxs("div",{className:"text-xs text-gray-500",children:[m.totalApproved," requests approved"]})]})]}),e.jsxs("span",{className:`px-2 py-1 rounded text-xs font-medium ${Jf(h)} flex-shrink-0`,children:[h,"% TAT"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 mt-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"Avg Response"}),e.jsx("div",{className:"text-sm font-medium text-gray-900",children:nt(m.avgResponseHours)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"Pending"}),e.jsx("div",{className:"text-sm font-medium text-gray-900",children:e.jsx("span",{className:"bg-gray-500 text-white px-2 py-1 rounded text-xs",children:m.pendingCount})})]})]})]},u)})}),e.jsx("div",{className:"mt-4",children:e.jsx(ca,{currentPage:s.page,totalPages:s.totalPages,totalRecords:s.totalRecords,itemsPerPage:10,onPageChange:l,itemLabel:"approvers",testIdPrefix:"dashboard-approver-pagination"})})]})]})}function p0(t){const s=new URLSearchParams;t.status&&s.set("status",t.status),t.priority&&s.set("priority",t.priority),t.slaCompliance&&s.set("slaCompliance",t.slaCompliance),t.department&&s.set("department",t.department),t.dateRange&&s.set("dateRange",t.dateRange),t.startDate&&s.set("startDate",t.startDate.toISOString()),t.endDate&&s.set("endDate",t.endDate.toISOString());const a=s.toString(),r=t.targetPage||"requests",n=r==="open-requests"?"/open-requests":r==="my-requests"?"/my-requests":"/requests";return a?`${n}?${a}`:n}function x0(t,s,a){const r=[{label:"New Request",icon:Te,action:()=>s==null?void 0:s(),color:"bg-emerald-600 hover:bg-emerald-700"},{label:"View Pending",icon:De,action:()=>a==null?void 0:a("open-requests"),color:"bg-blue-600 hover:bg-blue-700"},{label:"Settings",icon:la,action:()=>a==null?void 0:a("settings"),color:"bg-slate-600 hover:bg-slate-700"}];return t&&r.splice(2,0,{label:"Reports",icon:as,action:()=>a==null?void 0:a("detailed-reports"),color:"bg-purple-600 hover:bg-purple-700"}),r}function ll({onNavigate:t,onNewRequest:s}){const{user:a}=Bt(),r=wf(),n=Vd(O=>O.dashboard.viewAsUser),i=g.useMemo(()=>qr(a),[a]),o=i&&!n,l=g.useCallback(O=>{r(Af(O))},[r]),c=Tf(),{dateRange:d,customStartDate:m,customEndDate:u,showCustomDatePicker:h,handleDateRangeChange:x,handleApplyCustomDate:p,resetCustomDates:y,setCustomStartDate:v,setCustomEndDate:N,setShowCustomDatePicker:f}=c,b=kf(),{activity:j,critical:C,deadlines:R,approver:I,updateActivityPagination:T,updateCriticalPagination:E,updateDeadlinesPagination:w,updateApproverPagination:S,handleActivityPageChange:D,handleCriticalPageChange:H,handleDeadlinesPageChange:L,handleApproverPageChange:F}=b,A=Df({isAdmin:o,viewAsUser:i&&n,userId:a==null?void 0:a.userId,dateRange:d,customStartDate:m,customEndDate:u,onPaginationUpdate:{activity:T,critical:E,deadlines:w,approver:S}}),{kpis:k,recentActivity:P,criticalRequests:_,departmentStats:W,priorityDistribution:Z,upcomingDeadlines:ae,aiRemarkUtilization:$,approverPerformance:ne,loading:me,refreshing:q,fetchDashboardData:z,fetchRecentActivities:re,fetchCriticalRequests:K,fetchUpcomingDeadlines:B,fetchApproverPerformance:J}=A,ue=Uf(),{exportingDeptStats:be,exportingApproverPerformance:Ie,handleExportDepartmentStats:Ve,handleExportApproverPerformance:Oe}=ue,Ue=g.useMemo(()=>Zf(_),[_]),$e=g.useMemo(()=>Xf(ae),[ae]),Dt=g.useCallback(()=>{z(!0)},[d,m,u,z]),Fe=g.useCallback(()=>{p(()=>{m&&u&&z(!1)})},[m,u,p,z]),Ra=g.useCallback(O=>{D(O,re)},[D,re]),Hs=g.useCallback(O=>{H(O,K)},[H,K]),Da=g.useCallback(O=>{L(O,B)},[L,B]),Pa=g.useCallback(O=>{F(O,()=>J(O))},[F,J]);g.useEffect(()=>{d==="custom"?m&&u&&z(!1):z(!1)},[d,m,u,n]);const da=g.useMemo(()=>x0(i,s,t),[i,s,t]),Ss=g.useCallback(O=>{const ee=p0(O);t==null||t(ee)},[t]);return me?e.jsx("div",{className:"flex items-center justify-center h-screen",children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx(Lt,{className:"w-8 h-8 animate-spin text-blue-600"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading dashboard..."})]})}):e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto p-3 sm:p-4","data-testid":"dashboard",children:[e.jsx(Vf,{isAdmin:i,effectiveIsAdmin:o,viewAsUser:n,onToggleView:l,quickActions:da,userDisplayName:a==null?void 0:a.displayName,userEmail:a==null?void 0:a.email}),e.jsx(Hf,{isAdmin:o,dateRange:d,customStartDate:m,customEndDate:u,showCustomDatePicker:h,refreshing:q,onDateRangeChange:x,onCustomStartDateChange:v,onCustomEndDateChange:N,onShowCustomDatePickerChange:f,onApplyCustomDate:Fe,onResetCustomDates:y,onRefresh:Dt}),o?e.jsx(qf,{kpis:k,priorityDistribution:Z,dateRange:d,customStartDate:m,customEndDate:u,onKPIClick:Ss}):e.jsx(Wf,{kpis:k,criticalRequests:_,dateRange:d,customStartDate:m,customEndDate:u,onKPIClick:Ss,onNavigate:t,userId:a==null?void 0:a.userId,userDisplayName:(a==null?void 0:a.displayName)||(a==null?void 0:a.email)}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4 sm:gap-6 h-[90vh] min-h-[720px] lg:h-[60vh] lg:min-h-[480px]","data-testid":"dashboard-alerts-activity",children:[e.jsx(e0,{isAdmin:o,breachedRequests:Ue,pagination:C,onPageChange:Hs,onNavigate:t}),e.jsx(i0,{isAdmin:o,recentActivity:P,pagination:j,refreshing:q,onPageChange:Ra,onRefresh:Dt,onNavigate:t,currentUserId:a==null?void 0:a.userId,currentUserDisplayName:a==null?void 0:a.displayName,currentUserEmail:a==null?void 0:a.email})]}),o&&k&&e.jsx(o0,{kpis:k,upcomingDeadlines:ae,criticalRequests:_,departmentStats:W,dateRange:d,customStartDate:m,customEndDate:u,exportingDeptStats:be,onKPIClick:Ss,onExportDepartmentStats:Ve}),!o&&k&&e.jsx(l0,{kpis:k}),o&&Z.length>0&&e.jsx(c0,{priorityDistribution:Z,onNavigate:t}),o&&Ue.length>0&&e.jsx(d0,{breachedRequests:Ue,pagination:C,dateRange:d,customStartDate:m,customEndDate:u,onPageChange:Hs,onKPIClick:Ss,onNavigate:t}),$e.length>0&&e.jsx(m0,{isAdmin:o,upcomingDeadlines:$e,pagination:R,onPageChange:Da,onNavigate:t}),o&&$&&e.jsx(u0,{aiRemarkUtilization:$}),o&&ne.length>0&&e.jsx(h0,{approverPerformance:ne,pagination:I,dateRange:d,customStartDate:m,customEndDate:u,loading:me,exportingApproverPerformance:Ie,onPageChange:Pa,onExport:Oe,onNavigate:t})]})}function xn(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const s=Math.random()*16|0;return(t==="x"?s:s&3|8).toString(16)})}async function Hd(t){var l;const s=t.priorityUi.toUpperCase()==="EXPRESS"?"EXPRESS":"STANDARD",a=Array.from({length:t.approverCount||1},(c,d)=>{const m=d,u=t.approvers[m]||{},h=m+1,x=u.tat??"";let p=0;typeof x=="number"&&(p=u.tatType==="days"?x*24:x);const y=u.email||"",v=u.name&&u.name.trim()||y.split("@")[0]||`Approver ${h}`;return{levelNumber:h,levelName:`Level ${h}`,approverId:xn(),approverEmail:y,approverName:v,tatHours:p>0?p:24,isFinalApprover:h===(t.approverCount||1)}}),r=[...(t.spectators||[]).map(c=>({userId:xn(),userEmail:c.email,userName:c.name||c.email.split("@")[0]||"Spectator",participantType:"SPECTATOR",canComment:!0,canViewDocuments:!0,canDownloadDocuments:!1,notificationEnabled:!0})),...(t.ccList||[]).map(c=>({userId:xn(),userEmail:c.email,userName:c.name||c.email.split("@")[0]||"CC",participantType:"CONSULTATION",canComment:!1,canViewDocuments:!0,canDownloadDocuments:!1,notificationEnabled:!0}))],n={templateType:t.templateType,title:t.title,description:t.description,priority:s,approvalLevels:a,participants:r.length?r:void 0},i=await ie.post("/workflows",n),o=((l=i.data)==null?void 0:l.data)||i.data;return{id:o.id||o.workflowId||""}}async function Oi(t,s,a="SUPPORTING"){var d;const r=m=>typeof m=="string"&&/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/.test(m.trim()),n={templateType:t.templateType,title:t.title,description:t.description,priority:t.priorityUi.toUpperCase()==="EXPRESS"?"EXPRESS":"STANDARD",approvalLevels:Array.from({length:t.approverCount||1},(m,u)=>{const h=t.approvers[u]||{},x=typeof h.tat=="number"?h.tat:0,p=(h.userId||"").trim();if(!r(p))throw new Error(`Invalid approverId for level ${u+1}. Please pick an approver via @ search.`);return{levelNumber:u+1,levelName:`Level ${u+1}`,approverId:p,approverEmail:h.email||"",approverName:h.name||(h.email?h.email.split("@")[0]:`Approver ${u+1}`),tatHours:h.tatType==="days"?x*24:x||24,isFinalApprover:u+1===(t.approverCount||1)}})},i=t.participants;Array.isArray(i)&&i.length&&(n.participants=i);const o=new FormData;o.append("payload",JSON.stringify(n)),o.append("category",a),s.forEach(m=>o.append("files",m));const l=await ie.post("/workflows/multipart",o,{headers:{"Content-Type":"multipart/form-data"}}),c=((d=l.data)==null?void 0:d.data)||l.data;return{id:c==null?void 0:c.requestId}}async function qd(t={}){var p;const{page:s=1,limit:a=20,search:r,status:n,priority:i,department:o,initiator:l,approver:c,slaCompliance:d,dateRange:m,startDate:u,endDate:h}=t,x=await ie.get("/workflows",{params:{page:s,limit:a,search:r,status:n,priority:i,department:o,initiator:l,approver:c,slaCompliance:d,dateRange:m,startDate:u,endDate:h}});return((p=x.data)==null?void 0:p.data)||x.data}async function Wd(t={}){var y,v,N,f,b;const{page:s=1,limit:a=20,search:r,status:n,priority:i,department:o,initiator:l,approver:c,approverType:d,slaCompliance:m,dateRange:u,startDate:h,endDate:x}=t,p=await ie.get("/workflows/participant-requests",{params:{page:s,limit:a,search:r,status:n,priority:i,department:o,initiator:l,approver:c,approverType:d,slaCompliance:m,dateRange:u,startDate:h,endDate:x}});return{data:((v=(y=p.data)==null?void 0:y.data)==null?void 0:v.data)||((N=p.data)==null?void 0:N.data)||[],pagination:((b=(f=p.data)==null?void 0:f.data)==null?void 0:b.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Kd(t={}){var p,y,v,N,f;const{page:s=1,limit:a=20,search:r,status:n,priority:i,department:o,initiator:l,approver:c,slaCompliance:d,dateRange:m,startDate:u,endDate:h}=t,x=await ie.get("/workflows/my",{params:{page:s,limit:a,search:r,status:n,priority:i,department:o,initiator:l,approver:c,slaCompliance:d,dateRange:m,startDate:u,endDate:h}});return{data:((y=(p=x.data)==null?void 0:p.data)==null?void 0:y.data)||((v=x.data)==null?void 0:v.data)||[],pagination:((f=(N=x.data)==null?void 0:N.data)==null?void 0:f.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Gd(t={}){var h,x,p,y,v;const{page:s=1,limit:a=20,search:r,status:n,priority:i,department:o,slaCompliance:l,dateRange:c,startDate:d,endDate:m}=t,u=await ie.get("/workflows/my-initiated",{params:{page:s,limit:a,search:r,status:n,priority:i,department:o,slaCompliance:l,dateRange:c,startDate:d,endDate:m}});return{data:((x=(h=u.data)==null?void 0:h.data)==null?void 0:x.data)||((p=u.data)==null?void 0:p.data)||[],pagination:((v=(y=u.data)==null?void 0:y.data)==null?void 0:v.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Yd(t={}){var d,m,u,h,x;const{page:s=1,limit:a=20,search:r,status:n,priority:i,sortBy:o,sortOrder:l}=t,c=await ie.get("/workflows/open-for-me",{params:{page:s,limit:a,search:r,status:n,priority:i,sortBy:o,sortOrder:l}});return{data:((m=(d=c.data)==null?void 0:d.data)==null?void 0:m.data)||((u=c.data)==null?void 0:u.data)||[],pagination:((x=(h=c.data)==null?void 0:h.data)==null?void 0:x.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Zd(t={}){var d,m,u,h,x;const{page:s=1,limit:a=20,search:r,status:n,priority:i,sortBy:o,sortOrder:l}=t,c=await ie.get("/workflows/closed-by-me",{params:{page:s,limit:a,search:r,status:n,priority:i,sortBy:o,sortOrder:l}});return{data:((m=(d=c.data)==null?void 0:d.data)==null?void 0:m.data)||((u=c.data)==null?void 0:u.data)||[],pagination:((x=(h=c.data)==null?void 0:h.data)==null?void 0:x.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Rs(t){var a;const s=await ie.get(`/workflows/${t}/details`);return((a=s.data)==null?void 0:a.data)||s.data}async function aa(t){var a;const s=await ie.get(`/workflows/${t}/work-notes`);return((a=s.data)==null?void 0:a.data)||s.data}async function $i(t,s,a=[]){var i;const r=new FormData;r.append("payload",JSON.stringify(s||{})),a.forEach(o=>r.append("files",o));const n=await ie.post(`/workflows/${t}/work-notes`,r,{headers:{"Content-Type":"multipart/form-data"}});return((i=n.data)==null?void 0:i.data)||n.data}async function Ui(t,s,a,r){var i;const n=await ie.post(`/workflows/${t}/approvers/at-level`,{email:s,tatHours:a,level:r});return((i=n.data)==null?void 0:i.data)||n.data}async function Xd(t,s,a){var n;const r=await ie.post(`/workflows/${t}/approvals/${s}/skip`,{reason:a});return((n=r.data)==null?void 0:n.data)||r.data}async function Vi(t,s){var r;const a=await ie.post(`/workflows/${t}/participants/spectator`,{email:s});return((r=a.data)==null?void 0:r.data)||a.data}async function Qd(t,s,a,r){var i;const n=await ie.post(`/workflows/${t}/pause`,{levelId:s,reason:a,resumeDate:r.toISOString()});return((i=n.data)==null?void 0:i.data)||n.data}async function Jd(t){var a;const s=await ie.post(`/workflows/${t}/resume`);return((a=s.data)==null?void 0:a.data)||s.data}async function em(t){var a;const s=await ie.post(`/workflows/${t}/pause/retrigger`);return((a=s.data)==null?void 0:a.data)||s.data}async function g0(t){var a;const s=await ie.get(`/workflows/${t}/pause`);return((a=s.data)==null?void 0:a.data)||s.data}function tm(t){return`https://re-workflow-nt-dev.siplsolutions.com/api/v1/workflows/work-notes/attachments/${t}/preview`}function Bi(t){return`https://re-workflow-nt-dev.siplsolutions.com/api/v1/workflows/documents/${t}/preview`}async function Tr(t){var n;const a=`https://re-workflow-nt-dev.siplsolutions.com/api/v1/workflows/documents/${t}/download`,r=!0;try{const o=await fetch(a,{credentials:"include"});if(!o.ok){const x=await o.text();throw new Error(`Download failed: ${o.status} - ${x}`)}const l=await o.blob(),c=window.URL.createObjectURL(l),d=o.headers.get("Content-Disposition"),u=((n=d==null?void 0:d.split("filename=")[1])==null?void 0:n.replace(/"/g,""))||"download",h=document.createElement("a");h.href=c,h.download=u,document.body.appendChild(h),h.click(),document.body.removeChild(h),window.URL.revokeObjectURL(c)}catch(i){throw console.error("[Download] Failed:",i),i}}async function Qn(t){var n;const a=`https://re-workflow-nt-dev.siplsolutions.com/api/v1/workflows/work-notes/attachments/${t}/download`,r=!0;try{const o=await fetch(a,{credentials:"include"});if(!o.ok){const x=await o.text();throw new Error(`Download failed: ${o.status} - ${x}`)}const l=await o.blob(),c=window.URL.createObjectURL(l),d=o.headers.get("Content-Disposition"),u=((n=d==null?void 0:d.split("filename=")[1])==null?void 0:n.replace(/"/g,""))||"download",h=document.createElement("a");h.href=c,h.download=u,document.body.appendChild(h),h.click(),document.body.removeChild(h),window.URL.revokeObjectURL(c)}catch(i){throw console.error("[Download] Failed:",i),i}}const It={createWorkflowFromForm:Hd,createWorkflowMultipart:Oi,listWorkflows:qd,listParticipantRequests:Wd,listMyWorkflows:Kd,listMyInitiatedWorkflows:Gd,listOpenForMe:Yd,listClosedByMe:Zd,submitWorkflow:zi,getWorkflowDetails:Rs,getWorkNotes:aa,createWorkNoteMultipart:$i};async function zi(t){var a;const s=await ie.patch(`/workflows/${t}/submit`);return((a=s.data)==null?void 0:a.data)||s.data}async function sm(t,s){var r;const a=await ie.put(`/workflows/${t}`,s);return((r=a.data)==null?void 0:r.data)||a.data}async function am(t,s,a,r){var l;const n={...s,deleteDocumentIds:r||[]},i=new FormData;i.append("payload",JSON.stringify(n)),i.append("category","SUPPORTING"),a&&a.length>0&&a.forEach(c=>i.append("files",c));const o=await ie.put(`/workflows/${t}/multipart`,i,{headers:{"Content-Type":"multipart/form-data"}});return((l=o.data)==null?void 0:l.data)||o.data}async function rm(t,s,a){var n;const r=await ie.patch(`/workflows/${t}/approvals/${s}/approve`,{action:"APPROVE",comments:a||""});return((n=r.data)==null?void 0:n.data)||r.data}async function nm(t,s,a,r){var i;const n=await ie.patch(`/workflows/${t}/approvals/${s}/reject`,{action:"REJECT",rejectionReason:a||"",comments:r||""});return((i=n.data)==null?void 0:i.data)||n.data}async function im(t,s){const a=await ie.put(`/tat/breach-reason/${t}`,{breachReason:s});if(!a.data.success)throw new Error(a.data.error||"Failed to update breach reason")}const f0=Object.freeze(Object.defineProperty({__proto__:null,addApproverAtLevel:Ui,addSpectator:Vi,approveLevel:rm,createWorkNoteMultipart:$i,createWorkflowFromForm:Hd,createWorkflowMultipart:Oi,default:It,downloadDocument:Tr,downloadWorkNoteAttachment:Qn,getDocumentPreviewUrl:Bi,getPauseDetails:g0,getWorkNoteAttachmentPreviewUrl:tm,getWorkNotes:aa,getWorkflowDetails:Rs,listClosedByMe:Zd,listMyInitiatedWorkflows:Gd,listMyWorkflows:Kd,listOpenForMe:Yd,listParticipantRequests:Wd,listWorkflows:qd,pauseWorkflow:Qd,rejectLevel:nm,resumeWorkflow:Jd,retriggerPause:em,skipApprover:Xd,submitWorkflow:zi,updateBreachReason:im,updateWorkflow:sm,updateWorkflowMultipart:am},Symbol.toStringTag,{value:"Module"}));function Ot(t,s){if(!t)return"N/A";try{const a=typeof t=="string"?new Date(t):t;if(isNaN(a.getTime()))return"Invalid Date";const{includeTime:r=!0,includeSeconds:n=!1,format:i="medium"}=s||{};return r?a.toLocaleString("en-US",{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",...n&&{second:"2-digit"},hour12:!0}):a.toLocaleDateString("en-US",{year:"numeric",month:i==="short"?"short":"long",day:"numeric"})}catch(a){return console.error("Error formatting date:",a),String(t)}}function om(t){return Ot(t,{includeTime:!1,format:"short"})}function ps(t,s=!1){if(!t)return"N/A";try{const a=typeof t=="string"?new Date(t):t;if(isNaN(a.getTime()))return"Invalid Date";const r=String(a.getDate()).padStart(2,"0"),i=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][a.getMonth()],o=a.getFullYear();if(s){const l=a.getHours(),c=l%12||12,d=String(a.getMinutes()).padStart(2,"0"),m=String(a.getSeconds()).padStart(2,"0"),u=l>=12?"PM":"AM";return`${r} ${i} ${o}, ${c}:${d}:${m} ${u}`}return`${r} ${i} ${o}`}catch(a){return console.error("Error formatting date:",a),String(t)}}const y0=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:ls,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:it,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:it,iconColor:"text-gray-600"}}},v0=t=>{switch(t){case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:De,iconColor:"text-yellow-600",label:"Pending"};case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:Re,iconColor:"text-green-600",label:"Needs Closure"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ze,iconColor:"text-red-600",label:"Rejected"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:ve,iconColor:"text-gray-600",label:"Closed"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Re,iconColor:"text-gray-600",label:t}}};function b0({onViewRequest:t}){const[s]=Hr(),[a,r]=g.useState(s.get("search")||""),[n,i]=g.useState(s.get("priority")||"all"),[o,l]=g.useState(s.get("status")||"all"),[c,d]=g.useState(s.get("sortBy")||"created"),[m,u]=g.useState(s.get("sortOrder")||"desc"),[h,x]=g.useState([]),[p,y]=g.useState(!1),[v,N]=g.useState(!1),[f,b]=g.useState(1),[j,C]=g.useState(1),[R,I]=g.useState(0),[T]=g.useState(10),E=g.useCallback(async(k=1,P)=>{try{k===1&&(y(!0),x([]));const _=await It.listOpenForMe({page:k,limit:T,search:P==null?void 0:P.search,status:P==null?void 0:P.status,priority:P==null?void 0:P.priority,sortBy:P==null?void 0:P.sortBy,sortOrder:P==null?void 0:P.sortOrder}),W=Array.isArray(_==null?void 0:_.data)?_.data:[],Z=_==null?void 0:_.pagination;Z&&(b(Z.page||1),C(Z.totalPages||1),I(Z.total||0));const ae=W.map($=>{var me,q,z,re;const ne=$.submittedAt||$.submitted_at||$.createdAt||$.created_at;return{id:$.requestNumber||$.request_number||$.requestId,requestId:$.requestId,displayId:$.requestNumber||$.request_number||$.requestId,title:$.title,description:$.description,status:($.status||"").toString().toLowerCase().replace("_","-"),priority:($.priority||"").toString().toLowerCase(),initiator:{name:((me=$.initiator)==null?void 0:me.displayName)||((q=$.initiator)==null?void 0:q.email)||"—",avatar:(((z=$.initiator)==null?void 0:z.displayName)||((re=$.initiator)==null?void 0:re.email)||"NA").split(" ").map(K=>K[0]).join("").slice(0,2).toUpperCase()},currentApprover:$.currentApprover?{name:$.currentApprover.name||$.currentApprover.email||"—",avatar:($.currentApprover.name||$.currentApprover.email||"CA").split(" ").map(K=>K[0]).join("").slice(0,2).toUpperCase(),sla:$.currentApprover.sla}:void 0,createdAt:ne||"—",approvalStep:$.currentLevel?`Step ${$.currentLevel} of ${$.totalLevels||"?"}`:void 0,department:$.department,currentLevelSLA:$.currentLevelSLA}});x(ae)}finally{y(!1),N(!1)}},[T]),w=()=>{N(!0),E(f,{search:a||void 0,status:o!=="all"?o:void 0,priority:n!=="all"?n:void 0,sortBy:c,sortOrder:m})},S=k=>{k>=1&&k<=j&&(b(k),E(k,{search:a||void 0,status:o!=="all"?o:void 0,priority:n!=="all"?n:void 0,sortBy:c,sortOrder:m}))},D=()=>{const k=[];let _=Math.max(1,f-Math.floor(2.5)),W=Math.min(j,_+5-1);W-_<4&&(_=Math.max(1,W-5+1));for(let Z=_;Z<=W;Z++)k.push(Z);return k},H=g.useRef(!0);g.useEffect(()=>{H.current&&(H.current=!1,E(1,{search:a||void 0,status:o!=="all"?o:void 0,priority:n!=="all"?n:void 0,sortBy:c,sortOrder:m}))},[]),g.useEffect(()=>{if(H.current)return;const k=setTimeout(()=>{b(1),E(1,{search:a||void 0,status:o!=="all"?o:void 0,priority:n!=="all"?n:void 0,sortBy:c,sortOrder:m})},a?500:0);return()=>clearTimeout(k)},[a,o,n,c,m,E]);const L=h,F=()=>{r(""),i("all"),l("all")},A=[a,n!=="all"?n:null,o!=="all"?o:null].filter(Boolean).length;return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto",children:[e.jsxs("div",{className:"flex flex-col lg:flex-row lg:items-center justify-between gap-3 sm:gap-4 md:gap-6",children:[e.jsx("div",{className:"space-y-1 sm:space-y-2",children:e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("div",{className:"w-10 h-10 sm:w-12 sm:h-12 bg-gradient-to-br from-slate-800 to-slate-900 rounded-xl flex items-center justify-center shadow-lg",children:e.jsx(Te,{className:"w-5 h-5 sm:w-6 sm:h-6 text-white"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl sm:text-2xl md:text-3xl font-bold text-gray-900",children:"My Open Requests"}),e.jsx("p",{className:"text-sm sm:text-base text-gray-600",children:"Manage and track your active approval requests"})]})]})}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsxs(Q,{variant:"secondary",className:"text-xs sm:text-sm md:text-base px-2 sm:px-3 md:px-4 py-1 sm:py-1.5 md:py-2 bg-slate-100 text-slate-800 font-semibold",children:[p?"Loading…":`${R||h.length} open`,e.jsx("span",{className:"hidden sm:inline ml-1",children:"requests"})]}),e.jsxs(M,{variant:"outline",size:"sm",className:"gap-1 sm:gap-2 h-8 sm:h-9",onClick:w,disabled:v,children:[e.jsx(Lt,{className:`w-3.5 h-3.5 sm:w-4 sm:h-4 ${v?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:v?"Refreshing...":"Refresh"})]})]})]}),e.jsxs(G,{className:"shadow-lg border-0",children:[e.jsx(te,{className:"pb-3 sm:pb-4 px-3 sm:px-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("div",{className:"p-1.5 sm:p-2 bg-blue-100 rounded-lg",children:e.jsx(Qa,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(se,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(he,{className:"text-xs sm:text-sm",children:A>0&&e.jsxs("span",{className:"text-blue-600 font-medium",children:[A," filter",A>1?"s":""," active"]})})]})]}),A>0&&e.jsxs(M,{variant:"ghost",size:"sm",onClick:F,className:"text-red-600 hover:bg-red-50 gap-1 h-8 sm:h-9 px-2 sm:px-3",children:[e.jsx(ft,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Clear"})]})]})}),e.jsx(Y,{className:"space-y-3 sm:space-y-4 px-3 sm:px-6",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Yt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx(xe,{placeholder:"Search requests, IDs...",value:a,onChange:k=>r(k.target.value),className:"pl-9 sm:pl-10 h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200 transition-colors"})]}),e.jsxs(we,{value:n,onValueChange:i,children:[e.jsx(Se,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ce,{placeholder:"All Priorities"})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"all",children:"All Priorities"}),e.jsx(V,{value:"express",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ls,{className:"w-4 h-4 text-orange-600"}),e.jsx("span",{children:"Express"})]})}),e.jsx(V,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(it,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(we,{value:o,onValueChange:l,children:[e.jsx(Se,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ce,{placeholder:"All Statuses"})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"all",children:"All Statuses"}),e.jsx(V,{value:"pending",children:"Pending (In Approval)"}),e.jsx(V,{value:"approved",children:"Approved (Needs Closure)"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(we,{value:c,onValueChange:k=>d(k),children:[e.jsx(Se,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ce,{placeholder:"Sort by"})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"due",children:"Due Date"}),e.jsx(V,{value:"created",children:"Date Created"}),e.jsx(V,{value:"priority",children:"Priority"}),e.jsx(V,{value:"sla",children:"SLA Progress"})]})]}),e.jsx(M,{variant:"outline",size:"sm",onClick:()=>u(m==="asc"?"desc":"asc"),className:"px-2 sm:px-3 h-9 sm:h-10 md:h-11",children:m==="asc"?e.jsx(ud,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(hd,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]}),e.jsx("div",{className:"space-y-3",children:L.map(k=>{const P=y0(k.priority),_=v0(k.status);return e.jsx(G,{className:"group hover:shadow-lg transition-all duration-200 cursor-pointer border border-gray-200 hover:border-blue-400 hover:scale-[1.002]",onClick:()=>t==null?void 0:t(k.id,k.title),children:e.jsx(Y,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex-shrink-0 pt-1",children:e.jsx("div",{className:`p-2.5 rounded-lg ${P.color} border shadow-sm`,children:e.jsx(P.icon,{className:`w-5 h-5 ${P.iconColor}`})})}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-2.5",children:[e.jsxs("div",{className:"flex items-center gap-2.5 flex-wrap",children:[e.jsx("h3",{className:"text-base font-bold text-gray-900 group-hover:text-blue-600 transition-colors",children:k.displayId||k.id}),e.jsxs(Q,{variant:"outline",className:`${_.color} text-xs px-2.5 py-0.5 font-semibold shrink-0`,children:[e.jsx(_.icon,{className:"w-3.5 h-3.5 mr-1"}),_.label||k.status]}),k.department&&e.jsx(Q,{variant:"secondary",className:"bg-blue-50 text-blue-700 text-xs px-2.5 py-0.5 hidden sm:inline-flex",children:k.department}),e.jsx(Q,{variant:"outline",className:`${P.color} text-xs px-2.5 py-0.5 capitalize hidden md:inline-flex`,children:k.priority})]}),e.jsx("h4",{className:"text-sm font-semibold text-gray-800 line-clamp-1 leading-relaxed",children:k.title}),k.currentLevelSLA&&e.jsxs("div",{className:`p-2 rounded-md ${k.currentLevelSLA.status==="breached"?"bg-red-50 border border-red-200":k.currentLevelSLA.status==="critical"?"bg-orange-50 border border-orange-200":k.currentLevelSLA.status==="approaching"?"bg-yellow-50 border border-yellow-200":"bg-green-50 border border-green-200"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(De,{className:"w-3.5 h-3.5 text-gray-600"}),e.jsxs("span",{className:"text-xs font-medium text-gray-900",children:["TAT: ",k.currentLevelSLA.percentageUsed,"%"]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"text-gray-600",children:k.currentLevelSLA.elapsedText}),e.jsxs("span",{className:`font-semibold ${k.currentLevelSLA.status==="breached"?"text-red-600":k.currentLevelSLA.status==="critical"?"text-orange-600":"text-gray-700"}`,children:[k.currentLevelSLA.remainingText," left"]})]})]}),e.jsx(hs,{value:k.currentLevelSLA.percentageUsed,className:`h-1.5 ${k.currentLevelSLA.status==="breached"?"[&>div]:bg-red-600":k.currentLevelSLA.status==="critical"?"[&>div]:bg-orange-600":k.currentLevelSLA.status==="approaching"?"[&>div]:bg-yellow-600":"[&>div]:bg-green-600"}`})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-xs text-gray-600",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(jt,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(Nt,{className:"bg-gradient-to-br from-slate-700 to-slate-900 text-white text-[10px] font-bold",children:k.initiator.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:k.initiator.name})]}),k.currentApprover&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(jt,{className:"h-6 w-6 ring-2 ring-yellow-200 shadow-sm",children:e.jsx(Nt,{className:"bg-yellow-500 text-white text-[10px] font-bold",children:k.currentApprover.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:k.currentApprover.name})]}),k.approvalStep&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Re,{className:"w-3.5 h-3.5 text-blue-500"}),e.jsx("span",{className:"font-medium",children:k.approvalStep})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(qe,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",k.createdAt!=="—"?ps(k.createdAt):"—"]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(wt,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})},k.id)})}),L.length===0&&e.jsx(G,{className:"shadow-lg border-0",children:e.jsxs(Y,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx("div",{className:"w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mb-4",children:e.jsx(Te,{className:"h-8 w-8 text-gray-400"})}),e.jsx("h3",{className:"text-xl font-semibold text-gray-900 mb-2",children:"No requests found"}),e.jsx("p",{className:"text-gray-600 text-center max-w-md",children:a||A>0?"Try adjusting your filters or search terms to see more results.":"No open requests available at the moment."}),A>0&&e.jsx(M,{variant:"outline",className:"mt-4",onClick:F,children:"Clear all filters"})]})}),j>1&&!p&&e.jsx(G,{className:"shadow-md",children:e.jsx(Y,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-between gap-3",children:[e.jsxs("div",{className:"text-xs sm:text-sm text-muted-foreground",children:["Showing ",(f-1)*T+1," to ",Math.min(f*T,R)," of ",R," open requests"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(M,{variant:"outline",size:"sm",onClick:()=>S(f-1),disabled:f===1,className:"h-8 w-8 p-0",children:e.jsx(wt,{className:"h-4 w-4 rotate-180"})}),f>3&&j>5&&e.jsxs(e.Fragment,{children:[e.jsx(M,{variant:"outline",size:"sm",onClick:()=>S(1),className:"h-8 w-8 p-0",children:"1"}),e.jsx("span",{className:"text-muted-foreground",children:"..."})]}),D().map(k=>e.jsx(M,{variant:k===f?"default":"outline",size:"sm",onClick:()=>S(k),className:`h-8 w-8 p-0 ${k===f?"bg-re-green text-white hover:bg-re-green/90":""}`,children:k},k)),f5&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"..."}),e.jsx(M,{variant:"outline",size:"sm",onClick:()=>S(j),className:"h-8 w-8 p-0",children:j})]}),e.jsx(M,{variant:"outline",size:"sm",onClick:()=>S(f+1),disabled:f===j,className:"h-8 w-8 p-0",children:e.jsx(wt,{className:"h-4 w-4"})})]})]})})})]})}function j0({totalRecords:t,loading:s,refreshing:a,onRefresh:r}){return e.jsxs("div",{className:"flex flex-col lg:flex-row lg:items-center justify-between gap-3 sm:gap-4 md:gap-6","data-testid":"closed-requests-header",children:[e.jsx("div",{className:"space-y-1 sm:space-y-2",children:e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("div",{className:"w-10 h-10 sm:w-12 sm:h-12 bg-gradient-to-br from-slate-800 to-slate-900 rounded-xl flex items-center justify-center shadow-lg",children:e.jsx(Te,{className:"w-5 h-5 sm:w-6 sm:h-6 text-white"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl sm:text-2xl md:text-3xl font-bold text-gray-900",children:"My Closed Requests"}),e.jsx("p",{className:"text-sm sm:text-base text-gray-600",children:"Review your completed and archived requests"})]})]})}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsxs(Q,{variant:"secondary",className:"text-xs sm:text-sm md:text-base px-2 sm:px-3 md:px-4 py-1 sm:py-1.5 md:py-2 bg-slate-100 text-slate-800 font-semibold","data-testid":"closed-requests-count",children:[s?"Loading…":`${t} closed`,e.jsx("span",{className:"hidden sm:inline ml-1",children:"requests"})]}),e.jsxs(M,{variant:"outline",size:"sm",className:"gap-1 sm:gap-2 h-8 sm:h-9",onClick:r,disabled:a,"data-testid":"closed-requests-refresh",children:[e.jsx(Lt,{className:`w-3.5 h-3.5 sm:w-4 sm:h-4 ${a?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:a?"Refreshing...":"Refresh"})]})]})]})}function N0({searchTerm:t,priorityFilter:s,statusFilter:a,sortBy:r,sortOrder:n,activeFiltersCount:i,onSearchChange:o,onPriorityChange:l,onStatusChange:c,onSortByChange:d,onSortOrderChange:m,onClearFilters:u}){return e.jsxs(G,{className:"shadow-lg border-0","data-testid":"closed-requests-filters",children:[e.jsx(te,{className:"pb-3 sm:pb-4 px-3 sm:px-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("div",{className:"p-1.5 sm:p-2 bg-blue-100 rounded-lg",children:e.jsx(Qa,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(se,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(he,{className:"text-xs sm:text-sm",children:i>0&&e.jsxs("span",{className:"text-blue-600 font-medium",children:[i," filter",i>1?"s":""," active"]})})]})]}),i>0&&e.jsxs(M,{variant:"ghost",size:"sm",onClick:u,className:"text-red-600 hover:bg-red-50 gap-1 h-8 sm:h-9 px-2 sm:px-3","data-testid":"closed-requests-clear-filters",children:[e.jsx(ft,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Clear"})]})]})}),e.jsx(Y,{className:"space-y-3 sm:space-y-4 px-3 sm:px-6",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Yt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx(xe,{placeholder:"Search requests, IDs...",value:t,onChange:h=>o(h.target.value),className:"pl-9 sm:pl-10 h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white transition-colors","data-testid":"closed-requests-search"})]}),e.jsxs(we,{value:s,onValueChange:l,children:[e.jsx(Se,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white","data-testid":"closed-requests-priority-filter",children:e.jsx(Ce,{placeholder:"All Priorities"})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"all",children:"All Priorities"}),e.jsx(V,{value:"express",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ls,{className:"w-4 h-4 text-orange-600"}),e.jsx("span",{children:"Express"})]})}),e.jsx(V,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(it,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(we,{value:a,onValueChange:c,children:[e.jsx(Se,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white","data-testid":"closed-requests-status-filter",children:e.jsx(Ce,{placeholder:"All Statuses"})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"all",children:"All Statuses"}),e.jsx(V,{value:"closed",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ve,{className:"w-4 h-4 text-gray-600"}),e.jsx("span",{children:"Closed"})]})}),e.jsx(V,{value:"rejected",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ze,{className:"w-4 h-4 text-red-600"}),e.jsx("span",{children:"Rejected"})]})})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(we,{value:r,onValueChange:h=>d(h),children:[e.jsx(Se,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white","data-testid":"closed-requests-sort-by",children:e.jsx(Ce,{placeholder:"Sort by"})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"due",children:"Due Date"}),e.jsx(V,{value:"created",children:"Date Created"}),e.jsx(V,{value:"priority",children:"Priority"})]})]}),e.jsx(M,{variant:"outline",size:"sm",onClick:m,className:"px-2 sm:px-3 h-9 sm:h-10 md:h-11","data-testid":"closed-requests-sort-order",children:n==="asc"?e.jsx(ud,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(hd,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function w0(t){switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:ls,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:it,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:it,iconColor:"text-gray-600"}}}function C0(t){switch(t){case"closed":return{color:"bg-slate-100 text-slate-800 border-slate-300",icon:ve,iconColor:"text-slate-600",label:"Closed",description:"Request finalized and archived"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-300",icon:Ze,iconColor:"text-red-600",label:"Rejected",description:"Request was declined"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Re,iconColor:"text-gray-600",label:t,description:""}}}function S0({request:t,onViewRequest:s}){const a=w0(t.priority),r=C0(t.status),n=a.icon,i=r.icon;return e.jsx(G,{className:"group hover:shadow-lg transition-all duration-200 cursor-pointer border border-gray-200 hover:border-blue-400 hover:scale-[1.002]",onClick:()=>s==null?void 0:s(t.id,t.title),"data-testid":`closed-request-card-${t.id}`,children:e.jsx(Y,{className:"p-5",children:e.jsxs("div",{className:"flex items-start gap-5",children:[e.jsx("div",{className:"flex-shrink-0 pt-1",children:e.jsx("div",{className:`p-2.5 rounded-lg ${a.color} border shadow-sm`,children:e.jsx(n,{className:`w-5 h-5 ${a.iconColor}`})})}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2.5 flex-wrap",children:[e.jsx("h3",{className:"text-base font-bold text-gray-900 group-hover:text-blue-600 transition-colors",children:t.displayId||t.id}),e.jsxs(Q,{variant:"outline",className:`${r.color} text-xs px-2.5 py-0.5 font-semibold shrink-0`,children:[e.jsx(i,{className:"w-3.5 h-3.5 mr-1"}),r.label]}),t.department&&e.jsx(Q,{variant:"secondary",className:"bg-blue-50 text-blue-700 text-xs px-2.5 py-0.5 hidden sm:inline-flex",children:t.department}),e.jsx(Q,{variant:"outline",className:`${a.color} text-xs px-2.5 py-0.5 capitalize hidden md:inline-flex`,children:t.priority})]}),e.jsx("h4",{className:"text-sm font-semibold text-gray-800 line-clamp-1 leading-relaxed",children:t.title}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-xs text-gray-600",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(jt,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(Nt,{className:"bg-gradient-to-br from-slate-700 to-slate-900 text-white text-[10px] font-bold",children:t.initiator.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:t.initiator.name})]}),(t.totalLevels??0)>0&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ve,{className:"w-3.5 h-3.5 text-green-600"}),e.jsxs("span",{className:"font-medium",children:[t.completedLevels||0,"/",t.totalLevels," Approvals"]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(qe,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",t.createdAt!=="—"?ps(t.createdAt,!0):"—"]})]}),t.dueDate&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ve,{className:"w-3.5 h-3.5 text-slate-600"}),e.jsxs("span",{className:"font-medium",children:["Closed: ",ps(t.dueDate,!0)]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(wt,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})})}function A0({requests:t,loading:s,onViewRequest:a}){return s&&t.length===0?e.jsx("div",{className:"space-y-4","data-testid":"closed-requests-list-loading",children:[...Array(3)].map((r,n)=>e.jsx("div",{className:"h-32 bg-gray-100 animate-pulse rounded-lg"},n))}):t.length===0?null:e.jsx("div",{className:"space-y-4","data-testid":"closed-requests-list",children:t.map(r=>e.jsx(S0,{request:r,onViewRequest:a},r.id))})}function T0({searchTerm:t,activeFiltersCount:s,onClearFilters:a}){return e.jsx(G,{className:"shadow-lg border-0","data-testid":"closed-requests-empty",children:e.jsxs(Y,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx("div",{className:"w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mb-4",children:e.jsx(Te,{className:"h-8 w-8 text-gray-400"})}),e.jsx("h3",{className:"text-xl font-semibold text-gray-900 mb-2",children:"No requests found"}),e.jsx("p",{className:"text-gray-600 text-center max-w-md",children:t||s>0?"Try adjusting your filters or search terms to see more results.":"No closed requests available at the moment."}),s>0&&e.jsx(M,{variant:"outline",className:"mt-4",onClick:a,"data-testid":"closed-requests-empty-clear-filters",children:"Clear all filters"})]})})}function k0(t,s){const a=[];let n=Math.max(1,t-Math.floor(2.5)),i=Math.min(s,n+5-1);i-n<4&&(n=Math.max(1,i-5+1));for(let o=n;o<=i;o++)a.push(o);return a}function R0({pagination:t,onPageChange:s}){const{currentPage:a,totalPages:r,totalRecords:n,itemsPerPage:i}=t;if(r<=1)return null;const o=k0(a,r);return e.jsx(G,{className:"shadow-md","data-testid":"closed-requests-pagination",children:e.jsx(Y,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-between gap-3",children:[e.jsxs("div",{className:"text-xs sm:text-sm text-muted-foreground",children:["Showing ",(a-1)*i+1," to ",Math.min(a*i,n)," of ",n," closed requests"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(M,{variant:"outline",size:"sm",onClick:()=>s(a-1),disabled:a===1,className:"h-8 w-8 p-0","data-testid":"closed-requests-pagination-prev",children:e.jsx(wt,{className:"h-4 w-4 rotate-180"})}),a>3&&r>5&&e.jsxs(e.Fragment,{children:[e.jsx(M,{variant:"outline",size:"sm",onClick:()=>s(1),className:"h-8 w-8 p-0","data-testid":"closed-requests-pagination-first",children:"1"}),e.jsx("span",{className:"text-muted-foreground",children:"..."})]}),o.map(l=>e.jsx(M,{variant:l===a?"default":"outline",size:"sm",onClick:()=>s(l),className:`h-8 w-8 p-0 ${l===a?"bg-re-green text-white hover:bg-re-green/90":""}`,"data-testid":`closed-requests-pagination-page-${l}`,children:l},l)),a5&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"..."}),e.jsx(M,{variant:"outline",size:"sm",onClick:()=>s(r),className:"h-8 w-8 p-0","data-testid":"closed-requests-pagination-last",children:r})]}),e.jsx(M,{variant:"outline",size:"sm",onClick:()=>s(a+1),disabled:a===r,className:"h-8 w-8 p-0","data-testid":"closed-requests-pagination-next",children:e.jsx(wt,{className:"h-4 w-4"})})]})]})})})}function D0(t){var s,a,r,n;return{id:t.requestNumber||t.request_number||t.requestId,requestId:t.requestId,displayId:t.requestNumber||t.request_number||t.requestId,title:t.title,description:t.description,status:(t.status||"").toString().toLowerCase(),priority:(t.priority||"").toString().toLowerCase(),initiator:{name:((s=t.initiator)==null?void 0:s.displayName)||((a=t.initiator)==null?void 0:a.email)||"—",avatar:(((r=t.initiator)==null?void 0:r.displayName)||"NA").split(" ").map(i=>i[0]).join("").slice(0,2).toUpperCase()},createdAt:t.submittedAt||t.createdAt||t.created_at||"—",dueDate:t.closureDate||t.closure_date||t.closedAt||void 0,reason:t.conclusionRemark||t.conclusion_remark,department:t.department,totalLevels:t.totalLevels||0,completedLevels:((n=t.summary)==null?void 0:n.approvedLevels)||0}}function P0(t){return t.map(D0)}function E0({itemsPerPage:t=10,initialFilters:s}={}){const[a,r]=g.useState([]),[n,i]=g.useState(!1),[o,l]=g.useState(!1),[c,d]=g.useState({currentPage:1,totalPages:1,totalRecords:0,itemsPerPage:t}),m=g.useRef(!0),u=g.useCallback(async(x=1,p)=>{try{x===1&&(i(!0),r([]));let y=p==null?void 0:p.status;if(y==="approved"){r([]),d({currentPage:1,totalPages:1,totalRecords:0,itemsPerPage:t}),i(!1),l(!1);return}const v=await It.listClosedByMe({page:x,limit:t,search:p==null?void 0:p.search,status:y&&y!=="all"?y:void 0,priority:p==null?void 0:p.priority,sortBy:p==null?void 0:p.sortBy,sortOrder:p==null?void 0:p.sortOrder}),N=Array.isArray(v==null?void 0:v.data)?v.data:[],b=P0(N).filter(C=>C.status==="rejected"||C.status==="closed");r(b);const j=v==null?void 0:v.pagination;j&&d({currentPage:j.page||1,totalPages:j.totalPages||1,totalRecords:j.total||0,itemsPerPage:t})}catch(y){console.error("[ClosedRequests] Error fetching requests:",y),r([])}finally{i(!1),l(!1)}},[t]);g.useEffect(()=>{m.current&&(u(1,s),m.current=!1)},[]);const h=g.useCallback(x=>{l(!0),u(c.currentPage,x)},[u,c.currentPage]);return{requests:a,loading:n,refreshing:o,pagination:c,fetchRequests:u,handleRefresh:h}}function M0({onFiltersChange:t,debounceMs:s=500}={}){const[a,r]=g.useState(""),[n,i]=g.useState("all"),[o,l]=g.useState("all"),[c,d]=g.useState("due"),[m,u]=g.useState("desc"),h=g.useRef(null),x=g.useRef(!0),p=g.useCallback(()=>({search:a,status:o,priority:n,sortBy:c,sortOrder:m}),[a,o,n,c,m]);g.useEffect(()=>{if(x.current){x.current=!1;return}h.current&&clearTimeout(h.current);const N=setTimeout(()=>{t&&t(p())},a?s:0);return h.current=N,()=>{h.current&&clearTimeout(h.current)}},[a,o,n,c,m,t,p,s]);const y=g.useCallback(()=>{r(""),i("all"),l("all")},[]),v=[a,n!=="all"?n:null,o!=="all"?o:null].filter(Boolean).length;return{searchTerm:a,priorityFilter:n,statusFilter:o,sortBy:c,sortOrder:m,setSearchTerm:r,setPriorityFilter:i,setStatusFilter:l,setSortBy:d,setSortOrder:u,clearFilters:y,activeFiltersCount:v,getFilters:p}}function I0({onViewRequest:t}){const s=E0({itemsPerPage:10}),a=g.useRef(s.fetchRequests);a.current=s.fetchRequests;const r=M0({onFiltersChange:g.useCallback(o=>{a.current(1,{search:o.search||void 0,status:o.status!=="all"?o.status:void 0,priority:o.priority!=="all"?o.priority:void 0,sortBy:o.sortBy,sortOrder:o.sortOrder})},[])}),n=g.useCallback(o=>{o>=1&&o<=s.pagination.totalPages&&s.fetchRequests(o,{search:r.searchTerm||void 0,status:r.statusFilter!=="all"?r.statusFilter:void 0,priority:r.priorityFilter!=="all"?r.priorityFilter:void 0,sortBy:r.sortBy,sortOrder:r.sortOrder})},[s,r]),i=g.useCallback(()=>{s.handleRefresh({search:r.searchTerm||void 0,status:r.statusFilter!=="all"?r.statusFilter:void 0,priority:r.priorityFilter!=="all"?r.priorityFilter:void 0,sortBy:r.sortBy,sortOrder:r.sortOrder})},[s,r]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"closed-requests-page",children:[e.jsx(j0,{totalRecords:s.pagination.totalRecords,loading:s.loading,refreshing:s.refreshing,onRefresh:i}),e.jsx(N0,{searchTerm:r.searchTerm,priorityFilter:r.priorityFilter,statusFilter:r.statusFilter,sortBy:r.sortBy,sortOrder:r.sortOrder,activeFiltersCount:r.activeFiltersCount,onSearchChange:r.setSearchTerm,onPriorityChange:r.setPriorityFilter,onStatusChange:r.setStatusFilter,onSortByChange:r.setSortBy,onSortOrderChange:()=>r.setSortOrder(r.sortOrder==="asc"?"desc":"asc"),onClearFilters:r.clearFilters}),e.jsx(A0,{requests:s.requests,loading:s.loading,onViewRequest:t}),s.requests.length===0&&!s.loading&&e.jsx(T0,{searchTerm:r.searchTerm,activeFiltersCount:r.activeFiltersCount,onClearFilters:r.clearFilters}),!s.loading&&e.jsx(R0,{pagination:s.pagination,onPageChange:n})]})}function Kr({className:t,...s}){return e.jsx(cp,{"data-slot":"tabs",className:oe("flex flex-col gap-2",t),...s})}function Gr({className:t,...s}){return e.jsx(dp,{"data-slot":"tabs-list",className:oe("bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-xl p-[3px] flex",t),...s})}function pt({className:t,...s}){return e.jsx(mp,{"data-slot":"tabs-trigger",className:oe("data-[state=active]:bg-card dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-xl border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...s})}function xt({className:t,...s}){return e.jsx(up,{"data-slot":"tabs-content",className:oe("flex-1 outline-none",t),...s})}const _0="modulepreload",L0=function(t){return"/"+t},cl={},yr=function(s,a,r){let n=Promise.resolve();if(a&&a.length>0){document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),l=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));n=Promise.allSettled(a.map(c=>{if(c=L0(c),c in cl)return;cl[c]=!0;const d=c.endsWith(".css"),m=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${m}`))return;const u=document.createElement("link");if(u.rel=d?"stylesheet":_0,d||(u.as="script"),u.crossOrigin="",u.href=c,l&&u.setAttribute("nonce",l),document.head.appendChild(u),d)return new Promise((h,x)=>{u.addEventListener("load",h),u.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${c}`)))})}))}function i(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return n.then(o=>{for(const l of o||[])l.status==="rejected"&&i(l.reason);return s().catch(i)})},lm={"RE-REQ-2024-001":{id:"RE-REQ-2024-001",title:"Himalayan 450 Launch Campaign - Digital Media Blitz",description:`Comprehensive digital marketing campaign for Himalayan 450 adventure motorcycle launch. Includes social media campaigns, influencer partnerships, performance marketing, content creation, and digital advertising across platforms. Target: Reach 10M adventure enthusiasts across India. Equipment Specifications: • 10x MacBook Pro 16-inch (M2 Pro chip) • 5x Professional Camera Kits (Canon EOS R5) • Video Editing Workstations • Social Media Management Tools`,category:"Marketing & Campaigns",subcategory:"Digital Marketing",status:"pending",priority:"express",amount:"₹3,75,00,000",slaProgress:65,slaRemaining:"8 hours 45 minutes",slaEndDate:"Oct 9, 2024 5:00 PM",currentStep:1,totalSteps:3,template:"custom",initiator:{name:"Priya Sharma",role:"Senior Digital Marketing Manager",department:"Marketing",email:"priya.sharma@royalenfield.com",phone:"+91 98765 43210",avatar:"PS"},department:"Marketing",createdAt:"Oct 6, 2024 10:30 AM",updatedAt:"Oct 7, 2024 2:15 PM",dueDate:"2024-10-09T17:00:00Z",conclusionRemark:"",approvalFlow:[{step:1,approver:"Rajesh Kumar",role:"Marketing Director - India",status:"pending",tatHours:24,elapsedHours:22,assignedAt:"2024-10-06T10:30:00Z",comment:null,timestamp:null},{step:2,approver:"Amit Desai",role:"VP Product Marketing",status:"waiting",tatHours:48,elapsedHours:0,assignedAt:null,comment:null,timestamp:null},{step:3,approver:"Deepika Sharma",role:"VP Sales & Marketing",status:"waiting",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null}],documents:[{name:"Himalayan_450_Digital_Strategy.pdf",size:"5.2 MB",type:"PDF",uploadedBy:"Priya Sharma",uploadedAt:"Oct 6, 2024 10:45 AM"},{name:"Budget_Breakdown_Q4_2024.xlsx",size:"980 KB",type:"Excel",uploadedBy:"Priya Sharma",uploadedAt:"Oct 6, 2024 11:15 AM"},{name:"Influencer_Partnership_List.xlsx",size:"450 KB",type:"Excel",uploadedBy:"Marketing Team",uploadedAt:"Oct 6, 2024 2:30 PM"},{name:"Creative_Campaign_Assets.zip",size:"125 MB",type:"ZIP",uploadedBy:"Creative Team",uploadedAt:"Oct 6, 2024 4:15 PM"}],spectators:[{name:"Sarah Khan",role:"Brand Strategy Lead",avatar:"SK"},{name:"Finance Team",role:"Budget Approval",avatar:"FT"}],auditTrail:[{type:"created",action:"Request Created",details:"New digital marketing campaign request submitted",user:"Priya Sharma",timestamp:"Oct 6, 2024 10:30 AM"},{type:"assignment",action:"Assigned to Rajesh Kumar",details:"Forwarded to Marketing Director for review",user:"System",timestamp:"Oct 6, 2024 10:31 AM"},{type:"comment",action:"Work Note Added",details:"Reviewed budget allocation and target metrics",user:"Rajesh Kumar",timestamp:"Oct 7, 2024 2:15 PM"},{type:"reminder",action:"SLA Reminder",details:"TAT approaching - 8 hours remaining",user:"System",timestamp:"Oct 7, 2024 8:15 AM"}],tags:["digital-marketing","launch-campaign","himalayan-450","high-priority"]},"RE-REQ-2024-002":{id:"RE-REQ-2024-002",title:"New Laptop Procurement - Design Team Expansion",description:"Purchase of 10 high-performance laptops for the newly expanded Product Design team. Required specifications: Latest generation processor, 32GB RAM, dedicated graphics card for 3D modeling and rendering work.",category:"IT & Infrastructure",subcategory:"Hardware Procurement",status:"in-review",priority:"standard",amount:"₹12,50,000",slaProgress:45,slaRemaining:"2 days 8 hours",slaEndDate:"Oct 11, 2024 5:00 PM",currentStep:2,totalSteps:3,template:"custom",initiator:{name:"Vikram Singh",role:"Head - IT Operations",department:"Information Technology",email:"vikram.singh@royalenfield.com",phone:"+91 98765 43221",avatar:"VS"},department:"Information Technology",createdAt:"Oct 5, 2024 9:15 AM",updatedAt:"Oct 7, 2024 3:45 PM",dueDate:"2024-10-11T17:00:00Z",conclusionRemark:"",approvalFlow:[{step:1,approver:"Meera Patel",role:"IT Manager",status:"approved",tatHours:24,actualHours:18,assignedAt:"2024-10-05T09:15:00Z",comment:"Technical specifications verified. Hardware meets design team requirements.",timestamp:"2024-10-06T03:15:00Z"},{step:2,approver:"Anil Kapoor",role:"Finance Manager",status:"in-review",tatHours:48,elapsedHours:32,assignedAt:"2024-10-06T03:15:00Z",comment:null,timestamp:null},{step:3,approver:"Ramesh Kulkarni",role:"VP Operations",status:"waiting",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null}],documents:[{name:"Laptop_Specifications.pdf",size:"850 KB",type:"PDF",uploadedBy:"Vikram Singh",uploadedAt:"Oct 5, 2024 9:20 AM"},{name:"Vendor_Quotations.xlsx",size:"1.2 MB",type:"Excel",uploadedBy:"Procurement Team",uploadedAt:"Oct 5, 2024 11:45 AM"},{name:"Team_Expansion_Plan.pdf",size:"620 KB",type:"PDF",uploadedBy:"Design Team",uploadedAt:"Oct 5, 2024 2:30 PM"}],spectators:[{name:"Design Team Lead",role:"End Users",avatar:"DT"},{name:"Procurement Team",role:"Vendor Management",avatar:"PT"}],auditTrail:[{type:"created",action:"Request Created",details:"Laptop procurement request for design team",user:"Vikram Singh",timestamp:"Oct 5, 2024 9:15 AM"},{type:"assignment",action:"Assigned to Meera Patel",details:"IT Manager to verify specifications",user:"System",timestamp:"Oct 5, 2024 9:16 AM"},{type:"approval",action:"Approved by Meera Patel",details:"Technical specifications approved",user:"Meera Patel",timestamp:"Oct 6, 2024 3:15 AM"},{type:"assignment",action:"Assigned to Anil Kapoor",details:"Forwarded to Finance for budget approval",user:"System",timestamp:"Oct 6, 2024 3:15 AM"}],tags:["hardware","procurement","design-team","laptops"]},"RE-REQ-2024-003":{id:"RE-REQ-2024-003",title:"Annual Service Center Expansion - Western Region",description:"Proposal for opening 15 new authorized service centers across tier-2 cities in Western region. Includes infrastructure setup, technician training, spare parts inventory, and marketing support. Expected to improve service accessibility by 35% in the target region.",category:"Operations & Expansion",subcategory:"Service Network",status:"pending",priority:"standard",amount:"₹8,75,00,000",slaProgress:78,slaRemaining:"1 day 4 hours",slaEndDate:"Oct 10, 2024 5:00 PM",currentStep:1,totalSteps:4,template:"custom",initiator:{name:"Sanjay Reddy",role:"Regional Service Manager - West",department:"After Sales Service",email:"sanjay.reddy@royalenfield.com",phone:"+91 98765 43232",avatar:"SR"},department:"After Sales Service",createdAt:"Oct 3, 2024 8:45 AM",updatedAt:"Oct 6, 2024 5:45 PM",dueDate:"2024-10-10T17:00:00Z",conclusionRemark:"",approvalFlow:[{step:1,approver:"Ramesh Kulkarni",role:"Head - After Sales Service",status:"pending",tatHours:72,elapsedHours:85,assignedAt:"2024-10-03T08:45:00Z",comment:null,timestamp:null},{step:2,approver:"Finance Team",role:"Budget Allocation",status:"waiting",tatHours:96,elapsedHours:0,assignedAt:null,comment:null,timestamp:null},{step:3,approver:"Legal Team",role:"Compliance Review",status:"waiting",tatHours:120,elapsedHours:0,assignedAt:null,comment:null,timestamp:null},{step:4,approver:"Deepika Sharma",role:"VP Sales & Marketing",status:"waiting",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null}],documents:[{name:"Western_Region_Expansion_Plan.pdf",size:"7.5 MB",type:"PDF",uploadedBy:"Sanjay Reddy",uploadedAt:"Oct 3, 2024 9:00 AM"},{name:"Service_Center_Requirements.xlsx",size:"2.8 MB",type:"Excel",uploadedBy:"Planning Team",uploadedAt:"Oct 3, 2024 11:30 AM"},{name:"Customer_Demand_Analysis.pptx",size:"4.2 MB",type:"PowerPoint",uploadedBy:"Analytics Team",uploadedAt:"Oct 4, 2024 2:15 PM"},{name:"ROI_Projections_Service_Network.xlsx",size:"1.9 MB",type:"Excel",uploadedBy:"Finance Team",uploadedAt:"Oct 5, 2024 10:45 AM"}],spectators:[{name:"Regional Managers",role:"Service Operations",avatar:"RM"},{name:"Training Team",role:"Technician Development",avatar:"TT"}],auditTrail:[{type:"created",action:"Request Created",details:"Service center expansion proposal submitted",user:"Sanjay Reddy",timestamp:"Oct 3, 2024 8:45 AM"},{type:"assignment",action:"Assigned to Ramesh Kulkarni",details:"Forwarded to Head of After Sales Service",user:"System",timestamp:"Oct 3, 2024 8:46 AM"},{type:"reminder",action:"Reminder Sent",details:"TAT breach reminder sent to approver",user:"System",timestamp:"Oct 6, 2024 5:45 PM"},{type:"updated",action:"Additional Documents",details:"ROI projections added by finance team",user:"Finance Team",timestamp:"Oct 5, 2024 10:45 AM"}],tags:["service-expansion","western-region","tier2-cities","overdue"]},"RE-REQ-2024-004":{id:"RE-REQ-2024-004",title:"Employee Training Program - Advanced Motorcycle Mechanics",description:"Comprehensive training program for 50 service center technicians covering advanced diagnostics, electrical systems, fuel injection troubleshooting, and customer service excellence. Program duration: 3 weeks. Includes certification upon completion.",category:"Human Resources",subcategory:"Training & Development",status:"approved",priority:"standard",amount:"₹18,50,000",slaProgress:100,slaRemaining:"Completed",slaEndDate:"Oct 5, 2024 5:00 PM",currentStep:3,totalSteps:3,template:"custom",initiator:{name:"Kavita Menon",role:"Training Manager",department:"Human Resources",email:"kavita.menon@royalenfield.com",phone:"+91 98765 43243",avatar:"KM"},department:"Human Resources",createdAt:"Sep 28, 2024 11:00 AM",updatedAt:"Oct 5, 2024 4:30 PM",dueDate:"2024-10-05T17:00:00Z",submittedDate:"2024-09-28T11:00:00Z",estimatedCompletion:"Oct 5, 2024",currentApprover:"Completed",approverLevel:"3 of 3",conclusionRemark:"All approvals completed. Training program scheduled for November 2024.",approvalFlow:[{step:1,approver:"Ramesh Kulkarni",role:"Head - After Sales Service",status:"approved",tatHours:48,actualHours:36,assignedAt:"2024-09-28T11:00:00Z",comment:"Excellent initiative. Training content approved.",timestamp:"Sep 29, 2024 11:00 PM"},{step:2,approver:"Anil Kapoor",role:"Finance Manager",status:"approved",tatHours:72,actualHours:48,assignedAt:"2024-09-29T23:00:00Z",comment:"Budget approved. Cost per participant is reasonable.",timestamp:"Oct 1, 2024 11:00 PM"},{step:3,approver:"Deepika Sharma",role:"VP Sales & Marketing",status:"approved",tatHours:96,actualHours:72,assignedAt:"2024-10-01T23:00:00Z",comment:"Final approval granted. Proceed with program execution.",timestamp:"Oct 5, 2024 4:30 PM"}],documents:[{name:"Training_Curriculum.pdf",size:"3.2 MB",type:"PDF",uploadedBy:"Kavita Menon",uploadedAt:"Sep 28, 2024 11:15 AM"},{name:"Trainer_Profiles.pdf",size:"1.8 MB",type:"PDF",uploadedBy:"HR Team",uploadedAt:"Sep 28, 2024 2:45 PM"},{name:"Budget_Training_Program.xlsx",size:"680 KB",type:"Excel",uploadedBy:"Finance Team",uploadedAt:"Sep 29, 2024 10:30 AM"}],spectators:[{name:"Service Center Managers",role:"Participant Coordination",avatar:"SC"},{name:"Quality Assurance",role:"Training Quality",avatar:"QA"}],auditTrail:[{type:"created",action:"Request Created",details:"Training program proposal submitted",user:"Kavita Menon",timestamp:"Sep 28, 2024 11:00 AM"},{type:"assignment",action:"Assigned to Ramesh Kulkarni",details:"Forwarded to After Sales Service Head",user:"System",timestamp:"Sep 28, 2024 11:01 AM"},{type:"approval",action:"Approved by Ramesh Kulkarni",details:"Level 1 approval completed",user:"Ramesh Kulkarni",timestamp:"Sep 29, 2024 11:00 PM"},{type:"assignment",action:"Assigned to Anil Kapoor",details:"Forwarded to Finance Manager",user:"System",timestamp:"Sep 29, 2024 11:01 PM"},{type:"approval",action:"Approved by Anil Kapoor",details:"Budget approval completed",user:"Anil Kapoor",timestamp:"Oct 1, 2024 11:00 PM"},{type:"assignment",action:"Assigned to Deepika Sharma",details:"Forwarded to VP for final approval",user:"System",timestamp:"Oct 1, 2024 11:01 PM"},{type:"approval",action:"Approved by Deepika Sharma",details:"Final approval - Request completed",user:"Deepika Sharma",timestamp:"Oct 5, 2024 4:30 PM"},{type:"completed",action:"Request Completed",details:"All approvals obtained. Training scheduled.",user:"System",timestamp:"Oct 5, 2024 4:31 PM"}],tags:["training","technicians","approved","completed"]},"RE-REQ-2024-005":{id:"RE-REQ-2024-005",title:"Showroom Renovation - Chennai Flagship Store",description:"Complete renovation of Chennai flagship showroom including modern interior design, interactive display zones, customer lounge upgrade, motorcycle test ride facility, and digital experience center. Project timeline: 8 weeks.",category:"Infrastructure",subcategory:"Retail & Showroom",status:"rejected",priority:"standard",amount:"₹65,00,000",slaProgress:100,slaRemaining:"Rejected",slaEndDate:"Oct 4, 2024 5:00 PM",currentStep:2,totalSteps:4,template:"custom",initiator:{name:"Arjun Nair",role:"Showroom Manager - South",department:"Retail Operations",email:"arjun.nair@royalenfield.com",phone:"+91 98765 43254",avatar:"AN"},department:"Retail Operations",createdAt:"Oct 1, 2024 9:30 AM",updatedAt:"Oct 4, 2024 3:15 PM",dueDate:"2024-10-04T17:00:00Z",submittedDate:"2024-10-01T09:30:00Z",estimatedCompletion:"N/A",currentApprover:"Rejected by Anil Kapoor",approverLevel:"2 of 4",conclusionRemark:"Request rejected due to insufficient budget justification. Please revise with detailed ROI analysis.",approvalFlow:[{step:1,approver:"Suresh Iyer",role:"Regional Manager - South",status:"approved",tatHours:48,actualHours:24,assignedAt:"2024-10-01T09:30:00Z",comment:"Renovation is necessary. Current showroom needs upgrade.",timestamp:"Oct 2, 2024 9:30 AM"},{step:2,approver:"Anil Kapoor",role:"Finance Manager",status:"rejected",tatHours:72,actualHours:48,assignedAt:"2024-10-02T09:30:00Z",comment:"Budget allocation not justified. Need detailed ROI analysis and comparison with alternative renovation options. Please revise and resubmit with comprehensive financial projections.",timestamp:"Oct 4, 2024 3:15 PM"},{step:3,approver:"Legal Team",role:"Compliance & Contracts",status:"cancelled",tatHours:96,elapsedHours:0,assignedAt:null,comment:null,timestamp:null},{step:4,approver:"Ramesh Kulkarni",role:"VP Operations",status:"cancelled",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null}],documents:[{name:"Showroom_Renovation_Plan.pdf",size:"12.5 MB",type:"PDF",uploadedBy:"Arjun Nair",uploadedAt:"Oct 1, 2024 9:45 AM"},{name:"Interior_Design_Mockups.zip",size:"85 MB",type:"ZIP",uploadedBy:"Design Team",uploadedAt:"Oct 1, 2024 2:30 PM"},{name:"Contractor_Quotations.xlsx",size:"2.1 MB",type:"Excel",uploadedBy:"Procurement Team",uploadedAt:"Oct 2, 2024 11:15 AM"}],spectators:[{name:"Marketing Team",role:"Brand Experience",avatar:"MT"},{name:"Customer Experience",role:"Feedback & Analysis",avatar:"CX"}],auditTrail:[{type:"created",action:"Request Created",details:"Showroom renovation request submitted",user:"Arjun Nair",timestamp:"Oct 1, 2024 9:30 AM"},{type:"assignment",action:"Assigned to Suresh Iyer",details:"Forwarded to Regional Manager",user:"System",timestamp:"Oct 1, 2024 9:31 AM"},{type:"approval",action:"Approved by Suresh Iyer",details:"Level 1 approval completed",user:"Suresh Iyer",timestamp:"Oct 2, 2024 9:30 AM"},{type:"assignment",action:"Assigned to Anil Kapoor",details:"Forwarded to Finance Manager",user:"System",timestamp:"Oct 2, 2024 9:31 AM"},{type:"rejection",action:"Rejected by Anil Kapoor",details:"Budget justification insufficient",user:"Anil Kapoor",timestamp:"Oct 4, 2024 3:15 PM"},{type:"completed",action:"Request Rejected",details:"Workflow terminated. Requires resubmission with revisions.",user:"System",timestamp:"Oct 4, 2024 3:16 PM"}],tags:["showroom","renovation","rejected","south-region"]},"RE-REQ-2024-006":{id:"RE-REQ-2024-006",title:"Spare Parts Inventory Optimization System",description:"Implementation of AI-powered inventory management system for spare parts across all service centers. Features include demand forecasting, automated reordering, stock level optimization, and real-time tracking. Expected to reduce inventory costs by 20% and improve part availability.",category:"Technology & Innovation",subcategory:"Software Implementation",status:"pending",priority:"express",amount:"₹42,00,000",slaProgress:35,slaRemaining:"1 day 16 hours",slaEndDate:"Oct 12, 2024 5:00 PM",currentStep:1,totalSteps:4,template:"custom",initiator:{name:"Rahul Deshmukh",role:"Head - Supply Chain Technology",department:"Supply Chain",email:"rahul.deshmukh@royalenfield.com",phone:"+91 98765 43265",avatar:"RD"},department:"Supply Chain",createdAt:"Oct 7, 2024 10:00 AM",updatedAt:"Oct 8, 2024 9:15 AM",dueDate:"2024-10-12T17:00:00Z",submittedDate:"2024-10-07T10:00:00Z",estimatedCompletion:"Oct 12, 2024",currentApprover:"Vikram Singh",approverLevel:"1 of 4",conclusionRemark:"",approvalFlow:[{step:1,approver:"Vikram Singh",role:"Head - IT Operations",status:"pending",tatHours:48,elapsedHours:23,assignedAt:"2024-10-07T10:00:00Z",comment:null,timestamp:null},{step:2,approver:"Supply Chain Director",role:"Operations Approval",status:"waiting",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null},{step:3,approver:"Anil Kapoor",role:"Finance Manager",status:"waiting",tatHours:96,elapsedHours:0,assignedAt:null,comment:null,timestamp:null},{step:4,approver:"Ramesh Kulkarni",role:"VP Operations",status:"waiting",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null}],documents:[{name:"AI_Inventory_System_Proposal.pdf",size:"8.9 MB",type:"PDF",uploadedBy:"Rahul Deshmukh",uploadedAt:"Oct 7, 2024 10:15 AM"},{name:"Vendor_Comparison_Analysis.xlsx",size:"3.4 MB",type:"Excel",uploadedBy:"IT Procurement",uploadedAt:"Oct 7, 2024 2:45 PM"},{name:"Cost_Benefit_Analysis.pptx",size:"6.2 MB",type:"PowerPoint",uploadedBy:"Analytics Team",uploadedAt:"Oct 7, 2024 4:30 PM"},{name:"Implementation_Timeline.pdf",size:"1.5 MB",type:"PDF",uploadedBy:"Project Management",uploadedAt:"Oct 8, 2024 9:15 AM"}],spectators:[{name:"Service Center Network",role:"End Users",avatar:"SN"},{name:"Data Analytics Team",role:"System Integration",avatar:"DA"}],auditTrail:[{type:"created",action:"Request Created",details:"AI inventory system proposal submitted",user:"Rahul Deshmukh",timestamp:"Oct 7, 2024 10:00 AM"},{type:"assignment",action:"Assigned to Vikram Singh",details:"Forwarded to IT Operations Head",user:"System",timestamp:"Oct 7, 2024 10:01 AM"},{type:"updated",action:"Documents Added",details:"Implementation timeline document uploaded",user:"Project Management",timestamp:"Oct 8, 2024 9:15 AM"}],tags:["technology","ai","inventory","supply-chain","high-priority"]},"RE-REQ-2024-007":{id:"RE-REQ-2024-007",title:"Dealer Network Meeting - Q4 Business Review",description:"Quarterly business review meeting for all authorized dealers across India. Venue: Bangalore. Topics include Q3 performance review, Q4 targets, new model launches, marketing initiatives, service excellence programs, and dealer support policies. Expected attendance: 250 dealers.",category:"Events & Conferences",subcategory:"Dealer Meetings",status:"in-review",priority:"standard",amount:"₹28,50,000",slaProgress:58,slaRemaining:"1 day 12 hours",slaEndDate:"Oct 11, 2024 5:00 PM",currentStep:2,totalSteps:3,template:"custom",initiator:{name:"Neha Kapoor",role:"Dealer Network Manager",department:"Sales & Distribution",email:"neha.kapoor@royalenfield.com",phone:"+91 98765 43276",avatar:"NK"},department:"Sales & Distribution",createdAt:"Oct 6, 2024 2:00 PM",updatedAt:"Oct 8, 2024 11:30 AM",dueDate:"2024-10-11T17:00:00Z",submittedDate:"2024-10-06T14:00:00Z",estimatedCompletion:"Oct 11, 2024",currentApprover:"Anil Kapoor",approverLevel:"2 of 3",conclusionRemark:"",approvalFlow:[{step:1,approver:"Suresh Mehta",role:"Sales Director",status:"approved",tatHours:48,actualHours:36,assignedAt:"2024-10-06T14:00:00Z",comment:"Dealer meeting approved. Agenda looks comprehensive.",timestamp:"Oct 8, 2024 2:00 AM"},{step:2,approver:"Anil Kapoor",role:"Finance Manager",status:"in-review",tatHours:72,elapsedHours:33,assignedAt:"2024-10-08T02:00:00Z",comment:null,timestamp:null},{step:3,approver:"Deepika Sharma",role:"VP Sales & Marketing",status:"waiting",tatHours:48,elapsedHours:0,assignedAt:null,comment:null,timestamp:null}],documents:[{name:"Q4_Dealer_Meeting_Agenda.pdf",size:"2.8 MB",type:"PDF",uploadedBy:"Neha Kapoor",uploadedAt:"Oct 6, 2024 2:15 PM"},{name:"Venue_Booking_Confirmation.pdf",size:"980 KB",type:"PDF",uploadedBy:"Events Team",uploadedAt:"Oct 6, 2024 4:45 PM"},{name:"Event_Budget_Breakdown.xlsx",size:"1.2 MB",type:"Excel",uploadedBy:"Finance Team",uploadedAt:"Oct 7, 2024 10:30 AM"},{name:"Dealer_Invitations_List.xlsx",size:"580 KB",type:"Excel",uploadedBy:"Sales Team",uploadedAt:"Oct 7, 2024 3:15 PM"}],spectators:[{name:"Marketing Team",role:"Presentation Support",avatar:"MT"},{name:"Events Management",role:"Logistics Coordination",avatar:"EM"}],auditTrail:[{type:"created",action:"Request Created",details:"Dealer meeting proposal submitted",user:"Neha Kapoor",timestamp:"Oct 6, 2024 2:00 PM"},{type:"assignment",action:"Assigned to Suresh Mehta",details:"Forwarded to Sales Director",user:"System",timestamp:"Oct 6, 2024 2:01 PM"},{type:"approval",action:"Approved by Suresh Mehta",details:"Sales approval completed",user:"Suresh Mehta",timestamp:"Oct 8, 2024 2:00 AM"},{type:"assignment",action:"Assigned to Anil Kapoor",details:"Forwarded to Finance Manager",user:"System",timestamp:"Oct 8, 2024 2:01 AM"},{type:"updated",action:"Documents Added",details:"Dealer invitations list uploaded",user:"Sales Team",timestamp:"Oct 7, 2024 3:15 PM"}],tags:["dealer-meeting","q4-review","event","bangalore"]},"RE-REQ-2024-008":{id:"RE-REQ-2024-008",title:"Cybersecurity Infrastructure Upgrade",description:"Comprehensive upgrade of cybersecurity infrastructure including next-gen firewall, intrusion detection system, endpoint protection for 500+ devices, security information and event management (SIEM) system, and employee security awareness training. Critical for protecting customer data and business operations.",category:"IT & Infrastructure",subcategory:"Security & Compliance",status:"pending",priority:"urgent",amount:"₹52,00,000",slaProgress:82,slaRemaining:"4 hours 20 minutes",slaEndDate:"Oct 8, 2024 6:00 PM",currentStep:2,totalSteps:3,template:"custom",initiator:{name:"Sameer Joshi",role:"Chief Information Security Officer",department:"Information Technology",email:"sameer.joshi@royalenfield.com",phone:"+91 98765 43287",avatar:"SJ"},department:"Information Technology",createdAt:"Oct 5, 2024 11:30 AM",updatedAt:"Oct 8, 2024 12:45 PM",dueDate:"2024-10-08T18:00:00Z",submittedDate:"2024-10-05T11:30:00Z",estimatedCompletion:"Oct 8, 2024",currentApprover:"Anil Kapoor",approverLevel:"2 of 3",conclusionRemark:"",approvalFlow:[{step:1,approver:"Vikram Singh",role:"Head - IT Operations",status:"approved",tatHours:24,actualHours:18,assignedAt:"2024-10-05T11:30:00Z",comment:"Critical security upgrade. Approve immediately.",timestamp:"Oct 6, 2024 5:30 AM"},{step:2,approver:"Anil Kapoor",role:"Finance Manager",status:"pending",tatHours:48,elapsedHours:55,assignedAt:"2024-10-06T05:30:00Z",comment:null,timestamp:null},{step:3,approver:"Ramesh Kulkarni",role:"VP Operations",status:"waiting",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null}],documents:[{name:"Security_Assessment_Report.pdf",size:"15.3 MB",type:"PDF",uploadedBy:"Sameer Joshi",uploadedAt:"Oct 5, 2024 11:45 AM"},{name:"Vendor_Solutions_Comparison.xlsx",size:"4.8 MB",type:"Excel",uploadedBy:"IT Security Team",uploadedAt:"Oct 5, 2024 3:30 PM"},{name:"Implementation_Roadmap.pptx",size:"7.6 MB",type:"PowerPoint",uploadedBy:"Project Management",uploadedAt:"Oct 6, 2024 10:15 AM"},{name:"Risk_Analysis_Report.pdf",size:"5.9 MB",type:"PDF",uploadedBy:"Security Consultant",uploadedAt:"Oct 6, 2024 4:45 PM"}],spectators:[{name:"Legal & Compliance",role:"Data Protection",avatar:"LC"},{name:"IT Infrastructure",role:"System Integration",avatar:"IT"}],auditTrail:[{type:"created",action:"Request Created",details:"Cybersecurity upgrade proposal submitted",user:"Sameer Joshi",timestamp:"Oct 5, 2024 11:30 AM"},{type:"assignment",action:"Assigned to Vikram Singh",details:"Forwarded to IT Operations Head",user:"System",timestamp:"Oct 5, 2024 11:31 AM"},{type:"approval",action:"Approved by Vikram Singh",details:"IT approval - marked as critical",user:"Vikram Singh",timestamp:"Oct 6, 2024 5:30 AM"},{type:"assignment",action:"Assigned to Anil Kapoor",details:"Forwarded to Finance Manager",user:"System",timestamp:"Oct 6, 2024 5:31 AM"},{type:"reminder",action:"Urgent Reminder",details:"TAT breach warning - 4 hours remaining",user:"System",timestamp:"Oct 8, 2024 12:45 PM"}],tags:["cybersecurity","urgent","critical","infrastructure","overdue"]}},F0={"RE-REQ-2024-CM-001":{id:"RE-REQ-2024-CM-001",title:"Dealer Marketing Activity Claim - Diwali Festival Campaign",description:"Claim request for dealer-led Diwali festival marketing campaign including showroom decoration, test ride events, customer engagement activities, and promotional merchandise distribution. Activity conducted at Royal Motors Mumbai dealership.",category:"Dealer Operations",subcategory:"Claim Management",status:"pending",priority:"standard",amount:"TBD",slaProgress:35,slaRemaining:"4 days 12 hours",slaEndDate:"Oct 16, 2024 5:00 PM",currentStep:1,totalSteps:8,template:"claim-management",templateName:"Claim Management",initiator:{name:"Sneha Patil",role:"Regional Marketing Coordinator",department:"Marketing - West Zone",email:"sneha.patil@royalenfield.com",phone:"+91 98765 43250",avatar:"SP"},department:"Marketing - West Zone",createdAt:"Oct 7, 2024 9:30 AM",updatedAt:"Oct 7, 2024 9:30 AM",dueDate:"2024-10-16T17:00:00Z",conclusionRemark:"",claimDetails:{activityName:"Diwali Festival Campaign 2024",activityType:"Marketing Activity",activityDate:"Oct 5, 2024",location:"Mumbai, Maharashtra",dealerCode:"RE-MH-001",dealerName:"Royal Motors Mumbai",dealerEmail:"dealer@royalmotorsmumbai.com",dealerPhone:"+91 98765 12345",dealerAddress:"123 Main Street, Andheri West, Mumbai, Maharashtra 400053",requestDescription:"Marketing campaign for Diwali festival including showroom decoration, test ride events, customer engagement activities, and promotional merchandise distribution at Royal Motors Mumbai dealership.",estimatedBudget:"₹2,45,000",periodStart:"Oct 1, 2024",periodEnd:"Oct 10, 2024"},approvalFlow:[{step:1,approver:"Royal Motors Mumbai (Dealer)",role:"Dealer - Document Upload",status:"pending",tatHours:72,elapsedHours:12,assignedAt:"2024-10-07T09:30:00Z",comment:null,timestamp:null,description:"Dealer uploads proposal document, cost breakup, timeline for closure, and other supporting documents"},{step:2,approver:"Sneha Patil (Initiator)",role:"Initiator Evaluation",status:"waiting",tatHours:48,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Initiator reviews dealer documents and approves or requests modifications"},{step:3,approver:"System Auto-Process",role:"IO Confirmation",status:"waiting",tatHours:1,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Automatic IO (Internal Order) confirmation generated upon initiator approval"},{step:4,approver:"Rajesh Kumar",role:"Department Lead Approval",status:"waiting",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Department head approves and blocks budget in IO for this activity"},{step:5,approver:"Royal Motors Mumbai (Dealer)",role:"Dealer - Completion Documents",status:"waiting",tatHours:120,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Dealer submits activity completion documents and description"},{step:6,approver:"Sneha Patil (Initiator)",role:"Initiator Verification",status:"waiting",tatHours:48,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Initiator verifies completion documents and can modify approved amount"},{step:7,approver:"System Auto-Process",role:"E-Invoice Generation",status:"waiting",tatHours:1,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Auto-generate e-invoice based on final approved amount"},{step:8,approver:"Meera Patel",role:"Finance - Credit Note Issuance",status:"waiting",tatHours:48,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Finance team issues credit note to dealer"}],documents:[{name:"Claim_Proposal_Diwali_2024.pdf",size:"1.8 MB",type:"PDF",uploadedBy:"Sneha Patil",uploadedAt:"Oct 7, 2024 9:35 AM"},{name:"Cost_Breakup_Detailed.xlsx",size:"450 KB",type:"Excel",uploadedBy:"Sneha Patil",uploadedAt:"Oct 7, 2024 9:38 AM"},{name:"Activity_Timeline.pdf",size:"320 KB",type:"PDF",uploadedBy:"Sneha Patil",uploadedAt:"Oct 7, 2024 9:40 AM"}],spectators:[{name:"Arjun Menon",role:"Brand Manager",avatar:"AM"},{name:"Finance Team",role:"Budget Monitoring",avatar:"FT"}],auditTrail:[{type:"created",action:"Claim Request Created",details:"Diwali festival campaign claim initiated using Claim Management template",user:"Sneha Patil",timestamp:"Oct 7, 2024 9:30 AM"},{type:"assignment",action:"Assigned to Dealer",details:"Dealer Royal Motors Mumbai assigned for document upload",user:"System",timestamp:"Oct 7, 2024 9:31 AM"},{type:"status_change",action:"Workflow Started",details:"Step 1: Dealer document upload phase initiated",user:"System",timestamp:"Oct 7, 2024 9:31 AM"}],tags:["claim-management","dealer-activity","marketing","diwali-campaign","template"]}};function O0(t,s=[],a){const[r,n]=g.useState(null),[i,o]=g.useState(!1),[l,c]=g.useState(null),[d,m]=g.useState(!1),u=(N,f)=>(N||f||"NA").toString().split(" ").map(j=>j[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),h=N=>{const f=(N||"").toUpperCase();return f==="IN_PROGRESS"?"in-review":f==="PENDING"?"pending":f==="APPROVED"?"approved":f==="REJECTED"?"rejected":f==="CLOSED"?"closed":f==="SKIPPED"?"skipped":(N||"").toLowerCase()},x=async()=>{var N,f,b,j,C,R,I,T,E;o(!0);try{const w=await It.getWorkflowDetails(t);if(!w){console.warn("[useRequestDetails] No details returned from API");return}const S=w.workflow||{},D=Array.isArray(w.approvals)?w.approvals:[],H=Array.isArray(w.participants)?w.participants:[],L=Array.isArray(w.documents)?w.documents:[],F=w.summary||{},A=Array.isArray(w.tatAlerts)?w.tatAlerts:[];A.length>0;const k=(F==null?void 0:F.currentLevel)||S.currentLevel||1,P=D.map(z=>{const re=z.levelNumber||0,K=(z.status||"").toString().toUpperCase(),B=z.levelId||z.level_id;let J=h(z.status);re>k&&K!=="APPROVED"&&K!=="REJECTED"?J="waiting":re===k&&K==="PENDING"&&(J="pending");const ue=A.filter(be=>be.levelId===B);return{step:re,levelId:B,role:z.levelName||z.approverName||"Approver",status:J,approver:z.approverName||z.approverEmail,approverId:z.approverId||z.approver_id,approverEmail:z.approverEmail,tatHours:Number(z.tatHours||0),elapsedHours:Number(z.elapsedHours||0),remainingHours:Number(z.remainingHours||0),tatPercentageUsed:Number(z.tatPercentageUsed||0),actualHours:z.levelEndTime&&z.levelStartTime?Math.max(0,(new Date(z.levelEndTime).getTime()-new Date(z.levelStartTime).getTime())/(1e3*60*60)):void 0,comment:z.comments||void 0,timestamp:z.actionDate||void 0,levelStartTime:z.levelStartTime||z.tatStartTime,tatAlerts:ue,skipReason:z.skipReason||void 0,isSkipped:K==="SKIPPED"||z.isSkipped||!1}}),_=H.filter(z=>(z.participantType||z.participant_type||"").toUpperCase()==="SPECTATOR").map(z=>({name:z.userName||z.user_name||z.userEmail||z.user_email,role:"Spectator",email:z.userEmail||z.user_email,avatar:u(z.userName||z.user_name,z.userEmail||z.user_email)})),W=z=>{var K,B;if(!z)return;const re=H.find(J=>J.userId===z||J.user_id===z);return re!=null&&re.userName||re!=null&&re.user_name?re.userName||re.user_name:S.initiatorId===z?((K=S.initiator)==null?void 0:K.displayName)||((B=S.initiator)==null?void 0:B.email):z},Z=L.map(z=>{const re=Number(z.fileSize||z.file_size||0),K=(re/(1024*1024)).toFixed(2)+" MB";return{documentId:z.documentId||z.document_id,name:z.originalFileName||z.fileName||z.file_name,fileType:z.fileType||z.file_type||"",size:K,sizeBytes:re,uploadedBy:W(z.uploadedBy||z.uploaded_by),uploadedAt:z.uploadedAt||z.uploaded_at}}),ae=Array.isArray(w.activities)?w.activities.filter(z=>(z.type||"").toLowerCase()!=="sla_warning"):[],$={...S,id:S.requestNumber||S.requestId,requestId:S.requestId,requestNumber:S.requestNumber,title:S.title,description:S.description,status:h(S.status),priority:(S.priority||"").toString().toLowerCase(),approvalFlow:P,approvals:D,participants:H,documents:Z,spectators:_,summary:F,initiator:{name:((N=S.initiator)==null?void 0:N.displayName)||((f=S.initiator)==null?void 0:f.email),role:((b=S.initiator)==null?void 0:b.designation)||void 0,department:((j=S.initiator)==null?void 0:j.department)||void 0,email:((C=S.initiator)==null?void 0:C.email)||void 0,phone:((R=S.initiator)==null?void 0:R.phone)||void 0,avatar:u((I=S.initiator)==null?void 0:I.displayName,(T=S.initiator)==null?void 0:T.email)},createdAt:S.createdAt,updatedAt:S.updatedAt,totalSteps:S.totalLevels||1,currentStepRaw:(F==null?void 0:F.currentLevel)||S.currentLevel||1,currentStep:Math.min(Math.max(1,(F==null?void 0:F.currentLevel)||S.currentLevel||1),S.totalLevels||1),auditTrail:ae,conclusionRemark:S.conclusionRemark||null,closureDate:S.closureDate||null};n($);const ne=(E=a==null?void 0:a.email)==null?void 0:E.toLowerCase(),me=D.find(z=>{const re=(z.status||"").toString().toUpperCase(),K=(z.approverEmail||"").toLowerCase(),B=z.levelNumber||0;return(re==="PENDING"||re==="IN_PROGRESS"||re==="PAUSED")&&K===ne&&B===k});c(me||null);const q=a==null?void 0:a.userId;if(q){const z=H.some(re=>(re.participantType||re.participant_type||"").toUpperCase()==="SPECTATOR"&&(re.userId||re.user_id)===q);m(z)}else m(!1)}catch(w){console.error("[useRequestDetails] Error refreshing details:",w),alert("Failed to refresh request details. Please try again.")}finally{o(!1)}};g.useEffect(()=>{if(!t)return;let N=!0;return(async()=>{var f,b,j,C,R,I,T,E,w;try{const S=await It.getWorkflowDetails(t);if(!N||!S)return;const D=S.workflow||{},H=Array.isArray(S.approvals)?S.approvals:[],L=Array.isArray(S.participants)?S.participants:[],F=Array.isArray(S.documents)?S.documents:[],A=S.summary||{},k=Array.isArray(S.tatAlerts)?S.tatAlerts:[],P=(D.priority||"").toString().toLowerCase(),_=(A==null?void 0:A.currentLevel)||D.currentLevel||1,W=H.map(B=>{const J=B.levelNumber||0,ue=(B.status||"").toString().toUpperCase(),be=B.levelId||B.level_id;let Ie=h(B.status);ue==="PAUSED"?Ie="paused":J>_&&ue!=="APPROVED"&&ue!=="REJECTED"?Ie="waiting":J===_&&(ue==="PENDING"||ue==="IN_PROGRESS")&&(Ie=ue==="IN_PROGRESS"?"in-review":"pending");const Ve=k.filter(Oe=>Oe.levelId===be);return{step:J,levelId:be,role:B.levelName||B.approverName||"Approver",status:Ie,approver:B.approverName||B.approverEmail,approverId:B.approverId||B.approver_id,approverEmail:B.approverEmail,tatHours:Number(B.tatHours||0),elapsedHours:Number(B.elapsedHours||0),remainingHours:Number(B.remainingHours||0),tatPercentageUsed:Number(B.tatPercentageUsed||0),actualHours:B.elapsedHours!==void 0&&B.elapsedHours!==null?Number(B.elapsedHours):void 0,comment:B.comments||void 0,timestamp:B.actionDate||void 0,levelStartTime:B.levelStartTime||B.tatStartTime,tatAlerts:Ve}}),Z=L.filter(B=>(B.participantType||"").toUpperCase()==="SPECTATOR").map(B=>({name:B.userName||B.userEmail,role:"Spectator",avatar:u(B.userName,B.userEmail)})),ae=B=>{var ue,be;if(!B)return;const J=L.find(Ie=>Ie.userId===B);return J!=null&&J.userName?J.userName:D.initiatorId===B?((ue=D.initiator)==null?void 0:ue.displayName)||((be=D.initiator)==null?void 0:be.email):B},$=F.map(B=>{const J=Number(B.fileSize||0),ue=(J/(1024*1024)).toFixed(2)+" MB";return{documentId:B.documentId||B.document_id,name:B.originalFileName||B.fileName,fileType:B.fileType||B.file_type||"",size:ue,sizeBytes:J,uploadedBy:ae(B.uploadedBy),uploadedAt:B.uploadedAt}}),ne=Array.isArray(S.activities)?S.activities.filter(B=>(B.type||"").toLowerCase()!=="sla_warning"):[];let me=null;try{const{getPauseDetails:B}=await yr(async()=>{const{getPauseDetails:J}=await Promise.resolve().then(()=>f0);return{getPauseDetails:J}},void 0);me=await B(D.requestId)}catch(B){console.debug("Pause details not available:",B)}const q={id:D.requestNumber||D.requestId,requestId:D.requestId,title:D.title,description:D.description,priority:P,status:h(D.status),summary:A,initiator:{name:((f=D.initiator)==null?void 0:f.displayName)||((b=D.initiator)==null?void 0:b.email),role:((j=D.initiator)==null?void 0:j.designation)||void 0,department:((C=D.initiator)==null?void 0:C.department)||void 0,email:((R=D.initiator)==null?void 0:R.email)||void 0,phone:((I=D.initiator)==null?void 0:I.phone)||void 0,avatar:u((T=D.initiator)==null?void 0:T.displayName,(E=D.initiator)==null?void 0:E.email)},createdAt:D.createdAt,updatedAt:D.updatedAt,totalSteps:D.totalLevels||1,currentStepRaw:(A==null?void 0:A.currentLevel)||D.currentLevel||1,currentStep:Math.min(Math.max(1,(A==null?void 0:A.currentLevel)||D.currentLevel||1),D.totalLevels||1),approvalFlow:W,approvals:H,documents:$,spectators:Z,auditTrail:ne,conclusionRemark:D.conclusionRemark||null,closureDate:D.closureDate||null,pauseInfo:me||null};n(q);const z=(w=a==null?void 0:a.email)==null?void 0:w.toLowerCase(),re=H.find(B=>{const J=(B.status||"").toString().toUpperCase(),ue=(B.approverEmail||"").toLowerCase(),be=B.levelNumber||0;return(J==="PENDING"||J==="IN_PROGRESS"||J==="PAUSED")&&ue===z&&be===_});c(re||null);const K=a==null?void 0:a.userId;if(K){const B=L.some(J=>(J.participantType||"").toUpperCase()==="SPECTATOR"&&J.userId===K);m(B)}else m(!1)}catch(S){console.error("[useRequestDetails] Error loading request details:",S),N&&n(null)}})(),()=>{N=!1}},[t,a]);const p=g.useMemo(()=>{if(r)return r;const N=lm[t];if(N)return N;const f=F0[t];if(f)return f;const b=s.find(j=>j.id===t||j.requestNumber===t||j.request_number===t);return b||null},[t,s,r]),y=g.useMemo(()=>{var b,j,C;if(!p||!a)return!1;const N=(b=a==null?void 0:a.email)==null?void 0:b.toLowerCase(),f=(C=(j=p.initiator)==null?void 0:j.email)==null?void 0:C.toLowerCase();return N===f},[p,a]),v=g.useMemo(()=>{var f;if(!p)return[];const N=[];return(f=p.initiator)!=null&&f.email&&N.push({email:p.initiator.email.toLowerCase(),participantType:"INITIATOR",name:p.initiator.name}),p.approvalFlow&&Array.isArray(p.approvalFlow)&&p.approvalFlow.forEach(b=>{b.approverEmail&&N.push({email:b.approverEmail.toLowerCase(),participantType:"APPROVER",name:b.approver})}),p.spectators&&Array.isArray(p.spectators)&&p.spectators.forEach(b=>{b.email&&N.push({email:b.email.toLowerCase(),participantType:"SPECTATOR",name:b.name})}),p.participants&&Array.isArray(p.participants)&&p.participants.forEach(b=>{const j=(b.userEmail||b.email||"").toLowerCase(),C=(b.participantType||b.participant_type||"").toUpperCase(),R=b.userName||b.user_name||b.name;j&&C&&!N.find(I=>I.email===j)&&N.push({email:j,participantType:C,name:R})}),N},[p]);return{request:p,apiRequest:r,refreshing:i,refreshDetails:x,currentApprovalLevel:l,isSpectator:d,isInitiator:y,existingParticipants:v}}function $0(t,s,a,r){const[n,i]=g.useState([]),[o,l]=g.useState(0),[c,d]=g.useState([]);return g.useEffect(()=>{if(!t){console.warn("[useRequestSocket] No requestIdentifier, cannot join socket room");return}let m=!0,u=t;return(async()=>{var y;try{const v=await It.getWorkflowDetails(t);(y=v==null?void 0:v.workflow)!=null&&y.requestId&&m&&(u=v.workflow.requestId)}catch(v){console.error("[useRequestSocket] Failed to resolve UUID:",v)}if(!m)return;const h=Ar();if(!h){console.error("[useRequestSocket] Socket not available");return}const x=r==null?void 0:r.userId,p=()=>{Xn(h,u,x)};return h.connected?p():h.on("connect",p),()=>{m&&(h.off("connect",p),Ud(h,u))}})(),()=>{m=!1}},[t,r]),g.useEffect(()=>{!t||!s||(async()=>{try{const m=await aa(t),u=s.auditTrail||[],h=[...m,...u];h.sort((x,p)=>{const y=new Date(x.createdAt||x.created_at||x.timestamp||0).getTime(),v=new Date(p.createdAt||p.created_at||p.timestamp||0).getTime();return y-v}),i(h)}catch(m){console.error("[useRequestSocket] Failed to fetch and merge messages:",m)}})()},[t,s]),g.useEffect(()=>{if(!t)return;const m=Ar();if(!m)return;const u=x=>{a!=="worknotes"&&l(p=>p+1),(async()=>{try{const p=await aa(t),y=(s==null?void 0:s.auditTrail)||[],v=[...p,...y].sort((N,f)=>{const b=new Date(N.createdAt||N.created_at||N.timestamp||0).getTime(),j=new Date(f.createdAt||f.created_at||f.timestamp||0).getTime();return b-j});i(v)}catch(p){console.error("[useRequestSocket] Failed to refresh messages:",p)}})()},h=x=>{const p=x.type==="breach"?"⏰":x.type==="threshold2"?"⚠️":"⏳";(async()=>{try{const y=await It.getWorkflowDetails(t);y&&(Array.isArray(y.tatAlerts)&&y.tatAlerts,"Notification"in window&&Notification.permission==="granted"&&new Notification(`${p} TAT Alert`,{body:x.message,icon:"/favicon.ico",tag:`tat-${x.requestId}-${x.type}`,requireInteraction:!1}))}catch(y){console.error("[useRequestSocket] Failed to refresh after TAT alert:",y)}})()};return m.on("noteHandler",u),m.on("worknote:new",u),m.on("tat:alert",h),()=>{m.off("noteHandler",u),m.off("worknote:new",u),m.off("tat:alert",h)}},[t,a,s]),g.useEffect(()=>{a==="worknotes"&&l(0)},[a]),{mergedMessages:n,unreadWorkNotes:o,workNoteAttachments:c,setWorkNoteAttachments:d}}async function U0(t,s,a="SUPPORTING"){var o;const r=new FormData;r.append("file",t),r.append("requestId",s),r.append("category",a);const n=await ie.post("/documents",r,{headers:{"Content-Type":"multipart/form-data"}}),i=((o=n.data)==null?void 0:o.data)||n.data;return{documentId:(i==null?void 0:i.documentId)||(i==null?void 0:i.document_id)||"",storageUrl:(i==null?void 0:i.storageUrl)||(i==null?void 0:i.storage_url),fileName:(i==null?void 0:i.fileName)||(i==null?void 0:i.file_name)||t.name,originalFileName:(i==null?void 0:i.originalFileName)||(i==null?void 0:i.original_file_name)||t.name}}const ra=async t=>{const s=t?{category:t}:{};return(await ie.get("/users/configurations",{params:s})).data.data},Yr=async t=>{const s=t?{category:t}:{};return(await ie.get("/admin/configurations",{params:s})).data.data},bt=async(t,s)=>{await ie.put(`/admin/configurations/${t}`,{configValue:s})},V0=async t=>{await ie.post(`/admin/configurations/${t}/reset`)},B0=async t=>{const s=t?{year:t}:{};return(await ie.get("/admin/holidays",{params:s})).data.data},z0=async t=>(await ie.post("/admin/holidays",t)).data.data,H0=async(t,s)=>(await ie.put(`/admin/holidays/${t}`,s)).data.data,q0=async t=>{await ie.delete(`/admin/holidays/${t}`)};function W0(t,s){const[a,r]=g.useState(!1),[n,i]=g.useState(null),[o,l]=g.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[c,d]=g.useState({show:!1,errors:[]});g.useEffect(()=>{(async()=>{try{const p=await ra("DOCUMENT_POLICY"),y={};p.forEach(b=>{y[b.configKey]=b.configValue});const v=parseInt(y.MAX_FILE_SIZE_MB||"10"),f=(y.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(b=>b.trim().toLowerCase());l({maxFileSizeMB:v,allowedFileTypes:f})}catch(p){console.error("Failed to load document policy:",p)}})()},[]);const m=x=>{const p=o.maxFileSizeMB*1024*1024;if(x.size>p)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${o.maxFileSizeMB}MB. Current size: ${(x.size/(1024*1024)).toFixed(2)}MB`};const y=x.name.toLowerCase(),v=y.substring(y.lastIndexOf(".")+1);return o.allowedFileTypes.includes(v)?{valid:!0}:{valid:!1,reason:`File type "${v}" is not allowed. Allowed types: ${o.allowedFileTypes.join(", ")}`}},u=async x=>{var f,b;const p=x.target.files;if(!p||p.length===0)return;const y=Array.from(p),v=[],N=[];if(y.forEach(j=>{const C=m(j);C.valid?N.push(j):v.push({fileName:j.name,reason:C.reason||"Unknown validation error"})}),v.length>0&&d({show:!0,errors:v}),N.length===0){x.target&&(x.target.value="");return}r(!0);try{const j=N[0],C=t==null?void 0:t.requestId;if(!C){fe.error("Request ID not found");return}j&&await U0(j,C,"SUPPORTING"),await s(),N.length{const x=document.createElement("input");x.type="file",x.accept=o.allowedFileTypes.map(p=>`.${p}`).join(","),x.onchange=u,x.click()},previewDocument:n,setPreviewDocument:i,documentPolicy:o,documentError:c,setDocumentError:d}}function K0(t,s,a,r,n,i,o){const[l,c]=g.useState(""),[d,m]=g.useState(!1),[u,h]=g.useState(!1),[x,p]=g.useState(!1),y=async()=>{try{const{getConclusion:f}=await yr(async()=>{const{getConclusion:j}=await import("./conclusionApi-Dp5idKr8.js");return{getConclusion:j}},__vite__mapDeps([0,1,2,3,4,5,6,7])),b=await f(t.requestId||s);b&&b.aiGeneratedRemark&&(c(b.finalRemark||b.aiGeneratedRemark),p(!!b.aiGeneratedRemark))}catch{}},v=async()=>{try{m(!0);const{generateConclusion:f}=await yr(async()=>{const{generateConclusion:j}=await import("./conclusionApi-Dp5idKr8.js");return{generateConclusion:j}},__vite__mapDeps([0,1,2,3,4,5,6,7])),b=await f(t.requestId||s);c(b.aiGeneratedRemark),p(!0)}catch(f){console.error("[useConclusionRemark] AI generation failed:",f),c(""),p(!1)}finally{m(!1)}},N=async()=>{var b,j;const f=l.replace(/<[^>]*>/g,"").trim();if(!f){i==null||i({success:!1,title:"Validation Error",message:"Conclusion remark cannot be empty"}),o==null||o(!0);return}if(f.length>2e3){i==null||i({success:!1,title:"Validation Error",message:"Conclusion remark exceeds 2000 characters limit"}),o==null||o(!0);return}try{h(!0);const{finalizeConclusion:C}=await yr(async()=>{const{finalizeConclusion:R}=await import("./conclusionApi-Dp5idKr8.js");return{finalizeConclusion:R}},__vite__mapDeps([0,1,2,3,4,5,6,7]));await C(t.requestId||s,l),i==null||i({success:!0,title:"Request Closed with Successful Completion",message:"The request has been finalized and moved to Closed Requests."}),o==null||o(!0),await r(),setTimeout(()=>{n?(n(),setTimeout(()=>{window.location.hash="#/closed-requests"},100)):window.location.hash="#/closed-requests"},2e3)}catch(C){i==null||i({success:!1,title:"Error",message:((j=(b=C.response)==null?void 0:b.data)==null?void 0:j.error)||"Failed to finalize conclusion"}),o==null||o(!0)}finally{h(!1)}};return g.useEffect(()=>{((t==null?void 0:t.status)==="approved"||(t==null?void 0:t.status)==="rejected")&&a&&!l&&y()},[t==null?void 0:t.status,a]),{conclusionRemark:l,setConclusionRemark:c,conclusionLoading:d,conclusionSubmitting:u,aiGenerated:x,handleGenerateConclusion:v,handleFinalizeConclusion:N}}function G0(t,s,a){const[r,n]=g.useState(!1),[i,o]=g.useState(!1),[l,c]=g.useState(!1),[d,m]=g.useState(!1),[u,h]=g.useState(!1),[x,p]=g.useState(!1),[y,v]=g.useState(null),[N,f]=g.useState(null);return{showApproveModal:r,setShowApproveModal:n,showRejectModal:i,setShowRejectModal:o,showAddApproverModal:l,setShowAddApproverModal:c,showAddSpectatorModal:d,setShowAddSpectatorModal:m,showSkipApproverModal:u,setShowSkipApproverModal:h,showActionStatusModal:x,setShowActionStatusModal:p,skipApproverData:y,setSkipApproverData:v,actionStatus:N,setActionStatus:f,handleApproveConfirm:async T=>{var w,S;const E=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!E){alert("Approval level not found");return}await rm(t,E,T||""),await a(),(w=window==null?void 0:window.closeModal)==null||w.call(window),(S=window==null?void 0:window.toast)==null||S.call(window,"Approved successfully")},handleRejectConfirm:async T=>{var w,S;if(!(T!=null&&T.trim())){alert("Comments & remarks are required");return}const E=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!E){alert("Approval level not found");return}await nm(t,E,T.trim(),T.trim()),await a(),(w=window==null?void 0:window.closeModal)==null||w.call(window),(S=window==null?void 0:window.toast)==null||S.call(window,"Rejected successfully")},handleAddApprover:async(T,E,w)=>{var S,D;try{await Ui(t,T,E,w),await a(),c(!1),f==null||f({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${w} with ${E}h TAT`}),p==null||p(!0)}catch(H){throw f==null||f({success:!1,title:"Failed to Add Approver",message:((D=(S=H==null?void 0:H.response)==null?void 0:S.data)==null?void 0:D.error)||"Failed to add approver. Please try again."}),p==null||p(!0),H}},handleSkipApprover:async T=>{var E,w;if(y)try{await Xd(t,y.levelId,T),await a(),h(!1),v(null),f==null||f({success:!0,title:"Approver Skipped",message:"Approver skipped successfully. The workflow has moved to the next level."}),p==null||p(!0)}catch(S){throw f==null||f({success:!1,title:"Failed to Skip Approver",message:((w=(E=S==null?void 0:S.response)==null?void 0:E.data)==null?void 0:w.error)||"Failed to skip approver. Please try again."}),p==null||p(!0),S}},handleAddSpectator:async T=>{var E,w;try{await Vi(t,T),await a(),m(!1),f==null||f({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),p==null||p(!0)}catch(S){throw f==null||f({success:!1,title:"Failed to Add Spectator",message:((w=(E=S==null?void 0:S.response)==null?void 0:E.data)==null?void 0:w.error)||"Failed to add spectator. Please try again."}),p==null||p(!0),S}}}}const Y0=t=>{switch(t){case"express":case"urgent":return{color:"bg-red-100 text-red-800 border-red-200",label:"urgent priority"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",label:"standard priority"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",label:"normal priority"}}},Z0=t=>{switch(t){case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",label:"pending"};case"in-review":return{color:"bg-blue-100 text-blue-800 border-blue-200",label:"in-review"};case"approved":return{color:"bg-green-100 text-green-800 border-green-200",label:"approved"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",label:"rejected"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-300",label:"closed"};case"skipped":return{color:"bg-orange-100 text-orange-800 border-orange-200",label:"skipped"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",label:t}}},X0=t=>{switch(t){case"approval":case"approved":return e.jsx(ve,{className:"w-5 h-5 text-green-600"});case"rejection":case"rejected":return e.jsx(Ze,{className:"w-5 h-5 text-red-600"});case"comment":return e.jsx(ws,{className:"w-5 h-5 text-blue-600"});case"status_change":case"updated":return e.jsx(Lt,{className:"w-5 h-5 text-orange-600"});case"assignment":return e.jsx($r,{className:"w-5 h-5 text-purple-600"});case"created":return e.jsx(Te,{className:"w-5 h-5 text-blue-600"});case"reminder":return e.jsx(De,{className:"w-5 h-5 text-yellow-600"});case"document_added":return e.jsx(Or,{className:"w-5 h-5 text-indigo-600"});case"sla_warning":return e.jsx(is,{className:"w-5 h-5 text-amber-600"});default:return e.jsx(as,{className:"w-5 h-5 text-gray-600"})}};function Q0({sla:t,requestStatus:s,testId:a="sla-progress"}){return!t||s==="approved"||s==="rejected"||s==="closed"?e.jsxs("div",{className:"flex items-center gap-2","data-testid":`${a}-status-only`,children:[s==="closed"?e.jsx(qn,{className:"h-4 w-4 text-gray-600"}):s==="approved"?e.jsx(ve,{className:"h-4 w-4 text-green-600"}):s==="rejected"?e.jsx(Ze,{className:"h-4 w-4 text-red-600"}):e.jsx(De,{className:"h-4 w-4 text-gray-500"}),e.jsx("span",{className:"text-sm font-medium text-gray-700",children:s==="closed"?"Request Closed":s==="approved"?"Request Approved":s==="rejected"?"Request Rejected":"SLA Not Available"})]}):e.jsxs("div",{"data-testid":a,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(De,{className:"h-4 w-4 text-blue-600"}),e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:"SLA Progress"})]}),e.jsxs(Q,{className:`text-xs ${t.status==="breached"?"bg-red-600 text-white animate-pulse":t.status==="critical"?"bg-orange-600 text-white":t.status==="approaching"?"bg-yellow-600 text-white":"bg-green-600 text-white"}`,"data-testid":`${a}-badge`,children:[t.percentageUsed||0,"% elapsed"]})]}),e.jsx(hs,{value:t.percentageUsed||0,className:`h-3 mb-2 ${t.status==="breached"?"[&>div]:bg-red-600":t.status==="critical"?"[&>div]:bg-orange-600":t.status==="approaching"?"[&>div]:bg-yellow-600":"[&>div]:bg-green-600"}`,"data-testid":`${a}-bar`}),e.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[e.jsxs("span",{className:"text-gray-600","data-testid":`${a}-elapsed`,children:[t.elapsedText||nt(t.elapsedHours||0)," elapsed"]}),e.jsxs("span",{className:`font-semibold ${t.status==="breached"?"text-red-600":t.status==="critical"?"text-orange-600":"text-gray-700"}`,"data-testid":`${a}-remaining`,children:[t.remainingText||nt(t.remainingHours||0)," remaining"]})]}),t.deadline&&e.jsxs("p",{className:"text-xs text-gray-500","data-testid":`${a}-deadline`,children:["Due: ",ps(t.deadline,!0)," • ",t.percentageUsed||0,"% elapsed"]}),t.status==="critical"&&e.jsxs("p",{className:"text-xs text-orange-600 font-semibold mt-1 flex items-center gap-1.5","data-testid":`${a}-warning-critical`,children:[e.jsx(is,{className:"h-3.5 w-3.5"}),"Approaching Deadline"]}),t.status==="breached"&&e.jsxs("p",{className:"text-xs text-red-600 font-semibold mt-1 flex items-center gap-1.5","data-testid":`${a}-warning-breached`,children:[e.jsx(Wn,{className:"h-3.5 w-3.5"}),"URGENT - Deadline Passed"]})]})}function J0({request:t,refreshing:s,onBack:a,onRefresh:r,onShareSummary:n,isInitiator:i}){var c,d;const o=Y0((t==null?void 0:t.priority)||"standard"),l=Z0((t==null?void 0:t.status)||"pending");return e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border border-gray-300 mb-4 sm:mb-6","data-testid":"request-detail-header",children:[e.jsxs("div",{className:"p-3 sm:p-4 md:p-6 border-b border-gray-300",children:[e.jsxs("div",{className:"flex items-start sm:items-center justify-between gap-2 sm:gap-4",children:[e.jsxs("div",{className:"flex items-start sm:items-center gap-2 sm:gap-4 min-w-0 flex-1",children:[e.jsx(M,{variant:"ghost",size:"icon",onClick:a,className:"rounded-lg flex-shrink-0 h-8 w-8 sm:h-10 sm:w-10","data-testid":"back-button",children:e.jsx(_s,{className:"h-4 w-4 sm:h-5 sm:h-5"})}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-3 min-w-0 flex-1",children:[e.jsx("div",{className:"w-8 h-8 sm:w-10 sm:h-10 rounded-full bg-blue-100 flex items-center justify-center flex-shrink-0",children:e.jsx(Te,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"})}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-2 min-w-0 flex-1",children:[e.jsx("h1",{className:"text-sm sm:text-base md:text-lg font-bold text-gray-900 truncate","data-testid":"request-id",children:t.id||"N/A"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2",children:[e.jsx(Q,{className:`${o.color} rounded-full px-2 sm:px-3 text-xs capitalize shrink-0`,variant:"outline","data-testid":"priority-badge",children:o.label}),e.jsx(Q,{className:`${l.color} rounded-full px-2 sm:px-3 text-xs capitalize shrink-0`,variant:"outline","data-testid":"status-badge",children:l.label})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[n&&i&&((c=t==null?void 0:t.status)==null?void 0:c.toLowerCase())==="closed"&&e.jsxs(M,{variant:"default",size:"sm",className:"gap-1 sm:gap-2 flex-shrink-0 h-8 sm:h-9",onClick:n,"data-testid":"share-summary-button",children:[e.jsx(wa,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Share Summary"})]}),e.jsxs(M,{variant:"outline",size:"sm",className:"gap-1 sm:gap-2 flex-shrink-0 h-8 sm:h-9",onClick:r,disabled:s,"data-testid":"refresh-button",children:[e.jsx(Lt,{className:`w-3.5 h-3.5 sm:w-4 sm:h-4 ${s?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:s?"Refreshing...":"Refresh"})]})]})]}),e.jsx("div",{className:"mt-3 ml-0 sm:ml-14",children:e.jsx("h2",{className:"text-base sm:text-lg md:text-xl font-semibold text-gray-900 line-clamp-2","data-testid":"request-title",children:t.title})})]}),e.jsx("div",{className:"px-3 sm:px-4 md:px-6 py-3 sm:py-4 bg-gradient-to-r from-blue-50 to-indigo-50 border-b border-gray-200","data-testid":"sla-section",children:e.jsx(Q0,{sla:((d=t.summary)==null?void 0:d.sla)||t.sla,requestStatus:t.status,testId:"request-sla"})})]})}function ot({...t}){return e.jsx(xp,{"data-slot":"dialog",...t})}function ey({...t}){return e.jsx(pp,{"data-slot":"dialog-portal",...t})}const cm=g.forwardRef(({className:t,...s},a)=>e.jsx(Gc,{ref:a,"data-slot":"dialog-overlay",className:oe("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",t),...s}));cm.displayName=Gc.displayName;const Je=g.forwardRef(({className:t,children:s,...a},r)=>e.jsxs(ey,{"data-slot":"dialog-portal",children:[e.jsx(cm,{}),e.jsxs(Yc,{ref:r,"data-slot":"dialog-content",className:oe("bg-white data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",t),...a,children:[s,e.jsxs(hp,{className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[e.jsx(ft,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Je.displayName=Yc.displayName;const lt=g.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,"data-slot":"dialog-header",className:oe("flex flex-col gap-2 text-center sm:text-left",t),...s}));lt.displayName="DialogHeader";const Tt=g.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,"data-slot":"dialog-footer",className:oe("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s}));Tt.displayName="DialogFooter";const et=g.forwardRef(({className:t,...s},a)=>e.jsx(Zc,{ref:a,"data-slot":"dialog-title",className:oe("text-lg leading-none font-semibold",t),...s}));et.displayName=Zc.displayName;const Zt=g.forwardRef(({className:t,...s},a)=>e.jsx(Xc,{ref:a,"data-slot":"dialog-description",className:oe("text-muted-foreground text-sm",t),...s}));Zt.displayName=Xc.displayName;function Hi({className:t,...s}){return e.jsx(gp,{"data-slot":"checkbox",className:oe("peer border bg-input-background dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",t),...s,children:e.jsx(fp,{"data-slot":"checkbox-indicator",className:"flex items-center justify-center text-current transition-none",children:e.jsx(Ca,{className:"size-3.5"})})})}async function dl(t){return(await ie.post("/summaries",{requestId:t})).data.data}async function Jn(t){return(await ie.get(`/summaries/${t}`)).data.data}async function ty(t,s){return(await ie.post(`/summaries/${t}/share`,{userIds:s})).data.data}async function sy(t={}){var n,i;const{page:s=1,limit:a=20}=t,r=await ie.get("/summaries/shared",{params:{page:s,limit:a}});return{data:((n=r.data.data)==null?void 0:n.data)||r.data.data||[],pagination:((i=r.data.data)==null?void 0:i.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function dm(t){await ie.patch(`/summaries/shared/${t}/view`)}async function ay(t){return(await ie.get(`/summaries/${t}/recipients`)).data.data||[]}async function xs(t,s=10){return await ie.get("/users/search",{params:{q:t,limit:s}})}async function bs(t){var a;const s=await ie.post("/users/ensure",t);return((a=s.data)==null?void 0:a.data)||s.data}async function ry(t,s,a){return await ie.post("/admin/users/assign-role",{email:t,role:s,userData:a?{userId:a.userId,email:a.email,displayName:a.displayName,firstName:a.firstName,lastName:a.lastName,department:a.department,phone:a.phone,mobilePhone:a.mobilePhone,designation:a.designation,jobTitle:a.jobTitle,manager:a.manager,employeeId:a.employeeId,employeeNumber:a.employeeNumber,secondEmail:a.secondEmail,location:a.location}:void 0})}async function ny(t,s){return await ie.put(`/admin/users/${t}/role`,{role:s})}async function iy(t,s=1,a=10){return await ie.get("/admin/users/by-role",{params:{role:t||"ELEVATED",page:s,limit:a}})}async function oy(){return await ie.get("/admin/users/role-statistics")}async function ly(){var s,a;return((a=(s=(await ie.get("/users")).data)==null?void 0:s.data)==null?void 0:a.users)||[]}const Wt={searchUsers:xs,ensureUserExists:bs,assignRole:ry,updateUserRole:ny,getUsersByRole:iy,getRoleStatistics:oy,getAllUsers:ly};function cy({isOpen:t,onClose:s,summaryId:a,requestTitle:r,onSuccess:n}){const[i,o]=g.useState(""),[l,c]=g.useState([]),[d,m]=g.useState(new Set),[u,h]=g.useState(!1),[x,p]=g.useState(!1);g.useEffect(()=>{if(!t||!i.trim()){c([]);return}const f=setTimeout(async()=>{var b;try{h(!0);const j=await xs(i),C=((b=j==null?void 0:j.data)==null?void 0:b.data)||(j==null?void 0:j.data)||[];c(Array.isArray(C)?C:[])}catch(j){console.error("Failed to search users:",j),fe.error("Failed to search users")}finally{h(!1)}},300);return()=>clearTimeout(f)},[i,t]);const y=f=>{m(b=>{const j=new Set(b);return j.has(f)?j.delete(f):j.add(f),j})},v=async()=>{var f,b;if(d.size===0){fe.error("Please select at least one user to share with");return}try{p(!0),await ty(a,Array.from(d)),fe.success(`Summary shared with ${d.size} user(s)`),m(new Set),o(""),c([]),n==null||n(),s()}catch(j){console.error("Failed to share summary:",j),fe.error(((b=(f=j==null?void 0:j.response)==null?void 0:f.data)==null?void 0:b.message)||"Failed to share summary")}finally{p(!1)}},N=()=>{m(new Set),o(""),c([]),s()};return e.jsx(ot,{open:t,onOpenChange:N,children:e.jsxs(Je,{className:"sm:max-w-[500px]",children:[e.jsx(lt,{children:e.jsx(et,{children:"Share Summary"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{children:[e.jsx(X,{className:"text-sm font-medium text-gray-700",children:"Request"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:r})]}),e.jsxs("div",{children:[e.jsx(X,{htmlFor:"user-search",className:"text-sm font-medium text-gray-700",children:"Search Users"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(Yt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(xe,{id:"user-search",placeholder:"Search by name or email...",value:i,onChange:f=>o(f.target.value),className:"pl-10"})]})]}),u&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Le,{className:"h-5 w-5 animate-spin text-blue-600"})}),!u&&l.length>0&&e.jsx("div",{className:"border rounded-lg max-h-[300px] overflow-y-auto",children:l.map(f=>{const b=d.has(f.userId);return e.jsxs("div",{className:"flex items-center gap-3 p-3 hover:bg-gray-50 border-b last:border-b-0 cursor-pointer",onClick:()=>y(f.userId),children:[e.jsx("div",{onClick:j=>j.stopPropagation(),onMouseDown:j=>j.stopPropagation(),className:"flex items-center",children:e.jsx(Hi,{checked:b,onCheckedChange:()=>y(f.userId)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rt,{className:"h-4 w-4 text-gray-400 flex-shrink-0"}),e.jsx("p",{className:"text-sm font-medium text-gray-900 truncate",children:f.displayName||f.email})]}),(f.designation||f.department)&&e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:f.designation||f.department}),e.jsx("p",{className:"text-xs text-gray-400 truncate",children:f.email})]})]},f.userId)})}),!u&&i&&l.length===0&&e.jsx("div",{className:"text-center py-8 text-gray-500 text-sm",children:"No users found"}),d.size>0&&e.jsxs("div",{className:"border rounded-lg p-3 bg-blue-50",children:[e.jsxs("p",{className:"text-sm font-medium text-gray-700 mb-2",children:["Selected (",d.size,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(d).map(f=>{const b=l.find(j=>j.userId===f);return e.jsxs("div",{className:"flex items-center gap-1 bg-white px-2 py-1 rounded-full text-xs",children:[e.jsx("span",{children:(b==null?void 0:b.displayName)||(b==null?void 0:b.email)||f}),e.jsx("button",{onClick:()=>y(f),className:"ml-1 hover:text-red-600",children:e.jsx(ft,{className:"h-3 w-3"})})]},f)})})]})]}),e.jsxs(Tt,{children:[e.jsx(M,{variant:"outline",onClick:N,disabled:x,children:"Cancel"}),e.jsx(M,{onClick:v,disabled:x||d.size===0,children:x?e.jsxs(e.Fragment,{children:[e.jsx(Le,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):`Share with ${d.size} user(s)`})]})]})})}function mm({value:t,onChange:s,placeholder:a="Enter text...",className:r,minHeight:n="120px",...i}){const o=g.useRef(null),[l,c]=g.useState(!1),[d,m]=g.useState(new Set);g.useEffect(()=>{o.current&&o.current.innerHTML!==t&&o.current.innerHTML!==t&&(o.current.innerHTML=t||"")},[t]);const u=g.useCallback(b=>(b=b.replace(//g,""),b=b.replace(/]*>[\s\S]*?<\/style>/gi,""),b=b.replace(/]*>[\s\S]*?<\/script>/gi,""),b=b.replace(/]*>/gi,""),b=b.replace(/\s*class="Mso[^"]*"/gi,""),b=b.replace(/\s*class="mso[^"]*"/gi,""),b=b.replace(/\s*style="[^"]*mso-[^"]*"/gi,""),b=b.replace(/\s*style="[^"]*font-family:[^"]*"/gi,""),b=b.replace(/\s*xmlns[^=]*="[^"]*"/gi,""),b=b.replace(/<\/?o:p[^>]*>/gi,""),b=b.replace(/]*>[\s\S]*?<\/v:[^>]*>/gi,""),b=b.replace(/]*\/>/gi,""),b=b.replace(/]*>\s*<\/p>/gi,""),b=b.replace(/]*>\s*<\/div>/gi,""),b=b.replace(/\s+/g," "),b=b.trim(),b),[]),h=g.useCallback(b=>{b.preventDefault();const j=b.clipboardData;let C=j.getData("text/html")||j.getData("text/plain");if((C.includes("/g,"");D.innerHTML=L,D.removeAttribute("style"),D.removeAttribute("class"),E.appendChild(D)}else if(S.tagName==="BR")E.appendChild(S.cloneNode(!0));else{const D=S.textContent||"";if(D.trim()){const H=document.createElement("p");H.textContent=D.trim(),E.appendChild(H)}}}else if(w.nodeType===Node.TEXT_NODE){const S=w.textContent||"";if(S.trim()){const D=document.createElement("p");D.textContent=S.trim(),E.appendChild(D)}}}),E.childNodes.length===0&&j.getData("text/plain").split(` `).forEach(D=>{if(D.trim()){const H=document.createElement("p");H.textContent=D.trim(),E.appendChild(H)}else E.appendChild(document.createElement("br"))}),I.insertNode(E),I.collapse(!1),R.removeAllRanges(),R.addRange(I),o.current&&s(o.current.innerHTML)},[s,u]),x=g.useCallback(()=>{if(!o.current||!l)return;const b=new Set,j=window.getSelection();if(j&&j.rangeCount>0){const R=j.getRangeAt(0).commonAncestorContainer;let I=null;for(R.nodeType===Node.TEXT_NODE?I=R.parentElement:I=R;I&&I!==o.current;){const T=I.tagName.toLowerCase();(T==="strong"||T==="b")&&b.add("bold"),(T==="em"||T==="i")&&b.add("italic"),T==="u"&&b.add("underline"),T==="h1"&&b.add("h1"),T==="h2"&&b.add("h2"),T==="h3"&&b.add("h3"),T==="ul"&&b.add("ul"),T==="ol"&&b.add("ol");const E=window.getComputedStyle(I);E.textAlign==="center"&&b.add("center"),E.textAlign==="right"&&b.add("right"),E.textAlign==="left"&&b.add("left"),I=I.parentElement}}m(b)},[l]),p=g.useCallback((b,j)=>{if(!o.current)return;l||o.current.focus();const C=window.getSelection();if(!C||C.rangeCount===0){o.current.focus();return}document.execCommand(b,!1,j),o.current&&s(o.current.innerHTML),setTimeout(x,10)},[l,s,x]),y=g.useCallback(()=>{o.current&&s(o.current.innerHTML),x()},[s,x]),v=g.useCallback(b=>{if(b.ctrlKey&&b.key==="b"){b.preventDefault(),p("bold");return}if(b.ctrlKey&&b.key==="i"){b.preventDefault(),p("italic");return}if(b.ctrlKey&&b.key==="u"){b.preventDefault(),p("underline");return}},[p]),N=g.useCallback(()=>{c(!0)},[]),f=g.useCallback(()=>{c(!1),o.current&&s(o.current.innerHTML)},[s]);return g.useEffect(()=>{if(!l)return;const b=()=>{x()};return document.addEventListener("selectionchange",b),()=>{document.removeEventListener("selectionchange",b)}},[l,x]),e.jsxs("div",{className:"relative border border-gray-300 rounded-md bg-white",children:[e.jsxs("div",{className:"flex items-center gap-1 p-2 border-b border-gray-200 bg-gray-50 rounded-t-md flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-1 border-r border-gray-300 pr-2",children:[e.jsx(M,{type:"button",variant:"ghost",size:"sm",className:oe("h-7 w-7 p-0",d.has("bold")&&"bg-blue-100 text-blue-700"),onClick:()=>p("bold"),title:"Bold (Ctrl+B)",children:e.jsx(rx,{className:"h-4 w-4"})}),e.jsx(M,{type:"button",variant:"ghost",size:"sm",className:oe("h-7 w-7 p-0",d.has("italic")&&"bg-blue-100 text-blue-700"),onClick:()=>p("italic"),title:"Italic (Ctrl+I)",children:e.jsx(nx,{className:"h-4 w-4"})}),e.jsx(M,{type:"button",variant:"ghost",size:"sm",className:oe("h-7 w-7 p-0",d.has("underline")&&"bg-blue-100 text-blue-700"),onClick:()=>p("underline"),title:"Underline (Ctrl+U)",children:e.jsx(ix,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-1 border-r border-gray-300 pr-2",children:[e.jsx(M,{type:"button",variant:"ghost",size:"sm",className:oe("h-7 w-7 p-0",d.has("h1")&&"bg-blue-100 text-blue-700"),onClick:()=>p("formatBlock","

"),title:"Heading 1",children:e.jsx(ox,{className:"h-4 w-4"})}),e.jsx(M,{type:"button",variant:"ghost",size:"sm",className:oe("h-7 w-7 p-0",d.has("h2")&&"bg-blue-100 text-blue-700"),onClick:()=>p("formatBlock","

"),title:"Heading 2",children:e.jsx(lx,{className:"h-4 w-4"})}),e.jsx(M,{type:"button",variant:"ghost",size:"sm",className:oe("h-7 w-7 p-0",d.has("h3")&&"bg-blue-100 text-blue-700"),onClick:()=>p("formatBlock","

"),title:"Heading 3",children:e.jsx(cx,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-1 border-r border-gray-300 pr-2",children:[e.jsx(M,{type:"button",variant:"ghost",size:"sm",className:oe("h-7 w-7 p-0",d.has("ul")&&"bg-blue-100 text-blue-700"),onClick:()=>p("insertUnorderedList"),title:"Bullet List",children:e.jsx(cd,{className:"h-4 w-4"})}),e.jsx(M,{type:"button",variant:"ghost",size:"sm",className:oe("h-7 w-7 p-0",d.has("ol")&&"bg-blue-100 text-blue-700"),onClick:()=>p("insertOrderedList"),title:"Numbered List",children:e.jsx(dx,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(M,{type:"button",variant:"ghost",size:"sm",className:oe("h-7 w-7 p-0",d.has("left")&&"bg-blue-100 text-blue-700"),onClick:()=>p("justifyLeft"),title:"Align Left",children:e.jsx(mx,{className:"h-4 w-4"})}),e.jsx(M,{type:"button",variant:"ghost",size:"sm",className:oe("h-7 w-7 p-0",d.has("center")&&"bg-blue-100 text-blue-700"),onClick:()=>p("justifyCenter"),title:"Align Center",children:e.jsx(ux,{className:"h-4 w-4"})}),e.jsx(M,{type:"button",variant:"ghost",size:"sm",className:oe("h-7 w-7 p-0",d.has("right")&&"bg-blue-100 text-blue-700"),onClick:()=>p("justifyRight"),title:"Align Right",children:e.jsx(hx,{className:"h-4 w-4"})})]})]}),e.jsx("div",{ref:o,contentEditable:!0,onPaste:h,onInput:y,onFocus:N,onBlur:f,onKeyDown:v,onMouseUp:x,onKeyUp:x,"data-placeholder":a,className:oe("w-full rounded-b-md border-0 px-3 py-2 text-base transition-all outline-none","bg-white text-gray-900","min-h-[120px]","overflow-y-auto","overflow-x-auto","md:overflow-x-visible","md:text-sm","empty:before:content-[attr(data-placeholder)] empty:before:text-muted-foreground empty:before:pointer-events-none","focus-visible:outline-none","[&_ul]:list-disc [&_ul]:ml-6 [&_ul]:my-2 [&_ul]:list-outside","[&_ol]:list-decimal [&_ol]:ml-6 [&_ol]:my-2 [&_ol]:list-outside","[&_li]:my-1 [&_li]:pl-2","[&_.table-wrapper]:overflow-x-auto [&_.table-wrapper]:max-w-full [&_.table-wrapper]:my-2","[&_.table-wrapper_table]:border-collapse [&_.table-wrapper_table]:border [&_.table-wrapper_table]:border-gray-300 [&_.table-wrapper_table]:min-w-full","[&_.table-wrapper_table_td]:border [&_.table-wrapper_table_td]:border-gray-300 [&_.table-wrapper_table_td]:px-3 [&_.table-wrapper_table_td]:py-2 [&_.table-wrapper_table_td]:text-sm [&_.table-wrapper_table_td]:whitespace-nowrap","[&_.table-wrapper_table_th]:border [&_.table-wrapper_table_th]:border-gray-300 [&_.table-wrapper_table_th]:px-3 [&_.table-wrapper_table_th]:py-2 [&_.table-wrapper_table_th]:bg-gray-50 [&_.table-wrapper_table_th]:font-semibold [&_.table-wrapper_table_th]:text-sm [&_.table-wrapper_table_th]:text-left [&_.table-wrapper_table_th]:whitespace-nowrap","[&_.table-wrapper_table_tr:nth-child(even)]:bg-gray-50","[&_table]:border-collapse [&_table]:my-2 [&_table]:border [&_table]:border-gray-300 [&_table]:w-full","[&_table_td]:border [&_table_td]:border-gray-300 [&_table_td]:px-3 [&_table_td]:py-2 [&_table_td]:text-sm","[&_table_th]:border [&_table_th]:border-gray-300 [&_table_th]:px-3 [&_table_th]:py-2 [&_table_th]:bg-gray-50 [&_table_th]:font-semibold [&_table_th]:text-sm [&_table_th]:text-left","[&_table_tr:nth-child(even)]:bg-gray-50","[&_p]:my-1 [&_p]:leading-relaxed","[&_strong]:font-bold","[&_em]:italic","[&_u]:underline","[&_h1]:text-xl [&_h1]:font-bold [&_h1]:my-2","[&_h2]:text-lg [&_h2]:font-semibold [&_h2]:my-2","[&_h3]:text-base [&_h3]:font-semibold [&_h3]:my-1",r),style:{minHeight:n},...i})]})}function Ms({content:t,className:s}){const a=g.useMemo(()=>{if(!t)return"";let r=t;const n=/]*>[\s\S]*?<\/table>/gi;return r=r.replace(n,i=>i.includes("table-wrapper")?i:`
${i}
`),r},[t]);return t?e.jsx("div",{className:oe("text-sm text-gray-700 max-w-none","overflow-x-auto","md:overflow-x-visible","[&_ul]:list-disc [&_ul]:ml-6 [&_ul]:my-2 [&_ul]:list-outside","[&_ol]:list-decimal [&_ol]:ml-6 [&_ol]:my-2 [&_ol]:list-outside","[&_li]:my-1 [&_li]:pl-2","[&_.table-wrapper]:overflow-x-auto [&_.table-wrapper]:max-w-full [&_.table-wrapper]:my-2 [&_.table-wrapper]:-mx-2 [&_.table-wrapper]:px-2","[&_.table-wrapper_table]:border-collapse [&_.table-wrapper_table]:border [&_.table-wrapper_table]:border-gray-300 [&_.table-wrapper_table]:min-w-full","[&_.table-wrapper_table_td]:border [&_.table-wrapper_table_td]:border-gray-300 [&_.table-wrapper_table_td]:px-3 [&_.table-wrapper_table_td]:py-2 [&_.table-wrapper_table_td]:text-sm [&_.table-wrapper_table_td]:whitespace-nowrap","[&_.table-wrapper_table_th]:border [&_.table-wrapper_table_th]:border-gray-300 [&_.table-wrapper_table_th]:px-3 [&_.table-wrapper_table_th]:py-2 [&_.table-wrapper_table_th]:bg-gray-50 [&_.table-wrapper_table_th]:font-semibold [&_.table-wrapper_table_th]:text-sm [&_.table-wrapper_table_th]:text-left [&_.table-wrapper_table_th]:whitespace-nowrap","[&_.table-wrapper_table_tr:nth-child(even)]:bg-gray-50","[&_table]:border-collapse [&_table]:my-2 [&_table]:border [&_table]:border-gray-300","[&_table_td]:border [&_table_td]:border-gray-300 [&_table_td]:px-3 [&_table_td]:py-2 [&_table_td]:text-sm","[&_table_th]:border [&_table_th]:border-gray-300 [&_table_th]:px-3 [&_table_th]:py-2 [&_table_th]:bg-gray-50 [&_table_th]:font-semibold [&_table_th]:text-sm [&_table_th]:text-left","[&_table_tr:nth-child(even)]:bg-gray-50","[&_p]:my-1 [&_p]:leading-relaxed","[&_strong]:font-bold","[&_em]:italic","[&_u]:underline","[&_h1]:text-xl [&_h1]:font-bold [&_h1]:my-2","[&_h2]:text-lg [&_h2]:font-semibold [&_h2]:my-2","[&_h3]:text-base [&_h3]:font-semibold [&_h3]:my-1",s),dangerouslySetInnerHTML:{__html:a}}):null}var um={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(_r,function(){var a=1e3,r=6e4,n=36e5,i="millisecond",o="second",l="minute",c="hour",d="day",m="week",u="month",h="quarter",x="year",p="date",y="Invalid Date",v=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,N=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,f={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(L){var F=["th","st","nd","rd"],A=L%100;return"["+L+(F[(A-20)%10]||F[A]||F[0])+"]"}},b=function(L,F,A){var k=String(L);return!k||k.length>=F?L:""+Array(F+1-k.length).join(A)+L},j={s:b,z:function(L){var F=-L.utcOffset(),A=Math.abs(F),k=Math.floor(A/60),P=A%60;return(F<=0?"+":"-")+b(k,2,"0")+":"+b(P,2,"0")},m:function L(F,A){if(F.date()1)return L(W[0])}else{var Z=F.name;R[Z]=F,P=Z}return!k&&P&&(C=P),P||!k&&C},w=function(L,F){if(T(L))return L.clone();var A=typeof F=="object"?F:{};return A.date=L,A.args=arguments,new D(A)},S=j;S.l=E,S.i=T,S.w=function(L,F){return w(L,{locale:F.$L,utc:F.$u,x:F.$x,$offset:F.$offset})};var D=function(){function L(A){this.$L=E(A.locale,null,!0),this.parse(A),this.$x=this.$x||A.x||{},this[I]=!0}var F=L.prototype;return F.parse=function(A){this.$d=function(k){var P=k.date,_=k.utc;if(P===null)return new Date(NaN);if(S.u(P))return new Date;if(P instanceof Date)return new Date(P);if(typeof P=="string"&&!/Z$/i.test(P)){var W=P.match(v);if(W){var Z=W[2]-1||0,ae=(W[7]||"0").substring(0,3);return _?new Date(Date.UTC(W[1],Z,W[3]||1,W[4]||0,W[5]||0,W[6]||0,ae)):new Date(W[1],Z,W[3]||1,W[4]||0,W[5]||0,W[6]||0,ae)}}return new Date(P)}(A),this.init()},F.init=function(){var A=this.$d;this.$y=A.getFullYear(),this.$M=A.getMonth(),this.$D=A.getDate(),this.$W=A.getDay(),this.$H=A.getHours(),this.$m=A.getMinutes(),this.$s=A.getSeconds(),this.$ms=A.getMilliseconds()},F.$utils=function(){return S},F.isValid=function(){return this.$d.toString()!==y},F.isSame=function(A,k){var P=w(A);return this.startOf(k)<=P&&P<=this.endOf(k)},F.isAfter=function(A,k){return w(A)0,R<=C.r||!C.r){R<=1&&j>0&&(C=f[j-1]);var I=N[C.l];x&&(R=x(""+R)),y=typeof I=="string"?I.replace("%d",R):I(R,m,C.l,v);break}}if(m)return y;var T=v?N.future:N.past;return typeof T=="function"?T(y):T.replace("%s",y)},i.to=function(d,m){return l(d,m,this,!0)},i.from=function(d,m){return l(d,m,this)};var c=function(d){return d.$u?n.utc():n()};i.toNow=function(d){return this.to(c(this),d)},i.fromNow=function(d){return this.from(c(this),d)}}})})(hm);var my=hm.exports;const uy=Lr(my);Xe.extend(uy);function hy({request:t,isInitiator:s,needsClosure:a,conclusionRemark:r,setConclusionRemark:n,conclusionLoading:i,conclusionSubmitting:o,aiGenerated:l,handleGenerateConclusion:c,handleFinalizeConclusion:d,onPause:m,onResume:u,onRetrigger:h,currentUserIsApprover:x=!1,pausedByUserId:p,currentUserId:y}){var j,C,R,I,T,E,w;const v=t==null?void 0:t.pauseInfo,N=(v==null?void 0:v.isPaused)||!1,f=N&&x&&p===y,b=N&&s;return e.jsxs("div",{className:"space-y-4 sm:space-y-6","data-testid":"overview-tab-content",children:[e.jsxs(G,{"data-testid":"initiator-card",children:[e.jsx(te,{className:"pb-3 sm:pb-4",children:e.jsxs(se,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(rt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Initiator"]})}),e.jsx(Y,{children:e.jsxs("div",{className:"flex items-start gap-3 sm:gap-4",children:[e.jsx(jt,{className:"h-10 w-10 sm:h-12 sm:w-12 ring-2 ring-white shadow-sm flex-shrink-0",children:e.jsx(Nt,{className:"bg-gray-700 text-white font-semibold text-sm",children:((j=t.initiator)==null?void 0:j.avatar)||"U"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-gray-900 text-sm sm:text-base truncate",children:((C=t.initiator)==null?void 0:C.name)||"N/A"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 truncate",children:((R=t.initiator)==null?void 0:R.role)||"N/A"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-500 truncate",children:((I=t.initiator)==null?void 0:I.department)||"N/A"}),e.jsxs("div",{className:"mt-2 sm:mt-3 space-y-1.5 sm:space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs sm:text-sm text-gray-600 min-w-0",children:[e.jsx(pd,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:((T=t.initiator)==null?void 0:T.email)||"N/A"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs sm:text-sm text-gray-600",children:[e.jsx(xd,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{children:((E=t.initiator)==null?void 0:E.phone)||"N/A"})]})]})]})]})})]}),e.jsxs(G,{"data-testid":"request-details-card",children:[e.jsx(te,{className:"pb-3 sm:pb-4",children:e.jsxs(se,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Te,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Details"]})}),e.jsxs(Y,{className:"space-y-3 sm:space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs sm:text-sm font-medium text-gray-700 block mb-2",children:"Description"}),e.jsx("div",{className:"bg-gray-50 rounded-lg p-3 sm:p-4 border border-gray-300",children:e.jsx(Ms,{content:t.description||"",className:"text-xs sm:text-sm"})})]}),(t.category||t.subcategory)&&e.jsxs("div",{className:"grid grid-cols-2 gap-4 pt-4 border-t border-gray-300",children:[t.category&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Category"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.category})]}),t.subcategory&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Subcategory"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.subcategory})]})]}),t.amount&&e.jsxs("div",{className:"pt-4 border-t border-gray-300",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Amount"}),e.jsx("p",{className:"text-lg font-bold text-gray-900 mt-1",children:t.amount})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 pt-4 border-t border-gray-300",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Created"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:Ot(t.createdAt)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Last Updated"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:Ot(t.updatedAt)})]})]})]})]}),N&&v&&e.jsxs(G,{className:"border-orange-300 bg-orange-50/50","data-testid":"pause-status-card",children:[e.jsx(te,{className:"pb-3 sm:pb-4",children:e.jsxs(se,{className:"flex items-center gap-2 text-sm sm:text-base text-orange-800",children:[e.jsx(Ls,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Workflow Paused"]})}),e.jsxs(Y,{className:"space-y-3 sm:space-y-4",children:[e.jsx("div",{className:"bg-white rounded-lg p-3 sm:p-4 border border-orange-200",children:e.jsxs("div",{className:"space-y-2 sm:space-y-3",children:[v.pauseReason&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Reason"}),e.jsx("p",{className:"text-sm text-gray-900 mt-1",children:v.pauseReason})]}),v.pausedBy&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Paused By"}),e.jsx("p",{className:"text-sm text-gray-900 mt-1",children:v.pausedBy.name||v.pausedBy.email})]}),v.pauseResumeDate&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Auto-Resume Date"}),e.jsxs("p",{className:"text-sm text-gray-900 mt-1",children:[Ot(v.pauseResumeDate),Xe(v.pauseResumeDate).isAfter(Xe())&&e.jsxs("span",{className:"ml-2 text-xs text-gray-500",children:["(",Xe(v.pauseResumeDate).fromNow(),")"]})]})]}),v.pausedAt&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Paused At"}),e.jsx("p",{className:"text-sm text-gray-900 mt-1",children:Ot(v.pausedAt)})]})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-2 border-t border-orange-200",children:[f&&u&&e.jsxs(M,{onClick:u,className:"bg-green-600 hover:bg-green-700 text-white text-xs sm:text-sm h-8 sm:h-9",size:"sm",children:[e.jsx(gd,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-1.5"}),"Resume Now"]}),b&&h&&e.jsxs(M,{onClick:h,variant:"outline",className:"border-orange-300 text-orange-700 hover:bg-orange-50 text-xs sm:text-sm h-8 sm:h-9",size:"sm",children:[e.jsx(Re,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-1.5"}),"Request Resume"]})]})]})]}),t.claimDetails&&e.jsxs(G,{children:[e.jsx(te,{className:"pb-4",children:e.jsxs(se,{className:"flex items-center gap-2 text-base",children:[e.jsx(Te,{className:"w-5 h-5 text-purple-600"}),"Claim Management Details"]})}),e.jsxs(Y,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Activity Name"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.claimDetails.activityName||"N/A"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Activity Type"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.claimDetails.activityType||"N/A"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Location"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.claimDetails.location||"N/A"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Activity Date"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.claimDetails.activityDate?om(t.claimDetails.activityDate):"N/A"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Dealer Code"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.claimDetails.dealerCode||"N/A"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Dealer Name"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.claimDetails.dealerName||"N/A"})]})]}),t.claimDetails.requestDescription&&e.jsxs("div",{className:"pt-4 border-t border-gray-300",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Request Description"}),e.jsx("div",{className:"mt-2 bg-gray-50 p-3 rounded-lg",children:e.jsx(Ms,{content:t.claimDetails.requestDescription,className:"text-sm"})})]})]})]}),t.status==="closed"&&t.conclusionRemark&&e.jsxs(G,{children:[e.jsxs(te,{className:"bg-gradient-to-r from-gray-50 to-slate-50 border-b border-gray-200",children:[e.jsxs(se,{className:"flex items-center gap-2 text-base",children:[e.jsx(ve,{className:"w-5 h-5 text-gray-600"}),"Conclusion Remark"]}),e.jsx(he,{className:"mt-1 text-xs sm:text-sm",children:"Final summary of this closed request"})]}),e.jsxs(Y,{className:"pt-4",children:[e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-4",children:e.jsx(Ms,{content:t.conclusionRemark||"",className:"text-sm"})}),t.closureDate&&e.jsxs("div",{className:"mt-3 flex items-center justify-between text-xs text-gray-500 border-t border-gray-200 pt-3",children:[e.jsxs("span",{children:["Request closed on ",Ot(t.closureDate)]}),e.jsxs("span",{children:["By ",((w=t.initiator)==null?void 0:w.name)||"Initiator"]})]})]})]}),a&&e.jsxs(G,{"data-testid":"conclusion-remark-card",children:[e.jsx(te,{className:`bg-gradient-to-r border-b ${t.status==="rejected"?"from-red-50 to-rose-50 border-red-200":"from-green-50 to-emerald-50 border-green-200"}`,children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(se,{className:`flex items-center gap-2 text-base sm:text-lg ${t.status==="rejected"?"text-red-700":"text-green-700"}`,children:[e.jsx(ve,{className:`w-5 h-5 ${t.status==="rejected"?"text-red-600":"text-green-600"}`}),"Conclusion Remark - Final Step"]}),e.jsx(he,{className:"mt-1 text-xs sm:text-sm",children:t.status==="rejected"?"This request was rejected. Please review the AI-generated closure remark and finalize it to close this request.":"All approvals are complete. Please review and finalize the conclusion to close this request."})]}),e.jsxs(M,{variant:"outline",size:"sm",onClick:c,disabled:i,className:"gap-2 shrink-0","data-testid":"generate-ai-conclusion-button",children:[e.jsx(Lt,{className:`w-3.5 h-3.5 ${i?"animate-spin":""}`}),l?"Regenerate":"Generate with AI"]})]})}),e.jsx(Y,{className:"pt-4",children:i?e.jsx("div",{className:"flex items-center justify-center py-8","data-testid":"conclusion-loading",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Le,{className:"w-8 h-8 text-blue-600 animate-spin mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Preparing conclusion remark..."})]})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Conclusion Remark"}),l&&e.jsx("span",{className:"text-xs text-blue-600","data-testid":"ai-generated-label",children:"✓ System-generated suggestion (editable)"})]}),e.jsx(mm,{value:r,onChange:S=>n(S),placeholder:"Enter a professional conclusion remark summarizing the request outcome, key decisions, and approvals...",className:"text-sm",minHeight:"160px","data-testid":"conclusion-remark-textarea"}),e.jsx("p",{className:"text-xs text-blue-600 mt-1",children:"💡 Tip: You can paste formatted content (lists, tables) and the formatting will be preserved."}),e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsx("p",{className:"text-xs text-gray-500",children:"This will be the final summary for this request"}),e.jsxs("p",{className:"text-xs text-gray-500","data-testid":"character-count",children:[r?r.replace(/<[^>]*>/g,"").length:0," / 2000 characters"]})]})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs sm:text-sm font-semibold text-blue-900 mb-1.5",children:"Finalizing this request will:"}),e.jsxs("ul",{className:"text-xs sm:text-sm text-blue-800 space-y-0.5 pl-4",children:[e.jsx("li",{className:"list-disc",children:'Change request status to "CLOSED"'}),e.jsx("li",{className:"list-disc",children:"Notify all participants of closure"}),e.jsx("li",{className:"list-disc",children:"Move request to Closed Requests"}),e.jsx("li",{className:"list-disc",children:"Save conclusion remark permanently"})]})]}),e.jsx("div",{className:"flex gap-3 justify-end pt-3 border-t",children:e.jsx(M,{onClick:d,disabled:o||!r.trim(),className:"bg-green-600 hover:bg-green-700 text-white","data-testid":"finalize-close-button",children:o?e.jsxs(e.Fragment,{children:[e.jsx(Le,{className:"w-4 h-4 mr-2 animate-spin"}),"Finalizing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ve,{className:"w-4 h-4 mr-2"}),"Finalize & Close Request"]})})})]})})]})]})}function vr({delayDuration:t=0,...s}){return e.jsx(yp,{"data-slot":"tooltip-provider",delayDuration:t,...s})}function gn({...t}){return e.jsx(vr,{children:e.jsx(vp,{"data-slot":"tooltip",...t})})}function fn({...t}){return e.jsx(bp,{"data-slot":"tooltip-trigger",...t})}function yn({className:t,sideOffset:s=0,children:a,...r}){return e.jsx(jp,{children:e.jsxs(Np,{"data-slot":"tooltip-content",sideOffset:s,className:oe("bg-primary text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",t),...r,children:[a,e.jsx(wp,{className:"bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function Cs({className:t,...s}){return e.jsx("textarea",{"data-slot":"textarea",className:oe("resize-none border-gray-400 placeholder:text-muted-foreground bg-white text-gray-900 flex field-sizing-content min-h-16 w-full rounded-md border px-3 py-2 text-base transition-all outline-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm","hover:border-gray-500","focus-visible:border-re-light-green focus-visible:ring-0 focus-visible:outline-none","aria-invalid:ring-destructive/20 aria-invalid:border-destructive",t),...s})}const ml=t=>{if(t<8)return nt(t);const a=Math.floor(t/8),r=t%8;return r>0?`${a}d ${nt(r)}`:`${a}d`},py=(t,s)=>{if(s)return e.jsx(Re,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"});switch(t){case"approved":return e.jsx(ve,{className:"w-4 h-4 sm:w-5 sm:w-5 text-green-600"});case"rejected":return e.jsx(Ze,{className:"w-4 h-4 sm:w-5 sm:h-5 text-red-600"});case"paused":return e.jsx(fd,{className:"w-4 h-4 sm:w-5 sm:h-5 text-yellow-600"});case"pending":case"in-review":return e.jsx(De,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"});case"waiting":return e.jsx(De,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400"});default:return e.jsx(De,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400"})}};function xy({step:t,index:s,approval:a,isCurrentUser:r=!1,isInitiator:n=!1,isCurrentLevel:i=!1,onSkipApprover:o,onRefresh:l,testId:c="approval-step"}){const{user:d}=Bt(),[m,u]=g.useState(!1),[h,x]=g.useState(""),[p,y]=g.useState(!1),v=(a==null?void 0:a.breachReason)||(t==null?void 0:t.breachReason)||"";g.useEffect(()=>{m||x("")},[m]);const N=t.status==="pending"||t.status==="in-review",f=t.status==="approved",b=t.status==="rejected",j=t.status==="waiting",C=t.status==="paused",R=Number(t.tatHours||0),I=t.actualHours??0,T=f&&I?Math.max(0,R-I):0,E=R>0?I/R*100:0,w=E>=100,S=(d==null?void 0:d.role)==="ADMIN",D=qr(d),H=t.approverId===(d==null?void 0:d.userId),L=S||D||H,F=async()=>{var A,k;if(!h.trim()){fe.error("Breach Reason Required",{description:"Please enter a reason for the breach."});return}y(!0);try{await im(t.levelId,h.trim()),u(!1),x(""),fe.success("Breach Reason Updated",{description:"The breach reason has been saved and will appear in the TAT Breach Report.",duration:5e3}),l?await l():setTimeout(()=>{window.location.reload()},1e3)}catch(P){console.error("Error updating breach reason:",P);const _=((k=(A=P==null?void 0:P.response)==null?void 0:A.data)==null?void 0:k.error)||(P==null?void 0:P.message)||"Failed to update breach reason. Please try again.";fe.error("Failed to Update Breach Reason",{description:_,duration:5e3})}finally{y(!1)}};return e.jsxs("div",{className:`relative p-3 sm:p-4 md:p-5 rounded-lg border-2 transition-all ${t.isSkipped?"border-orange-500 bg-orange-50":N?"border-blue-500 bg-blue-50 shadow-md":f?"border-green-500 bg-green-50":b?"border-red-500 bg-red-50":j?"border-gray-300 bg-gray-50":"border-gray-200 bg-white"}`,"data-testid":`${c}-${t.step}`,children:[e.jsxs("div",{className:"flex items-start gap-2 sm:gap-3 md:gap-4",children:[e.jsx("div",{className:`p-2 sm:p-2.5 md:p-3 rounded-xl flex-shrink-0 ${t.isSkipped?"bg-orange-100":C?"bg-yellow-100":N?"bg-blue-100":f?"bg-green-100":b?"bg-red-100":j?"bg-gray-200":"bg-gray-100"}`,children:py(t.status,t.isSkipped)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-2 sm:gap-4 mb-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2 mb-2",children:[e.jsxs("h4",{className:"font-semibold text-gray-900 text-base sm:text-lg","data-testid":`${c}-approver-label`,children:["Approver ",s+1]}),e.jsx(Q,{variant:"outline",className:`text-xs shrink-0 capitalize ${t.isSkipped?"bg-orange-100 text-orange-800 border-orange-200":N?"bg-yellow-100 text-yellow-800 border-yellow-200":f?"bg-green-100 text-green-800 border-green-200":b?"bg-red-100 text-red-800 border-red-200":j?"bg-gray-200 text-gray-600 border-gray-300":"bg-gray-100 text-gray-800 border-gray-200"}`,"data-testid":`${c}-status-badge`,children:t.isSkipped?"skipped":t.status}),t.isSkipped&&t.skipReason&&e.jsx(vr,{delayDuration:200,children:e.jsxs(gn,{children:[e.jsx(fn,{asChild:!0,children:e.jsx("button",{type:"button",className:"inline-flex items-center justify-center cursor-pointer hover:opacity-80 transition-opacity",onClick:A=>A.stopPropagation(),children:e.jsx(Re,{className:"w-4 h-4 text-orange-600"})})}),e.jsxs(yn,{side:"top",className:"max-w-xs bg-orange-50 border-orange-200",children:[e.jsxs("p",{className:"text-xs font-semibold text-orange-900 mb-1 flex items-center gap-1",children:[e.jsx(Wo,{className:"w-3 h-3"}),"Skip Reason:"]}),e.jsx("p",{className:"text-xs text-gray-700",children:t.skipReason})]})]})}),f&&I&&e.jsx(Q,{className:"bg-green-600 text-white text-xs","data-testid":`${c}-completion-time`,children:ml(I)})]}),e.jsx("p",{className:"text-sm font-semibold text-gray-900","data-testid":`${c}-approver-name`,children:r?e.jsx("span",{className:"text-blue-600",children:"You"}):t.approver}),e.jsx("p",{className:"text-xs text-gray-600","data-testid":`${c}-role`,children:t.role})]}),e.jsxs("div",{className:"text-left sm:text-right flex-shrink-0",children:[e.jsx("p",{className:"text-xs text-gray-500 font-medium",children:"Turnaround Time (TAT)"}),e.jsxs("p",{className:"text-lg font-bold text-gray-900","data-testid":`${c}-tat-hours`,children:[R," hours"]})]})]}),f&&I!==void 0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Completed:"}),e.jsx("span",{className:"font-medium text-gray-900",children:t.timestamp?Ot(t.timestamp):"N/A"})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Completed in:"}),e.jsx("span",{className:"font-medium text-gray-900",children:ml(I)})]}),e.jsx("div",{className:"space-y-2",children:(()=>{const A=Math.min(100,E);return e.jsxs(e.Fragment,{children:[e.jsx(hs,{value:A,className:`h-2 bg-gray-200 ${w?"[&>div]:bg-red-600":"[&>div]:bg-green-600"}`,"data-testid":`${c}-progress-bar`}),e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:`font-semibold ${w?"text-red-600":"text-green-600"}`,children:[Math.round(A),"% of TAT used"]}),w&&L&&e.jsx(vr,{children:e.jsxs(gn,{children:[e.jsx(fn,{asChild:!0,children:e.jsx(M,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",onClick:()=>{x(v),u(!0)},children:e.jsx(dr,{className:"w-3 h-3"})})}),e.jsx(yn,{children:e.jsx("p",{children:v?"Edit breach reason":"Add breach reason"})})]})})]}),T>0&&e.jsxs("span",{className:"text-green-600 font-semibold",children:["Saved ",nt(T)]})]})]})})()}),w&&v&&e.jsxs("div",{className:"mt-4 p-3 sm:p-4 bg-red-50 border-l-4 border-red-500 rounded-r-lg",children:[e.jsxs("p",{className:"text-xs font-semibold text-red-700 mb-2 flex items-center gap-1.5",children:[e.jsx(dr,{className:"w-3.5 h-3.5"}),"Breach Reason:"]}),e.jsx("p",{className:"text-sm text-gray-700 leading-relaxed whitespace-pre-line",children:v})]}),t.comment&&e.jsxs("div",{className:"mt-4 p-3 sm:p-4 bg-blue-50 border-l-4 border-blue-500 rounded-r-lg",children:[e.jsxs("p",{className:"text-xs font-semibold text-gray-700 mb-2 flex items-center gap-1.5",children:[e.jsx(ws,{className:"w-3.5 h-3.5 text-blue-600"}),"Conclusion Remark:"]}),e.jsx("p",{className:"text-sm text-gray-700 italic leading-relaxed",children:t.comment})]})]}),i&&(N||C)&&(a==null?void 0:a.sla)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Due by:"}),e.jsx("span",{className:"font-medium text-gray-900",children:a.sla.deadline?ps(a.sla.deadline,!0):"Not set"})]}),e.jsxs("div",{className:`border rounded-lg p-3 ${a.sla.status==="critical"?"bg-orange-50 border-orange-200":a.sla.status==="breached"?"bg-red-50 border-red-200":"bg-yellow-50 border-yellow-200"}`,children:[e.jsxs("p",{className:"text-xs font-semibold text-gray-900 mb-3 flex items-center gap-2",children:[e.jsx(De,{className:"w-4 h-4"}),"Current Approver - Time Tracking"]}),e.jsxs("div",{className:"space-y-2 text-xs mb-3",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-600",children:"Time elapsed since assigned:"}),e.jsx("span",{className:"font-medium text-gray-900",children:a.sla.elapsedText})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-600",children:"Time used:"}),e.jsxs("span",{className:"font-medium text-gray-900",children:[a.sla.elapsedText," / ",nt(R)," allocated"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(hs,{value:a.sla.percentageUsed,className:`h-3 ${a.sla.status==="breached"?"[&>div]:bg-red-600":a.sla.status==="critical"?"[&>div]:bg-orange-600":"[&>div]:bg-yellow-600"}`,"data-testid":`${c}-sla-progress`}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:`text-xs font-semibold ${a.sla.status==="breached"?"text-red-600":a.sla.status==="critical"?"text-orange-600":"text-yellow-700"}`,children:["Progress: ",Math.min(100,a.sla.percentageUsed),"% of TAT used"]}),a.sla.status==="breached"&&L&&e.jsx(vr,{children:e.jsxs(gn,{children:[e.jsx(fn,{asChild:!0,children:e.jsx(M,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",onClick:()=>{x(v),u(!0)},children:e.jsx(dr,{className:"w-3 h-3"})})}),e.jsx(yn,{children:e.jsx("p",{children:v?"Edit breach reason":"Add breach reason"})})]})})]}),e.jsxs("span",{className:"text-xs font-medium text-gray-700",children:[a.sla.remainingText," remaining"]})]}),a.sla.status==="breached"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-xs font-semibold text-center text-red-600 flex items-center justify-center gap-1.5",children:[e.jsx(Wn,{className:"w-4 h-4"}),"Deadline Breached"]}),v&&e.jsxs("div",{className:"mt-3 p-3 bg-red-50 border-l-4 border-red-500 rounded-r-lg",children:[e.jsxs("p",{className:"text-xs font-semibold text-red-700 mb-2 flex items-center gap-1.5",children:[e.jsx(dr,{className:"w-3.5 h-3.5"}),"Breach Reason:"]}),e.jsx("p",{className:"text-sm text-gray-700 leading-relaxed whitespace-pre-line",children:v})]})]}),a.sla.status==="critical"&&e.jsxs("p",{className:"text-xs font-semibold text-center text-orange-600 flex items-center justify-center gap-1.5",children:[e.jsx(is,{className:"w-4 h-4"}),"Approaching Deadline"]})]})]})]}),j&&e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"bg-gray-100 border border-gray-300 rounded-lg p-3",children:[e.jsxs("p",{className:"text-xs text-gray-600 mb-1 flex items-center gap-1.5",children:[e.jsx(fd,{className:"w-3.5 h-3.5 text-gray-500"}),"Awaiting Previous Approval"]}),e.jsx("p",{className:"text-sm font-medium text-gray-700",children:"Will be assigned after previous step"}),e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Allocated ",R," hours for approval"]})]})}),b&&t.comment&&e.jsxs("div",{className:"mt-3 p-3 sm:p-4 bg-red-50 border-l-4 border-red-500 rounded-r-lg",children:[e.jsxs("p",{className:"text-xs font-semibold text-red-700 mb-2 flex items-center gap-1.5",children:[e.jsx(Ze,{className:"w-3.5 h-3.5"}),"Rejection Reason:"]}),e.jsx("p",{className:"text-sm text-gray-700 leading-relaxed",children:t.comment})]}),t.isSkipped&&t.skipReason&&e.jsxs("div",{className:"mt-3 p-3 sm:p-4 bg-orange-50 border-l-4 border-orange-500 rounded-r-lg",children:[e.jsxs("p",{className:"text-xs font-semibold text-orange-700 mb-2 flex items-center gap-1.5",children:[e.jsx(Wo,{className:"w-3.5 h-3.5"}),"Skip Reason:"]}),e.jsx("p",{className:"text-sm text-gray-700 leading-relaxed",children:t.skipReason}),t.timestamp&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Skipped on ",Ot(t.timestamp)]})]}),t.tatAlerts&&t.tatAlerts.length>0&&e.jsx("div",{className:"mt-2 sm:mt-3 space-y-2",children:t.tatAlerts.map((A,k)=>{var P,_,W,Z,ae,$;return e.jsx("div",{className:`p-2 sm:p-3 rounded-lg border ${A.isBreached?"bg-red-50 border-red-200":(A.thresholdPercentage||0)===75?"bg-orange-50 border-orange-200":"bg-yellow-50 border-yellow-200"}`,"data-testid":`${c}-tat-alert-${k}`,children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("div",{className:"flex-shrink-0 mt-0.5",children:[(A.thresholdPercentage||0)===50&&e.jsx(px,{className:"w-5 h-5 text-yellow-600"}),(A.thresholdPercentage||0)===75&&e.jsx(is,{className:"w-5 h-5 text-orange-600"}),(A.thresholdPercentage||0)===100&&e.jsx(Wn,{className:"w-5 h-5 text-red-600"})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1 sm:gap-2 mb-1",children:[e.jsxs("p",{className:"text-xs sm:text-sm font-semibold text-gray-900",children:["Reminder ",k+1," - ",A.thresholdPercentage||0,"% TAT"]}),e.jsx(Q,{variant:"outline",className:`text-[10px] sm:text-xs shrink-0 ${A.isBreached?"bg-red-100 text-red-800 border-red-300":"bg-amber-100 text-amber-800 border-amber-300"}`,children:A.isBreached?"BREACHED":"WARNING"})]}),e.jsxs("p",{className:"text-[10px] sm:text-xs md:text-sm text-gray-700 mt-1",children:[A.thresholdPercentage||0,"% of SLA breach reminder have been sent"]}),e.jsxs("div",{className:"mt-2 grid grid-cols-2 gap-1.5 sm:gap-2 text-[10px] sm:text-xs",children:[e.jsxs("div",{className:"bg-white/50 rounded px-2 py-1",children:[e.jsx("span",{className:"text-gray-500",children:"Allocated:"}),e.jsx("span",{className:"ml-1 font-medium text-gray-900",children:nt(Number(A.tatHoursAllocated||0))})]}),e.jsxs("div",{className:"bg-white/50 rounded px-2 py-1",children:[e.jsx("span",{className:"text-gray-500",children:"Elapsed:"}),e.jsxs("span",{className:"ml-1 font-medium text-gray-900",children:[nt(Number(A.tatHoursElapsed||0)),((P=A.metadata)==null?void 0:P.tatTestMode)&&e.jsxs("span",{className:"text-purple-600 ml-1",children:["(",(Number(A.tatHoursElapsed||0)*60).toFixed(0),"m)"]})]})]}),e.jsxs("div",{className:"bg-white/50 rounded px-2 py-1",children:[e.jsx("span",{className:"text-gray-500",children:"Remaining:"}),e.jsxs("span",{className:`ml-1 font-medium ${(A.tatHoursRemaining||0)<2?"text-red-600":"text-gray-900"}`,children:[nt(Number(A.tatHoursRemaining||0)),((_=A.metadata)==null?void 0:_.tatTestMode)&&e.jsxs("span",{className:"text-purple-600 ml-1",children:["(",(Number(A.tatHoursRemaining||0)*60).toFixed(0),"m)"]})]})]}),e.jsxs("div",{className:"bg-white/50 rounded px-2 py-1",children:[e.jsx("span",{className:"text-gray-500",children:"Due by:"}),e.jsx("span",{className:"ml-1 font-medium text-gray-900",children:A.expectedCompletionTime?ps(A.expectedCompletionTime,!0):"N/A"})]})]}),e.jsxs("div",{className:"mt-2 pt-2 border-t border-gray-200",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1",children:[e.jsx("p",{className:"text-[10px] sm:text-xs text-gray-500",children:"Reminder sent by system automatically"}),(((W=A.metadata)==null?void 0:W.testMode)||((Z=A.metadata)==null?void 0:Z.tatTestMode))&&e.jsx(Q,{variant:"outline",className:"bg-purple-50 text-purple-700 border-purple-300 text-[10px] px-1.5 py-0 shrink-0",children:"TEST MODE"})]}),e.jsxs("p",{className:"text-[10px] sm:text-xs text-gray-600 font-medium mt-0.5",children:["Sent at: ",A.alertSentAt?Ot(A.alertSentAt):"N/A"]}),(((ae=A.metadata)==null?void 0:ae.testMode)||(($=A.metadata)==null?void 0:$.tatTestMode))&&e.jsx("p",{className:"text-[10px] text-purple-600 mt-1 italic",children:"Note: Test mode active (1 hour = 1 minute)"})]})]})]})},k)})}),t.timestamp&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:[f?"Approved":b?"Rejected":"Actioned"," on ",Ot(t.timestamp)]}),n&&(N||t.status==="pending")&&!f&&!b&&t.levelId&&o&&e.jsxs("div",{className:"mt-2 sm:mt-3 pt-2 sm:pt-3 border-t border-gray-200",children:[e.jsxs(M,{variant:"outline",size:"sm",className:"w-full border-orange-300 text-orange-700 hover:bg-orange-50 h-9 sm:h-10 text-xs sm:text-sm",onClick:()=>o({levelId:t.levelId,approverName:t.approver,levelNumber:t.step}),"data-testid":`${c}-skip-button`,children:[e.jsx(Re,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Skip This Approver"]}),e.jsx("p",{className:"text-[10px] sm:text-xs text-gray-500 mt-1 text-center",children:"Skip if approver is unavailable and move to next level"})]})]})]}),e.jsx(ot,{open:m,onOpenChange:u,children:e.jsxs(Je,{className:"sm:max-w-[500px]",children:[e.jsxs(lt,{children:[e.jsx(et,{children:v?"Edit Breach Reason":"Add Breach Reason"}),e.jsx(Zt,{children:v?"Update the reason for the TAT breach. This will be reflected in the TAT Breach Report.":"Please provide a reason for the TAT breach. This will be reflected in the TAT Breach Report."})]}),e.jsxs("div",{className:"py-4",children:[e.jsx(Cs,{placeholder:"Enter the reason for the breach...",value:h,onChange:A=>x(A.target.value),className:"min-h-[100px]",maxLength:500}),e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:[h.length,"/500 characters"]})]}),e.jsxs(Tt,{children:[e.jsx(M,{variant:"outline",onClick:()=>{u(!1),x("")},disabled:p,children:"Cancel"}),e.jsx(M,{onClick:F,disabled:!h.trim()||p,className:"bg-red-600 hover:bg-red-700",children:p?"Saving...":"Save Reason"})]})]})})]})}function gy({request:t,user:s,isInitiator:a,onSkipApprover:r,onRefresh:n}){return e.jsxs(G,{children:[e.jsx(te,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-4",children:[e.jsxs("div",{children:[e.jsxs(se,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Us,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Approval Workflow"]}),e.jsx(he,{className:"mt-1 sm:mt-2 text-xs sm:text-sm",children:"Track the approval progress through each step"})]}),t.totalSteps&&(()=>{var x;const i=t.totalSteps||1,o=t.currentStepRaw!==void 0?t.currentStepRaw:t.currentStep||1,l=((x=t.approvalFlow)==null?void 0:x.filter(p=>{const y=(p.status||"").toLowerCase();return y==="approved"||y==="rejected"}).length)||0,c=l>=i,d=(t.status||"").toLowerCase(),m=d==="approved"||d==="rejected"||d==="closed",u=o>i,h=Math.min(Math.max(1,o),i);return u?e.jsxs(Q,{variant:"outline",className:"font-medium text-xs sm:text-sm shrink-0 bg-blue-50 text-blue-700 border-blue-200",children:["Closure Step - ",l," of ",i," steps completed"]}):m||c?e.jsxs(Q,{variant:"outline",className:"font-medium text-xs sm:text-sm shrink-0 bg-green-50 text-green-700 border-green-200",children:["Completed - ",l," of ",i," steps"]}):e.jsxs(Q,{variant:"outline",className:"font-medium text-xs sm:text-sm shrink-0",children:["Step ",h," of ",i," - ",l," completed"]})})()]})}),e.jsx(Y,{children:t.approvalFlow&&t.approvalFlow.length>0?e.jsx("div",{className:"space-y-4 sm:space-y-6",children:t.approvalFlow.map((i,o)=>{var x,p,y;const l=(x=t.approvals)==null?void 0:x.find(v=>v.levelId===i.levelId),c=(p=s==null?void 0:s.email)==null?void 0:p.toLowerCase(),d=(y=i.approverEmail)==null?void 0:y.toLowerCase(),m=c&&d&&c===d,u=t.currentStepRaw!==void 0?t.currentStepRaw:t.currentStep||1,h=i.step===u;return e.jsx(xy,{step:i,index:o,approval:l,isCurrentUser:m,isInitiator:a,isCurrentLevel:h,onSkipApprover:r,onRefresh:n,testId:"workflow-step"},o)})}):e.jsx("p",{className:"text-sm text-gray-500 text-center py-8","data-testid":"no-workflow-steps",children:"No workflow steps defined"})})]})}const fy=t=>{const s=(t||"").toLowerCase();return s.includes("image")||s.includes("pdf")||s.includes("jpg")||s.includes("jpeg")||s.includes("png")||s.includes("gif")};function ul({document:t,onPreview:s,onDownload:a,showPreview:r=!0,testId:n="document-card"}){return e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors","data-testid":`${n}-${t.documentId}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-blue-100 rounded-lg",children:e.jsx(Te,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900","data-testid":`${n}-name`,children:t.name}),e.jsxs("p",{className:"text-xs text-gray-500","data-testid":`${n}-metadata`,children:[t.size," • Uploaded by ",t.uploadedBy," on ",Ot(t.uploadedAt)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&fy(t.fileType)&&s&&e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>s({fileName:t.name,fileType:t.fileType,documentId:t.documentId,fileSize:t.sizeBytes}),title:"Preview file","data-testid":`${n}-preview-btn`,children:e.jsx(At,{className:"w-4 h-4"})}),a&&e.jsx(M,{variant:"ghost",size:"sm",onClick:async()=>{if(!t.documentId){alert("Document ID not available");return}try{await a(t.documentId)}catch{alert("Failed to download document")}},title:"Download file","data-testid":`${n}-download-btn`,children:e.jsx(ns,{className:"w-4 h-4"})})]})]})}function yy({request:t,workNoteAttachments:s,uploadingDocument:a,documentPolicy:r,triggerFileInput:n,setPreviewDocument:i,downloadDocument:o}){return e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[e.jsxs(G,{children:[e.jsx(te,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-4",children:[e.jsxs("div",{children:[e.jsxs(se,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Te,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Documents"]}),e.jsx(he,{className:"text-xs sm:text-sm mt-1",children:"Documents attached while creating the request"})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsxs(M,{size:"sm",onClick:n,disabled:a||t.status==="closed",className:"gap-1 sm:gap-2 h-8 sm:h-9 text-xs sm:text-sm shrink-0","data-testid":"upload-document-btn",children:[e.jsx(ba,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),a?"Uploading...":t.status==="closed"?"Closed":"Upload",e.jsx("span",{className:"hidden sm:inline",children:t.status==="closed"?"":"Document"})]}),e.jsxs("p",{className:"text-xs text-gray-500 whitespace-nowrap",children:["Max ",r.maxFileSizeMB,"MB"]})]})]})}),e.jsx(Y,{children:t.documents&&t.documents.length>0?e.jsx("div",{className:"space-y-3",children:t.documents.map((l,c)=>e.jsx(ul,{document:l,onPreview:d=>i(d),onDownload:o,testId:"request-document"},c))}):e.jsx("p",{className:"text-sm text-gray-500 text-center py-8","data-testid":"no-documents",children:"No documents uploaded yet"})})]}),e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsxs(se,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(ws,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"Work Note Attachments"]}),e.jsx(he,{className:"text-xs sm:text-sm",children:"Files shared in work notes discussions"})]}),e.jsx(Y,{children:s&&s.length>0?e.jsx("div",{className:"space-y-3",children:s.map((l,c)=>e.jsx(ul,{document:{documentId:l.attachmentId||"",name:l.name,fileType:l.type||"",size:l.size?`${(l.size/1024).toFixed(1)} KB`:"Unknown size",sizeBytes:l.size,uploadedBy:l.uploadedBy,uploadedAt:l.uploadedAt},onPreview:d=>i(d),onDownload:async d=>{const{downloadWorkNoteAttachment:m}=require("@/services/workflowApi");await m(d)},testId:"worknote-attachment"},l.attachmentId||c))}):e.jsx("p",{className:"text-sm text-gray-500 text-center py-8","data-testid":"no-attachments",children:"No files shared in work notes yet"})})]})]})}function vy({request:t}){return e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsxs(se,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(as,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Activity Timeline"]}),e.jsx(he,{className:"text-xs sm:text-sm",children:"Complete audit trail of all request activities"})]}),e.jsx(Y,{children:e.jsx("div",{className:"space-y-4 sm:space-y-6",children:t.auditTrail&&t.auditTrail.length>0?t.auditTrail.map((s,a)=>e.jsxs("div",{className:"flex items-start gap-4","data-testid":`activity-item-${a}`,children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center",children:X0(s.type)})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"bg-white rounded-lg border border-gray-200 p-4 shadow-sm",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"font-semibold text-gray-900",children:s.action}),e.jsx("span",{className:"text-xs text-gray-500 whitespace-nowrap ml-4",children:Ot(s.timestamp)})]}),e.jsx("div",{className:"text-sm text-gray-600 leading-relaxed",children:e.jsx("p",{className:"whitespace-pre-line break-words",children:s.details})})]})})]},a)):e.jsxs("div",{className:"text-center py-12","data-testid":"no-activity",children:[e.jsx(as,{className:"w-12 h-12 text-gray-400 mx-auto mb-4"}),e.jsx("p",{className:"text-sm text-gray-500",children:"No activity recorded yet"}),e.jsx("p",{className:"text-xs text-gray-400 mt-2",children:"Actions and updates will appear here"})]})})})]})}function qi({fileName:t,fileType:s,fileUrl:a,fileSize:r,attachmentId:n,onDownload:i,open:o,onClose:l}){const[c,d]=g.useState(100),[m,u]=g.useState(0),[h,x]=g.useState(null),[p,y]=g.useState(!1),[v,N]=g.useState(null),f=s.toLowerCase().includes("image")||s.toLowerCase().includes("png")||s.toLowerCase().includes("jpg")||s.toLowerCase().includes("jpeg")||s.toLowerCase().includes("gif")||s.toLowerCase().includes("webp"),b=s.toLowerCase().includes("pdf"),j=f||b;g.useEffect(()=>{if(!o||!j||!a){x(null);return}return(async()=>{y(!0),N(null);try{const w=localStorage.getItem("accessToken");let S=a;a.startsWith("/")&&!a.startsWith("//")&&(S=`${window.location.origin}${a}`);const D=await fetch(S,{headers:{Authorization:`Bearer ${w}`,Accept:b?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!D.ok){const F=await D.text().catch(()=>"");throw new Error(`Failed to load file: ${D.status} ${D.statusText}. ${F}`)}const H=await D.blob();if(H.size===0)throw new Error("File is empty or could not be loaded");b&&!H.type.includes("pdf")&&H.type!=="application/octet-stream"&&console.warn(`Expected PDF but got ${H.type}`);const L=window.URL.createObjectURL(H);x(L)}catch(w){console.error("Failed to load file for preview:",w),N(w instanceof Error?w.message:"Failed to load file for preview")}finally{y(!1)}})(),()=>{h&&(window.URL.revokeObjectURL(h),x(null))}},[o,a,j,b]);const C=async()=>{if(i&&n)try{await i(n)}catch{alert("Failed to download file")}},R=()=>d(E=>Math.min(E+25,200)),I=()=>d(E=>Math.max(E-25,50)),T=()=>u(E=>(E+90)%360);return e.jsx(ot,{open:o,onOpenChange:l,children:e.jsx(Je,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(lt,{className:"pb-4 flex-shrink-0 pr-8",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx(At,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(et,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:t}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[s," ",r&&`• ${(r/1024).toFixed(1)} KB`]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mr-2",children:[f&&e.jsxs("div",{className:"flex items-center gap-1 mr-2",children:[e.jsx(M,{variant:"ghost",size:"sm",onClick:I,disabled:c<=50,title:"Zoom out",className:"h-8 w-8 p-0",children:e.jsx(xx,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs sm:text-sm text-gray-600 min-w-[3rem] text-center",children:[c,"%"]}),e.jsx(M,{variant:"ghost",size:"sm",onClick:R,disabled:c>=200,title:"Zoom in",className:"h-8 w-8 p-0",children:e.jsx(gx,{className:"h-4 w-4"})}),e.jsx(M,{variant:"ghost",size:"sm",onClick:T,title:"Rotate",className:"h-8 w-8 p-0",children:e.jsx(fx,{className:"h-4 w-4"})})]}),i&&n&&e.jsxs(M,{variant:"outline",size:"sm",onClick:C,className:"gap-2 h-9",children:[e.jsx(ns,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Download"})]})]})]})}),e.jsx("div",{className:"file-preview-body bg-gray-100 rounded-lg p-2 sm:p-4",children:p?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full",children:[e.jsx(Le,{className:"w-12 h-12 text-blue-600 animate-spin mb-4"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Loading preview..."})]}):v?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-red-100 rounded-full flex items-center justify-center mb-4",children:e.jsx(ft,{className:"w-10 h-10 text-red-600"})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Preview Failed"}),e.jsx("p",{className:"text-sm text-gray-600 mb-6",children:v}),i&&n&&e.jsxs(M,{onClick:C,className:"gap-2",children:[e.jsx(ns,{className:"h-4 w-4"}),"Download ",t]})]}):j&&h?e.jsxs(e.Fragment,{children:[f&&e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("img",{src:h,alt:t,style:{transform:`scale(${c/100}) rotate(${m}deg)`,transition:"transform 0.2s ease-in-out",maxWidth:"100%",maxHeight:"100%",objectFit:"contain"},className:"rounded-lg shadow-lg"})}),b&&e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("iframe",{src:h,className:"w-full h-full rounded-lg border-0",title:t,style:{minHeight:"70vh",height:"100%"},onError:()=>{N("Failed to load PDF preview")}})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-gray-200 rounded-full flex items-center justify-center mb-4",children:e.jsx(At,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Preview Not Available"}),e.jsx("p",{className:"text-sm text-gray-600 mb-6",children:"This file type cannot be previewed. Please download to view."}),i&&n&&e.jsxs(M,{onClick:C,className:"gap-2",children:[e.jsx(ns,{className:"h-4 w-4"}),"Download ",t]})]})})]})})})}function pm({open:t,onClose:s,violations:a,policyDetails:r}){return e.jsx(ot,{open:t,onOpenChange:s,children:e.jsxs(Je,{className:"sm:max-w-lg",children:[e.jsxs(lt,{children:[e.jsxs(et,{className:"flex items-center gap-2",children:[e.jsx(Re,{className:"w-5 h-5 text-red-600"}),"Policy Violation"]}),e.jsx(Zt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-gray-700",children:"The following policy violations were detected:"}),e.jsx("div",{className:"space-y-2 max-h-60 overflow-y-auto",children:a.map((n,i)=>e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3",children:[e.jsx("p",{className:"font-medium text-red-900 text-sm",children:n.type}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:n.message}),n.currentValue!==void 0&&n.maxValue!==void 0&&e.jsxs("p",{className:"text-xs text-red-600 mt-1 font-semibold",children:["Current: ",n.currentValue," / Maximum: ",n.maxValue]})]},i))}),r&&e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-sm text-blue-800 font-semibold mb-1",children:"System Policy:"}),e.jsxs("ul",{className:"text-xs text-blue-700 space-y-1 list-disc list-inside",children:[r.maxApprovalLevels!==void 0&&e.jsxs("li",{children:["Maximum approval levels: ",r.maxApprovalLevels]}),r.maxParticipants!==void 0&&e.jsxs("li",{children:["Maximum participants per request: ",r.maxParticipants]}),r.allowSpectators!==void 0&&e.jsxs("li",{children:["Allow adding spectators: ",r.allowSpectators?"Yes":"No"]}),r.maxSpectators!==void 0&&e.jsxs("li",{children:["Maximum spectators per request: ",r.maxSpectators]})]})]})]})})]}),e.jsx(Tt,{children:e.jsx(M,{onClick:s,className:"w-full sm:w-auto",children:"OK"})})]})})}function xm({open:t,onClose:s,onConfirm:a,existingParticipants:r=[]}){const[n,i]=g.useState(""),[o,l]=g.useState(!1),[c,d]=g.useState([]),[m,u]=g.useState(!1),[h,x]=g.useState(null),p=g.useRef(null),y=g.useRef(null),[v,N]=g.useState({open:!1,type:"error",email:"",message:""}),[f,b]=g.useState({open:!1,violations:[]}),[j,C]=g.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20});g.useEffect(()=>{t&&(async()=>{var S;try{const D=await ra("WORKFLOW_SHARING"),H=await ra("TAT_SETTINGS"),L=[...D,...H],F={};L.forEach(A=>{F[A.configKey]=A.configValue}),C({maxApprovalLevels:parseInt(F.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(F.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((S=F.ALLOW_ADD_SPECTATOR)==null?void 0:S.toLowerCase())==="true",maxSpectators:parseInt(F.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(D){console.error("Failed to load system policy:",D)}})()},[t]);const R=async()=>{var k,P;const w=n.trim().toLowerCase();if(!w){N({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(w)){N({open:!0,type:"error",email:w,message:"Please enter a valid email address"});return}const D=r.find(_=>(_.email||"").toLowerCase()===w);if(D){const _=((k=D.participantType)==null?void 0:k.toUpperCase())||"PARTICIPANT",W=D.name||w;if(_==="INITIATOR"){N({open:!0,type:"error",email:w,message:`${W} is the request initiator and cannot be added as a spectator.`});return}else if(_==="APPROVER"){N({open:!0,type:"error",email:w,message:`${W} is already an approver on this request and cannot be added as a spectator.`});return}else if(_==="SPECTATOR"){N({open:!0,type:"error",email:w,message:`${W} is already a spectator on this request.`});return}else{N({open:!0,type:"error",email:w,message:`${W} is already a participant on this request.`});return}}const H=[];j.allowSpectators||H.push({type:"Spectators Not Allowed",message:"Adding spectators is not allowed by system policy."});const F=r.filter(_=>(_.participantType||"").toUpperCase()==="SPECTATOR").length;F>=j.maxSpectators&&H.push({type:"Maximum Spectators Exceeded",message:"This request has reached the maximum number of spectators allowed.",currentValue:F,maxValue:j.maxSpectators});const A=r.length+1;if(A>j.maxParticipants&&H.push({type:"Maximum Participants Exceeded",message:"Adding this spectator would exceed the maximum participants limit.",currentValue:A,maxValue:j.maxParticipants}),H.length>0){b({open:!0,violations:H});return}if(!h||h.email.toLowerCase()!==w)try{const W=((P=(await xs(w,1)).data)==null?void 0:P.data)||[];if(W.length===0){N({open:!0,type:"not-found",email:w,message:""});return}const Z=W[0];await bs({userId:Z.userId,email:Z.email,displayName:Z.displayName,firstName:Z.firstName,lastName:Z.lastName,department:Z.department,phone:Z.phone,mobilePhone:Z.mobilePhone,designation:Z.designation,jobTitle:Z.jobTitle,manager:Z.manager,employeeId:Z.employeeId,employeeNumber:Z.employeeNumber,secondEmail:Z.secondEmail,location:Z.location})}catch(_){console.error("Failed to validate spectator:",_),N({open:!0,type:"error",email:w,message:"Failed to validate user. Please try again."});return}try{l(!0),await a(w),i(""),x(null),s()}catch(_){console.error("Failed to add spectator:",_)}finally{l(!1)}},I=()=>{o||(i(""),x(null),d([]),u(!1),s())};g.useEffect(()=>{c.length>0&&y.current&&y.current.scrollTo({top:y.current.scrollHeight,behavior:"smooth"})},[c.length]),g.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]);const T=w=>{if(i(w),h&&h.email.toLowerCase()!==w.toLowerCase()&&x(null),p.current&&clearTimeout(p.current),!w||!w.startsWith("@")||w.length<2){d([]),u(!1);return}u(!0),p.current=setTimeout(async()=>{var S;try{const D=w.slice(1),L=((S=(await xs(D,10)).data)==null?void 0:S.data)||[];d(L)}catch(D){console.error("Search failed:",D),d([])}finally{u(!1)}},300)},E=async w=>{try{await bs({userId:w.userId,email:w.email,displayName:w.displayName,firstName:w.firstName,lastName:w.lastName,department:w.department,phone:w.phone,mobilePhone:w.mobilePhone,designation:w.designation,jobTitle:w.jobTitle,manager:w.manager,employeeId:w.employeeId,employeeNumber:w.employeeNumber,secondEmail:w.secondEmail,location:w.location}),i(w.email),x(w),d([]),u(!1)}catch(S){console.error("Failed to ensure user exists:",S),N({open:!0,type:"error",email:w.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(ot,{open:t,onOpenChange:I,children:[e.jsxs(Je,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:I,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:o,children:[e.jsx(ft,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(lt,{className:"px-6 pt-6 pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center",children:e.jsx(At,{className:"w-5 h-5 text-purple-600"})}),e.jsx(et,{className:"text-xl font-bold text-gray-900",children:"Add Spectator"})]})}),e.jsxs("div",{ref:y,className:"space-y-4 px-6 py-4 pb-8 overflow-y-auto flex-1",children:[e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed",children:"Add a spectator to this request. They will receive notifications but cannot approve or reject."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Email Address"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ri,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(xe,{type:"text",placeholder:"@username or user@example.com",value:n,onChange:w=>T(w.target.value),className:"pl-10 h-11 border-gray-300",disabled:o,autoFocus:!0}),(m||c.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg max-h-60 overflow-auto",children:m?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):c.length>0?e.jsx("ul",{className:"divide-y",children:c.map(w=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>E(w),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(jt,{className:"h-8 w-8",children:e.jsx(Nt,{className:"bg-purple-100 text-purple-800 text-xs font-semibold",children:(w.displayName||w.email).split(" ").map(S=>S[0]).join("").slice(0,2).toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:w.displayName||[w.firstName,w.lastName].filter(Boolean).join(" ")||w.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:w.email}),w.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:w.designation})]})]})},w.userId))}):null})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Type ",e.jsx("span",{className:"font-semibold",children:"@username"})," to search for users, or enter email directly."]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(M,{type:"button",variant:"outline",onClick:I,className:"flex-1 h-11 border-gray-300",disabled:o,children:"Cancel"}),e.jsxs(M,{type:"button",onClick:R,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:o||!n.trim(),children:[e.jsx(At,{className:"w-4 h-4 mr-2"}),o?"Adding...":"Add Spectator"]})]})]}),e.jsx(ot,{open:v.open,onOpenChange:w=>N(S=>({...S,open:w})),children:e.jsxs(Je,{className:"sm:max-w-md",children:[e.jsxs(lt,{children:[e.jsx(et,{className:"flex items-center gap-2",children:v.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(Re,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Re,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(Zt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[v.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:v.email})," was not found in the organization directory."]}),e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3 space-y-2",children:[e.jsx("p",{className:"text-sm text-red-800 font-semibold",children:"Please verify:"}),e.jsxs("ul",{className:"text-sm text-red-700 space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"Email address is spelled correctly"}),e.jsx("li",{children:"User exists in Okta/SSO system"}),e.jsx("li",{children:"User has an active account"})]})]}),e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-blue-800 flex items-center gap-1",children:[e.jsx(Ur,{className:"w-4 h-4"}),e.jsx("strong",{children:"Tip:"})," Use ",e.jsx("span",{className:"font-mono bg-blue-100 px-1 rounded",children:"@"})," sign to search users from the directory."]})})]}),v.type==="error"&&e.jsxs(e.Fragment,{children:[v.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:v.email}),"."]}),v.message&&e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-3",children:e.jsx("p",{className:"text-sm text-gray-700",children:v.message})})]})]})})]}),e.jsx(Tt,{children:e.jsx(M,{onClick:()=>N(w=>({...w,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(pm,{open:f.open,onClose:()=>b({open:!1,violations:[]}),violations:f.violations,policyDetails:{maxApprovalLevels:j.maxApprovalLevels,maxParticipants:j.maxParticipants,allowSpectators:j.allowSpectators,maxSpectators:j.maxSpectators}})]})}function gm({open:t,onClose:s,onConfirm:a,existingParticipants:r=[],currentLevels:n=[]}){const[i,o]=g.useState(""),[l,c]=g.useState(24),[d,m]=g.useState(null),[u,h]=g.useState(!1),[x,p]=g.useState([]),[y,v]=g.useState(!1),[N,f]=g.useState(null),b=g.useRef(null),j=g.useRef(null),[C,R]=g.useState({open:!1,type:"error",email:"",message:""}),I=n.filter(A=>A&&(A.status==="approved"||A.status==="rejected"||A.status==="skipped")),T=Math.max(1,I.length+1),E=Math.max(1,n.length+1),w=E>=T?Array.from({length:E-T+1},(A,k)=>T+k):[T];g.useEffect(()=>{w.length>0&&d===null&&m(w[0]||null)},[w.length,d]);const S=async()=>{var _,W;const A=i.trim().toLowerCase();if(!A){R({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(A)){R({open:!0,type:"error",email:A,message:"Please enter a valid email address"});return}if(!l||l<=0){R({open:!0,type:"error",email:"",message:"Please enter valid TAT hours (minimum 1 hour)"});return}if(l>720){R({open:!0,type:"error",email:"",message:"TAT hours cannot exceed 720 hours (30 days)"});return}if(!d){R({open:!0,type:"error",email:"",message:"Please select an approval level"});return}if(d(Z.email||"").toLowerCase()===A);if(P){const Z=((_=P.participantType)==null?void 0:_.toUpperCase())||"PARTICIPANT",ae=P.name||A;if(Z==="INITIATOR"){R({open:!0,type:"error",email:A,message:`${ae} is the request initiator and cannot be added as an approver.`});return}else if(Z==="APPROVER"){R({open:!0,type:"error",email:A,message:`${ae} is already an approver on this request.`});return}else if(Z==="SPECTATOR"){R({open:!0,type:"error",email:A,message:`${ae} is currently a spectator on this request and cannot be added as an approver. Please remove them as spectator first.`});return}else{R({open:!0,type:"error",email:A,message:`${ae} is already a participant on this request.`});return}}if(!N||N.email.toLowerCase()!==A)try{const ae=((W=(await xs(A,1)).data)==null?void 0:W.data)||[];if(ae.length===0){R({open:!0,type:"not-found",email:A,message:""});return}const $=ae[0];await bs({userId:$.userId,email:$.email,displayName:$.displayName,firstName:$.firstName,lastName:$.lastName,department:$.department,phone:$.phone,mobilePhone:$.mobilePhone,designation:$.designation,jobTitle:$.jobTitle,manager:$.manager,employeeId:$.employeeId,employeeNumber:$.employeeNumber,secondEmail:$.secondEmail,location:$.location})}catch(Z){console.error("Failed to validate approver:",Z),R({open:!0,type:"error",email:A,message:"Failed to validate user. Please try again."});return}try{h(!0),await a(A,l,d),o(""),c(24),m(null),f(null),s()}catch(Z){console.error("Failed to add approver:",Z)}finally{h(!1)}},D=()=>{u||(o(""),c(24),m(null),f(null),p([]),v(!1),s())},H=A=>{const k=A.toLowerCase();return k==="approved"?e.jsx(ve,{className:"w-4 h-4 text-green-600"}):k==="rejected"?e.jsx(Ze,{className:"w-4 h-4 text-red-600"}):k==="skipped"?e.jsx(Re,{className:"w-4 h-4 text-orange-600"}):k==="in-review"||k==="pending"?e.jsx(De,{className:"w-4 h-4 text-blue-600"}):e.jsx(De,{className:"w-4 h-4 text-gray-400"})};g.useEffect(()=>{x.length>0&&j.current&&j.current.scrollTo({top:j.current.scrollHeight,behavior:"smooth"})},[x.length]),g.useEffect(()=>()=>{b.current&&clearTimeout(b.current)},[]);const L=A=>{if(o(A),N&&N.email.toLowerCase()!==A.toLowerCase()&&f(null),b.current&&clearTimeout(b.current),!A||!A.startsWith("@")||A.length<2){p([]),v(!1);return}v(!0),b.current=setTimeout(async()=>{var k;try{const P=A.slice(1),W=((k=(await xs(P,10)).data)==null?void 0:k.data)||[];p(W)}catch(P){console.error("Search failed:",P),p([])}finally{v(!1)}},300)},F=async A=>{try{await bs({userId:A.userId,email:A.email,displayName:A.displayName,firstName:A.firstName,lastName:A.lastName,department:A.department,phone:A.phone,mobilePhone:A.mobilePhone,designation:A.designation,jobTitle:A.jobTitle,manager:A.manager,employeeId:A.employeeId,employeeNumber:A.employeeNumber,secondEmail:A.secondEmail,location:A.location}),o(A.email),f(A),p([]),v(!1)}catch(k){console.error("Failed to ensure user exists:",k),R({open:!0,type:"error",email:A.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(ot,{open:t,onOpenChange:D,children:[e.jsxs(Je,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:D,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:u,children:[e.jsx(ft,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(lt,{className:"px-6 pt-6 pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center",children:e.jsx(at,{className:"w-5 h-5 text-blue-600"})}),e.jsx(et,{className:"text-xl font-bold text-gray-900",children:"Add Approver"})]})}),e.jsxs("div",{ref:j,className:"space-y-4 px-6 py-4 pb-8 overflow-y-auto flex-1",children:[e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed",children:"Add a new approver at a specific level. Existing approvers at and after the selected level will be shifted down."}),n.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{className:"text-sm font-semibold text-gray-700",children:"Current Approval Levels"}),e.jsx("div",{className:"max-h-40 overflow-y-auto space-y-2 border rounded-lg p-3 bg-gray-50",children:n.map(A=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-md ${A.status==="approved"?"bg-green-100 border border-green-200":A.status==="rejected"?"bg-red-100 border border-red-200":A.status==="skipped"?"bg-orange-100 border border-orange-200":"bg-white border border-gray-200"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-blue-600 text-white text-xs font-semibold flex items-center justify-center",children:A.levelNumber}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:A.approverName}),e.jsxs("p",{className:"text-xs text-gray-500",children:[A.tatHours,"h TAT"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[H(A.status),e.jsx(Q,{variant:"outline",className:`text-xs ${A.status==="approved"?"bg-green-50 text-green-700 border-green-300":A.status==="rejected"?"bg-red-50 text-red-700 border-red-300":A.status==="skipped"?"bg-orange-50 text-orange-700 border-orange-300":"bg-blue-50 text-blue-700 border-blue-300"}`,children:A.status})]})]},A.levelNumber))}),e.jsxs("p",{className:"text-xs text-gray-500",children:["ℹ️ New approver can only be added at level ",T," or higher (after completed levels)"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{className:"text-sm font-medium text-gray-700",children:"Approval Level *"}),e.jsxs(we,{value:(d==null?void 0:d.toString())||"",onValueChange:A=>m(Number(A)),disabled:u,children:[e.jsx(Se,{className:"h-11 border-gray-300",children:e.jsx(Ce,{placeholder:"Select level"})}),e.jsx(Ae,{children:w.map(A=>e.jsx(V,{value:A.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gt,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Level ",A]}),A<=n.length&&e.jsxs("span",{className:"text-xs text-gray-500",children:["(will shift existing Level ",A,")"]})]})},A))})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Choose where to insert the new approver. Existing levels will be automatically shifted."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{className:"text-sm font-medium text-gray-700",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{type:"number",min:"1",max:"720",value:l,onChange:A=>c(Number(A.target.value)),className:"h-11 border-gray-300 flex-1",disabled:u,placeholder:"24"}),e.jsxs("div",{className:"flex items-center gap-1 text-sm text-gray-600 bg-gray-100 px-3 h-11 rounded-md border border-gray-300",children:[e.jsx(De,{className:"w-4 h-4"}),"hours"]})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Maximum time for this approver to respond (1-720 hours)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Email Address *"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ri,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(xe,{type:"text",placeholder:"@username or user@example.com",value:i,onChange:A=>L(A.target.value),className:"pl-10 h-11 border-gray-300",disabled:u,autoFocus:!0}),(y||x.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg max-h-60 overflow-auto",children:y?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):x.length>0?e.jsx("ul",{className:"divide-y",children:x.map(A=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>F(A),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(jt,{className:"h-8 w-8",children:e.jsx(Nt,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:(A.displayName||A.email).split(" ").map(k=>k[0]).join("").slice(0,2).toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:A.displayName||[A.firstName,A.lastName].filter(Boolean).join(" ")||A.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:A.email}),A.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:A.designation})]})]})},A.userId))}):null})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Type ",e.jsx("span",{className:"font-semibold",children:"@username"})," to search for users, or enter email directly."]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(M,{type:"button",variant:"outline",onClick:D,className:"flex-1 h-11 border-gray-300",disabled:u,children:"Cancel"}),e.jsxs(M,{type:"button",onClick:S,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:u||!i.trim()||!d||!l,children:[e.jsx(at,{className:"w-4 h-4 mr-2"}),u?"Adding...":`Add at Level ${d||"?"}`]})]})]}),e.jsx(ot,{open:C.open,onOpenChange:A=>R(k=>({...k,open:A})),children:e.jsxs(Je,{className:"sm:max-w-md",children:[e.jsxs(lt,{children:[e.jsx(et,{className:"flex items-center gap-2",children:C.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(Re,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Re,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(Zt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[C.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:C.email})," was not found in the organization directory."]}),e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3 space-y-2",children:[e.jsx("p",{className:"text-sm text-red-800 font-semibold",children:"Please verify:"}),e.jsxs("ul",{className:"text-sm text-red-700 space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"Email address is spelled correctly"}),e.jsx("li",{children:"User exists in Okta/SSO system"}),e.jsx("li",{children:"User has an active account"})]})]}),e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-blue-800 flex items-center gap-1",children:[e.jsx(Ur,{className:"w-4 h-4"}),e.jsx("strong",{children:"Tip:"})," Use ",e.jsx("span",{className:"font-mono bg-blue-100 px-1 rounded",children:"@"})," sign to search users from the directory."]})})]}),C.type==="error"&&e.jsxs(e.Fragment,{children:[C.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:C.email}),"."]}),C.message&&e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-3",children:e.jsx("p",{className:"text-sm text-gray-700",children:C.message})})]})]})})]}),e.jsx(Tt,{children:e.jsx(M,{onClick:()=>R(A=>({...A,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const by=t=>{switch(t){case"online":return"bg-green-500";case"away":return"bg-yellow-500";case"offline":return"bg-gray-400";default:return"bg-gray-400"}},jy=t=>{switch(t){case"online":return"Online";case"away":return"Away";case"offline":return"Offline";default:return"Unknown"}},Ny=t=>t.replace(/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,(s,a,r,n)=>{const i=r+s.length,o=n[i];return!o||/\s|[.,!?;:]|@/.test(o)?'@'+a+"":s}).replace(/\n/g,"
"),wy=t=>t<1024?t+" B":t<1024*1024?(t/1024).toFixed(1)+" KB":(t/(1024*1024)).toFixed(1)+" MB",hl=({type:t})=>{const s="w-4 h-4",a=t.toLowerCase();return a.includes("pdf")?e.jsx(Te,{className:`${s} text-red-600`}):a.includes("excel")||a.includes("spreadsheet")||a.includes("xlsx")?e.jsx(jx,{className:`${s} text-green-600`}):a.includes("powerpoint")||a.includes("presentation")||a.includes("pptx")?e.jsx(Te,{className:`${s} text-orange-600`}):a.includes("word")||a.includes("document")||a.includes("docx")?e.jsx(Te,{className:`${s} text-blue-600`}):a.includes("image")||a.includes("png")||a.includes("jpg")||a.includes("jpeg")||a.includes("gif")||a.includes("webp")?e.jsx(Nx,{className:`${s} text-purple-600`}):e.jsx(Or,{className:`${s} text-gray-600`})};function fm({requestId:t,messages:s,onSend:a,skipSocketJoin:r=!1,requestTitle:n,onAttachmentsExtracted:i,isInitiator:o=!1,isSpectator:l=!1,currentLevels:c=[],onAddApprover:d}){const m=Ja(),u=t||m.requestId||"",[h,x]=g.useState(""),[p,y]=g.useState(""),[v,N]=g.useState(!1),[f,b]=g.useState([]),[j,C]=g.useState(!1),[R,I]=g.useState([]),[T,E]=g.useState(null),[w,S]=g.useState(null),[D,H]=g.useState(!1),[L,F]=g.useState(!1),A=g.useRef(null),k=g.useRef(null),P=g.useRef(null),_=g.useRef(!1),[W,Z]=g.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[ae,$]=g.useState({open:!1,errors:[]}),ne=g.useMemo(()=>({id:u,title:n||"Request Details"}),[u,n]),[me,q]=g.useState([]),z=me.filter(O=>O.status==="online"),re=f.filter(O=>O.content.toLowerCase().includes(p.toLowerCase())||O.user.name.toLowerCase().includes(p.toLowerCase())),K=g.useMemo(()=>l!==void 0?l:!T||me.length===0?!1:me.some(O=>{const ee=O.userId||O.user_id,U=(O.role||"").toString().toUpperCase(),ce=(O.participantType||O.participant_type||"").toString().toUpperCase();return ee===T&&(U==="SPECTATOR"||ce==="SPECTATOR")}),[l,T,me]);g.useEffect(()=>{},[me]),g.useEffect(()=>{!u||!T||s||(async()=>{try{const O=await aa(u),ee=Array.isArray(O)?O.map(U=>{const ce=U.userId||U.user_id;return{id:U.noteId||U.id||String(Math.random()),user:{name:U.userName||"User",avatar:(U.userName||"U").slice(0,2).toUpperCase(),role:U.userRole||"Participant"},content:U.message||"",timestamp:U.createdAt||new Date().toISOString(),isCurrentUser:ce===T,attachments:Array.isArray(U.attachments)?U.attachments.map(le=>({attachmentId:le.attachmentId||le.attachment_id,name:le.fileName||le.file_name||le.name,fileName:le.fileName||le.file_name||le.name,url:le.storageUrl||le.storage_url||le.url||"#",type:le.fileType||le.file_type||le.type||"file",fileType:le.fileType||le.file_type||le.type||"file",fileSize:le.fileSize||le.file_size})):void 0}}):[];b(ee)}catch(O){console.error("[WorkNoteChat] Failed to load messages:",O)}})()},[u,T,s]);const B=g.useMemo(()=>{const O=[];return f.forEach(ee=>{ee.attachments&&ee.attachments.length>0&&ee.attachments.forEach(U=>{O.push({attachmentId:U.attachmentId||U.attachment_id,name:U.fileName||U.file_name||U.name||"Untitled",fileName:U.fileName||U.file_name||U.name||"Untitled",size:U.fileSize||U.file_size,type:U.fileType||U.file_type||U.type||"file",uploadedBy:ee.user.name,uploadedAt:ee.timestamp,url:U.storageUrl||U.storage_url||U.url||"#"})})}),O},[f]);g.useEffect(()=>{i&&B.length>=0&&i(B)},[B,i]);const J=g.useMemo(()=>me.map(O=>({email:(O.email||"").toLowerCase(),participantType:O.role==="Initiator"?"INITIATOR":O.role==="Approver"?"APPROVER":O.role==="Spectator"?"SPECTATOR":"PARTICIPANT",name:O.name})),[me]),ue=O=>{if(!O)return"Participant";switch(O.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return O.charAt(0).toUpperCase()+O.slice(1).toLowerCase()}},be=()=>{var O;(O=A.current)==null||O.scrollIntoView({behavior:"smooth"})};g.useEffect(()=>{be()},[f]);const Ie=O=>{switch(O.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return O.charAt(0).toUpperCase()+O.slice(1).toLowerCase()}};g.useEffect(()=>{_.current||u&&(async()=>{try{const O=await Rs(u),ee=Array.isArray(O==null?void 0:O.participants)?O.participants:[];if(ee.length===0)return;const U=ee.map(de=>{const ke=de.participantType||de.participant_type||"participant",ge=de.userId||de.user_id||"";return{name:de.userName||de.user_name||de.user_email||de.userEmail||"User",avatar:(de.userName||de.user_name||de.user_email||"U").toString().split(" ").map(Pe=>Pe[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ie(ke.toString()),status:"offline",email:de.userEmail||de.user_email||"",permissions:["read","write","mention"],userId:ge}});_.current=!0,q(U);let ce=0;const le=3,ye=()=>{P.current&&P.current.connected?(P.current.emit("request:online-users",{requestId:u}),ce++,ce()=>{u&&(_.current=!1)},[u]),g.useEffect(()=>{const O=localStorage.getItem("userData");if(O)try{const ee=JSON.parse(O),U=(ee==null?void 0:ee.id)||(ee==null?void 0:ee.userId)||(ee==null?void 0:ee.user_id)||null;E(U)}catch(ee){console.error("[WorkNoteChat] Failed to parse userData:",ee)}},[]),g.useEffect(()=>{(async()=>{try{const ee=await ra("DOCUMENT_POLICY"),U={};ee.forEach(de=>{U[de.configKey]=de.configValue});const ce=parseInt(U.MAX_FILE_SIZE_MB||"10"),ye=(U.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(de=>de.trim().toLowerCase());Z({maxFileSizeMB:ce,allowedFileTypes:ye})}catch(ee){console.error("Failed to load document policy:",ee)}})()},[]),g.useEffect(()=>{if(!T)return;let O=u;return(async()=>{var ee;try{const U=await Rs(u);(ee=U==null?void 0:U.workflow)!=null&&ee.requestId&&(O=U.workflow.requestId)}catch{}try{const U=Ar();r?q(_e=>_e.map(ze=>ze.userId===T?{...ze,status:"online"}:ze)):(Xn(U,O,T),q(_e=>_e.map(ze=>ze.userId===T?{...ze,status:"online"}:ze)));const ce=_e=>{const Ee=(_e==null?void 0:_e.note)||_e;if(!Ee)return;const ze=Ee.noteId||Ee.id;b(zt=>{if(zt.some(We=>We.id===ze))return zt;const tt=Ee.userName||Ee.user_name||"User",Ea=Ee.userRole||Ee.user_role,ma=ue(Ea),lr=Ee.userId||Ee.user_id,cr={id:ze||String(Date.now()),user:{name:tt,avatar:tt.split(" ").map(We=>We[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:ma},content:Ee.message||"",timestamp:Ee.createdAt||new Date().toISOString(),isCurrentUser:lr===T,attachments:Array.isArray(Ee.attachments)?Ee.attachments.map(We=>({attachmentId:We.attachmentId||We.attachment_id,name:We.fileName||We.file_name||We.name,fileName:We.fileName||We.file_name||We.name,url:We.storageUrl||We.storage_url||We.url||"#",type:We.fileType||We.file_type||We.type||"file",fileType:We.fileType||We.file_type||We.type||"file",fileSize:We.fileSize||We.file_size})):void 0};return[...zt,cr]})},le=_e=>{q(Ee=>Ee.length===0||!Ee.find(tt=>tt.userId===_e.userId)?Ee:Ee.map(tt=>tt.userId===_e.userId?{...tt,status:"online"}:tt))},ye=_e=>{_e.userId!==T&&q(Ee=>Ee.length===0||!Ee.find(tt=>tt.userId===_e.userId)?Ee:Ee.map(tt=>tt.userId===_e.userId?{...tt,status:"offline"}:tt))},de=_e=>{q(Ee=>Ee.length===0?Ee:Ee.map(zt=>{const tt=zt.userId||"";if(tt===T)return{...zt,status:"online"};const ma=_e.userIds.includes(tt);return{...zt,status:ma?"online":"offline"}}))},ke=()=>{q(_e=>_e.map(ze=>ze.userId===T?{...ze,status:"online"}:ze)),r||Xn(U,O,T),_.current&&(U.emit("request:online-users",{requestId:O}),setTimeout(()=>U.emit("request:online-users",{requestId:O}),300),setTimeout(()=>U.emit("request:online-users",{requestId:O}),800))},ge=_e=>{console.error("[WorkNoteChat] ❌ Socket error:",_e)},Pe=_e=>{console.warn("[WorkNoteChat] ⚠️ Socket disconnected:",_e),q(Ee=>Ee.map(ze=>ze.userId===T?ze:{...ze,status:"offline"}))},Xt=_e=>{_e.includes("presence")||_e.includes("worknote")||_e.includes("request")};U.on("connect",ke),U.on("disconnect",Pe),U.on("error",ge),U.on("worknote:new",ce),U.on("presence:join",le),U.on("presence:leave",ye),U.on("presence:online",de),U.onAny(Xt),P.current=U,U.connected&&_.current&&(U.emit("request:online-users",{requestId:O}),setTimeout(()=>{U.emit("request:online-users",{requestId:O})},300),setTimeout(()=>{U.emit("request:online-users",{requestId:O})},800),setTimeout(()=>{U.emit("request:online-users",{requestId:O})},1500));const vt=()=>{U.off("connect",ke),U.off("disconnect",Pe),U.off("error",ge),U.off("worknote:new",ce),U.off("presence:join",le),U.off("presence:leave",ye),U.off("presence:online",de),U.offAny(Xt),r||Ud(U,O),P.current=null};window.__wn_cleanup=vt}catch{}})(),()=>{var ee;try{(ee=window.__wn_cleanup)==null||ee.call(window)}catch{}}},[u,T,r]);const Ve=async()=>{if(h.trim()||R.length>0){const O=Pa(h),ee=O.map(le=>{const ye=me.find(de=>de.name.toLowerCase().includes(le.toLowerCase()));return ye==null?void 0:ye.userId}).filter(Boolean),U=R.map(le=>({name:le.name,url:URL.createObjectURL(le),type:le.type.split("/")[1]||"file"})),ce={id:Date.now().toString(),user:{name:"You",avatar:"YO",role:"Current User"},content:h,timestamp:new Date().toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0}),mentions:O,isHighPriority:h.includes("!important")||h.includes("urgent"),attachments:U.length>0?U:void 0,isCurrentUser:!0};if(a)try{await a(h,R)}catch{}else try{await $i(u,{message:h,mentions:ee},R);const le=await aa(u),ye=Array.isArray(le)?le.map(de=>{const ke=de.userId||de.user_id;return{id:de.noteId||de.id||String(Math.random()),user:{name:de.userName||"User",avatar:(de.userName||"U").slice(0,2).toUpperCase(),role:de.userRole||"Participant"},content:de.message||"",timestamp:de.createdAt||new Date().toISOString(),isCurrentUser:ke===T,attachments:Array.isArray(de.attachments)?de.attachments.map(ge=>({attachmentId:ge.attachmentId||ge.attachment_id,name:ge.fileName||ge.file_name||ge.name,fileName:ge.fileName||ge.file_name||ge.name,url:ge.storageUrl||ge.storage_url||ge.url||"#",type:ge.fileType||ge.file_type||ge.type||"file",fileType:ge.fileType||ge.file_type||ge.type||"file",fileSize:ge.fileSize||ge.file_size})):void 0}}):[];b(ye)}catch{b(le=>[...le,ce])}x(""),I([])}};g.useEffect(()=>{if(s&&Array.isArray(s))try{const ee=s.filter(U=>(U.type||"").toLowerCase()!=="sla_warning").map(U=>{var le;if(U.type||U.activityType||U.isSystem)return{id:U.id||`activity-${U.timestamp||Date.now()}-${Math.random()}`,user:{name:"System",avatar:"SY",role:"System"},content:U.details||U.action||U.content||"",timestamp:U.timestamp||U.createdAt||U.created_at||new Date().toISOString(),isSystem:!0,isCurrentUser:!1};{const ye=U.userName||U.user_name||((le=U.user)==null?void 0:le.name)||"User",de=U.userRole||U.user_role,ke=ue(de),ge=U.userId||U.user_id;return{id:U.noteId||U.note_id||U.id||String(Math.random()),user:{name:ye,avatar:ye.split(" ").map(Pe=>Pe[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:ke},content:U.message||U.content||"",timestamp:U.createdAt||U.created_at||U.timestamp||new Date().toISOString(),isSystem:!1,attachments:Array.isArray(U.attachments)?U.attachments.map(Pe=>({attachmentId:Pe.attachmentId||Pe.attachment_id,name:Pe.fileName||Pe.file_name||Pe.name,fileName:Pe.fileName||Pe.file_name||Pe.name,url:Pe.storageUrl||Pe.storage_url||Pe.url||"#",type:Pe.fileType||Pe.file_type||Pe.type||"file",fileType:Pe.fileType||Pe.file_type||Pe.type||"file",fileSize:Pe.fileSize||Pe.file_size})):void 0,isCurrentUser:ge===T}}}).sort((U,ce)=>new Date(U.timestamp).getTime()-new Date(ce.timestamp).getTime());b(ee)}catch(O){console.error("[WorkNoteChat] Error mapping messages:",O)}else(async()=>{try{const O=await aa(u),ee=Array.isArray(O)?O.map(U=>{const ce=U.userName||U.user_name||"User",le=U.userRole||U.user_role,ye=ue(le),de=U.userId||U.user_id;return{id:U.noteId||U.note_id||U.id||String(Math.random()),user:{name:ce,avatar:ce.split(" ").map(ke=>ke[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:ye},content:U.message||"",timestamp:U.createdAt||U.created_at||new Date().toISOString(),attachments:Array.isArray(U.attachments)?U.attachments.map(ke=>({attachmentId:ke.attachmentId||ke.attachment_id,name:ke.fileName||ke.file_name||ke.name,fileName:ke.fileName||ke.file_name||ke.name,url:ke.storageUrl||ke.storage_url||ke.url||"#",type:ke.fileType||ke.file_type||ke.type||"file",fileType:ke.fileType||ke.file_type||ke.type||"file",fileSize:ke.fileSize||ke.file_size})):void 0,isCurrentUser:de===T}}):[];b(ee)}catch(O){console.error("[WorkNoteChat] Error loading work notes:",O)}})()},[s,u,me]);const Oe=O=>{const ee=W.maxFileSizeMB*1024*1024;if(O.size>ee)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${W.maxFileSizeMB}MB. Current size: ${(O.size/(1024*1024)).toFixed(2)}MB`};const U=O.name.toLowerCase(),ce=U.substring(U.lastIndexOf(".")+1);return W.allowedFileTypes.includes(ce)?{valid:!0}:{valid:!1,reason:`File type "${ce}" is not allowed. Allowed types: ${W.allowedFileTypes.join(", ")}`}},Ue=O=>{if(!O.target.files||O.target.files.length===0)return;const ee=Array.from(O.target.files),U=[],ce=[];ee.forEach(le=>{const ye=Oe(le);ye.valid?ce.push(le):U.push({fileName:le.name,reason:ye.reason||"Unknown validation error"})}),U.length>0&&$({open:!0,errors:U}),ce.length>0&&(I(le=>[...le,...ce]),ce.length{I(ee=>ee.filter((U,ce)=>ce!==O)),k.current&&(k.current.value="")},Dt=O=>{x(ee=>ee+O),N(!1)},Fe=()=>{var O;(O=k.current)==null||O.click()},Ra=async O=>{var ee,U;try{await Vi(u,O);const ce=await Rs(u),le=Array.isArray(ce==null?void 0:ce.participants)?ce.participants:[];if(le.length){const ye=le.map(de=>{const ke=de.participantType||de.participant_type||"participant",ge=de.userId||de.user_id||"",Pe=de.userName||de.user_name||de.userEmail||de.user_email||"User",Xt=de.userEmail||de.user_email||"",vt=Pe.split(" ").map(_e=>_e[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:Pe,avatar:vt,role:Ie(ke),status:"offline",email:Xt,lastSeen:void 0,permissions:["read"],userId:ge}});q(ye),P.current&&P.current.connected&&P.current.emit("request:online-users",{requestId:u})}H(!1),alert("Spectator added successfully")}catch(ce){throw console.error("Failed to add spectator:",ce),alert(((U=(ee=ce==null?void 0:ce.response)==null?void 0:ee.data)==null?void 0:U.error)||"Failed to add spectator"),ce}},Hs=async(O,ee,U)=>{var ce,le;if(d)await d(O,ee,U),F(!1);else try{await Ui(u,O,ee,U);const ye=await Rs(u),de=Array.isArray(ye==null?void 0:ye.participants)?ye.participants:[];if(de.length){const ke=de.map(ge=>{const Pe=ge.participantType||ge.participant_type||"participant",Xt=ge.userId||ge.user_id||"",vt=ge.userName||ge.user_name||ge.userEmail||ge.user_email||"User",_e=ge.userEmail||ge.user_email||"",Ee=vt.split(" ").map(ze=>ze[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:vt,avatar:Ee,role:Ie(Pe),status:"offline",email:_e,lastSeen:void 0,permissions:["read"],userId:Xt}});q(ke),P.current&&P.current.connected&&P.current.emit("request:online-users",{requestId:u})}F(!1),alert(`Approver added successfully at Level ${U} with ${ee}h TAT`)}catch(ye){throw console.error("Failed to add approver:",ye),alert(((le=(ce=ye==null?void 0:ye.response)==null?void 0:ce.data)==null?void 0:le.error)||"Failed to add approver"),ye}},Da=["😊","😂","🤣","😁","😃","😄","😅","😆","😉","😌","😍","🥰","😘","😗","😙","😚","🙂","🤗","🤩","🤔","🤨","😐","😑","😶","🙄","😏","😒","🙃","😬","🤐","😴","😪","😵","🤯","🤪","😜","😝","😛","🤤","😋","😎","🤓","🧐","😕","😟","🙁","☹️","😮","😯","😲","😳","🥺","😦","😧","😨","😰","😥","😢","😭","😱","😖","😣","😞","😓","😩","😫","🥱","😤","😡","😠","🤬","😈","👿","💀","☠️","💩","🤡","👹","👺","👻","👋","🤚","🖐️","✋","🖖","👌","🤌","🤏","✌️","🤞","🤟","🤘","🤙","👈","👉","👆","🖕","👇","☝️","👍","👎","✊","👊","🤛","🤜","👏","🙌","👐","🤲","🤝","🙏","💪","🦾","🦿","🦵","🦶","👂","🦻","👃","🧠","❤️","🧡","💛","💚","💙","💜","🖤","🤍","🤎","💔","❣️","💕","💞","💓","💗","💖","💘","💝","💟","❤️‍🔥","💼","📊","📈","📉","💻","⌨️","🖥️","🖨️","🖱️","💾","💿","📱","☎️","📞","📟","📠","📧","✉️","📨","📩","📮","📪","📫","📬","📭","📄","📃","📑","📝","✏️","✒️","🖊️","🖋️","📏","📐","📌","📍","🗂️","📁","📂","✅","✔️","☑️","🎯","🎖️","🏆","🥇","🥈","🥉","⭐","🌟","✨","💫","🔥","💥","⚡","💯","🎉","🎊","🎈","⚠️","🚫","❌","⛔","🚷","🚯","🚱","🚳","🔞","📵","❗","❓","❕","❔","‼️","⁉️","💢","💬","💭","🗯️","⏰","⏱️","⏲️","⏳","⌛","📅","📆","🗓️","📇","🕐","🕑","🕒","🕓","🕔","🕕","🕖","🕗","🕘","🕙","🕚","🚀","🎯","🎲","🎰","🧩","🔍","🔎","🔑","🗝️","🔒","🔓","🔐","🔏","🔔","🔕","📣","📢","💡","🔦","🏮","➕","➖","✖️","➗","♾️","‼️","⁉️","❓","❔","❕","🔄","🔃","🔂","▶️","⏸️","⏯️","⏹️","⏺️","⏭️","⏮️","⏩","⏪","⏫","⏬","◀️","🔼","🔽","➡️","⬅️","⬆️","⬇️","↗️","↘️","↙️","↖️","↕️","↔️","↪️","↩️","⤴️"],Pa=O=>{const ee=/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,U=[];let ce;for(;(ce=ee.exec(O))!==null;)if(ce[1]){const le=ce.index+ce[0].length,ye=O.slice(le),de=O[le];(ye.startsWith("@")||!de||/\s|[.,!?;:]|@/.test(de))&&U.push(ce[1].trim())}return U},da=O=>{O.key==="Enter"&&!O.shiftKey&&(O.preventDefault(),Ve())},Ss=(O,ee)=>{b(U=>U.map(ce=>{if(ce.id===O){const le=ce.reactions||[],ye=le.find(de=>de.emoji===ee);if(ye)if(ye.users.includes("You")){if(ye.users=ye.users.filter(de=>de!=="You"),ye.users.length===0)return{...ce,reactions:le.filter(de=>de.emoji!==ee)}}else ye.users.push("You");else le.push({emoji:ee,users:["You"]});return{...ce,reactions:le}}return ce}))};return e.jsxs("div",{className:"h-full flex flex-col bg-gray-50 overflow-hidden",children:[e.jsx("div",{className:"bg-white border-b border-gray-200 px-3 sm:px-6 py-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-4 min-w-0 flex-1",children:[e.jsx("div",{className:"w-10 h-10 sm:w-12 sm:h-12 bg-gradient-to-br from-blue-500 to-purple-600 rounded-xl flex items-center justify-center shadow-lg shrink-0",children:e.jsx(ws,{className:"w-5 h-5 sm:w-6 sm:h-6 text-white"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h1",{className:"text-lg sm:text-2xl font-bold text-gray-900",children:"Work Notes"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("p",{className:"text-gray-600 text-sm sm:text-base truncate",children:ne.title}),e.jsx(Q,{variant:"outline",className:"text-xs shrink-0",children:t})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:e.jsxs("div",{className:"flex -space-x-2",children:[z.slice(0,3).map((O,ee)=>e.jsx(jt,{className:"h-8 w-8 ring-2 ring-white shadow-sm",children:e.jsx(Nt,{className:"bg-blue-500 text-white text-xs font-semibold",children:O.avatar})},ee)),z.length>3&&e.jsxs("div",{className:"h-8 w-8 rounded-full bg-gray-100 ring-2 ring-white flex items-center justify-center text-xs font-medium text-gray-600",children:["+",z.length-3]})]})}),e.jsx(M,{variant:"outline",size:"sm",onClick:()=>C(!j),className:"lg:hidden",children:e.jsx(at,{className:"h-4 w-4"})})]})]})}),e.jsxs("div",{className:"flex-1 flex overflow-hidden relative",children:[e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsx("div",{className:"bg-white border-b border-gray-200 px-2 sm:px-3 lg:px-6 py-2 sm:py-3 flex-shrink-0",children:e.jsxs("div",{className:"relative",children:[e.jsx(Yt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(xe,{placeholder:"Search messages...",value:p,onChange:O=>y(O.target.value),className:"pl-10 bg-gray-50 border-gray-200 h-9 sm:h-10"})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto overflow-x-hidden px-2 sm:px-3 lg:px-6 py-2 sm:py-4 min-h-0",children:e.jsxs("div",{className:"space-y-3 sm:space-y-6 max-w-full",children:[re.map(O=>{const ee=O.isCurrentUser||!1;return e.jsxs("div",{className:`flex gap-2 sm:gap-3 lg:gap-4 ${O.isSystem?"justify-center":ee?"justify-end":""}`,children:[!O.isSystem&&!ee&&e.jsx(jt,{className:"h-8 w-8 sm:h-10 sm:w-10 lg:h-12 lg:w-12 flex-shrink-0 ring-1 sm:ring-2 ring-white shadow-sm",children:e.jsx(Nt,{className:`text-white font-semibold text-xs sm:text-sm ${O.user.role==="Initiator"?"bg-green-600":O.user.role==="Current User"?"bg-blue-500":O.user.role==="System"?"bg-gray-500":"bg-slate-600"}`,children:O.user.avatar})}),e.jsx("div",{className:`${ee?"max-w-[70%]":"flex-1"} min-w-0 ${O.isSystem?"text-center max-w-xs sm:max-w-md mx-auto":""}`,children:O.isSystem?e.jsxs("div",{className:"inline-flex items-center gap-2 sm:gap-3 px-3 sm:px-4 py-1.5 sm:py-2 bg-gray-100 rounded-full",children:[e.jsx(as,{className:"w-3 h-3 sm:w-4 sm:h-4 text-gray-500 flex-shrink-0"}),e.jsx("span",{className:"text-xs sm:text-sm text-gray-700",children:O.content}),e.jsx("span",{className:"text-xs text-gray-500 hidden sm:inline",children:Ot(O.timestamp)})]}):e.jsxs("div",{children:[e.jsxs("div",{className:`flex items-center gap-2 sm:gap-3 mb-1 sm:mb-2 flex-wrap ${ee?"justify-end":""}`,children:[e.jsxs("span",{className:"font-semibold text-gray-900 text-sm sm:text-base truncate",children:[O.user.name," ",ee&&e.jsx("span",{className:"text-xs text-gray-500 font-normal",children:"(you)"})]}),e.jsx(Q,{variant:"outline",className:"text-xs flex-shrink-0",children:O.user.role}),e.jsxs("span",{className:"text-xs text-gray-500 flex items-center gap-1 flex-shrink-0",children:[e.jsx(De,{className:"w-3 h-3"}),Ot(O.timestamp)]}),O.isHighPriority&&e.jsxs(Q,{variant:"destructive",className:"text-xs flex-shrink-0",children:[e.jsx(yx,{className:"w-3 h-3 mr-1"}),"Priority"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 sm:p-4 shadow-sm ${ee?"bg-blue-50 border-blue-200":"bg-white border-gray-200"}`,children:[e.jsx("div",{className:"text-gray-800 leading-relaxed text-sm sm:text-base",dangerouslySetInnerHTML:{__html:Ny(O.content)}}),O.attachments&&O.attachments.length>0&&e.jsx("div",{className:"mt-2 sm:mt-3 pt-2 sm:pt-3 border-t border-gray-100",children:e.jsx("div",{className:"space-y-2",children:O.attachments.map((U,ce)=>{const le=U.fileSize||U.file_size,ye=U.fileName||U.file_name||U.name,de=U.fileType||U.file_type||U.type||"",ke=U.attachmentId||U.attachment_id;return e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 p-2 sm:p-3 bg-gray-50 rounded-lg border border-gray-200 hover:bg-gray-100 transition-colors",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx(hl,{type:de})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs sm:text-sm font-medium text-gray-700 truncate",children:ye}),le&&e.jsx("p",{className:"text-xs text-gray-500",children:wy(le)})]}),ke&&(()=>{const ge=(de||"").toLowerCase();return ge.includes("image")||ge.includes("pdf")||ge.includes("jpg")||ge.includes("jpeg")||ge.includes("png")||ge.includes("gif")})()&&e.jsx(M,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-8 sm:w-8 p-0 flex-shrink-0 hover:bg-purple-100 hover:text-purple-600",onClick:ge=>{ge.preventDefault(),ge.stopPropagation();const Pe=tm(ke);S({fileName:ye,fileType:de,fileUrl:Pe,fileSize:le,attachmentId:ke})},title:"Preview file",children:e.jsx(At,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),e.jsx(M,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-8 sm:w-8 p-0 flex-shrink-0 hover:bg-blue-100 hover:text-blue-600",onClick:async ge=>{if(ge.preventDefault(),ge.stopPropagation(),!ke){alert("Cannot download: Attachment ID missing");return}try{await Qn(ke)}catch{alert("Failed to download file")}},title:"Download file",children:e.jsx(ns,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]},ce)})})}),O.reactions&&O.reactions.length>0&&e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 mt-2 sm:mt-3 pt-2 sm:pt-3 border-t border-gray-100 flex-wrap",children:[O.reactions.map((U,ce)=>e.jsxs("button",{onClick:()=>Ss(O.id,U.emoji),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs sm:text-sm transition-colors flex-shrink-0 ${U.users.includes("You")?"bg-blue-100 text-blue-800 border border-blue-200":"bg-gray-100 text-gray-700 hover:bg-gray-200"}`,children:[e.jsx("span",{children:U.emoji}),e.jsx("span",{className:"text-xs font-medium",children:U.users.length})]},ce)),e.jsx(M,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-7 sm:w-7 p-0 flex-shrink-0",onClick:()=>N(!v),children:e.jsx(Is,{className:"w-2 h-2 sm:w-3 sm:h-3"})})]})]})]})}),!O.isSystem&&ee&&e.jsx(jt,{className:"h-8 w-8 sm:h-10 sm:w-10 lg:h-12 lg:w-12 flex-shrink-0 ring-1 sm:ring-2 ring-white shadow-sm",children:e.jsx(Nt,{className:"bg-blue-500 text-white font-semibold text-xs sm:text-sm",children:O.user.avatar})})]},O.id)}),e.jsx("div",{ref:A})]})}),e.jsx("div",{className:"bg-white border-t border-gray-200 p-2 sm:p-3 lg:p-6 flex-shrink-0",children:e.jsxs("div",{className:"max-w-full",children:[e.jsx("input",{type:"file",ref:k,onChange:Ue,className:"hidden",multiple:!0,accept:W.allowedFileTypes.map(O=>`.${O}`).join(",")}),R.length>0&&e.jsx("div",{className:"mb-3 space-y-2 max-h-32 overflow-y-auto pr-2",children:R.map((O,ee)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-blue-50 rounded-lg border border-blue-200",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx(hl,{type:O.type.split("/")[1]||"file"})}),e.jsx("span",{className:"text-sm text-gray-700 flex-1 truncate min-w-0",children:O.name}),e.jsxs("span",{className:"text-xs text-gray-500 flex-shrink-0",children:[(O.size/1024).toFixed(1)," KB"]}),e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>$e(ee),className:"h-6 w-6 p-0 hover:bg-red-100 flex-shrink-0",children:e.jsx(ft,{className:"h-3 w-3 text-red-600"})})]},ee))}),e.jsxs("div",{className:"relative mb-2",children:[(()=>{const O=h.lastIndexOf("@"),ee=O>=0;if(!ee)return null;const U=h.slice(O+1),ce=U.trim(),le=U.endsWith(" "),ye=ce.length>0,de=ce.includes(" ")&&!le,ke=le&&ye;if(!(ee&&U.length<=20&&!de&&!ke))return null;const Pe=ce.toLowerCase(),Xt=me.filter(vt=>vt.userId===T?!1:Pe?vt.name.toLowerCase().includes(Pe):!0);return e.jsxs("div",{className:"absolute bottom-full left-0 mb-2 bg-white border-2 border-blue-300 rounded-lg shadow-2xl p-3 z-[100] w-full sm:max-w-md",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900 mb-2",children:"💬 Mention someone"}),e.jsx("div",{className:"max-h-60 overflow-y-auto space-y-1",children:Xt.length>0?Xt.map((vt,_e)=>e.jsxs("button",{type:"button",onClick:Ee=>{Ee.preventDefault(),Ee.stopPropagation();const ze=h.lastIndexOf("@"),zt=h.slice(0,ze);x(zt+"@"+vt.name+" ")},className:"w-full flex items-center gap-3 p-3 hover:bg-blue-50 rounded-lg text-left transition-colors border border-transparent hover:border-blue-200",children:[e.jsx(jt,{className:"h-10 w-10",children:e.jsx(Nt,{className:`text-white text-sm font-semibold ${vt.role==="Initiator"?"bg-green-600":vt.role==="Approver"?"bg-purple-600":"bg-blue-500"}`,children:vt.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:vt.name}),e.jsx("p",{className:"text-xs text-gray-600",children:vt.role})]})]},_e)):e.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:Pe?`No participants found matching "${Pe}"`:"No other participants available"})})]})})(),e.jsx(Cs,{placeholder:"Type your message... Use @username to mention someone",value:h,onChange:O=>x(O.target.value),onKeyPress:da,className:"min-h-[50px] sm:min-h-[60px] resize-none border-gray-200 focus:ring-blue-500 focus:border-blue-500 w-full text-sm",rows:2}),v&&e.jsxs("div",{className:"absolute bottom-full left-0 mb-2 bg-white border border-gray-200 rounded-lg shadow-xl p-3 z-50 w-full sm:w-96 max-h-80 overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 sticky top-0 bg-white pb-2 border-b",children:[e.jsx("span",{className:"text-sm font-semibold text-gray-700",children:"Pick an emoji"}),e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>N(!1),className:"h-6 w-6 p-0",children:e.jsx(ft,{className:"h-3 w-3"})})]}),e.jsx("div",{className:"grid grid-cols-8 sm:grid-cols-10 gap-1",children:Da.map((O,ee)=>e.jsx("button",{onClick:()=>Dt(O),className:"text-xl sm:text-2xl hover:bg-gray-100 rounded p-1 transition-colors flex items-center justify-center",title:O,children:O},ee))})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 flex-shrink-0",children:[e.jsx(M,{variant:"ghost",size:"sm",className:"text-gray-500 h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600 flex-shrink-0",onClick:Fe,title:"Attach file",children:e.jsx(Or,{className:"h-4 w-4"})}),e.jsx(M,{variant:"ghost",size:"sm",className:"text-gray-500 h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600 flex-shrink-0",onClick:()=>N(!v),title:"Add emoji",children:e.jsx(vx,{className:"h-4 w-4"})}),e.jsx(M,{variant:"ghost",size:"sm",className:"text-gray-500 h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600 flex-shrink-0",onClick:()=>x(O=>O+"@"),title:"Mention someone",children:e.jsx(Ri,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-auto flex-shrink-0",children:[e.jsxs("span",{className:"text-xs text-gray-500 hidden md:inline whitespace-nowrap",children:[h.length,"/2000"]}),e.jsxs(M,{onClick:Ve,disabled:!h.trim()&&R.length===0,className:"bg-blue-600 hover:bg-blue-700 h-8 sm:h-9 px-3 sm:px-4 disabled:opacity-50 disabled:cursor-not-allowed flex-shrink-0",size:"sm",children:[e.jsx(bx,{className:"h-4 w-4 sm:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Send"})]})]})]})]})})]}),j&&e.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 z-40 lg:hidden",onClick:()=>C(!1)}),e.jsxs("div",{className:` w-72 sm:w-80 bg-white border-l border-gray-200 flex flex-col lg:relative lg:translate-x-0 lg:shadow-none ${j?"fixed right-0 top-0 bottom-0 z-50 shadow-xl":"hidden lg:flex"} `,children:[e.jsxs("div",{className:"p-4 sm:p-6 border-b border-gray-200 flex-1 flex flex-col min-h-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4 flex-shrink-0",children:[e.jsx("h3",{className:"text-base sm:text-lg font-semibold text-gray-900",children:"Participants"}),e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>C(!1),className:"lg:hidden h-8 w-8 p-0",children:e.jsx(ft,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-3 sm:space-y-4 overflow-y-auto flex-1 pr-2",children:me.map((O,ee)=>{const U=O.userId===T;return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(jt,{className:"h-9 w-9 sm:h-10 sm:w-10",children:e.jsx(Nt,{className:`text-white font-semibold text-sm ${O.role==="Initiator"?"bg-green-600":U?"bg-blue-500":"bg-slate-600"}`,children:O.avatar})}),e.jsx("div",{className:`absolute -bottom-1 -right-1 w-3 h-3 rounded-full border-2 border-white ${by(O.status)}`})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"font-medium text-gray-900 truncate text-sm sm:text-base",children:[O.name," ",U&&e.jsx("span",{className:"text-xs text-gray-500 font-normal",children:"(you)"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-xs text-gray-500",children:O.role}),e.jsx("span",{className:"text-xs text-gray-400",children:"•"}),e.jsx("p",{className:"text-xs text-gray-500",children:jy(O.status)})]}),O.lastSeen&&O.status==="offline"&&e.jsx("p",{className:"text-xs text-gray-400",children:O.lastSeen})]})]},ee)})})]}),!K&&e.jsxs("div",{className:"p-4 sm:p-6 flex-shrink-0",children:[e.jsx("h4",{className:"font-semibold text-gray-900 mb-3 text-sm sm:text-base",children:"Quick Actions"}),e.jsxs("div",{className:"space-y-2",children:[o&&e.jsxs(M,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>F(!0),children:[e.jsx($r,{className:"h-4 w-4"}),"Add Approver"]}),e.jsxs(M,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>H(!0),children:[e.jsx(At,{className:"h-4 w-4"}),"Add Spectator"]})]})]})]})]}),w&&e.jsx(qi,{fileName:w.fileName,fileType:w.fileType,fileUrl:w.fileUrl,fileSize:w.fileSize,attachmentId:w.attachmentId,onDownload:Qn,open:!!w,onClose:()=>S(null)}),!K&&e.jsx(xm,{open:D,onClose:()=>H(!1),onConfirm:Ra,requestIdDisplay:u,requestTitle:ne.title,existingParticipants:J}),!K&&o&&e.jsx(gm,{open:L,onClose:()=>F(!1),onConfirm:Hs,requestIdDisplay:u,requestTitle:ne.title,existingParticipants:J,currentLevels:c}),e.jsx(ot,{open:ae.open,onOpenChange:O=>$(ee=>({...ee,open:O})),children:e.jsxs(Je,{className:"sm:max-w-lg",children:[e.jsxs(lt,{children:[e.jsxs(et,{className:"flex items-center gap-2",children:[e.jsx(Re,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Zt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-gray-700",children:"The following file(s) could not be uploaded due to policy violations:"}),e.jsx("div",{className:"space-y-2 max-h-60 overflow-y-auto",children:ae.errors.map((O,ee)=>e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3",children:[e.jsx("p",{className:"font-medium text-red-900 text-sm",children:O.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:O.reason})]},ee))}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-sm text-blue-800 font-semibold mb-1",children:"Document Policy:"}),e.jsxs("ul",{className:"text-xs text-blue-700 space-y-1 list-disc list-inside",children:[e.jsxs("li",{children:["Maximum file size: ",W.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",W.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(Tt,{children:e.jsx(M,{onClick:()=>$({open:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})})]})}function Cy({requestId:t,requestTitle:s,mergedMessages:a,setWorkNoteAttachments:r,isInitiator:n,isSpectator:i,currentLevels:o,onAddApprover:l}){return e.jsx("div",{className:"h-[calc(100vh-300px)] min-h-[600px]",children:e.jsx(fm,{requestId:t,requestTitle:s,skipSocketJoin:!0,messages:a,onAttachmentsExtracted:r,isInitiator:n,isSpectator:i,currentLevels:o,onAddApprover:l})})}function Sy({summary:t,loading:s,onShare:a,isInitiator:r}){const n=l=>{const c=l.toLowerCase();return c==="approved"?e.jsx(ve,{className:"h-4 w-4 text-green-600"}):c==="rejected"?e.jsx(Ze,{className:"h-4 w-4 text-red-600"}):c==="pending"||c==="in progress"?e.jsx(De,{className:"h-4 w-4 text-orange-600"}):e.jsx(Te,{className:"h-4 w-4 text-gray-600"})},i=l=>{const c=l.toLowerCase();return c==="approved"?"bg-green-100 text-green-700 border-green-300":c==="rejected"?"bg-red-100 text-red-700 border-red-300":c==="pending"||c==="in progress"?"bg-orange-100 text-orange-700 border-orange-300":"bg-gray-100 text-gray-700 border-gray-300"},o=(l,c)=>l&&l.trim()&&l.trim().toUpperCase()!=="N/A"?l:c&&c.trim()&&c.trim().toUpperCase()!=="N/A"?c:"N/A";return s?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Le,{className:"h-12 w-12 animate-spin text-blue-600 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading summary..."})]})}):t?e.jsx("div",{className:"space-y-6",children:e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border border-gray-200",children:[e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-2",children:t.title}),e.jsxs("p",{className:"text-sm text-gray-600",children:["Request #",t.requestNumber]})]}),r&&a?e.jsxs(M,{variant:"outline",size:"sm",onClick:a,className:"flex items-center gap-2",children:[e.jsx(wa,{className:"w-4 h-4"}),e.jsx("span",{children:"Share"})]}):e.jsxs(Q,{className:i(t.workflow.status),children:[n(t.workflow.status),e.jsx("span",{className:"ml-1 capitalize",children:t.workflow.status})]})]}),t.description&&e.jsx("div",{className:"mb-4",children:e.jsx(Ms,{content:t.description,className:"text-gray-700"})})]}),e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Initiator"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:t.initiator.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:o(t.initiator.designation,t.initiator.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:t.initiator.status})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Time Stamp"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:pe(new Date(t.initiator.timestamp),"MMM dd, yy, HH:mm")})]})]})]}),t.approvers&&t.approvers.length>0&&e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Workflow"}),t.approvers.map((l,c)=>e.jsxs("div",{className:"mb-6 last:mb-0",children:[e.jsx("h4",{className:"text-md font-semibold text-gray-800 mb-3",children:l.levelName||`Approver ${l.levelNumber}`}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:l.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:o(l.designation,l.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsxs("div",{className:"flex items-center gap-1",children:[n(l.status),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:l.status})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Time Stamp"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:pe(new Date(l.timestamp),"MMM dd, yy, HH:mm")})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Remarks"}),e.jsx("p",{className:"text-sm text-gray-700",children:l.remarks||"—"})]})]},c))]}),e.jsxs("div",{className:"p-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Closing Remarks (Conclusion)"}),e.jsxs("div",{className:"bg-gray-50 rounded-lg p-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:t.initiator.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:o(t.initiator.designation,t.initiator.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:"Concluded"})]}),t.isAiGenerated&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Source"}),e.jsx(Q,{variant:"outline",className:"text-xs",children:"AI Generated"})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Remarks"}),t.closingRemarks?e.jsx(Ms,{content:t.closingRemarks,className:"text-sm text-gray-700"}):e.jsx("p",{className:"text-sm text-gray-700",children:"—"})]})]})]})]})}):e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Te,{className:"h-12 w-12 text-gray-400 mx-auto mb-4"}),e.jsx("h2",{className:"text-xl font-bold text-gray-900 mb-2",children:"Summary Not Available"}),e.jsx("p",{className:"text-gray-600",children:"Summary has not been generated for this request yet."})]})})}function Ay({request:t,isInitiator:s,isSpectator:a,currentApprovalLevel:r,onAddApprover:n,onAddSpectator:i,onApprove:o,onReject:l,onPause:c,onResume:d,onRetrigger:m,summaryId:u,refreshTrigger:h,pausedByUserId:x,currentUserId:p}){var T;const[y,v]=g.useState([]),[N,f]=g.useState(!1),b=(t==null?void 0:t.status)==="closed",j=((T=t==null?void 0:t.pauseInfo)==null?void 0:T.isPaused)||!1,C=!j&&!b&&r,R=j&&d&&!s&&x===p,I=j&&s&&m;return g.useEffect(()=>{(async()=>{if(!b||!u||!s){v([]);return}try{f(!0);const w=await ay(u);v(w)}catch(w){console.error("Failed to fetch shared recipients:",w),v([])}finally{f(!1)}})()},[b,u,s,h]),e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[!a&&t.status!=="closed"&&e.jsxs(G,{"data-testid":"quick-actions-card",children:[e.jsx(te,{className:"pb-2",children:e.jsx(se,{className:"text-sm sm:text-base",children:"Quick Actions"})}),e.jsxs(Y,{className:"space-y-2",children:[s&&t.status!=="closed"&&e.jsxs(M,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-gray-700 border-gray-300 hover:bg-gray-50 hover:text-gray-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:n,"data-testid":"add-approver-button",children:[e.jsx($r,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Add Approver"]}),t.status!=="closed"&&e.jsxs(M,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-gray-700 border-gray-300 hover:bg-gray-50 hover:text-gray-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:i,"data-testid":"add-spectator-button",children:[e.jsx(At,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Add Spectator"]}),C&&c&&e.jsxs(M,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-orange-700 border-orange-300 hover:bg-orange-50 hover:text-orange-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:c,"data-testid":"pause-workflow-button",children:[e.jsx(Ls,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Pause Workflow"]}),R&&e.jsxs(M,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-green-700 border-green-300 hover:bg-green-50 hover:text-green-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:d,"data-testid":"resume-workflow-button",children:[e.jsx(gd,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Resume Workflow"]}),I&&e.jsxs(M,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-orange-700 border-orange-300 hover:bg-orange-50 hover:text-orange-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:m,"data-testid":"request-resume-button",children:[e.jsx(Re,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Request Resume"]}),e.jsxs("div",{className:"pt-3 sm:pt-4 space-y-2",children:[r&&!j&&e.jsxs(e.Fragment,{children:[e.jsxs(M,{className:"w-full bg-green-600 hover:bg-green-700 text-white h-9 sm:h-10 text-xs sm:text-sm",onClick:o,"data-testid":"approve-request-button",children:[e.jsx(ve,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Approve Request"]}),e.jsxs(M,{variant:"destructive",className:"w-full h-9 sm:h-10 text-xs sm:text-sm",onClick:l,"data-testid":"reject-request-button",children:[e.jsx(Ze,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Reject Request"]})]}),j&&e.jsxs("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-3 text-center",children:[e.jsx("p",{className:"text-xs text-orange-800 font-medium",children:"Workflow is paused"}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:"Actions are disabled until resumed"})]})]})]})]}),e.jsxs(G,{"data-testid":"spectators-card",children:[e.jsx(te,{className:"pb-2",children:e.jsx(se,{className:"text-sm sm:text-base",children:"Spectators"})}),e.jsx(Y,{className:"space-y-3",children:t.spectators&&t.spectators.length>0?t.spectators.map((E,w)=>e.jsxs("div",{className:"flex items-center gap-3","data-testid":`spectator-${w}`,children:[e.jsx(jt,{className:"h-8 w-8",children:e.jsx(Nt,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:E.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:E.name}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:E.role})]})]},w)):e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"No spectators added"})})})]}),b&&s&&e.jsxs(G,{"data-testid":"shared-recipients-card",children:[e.jsx(te,{className:"pb-2",children:e.jsxs(se,{className:"text-sm sm:text-base flex items-center gap-2",children:[e.jsx(wa,{className:"w-4 h-4"}),"Summary Shared With"]})}),e.jsx(Y,{className:"space-y-3",children:N?e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Loading..."})}):y.length>0?y.map((E,w)=>{const S=(E.displayName||"NA").split(" ").map(D=>D[0]).join("").slice(0,2).toUpperCase();return e.jsxs("div",{className:"flex items-center gap-3","data-testid":`shared-recipient-${w}`,children:[e.jsx(jt,{className:"h-8 w-8",children:e.jsx(Nt,{className:"bg-green-100 text-green-800 text-xs font-semibold",children:S})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:E.displayName}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:E.email}),E.isRead&&e.jsx("p",{className:"text-xs text-green-600 mt-0.5",children:"Viewed"})]})]},E.userId||w)}):e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Summary not shared yet"})})})]})]})}function Ty({open:t,onClose:s,onConfirm:a,defaultDescription:r="",title:n="Approve Request",requestIdDisplay:i,requestTitle:o}){const[l,c]=g.useState(r),[d,m]=g.useState(!1),u=(l==null?void 0:l.length)||0,h=g.useMemo(()=>l.slice(0,500),[l]),x=async()=>{try{m(!0),await a(h),s()}finally{m(!1)}};return e.jsx(ot,{open:t,onOpenChange:p=>!p&&s(),children:e.jsxs(Je,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(lt,{children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-green-100 flex items-center justify-center",children:e.jsx(ve,{className:"w-7 h-7 text-green-600"})}),e.jsxs("div",{children:[e.jsx(et,{className:"text-lg",children:n}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Please provide your approval comments and remarks"})]})]})}),e.jsxs("div",{className:"border rounded-lg p-4 bg-white",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800",children:"Request ID"}),e.jsx("span",{className:"text-xs bg-gray-100 border border-gray-300 text-gray-800 rounded-full px-2 py-0.5",children:i||"—"})]}),e.jsxs("div",{className:"mb-3",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800 block",children:"Title"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1 truncate",children:o||"—"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800",children:"Action"}),e.jsx(Q,{className:"bg-green-100 text-green-800 border-green-200",variant:"outline",children:"APPROVE"})]})]}),e.jsxs("div",{className:"space-y-2 mt-4",children:[e.jsx("label",{className:"text-sm font-semibold text-gray-800",children:"Comments & Remarks *"}),e.jsx(Cs,{value:h,onChange:p=>c(p.target.value),rows:5,placeholder:"Enter your approval comments and any conditions or notes...",className:"border-gray-300"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsx("span",{children:"Comments are required and will be visible to all participants"}),e.jsxs("span",{children:[Math.min(u,500),"/500"]})]})]}),e.jsxs("div",{className:"mt-4 border rounded-lg p-3 bg-green-50 border-green-200 text-green-900 flex items-start gap-2",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx(ve,{className:"w-4 h-4"})}),e.jsxs("div",{className:"text-sm",children:[e.jsx("div",{className:"font-semibold",children:"Approval Confirmation"}),e.jsx("div",{children:"This request will be forwarded to the next approver or completed if this is the final step."})]})]}),e.jsxs(Tt,{className:"mt-4",children:[e.jsx(M,{variant:"outline",onClick:s,disabled:d,children:"Cancel"}),e.jsxs(M,{onClick:x,disabled:d,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(ve,{className:"w-4 h-4 mr-2"}),d?"Approving...":"Approve Request"]})]})]})})}function ky({open:t,onClose:s,onConfirm:a,defaultDescription:r="",title:n="Reject Request",requestIdDisplay:i,requestTitle:o}){const[l,c]=g.useState(r),[d,m]=g.useState(!1),u=(l==null?void 0:l.length)||0,h=g.useMemo(()=>l.slice(0,500),[l]),x=async()=>{if(!h.trim()){alert("Comments & remarks are required");return}try{m(!0),await a(h),s()}finally{m(!1)}};return e.jsx(ot,{open:t,onOpenChange:p=>!p&&s(),children:e.jsxs(Je,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(lt,{children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-red-100 flex items-center justify-center",children:e.jsx(Ze,{className:"w-7 h-7 text-red-600"})}),e.jsxs("div",{children:[e.jsx(et,{className:"text-lg",children:n}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Please provide detailed reasons for rejection"})]})]})}),e.jsxs("div",{className:"border rounded-lg p-4 bg-white",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800",children:"Request ID"}),e.jsx("span",{className:"text-xs bg-gray-100 border border-gray-300 text-gray-800 rounded-full px-2 py-0.5",children:i||"—"})]}),e.jsxs("div",{className:"mb-3",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800 block",children:"Title"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1 truncate",children:o||"—"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800",children:"Action"}),e.jsx(Q,{className:"bg-red-100 text-red-800 border-red-200",variant:"outline",children:"REJECT"})]})]}),e.jsxs("div",{className:"space-y-3 mt-4",children:[e.jsx("label",{className:"text-sm font-semibold text-gray-800",children:"Comments & Remarks *"}),e.jsx(Cs,{value:h,onChange:p=>c(p.target.value),rows:5,placeholder:"Enter detailed reasons for rejection and any suggestions for improvement...",className:"border-gray-300"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsx("span",{children:"Comments are required and will be visible to all participants"}),e.jsxs("span",{children:[Math.min(u,500),"/500"]})]})]}),e.jsxs("div",{className:"mt-4 border rounded-lg p-3 bg-red-50 border-red-200 text-red-900 flex items-start gap-2",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx(Re,{className:"w-4 h-4"})}),e.jsxs("div",{className:"text-sm",children:[e.jsx("div",{className:"font-semibold",children:"Rejection Guidelines"}),e.jsx("div",{children:"Please provide specific, actionable feedback to help the initiator improve their request."})]})]}),e.jsxs(Tt,{className:"mt-4",children:[e.jsx(M,{variant:"outline",onClick:s,disabled:d,children:"Cancel"}),e.jsxs(M,{variant:"destructive",onClick:x,disabled:d,children:[e.jsx(Ze,{className:"w-4 h-4 mr-2"}),d?"Rejecting...":"Reject Request"]})]})]})})}function Ry({open:t,onClose:s,onConfirm:a,approverName:r,levelNumber:n,requestIdDisplay:i,requestTitle:o}){const[l,c]=g.useState(""),[d,m]=g.useState(!1),u=async()=>{if(l.trim())try{m(!0),await a(l.trim()),c(""),s()}catch(x){console.error("Failed to skip approver:",x)}finally{m(!1)}},h=()=>{d||(c(""),s())};return e.jsx(ot,{open:t,onOpenChange:h,children:e.jsxs(Je,{className:"sm:max-w-md max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:h,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:d,children:[e.jsx(ft,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(lt,{className:"px-6 pt-6 pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-orange-100 rounded-lg flex items-center justify-center",children:e.jsx(Re,{className:"w-5 h-5 text-orange-600"})}),e.jsx(et,{className:"text-xl font-bold text-gray-900",children:"Skip Approver"})]})}),e.jsxs("div",{className:"space-y-4 px-6 py-4 overflow-y-auto flex-1",children:[e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Re,{className:"w-5 h-5 text-orange-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-semibold text-orange-900 mb-1",children:"Important Notice"}),e.jsx("p",{className:"text-sm text-orange-800",children:"You are about to skip the current approver. The request will be moved to the next approval level."})]})]})}),(i||o)&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{className:"text-sm font-semibold text-gray-700",children:"Request Details"}),e.jsxs("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-3 space-y-1",children:[i&&e.jsxs("p",{className:"text-sm text-gray-900",children:[e.jsx("span",{className:"font-medium",children:"Request ID:"})," ",i]}),o&&e.jsxs("p",{className:"text-sm text-gray-700",children:[e.jsx("span",{className:"font-medium",children:"Title:"})," ",o]})]})]}),(r||n)&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{className:"text-sm font-semibold text-gray-700",children:"Approver Being Skipped"}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3 space-y-1",children:[n&&e.jsxs("p",{className:"text-sm text-blue-900",children:[e.jsx("span",{className:"font-medium",children:"Level:"})," ",n]}),r&&e.jsxs("p",{className:"text-sm text-blue-900",children:[e.jsx("span",{className:"font-medium",children:"Approver:"})," ",r]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"skip-reason",className:"text-sm font-semibold text-gray-700",children:"Reason for Skipping *"}),e.jsx(Cs,{id:"skip-reason",placeholder:"Please provide a detailed reason for skipping this approver (e.g., 'Approver is on leave until [date]', 'Approver unavailable - escalating to next level')",value:l,onChange:x=>c(x.target.value),className:"min-h-[100px] border-2 border-gray-300 focus:border-orange-500",disabled:d,autoFocus:!0}),e.jsx("p",{className:"text-xs text-gray-500",children:"This reason will be recorded in the activity log and all participants will be notified."})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(M,{type:"button",variant:"outline",onClick:h,className:"flex-1 h-11 border-gray-300",disabled:d,children:"Cancel"}),e.jsxs(M,{type:"button",onClick:u,className:"flex-1 h-11 bg-orange-600 hover:bg-orange-700 text-white",disabled:d||!l.trim(),children:[e.jsx(Re,{className:"w-4 h-4 mr-2"}),d?"Skipping...":"Skip Approver"]})]})]})})}function Dy({open:t,onClose:s,success:a,title:r,message:n}){return e.jsx(ot,{open:t,onOpenChange:s,children:e.jsxs(Je,{className:"sm:max-w-md",children:[e.jsx(lt,{children:e.jsxs(et,{className:"flex items-center gap-2",children:[a?e.jsx(ve,{className:"w-5 h-5 text-green-600"}):e.jsx(Re,{className:"w-5 h-5 text-red-600"}),r||(a?"Success":"Error")]})}),e.jsx("div",{className:"py-6",children:e.jsx("div",{className:"flex flex-col items-center text-center",children:a?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mb-4",children:e.jsx(ve,{className:"w-8 h-8 text-green-600"})}),e.jsx("p",{className:"text-sm text-gray-700",children:n||"Operation completed successfully!"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-red-100 flex items-center justify-center mb-4",children:e.jsx(Ze,{className:"w-8 h-8 text-red-600"})}),e.jsx("p",{className:"text-sm text-gray-700",children:n||"Operation failed. Please try again."})]})})}),e.jsx(Tt,{children:e.jsx(M,{onClick:s,className:`w-full ${a?"bg-green-600 hover:bg-green-700":"bg-gray-600 hover:bg-gray-700"}`,children:"OK"})})]})})}function Py({showApproveModal:t,showRejectModal:s,showAddApproverModal:a,showAddSpectatorModal:r,showSkipApproverModal:n,showActionStatusModal:i,previewDocument:o,documentError:l,request:c,skipApproverData:d,actionStatus:m,existingParticipants:u,currentLevels:h,setShowApproveModal:x,setShowRejectModal:p,setShowAddApproverModal:y,setShowAddSpectatorModal:v,setShowSkipApproverModal:N,setShowActionStatusModal:f,setPreviewDocument:b,setDocumentError:j,setSkipApproverData:C,setActionStatus:R,handleApproveConfirm:I,handleRejectConfirm:T,handleAddApprover:E,handleAddSpectator:w,handleSkipApprover:S,downloadDocument:D,documentPolicy:H}){return e.jsxs(e.Fragment,{children:[e.jsx(Ty,{open:t,onClose:()=>x(!1),onConfirm:I,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(ky,{open:s,onClose:()=>p(!1),onConfirm:T,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(gm,{open:a,onClose:()=>y(!1),onConfirm:E,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:u,currentLevels:h}),e.jsx(xm,{open:r,onClose:()=>v(!1),onConfirm:w,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:u}),e.jsx(Ry,{open:n,onClose:()=>{N(!1),C(null)},onConfirm:S,approverName:d==null?void 0:d.approverName,levelNumber:d==null?void 0:d.levelNumber,requestIdDisplay:c.id,requestTitle:c.title}),o&&e.jsx(qi,{fileName:o.fileName,fileType:o.fileType,fileUrl:Bi(o.documentId),fileSize:o.fileSize,attachmentId:o.documentId,onDownload:D,open:!!o,onClose:()=>b(null)}),m&&e.jsx(Dy,{open:i,onClose:()=>{f(!1),R(null)},success:m.success,title:m.title,message:m.message}),e.jsx(ot,{open:l.show,onOpenChange:L=>j(F=>({...F,show:L})),children:e.jsxs(Je,{className:"sm:max-w-lg",children:[e.jsxs(lt,{children:[e.jsxs(et,{className:"flex items-center gap-2",children:[e.jsx(Re,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Zt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-gray-700",children:"The following file(s) could not be uploaded due to policy violations:"}),e.jsx("div",{className:"space-y-2 max-h-60 overflow-y-auto",children:l.errors.map((L,F)=>e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3",children:[e.jsx("p",{className:"font-medium text-red-900 text-sm",children:L.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:L.reason})]},F))}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-sm text-blue-800 font-semibold mb-1",children:"Document Policy:"}),e.jsxs("ul",{className:"text-xs text-blue-700 space-y-1 list-disc list-inside",children:[e.jsxs("li",{children:["Maximum file size: ",H.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",H.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(Tt,{children:e.jsx(M,{onClick:()=>j({show:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})})]})}function Ey({isOpen:t,onClose:s,requestId:a,levelId:r,onSuccess:n}){const[i,o]=g.useState(""),[l,c]=g.useState(""),[d,m]=g.useState(!1),u=()=>Xe().add(1,"month").format("YYYY-MM-DD"),h=()=>Xe().add(1,"month").format("YYYY-MM-DD"),x=()=>Xe().add(1,"day").format("YYYY-MM-DD");g.useEffect(()=>{t&&!l&&c(u())},[t]);const p=async()=>{var b,j,C,R;if(!i.trim()){fe.error("Please provide a reason for pausing");return}if(!l){fe.error("Please select a resume date");return}const v=Xe(l),N=Xe().add(1,"month"),f=Xe().add(1,"day");if(v.isAfter(N)){fe.error("Resume date cannot be more than 1 month from now");return}if(v.isBefore(f,"day")){fe.error("Resume date must be at least 1 day from now");return}try{m(!0),await Qd(a,r,i.trim(),v.toDate()),fe.success("Workflow paused successfully"),o(""),c(u()),n==null||n(),s()}catch(I){console.error("Failed to pause workflow:",I),fe.error(((j=(b=I==null?void 0:I.response)==null?void 0:b.data)==null?void 0:j.error)||((R=(C=I==null?void 0:I.response)==null?void 0:C.data)==null?void 0:R.message)||"Failed to pause workflow")}finally{m(!1)}},y=()=>{d||(o(""),c(u()),s())};return e.jsx(ot,{open:t,onOpenChange:y,children:e.jsxs(Je,{className:"sm:max-w-[500px]",children:[e.jsx(lt,{children:e.jsxs(et,{className:"flex items-center gap-2",children:[e.jsx(Ls,{className:"w-5 h-5 text-orange-600"}),"Pause Workflow"]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-orange-800",children:[e.jsx("strong",{children:"Note:"})," Pausing will temporarily halt TAT calculations and notifications. The workflow will automatically resume on the selected date."]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(X,{htmlFor:"pause-reason",className:"text-sm font-medium",children:["Reason for Pausing ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Cs,{id:"pause-reason",value:i,onChange:v=>o(v.target.value),placeholder:"Enter the reason for pausing this workflow...",className:"min-h-[100px] text-sm",disabled:d}),e.jsxs("p",{className:"text-xs text-gray-500",children:[i.length," / 1000 characters"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(X,{htmlFor:"resume-date",className:"text-sm font-medium",children:["Resume Date ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(xe,{id:"resume-date",type:"date",value:l,onChange:v=>c(v.target.value),min:x(),max:h(),className:"text-sm",disabled:d}),e.jsx("p",{className:"text-xs text-gray-500",children:"Maximum 1 month from today. The workflow will automatically resume on this date."})]})]}),e.jsxs(Tt,{children:[e.jsx(M,{variant:"outline",onClick:y,disabled:d,children:"Cancel"}),e.jsx(M,{onClick:p,disabled:d||!i.trim()||!l,className:"bg-orange-600 hover:bg-orange-700 text-white",children:d?e.jsxs(e.Fragment,{children:[e.jsx(Le,{className:"w-4 h-4 mr-2 animate-spin"}),"Pausing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ls,{className:"w-4 h-4 mr-2"}),"Pause Workflow"]})})]})]})})}function My({isOpen:t,onClose:s,requestId:a,approverName:r,onSuccess:n}){const[i,o]=g.useState(!1),l=async()=>{var c,d,m,u;try{o(!0),await em(a),fe.success("Retrigger request sent to approver"),n==null||n(),s()}catch(h){console.error("Failed to retrigger pause:",h),fe.error(((d=(c=h==null?void 0:h.response)==null?void 0:c.data)==null?void 0:d.error)||((u=(m=h==null?void 0:h.response)==null?void 0:m.data)==null?void 0:u.message)||"Failed to send retrigger request")}finally{o(!1)}};return e.jsx(ot,{open:t,onOpenChange:s,children:e.jsxs(Je,{className:"sm:max-w-[450px]",children:[e.jsx(lt,{children:e.jsxs(et,{className:"flex items-center gap-2",children:[e.jsx(Re,{className:"w-5 h-5 text-orange-600"}),"Request Resume"]})}),e.jsxs("div",{className:"py-4",children:[e.jsxs("p",{className:"text-sm text-gray-700 mb-4",children:["You are requesting the approver",r?` (${r})`:""," to cancel the pause and resume work on this request."]}),e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-3",children:e.jsx("p",{className:"text-sm text-orange-800",children:"A notification will be sent to the approver who paused this workflow, requesting them to resume it."})})]}),e.jsxs(Tt,{children:[e.jsx(M,{variant:"outline",onClick:s,disabled:i,children:"Cancel"}),e.jsx(M,{onClick:l,disabled:i,className:"bg-orange-600 hover:bg-orange-700 text-white",children:i?e.jsxs(e.Fragment,{children:[e.jsx(Le,{className:"w-4 h-4 mr-2 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Re,{className:"w-4 h-4 mr-2"}),"Send Request"]})})]})]})})}class Iy extends g.Component{constructor(s){super(s),this.state={hasError:!1,error:null}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,a){console.error("RequestDetail Error:",s,a)}render(){var s;return this.state.hasError?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-6",children:e.jsxs("div",{className:"max-w-md w-full bg-white rounded-lg shadow-lg p-8 text-center",children:[e.jsx(is,{className:"w-16 h-16 text-red-500 mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-bold mb-2",children:"Error Loading Request"}),e.jsx("p",{className:"text-gray-600 mb-4",children:((s=this.state.error)==null?void 0:s.message)||"An unexpected error occurred"}),e.jsx(M,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(M,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}}function _y({requestId:t,onBack:s,dynamicRequests:a=[]}){var ma,lr,cr,We,$o,Uo;const n=Ja().requestId||t||"",o=new URLSearchParams(window.location.search).get("tab")||"overview",[l,c]=g.useState(o),[d,m]=g.useState(!1),[u,h]=g.useState(null),[x,p]=g.useState(null),[y,v]=g.useState(!1),[N,f]=g.useState(0),[b,j]=g.useState(!1),[C,R]=g.useState(!1),{user:I}=Bt(),{request:T,apiRequest:E,refreshing:w,refreshDetails:S,currentApprovalLevel:D,isSpectator:H,isInitiator:L,existingParticipants:F}=O0(n,a,I),{mergedMessages:A,unreadWorkNotes:k,workNoteAttachments:P,setWorkNoteAttachments:_}=$0(n,E,l,I),{uploadingDocument:W,triggerFileInput:Z,previewDocument:ae,setPreviewDocument:$,documentPolicy:ne,documentError:me,setDocumentError:q}=W0(E,S),{showApproveModal:z,setShowApproveModal:re,showRejectModal:K,setShowRejectModal:B,showAddApproverModal:J,setShowAddApproverModal:ue,showAddSpectatorModal:be,setShowAddSpectatorModal:Ie,showSkipApproverModal:Ve,setShowSkipApproverModal:Oe,showActionStatusModal:Ue,setShowActionStatusModal:$e,skipApproverData:Dt,setSkipApproverData:Fe,actionStatus:Ra,setActionStatus:Hs,handleApproveConfirm:Da,handleRejectConfirm:Pa,handleAddApprover:da,handleSkipApprover:Ss,handleAddSpectator:O}=G0(n,D,S),{conclusionRemark:ee,setConclusionRemark:U,conclusionLoading:ce,conclusionSubmitting:le,aiGenerated:ye,handleGenerateConclusion:de,handleFinalizeConclusion:ke}=K0(T,n,L,S,s,Hs,$e);g.useEffect(()=>{const Ct=new URLSearchParams(window.location.search).get("tab");Ct&&c(Ct)},[n]);const ge=()=>{S()},Pe=()=>{j(!0)},Xt=async()=>{var mt,Ct;if(!(E!=null&&E.requestId)){fe.error("Request ID not found");return}try{await Jd(E.requestId),fe.success("Workflow resumed successfully"),S()}catch(cs){fe.error(((Ct=(mt=cs==null?void 0:cs.response)==null?void 0:mt.data)==null?void 0:Ct.error)||"Failed to resume workflow")}},vt=()=>{R(!0)},_e=async()=>{S()},Ee=async()=>{S()},ze=async()=>{var mt,Ct,cs,Vo;if(!(E!=null&&E.requestId)){fe.error("Request ID not found");return}try{let Pt=u;if(!Pt){Pt=(await dl(E.requestId)).summaryId,h(Pt);try{const sn=await Jn(Pt);p(sn)}catch(sn){console.error("Failed to fetch summary details after creation:",sn)}}Pt&&m(!0)}catch(Pt){console.error("Failed to create/get summary:",Pt);const Bo=((Ct=(mt=Pt==null?void 0:Pt.response)==null?void 0:mt.data)==null?void 0:Ct.error)||((Vo=(cs=Pt==null?void 0:Pt.response)==null?void 0:cs.data)==null?void 0:Vo.message)||(Pt==null?void 0:Pt.message);fe.error(Bo||"Failed to prepare summary for sharing")}},zt=((T==null?void 0:T.status)==="approved"||(T==null?void 0:T.status)==="rejected")&&L,tt=(T==null?void 0:T.status)==="closed"||(T==null?void 0:T.status)==="approved"&&!L||(T==null?void 0:T.status)==="rejected"&&!L;g.useEffect(()=>{(async()=>{if(!tt||!(E!=null&&E.requestId)){p(null),h(null);return}try{v(!0);const Ct=await dl(E.requestId);if(Ct!=null&&Ct.summaryId){h(Ct.summaryId);try{const cs=await Jn(Ct.summaryId);p(cs)}catch(cs){console.error("Failed to fetch summary details:",cs),p(null),h(null)}}else p(null),h(null)}catch(Ct){console.error("Summary not available:",Ct==null?void 0:Ct.message),p(null),h(null)}finally{v(!1)}})()},[tt,E==null?void 0:E.requestId]);const Ea=((T==null?void 0:T.approvalFlow)||[]).filter(mt=>mt&&typeof mt.step=="number").map(mt=>({levelNumber:mt.step||0,approverName:mt.approver||"Unknown",status:mt.status||"pending",tatHours:mt.tatHours||24}));return!T&&!E?e.jsx("div",{className:"flex items-center justify-center h-screen","data-testid":"loading-state",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading request details..."})]})}):T?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"min-h-screen bg-gray-50","data-testid":"request-detail-page",children:e.jsxs("div",{className:"max-w-7xl mx-auto",children:[e.jsx(J0,{request:T,refreshing:w,onBack:s||(()=>window.history.back()),onRefresh:ge,onShareSummary:ze,isInitiator:L}),e.jsxs(Kr,{value:l,onValueChange:c,className:"w-full","data-testid":"request-detail-tabs",children:[e.jsx("div",{className:"mb-4 sm:mb-6",children:e.jsxs(Gr,{className:"grid grid-cols-3 sm:grid-cols-6 lg:flex lg:flex-row h-auto bg-gray-100 p-1.5 sm:p-1 rounded-lg gap-1.5 sm:gap-1",children:[e.jsxs(pt,{value:"overview",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900","data-testid":"tab-overview",children:[e.jsx(wx,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Overview"})]}),tt&&x&&e.jsxs(pt,{value:"summary",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900","data-testid":"tab-summary",children:[e.jsx(yd,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Summary"})]}),e.jsxs(pt,{value:"workflow",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900","data-testid":"tab-workflow",children:[e.jsx(Us,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Workflow"})]}),e.jsxs(pt,{value:"documents",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900","data-testid":"tab-documents",children:[e.jsx(Te,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Docs"})]}),e.jsxs(pt,{value:"activity",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900 col-span-1 sm:col-span-1","data-testid":"tab-activity",children:[e.jsx(as,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Activity"})]}),e.jsxs(pt,{value:"worknotes",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900 relative col-span-2 sm:col-span-1","data-testid":"tab-worknotes",children:[e.jsx(ws,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Work Notes"}),k>0&&e.jsx(Q,{className:"absolute -top-1 -right-1 h-5 w-5 rounded-full bg-red-500 text-white text-[10px] flex items-center justify-center p-0","data-testid":"worknotes-unread-badge",children:k>9?"9+":k})]})]})}),e.jsxs("div",{className:l==="worknotes"?"":"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs("div",{className:l==="worknotes"?"":"lg:col-span-2",children:[e.jsx(xt,{value:"overview",className:"mt-0","data-testid":"overview-tab-content",children:e.jsx(hy,{request:T,isInitiator:L,needsClosure:zt,conclusionRemark:ee,setConclusionRemark:U,conclusionLoading:ce,conclusionSubmitting:le,aiGenerated:ye,handleGenerateConclusion:de,handleFinalizeConclusion:ke,onPause:Pe,onResume:Xt,onRetrigger:vt,currentUserIsApprover:!!D,pausedByUserId:(lr=(ma=T==null?void 0:T.pauseInfo)==null?void 0:ma.pausedBy)==null?void 0:lr.userId,currentUserId:I==null?void 0:I.userId})}),tt&&e.jsx(xt,{value:"summary",className:"mt-0","data-testid":"summary-tab-content",children:e.jsx(Sy,{summary:x,loading:y,onShare:ze,isInitiator:L})}),e.jsx(xt,{value:"workflow",className:"mt-0",children:e.jsx(gy,{request:T,user:I,isInitiator:L,onSkipApprover:mt=>{if(!mt.levelId){alert("Level ID not available");return}Fe(mt),Oe(!0)},onRefresh:S})}),e.jsx(xt,{value:"documents",className:"mt-0",children:e.jsx(yy,{request:T,workNoteAttachments:P,uploadingDocument:W,documentPolicy:ne,triggerFileInput:Z,setPreviewDocument:$,downloadDocument:Tr})}),e.jsx(xt,{value:"activity",className:"mt-0",children:e.jsx(vy,{request:T})}),e.jsx(xt,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:l!=="worknotes",children:e.jsx(Cy,{requestId:n,requestTitle:T.title,mergedMessages:A,setWorkNoteAttachments:_,isInitiator:L,isSpectator:H,currentLevels:Ea,onAddApprover:da})})]}),l!=="worknotes"&&e.jsx(Ay,{request:T,isInitiator:L,isSpectator:H,currentApprovalLevel:D,onAddApprover:()=>ue(!0),onAddSpectator:()=>Ie(!0),onApprove:()=>re(!0),onReject:()=>B(!0),onPause:Pe,onResume:Xt,onRetrigger:vt,summaryId:u,refreshTrigger:N,pausedByUserId:(We=(cr=T==null?void 0:T.pauseInfo)==null?void 0:cr.pausedBy)==null?void 0:We.userId,currentUserId:I==null?void 0:I.userId})]})]})]})}),d&&u&&e.jsx(cy,{isOpen:d,onClose:()=>m(!1),summaryId:u,requestTitle:(T==null?void 0:T.title)||"N/A",onSuccess:()=>{S(),f(mt=>mt+1)}}),b&&(E==null?void 0:E.requestId)&&e.jsx(Ey,{isOpen:b,onClose:()=>j(!1),requestId:E.requestId,levelId:(D==null?void 0:D.levelId)||null,onSuccess:_e}),C&&(E==null?void 0:E.requestId)&&e.jsx(My,{isOpen:C,onClose:()=>R(!1),requestId:E.requestId,approverName:(Uo=($o=T==null?void 0:T.pauseInfo)==null?void 0:$o.pausedBy)==null?void 0:Uo.name,onSuccess:Ee}),e.jsx(Py,{showApproveModal:z,showRejectModal:K,showAddApproverModal:J,showAddSpectatorModal:be,showSkipApproverModal:Ve,showActionStatusModal:Ue,previewDocument:ae,documentError:me,request:T,skipApproverData:Dt,actionStatus:Ra,existingParticipants:F,currentLevels:Ea,setShowApproveModal:re,setShowRejectModal:B,setShowAddApproverModal:ue,setShowAddSpectatorModal:Ie,setShowSkipApproverModal:Oe,setShowActionStatusModal:$e,setPreviewDocument:$,setDocumentError:q,setSkipApproverData:Fe,setActionStatus:Hs,handleApproveConfirm:Da,handleRejectConfirm:Pa,handleAddApprover:da,handleAddSpectator:O,handleSkipApprover:Ss,downloadDocument:Tr,documentPolicy:ne})]}):e.jsx("div",{className:"flex items-center justify-center h-screen","data-testid":"not-found-state",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Request Not Found"}),e.jsx("p",{className:"text-gray-600 mb-4",children:"The request you're looking for doesn't exist."}),e.jsx(M,{onClick:s,children:"Go Back"})]})})}function Ly(t){return e.jsx(Iy,{children:e.jsx(_y,{...t})})}function Fy({onViewSummary:t}){const s=Bs(),[a,r]=g.useState([]),[n,i]=g.useState(!0),[o,l]=g.useState(""),[c,d]=g.useState(1),[m,u]=g.useState(1),[h,x]=g.useState(0),p=10,y=g.useCallback(async(b=1)=>{try{i(!0);const j=await sy({page:b,limit:p});r(j.data||[]),u(j.pagination.totalPages||1),x(j.pagination.total||0),d(j.pagination.page||1)}catch(j){console.error("Failed to fetch shared summaries:",j),fe.error("Failed to load shared summaries")}finally{i(!1)}},[]);g.useEffect(()=>{y(1)},[y]);const v=async b=>{try{await dm(b),r(j=>j.map(C=>C.sharedSummaryId===b?{...C,isRead:!0,viewedAt:new Date().toISOString()}:C)),t?t(b):s(`/shared-summaries/${b}`)}catch(j){console.error("Failed to mark as viewed:",j),t?t(b):s(`/shared-summaries/${b}`)}},N=b=>{b>=1&&b<=m&&y(b)},f=a.filter(b=>{var C,R,I,T;if(!o)return!0;const j=o.toLowerCase();return((C=b.title)==null?void 0:C.toLowerCase().includes(j))||((R=b.requestNumber)==null?void 0:R.toLowerCase().includes(j))||((I=b.initiatorName)==null?void 0:I.toLowerCase().includes(j))||((T=b.sharedByName)==null?void 0:T.toLowerCase().includes(j))});return e.jsx("div",{className:"min-h-screen bg-gray-50 p-3 sm:p-4 md:p-6 overflow-x-hidden",children:e.jsxs("div",{className:"max-w-7xl mx-auto w-full",children:[e.jsxs("div",{className:"mb-4 sm:mb-6",children:[e.jsx("h1",{className:"text-xl sm:text-2xl md:text-3xl font-bold text-gray-900 mb-1 sm:mb-2",children:"Shared Summaries"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600",children:"View summaries of closed requests shared with you"})]}),e.jsx("div",{className:"mb-4 sm:mb-6",children:e.jsxs("div",{className:"relative",children:[e.jsx(Yt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(xe,{placeholder:"Search by title, request number, or user...",value:o,onChange:b=>l(b.target.value),className:"pl-10 text-sm sm:text-base"})]})}),n&&e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Le,{className:"h-8 w-8 animate-spin text-blue-600"})}),!n&&f.length===0&&e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border border-gray-200 p-6 sm:p-12 text-center",children:[e.jsx(Te,{className:"h-8 w-8 sm:h-12 sm:w-12 text-gray-400 mx-auto mb-3 sm:mb-4"}),e.jsx("h3",{className:"text-base sm:text-lg font-semibold text-gray-900 mb-1 sm:mb-2",children:"No shared summaries"}),e.jsx("p",{className:"text-sm sm:text-base text-gray-600",children:o?"No summaries match your search.":"You haven't received any shared summaries yet."})]}),!n&&f.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid gap-3 sm:gap-4 mb-4 sm:mb-6",children:f.map(b=>e.jsx("div",{className:`bg-white rounded-lg shadow-sm border-2 transition-all cursor-pointer hover:shadow-md ${b.isRead?"border-gray-200":"border-blue-300 bg-blue-50"}`,onClick:()=>v(b.sharedSummaryId),children:e.jsx("div",{className:"p-3 sm:p-4 md:p-6",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0 w-full sm:w-auto",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[b.isRead?e.jsx(fr,{className:"h-4 w-4 text-gray-400 flex-shrink-0"}):e.jsx(At,{className:"h-4 w-4 text-blue-600 flex-shrink-0"}),e.jsx("h3",{className:"text-base sm:text-lg font-semibold text-gray-900 truncate flex-1 min-w-0",children:b.title}),!b.isRead&&e.jsx("span",{className:"px-2 py-0.5 bg-blue-100 text-blue-700 text-xs font-medium rounded-full flex-shrink-0",children:"New"})]}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-600 mb-2 sm:mb-3 break-words",children:["Request: ",e.jsx("span",{className:"font-medium",children:b.requestNumber})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:flex-wrap items-start sm:items-center gap-2 sm:gap-3 md:gap-4 text-xs sm:text-sm text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(rt,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Initiator: ",e.jsx("span",{className:"font-medium",children:b.initiatorName})]})]}),e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(rt,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Shared by: ",e.jsx("span",{className:"font-medium",children:b.sharedByName})]})]}),e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(qe,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Shared: ",pe(new Date(b.sharedAt),"MMM dd, yyyy HH:mm")]})]}),b.viewedAt&&e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(At,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Viewed: ",pe(new Date(b.viewedAt),"MMM dd, yyyy HH:mm")]})]})]})]}),e.jsx(M,{variant:"outline",size:"sm",className:"w-full sm:w-auto flex-shrink-0",onClick:j=>{j.stopPropagation(),v(b.sharedSummaryId)},children:"View"})]})})},b.sharedSummaryId))}),m>1&&e.jsxs("div",{className:"flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-3 sm:gap-4 bg-white rounded-lg shadow-sm border border-gray-200 p-3 sm:p-4",children:[e.jsxs("div",{className:"text-xs sm:text-sm text-gray-600 text-center sm:text-left",children:["Showing ",(c-1)*p+1," to ",Math.min(c*p,h)," of ",h," summaries"]}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.jsx(M,{variant:"outline",size:"sm",onClick:()=>N(c-1),disabled:c===1,className:"text-xs sm:text-sm",children:"Previous"}),e.jsxs("span",{className:"text-xs sm:text-sm text-gray-600 whitespace-nowrap",children:["Page ",c," of ",m]}),e.jsx(M,{variant:"outline",size:"sm",onClick:()=>N(c+1),disabled:c===m,className:"text-xs sm:text-sm",children:"Next"})]})]})]})]})})}function Oy(){const{sharedSummaryId:t}=Ja(),s=Bs(),[a,r]=g.useState(null),[n,i]=g.useState(!0);g.useEffect(()=>{if(!t){s("/shared-summaries");return}(async()=>{var m,u;try{i(!0);try{await dm(t)}catch(x){console.warn("Failed to mark as viewed:",x)}const h=await Jn(t);r(h)}catch(h){console.error("Failed to fetch summary details:",h),fe.error(((u=(m=h==null?void 0:h.response)==null?void 0:m.data)==null?void 0:u.message)||"Failed to load summary"),s("/shared-summaries")}finally{i(!1)}})()},[t,s]);const o=d=>{const m=d.toLowerCase();return m==="approved"?e.jsx(ve,{className:"h-4 w-4 text-green-600"}):m==="rejected"?e.jsx(Ze,{className:"h-4 w-4 text-red-600"}):m==="pending"||m==="in progress"?e.jsx(De,{className:"h-4 w-4 text-orange-600"}):e.jsx(Te,{className:"h-4 w-4 text-gray-600"})},l=d=>{const m=d.toLowerCase();return m==="approved"?"bg-green-100 text-green-700 border-green-300":m==="rejected"?"bg-red-100 text-red-700 border-red-300":m==="pending"||m==="in progress"?"bg-orange-100 text-orange-700 border-orange-300":"bg-gray-100 text-gray-700 border-gray-300"},c=(d,m)=>d&&d.trim()&&d.trim().toUpperCase()!=="N/A"?d:m&&m.trim()&&m.trim().toUpperCase()!=="N/A"?m:"N/A";return n?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Le,{className:"h-12 w-12 animate-spin text-blue-600 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading summary..."})]})}):a?e.jsx("div",{className:"min-h-screen bg-gray-50 p-4 sm:p-6",children:e.jsxs("div",{className:"max-w-5xl mx-auto",children:[e.jsxs("div",{className:"mb-6",children:[e.jsxs(M,{variant:"ghost",size:"sm",onClick:()=>s("/shared-summaries"),className:"mb-4",children:[e.jsx(_s,{className:"h-4 w-4 mr-2"}),"Back to Shared Summaries"]}),e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold text-gray-900 mb-2",children:"Request Summary"})]}),e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border border-gray-200 mb-6",children:[e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-2",children:a.title}),e.jsxs("p",{className:"text-sm text-gray-600",children:["Request #",a.requestNumber]})]}),e.jsxs(Q,{className:l(a.workflow.status),children:[o(a.workflow.status),e.jsx("span",{className:"ml-1 capitalize",children:a.workflow.status})]})]}),a.description&&e.jsx("div",{className:"mb-4",children:e.jsx(Ms,{content:a.description,className:"text-gray-700"})})]}),e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Initiator"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:a.initiator.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:c(a.initiator.designation,a.initiator.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:a.initiator.status})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Time Stamp"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:pe(new Date(a.initiator.timestamp),"MMM dd, yy, HH:mm")})]})]})]}),a.approvers&&a.approvers.length>0&&e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Workflow"}),a.approvers.map((d,m)=>e.jsxs("div",{className:"mb-6 last:mb-0",children:[e.jsxs("h4",{className:"text-md font-semibold text-gray-800 mb-3",children:["Approver ",d.levelNumber]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:d.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:c(d.designation,d.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsxs("div",{className:"flex items-center gap-1",children:[o(d.status),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:d.status})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Time Stamp"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:pe(new Date(d.timestamp),"MMM dd, yy, HH:mm")})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Remarks"}),e.jsx("p",{className:"text-sm text-gray-700",children:d.remarks})]})]},m))]}),e.jsxs("div",{className:"p-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Closing Remarks (Conclusion)"}),e.jsxs("div",{className:"bg-gray-50 rounded-lg p-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:a.initiator.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:c(a.initiator.designation,a.initiator.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:"Concluded"})]}),a.isAiGenerated&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Source"}),e.jsx(Q,{variant:"outline",className:"text-xs",children:"AI Generated"})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Remarks"}),a.closingRemarks?e.jsx(Ms,{content:a.closingRemarks,className:"text-sm text-gray-700"}):e.jsx("p",{className:"text-sm text-gray-700",children:"—"})]})]})]})]})]})}):e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Te,{className:"h-12 w-12 text-gray-400 mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Summary Not Found"}),e.jsx("p",{className:"text-gray-600 mb-4",children:"The summary you're looking for doesn't exist."}),e.jsx(M,{onClick:()=>s("/shared-summaries"),children:"Go Back"})]})})}function $y(){const{requestId:t}=Ja(),s=Bs(),a=i=>{s(`/${i}`)},r=()=>{s("/new-request")},n=()=>{s("/login")};return e.jsx(Et,{currentPage:"work-notes",onNavigate:a,onNewRequest:r,onLogout:n,children:e.jsx("div",{className:"h-full w-full overflow-hidden",children:e.jsx(fm,{requestId:t||""})})})}const Wi=g.createContext({});function Ki(t){const s=g.useRef(null);return s.current===null&&(s.current=t()),s.current}const Gi=typeof window<"u",ym=Gi?g.useLayoutEffect:g.useEffect,Zr=g.createContext(null);function Yi(t,s){t.indexOf(s)===-1&&t.push(s)}function Zi(t,s){const a=t.indexOf(s);a>-1&&t.splice(a,1)}const js=(t,s,a)=>a>s?s:a{};const Ns={},vm=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function bm(t){return typeof t=="object"&&t!==null}const jm=t=>/^0[^.\s]+$/u.test(t);function Qi(t){let s;return()=>(s===void 0&&(s=t()),s)}const ss=t=>t,Uy=(t,s)=>a=>s(t(a)),tr=(...t)=>t.reduce(Uy),Wa=(t,s,a)=>{const r=s-t;return r===0?1:(a-t)/r};class Ji{constructor(){this.subscriptions=[]}add(s){return Yi(this.subscriptions,s),()=>Zi(this.subscriptions,s)}notify(s,a,r){const n=this.subscriptions.length;if(n)if(n===1)this.subscriptions[0](s,a,r);else for(let i=0;it*1e3,es=t=>t/1e3;function Nm(t,s){return s?t*(1e3/s):0}const wm=(t,s,a)=>(((1-3*a+3*s)*t+(3*a-6*s))*t+3*s)*t,Vy=1e-7,By=12;function zy(t,s,a,r,n){let i,o,l=0;do o=s+(a-s)/2,i=wm(o,r,n)-t,i>0?a=o:s=o;while(Math.abs(i)>Vy&&++lzy(i,0,1,t,a);return i=>i===0||i===1?i:wm(n(i),s,r)}const Cm=t=>s=>s<=.5?t(2*s)/2:(2-t(2*(1-s)))/2,Sm=t=>s=>1-t(1-s),Am=sr(.33,1.53,.69,.99),eo=Sm(Am),Tm=Cm(eo),km=t=>(t*=2)<1?.5*eo(t):.5*(2-Math.pow(2,-10*(t-1))),to=t=>1-Math.sin(Math.acos(t)),Rm=Sm(to),Dm=Cm(to),Hy=sr(.42,0,1,1),qy=sr(0,0,.58,1),Pm=sr(.42,0,.58,1),Wy=t=>Array.isArray(t)&&typeof t[0]!="number",Em=t=>Array.isArray(t)&&typeof t[0]=="number",Ky={linear:ss,easeIn:Hy,easeInOut:Pm,easeOut:qy,circIn:to,circInOut:Dm,circOut:Rm,backIn:eo,backInOut:Tm,backOut:Am,anticipate:km},Gy=t=>typeof t=="string",pl=t=>{if(Em(t)){Xi(t.length===4);const[s,a,r,n]=t;return sr(s,a,r,n)}else if(Gy(t))return Ky[t];return t},ur=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function Yy(t,s){let a=new Set,r=new Set,n=!1,i=!1;const o=new WeakSet;let l={delta:0,timestamp:0,isProcessing:!1};function c(m){o.has(m)&&(d.schedule(m),t()),m(l)}const d={schedule:(m,u=!1,h=!1)=>{const p=h&&n?a:r;return u&&o.add(m),p.has(m)||p.add(m),m},cancel:m=>{r.delete(m),o.delete(m)},process:m=>{if(l=m,n){i=!0;return}n=!0,[a,r]=[r,a],a.forEach(c),a.clear(),n=!1,i&&(i=!1,d.process(m))}};return d}const Zy=40;function Mm(t,s){let a=!1,r=!0;const n={delta:0,timestamp:0,isProcessing:!1},i=()=>a=!0,o=ur.reduce((b,j)=>(b[j]=Yy(i),b),{}),{setup:l,read:c,resolveKeyframes:d,preUpdate:m,update:u,preRender:h,render:x,postRender:p}=o,y=()=>{const b=Ns.useManualTiming?n.timestamp:performance.now();a=!1,Ns.useManualTiming||(n.delta=r?1e3/60:Math.max(Math.min(b-n.timestamp,Zy),1)),n.timestamp=b,n.isProcessing=!0,l.process(n),c.process(n),d.process(n),m.process(n),u.process(n),h.process(n),x.process(n),p.process(n),n.isProcessing=!1,a&&s&&(r=!1,t(y))},v=()=>{a=!0,r=!0,n.isProcessing||t(y)};return{schedule:ur.reduce((b,j)=>{const C=o[j];return b[j]=(R,I=!1,T=!1)=>(a||v(),C.schedule(R,I,T)),b},{}),cancel:b=>{for(let j=0;j(br===void 0&&Vt.set(kt.isProcessing||Ns.useManualTiming?kt.timestamp:performance.now()),br),set:t=>{br=t,queueMicrotask(Xy)}},Im=t=>s=>typeof s=="string"&&s.startsWith(t),so=Im("--"),Qy=Im("var(--"),ao=t=>Qy(t)?Jy.test(t.split("/*")[0].trim()):!1,Jy=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,Aa={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},Ka={...Aa,transform:t=>js(0,1,t)},hr={...Aa,default:1},$a=t=>Math.round(t*1e5)/1e5,ro=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function ev(t){return t==null}const tv=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,no=(t,s)=>a=>!!(typeof a=="string"&&tv.test(a)&&a.startsWith(t)||s&&!ev(a)&&Object.prototype.hasOwnProperty.call(a,s)),_m=(t,s,a)=>r=>{if(typeof r!="string")return r;const[n,i,o,l]=r.match(ro);return{[t]:parseFloat(n),[s]:parseFloat(i),[a]:parseFloat(o),alpha:l!==void 0?parseFloat(l):1}},sv=t=>js(0,255,t),bn={...Aa,transform:t=>Math.round(sv(t))},ta={test:no("rgb","red"),parse:_m("red","green","blue"),transform:({red:t,green:s,blue:a,alpha:r=1})=>"rgba("+bn.transform(t)+", "+bn.transform(s)+", "+bn.transform(a)+", "+$a(Ka.transform(r))+")"};function av(t){let s="",a="",r="",n="";return t.length>5?(s=t.substring(1,3),a=t.substring(3,5),r=t.substring(5,7),n=t.substring(7,9)):(s=t.substring(1,2),a=t.substring(2,3),r=t.substring(3,4),n=t.substring(4,5),s+=s,a+=a,r+=r,n+=n),{red:parseInt(s,16),green:parseInt(a,16),blue:parseInt(r,16),alpha:n?parseInt(n,16)/255:1}}const ei={test:no("#"),parse:av,transform:ta.transform},ar=t=>({test:s=>typeof s=="string"&&s.endsWith(t)&&s.split(" ").length===1,parse:parseFloat,transform:s=>`${s}${t}`}),ks=ar("deg"),ms=ar("%"),je=ar("px"),rv=ar("vh"),nv=ar("vw"),xl={...ms,parse:t=>ms.parse(t)/100,transform:t=>ms.transform(t*100)},ha={test:no("hsl","hue"),parse:_m("hue","saturation","lightness"),transform:({hue:t,saturation:s,lightness:a,alpha:r=1})=>"hsla("+Math.round(t)+", "+ms.transform($a(s))+", "+ms.transform($a(a))+", "+$a(Ka.transform(r))+")"},ht={test:t=>ta.test(t)||ei.test(t)||ha.test(t),parse:t=>ta.test(t)?ta.parse(t):ha.test(t)?ha.parse(t):ei.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?ta.transform(t):ha.transform(t),getAnimatableNone:t=>{const s=ht.parse(t);return s.alpha=0,ht.transform(s)}},iv=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function ov(t){var s,a;return isNaN(t)&&typeof t=="string"&&(((s=t.match(ro))==null?void 0:s.length)||0)+(((a=t.match(iv))==null?void 0:a.length)||0)>0}const Lm="number",Fm="color",lv="var",cv="var(",gl="${}",dv=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function Ga(t){const s=t.toString(),a=[],r={color:[],number:[],var:[]},n=[];let i=0;const l=s.replace(dv,c=>(ht.test(c)?(r.color.push(i),n.push(Fm),a.push(ht.parse(c))):c.startsWith(cv)?(r.var.push(i),n.push(lv),a.push(c)):(r.number.push(i),n.push(Lm),a.push(parseFloat(c))),++i,gl)).split(gl);return{values:a,split:l,indexes:r,types:n}}function Om(t){return Ga(t).values}function $m(t){const{split:s,types:a}=Ga(t),r=s.length;return n=>{let i="";for(let o=0;otypeof t=="number"?0:ht.test(t)?ht.getAnimatableNone(t):t;function uv(t){const s=Om(t);return $m(t)(s.map(mv))}const $s={test:ov,parse:Om,createTransformer:$m,getAnimatableNone:uv};function jn(t,s,a){return a<0&&(a+=1),a>1&&(a-=1),a<1/6?t+(s-t)*6*a:a<1/2?s:a<2/3?t+(s-t)*(2/3-a)*6:t}function hv({hue:t,saturation:s,lightness:a,alpha:r}){t/=360,s/=100,a/=100;let n=0,i=0,o=0;if(!s)n=i=o=a;else{const l=a<.5?a*(1+s):a+s-a*s,c=2*a-l;n=jn(c,l,t+1/3),i=jn(c,l,t),o=jn(c,l,t-1/3)}return{red:Math.round(n*255),green:Math.round(i*255),blue:Math.round(o*255),alpha:r}}function kr(t,s){return a=>a>0?s:t}const Qe=(t,s,a)=>t+(s-t)*a,Nn=(t,s,a)=>{const r=t*t,n=a*(s*s-r)+r;return n<0?0:Math.sqrt(n)},pv=[ei,ta,ha],xv=t=>pv.find(s=>s.test(t));function fl(t){const s=xv(t);if(!s)return!1;let a=s.parse(t);return s===ha&&(a=hv(a)),a}const yl=(t,s)=>{const a=fl(t),r=fl(s);if(!a||!r)return kr(t,s);const n={...a};return i=>(n.red=Nn(a.red,r.red,i),n.green=Nn(a.green,r.green,i),n.blue=Nn(a.blue,r.blue,i),n.alpha=Qe(a.alpha,r.alpha,i),ta.transform(n))},ti=new Set(["none","hidden"]);function gv(t,s){return ti.has(t)?a=>a<=0?t:s:a=>a>=1?s:t}function fv(t,s){return a=>Qe(t,s,a)}function io(t){return typeof t=="number"?fv:typeof t=="string"?ao(t)?kr:ht.test(t)?yl:bv:Array.isArray(t)?Um:typeof t=="object"?ht.test(t)?yl:yv:kr}function Um(t,s){const a=[...t],r=a.length,n=t.map((i,o)=>io(i)(i,s[o]));return i=>{for(let o=0;o{for(const i in r)a[i]=r[i](n);return a}}function vv(t,s){const a=[],r={color:0,var:0,number:0};for(let n=0;n{const a=$s.createTransformer(s),r=Ga(t),n=Ga(s);return r.indexes.var.length===n.indexes.var.length&&r.indexes.color.length===n.indexes.color.length&&r.indexes.number.length>=n.indexes.number.length?ti.has(t)&&!n.values.length||ti.has(s)&&!r.values.length?gv(t,s):tr(Um(vv(r,n),n.values),a):kr(t,s)};function Vm(t,s,a){return typeof t=="number"&&typeof s=="number"&&typeof a=="number"?Qe(t,s,a):io(t)(t,s)}const jv=t=>{const s=({timestamp:a})=>t(a);return{start:(a=!0)=>Ye.update(s,a),stop:()=>Os(s),now:()=>kt.isProcessing?kt.timestamp:Vt.now()}},Bm=(t,s,a=10)=>{let r="";const n=Math.max(Math.round(s/a),2);for(let i=0;i=Rr?1/0:s}function Nv(t,s=100,a){const r=a({...t,keyframes:[0,s]}),n=Math.min(oo(r),Rr);return{type:"keyframes",ease:i=>r.next(n*i).value/s,duration:es(n)}}const wv=5;function zm(t,s,a){const r=Math.max(s-wv,0);return Nm(a-t(r),s-r)}const st={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1},wn=.001;function Cv({duration:t=st.duration,bounce:s=st.bounce,velocity:a=st.velocity,mass:r=st.mass}){let n,i,o=1-s;o=js(st.minDamping,st.maxDamping,o),t=js(st.minDuration,st.maxDuration,es(t)),o<1?(n=d=>{const m=d*o,u=m*t,h=m-a,x=si(d,o),p=Math.exp(-u);return wn-h/x*p},i=d=>{const u=d*o*t,h=u*a+a,x=Math.pow(o,2)*Math.pow(d,2)*t,p=Math.exp(-u),y=si(Math.pow(d,2),o);return(-n(d)+wn>0?-1:1)*((h-x)*p)/y}):(n=d=>{const m=Math.exp(-d*t),u=(d-a)*t+1;return-wn+m*u},i=d=>{const m=Math.exp(-d*t),u=(a-d)*(t*t);return m*u});const l=5/t,c=Av(n,i,l);if(t=ds(t),isNaN(c))return{stiffness:st.stiffness,damping:st.damping,duration:t};{const d=Math.pow(c,2)*r;return{stiffness:d,damping:o*2*Math.sqrt(r*d),duration:t}}}const Sv=12;function Av(t,s,a){let r=a;for(let n=1;nt[a]!==void 0)}function Rv(t){let s={velocity:st.velocity,stiffness:st.stiffness,damping:st.damping,mass:st.mass,isResolvedFromDuration:!1,...t};if(!vl(t,kv)&&vl(t,Tv))if(t.visualDuration){const a=t.visualDuration,r=2*Math.PI/(a*1.2),n=r*r,i=2*js(.05,1,1-(t.bounce||0))*Math.sqrt(n);s={...s,mass:st.mass,stiffness:n,damping:i}}else{const a=Cv(t);s={...s,...a,mass:st.mass},s.isResolvedFromDuration=!0}return s}function Dr(t=st.visualDuration,s=st.bounce){const a=typeof t!="object"?{visualDuration:t,keyframes:[0,1],bounce:s}:t;let{restSpeed:r,restDelta:n}=a;const i=a.keyframes[0],o=a.keyframes[a.keyframes.length-1],l={done:!1,value:i},{stiffness:c,damping:d,mass:m,duration:u,velocity:h,isResolvedFromDuration:x}=Rv({...a,velocity:-es(a.velocity||0)}),p=h||0,y=d/(2*Math.sqrt(c*m)),v=o-i,N=es(Math.sqrt(c/m)),f=Math.abs(v)<5;r||(r=f?st.restSpeed.granular:st.restSpeed.default),n||(n=f?st.restDelta.granular:st.restDelta.default);let b;if(y<1){const C=si(N,y);b=R=>{const I=Math.exp(-y*N*R);return o-I*((p+y*N*v)/C*Math.sin(C*R)+v*Math.cos(C*R))}}else if(y===1)b=C=>o-Math.exp(-N*C)*(v+(p+N*v)*C);else{const C=N*Math.sqrt(y*y-1);b=R=>{const I=Math.exp(-y*N*R),T=Math.min(C*R,300);return o-I*((p+y*N*v)*Math.sinh(T)+C*v*Math.cosh(T))/C}}const j={calculatedDuration:x&&u||null,next:C=>{const R=b(C);if(x)l.done=C>=u;else{let I=C===0?p:0;y<1&&(I=C===0?ds(p):zm(b,C,R));const T=Math.abs(I)<=r,E=Math.abs(o-R)<=n;l.done=T&&E}return l.value=l.done?o:R,l},toString:()=>{const C=Math.min(oo(j),Rr),R=Bm(I=>j.next(C*I).value,C,30);return C+"ms "+R},toTransition:()=>{}};return j}Dr.applyToOptions=t=>{const s=Nv(t,100,Dr);return t.ease=s.ease,t.duration=ds(s.duration),t.type="keyframes",t};function ai({keyframes:t,velocity:s=0,power:a=.8,timeConstant:r=325,bounceDamping:n=10,bounceStiffness:i=500,modifyTarget:o,min:l,max:c,restDelta:d=.5,restSpeed:m}){const u=t[0],h={done:!1,value:u},x=T=>l!==void 0&&Tc,p=T=>l===void 0?c:c===void 0||Math.abs(l-T)-y*Math.exp(-T/r),b=T=>N+f(T),j=T=>{const E=f(T),w=b(T);h.done=Math.abs(E)<=d,h.value=h.done?N:w};let C,R;const I=T=>{x(h.value)&&(C=T,R=Dr({keyframes:[h.value,p(h.value)],velocity:zm(b,T,h.value),damping:n,stiffness:i,restDelta:d,restSpeed:m}))};return I(0),{calculatedDuration:null,next:T=>{let E=!1;return!R&&C===void 0&&(E=!0,j(T),I(T)),C!==void 0&&T>=C?R.next(T-C):(!E&&j(T),h)}}}function Dv(t,s,a){const r=[],n=a||Ns.mix||Vm,i=t.length-1;for(let o=0;os[0];if(i===2&&s[0]===s[1])return()=>s[1];const o=t[0]===t[1];t[0]>t[i-1]&&(t=[...t].reverse(),s=[...s].reverse());const l=Dv(s,r,n),c=l.length,d=m=>{if(o&&m1)for(;ud(js(t[0],t[i-1],m)):d}function Ev(t,s){const a=t[t.length-1];for(let r=1;r<=s;r++){const n=Wa(0,s,r);t.push(Qe(a,1,n))}}function Mv(t){const s=[0];return Ev(s,t.length-1),s}function Iv(t,s){return t.map(a=>a*s)}function _v(t,s){return t.map(()=>s||Pm).splice(0,t.length-1)}function Ua({duration:t=300,keyframes:s,times:a,ease:r="easeInOut"}){const n=Wy(r)?r.map(pl):pl(r),i={done:!1,value:s[0]},o=Iv(a&&a.length===s.length?a:Mv(s),t),l=Pv(o,s,{ease:Array.isArray(n)?n:_v(s,n)});return{calculatedDuration:t,next:c=>(i.value=l(c),i.done=c>=t,i)}}const Lv=t=>t!==null;function lo(t,{repeat:s,repeatType:a="loop"},r,n=1){const i=t.filter(Lv),l=n<0||s&&a!=="loop"&&s%2===1?0:i.length-1;return!l||r===void 0?i[l]:r}const Fv={decay:ai,inertia:ai,tween:Ua,keyframes:Ua,spring:Dr};function Hm(t){typeof t.type=="string"&&(t.type=Fv[t.type])}class co{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(s=>{this.resolve=s})}notifyFinished(){this.resolve()}then(s,a){return this.finished.then(s,a)}}const Ov=t=>t/100;class mo extends co{constructor(s){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{var r,n;const{motionValue:a}=this.options;a&&a.updatedAt!==Vt.now()&&this.tick(Vt.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),(n=(r=this.options).onStop)==null||n.call(r))},this.options=s,this.initAnimation(),this.play(),s.autoplay===!1&&this.pause()}initAnimation(){const{options:s}=this;Hm(s);const{type:a=Ua,repeat:r=0,repeatDelay:n=0,repeatType:i,velocity:o=0}=s;let{keyframes:l}=s;const c=a||Ua;c!==Ua&&typeof l[0]!="number"&&(this.mixKeyframes=tr(Ov,Vm(l[0],l[1])),l=[0,100]);const d=c({...s,keyframes:l});i==="mirror"&&(this.mirroredGenerator=c({...s,keyframes:[...l].reverse(),velocity:-o})),d.calculatedDuration===null&&(d.calculatedDuration=oo(d));const{calculatedDuration:m}=d;this.calculatedDuration=m,this.resolvedDuration=m+n,this.totalDuration=this.resolvedDuration*(r+1)-n,this.generator=d}updateTime(s){const a=Math.round(s-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=a}tick(s,a=!1){const{generator:r,totalDuration:n,mixKeyframes:i,mirroredGenerator:o,resolvedDuration:l,calculatedDuration:c}=this;if(this.startTime===null)return r.next(0);const{delay:d=0,keyframes:m,repeat:u,repeatType:h,repeatDelay:x,type:p,onUpdate:y,finalKeyframe:v}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,s):this.speed<0&&(this.startTime=Math.min(s-n/this.speed,this.startTime)),a?this.currentTime=s:this.updateTime(s);const N=this.currentTime-d*(this.playbackSpeed>=0?1:-1),f=this.playbackSpeed>=0?N<0:N>n;this.currentTime=Math.max(N,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=n);let b=this.currentTime,j=r;if(u){const T=Math.min(this.currentTime,n)/l;let E=Math.floor(T),w=T%1;!w&&T>=1&&(w=1),w===1&&E--,E=Math.min(E,u+1),!!(E%2)&&(h==="reverse"?(w=1-w,x&&(w-=x/l)):h==="mirror"&&(j=o)),b=js(0,1,w)*l}const C=f?{done:!1,value:m[0]}:j.next(b);i&&(C.value=i(C.value));let{done:R}=C;!f&&c!==null&&(R=this.playbackSpeed>=0?this.currentTime>=n:this.currentTime<=0);const I=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&R);return I&&p!==ai&&(C.value=lo(m,this.options,v,this.speed)),y&&y(C.value),I&&this.finish(),C}then(s,a){return this.finished.then(s,a)}get duration(){return es(this.calculatedDuration)}get iterationDuration(){const{delay:s=0}=this.options||{};return this.duration+es(s)}get time(){return es(this.currentTime)}set time(s){var a;s=ds(s),this.currentTime=s,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=s:this.driver&&(this.startTime=this.driver.now()-s/this.playbackSpeed),(a=this.driver)==null||a.start(!1)}get speed(){return this.playbackSpeed}set speed(s){this.updateTime(Vt.now());const a=this.playbackSpeed!==s;this.playbackSpeed=s,a&&(this.time=es(this.currentTime))}play(){var n,i;if(this.isStopped)return;const{driver:s=jv,startTime:a}=this.options;this.driver||(this.driver=s(o=>this.tick(o))),(i=(n=this.options).onPlay)==null||i.call(n);const r=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=r):this.holdTime!==null?this.startTime=r-this.holdTime:this.startTime||(this.startTime=a??r),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(Vt.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){var s,a;this.notifyFinished(),this.teardown(),this.state="finished",(a=(s=this.options).onComplete)==null||a.call(s)}cancel(){var s,a;this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),(a=(s=this.options).onCancel)==null||a.call(s)}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(s){return this.startTime=0,this.tick(s,!0)}attachTimeline(s){var a;return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),(a=this.driver)==null||a.stop(),s.observe(this)}}function $v(t){for(let s=1;st*180/Math.PI,ri=t=>{const s=sa(Math.atan2(t[1],t[0]));return ni(s)},Uv={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:ri,rotateZ:ri,skewX:t=>sa(Math.atan(t[1])),skewY:t=>sa(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},ni=t=>(t=t%360,t<0&&(t+=360),t),bl=ri,jl=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),Nl=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),Vv={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:jl,scaleY:Nl,scale:t=>(jl(t)+Nl(t))/2,rotateX:t=>ni(sa(Math.atan2(t[6],t[5]))),rotateY:t=>ni(sa(Math.atan2(-t[2],t[0]))),rotateZ:bl,rotate:bl,skewX:t=>sa(Math.atan(t[4])),skewY:t=>sa(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function ii(t){return t.includes("scale")?1:0}function oi(t,s){if(!t||t==="none")return ii(s);const a=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,n;if(a)r=Vv,n=a;else{const l=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=Uv,n=l}if(!n)return ii(s);const i=r[s],o=n[1].split(",").map(zv);return typeof i=="function"?i(o):o[i]}const Bv=(t,s)=>{const{transform:a="none"}=getComputedStyle(t);return oi(a,s)};function zv(t){return parseFloat(t.trim())}const Ta=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],ka=new Set(Ta),wl=t=>t===Aa||t===je,Hv=new Set(["x","y","z"]),qv=Ta.filter(t=>!Hv.has(t));function Wv(t){const s=[];return qv.forEach(a=>{const r=t.getValue(a);r!==void 0&&(s.push([a,r.get()]),r.set(a.startsWith("scale")?1:0))}),s}const na={width:({x:t},{paddingLeft:s="0",paddingRight:a="0"})=>t.max-t.min-parseFloat(s)-parseFloat(a),height:({y:t},{paddingTop:s="0",paddingBottom:a="0"})=>t.max-t.min-parseFloat(s)-parseFloat(a),top:(t,{top:s})=>parseFloat(s),left:(t,{left:s})=>parseFloat(s),bottom:({y:t},{top:s})=>parseFloat(s)+(t.max-t.min),right:({x:t},{left:s})=>parseFloat(s)+(t.max-t.min),x:(t,{transform:s})=>oi(s,"x"),y:(t,{transform:s})=>oi(s,"y")};na.translateX=na.x;na.translateY=na.y;const ia=new Set;let li=!1,ci=!1,di=!1;function qm(){if(ci){const t=Array.from(ia).filter(r=>r.needsMeasurement),s=new Set(t.map(r=>r.element)),a=new Map;s.forEach(r=>{const n=Wv(r);n.length&&(a.set(r,n),r.render())}),t.forEach(r=>r.measureInitialState()),s.forEach(r=>{r.render();const n=a.get(r);n&&n.forEach(([i,o])=>{var l;(l=r.getValue(i))==null||l.set(o)})}),t.forEach(r=>r.measureEndState()),t.forEach(r=>{r.suspendedScrollY!==void 0&&window.scrollTo(0,r.suspendedScrollY)})}ci=!1,li=!1,ia.forEach(t=>t.complete(di)),ia.clear()}function Wm(){ia.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(ci=!0)})}function Kv(){di=!0,Wm(),qm(),di=!1}class uo{constructor(s,a,r,n,i,o=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...s],this.onComplete=a,this.name=r,this.motionValue=n,this.element=i,this.isAsync=o}scheduleResolve(){this.state="scheduled",this.isAsync?(ia.add(this),li||(li=!0,Ye.read(Wm),Ye.resolveKeyframes(qm))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:s,name:a,element:r,motionValue:n}=this;if(s[0]===null){const i=n==null?void 0:n.get(),o=s[s.length-1];if(i!==void 0)s[0]=i;else if(r&&a){const l=r.readValue(a,o);l!=null&&(s[0]=l)}s[0]===void 0&&(s[0]=o),n&&i===void 0&&n.set(s[0])}$v(s)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(s=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,s),ia.delete(this)}cancel(){this.state==="scheduled"&&(ia.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Gv=t=>t.startsWith("--");function Yv(t,s,a){Gv(s)?t.style.setProperty(s,a):t.style[s]=a}const Zv=Qi(()=>window.ScrollTimeline!==void 0),Xv={};function Qv(t,s){const a=Qi(t);return()=>Xv[s]??a()}const Km=Qv(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Oa=([t,s,a,r])=>`cubic-bezier(${t}, ${s}, ${a}, ${r})`,Cl={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Oa([0,.65,.55,1]),circOut:Oa([.55,0,1,.45]),backIn:Oa([.31,.01,.66,-.59]),backOut:Oa([.33,1.53,.69,.99])};function Gm(t,s){if(t)return typeof t=="function"?Km()?Bm(t,s):"ease-out":Em(t)?Oa(t):Array.isArray(t)?t.map(a=>Gm(a,s)||Cl.easeOut):Cl[t]}function Jv(t,s,a,{delay:r=0,duration:n=300,repeat:i=0,repeatType:o="loop",ease:l="easeOut",times:c}={},d=void 0){const m={[s]:a};c&&(m.offset=c);const u=Gm(l,n);Array.isArray(u)&&(m.easing=u);const h={delay:r,duration:n,easing:Array.isArray(u)?"linear":u,fill:"both",iterations:i+1,direction:o==="reverse"?"alternate":"normal"};return d&&(h.pseudoElement=d),t.animate(m,h)}function Ym(t){return typeof t=="function"&&"applyToOptions"in t}function eb({type:t,...s}){return Ym(t)&&Km()?t.applyToOptions(s):(s.duration??(s.duration=300),s.ease??(s.ease="easeOut"),s)}class tb extends co{constructor(s){if(super(),this.finishedTime=null,this.isStopped=!1,!s)return;const{element:a,name:r,keyframes:n,pseudoElement:i,allowFlatten:o=!1,finalKeyframe:l,onComplete:c}=s;this.isPseudoElement=!!i,this.allowFlatten=o,this.options=s,Xi(typeof s.type!="string");const d=eb(s);this.animation=Jv(a,r,n,d,i),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const m=lo(n,this.options,l,this.speed);this.updateMotionValue?this.updateMotionValue(m):Yv(a,r,m),this.animation.cancel()}c==null||c(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){var s,a;(a=(s=this.animation).finish)==null||a.call(s)}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:s}=this;s==="idle"||s==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){var s,a;this.isPseudoElement||(a=(s=this.animation).commitStyles)==null||a.call(s)}get duration(){var a,r;const s=((r=(a=this.animation.effect)==null?void 0:a.getComputedTiming)==null?void 0:r.call(a).duration)||0;return es(Number(s))}get iterationDuration(){const{delay:s=0}=this.options||{};return this.duration+es(s)}get time(){return es(Number(this.animation.currentTime)||0)}set time(s){this.finishedTime=null,this.animation.currentTime=ds(s)}get speed(){return this.animation.playbackRate}set speed(s){s<0&&(this.finishedTime=null),this.animation.playbackRate=s}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(s){this.animation.startTime=s}attachTimeline({timeline:s,observe:a}){var r;return this.allowFlatten&&((r=this.animation.effect)==null||r.updateTiming({easing:"linear"})),this.animation.onfinish=null,s&&Zv()?(this.animation.timeline=s,ss):a(this)}}const Zm={anticipate:km,backInOut:Tm,circInOut:Dm};function sb(t){return t in Zm}function ab(t){typeof t.ease=="string"&&sb(t.ease)&&(t.ease=Zm[t.ease])}const Sl=10;class rb extends tb{constructor(s){ab(s),Hm(s),super(s),s.startTime&&(this.startTime=s.startTime),this.options=s}updateMotionValue(s){const{motionValue:a,onUpdate:r,onComplete:n,element:i,...o}=this.options;if(!a)return;if(s!==void 0){a.set(s);return}const l=new mo({...o,autoplay:!1}),c=ds(this.finishedTime??this.time);a.setWithVelocity(l.sample(c-Sl).value,l.sample(c).value,Sl),l.stop()}}const Al=(t,s)=>s==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&($s.test(t)||t==="0")&&!t.startsWith("url("));function nb(t){const s=t[0];if(t.length===1)return!0;for(let a=0;aObject.hasOwnProperty.call(Element.prototype,"animate"));function cb(t){var m;const{motionValue:s,name:a,repeatDelay:r,repeatType:n,damping:i,type:o}=t;if(!(((m=s==null?void 0:s.owner)==null?void 0:m.current)instanceof HTMLElement))return!1;const{onUpdate:c,transformTemplate:d}=s.owner.getProps();return lb()&&a&&ob.has(a)&&(a!=="transform"||!d)&&!c&&!r&&n!=="mirror"&&i!==0&&o!=="inertia"}const db=40;class mb extends co{constructor({autoplay:s=!0,delay:a=0,type:r="keyframes",repeat:n=0,repeatDelay:i=0,repeatType:o="loop",keyframes:l,name:c,motionValue:d,element:m,...u}){var p;super(),this.stop=()=>{var y,v;this._animation&&(this._animation.stop(),(y=this.stopTimeline)==null||y.call(this)),(v=this.keyframeResolver)==null||v.cancel()},this.createdAt=Vt.now();const h={autoplay:s,delay:a,type:r,repeat:n,repeatDelay:i,repeatType:o,name:c,motionValue:d,element:m,...u},x=(m==null?void 0:m.KeyframeResolver)||uo;this.keyframeResolver=new x(l,(y,v,N)=>this.onKeyframesResolved(y,v,h,!N),c,d,m),(p=this.keyframeResolver)==null||p.scheduleResolve()}onKeyframesResolved(s,a,r,n){this.keyframeResolver=void 0;const{name:i,type:o,velocity:l,delay:c,isHandoff:d,onUpdate:m}=r;this.resolvedAt=Vt.now(),ib(s,i,o,l)||((Ns.instantAnimations||!c)&&(m==null||m(lo(s,r,a))),s[0]=s[s.length-1],mi(r),r.repeat=0);const h={startTime:n?this.resolvedAt?this.resolvedAt-this.createdAt>db?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:a,...r,keyframes:s},x=!d&&cb(h)?new rb({...h,element:h.motionValue.owner.current}):new mo(h);x.finished.then(()=>this.notifyFinished()).catch(ss),this.pendingTimeline&&(this.stopTimeline=x.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=x}get finished(){return this._animation?this.animation.finished:this._finished}then(s,a){return this.finished.finally(s).then(()=>{})}get animation(){var s;return this._animation||((s=this.keyframeResolver)==null||s.resume(),Kv()),this._animation}get duration(){return this.animation.duration}get iterationDuration(){return this.animation.iterationDuration}get time(){return this.animation.time}set time(s){this.animation.time=s}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(s){this.animation.speed=s}get startTime(){return this.animation.startTime}attachTimeline(s){return this._animation?this.stopTimeline=this.animation.attachTimeline(s):this.pendingTimeline=s,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){var s;this._animation&&this.animation.cancel(),(s=this.keyframeResolver)==null||s.cancel()}}const ub=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function hb(t){const s=ub.exec(t);if(!s)return[,];const[,a,r,n]=s;return[`--${a??r}`,n]}function Xm(t,s,a=1){const[r,n]=hb(t);if(!r)return;const i=window.getComputedStyle(s).getPropertyValue(r);if(i){const o=i.trim();return vm(o)?parseFloat(o):o}return ao(n)?Xm(n,s,a+1):n}function ho(t,s){return(t==null?void 0:t[s])??(t==null?void 0:t.default)??t}const Qm=new Set(["width","height","top","left","right","bottom",...Ta]),pb={test:t=>t==="auto",parse:t=>t},Jm=t=>s=>s.test(t),eu=[Aa,je,ms,ks,nv,rv,pb],Tl=t=>eu.find(Jm(t));function xb(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||jm(t):!0}const gb=new Set(["brightness","contrast","saturate","opacity"]);function fb(t){const[s,a]=t.slice(0,-1).split("(");if(s==="drop-shadow")return t;const[r]=a.match(ro)||[];if(!r)return t;const n=a.replace(r,"");let i=gb.has(s)?1:0;return r!==a&&(i*=100),s+"("+i+n+")"}const yb=/\b([a-z-]*)\(.*?\)/gu,ui={...$s,getAnimatableNone:t=>{const s=t.match(yb);return s?s.map(fb).join(" "):t}},kl={...Aa,transform:Math.round},vb={rotate:ks,rotateX:ks,rotateY:ks,rotateZ:ks,scale:hr,scaleX:hr,scaleY:hr,scaleZ:hr,skew:ks,skewX:ks,skewY:ks,distance:je,translateX:je,translateY:je,translateZ:je,x:je,y:je,z:je,perspective:je,transformPerspective:je,opacity:Ka,originX:xl,originY:xl,originZ:je},po={borderWidth:je,borderTopWidth:je,borderRightWidth:je,borderBottomWidth:je,borderLeftWidth:je,borderRadius:je,radius:je,borderTopLeftRadius:je,borderTopRightRadius:je,borderBottomRightRadius:je,borderBottomLeftRadius:je,width:je,maxWidth:je,height:je,maxHeight:je,top:je,right:je,bottom:je,left:je,padding:je,paddingTop:je,paddingRight:je,paddingBottom:je,paddingLeft:je,margin:je,marginTop:je,marginRight:je,marginBottom:je,marginLeft:je,backgroundPositionX:je,backgroundPositionY:je,...vb,zIndex:kl,fillOpacity:Ka,strokeOpacity:Ka,numOctaves:kl},bb={...po,color:ht,backgroundColor:ht,outlineColor:ht,fill:ht,stroke:ht,borderColor:ht,borderTopColor:ht,borderRightColor:ht,borderBottomColor:ht,borderLeftColor:ht,filter:ui,WebkitFilter:ui},tu=t=>bb[t];function su(t,s){let a=tu(t);return a!==ui&&(a=$s),a.getAnimatableNone?a.getAnimatableNone(s):void 0}const jb=new Set(["auto","none","0"]);function Nb(t,s,a){let r=0,n;for(;r{s.getValue(c).set(d)}),this.resolveNoneKeyframes()}}function Cb(t,s,a){if(t instanceof EventTarget)return[t];if(typeof t=="string"){let r=document;const n=(a==null?void 0:a[t])??r.querySelectorAll(t);return n?Array.from(n):[]}return Array.from(t)}const au=(t,s)=>s&&typeof t=="number"?s.transform(t):t;function ru(t){return bm(t)&&"offsetHeight"in t}const Rl=30,Sb=t=>!isNaN(parseFloat(t));class Ab{constructor(s,a={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=r=>{var i;const n=Vt.now();if(this.updatedAt!==n&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(r),this.current!==this.prev&&((i=this.events.change)==null||i.notify(this.current),this.dependents))for(const o of this.dependents)o.dirty()},this.hasAnimated=!1,this.setCurrent(s),this.owner=a.owner}setCurrent(s){this.current=s,this.updatedAt=Vt.now(),this.canTrackVelocity===null&&s!==void 0&&(this.canTrackVelocity=Sb(this.current))}setPrevFrameValue(s=this.current){this.prevFrameValue=s,this.prevUpdatedAt=this.updatedAt}onChange(s){return this.on("change",s)}on(s,a){this.events[s]||(this.events[s]=new Ji);const r=this.events[s].add(a);return s==="change"?()=>{r(),Ye.read(()=>{this.events.change.getSize()||this.stop()})}:r}clearListeners(){for(const s in this.events)this.events[s].clear()}attach(s,a){this.passiveEffect=s,this.stopPassiveEffect=a}set(s){this.passiveEffect?this.passiveEffect(s,this.updateAndNotify):this.updateAndNotify(s)}setWithVelocity(s,a,r){this.set(a),this.prev=void 0,this.prevFrameValue=s,this.prevUpdatedAt=this.updatedAt-r}jump(s,a=!0){this.updateAndNotify(s),this.prev=s,this.prevUpdatedAt=this.prevFrameValue=void 0,a&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){var s;(s=this.events.change)==null||s.notify(this.current)}addDependent(s){this.dependents||(this.dependents=new Set),this.dependents.add(s)}removeDependent(s){this.dependents&&this.dependents.delete(s)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const s=Vt.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||s-this.updatedAt>Rl)return 0;const a=Math.min(this.updatedAt-this.prevUpdatedAt,Rl);return Nm(parseFloat(this.current)-parseFloat(this.prevFrameValue),a)}start(s){return this.stop(),new Promise(a=>{this.hasAnimated=!0,this.animation=s(a),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){var s,a;(s=this.dependents)==null||s.clear(),(a=this.events.destroy)==null||a.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function ja(t,s){return new Ab(t,s)}const{schedule:xo}=Mm(queueMicrotask,!1),rs={x:!1,y:!1};function nu(){return rs.x||rs.y}function Tb(t){return t==="x"||t==="y"?rs[t]?null:(rs[t]=!0,()=>{rs[t]=!1}):rs.x||rs.y?null:(rs.x=rs.y=!0,()=>{rs.x=rs.y=!1})}function iu(t,s){const a=Cb(t),r=new AbortController,n={passive:!0,...s,signal:r.signal};return[a,n,()=>r.abort()]}function Dl(t){return!(t.pointerType==="touch"||nu())}function kb(t,s,a={}){const[r,n,i]=iu(t,a),o=l=>{if(!Dl(l))return;const{target:c}=l,d=s(c,l);if(typeof d!="function"||!c)return;const m=u=>{Dl(u)&&(d(u),c.removeEventListener("pointerleave",m))};c.addEventListener("pointerleave",m,n)};return r.forEach(l=>{l.addEventListener("pointerenter",o,n)}),i}const ou=(t,s)=>s?t===s?!0:ou(t,s.parentElement):!1,go=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,Rb=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Db(t){return Rb.has(t.tagName)||t.tabIndex!==-1}const jr=new WeakSet;function Pl(t){return s=>{s.key==="Enter"&&t(s)}}function Cn(t,s){t.dispatchEvent(new PointerEvent("pointer"+s,{isPrimary:!0,bubbles:!0}))}const Pb=(t,s)=>{const a=t.currentTarget;if(!a)return;const r=Pl(()=>{if(jr.has(a))return;Cn(a,"down");const n=Pl(()=>{Cn(a,"up")}),i=()=>Cn(a,"cancel");a.addEventListener("keyup",n,s),a.addEventListener("blur",i,s)});a.addEventListener("keydown",r,s),a.addEventListener("blur",()=>a.removeEventListener("keydown",r),s)};function El(t){return go(t)&&!nu()}function Eb(t,s,a={}){const[r,n,i]=iu(t,a),o=l=>{const c=l.currentTarget;if(!El(l))return;jr.add(c);const d=s(c,l),m=(x,p)=>{window.removeEventListener("pointerup",u),window.removeEventListener("pointercancel",h),jr.has(c)&&jr.delete(c),El(x)&&typeof d=="function"&&d(x,{success:p})},u=x=>{m(x,c===window||c===document||a.useGlobalTarget||ou(c,x.target))},h=x=>{m(x,!1)};window.addEventListener("pointerup",u,n),window.addEventListener("pointercancel",h,n)};return r.forEach(l=>{(a.useGlobalTarget?window:l).addEventListener("pointerdown",o,n),ru(l)&&(l.addEventListener("focus",d=>Pb(d,n)),!Db(l)&&!l.hasAttribute("tabindex")&&(l.tabIndex=0))}),i}function lu(t){return bm(t)&&"ownerSVGElement"in t}function Mb(t){return lu(t)&&t.tagName==="svg"}const Mt=t=>!!(t&&t.getVelocity),Ib=[...eu,ht,$s],_b=t=>Ib.find(Jm(t)),fo=g.createContext({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});function Ml(t,s){if(typeof t=="function")return t(s);t!=null&&(t.current=s)}function Lb(...t){return s=>{let a=!1;const r=t.map(n=>{const i=Ml(n,s);return!a&&typeof i=="function"&&(a=!0),i});if(a)return()=>{for(let n=0;n{const{width:d,height:m,top:u,left:h,right:x}=o.current;if(s||!i.current||!d||!m)return;const p=a==="left"?`left: ${h}`:`right: ${x}`;i.current.dataset.motionPopId=n;const y=document.createElement("style");l&&(y.nonce=l);const v=r??document.head;return v.appendChild(y),y.sheet&&y.sheet.insertRule(` [data-motion-pop-id="${n}"] { position: absolute !important; width: ${d}px !important; height: ${m}px !important; ${p}px !important; top: ${u}px !important; } `),()=>{v.contains(y)&&v.removeChild(y)}},[s]),e.jsx(Ob,{isPresent:s,childRef:i,sizeRef:o,children:g.cloneElement(t,{ref:c})})}const Ub=({children:t,initial:s,isPresent:a,onExitComplete:r,custom:n,presenceAffectsLayout:i,mode:o,anchorX:l,root:c})=>{const d=Ki(Vb),m=g.useId();let u=!0,h=g.useMemo(()=>(u=!1,{id:m,initial:s,isPresent:a,custom:n,onExitComplete:x=>{d.set(x,!0);for(const p of d.values())if(!p)return;r&&r()},register:x=>(d.set(x,!1),()=>d.delete(x))}),[a,d,r]);return i&&u&&(h={...h}),g.useMemo(()=>{d.forEach((x,p)=>d.set(p,!1))},[a]),g.useEffect(()=>{!a&&!d.size&&r&&r()},[a]),o==="popLayout"&&(t=e.jsx($b,{isPresent:a,anchorX:l,root:c,children:t})),e.jsx(Zr.Provider,{value:h,children:t})};function Vb(){return new Map}function cu(t=!0){const s=g.useContext(Zr);if(s===null)return[!0,null];const{isPresent:a,onExitComplete:r,register:n}=s,i=g.useId();g.useEffect(()=>{if(t)return n(i)},[t]);const o=g.useCallback(()=>t&&r&&r(i),[i,r,t]);return!a&&r?[!1,o]:[!0]}const pr=t=>t.key||"";function Il(t){const s=[];return g.Children.forEach(t,a=>{g.isValidElement(a)&&s.push(a)}),s}const Xr=({children:t,custom:s,initial:a=!0,onExitComplete:r,presenceAffectsLayout:n=!0,mode:i="sync",propagate:o=!1,anchorX:l="left",root:c})=>{const[d,m]=cu(o),u=g.useMemo(()=>Il(t),[t]),h=o&&!d?[]:u.map(pr),x=g.useRef(!0),p=g.useRef(u),y=Ki(()=>new Map),[v,N]=g.useState(u),[f,b]=g.useState(u);ym(()=>{x.current=!1,p.current=u;for(let R=0;R{const I=pr(R),T=o&&!d?!1:u===f||h.includes(I),E=()=>{if(y.has(I))y.set(I,!0);else return;let w=!0;y.forEach(S=>{S||(w=!1)}),w&&(C==null||C(),b(p.current),o&&(m==null||m()),r&&r())};return e.jsx(Ub,{isPresent:T,initial:!x.current||a?void 0:!1,custom:s,presenceAffectsLayout:n,mode:i,root:c,onExitComplete:T?void 0:E,anchorX:l,children:R},I)})})},du=g.createContext({strict:!1}),_l={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]},Na={};for(const t in _l)Na[t]={isEnabled:s=>_l[t].some(a=>!!s[a])};function Bb(t){for(const s in t)Na[s]={...Na[s],...t[s]}}const zb=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function Pr(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||zb.has(t)}let mu=t=>!Pr(t);function Hb(t){typeof t=="function"&&(mu=s=>s.startsWith("on")?!Pr(s):t(s))}try{Hb(require("@emotion/is-prop-valid").default)}catch{}function qb(t,s,a){const r={};for(const n in t)n==="values"&&typeof t.values=="object"||(mu(n)||a===!0&&Pr(n)||!s&&!Pr(n)||t.draggable&&n.startsWith("onDrag"))&&(r[n]=t[n]);return r}const Qr=g.createContext({});function Jr(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function Ya(t){return typeof t=="string"||Array.isArray(t)}const yo=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],vo=["initial",...yo];function en(t){return Jr(t.animate)||vo.some(s=>Ya(t[s]))}function uu(t){return!!(en(t)||t.variants)}function Wb(t,s){if(en(t)){const{initial:a,animate:r}=t;return{initial:a===!1||Ya(a)?a:void 0,animate:Ya(r)?r:void 0}}return t.inherit!==!1?s:{}}function Kb(t){const{initial:s,animate:a}=Wb(t,g.useContext(Qr));return g.useMemo(()=>({initial:s,animate:a}),[Ll(s),Ll(a)])}function Ll(t){return Array.isArray(t)?t.join(" "):t}const Za={};function Gb(t){for(const s in t)Za[s]=t[s],so(s)&&(Za[s].isCSSVariable=!0)}function hu(t,{layout:s,layoutId:a}){return ka.has(t)||t.startsWith("origin")||(s||a!==void 0)&&(!!Za[t]||t==="opacity")}const Yb={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Zb=Ta.length;function Xb(t,s,a){let r="",n=!0;for(let i=0;i({style:{},transform:{},transformOrigin:{},vars:{}});function pu(t,s,a){for(const r in s)!Mt(s[r])&&!hu(r,a)&&(t[r]=s[r])}function Qb({transformTemplate:t},s){return g.useMemo(()=>{const a=jo();return bo(a,s,t),Object.assign({},a.vars,a.style)},[s])}function Jb(t,s){const a=t.style||{},r={};return pu(r,a,t),Object.assign(r,Qb(t,s)),r}function ej(t,s){const a={},r=Jb(t,s);return t.drag&&t.dragListener!==!1&&(a.draggable=!1,r.userSelect=r.WebkitUserSelect=r.WebkitTouchCallout="none",r.touchAction=t.drag===!0?"none":`pan-${t.drag==="x"?"y":"x"}`),t.tabIndex===void 0&&(t.onTap||t.onTapStart||t.whileTap)&&(a.tabIndex=0),a.style=r,a}const tj={offset:"stroke-dashoffset",array:"stroke-dasharray"},sj={offset:"strokeDashoffset",array:"strokeDasharray"};function aj(t,s,a=1,r=0,n=!0){t.pathLength=1;const i=n?tj:sj;t[i.offset]=je.transform(-r);const o=je.transform(s),l=je.transform(a);t[i.array]=`${o} ${l}`}function xu(t,{attrX:s,attrY:a,attrScale:r,pathLength:n,pathSpacing:i=1,pathOffset:o=0,...l},c,d,m){if(bo(t,l,d),c){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:u,style:h}=t;u.transform&&(h.transform=u.transform,delete u.transform),(h.transform||u.transformOrigin)&&(h.transformOrigin=u.transformOrigin??"50% 50%",delete u.transformOrigin),h.transform&&(h.transformBox=(m==null?void 0:m.transformBox)??"fill-box",delete u.transformBox),s!==void 0&&(u.x=s),a!==void 0&&(u.y=a),r!==void 0&&(u.scale=r),n!==void 0&&aj(u,n,i,o,!1)}const gu=()=>({...jo(),attrs:{}}),fu=t=>typeof t=="string"&&t.toLowerCase()==="svg";function rj(t,s,a,r){const n=g.useMemo(()=>{const i=gu();return xu(i,s,fu(r),t.transformTemplate,t.style),{...i.attrs,style:{...i.style}}},[s]);if(t.style){const i={};pu(i,t.style,t),n.style={...i,...n.style}}return n}const nj=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function No(t){return typeof t!="string"||t.includes("-")?!1:!!(nj.indexOf(t)>-1||/[A-Z]/u.test(t))}function ij(t,s,a,{latestValues:r},n,i=!1){const l=(No(t)?rj:ej)(s,r,n,t),c=qb(s,typeof t=="string",i),d=t!==g.Fragment?{...c,...l,ref:a}:{},{children:m}=s,u=g.useMemo(()=>Mt(m)?m.get():m,[m]);return g.createElement(t,{...d,children:u})}function Fl(t){const s=[{},{}];return t==null||t.values.forEach((a,r)=>{s[0][r]=a.get(),s[1][r]=a.getVelocity()}),s}function wo(t,s,a,r){if(typeof s=="function"){const[n,i]=Fl(r);s=s(a!==void 0?a:t.custom,n,i)}if(typeof s=="string"&&(s=t.variants&&t.variants[s]),typeof s=="function"){const[n,i]=Fl(r);s=s(a!==void 0?a:t.custom,n,i)}return s}function Nr(t){return Mt(t)?t.get():t}function oj({scrapeMotionValuesFromProps:t,createRenderState:s},a,r,n){return{latestValues:lj(a,r,n,t),renderState:s()}}function lj(t,s,a,r){const n={},i=r(t,{});for(const h in i)n[h]=Nr(i[h]);let{initial:o,animate:l}=t;const c=en(t),d=uu(t);s&&d&&!c&&t.inherit!==!1&&(o===void 0&&(o=s.initial),l===void 0&&(l=s.animate));let m=a?a.initial===!1:!1;m=m||o===!1;const u=m?l:o;if(u&&typeof u!="boolean"&&!Jr(u)){const h=Array.isArray(u)?u:[u];for(let x=0;x(s,a)=>{const r=g.useContext(Qr),n=g.useContext(Zr),i=()=>oj(t,s,r,n);return a?i():Ki(i)};function Co(t,s,a){var i;const{style:r}=t,n={};for(const o in r)(Mt(r[o])||s.style&&Mt(s.style[o])||hu(o,t)||((i=a==null?void 0:a.getValue(o))==null?void 0:i.liveStyle)!==void 0)&&(n[o]=r[o]);return n}const cj=yu({scrapeMotionValuesFromProps:Co,createRenderState:jo});function vu(t,s,a){const r=Co(t,s,a);for(const n in t)if(Mt(t[n])||Mt(s[n])){const i=Ta.indexOf(n)!==-1?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n;r[i]=t[n]}return r}const dj=yu({scrapeMotionValuesFromProps:vu,createRenderState:gu}),mj=Symbol.for("motionComponentSymbol");function pa(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function uj(t,s,a){return g.useCallback(r=>{r&&t.onMount&&t.onMount(r),s&&(r?s.mount(r):s.unmount()),a&&(typeof a=="function"?a(r):pa(a)&&(a.current=r))},[s])}const So=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),hj="framerAppearId",bu="data-"+So(hj),ju=g.createContext({});function pj(t,s,a,r,n){var y,v;const{visualElement:i}=g.useContext(Qr),o=g.useContext(du),l=g.useContext(Zr),c=g.useContext(fo).reducedMotion,d=g.useRef(null);r=r||o.renderer,!d.current&&r&&(d.current=r(t,{visualState:s,parent:i,props:a,presenceContext:l,blockInitialAnimation:l?l.initial===!1:!1,reducedMotionConfig:c}));const m=d.current,u=g.useContext(ju);m&&!m.projection&&n&&(m.type==="html"||m.type==="svg")&&xj(d.current,a,n,u);const h=g.useRef(!1);g.useInsertionEffect(()=>{m&&h.current&&m.update(a,l)});const x=a[bu],p=g.useRef(!!x&&!((y=window.MotionHandoffIsComplete)!=null&&y.call(window,x))&&((v=window.MotionHasOptimisedAnimation)==null?void 0:v.call(window,x)));return ym(()=>{m&&(h.current=!0,window.MotionIsMounted=!0,m.updateFeatures(),m.scheduleRenderMicrotask(),p.current&&m.animationState&&m.animationState.animateChanges())}),g.useEffect(()=>{m&&(!p.current&&m.animationState&&m.animationState.animateChanges(),p.current&&(queueMicrotask(()=>{var N;(N=window.MotionHandoffMarkAsComplete)==null||N.call(window,x)}),p.current=!1),m.enteringChildren=void 0)}),m}function xj(t,s,a,r){const{layoutId:n,layout:i,drag:o,dragConstraints:l,layoutScroll:c,layoutRoot:d,layoutCrossfade:m}=s;t.projection=new a(t.latestValues,s["data-framer-portal-id"]?void 0:Nu(t.parent)),t.projection.setOptions({layoutId:n,layout:i,alwaysMeasureLayout:!!o||l&&pa(l),visualElement:t,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:m,layoutScroll:c,layoutRoot:d})}function Nu(t){if(t)return t.options.allowProjection!==!1?t.projection:Nu(t.parent)}function Sn(t,{forwardMotionProps:s=!1}={},a,r){a&&Bb(a);const n=No(t)?dj:cj;function i(l,c){let d;const m={...g.useContext(fo),...l,layoutId:gj(l)},{isStatic:u}=m,h=Kb(l),x=n(l,u);if(!u&&Gi){fj();const p=yj(m);d=p.MeasureLayout,h.visualElement=pj(t,x,m,r,p.ProjectionNode)}return e.jsxs(Qr.Provider,{value:h,children:[d&&h.visualElement?e.jsx(d,{visualElement:h.visualElement,...m}):null,ij(t,l,uj(x,h.visualElement,c),x,u,s)]})}i.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const o=g.forwardRef(i);return o[mj]=t,o}function gj({layoutId:t}){const s=g.useContext(Wi).id;return s&&t!==void 0?s+"-"+t:t}function fj(t,s){g.useContext(du).strict}function yj(t){const{drag:s,layout:a}=Na;if(!s&&!a)return{};const r={...s,...a};return{MeasureLayout:s!=null&&s.isEnabled(t)||a!=null&&a.isEnabled(t)?r.MeasureLayout:void 0,ProjectionNode:r.ProjectionNode}}function vj(t,s){if(typeof Proxy>"u")return Sn;const a=new Map,r=(i,o)=>Sn(i,o,t,s),n=(i,o)=>r(i,o);return new Proxy(n,{get:(i,o)=>o==="create"?r:(a.has(o)||a.set(o,Sn(o,void 0,t,s)),a.get(o))})}function wu({top:t,left:s,right:a,bottom:r}){return{x:{min:s,max:a},y:{min:t,max:r}}}function bj({x:t,y:s}){return{top:s.min,right:t.max,bottom:s.max,left:t.min}}function jj(t,s){if(!s)return t;const a=s({x:t.left,y:t.top}),r=s({x:t.right,y:t.bottom});return{top:a.y,left:a.x,bottom:r.y,right:r.x}}function An(t){return t===void 0||t===1}function hi({scale:t,scaleX:s,scaleY:a}){return!An(t)||!An(s)||!An(a)}function Ys(t){return hi(t)||Cu(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function Cu(t){return Ol(t.x)||Ol(t.y)}function Ol(t){return t&&t!=="0%"}function Er(t,s,a){const r=t-a,n=s*r;return a+n}function $l(t,s,a,r,n){return n!==void 0&&(t=Er(t,n,r)),Er(t,a,r)+s}function pi(t,s=0,a=1,r,n){t.min=$l(t.min,s,a,r,n),t.max=$l(t.max,s,a,r,n)}function Su(t,{x:s,y:a}){pi(t.x,s.translate,s.scale,s.originPoint),pi(t.y,a.translate,a.scale,a.originPoint)}const Ul=.999999999999,Vl=1.0000000000001;function Nj(t,s,a,r=!1){const n=a.length;if(!n)return;s.x=s.y=1;let i,o;for(let l=0;lUl&&(s.x=1),s.yUl&&(s.y=1)}function xa(t,s){t.min=t.min+s,t.max=t.max+s}function Bl(t,s,a,r,n=.5){const i=Qe(t.min,t.max,n);pi(t,s,a,i,r)}function ga(t,s){Bl(t.x,s.x,s.scaleX,s.scale,s.originX),Bl(t.y,s.y,s.scaleY,s.scale,s.originY)}function Au(t,s){return wu(jj(t.getBoundingClientRect(),s))}function wj(t,s,a){const r=Au(t,a),{scroll:n}=s;return n&&(xa(r.x,n.offset.x),xa(r.y,n.offset.y)),r}const zl=()=>({translate:0,scale:1,origin:0,originPoint:0}),fa=()=>({x:zl(),y:zl()}),Hl=()=>({min:0,max:0}),ct=()=>({x:Hl(),y:Hl()}),xi={current:null},Tu={current:!1};function Cj(){if(Tu.current=!0,!!Gi)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),s=()=>xi.current=t.matches;t.addEventListener("change",s),s()}else xi.current=!1}const Sj=new WeakMap;function Aj(t,s,a){for(const r in s){const n=s[r],i=a[r];if(Mt(n))t.addValue(r,n);else if(Mt(i))t.addValue(r,ja(n,{owner:t}));else if(i!==n)if(t.hasValue(r)){const o=t.getValue(r);o.liveStyle===!0?o.jump(n):o.hasAnimated||o.set(n)}else{const o=t.getStaticValue(r);t.addValue(r,ja(o!==void 0?o:n,{owner:t}))}}for(const r in a)s[r]===void 0&&t.removeValue(r);return s}const ql=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class Tj{scrapeMotionValuesFromProps(s,a,r){return{}}constructor({parent:s,props:a,presenceContext:r,reducedMotionConfig:n,blockInitialAnimation:i,visualState:o},l={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=uo,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const h=Vt.now();this.renderScheduledAtthis.bindToMotionValue(n,r)),Tu.current||Cj(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:xi.current,(a=this.parent)==null||a.addChild(this),this.update(this.props,this.presenceContext)}unmount(){var s;this.projection&&this.projection.unmount(),Os(this.notifyUpdate),Os(this.render),this.valueSubscriptions.forEach(a=>a()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),(s=this.parent)==null||s.removeChild(this);for(const a in this.events)this.events[a].clear();for(const a in this.features){const r=this.features[a];r&&(r.unmount(),r.isMounted=!1)}this.current=null}addChild(s){this.children.add(s),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(s)}removeChild(s){this.children.delete(s),this.enteringChildren&&this.enteringChildren.delete(s)}bindToMotionValue(s,a){this.valueSubscriptions.has(s)&&this.valueSubscriptions.get(s)();const r=ka.has(s);r&&this.onBindTransform&&this.onBindTransform();const n=a.on("change",o=>{this.latestValues[s]=o,this.props.onUpdate&&Ye.preRender(this.notifyUpdate),r&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let i;window.MotionCheckAppearSync&&(i=window.MotionCheckAppearSync(this,s,a)),this.valueSubscriptions.set(s,()=>{n(),i&&i(),a.owner&&a.stop()})}sortNodePosition(s){return!this.current||!this.sortInstanceNodePosition||this.type!==s.type?0:this.sortInstanceNodePosition(this.current,s.current)}updateFeatures(){let s="animation";for(s in Na){const a=Na[s];if(!a)continue;const{isEnabled:r,Feature:n}=a;if(!this.features[s]&&n&&r(this.props)&&(this.features[s]=new n(this)),this.features[s]){const i=this.features[s];i.isMounted?i.update():(i.mount(),i.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):ct()}getStaticValue(s){return this.latestValues[s]}setStaticValue(s,a){this.latestValues[s]=a}update(s,a){(s.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=s,this.prevPresenceContext=this.presenceContext,this.presenceContext=a;for(let r=0;ra.variantChildren.delete(s)}addValue(s,a){const r=this.values.get(s);a!==r&&(r&&this.removeValue(s),this.bindToMotionValue(s,a),this.values.set(s,a),this.latestValues[s]=a.get())}removeValue(s){this.values.delete(s);const a=this.valueSubscriptions.get(s);a&&(a(),this.valueSubscriptions.delete(s)),delete this.latestValues[s],this.removeValueFromRenderState(s,this.renderState)}hasValue(s){return this.values.has(s)}getValue(s,a){if(this.props.values&&this.props.values[s])return this.props.values[s];let r=this.values.get(s);return r===void 0&&a!==void 0&&(r=ja(a===null?void 0:a,{owner:this}),this.addValue(s,r)),r}readValue(s,a){let r=this.latestValues[s]!==void 0||!this.current?this.latestValues[s]:this.getBaseTargetFromProps(this.props,s)??this.readValueFromInstance(this.current,s,this.options);return r!=null&&(typeof r=="string"&&(vm(r)||jm(r))?r=parseFloat(r):!_b(r)&&$s.test(a)&&(r=su(s,a)),this.setBaseTarget(s,Mt(r)?r.get():r)),Mt(r)?r.get():r}setBaseTarget(s,a){this.baseTarget[s]=a}getBaseTarget(s){var i;const{initial:a}=this.props;let r;if(typeof a=="string"||typeof a=="object"){const o=wo(this.props,a,(i=this.presenceContext)==null?void 0:i.custom);o&&(r=o[s])}if(a&&r!==void 0)return r;const n=this.getBaseTargetFromProps(this.props,s);return n!==void 0&&!Mt(n)?n:this.initialValues[s]!==void 0&&r===void 0?void 0:this.baseTarget[s]}on(s,a){return this.events[s]||(this.events[s]=new Ji),this.events[s].add(a)}notify(s,...a){this.events[s]&&this.events[s].notify(...a)}scheduleRenderMicrotask(){xo.render(this.render)}}class ku extends Tj{constructor(){super(...arguments),this.KeyframeResolver=wb}sortInstanceNodePosition(s,a){return s.compareDocumentPosition(a)&2?1:-1}getBaseTargetFromProps(s,a){return s.style?s.style[a]:void 0}removeValueFromRenderState(s,{vars:a,style:r}){delete a[s],delete r[s]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:s}=this.props;Mt(s)&&(this.childSubscription=s.on("change",a=>{this.current&&(this.current.textContent=`${a}`)}))}}function Ru(t,{style:s,vars:a},r,n){const i=t.style;let o;for(o in s)i[o]=s[o];n==null||n.applyProjectionStyles(i,r);for(o in a)i.setProperty(o,a[o])}function kj(t){return window.getComputedStyle(t)}class Rj extends ku{constructor(){super(...arguments),this.type="html",this.renderInstance=Ru}readValueFromInstance(s,a){var r;if(ka.has(a))return(r=this.projection)!=null&&r.isProjecting?ii(a):Bv(s,a);{const n=kj(s),i=(so(a)?n.getPropertyValue(a):n[a])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(s,{transformPagePoint:a}){return Au(s,a)}build(s,a,r){bo(s,a,r.transformTemplate)}scrapeMotionValuesFromProps(s,a,r){return Co(s,a,r)}}const Du=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]);function Dj(t,s,a,r){Ru(t,s,void 0,r);for(const n in s.attrs)t.setAttribute(Du.has(n)?n:So(n),s.attrs[n])}class Pj extends ku{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ct}getBaseTargetFromProps(s,a){return s[a]}readValueFromInstance(s,a){if(ka.has(a)){const r=tu(a);return r&&r.default||0}return a=Du.has(a)?a:So(a),s.getAttribute(a)}scrapeMotionValuesFromProps(s,a,r){return vu(s,a,r)}build(s,a,r){xu(s,a,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(s,a,r,n){Dj(s,a,r,n)}mount(s){this.isSVGTag=fu(s.tagName),super.mount(s)}}const Ej=(t,s)=>No(t)?new Pj(s):new Rj(s,{allowProjection:t!==g.Fragment});function va(t,s,a){const r=t.getProps();return wo(r,s,a!==void 0?a:r.custom,t)}const gi=t=>Array.isArray(t);function Mj(t,s,a){t.hasValue(s)?t.getValue(s).set(a):t.addValue(s,ja(a))}function Ij(t){return gi(t)?t[t.length-1]||0:t}function _j(t,s){const a=va(t,s);let{transitionEnd:r={},transition:n={},...i}=a||{};i={...i,...r};for(const o in i){const l=Ij(i[o]);Mj(t,o,l)}}function Lj(t){return!!(Mt(t)&&t.add)}function fi(t,s){const a=t.getValue("willChange");if(Lj(a))return a.add(s);if(!a&&Ns.WillChange){const r=new Ns.WillChange("auto");t.addValue("willChange",r),r.add(s)}}function Pu(t){return t.props[bu]}const Fj=t=>t!==null;function Oj(t,{repeat:s,repeatType:a="loop"},r){const n=t.filter(Fj),i=s&&a!=="loop"&&s%2===1?0:n.length-1;return n[i]}const $j={type:"spring",stiffness:500,damping:25,restSpeed:10},Uj=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),Vj={type:"keyframes",duration:.8},Bj={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},zj=(t,{keyframes:s})=>s.length>2?Vj:ka.has(t)?t.startsWith("scale")?Uj(s[1]):$j:Bj;function Hj({when:t,delay:s,delayChildren:a,staggerChildren:r,staggerDirection:n,repeat:i,repeatType:o,repeatDelay:l,from:c,elapsed:d,...m}){return!!Object.keys(m).length}const Ao=(t,s,a,r={},n,i)=>o=>{const l=ho(r,t)||{},c=l.delay||r.delay||0;let{elapsed:d=0}=r;d=d-ds(c);const m={keyframes:Array.isArray(a)?a:[null,a],ease:"easeOut",velocity:s.getVelocity(),...l,delay:-d,onUpdate:h=>{s.set(h),l.onUpdate&&l.onUpdate(h)},onComplete:()=>{o(),l.onComplete&&l.onComplete()},name:t,motionValue:s,element:i?void 0:n};Hj(l)||Object.assign(m,zj(t,m)),m.duration&&(m.duration=ds(m.duration)),m.repeatDelay&&(m.repeatDelay=ds(m.repeatDelay)),m.from!==void 0&&(m.keyframes[0]=m.from);let u=!1;if((m.type===!1||m.duration===0&&!m.repeatDelay)&&(mi(m),m.delay===0&&(u=!0)),(Ns.instantAnimations||Ns.skipAnimations)&&(u=!0,mi(m),m.delay=0),m.allowFlatten=!l.type&&!l.ease,u&&!i&&s.get()!==void 0){const h=Oj(m.keyframes,l);if(h!==void 0){Ye.update(()=>{m.onUpdate(h),m.onComplete()});return}}return l.isSync?new mo(m):new mb(m)};function qj({protectedKeys:t,needsAnimating:s},a){const r=t.hasOwnProperty(a)&&s[a]!==!0;return s[a]=!1,r}function Eu(t,s,{delay:a=0,transitionOverride:r,type:n}={}){let{transition:i=t.getDefaultTransition(),transitionEnd:o,...l}=s;r&&(i=r);const c=[],d=n&&t.animationState&&t.animationState.getState()[n];for(const m in l){const u=t.getValue(m,t.latestValues[m]??null),h=l[m];if(h===void 0||d&&qj(d,m))continue;const x={delay:a,...ho(i||{},m)},p=u.get();if(p!==void 0&&!u.isAnimating&&!Array.isArray(h)&&h===p&&!x.velocity)continue;let y=!1;if(window.MotionHandoffAnimation){const N=Pu(t);if(N){const f=window.MotionHandoffAnimation(N,m,Ye);f!==null&&(x.startTime=f,y=!0)}}fi(t,m),u.start(Ao(m,u,h,t.shouldReduceMotion&&Qm.has(m)?{type:!1}:x,t,y));const v=u.animation;v&&c.push(v)}return o&&Promise.all(c).then(()=>{Ye.update(()=>{o&&_j(t,o)})}),c}function Mu(t,s,a,r=0,n=1){const i=Array.from(t).sort((d,m)=>d.sortNodePosition(m)).indexOf(s),o=t.size,l=(o-1)*r;return typeof a=="function"?a(i,o):n===1?i*r:l-i*r}function yi(t,s,a={}){var c;const r=va(t,s,a.type==="exit"?(c=t.presenceContext)==null?void 0:c.custom:void 0);let{transition:n=t.getDefaultTransition()||{}}=r||{};a.transitionOverride&&(n=a.transitionOverride);const i=r?()=>Promise.all(Eu(t,r,a)):()=>Promise.resolve(),o=t.variantChildren&&t.variantChildren.size?(d=0)=>{const{delayChildren:m=0,staggerChildren:u,staggerDirection:h}=n;return Wj(t,s,d,m,u,h,a)}:()=>Promise.resolve(),{when:l}=n;if(l){const[d,m]=l==="beforeChildren"?[i,o]:[o,i];return d().then(()=>m())}else return Promise.all([i(),o(a.delay)])}function Wj(t,s,a=0,r=0,n=0,i=1,o){const l=[];for(const c of t.variantChildren)c.notify("AnimationStart",s),l.push(yi(c,s,{...o,delay:a+(typeof r=="function"?0:r)+Mu(t.variantChildren,c,r,n,i)}).then(()=>c.notify("AnimationComplete",s)));return Promise.all(l)}function Kj(t,s,a={}){t.notify("AnimationStart",s);let r;if(Array.isArray(s)){const n=s.map(i=>yi(t,i,a));r=Promise.all(n)}else if(typeof s=="string")r=yi(t,s,a);else{const n=typeof s=="function"?va(t,s,a.custom):s;r=Promise.all(Eu(t,n,a))}return r.then(()=>{t.notify("AnimationComplete",s)})}function Iu(t,s){if(!Array.isArray(s))return!1;const a=s.length;if(a!==t.length)return!1;for(let r=0;rPromise.all(s.map(({animation:a,options:r})=>Kj(t,a,r)))}function Qj(t){let s=Xj(t),a=Wl(),r=!0;const n=c=>(d,m)=>{var h;const u=va(t,m,c==="exit"?(h=t.presenceContext)==null?void 0:h.custom:void 0);if(u){const{transition:x,transitionEnd:p,...y}=u;d={...d,...y,...p}}return d};function i(c){s=c(t)}function o(c){const{props:d}=t,m=_u(t.parent)||{},u=[],h=new Set;let x={},p=1/0;for(let v=0;vp&&j,E=!1;const w=Array.isArray(b)?b:[b];let S=w.reduce(n(N),{});C===!1&&(S={});const{prevResolvedValues:D={}}=f,H={...D,...S},L=k=>{T=!0,h.has(k)&&(E=!0,h.delete(k)),f.needsAnimating[k]=!0;const P=t.getValue(k);P&&(P.liveStyle=!1)};for(const k in H){const P=S[k],_=D[k];if(x.hasOwnProperty(k))continue;let W=!1;gi(P)&&gi(_)?W=!Iu(P,_):W=P!==_,W?P!=null?L(k):h.add(k):P!==void 0&&h.has(k)?L(k):f.protectedKeys[k]=!0}f.prevProp=b,f.prevResolvedValues=S,f.isActive&&(x={...x,...S}),r&&t.blockInitialAnimation&&(T=!1);const F=R&&I;T&&(!F||E)&&u.push(...w.map(k=>{const P={type:N};if(typeof k=="string"&&r&&!F&&t.manuallyAnimateOnMount&&t.parent){const{parent:_}=t,W=va(_,k);if(_.enteringChildren&&W){const{delayChildren:Z}=W.transition||{};P.delay=Mu(_.enteringChildren,t,Z)}}return{animation:k,options:P}}))}if(h.size){const v={};if(typeof d.initial!="boolean"){const N=va(t,Array.isArray(d.initial)?d.initial[0]:d.initial);N&&N.transition&&(v.transition=N.transition)}h.forEach(N=>{const f=t.getBaseTarget(N),b=t.getValue(N);b&&(b.liveStyle=!0),v[N]=f??null}),u.push({animation:v})}let y=!!u.length;return r&&(d.initial===!1||d.initial===d.animate)&&!t.manuallyAnimateOnMount&&(y=!1),r=!1,y?s(u):Promise.resolve()}function l(c,d){var u;if(a[c].isActive===d)return Promise.resolve();(u=t.variantChildren)==null||u.forEach(h=>{var x;return(x=h.animationState)==null?void 0:x.setActive(c,d)}),a[c].isActive=d;const m=o(c);for(const h in a)a[h].protectedKeys={};return m}return{animateChanges:o,setActive:l,setAnimateFunction:i,getState:()=>a,reset:()=>{a=Wl()}}}function Jj(t,s){return typeof s=="string"?s!==t:Array.isArray(s)?!Iu(s,t):!1}function Ws(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Wl(){return{animate:Ws(!0),whileInView:Ws(),whileHover:Ws(),whileTap:Ws(),whileDrag:Ws(),whileFocus:Ws(),exit:Ws()}}class zs{constructor(s){this.isMounted=!1,this.node=s}update(){}}class eN extends zs{constructor(s){super(s),s.animationState||(s.animationState=Qj(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();Jr(s)&&(this.unmountControls=s.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:s}=this.node.getProps(),{animate:a}=this.node.prevProps||{};s!==a&&this.updateAnimationControlsSubscription()}unmount(){var s;this.node.animationState.reset(),(s=this.unmountControls)==null||s.call(this)}}let tN=0;class sN extends zs{constructor(){super(...arguments),this.id=tN++}update(){if(!this.node.presenceContext)return;const{isPresent:s,onExitComplete:a}=this.node.presenceContext,{isPresent:r}=this.node.prevPresenceContext||{};if(!this.node.animationState||s===r)return;const n=this.node.animationState.setActive("exit",!s);a&&!s&&n.then(()=>{a(this.id)})}mount(){const{register:s,onExitComplete:a}=this.node.presenceContext||{};a&&a(this.id),s&&(this.unmount=s(this.id))}unmount(){}}const aN={animation:{Feature:eN},exit:{Feature:sN}};function Xa(t,s,a,r={passive:!0}){return t.addEventListener(s,a,r),()=>t.removeEventListener(s,a)}function rr(t){return{point:{x:t.pageX,y:t.pageY}}}const rN=t=>s=>go(s)&&t(s,rr(s));function Va(t,s,a,r){return Xa(t,s,rN(a),r)}const Lu=1e-4,nN=1-Lu,iN=1+Lu,Fu=.01,oN=0-Fu,lN=0+Fu;function _t(t){return t.max-t.min}function cN(t,s,a){return Math.abs(t-s)<=a}function Kl(t,s,a,r=.5){t.origin=r,t.originPoint=Qe(s.min,s.max,t.origin),t.scale=_t(a)/_t(s),t.translate=Qe(a.min,a.max,t.origin)-t.originPoint,(t.scale>=nN&&t.scale<=iN||isNaN(t.scale))&&(t.scale=1),(t.translate>=oN&&t.translate<=lN||isNaN(t.translate))&&(t.translate=0)}function Ba(t,s,a,r){Kl(t.x,s.x,a.x,r?r.originX:void 0),Kl(t.y,s.y,a.y,r?r.originY:void 0)}function Gl(t,s,a){t.min=a.min+s.min,t.max=t.min+_t(s)}function dN(t,s,a){Gl(t.x,s.x,a.x),Gl(t.y,s.y,a.y)}function Yl(t,s,a){t.min=s.min-a.min,t.max=t.min+_t(s)}function za(t,s,a){Yl(t.x,s.x,a.x),Yl(t.y,s.y,a.y)}function Jt(t){return[t("x"),t("y")]}const Ou=({current:t})=>t?t.ownerDocument.defaultView:null,Zl=(t,s)=>Math.abs(t-s);function mN(t,s){const a=Zl(t.x,s.x),r=Zl(t.y,s.y);return Math.sqrt(a**2+r**2)}class $u{constructor(s,a,{transformPagePoint:r,contextWindow:n=window,dragSnapToOrigin:i=!1,distanceThreshold:o=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const h=kn(this.lastMoveEventInfo,this.history),x=this.startEvent!==null,p=mN(h.offset,{x:0,y:0})>=this.distanceThreshold;if(!x&&!p)return;const{point:y}=h,{timestamp:v}=kt;this.history.push({...y,timestamp:v});const{onStart:N,onMove:f}=this.handlers;x||(N&&N(this.lastMoveEvent,h),this.startEvent=this.lastMoveEvent),f&&f(this.lastMoveEvent,h)},this.handlePointerMove=(h,x)=>{this.lastMoveEvent=h,this.lastMoveEventInfo=Tn(x,this.transformPagePoint),Ye.update(this.updatePoint,!0)},this.handlePointerUp=(h,x)=>{this.end();const{onEnd:p,onSessionEnd:y,resumeAnimation:v}=this.handlers;if(this.dragSnapToOrigin&&v&&v(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const N=kn(h.type==="pointercancel"?this.lastMoveEventInfo:Tn(x,this.transformPagePoint),this.history);this.startEvent&&p&&p(h,N),y&&y(h,N)},!go(s))return;this.dragSnapToOrigin=i,this.handlers=a,this.transformPagePoint=r,this.distanceThreshold=o,this.contextWindow=n||window;const l=rr(s),c=Tn(l,this.transformPagePoint),{point:d}=c,{timestamp:m}=kt;this.history=[{...d,timestamp:m}];const{onSessionStart:u}=a;u&&u(s,kn(c,this.history)),this.removeListeners=tr(Va(this.contextWindow,"pointermove",this.handlePointerMove),Va(this.contextWindow,"pointerup",this.handlePointerUp),Va(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(s){this.handlers=s}end(){this.removeListeners&&this.removeListeners(),Os(this.updatePoint)}}function Tn(t,s){return s?{point:s(t.point)}:t}function Xl(t,s){return{x:t.x-s.x,y:t.y-s.y}}function kn({point:t},s){return{point:t,delta:Xl(t,Uu(s)),offset:Xl(t,uN(s)),velocity:hN(s,.1)}}function uN(t){return t[0]}function Uu(t){return t[t.length-1]}function hN(t,s){if(t.length<2)return{x:0,y:0};let a=t.length-1,r=null;const n=Uu(t);for(;a>=0&&(r=t[a],!(n.timestamp-r.timestamp>ds(s)));)a--;if(!r)return{x:0,y:0};const i=es(n.timestamp-r.timestamp);if(i===0)return{x:0,y:0};const o={x:(n.x-r.x)/i,y:(n.y-r.y)/i};return o.x===1/0&&(o.x=0),o.y===1/0&&(o.y=0),o}function pN(t,{min:s,max:a},r){return s!==void 0&&ta&&(t=r?Qe(a,t,r.max):Math.min(t,a)),t}function Ql(t,s,a){return{min:s!==void 0?t.min+s:void 0,max:a!==void 0?t.max+a-(t.max-t.min):void 0}}function xN(t,{top:s,left:a,bottom:r,right:n}){return{x:Ql(t.x,a,n),y:Ql(t.y,s,r)}}function Jl(t,s){let a=s.min-t.min,r=s.max-t.max;return s.max-s.minr?a=Wa(s.min,s.max-r,t.min):r>n&&(a=Wa(t.min,t.max-n,s.min)),js(0,1,a)}function yN(t,s){const a={};return s.min!==void 0&&(a.min=s.min-t.min),s.max!==void 0&&(a.max=s.max-t.min),a}const vi=.35;function vN(t=vi){return t===!1?t=0:t===!0&&(t=vi),{x:ec(t,"left","right"),y:ec(t,"top","bottom")}}function ec(t,s,a){return{min:tc(t,s),max:tc(t,a)}}function tc(t,s){return typeof t=="number"?t:t[s]||0}const bN=new WeakMap;class jN{constructor(s){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=ct(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=s}start(s,{snapToCursor:a=!1,distanceThreshold:r}={}){const{presenceContext:n}=this.visualElement;if(n&&n.isPresent===!1)return;const i=u=>{const{dragSnapToOrigin:h}=this.getProps();h?this.pauseAnimation():this.stopAnimation(),a&&this.snapToCursor(rr(u).point)},o=(u,h)=>{const{drag:x,dragPropagation:p,onDragStart:y}=this.getProps();if(x&&!p&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Tb(x),!this.openDragLock))return;this.latestPointerEvent=u,this.latestPanInfo=h,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Jt(N=>{let f=this.getAxisMotionValue(N).get()||0;if(ms.test(f)){const{projection:b}=this.visualElement;if(b&&b.layout){const j=b.layout.layoutBox[N];j&&(f=_t(j)*(parseFloat(f)/100))}}this.originPoint[N]=f}),y&&Ye.postRender(()=>y(u,h)),fi(this.visualElement,"transform");const{animationState:v}=this.visualElement;v&&v.setActive("whileDrag",!0)},l=(u,h)=>{this.latestPointerEvent=u,this.latestPanInfo=h;const{dragPropagation:x,dragDirectionLock:p,onDirectionLock:y,onDrag:v}=this.getProps();if(!x&&!this.openDragLock)return;const{offset:N}=h;if(p&&this.currentDirection===null){this.currentDirection=NN(N),this.currentDirection!==null&&y&&y(this.currentDirection);return}this.updateAxis("x",h.point,N),this.updateAxis("y",h.point,N),this.visualElement.render(),v&&v(u,h)},c=(u,h)=>{this.latestPointerEvent=u,this.latestPanInfo=h,this.stop(u,h),this.latestPointerEvent=null,this.latestPanInfo=null},d=()=>Jt(u=>{var h;return this.getAnimationState(u)==="paused"&&((h=this.getAxisMotionValue(u).animation)==null?void 0:h.play())}),{dragSnapToOrigin:m}=this.getProps();this.panSession=new $u(s,{onSessionStart:i,onStart:o,onMove:l,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:m,distanceThreshold:r,contextWindow:Ou(this.visualElement)})}stop(s,a){const r=s||this.latestPointerEvent,n=a||this.latestPanInfo,i=this.isDragging;if(this.cancel(),!i||!n||!r)return;const{velocity:o}=n;this.startAnimation(o);const{onDragEnd:l}=this.getProps();l&&Ye.postRender(()=>l(r,n))}cancel(){this.isDragging=!1;const{projection:s,animationState:a}=this.visualElement;s&&(s.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:r}=this.getProps();!r&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),a&&a.setActive("whileDrag",!1)}updateAxis(s,a,r){const{drag:n}=this.getProps();if(!r||!xr(s,n,this.currentDirection))return;const i=this.getAxisMotionValue(s);let o=this.originPoint[s]+r[s];this.constraints&&this.constraints[s]&&(o=pN(o,this.constraints[s],this.elastic[s])),i.set(o)}resolveConstraints(){var i;const{dragConstraints:s,dragElastic:a}=this.getProps(),r=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(i=this.visualElement.projection)==null?void 0:i.layout,n=this.constraints;s&&pa(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&r?this.constraints=xN(r.layoutBox,s):this.constraints=!1,this.elastic=vN(a),n!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&Jt(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=yN(r.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:s,onMeasureDragConstraints:a}=this.getProps();if(!s||!pa(s))return!1;const r=s.current,{projection:n}=this.visualElement;if(!n||!n.layout)return!1;const i=wj(r,n.root,this.visualElement.getTransformPagePoint());let o=gN(n.layout.layoutBox,i);if(a){const l=a(bj(o));this.hasMutatedConstraints=!!l,l&&(o=wu(l))}return o}startAnimation(s){const{drag:a,dragMomentum:r,dragElastic:n,dragTransition:i,dragSnapToOrigin:o,onDragTransitionEnd:l}=this.getProps(),c=this.constraints||{},d=Jt(m=>{if(!xr(m,a,this.currentDirection))return;let u=c&&c[m]||{};o&&(u={min:0,max:0});const h=n?200:1e6,x=n?40:1e7,p={type:"inertia",velocity:r?s[m]:0,bounceStiffness:h,bounceDamping:x,timeConstant:750,restDelta:1,restSpeed:10,...i,...u};return this.startAxisValueAnimation(m,p)});return Promise.all(d).then(l)}startAxisValueAnimation(s,a){const r=this.getAxisMotionValue(s);return fi(this.visualElement,s),r.start(Ao(s,r,0,a,this.visualElement,!1))}stopAnimation(){Jt(s=>this.getAxisMotionValue(s).stop())}pauseAnimation(){Jt(s=>{var a;return(a=this.getAxisMotionValue(s).animation)==null?void 0:a.pause()})}getAnimationState(s){var a;return(a=this.getAxisMotionValue(s).animation)==null?void 0:a.state}getAxisMotionValue(s){const a=`_drag${s.toUpperCase()}`,r=this.visualElement.getProps(),n=r[a];return n||this.visualElement.getValue(s,(r.initial?r.initial[s]:void 0)||0)}snapToCursor(s){Jt(a=>{const{drag:r}=this.getProps();if(!xr(a,r,this.currentDirection))return;const{projection:n}=this.visualElement,i=this.getAxisMotionValue(a);if(n&&n.layout){const{min:o,max:l}=n.layout.layoutBox[a];i.set(s[a]-Qe(o,l,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:s,dragConstraints:a}=this.getProps(),{projection:r}=this.visualElement;if(!pa(a)||!r||!this.constraints)return;this.stopAnimation();const n={x:0,y:0};Jt(o=>{const l=this.getAxisMotionValue(o);if(l&&this.constraints!==!1){const c=l.get();n[o]=fN({min:c,max:c},this.constraints[o])}});const{transformTemplate:i}=this.visualElement.getProps();this.visualElement.current.style.transform=i?i({},""):"none",r.root&&r.root.updateScroll(),r.updateLayout(),this.resolveConstraints(),Jt(o=>{if(!xr(o,s,null))return;const l=this.getAxisMotionValue(o),{min:c,max:d}=this.constraints[o];l.set(Qe(c,d,n[o]))})}addListeners(){if(!this.visualElement.current)return;bN.set(this.visualElement,this);const s=this.visualElement.current,a=Va(s,"pointerdown",c=>{const{drag:d,dragListener:m=!0}=this.getProps();d&&m&&this.start(c)}),r=()=>{const{dragConstraints:c}=this.getProps();pa(c)&&c.current&&(this.constraints=this.resolveRefConstraints())},{projection:n}=this.visualElement,i=n.addEventListener("measure",r);n&&!n.layout&&(n.root&&n.root.updateScroll(),n.updateLayout()),Ye.read(r);const o=Xa(window,"resize",()=>this.scalePositionWithinConstraints()),l=n.addEventListener("didUpdate",({delta:c,hasLayoutChanged:d})=>{this.isDragging&&d&&(Jt(m=>{const u=this.getAxisMotionValue(m);u&&(this.originPoint[m]+=c[m].translate,u.set(u.get()+c[m].translate))}),this.visualElement.render())});return()=>{o(),a(),i(),l&&l()}}getProps(){const s=this.visualElement.getProps(),{drag:a=!1,dragDirectionLock:r=!1,dragPropagation:n=!1,dragConstraints:i=!1,dragElastic:o=vi,dragMomentum:l=!0}=s;return{...s,drag:a,dragDirectionLock:r,dragPropagation:n,dragConstraints:i,dragElastic:o,dragMomentum:l}}}function xr(t,s,a){return(s===!0||s===t)&&(a===null||a===t)}function NN(t,s=10){let a=null;return Math.abs(t.y)>s?a="y":Math.abs(t.x)>s&&(a="x"),a}class wN extends zs{constructor(s){super(s),this.removeGroupControls=ss,this.removeListeners=ss,this.controls=new jN(s)}mount(){const{dragControls:s}=this.node.getProps();s&&(this.removeGroupControls=s.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||ss}unmount(){this.removeGroupControls(),this.removeListeners()}}const sc=t=>(s,a)=>{t&&Ye.postRender(()=>t(s,a))};class CN extends zs{constructor(){super(...arguments),this.removePointerDownListener=ss}onPointerDown(s){this.session=new $u(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Ou(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:a,onPan:r,onPanEnd:n}=this.node.getProps();return{onSessionStart:sc(s),onStart:sc(a),onMove:r,onEnd:(i,o)=>{delete this.session,n&&Ye.postRender(()=>n(i,o))}}}mount(){this.removePointerDownListener=Va(this.node.current,"pointerdown",s=>this.onPointerDown(s))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const wr={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function ac(t,s){return s.max===s.min?0:t/(s.max-s.min)*100}const La={correct:(t,s)=>{if(!s.target)return t;if(typeof t=="string")if(je.test(t))t=parseFloat(t);else return t;const a=ac(t,s.target.x),r=ac(t,s.target.y);return`${a}% ${r}%`}},SN={correct:(t,{treeScale:s,projectionDelta:a})=>{const r=t,n=$s.parse(t);if(n.length>5)return r;const i=$s.createTransformer(t),o=typeof n[0]!="number"?1:0,l=a.x.scale*s.x,c=a.y.scale*s.y;n[0+o]/=l,n[1+o]/=c;const d=Qe(l,c,.5);return typeof n[2+o]=="number"&&(n[2+o]/=d),typeof n[3+o]=="number"&&(n[3+o]/=d),i(n)}};let Rn=!1;class AN extends g.Component{componentDidMount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r,layoutId:n}=this.props,{projection:i}=s;Gb(TN),i&&(a.group&&a.group.add(i),r&&r.register&&n&&r.register(i),Rn&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,onExitComplete:()=>this.safeToRemove()})),wr.hasEverUpdated=!0}getSnapshotBeforeUpdate(s){const{layoutDependency:a,visualElement:r,drag:n,isPresent:i}=this.props,{projection:o}=r;return o&&(o.isPresent=i,Rn=!0,n||s.layoutDependency!==a||a===void 0||s.isPresent!==i?o.willUpdate():this.safeToRemove(),s.isPresent!==i&&(i?o.promote():o.relegate()||Ye.postRender(()=>{const l=o.getStack();(!l||!l.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:s}=this.props.visualElement;s&&(s.root.didUpdate(),xo.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r}=this.props,{projection:n}=s;Rn=!0,n&&(n.scheduleCheckAfterUnmount(),a&&a.group&&a.group.remove(n),r&&r.deregister&&r.deregister(n))}safeToRemove(){const{safeToRemove:s}=this.props;s&&s()}render(){return null}}function Vu(t){const[s,a]=cu(),r=g.useContext(Wi);return e.jsx(AN,{...t,layoutGroup:r,switchLayoutGroup:g.useContext(ju),isPresent:s,safeToRemove:a})}const TN={borderRadius:{...La,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:La,borderTopRightRadius:La,borderBottomLeftRadius:La,borderBottomRightRadius:La,boxShadow:SN};function kN(t,s,a){const r=Mt(t)?t:ja(t);return r.start(Ao("",r,s,a)),r.animation}const RN=(t,s)=>t.depth-s.depth;class DN{constructor(){this.children=[],this.isDirty=!1}add(s){Yi(this.children,s),this.isDirty=!0}remove(s){Zi(this.children,s),this.isDirty=!0}forEach(s){this.isDirty&&this.children.sort(RN),this.isDirty=!1,this.children.forEach(s)}}function PN(t,s){const a=Vt.now(),r=({timestamp:n})=>{const i=n-a;i>=s&&(Os(r),t(i-s))};return Ye.setup(r,!0),()=>Os(r)}const Bu=["TopLeft","TopRight","BottomLeft","BottomRight"],EN=Bu.length,rc=t=>typeof t=="string"?parseFloat(t):t,nc=t=>typeof t=="number"||je.test(t);function MN(t,s,a,r,n,i){n?(t.opacity=Qe(0,a.opacity??1,IN(r)),t.opacityExit=Qe(s.opacity??1,0,_N(r))):i&&(t.opacity=Qe(s.opacity??1,a.opacity??1,r));for(let o=0;ors?1:a(Wa(t,s,r))}function oc(t,s){t.min=s.min,t.max=s.max}function Qt(t,s){oc(t.x,s.x),oc(t.y,s.y)}function lc(t,s){t.translate=s.translate,t.scale=s.scale,t.originPoint=s.originPoint,t.origin=s.origin}function cc(t,s,a,r,n){return t-=s,t=Er(t,1/a,r),n!==void 0&&(t=Er(t,1/n,r)),t}function LN(t,s=0,a=1,r=.5,n,i=t,o=t){if(ms.test(s)&&(s=parseFloat(s),s=Qe(o.min,o.max,s/100)-o.min),typeof s!="number")return;let l=Qe(i.min,i.max,r);t===i&&(l-=s),t.min=cc(t.min,s,a,l,n),t.max=cc(t.max,s,a,l,n)}function dc(t,s,[a,r,n],i,o){LN(t,s[a],s[r],s[n],s.scale,i,o)}const FN=["x","scaleX","originX"],ON=["y","scaleY","originY"];function mc(t,s,a,r){dc(t.x,s,FN,a?a.x:void 0,r?r.x:void 0),dc(t.y,s,ON,a?a.y:void 0,r?r.y:void 0)}function uc(t){return t.translate===0&&t.scale===1}function Hu(t){return uc(t.x)&&uc(t.y)}function hc(t,s){return t.min===s.min&&t.max===s.max}function $N(t,s){return hc(t.x,s.x)&&hc(t.y,s.y)}function pc(t,s){return Math.round(t.min)===Math.round(s.min)&&Math.round(t.max)===Math.round(s.max)}function qu(t,s){return pc(t.x,s.x)&&pc(t.y,s.y)}function xc(t){return _t(t.x)/_t(t.y)}function gc(t,s){return t.translate===s.translate&&t.scale===s.scale&&t.originPoint===s.originPoint}class UN{constructor(){this.members=[]}add(s){Yi(this.members,s),s.scheduleRender()}remove(s){if(Zi(this.members,s),s===this.prevLead&&(this.prevLead=void 0),s===this.lead){const a=this.members[this.members.length-1];a&&this.promote(a)}}relegate(s){const a=this.members.findIndex(n=>s===n);if(a===0)return!1;let r;for(let n=a;n>=0;n--){const i=this.members[n];if(i.isPresent!==!1){r=i;break}}return r?(this.promote(r),!0):!1}promote(s,a){const r=this.lead;if(s!==r&&(this.prevLead=r,this.lead=s,s.show(),r)){r.instance&&r.scheduleRender(),s.scheduleRender(),s.resumeFrom=r,a&&(s.resumeFrom.preserveOpacity=!0),r.snapshot&&(s.snapshot=r.snapshot,s.snapshot.latestValues=r.animationValues||r.latestValues),s.root&&s.root.isUpdating&&(s.isLayoutDirty=!0);const{crossfade:n}=s.options;n===!1&&r.hide()}}exitAnimationComplete(){this.members.forEach(s=>{const{options:a,resumingFrom:r}=s;a.onExitComplete&&a.onExitComplete(),r&&r.options.onExitComplete&&r.options.onExitComplete()})}scheduleRender(){this.members.forEach(s=>{s.instance&&s.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function VN(t,s,a){let r="";const n=t.x.translate/s.x,i=t.y.translate/s.y,o=(a==null?void 0:a.z)||0;if((n||i||o)&&(r=`translate3d(${n}px, ${i}px, ${o}px) `),(s.x!==1||s.y!==1)&&(r+=`scale(${1/s.x}, ${1/s.y}) `),a){const{transformPerspective:d,rotate:m,rotateX:u,rotateY:h,skewX:x,skewY:p}=a;d&&(r=`perspective(${d}px) ${r}`),m&&(r+=`rotate(${m}deg) `),u&&(r+=`rotateX(${u}deg) `),h&&(r+=`rotateY(${h}deg) `),x&&(r+=`skewX(${x}deg) `),p&&(r+=`skewY(${p}deg) `)}const l=t.x.scale*s.x,c=t.y.scale*s.y;return(l!==1||c!==1)&&(r+=`scale(${l}, ${c})`),r||"none"}const Dn=["","X","Y","Z"],BN=1e3;let zN=0;function Pn(t,s,a,r){const{latestValues:n}=s;n[t]&&(a[t]=n[t],s.setStaticValue(t,0),r&&(r[t]=0))}function Wu(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:s}=t.options;if(!s)return;const a=Pu(s);if(window.MotionHasOptimisedAnimation(a,"transform")){const{layout:n,layoutId:i}=t.options;window.MotionCancelOptimisedAnimation(a,"transform",Ye,!(n||i))}const{parent:r}=t;r&&!r.hasCheckedOptimisedAppear&&Wu(r)}function Ku({attachResizeListener:t,defaultParent:s,measureScroll:a,checkIsScrollRoot:r,resetTransform:n}){return class{constructor(o={},l=s==null?void 0:s()){this.id=zN++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,this.nodes.forEach(WN),this.nodes.forEach(ZN),this.nodes.forEach(XN),this.nodes.forEach(KN)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=o,this.root=l?l.root||l:this,this.path=l?[...l.path,l]:[],this.parent=l,this.depth=l?l.depth+1:0;for(let c=0;cthis.root.updateBlockedByResize=!1;Ye.read(()=>{u=window.innerWidth}),t(o,()=>{const x=window.innerWidth;x!==u&&(u=x,this.root.updateBlockedByResize=!0,m&&m(),m=PN(h,250),wr.hasAnimatedSinceResize&&(wr.hasAnimatedSinceResize=!1,this.nodes.forEach(vc)))})}l&&this.root.registerSharedNode(l,this),this.options.animate!==!1&&d&&(l||c)&&this.addEventListener("didUpdate",({delta:m,hasLayoutChanged:u,hasRelativeLayoutChanged:h,layout:x})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const p=this.options.transition||d.getDefaultTransition()||sw,{onLayoutAnimationStart:y,onLayoutAnimationComplete:v}=d.getProps(),N=!this.targetLayout||!qu(this.targetLayout,x),f=!u&&h;if(this.options.layoutRoot||this.resumeFrom||f||u&&(N||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const b={...ho(p,"layout"),onPlay:y,onComplete:v};(d.shouldReduceMotion||this.options.layoutRoot)&&(b.delay=0,b.type=!1),this.startAnimation(b),this.setAnimationOrigin(m,f)}else u||vc(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=x})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const o=this.getStack();o&&o.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),Os(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(QN),this.animationId++)}getTransformTemplate(){const{visualElement:o}=this.options;return o&&o.getProps().transformTemplate}willUpdate(o=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&Wu(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let m=0;m{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!_t(this.snapshot.measuredBox.x)&&!_t(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let c=0;c{const C=j/1e3;bc(u.x,o.x,C),bc(u.y,o.y,C),this.setTargetDelta(u),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(za(h,this.layout.layoutBox,this.relativeParent.layout.layoutBox),ew(this.relativeTarget,this.relativeTargetOrigin,h,C),b&&$N(this.relativeTarget,b)&&(this.isProjectionDirty=!1),b||(b=ct()),Qt(b,this.relativeTarget)),y&&(this.animationValues=m,MN(m,d,this.latestValues,C,f,N)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=C},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(o){var l,c,d;this.notifyListeners("animationStart"),(l=this.currentAnimation)==null||l.stop(),(d=(c=this.resumingFrom)==null?void 0:c.currentAnimation)==null||d.stop(),this.pendingAnimation&&(Os(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Ye.update(()=>{wr.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=ja(0)),this.currentAnimation=kN(this.motionValue,[0,1e3],{...o,velocity:0,isSync:!0,onUpdate:m=>{this.mixTargetDelta(m),o.onUpdate&&o.onUpdate(m)},onStop:()=>{},onComplete:()=>{o.onComplete&&o.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const o=this.getStack();o&&o.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(BN),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const o=this.getLead();let{targetWithTransforms:l,target:c,layout:d,latestValues:m}=o;if(!(!l||!c||!d)){if(this!==o&&this.layout&&d&&Gu(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||ct();const u=_t(this.layout.layoutBox.x);c.x.min=o.target.x.min,c.x.max=c.x.min+u;const h=_t(this.layout.layoutBox.y);c.y.min=o.target.y.min,c.y.max=c.y.min+h}Qt(l,c),ga(l,m),Ba(this.projectionDeltaWithTransform,this.layoutCorrected,l,m)}}registerSharedNode(o,l){this.sharedNodes.has(o)||this.sharedNodes.set(o,new UN),this.sharedNodes.get(o).add(l);const d=l.options.initialPromotionConfig;l.promote({transition:d?d.transition:void 0,preserveFollowOpacity:d&&d.shouldPreserveFollowOpacity?d.shouldPreserveFollowOpacity(l):void 0})}isLead(){const o=this.getStack();return o?o.lead===this:!0}getLead(){var l;const{layoutId:o}=this.options;return o?((l=this.getStack())==null?void 0:l.lead)||this:this}getPrevLead(){var l;const{layoutId:o}=this.options;return o?(l=this.getStack())==null?void 0:l.prevLead:void 0}getStack(){const{layoutId:o}=this.options;if(o)return this.root.sharedNodes.get(o)}promote({needsReset:o,transition:l,preserveFollowOpacity:c}={}){const d=this.getStack();d&&d.promote(this,c),o&&(this.projectionDelta=void 0,this.needsReset=!0),l&&this.setOptions({transition:l})}relegate(){const o=this.getStack();return o?o.relegate(this):!1}resetSkewAndRotation(){const{visualElement:o}=this.options;if(!o)return;let l=!1;const{latestValues:c}=o;if((c.z||c.rotate||c.rotateX||c.rotateY||c.rotateZ||c.skewX||c.skewY)&&(l=!0),!l)return;const d={};c.z&&Pn("z",o,d,this.animationValues);for(let m=0;m{var l;return(l=o.currentAnimation)==null?void 0:l.stop()}),this.root.nodes.forEach(fc),this.root.sharedNodes.clear()}}}function HN(t){t.updateLayout()}function qN(t){var a;const s=((a=t.resumeFrom)==null?void 0:a.snapshot)||t.snapshot;if(t.isLead()&&t.layout&&s&&t.hasListeners("didUpdate")){const{layoutBox:r,measuredBox:n}=t.layout,{animationType:i}=t.options,o=s.source!==t.layout.source;i==="size"?Jt(u=>{const h=o?s.measuredBox[u]:s.layoutBox[u],x=_t(h);h.min=r[u].min,h.max=h.min+x}):Gu(i,s.layoutBox,r)&&Jt(u=>{const h=o?s.measuredBox[u]:s.layoutBox[u],x=_t(r[u]);h.max=h.min+x,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[u].max=t.relativeTarget[u].min+x)});const l=fa();Ba(l,r,s.layoutBox);const c=fa();o?Ba(c,t.applyTransform(n,!0),s.measuredBox):Ba(c,r,s.layoutBox);const d=!Hu(l);let m=!1;if(!t.resumeFrom){const u=t.getClosestProjectingParent();if(u&&!u.resumeFrom){const{snapshot:h,layout:x}=u;if(h&&x){const p=ct();za(p,s.layoutBox,h.layoutBox);const y=ct();za(y,r,x.layoutBox),qu(p,y)||(m=!0),u.options.layoutRoot&&(t.relativeTarget=y,t.relativeTargetOrigin=p,t.relativeParent=u)}}}t.notifyListeners("didUpdate",{layout:r,snapshot:s,delta:c,layoutDelta:l,hasLayoutChanged:d,hasRelativeLayoutChanged:m})}else if(t.isLead()){const{onExitComplete:r}=t.options;r&&r()}t.options.transition=void 0}function WN(t){t.parent&&(t.isProjecting()||(t.isProjectionDirty=t.parent.isProjectionDirty),t.isSharedProjectionDirty||(t.isSharedProjectionDirty=!!(t.isProjectionDirty||t.parent.isProjectionDirty||t.parent.isSharedProjectionDirty)),t.isTransformDirty||(t.isTransformDirty=t.parent.isTransformDirty))}function KN(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function GN(t){t.clearSnapshot()}function fc(t){t.clearMeasurements()}function yc(t){t.isLayoutDirty=!1}function YN(t){const{visualElement:s}=t.options;s&&s.getProps().onBeforeLayoutMeasure&&s.notify("BeforeLayoutMeasure"),t.resetTransform()}function vc(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function ZN(t){t.resolveTargetDelta()}function XN(t){t.calcProjection()}function QN(t){t.resetSkewAndRotation()}function JN(t){t.removeLeadSnapshot()}function bc(t,s,a){t.translate=Qe(s.translate,0,a),t.scale=Qe(s.scale,1,a),t.origin=s.origin,t.originPoint=s.originPoint}function jc(t,s,a,r){t.min=Qe(s.min,a.min,r),t.max=Qe(s.max,a.max,r)}function ew(t,s,a,r){jc(t.x,s.x,a.x,r),jc(t.y,s.y,a.y,r)}function tw(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const sw={duration:.45,ease:[.4,0,.1,1]},Nc=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),wc=Nc("applewebkit/")&&!Nc("chrome/")?Math.round:ss;function Cc(t){t.min=wc(t.min),t.max=wc(t.max)}function aw(t){Cc(t.x),Cc(t.y)}function Gu(t,s,a){return t==="position"||t==="preserve-aspect"&&!cN(xc(s),xc(a),.2)}function rw(t){var s;return t!==t.root&&((s=t.scroll)==null?void 0:s.wasRoot)}const nw=Ku({attachResizeListener:(t,s)=>Xa(t,"resize",s),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),En={current:void 0},Yu=Ku({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!En.current){const t=new nw({});t.mount(window),t.setOptions({layoutScroll:!0}),En.current=t}return En.current},resetTransform:(t,s)=>{t.style.transform=s!==void 0?s:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),iw={pan:{Feature:CN},drag:{Feature:wN,ProjectionNode:Yu,MeasureLayout:Vu}};function Sc(t,s,a){const{props:r}=t;t.animationState&&r.whileHover&&t.animationState.setActive("whileHover",a==="Start");const n="onHover"+a,i=r[n];i&&Ye.postRender(()=>i(s,rr(s)))}class ow extends zs{mount(){const{current:s}=this.node;s&&(this.unmount=kb(s,(a,r)=>(Sc(this.node,r,"Start"),n=>Sc(this.node,n,"End"))))}unmount(){}}class lw extends zs{constructor(){super(...arguments),this.isActive=!1}onFocus(){let s=!1;try{s=this.node.current.matches(":focus-visible")}catch{s=!0}!s||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=tr(Xa(this.node.current,"focus",()=>this.onFocus()),Xa(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Ac(t,s,a){const{props:r}=t;if(t.current instanceof HTMLButtonElement&&t.current.disabled)return;t.animationState&&r.whileTap&&t.animationState.setActive("whileTap",a==="Start");const n="onTap"+(a==="End"?"":a),i=r[n];i&&Ye.postRender(()=>i(s,rr(s)))}class cw extends zs{mount(){const{current:s}=this.node;s&&(this.unmount=Eb(s,(a,r)=>(Ac(this.node,r,"Start"),(n,{success:i})=>Ac(this.node,n,i?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const bi=new WeakMap,Mn=new WeakMap,dw=t=>{const s=bi.get(t.target);s&&s(t)},mw=t=>{t.forEach(dw)};function uw({root:t,...s}){const a=t||document;Mn.has(a)||Mn.set(a,{});const r=Mn.get(a),n=JSON.stringify(s);return r[n]||(r[n]=new IntersectionObserver(mw,{root:t,...s})),r[n]}function hw(t,s,a){const r=uw(s);return bi.set(t,a),r.observe(t),()=>{bi.delete(t),r.unobserve(t)}}const pw={some:0,all:1};class xw extends zs{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:s={}}=this.node.getProps(),{root:a,margin:r,amount:n="some",once:i}=s,o={root:a?a.current:void 0,rootMargin:r,threshold:typeof n=="number"?n:pw[n]},l=c=>{const{isIntersecting:d}=c;if(this.isInView===d||(this.isInView=d,i&&!d&&this.hasEnteredView))return;d&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",d);const{onViewportEnter:m,onViewportLeave:u}=this.node.getProps(),h=d?m:u;h&&h(c)};return hw(this.node.current,o,l)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:s,prevProps:a}=this.node;["amount","margin","root"].some(gw(s,a))&&this.startObserver()}unmount(){}}function gw({viewport:t={}},{viewport:s={}}={}){return a=>t[a]!==s[a]}const fw={inView:{Feature:xw},tap:{Feature:cw},focus:{Feature:lw},hover:{Feature:ow}},yw={layout:{ProjectionNode:Yu,MeasureLayout:Vu}},vw={...aN,...fw,...iw,...yw},St=vj(vw,Ej),Tc=[{id:"claim-management",name:"Claim Management",description:"End-to-end dealer claim processing workflow with automatic IO generation and budget blocking",category:"Dealer Operations",icon:Kn,color:"from-blue-500 to-indigo-600",estimatedTime:"5-7 days",steps:7,features:["Automatic IO confirmation","Budget blocking","Document verification","E-invoice generation","Credit note issuance"]},{id:"vendor-payment",name:"Vendor Payment",description:"Streamlined vendor payment approval with PO validation and financial controls",category:"Finance",icon:Cx,color:"from-green-500 to-emerald-600",estimatedTime:"3-5 days",steps:5,features:["PO matching","Invoice verification","Multi-level approvals","Payment scheduling"]}];function bw({open:t,onClose:s,onSelectTemplate:a}){var l;const[r,n]=g.useState(null),i=c=>{n(c)},o=()=>{r&&(a(r),s())};return e.jsx(ot,{open:t,onOpenChange:s,children:e.jsxs(Je,{className:"!fixed !inset-0 !top-0 !left-0 !right-0 !bottom-0 !w-screen !h-screen !max-w-none !translate-x-0 !translate-y-0 p-0 gap-0 border-0 !rounded-none bg-gradient-to-br from-gray-50 to-white [&>button]:hidden !m-0",children:[e.jsx(et,{className:"sr-only",children:"Select a Template"}),e.jsx(Zt,{className:"sr-only",children:"Choose from pre-configured templates with predefined workflows and approval chains for faster processing."}),e.jsx("button",{onClick:s,className:"absolute top-6 right-6 z-50 w-10 h-10 rounded-full bg-white shadow-lg hover:shadow-xl border border-gray-200 flex items-center justify-center transition-all hover:scale-110",children:e.jsx(ft,{className:"w-5 h-5 text-gray-600"})}),e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsxs("div",{className:"min-h-full flex flex-col items-center justify-center px-6 py-12",children:[e.jsxs(St.div,{initial:{opacity:0,y:-20},animate:{opacity:1,y:0},className:"text-center mb-12 max-w-3xl",children:[e.jsx("div",{className:"w-20 h-20 bg-gradient-to-br from-blue-500 to-purple-600 rounded-2xl flex items-center justify-center mx-auto mb-6",children:e.jsx(Vr,{className:"w-10 h-10 text-white"})}),e.jsx("h1",{className:"text-4xl lg:text-5xl font-bold text-gray-900 mb-4",children:"Choose Your Template"}),e.jsx("p",{className:"text-lg text-gray-600",children:"Select from pre-configured templates with predefined workflows and approval chains for faster processing."})]}),e.jsx("div",{className:"w-full max-w-5xl grid grid-cols-1 md:grid-cols-2 gap-6 mb-8",children:Tc.map((c,d)=>{const m=c.icon,u=r===c.id;return e.jsx(St.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:d*.1},whileHover:{scale:1.03},whileTap:{scale:.98},children:e.jsxs(G,{className:`cursor-pointer h-full transition-all duration-300 border-2 ${u?"border-blue-500 shadow-xl bg-blue-50/50 ring-2 ring-blue-200":"border-gray-200 hover:border-blue-300 hover:shadow-lg"}`,onClick:()=>i(c.id),children:[e.jsxs(te,{className:"space-y-4 pb-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("div",{className:`w-14 h-14 rounded-xl bg-gradient-to-br ${c.color} flex items-center justify-center shadow-md`,children:e.jsx(m,{className:"w-7 h-7 text-white"})}),u&&e.jsx(St.div,{initial:{scale:0},animate:{scale:1},transition:{type:"spring",stiffness:500,damping:15},children:e.jsx("div",{className:"w-8 h-8 rounded-full bg-blue-600 flex items-center justify-center shadow-md",children:e.jsx(Ca,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsx(se,{className:"text-xl mb-2",children:c.name}),e.jsx(he,{className:"text-sm leading-relaxed",children:c.description})]})]}),e.jsxs(Y,{className:"pt-0 space-y-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(Q,{variant:"secondary",className:"text-xs",children:c.category})}),e.jsx(yt,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(De,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:c.estimatedTime})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(it,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[c.steps," steps"]})]})]}),e.jsxs("div",{className:"space-y-2 pt-2",children:[e.jsx("p",{className:"text-xs text-gray-500 font-semibold",children:"Key Features:"}),e.jsxs("div",{className:"space-y-1.5",children:[c.features.slice(0,3).map((h,x)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-600",children:[e.jsx(ve,{className:"w-3 h-3 text-green-600 flex-shrink-0"}),e.jsx("span",{children:h})]},x)),c.features.length>3&&e.jsxs("p",{className:"text-xs text-blue-600 italic pl-5",children:["+",c.features.length-3," more features"]})]})]})]})]})},c.id)})}),e.jsxs(St.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.3},className:"flex flex-col sm:flex-row justify-center gap-4 mt-4",children:[e.jsx(M,{variant:"outline",onClick:s,size:"lg",className:"px-8",children:"Cancel"}),e.jsxs(M,{onClick:o,disabled:!r,size:"lg",className:`gap-2 px-8 ${r?"bg-blue-600 hover:bg-blue-700":"bg-gray-400"}`,children:["Continue with Template",e.jsx(wt,{className:"w-4 h-4"})]})]}),e.jsx(Xr,{children:r&&e.jsx(St.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:-10},className:"mt-6 text-center",children:e.jsxs("p",{className:"text-sm text-gray-600",children:["Selected: ",e.jsx("span",{className:"font-semibold text-blue-600",children:(l=Tc.find(c=>c.id===r))==null?void 0:l.name})]})})})]})})]})})}const jw={template:"",title:"",description:"",category:"",priority:"",urgency:"",businessImpact:"",amount:"",currency:"USD",vendor:"",timeline:"",slaTemplate:"",slaHours:0,customSlaHours:0,slaEndDate:void 0,expectedCompletionDate:void 0,breachEscalation:!0,reminderSchedule:"50",workflowType:"sequential",requiresAllApprovals:!0,escalationEnabled:!0,reminderEnabled:!0,minimumLevel:1,maxLevel:1,approvers:[],approverCount:1,spectators:[],ccList:[],invitedUsers:[],allowComments:!0,allowDocumentUpload:!0,documents:[],tags:[],relatedRequests:[],costCenter:"",project:""};function Nw(t,s,a){const[r,n]=g.useState(jw),[i,o]=g.useState(null),[l,c]=g.useState(t),[d,m]=g.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[u,h]=g.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[x,p]=g.useState([]);return g.useEffect(()=>{(async()=>{var N;try{const f=await ra("DOCUMENT_POLICY"),b={};f.forEach(S=>{b[S.configKey]=S.configValue});const j=parseInt(b.MAX_FILE_SIZE_MB||"10"),R=(b.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(S=>S.trim().toLowerCase());h({maxFileSizeMB:j,allowedFileTypes:R});const I=await ra("WORKFLOW_SHARING"),T=await ra("TAT_SETTINGS"),E=[...I,...T],w={};E.forEach(S=>{w[S.configKey]=S.configValue}),m({maxApprovalLevels:parseInt(w.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(w.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((N=w.ALLOW_ADD_SPECTATOR)==null?void 0:N.toLowerCase())==="true",maxSpectators:parseInt(w.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(f){console.error("Failed to load policies:",f)}})()},[]),g.useEffect(()=>{if(!t||!s)return;let v=!0;return(async()=>{try{c(!0);const N=await Rs(s);if(!v||!N)return;const f=N.workflow||{},b=Array.isArray(N.approvals)?N.approvals:[],j=Array.isArray(N.participants)?N.participants:[],C=Array.isArray(N.documents)?N.documents.filter(D=>!D.isDeleted):[];p(C);const R=(f.priority||"").toString().toLowerCase(),I={standard:"standard",express:"express"},T=f.templateType==="TEMPLATE"?"existing-template":"custom",E=a.find(D=>D.id===T)||a[0]||null;o(E);const w=b.sort((D,H)=>(D.levelNumber||0)-(H.levelNumber||0)).map(D=>{const H=Number(D.tatHours||24),L=Math.floor(H/24),F=H%24;return{id:D.approverId||`temp-${D.levelNumber}`,name:D.approverName||D.approverEmail||"",email:D.approverEmail||"",role:D.levelName||`Level ${D.levelNumber}`,department:"",avatar:(D.approverName||D.approverEmail||"XX").substring(0,2).toUpperCase(),level:D.levelNumber||1,canClose:!1,tat:L>0?L:F,tatType:L>0?"days":"hours",userId:D.approverId}}),S=j.filter(D=>(D.participantType||D.participant_type||"").toString().toUpperCase().trim()==="SPECTATOR"?!!(D.userEmail||D.user_email||D.email):!1).map((D,H)=>{const L=D.userId||D.user_id||D.id,F=D.userName||D.user_name||D.name||"",A=D.userEmail||D.user_email||D.email||"",P=(F||A||"XX").split(" ").map(_=>_[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{id:L||`spectator-${s}-${H}-${Date.now()}`,userId:L,name:F||A||"Spectator",email:A,role:"Spectator",department:D.department||"",avatar:P,level:1,canClose:!1}});n(D=>({...D,template:T,title:f.title||"",description:f.description||"",priority:I[R]||"standard",approvers:w,approverCount:w.length||1,spectators:S,maxLevel:Math.max(...w.map(H=>H.level||1),1)}))}catch(N){console.error("Failed to load draft:",N)}finally{v&&c(!1)}})(),()=>{v=!1}},[t,s,a]),{formData:r,setFormData:n,updateFormData:(v,N)=>{n(f=>({...f,[v]:N}))},selectedTemplate:i,setSelectedTemplate:o,loadingDraft:l,systemPolicy:d,documentPolicy:u,existingDocuments:x,setExistingDocuments:p}}const kc=["Template Selection","Basic Information","Approval Workflow","Participants & Access","Documents & Attachments","Review & Submit"];function ww(t,s,a){const[r,n]=g.useState(t?2:1),i=kc.length,o=u=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(u),l=()=>{switch(r){case 1:return s!==null;case 2:return a.title.trim()!==""&&a.description.trim()!==""&&a.priority!=="";case 3:return(a.approverCount||1)>0&&a.approvers.length===(a.approverCount||1)&&a.approvers.every(u=>{if(!u||!u.email||!o(u.email))return!1;if(!u.userId)return!0;const h=u.tatType||"hours";return h==="hours"?u.tat&&u.tat>0&&u.tat<=720:h==="days"?u.tat&&u.tat>0&&u.tat<=30:!1});case 4:return!0;case 5:return!0;case 6:return!0;default:return!1}};return{currentStep:r,setCurrentStep:n,totalSteps:i,stepNames:kc,isStepValid:l,nextStep:()=>{l()&&(window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}),r{r>1&&(n(r-1),window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}))},goToStep:u=>{u>=1&&u<=i&&n(u)},validateEmail:o}}function Cw(){const[t,s]=g.useState({open:!1,type:"error",email:"",message:""}),[a,r]=g.useState({open:!1,violations:[]}),[n,i]=g.useState({open:!1,errors:[]});return{validationModal:t,policyViolationModal:a,documentErrorModal:n,openValidationModal:(h,x,p="")=>{s({open:!0,type:h,email:x,message:p})},closeValidationModal:()=>{s(h=>({...h,open:!1}))},openPolicyViolationModal:h=>{r({open:!0,violations:h})},closePolicyViolationModal:()=>{r({open:!1,violations:[]})},openDocumentErrorModal:h=>{i({open:!0,errors:h})},closeDocumentErrorModal:()=>{i({open:!1,errors:[]})}}}function Sw(t){const s=(t==null?void 0:t.userId)||"",a=(t==null?void 0:t.email)||"",r=(t==null?void 0:t.displayName)||(t==null?void 0:t.name)||a.split("@")[0]||"Initiator";return{userId:s,userEmail:a,userName:r,participantType:"INITIATOR",canComment:!0,canViewDocuments:!0,canDownloadDocuments:!0,notificationEnabled:!0,addedBy:s}}function Aw(t,s){return t.filter(a=>a==null?void 0:a.email).map(a=>({userId:a.userId||void 0,userEmail:a.email,userName:a.name||a.email.split("@")[0]||"Approver",participantType:"APPROVER",canComment:!0,canViewDocuments:!0,canDownloadDocuments:!0,notificationEnabled:!0,addedBy:s}))}function Tw(t,s){return t.filter(a=>a==null?void 0:a.email).map(a=>({userId:a.id||a.userId||void 0,userEmail:a.email,userName:a.name||a.email.split("@")[0]||"Spectator",participantType:"SPECTATOR",canComment:!0,canViewDocuments:!0,canDownloadDocuments:!0,notificationEnabled:!0,addedBy:s}))}function Zu(t,s,a){const r=Sw(t),n=(t==null?void 0:t.userId)||"",i=Aw(s,n),o=Tw(a,n);return[r,...i,...o]}function kw(t,s){const a=t.map(n=>n==null?void 0:n.userId).filter(Boolean),r=t.map(n=>{var i,o;return(o=(i=n==null?void 0:n.email)==null?void 0:i.toLowerCase)==null?void 0:o.call(i)}).filter(Boolean);return s.filter(n=>{const i=a.includes(n==null?void 0:n.id),o=r.includes(((n==null?void 0:n.email)||"").toLowerCase());return!i&&!o})}function Rw(t,s){const a=typeof t=="number"?t:parseInt(String(t))||0;return s==="days"?a*24:a||24}function Dw(t,s,a){var n;const r=Rw(t.tat||24,t.tatType||"hours");return{levelNumber:s,levelName:`Level ${s}`,approverId:t.userId||"",approverEmail:t.email||"",approverName:t.name||((n=t.email)==null?void 0:n.split("@")[0])||`Approver ${s}`,tatHours:r,isFinalApprover:a}}function Pw(t,s){return t.slice(0,s).map((a,r)=>{const n=r+1;return Dw(a,n,n===s)})}function Rc(t,s,a){const r=Zu(a,t.approvers||[],t.spectators||[]),n=kw(t.approvers||[],t.spectators||[]);return{templateId:(s==null?void 0:s.id)||null,templateType:(s==null?void 0:s.id)==="custom"?"CUSTOM":"TEMPLATE",title:t.title,description:t.description,priorityUi:t.priority==="express"?"express":"standard",approverCount:t.approverCount||1,approvers:(t.approvers||[]).map(i=>({userId:(i==null?void 0:i.userId)||"",email:(i==null?void 0:i.email)||"",name:i==null?void 0:i.name,tat:(i==null?void 0:i.tat)||"",tatType:(i==null?void 0:i.tatType)||"hours"})),spectators:n.map(i=>{var o,l;return{userId:(i==null?void 0:i.id)||"",name:(i==null?void 0:i.name)||((l=(o=i==null?void 0:i.email)==null?void 0:o.split("@"))==null?void 0:l[0])||"Spectator",email:(i==null?void 0:i.email)||""}}),ccList:(t.ccList||[]).map(i=>{var o,l;return{id:i==null?void 0:i.id,name:(i==null?void 0:i.name)||((l=(o=i==null?void 0:i.email)==null?void 0:o.split("@"))==null?void 0:l[0])||"CC",email:(i==null?void 0:i.email)||""}}),participants:r}}function Dc(t,s,a){const r=Pw(t.approvers||[],t.approverCount||1),n=Zu(s,(t.approvers||[]).filter(i=>(i==null?void 0:i.email)&&(i==null?void 0:i.userId)),(t.spectators||[]).filter(i=>i==null?void 0:i.email));return{title:t.title,description:t.description,priority:t.priority==="express"?"EXPRESS":"STANDARD",approvalLevels:r,participants:n,deleteDocumentIds:a.length>0?a:void 0}}function Ew(t,s){return t.slice(0,s).some(n=>!(n!=null&&n.userId)||!(n!=null&&n.email))?{valid:!1,message:"Please select approvers using @ search so we can capture their user IDs."}:{valid:!0}}async function Xu(t,s){return{id:(await Oi(t,s||[],"SUPPORTING")).id}}async function Qu(t,s,a,r){const n=a&&a.length>0,i=r.length>0;n||i?await am(t,s,a||[],r):await sm(t,s)}async function Ju(t){await zi(t)}async function Mw(t,s){const a=await Xu(t,s);return await Ju(a.id),a}async function Iw(t,s,a,r){await Qu(t,s,a,r),await Ju(t)}function _w({formData:t,selectedTemplate:s,documents:a,documentsToDelete:r,user:n,isEditing:i,editRequestId:o,onSubmit:l}){const[c,d]=g.useState(!1),[m,u]=g.useState(!1);return{submitting:c,savingDraft:m,handleSubmit:async()=>{if(c||m)return;const p=Ew(t.approvers||[],t.approverCount||1);if(!p.valid){alert(p.message);return}d(!0);try{if(i&&o){const y=Dc(t,n,r);await Iw(o,y,a,r),l==null||l({...t,backendId:o,template:s})}else{const y=Rc(t,s,n),v=await Mw(y,a);l==null||l({...t,backendId:v.id,template:s})}}catch(y){console.error("Failed to submit workflow:",y),d(!1)}},handleSaveDraft:async()=>{if(!(!s||!t.title.trim()||!t.description.trim()||!t.priority)&&!(c||m)){u(!0);try{if(i&&o){const p=Dc(t,n,r);await Qu(o,p,a,r),l==null||l({...t,backendId:o,template:s})}else{const p=Rc(t,s,n),y=await Xu(p,a);l==null||l({...t,backendId:y.id,template:s})}}catch(p){console.error("Failed to save draft:",p),u(!1)}}}}}async function Lw(t,s){var a;if(t.email.toLowerCase()===s.toLowerCase())return{success:!1,error:{type:"self-assign",email:t.email,message:""}};try{const n=((a=(await xs(t.email,1)).data)==null?void 0:a.data)||[];if(n.length===0)return{success:!1,error:{type:"not-found",email:t.email,message:""}};const i=n[0];return i?(await bs({userId:i.userId,email:i.email,displayName:i.displayName,firstName:i.firstName,lastName:i.lastName,department:i.department,phone:i.phone,mobilePhone:i.mobilePhone,designation:i.designation,jobTitle:i.jobTitle,manager:i.manager,employeeId:i.employeeId,employeeNumber:i.employeeNumber,secondEmail:i.secondEmail,location:i.location}),{success:!0}):{success:!1,error:{type:"error",email:t.email,message:"Could not retrieve user details. Please try again."}}}catch(r){return console.error(`Failed to validate approver ${t.email}:`,r),{success:!1,error:{type:"error",email:t.email,message:"Failed to validate user. Please try again or select a different user."}}}}async function Fw(t,s){var n;if(t.filter(i=>i&&i.email&&!i.userId).length===0)return{success:!0,validatedApprovers:t};const r=[...t];for(let i=0;i{s(C),a("template",C.id),a("category",C.category),a("priority",C.priority);const R=new Date;R.setDate(R.getDate()+C.suggestedSLA),a("slaEndDate",R),C.id==="existing-template"&&h(!0)},handleTemplateSelection:C=>{m&&m({templateType:C})},nextStep:async()=>{var C;if(i()){if(window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}),n===3){const R=((C=c==null?void 0:c.email)==null?void 0:C.toLowerCase())||"",I=await Fw(r.approvers,R);if(!I.success&&I.error){d(I.error.type,I.error.email,I.error.message);return}I.validatedApprovers&&a("approvers",I.validatedApprovers)}o()}},prevStep:()=>{l(),window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"})},handlePreviewDocument:(C,R)=>{if(R){const I=C.documentId||C.document_id||"";p({fileName:C.originalFileName||C.fileName||"Document",fileType:C.fileType||C.file_type||"application/octet-stream",fileUrl:Bi(I),fileSize:Number(C.fileSize||C.file_size||0),documentId:I})}else{const I=URL.createObjectURL(C);p({fileName:C.name,fileType:C.type||"application/octet-stream",fileUrl:I,fileSize:C.size,file:C})}},closePreview:()=>{x!=null&&x.fileUrl&&(x!=null&&x.file)&&URL.revokeObjectURL(x.fileUrl),p(null)}}}const Pc=[{id:"custom",name:"Custom Request",description:"Create a custom request for unique business needs with full flexibility to define your own workflow and requirements",category:"General",icon:Ur,estimatedTime:"Variable",commonApprovers:[],suggestedSLA:3,priority:"medium",fields:{}},{id:"existing-template",name:"Existing Template",description:"Use a pre-configured template with predefined approval workflows, timelines, and requirements for faster processing",category:"Templates",icon:Te,estimatedTime:"1-2 days",commonApprovers:["Department Head","Manager"],suggestedSLA:2,priority:"medium",fields:{timeline:!0}}];function $w({currentStep:t,totalSteps:s,stepNames:a}){const r=Math.round(t/s*100);return e.jsx("div",{className:"bg-white border-b border-gray-200 px-3 sm:px-6 py-2 sm:py-3 flex-shrink-0","data-testid":"wizard-stepper",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"block sm:hidden","data-testid":"wizard-stepper-mobile",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-green-600 text-white flex items-center justify-center text-xs font-semibold","data-testid":"wizard-stepper-mobile-current-step",children:t}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-900","data-testid":"wizard-stepper-mobile-step-name",children:a[t-1]}),e.jsxs("p",{className:"text-xs text-gray-600","data-testid":"wizard-stepper-mobile-step-info",children:["Step ",t," of ",s]})]})]}),e.jsx("div",{className:"text-right",children:e.jsxs("p",{className:"text-xs font-medium text-green-600","data-testid":"wizard-stepper-mobile-progress",children:[r,"%"]})})]}),e.jsx("div",{className:"w-full bg-gray-200 h-1.5 rounded-full overflow-hidden","data-testid":"wizard-stepper-mobile-progress-bar",children:e.jsx("div",{className:"bg-green-600 h-full transition-all duration-300",style:{width:`${r}%`},"data-testid":"wizard-stepper-mobile-progress-fill"})})]}),e.jsxs("div",{className:"hidden sm:block","data-testid":"wizard-stepper-desktop",children:[e.jsx("div",{className:"flex items-center justify-between mb-2","data-testid":"wizard-stepper-desktop-steps",children:a.map((n,i)=>e.jsxs("div",{className:"flex items-center","data-testid":`wizard-stepper-desktop-step-${i+1}`,children:[e.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center text-xs font-semibold ${i+1e.jsx("span",{className:`${i+1===t?"font-semibold text-blue-600":""}`,"data-testid":`wizard-stepper-desktop-label-${i+1}`,children:n},i))})]})]})})}function Uw({currentStep:t,totalSteps:s,isStepValid:a,onPrev:r,onNext:n,onSubmit:i,onSaveDraft:o,submitting:l,savingDraft:c,loadingDraft:d,isEditing:m}){return e.jsx("div",{className:"fixed sm:relative bottom-0 left-0 right-0 bg-white border-t border-gray-200 px-3 sm:px-6 py-3 sm:py-4 flex-shrink-0 shadow-lg sm:shadow-none z-50","data-testid":"wizard-footer",children:e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between items-stretch sm:items-center gap-2 sm:gap-4 max-w-6xl mx-auto",children:[e.jsxs(M,{variant:"outline",onClick:r,disabled:t===1,size:"sm",className:"sm:size-lg order-2 sm:order-1","data-testid":"wizard-footer-prev-button",children:[e.jsx(_s,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Previous"})]}),e.jsxs("div",{className:"flex gap-2 sm:gap-3 order-1 sm:order-2","data-testid":"wizard-footer-actions",children:[e.jsx(M,{variant:"outline",onClick:o,size:"sm",className:"sm:size-lg flex-1 sm:flex-none text-xs sm:text-sm",disabled:d||l||c,"data-testid":"wizard-footer-save-draft-button",children:c?e.jsxs(e.Fragment,{children:[e.jsx(Le,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2 animate-spin"}),e.jsx("span",{children:m?"Updating...":"Saving..."})]}):e.jsx("span",{children:m?"Update Draft":"Save Draft"})}),t===s?e.jsx(M,{onClick:i,disabled:!a||d||l||c,size:"sm",className:"sm:size-lg bg-green-600 hover:bg-green-700 flex-1 sm:flex-none sm:px-8 text-xs sm:text-sm","data-testid":"wizard-footer-submit-button",children:l?e.jsxs(e.Fragment,{children:[e.jsx(Le,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2 animate-spin"}),"Submitting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(vd,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),"Submit"]})}):e.jsxs(M,{onClick:n,disabled:!a,size:"sm",className:"sm:size-lg flex-1 sm:flex-none sm:px-8 text-xs sm:text-sm","data-testid":"wizard-footer-next-button",children:[e.jsx("span",{className:"hidden sm:inline",children:"Next Step"}),e.jsx("span",{className:"sm:hidden",children:"Next"}),e.jsx(wt,{className:"h-3 w-3 sm:h-4 sm:w-4 ml-1 sm:ml-2"})]})]})]})})}const Ec=t=>{switch(t){case"high":return e.jsx(ls,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(it,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(Us,{className:"w-4 h-4 text-green-600"});default:return e.jsx(it,{className:"w-4 h-4 text-gray-600"})}};function Vw({templates:t,selectedTemplate:s,onSelectTemplate:a}){return e.jsxs(St.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"min-h-full flex flex-col items-center justify-center py-8","data-testid":"template-selection-step",children:[e.jsxs("div",{className:"text-center mb-12 max-w-3xl","data-testid":"template-selection-header",children:[e.jsx("h1",{className:"text-4xl lg:text-5xl font-bold text-gray-900 mb-4","data-testid":"template-selection-title",children:"Choose Your Request Type"}),e.jsx("p",{className:"text-lg text-gray-600","data-testid":"template-selection-description",children:"Start with a pre-built template for faster approvals, or create a custom request tailored to your needs."})]}),e.jsx("div",{className:"w-full max-w-6xl grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8","data-testid":"template-selection-grid",children:t.map(r=>e.jsx(St.div,{whileHover:{scale:1.03},whileTap:{scale:.98},transition:{type:"spring",stiffness:300,damping:20},"data-testid":`template-card-${r.id}`,children:e.jsxs(G,{className:`cursor-pointer h-full transition-all duration-300 border-2 ${(s==null?void 0:s.id)===r.id?"border-blue-500 shadow-xl bg-blue-50/50 ring-2 ring-blue-200":"border-gray-200 hover:border-blue-300 hover:shadow-lg"}`,onClick:()=>a(r),"data-testid":`template-card-${r.id}-clickable`,children:[e.jsxs(te,{className:"space-y-4 pb-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("div",{className:`w-14 h-14 rounded-xl flex items-center justify-center ${(s==null?void 0:s.id)===r.id?"bg-blue-100":"bg-gray-100"}`,"data-testid":`template-card-${r.id}-icon`,children:e.jsx(r.icon,{className:`w-7 h-7 ${(s==null?void 0:s.id)===r.id?"text-blue-600":"text-gray-600"}`})}),(s==null?void 0:s.id)===r.id&&e.jsx(St.div,{initial:{scale:0},animate:{scale:1},transition:{type:"spring",stiffness:500,damping:15},"data-testid":`template-card-${r.id}-selected-indicator`,children:e.jsx("div",{className:"w-8 h-8 rounded-full bg-blue-600 flex items-center justify-center",children:e.jsx(Ca,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsx(se,{className:"text-xl mb-2","data-testid":`template-card-${r.id}-name`,children:r.name}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Q,{variant:"secondary",className:"text-xs","data-testid":`template-card-${r.id}-category`,children:r.category}),Ec(r.priority)]})]})]}),e.jsxs(Y,{className:"pt-0 space-y-4",children:[e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed line-clamp-2","data-testid":`template-card-${r.id}-description`,children:r.description}),e.jsx(yt,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1.5","data-testid":`template-card-${r.id}-estimated-time`,children:[e.jsx(De,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:r.estimatedTime})]}),e.jsxs("div",{className:"flex items-center gap-1.5","data-testid":`template-card-${r.id}-approvers-count`,children:[e.jsx(at,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[r.commonApprovers.length," approvers"]})]})]})]})]})},r.id))}),e.jsx(Xr,{children:s&&e.jsx(St.div,{initial:{opacity:0,y:20,height:0},animate:{opacity:1,y:0,height:"auto"},exit:{opacity:0,y:-20,height:0},transition:{duration:.3},className:"w-full max-w-6xl","data-testid":"template-details-card",children:e.jsxs(G,{className:"bg-gradient-to-br from-blue-50 to-indigo-50 border-2 border-blue-200",children:[e.jsx(te,{children:e.jsxs(se,{className:"flex items-center gap-2 text-blue-900","data-testid":"template-details-title",children:[e.jsx(Fr,{className:"w-5 h-5"}),s.name," - Template Details"]})}),e.jsxs(Y,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-sla",children:[e.jsx(X,{className:"text-blue-900 font-semibold",children:"Suggested SLA"}),e.jsxs("p",{className:"text-blue-700 mt-1",children:[s.suggestedSLA," days"]})]}),e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-priority",children:[e.jsx(X,{className:"text-blue-900 font-semibold",children:"Priority Level"}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[Ec(s.priority),e.jsx("span",{className:"text-blue-700 capitalize",children:s.priority})]})]}),e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-duration",children:[e.jsx(X,{className:"text-blue-900 font-semibold",children:"Estimated Duration"}),e.jsx("p",{className:"text-blue-700 mt-1",children:s.estimatedTime})]})]}),e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-approvers",children:[e.jsx(X,{className:"text-blue-900 font-semibold",children:"Common Approvers"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:s.commonApprovers.map((r,n)=>e.jsx(Q,{variant:"outline",className:"border-blue-300 text-blue-700 bg-white","data-testid":`template-details-approver-${n}`,children:r},`${s.id}-approver-${n}-${r}`))})]})]})]})})})]})}function Bw({className:t,...s}){return e.jsx(Cp,{"data-slot":"radio-group",className:oe("grid gap-3",t),...s})}function Mc({className:t,...s}){return e.jsx(Sp,{"data-slot":"radio-group-item",className:oe("border-input text-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 aspect-square size-4 shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",t),...s,children:e.jsx(Ap,{"data-slot":"radio-group-indicator",className:"relative flex items-center justify-center",children:e.jsx(Sx,{className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}function zw({formData:t,selectedTemplate:s,updateFormData:a}){return e.jsxs(St.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"space-y-6","data-testid":"basic-information-step",children:[e.jsxs("div",{className:"text-center mb-8","data-testid":"basic-information-header",children:[e.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-green-500 to-blue-600 rounded-2xl flex items-center justify-center mx-auto mb-4",children:e.jsx(Te,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"basic-information-title",children:"Basic Information"}),e.jsxs("p",{className:"text-gray-600","data-testid":"basic-information-description",children:["Provide the essential details for your ",(s==null?void 0:s.name)||"request","."]})]}),e.jsxs("div",{className:"max-w-2xl mx-auto space-y-6","data-testid":"basic-information-form",children:[e.jsxs("div",{"data-testid":"basic-information-title-field",children:[e.jsx(X,{htmlFor:"title",className:"text-base font-semibold",children:"Request Title *"}),e.jsx("p",{className:"text-sm text-gray-600 mb-3",children:"Be specific and descriptive. This will be visible to all participants."}),e.jsx(xe,{id:"title",placeholder:"e.g., Approval on new office location",value:t.title,onChange:r=>a("title",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-title-input"})]}),e.jsxs("div",{"data-testid":"basic-information-description-field",children:[e.jsx(X,{htmlFor:"description",className:"text-base font-semibold",children:"Detailed Description *"}),e.jsxs("p",{className:"text-sm text-gray-600 mb-3",children:["Explain what you need approval for, why it's needed, and any relevant background information.",e.jsx("span",{className:"block mt-1 text-xs text-blue-600",children:"💡 Tip: You can paste formatted content (lists, tables) and the formatting will be preserved."})]}),e.jsx(mm,{value:t.description||"",onChange:r=>a("description",r),placeholder:"Provide comprehensive details about your request including scope, objectives, expected outcomes, and any supporting context that will help approvers make an informed decision.",className:"min-h-[120px] text-base border-2 border-gray-300 focus-within:border-blue-500 bg-white shadow-sm",minHeight:"120px","data-testid":"basic-information-description-textarea"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6","data-testid":"basic-information-priority-section",children:e.jsxs("div",{"data-testid":"basic-information-priority-field",children:[e.jsx(X,{className:"text-base font-semibold",children:"Priority Level *"}),e.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"select priority for your request"}),e.jsxs(Bw,{value:t.priority||"",onValueChange:r=>a("priority",r),"data-testid":"basic-information-priority-radio-group",children:[e.jsxs("div",{className:`flex items-center space-x-3 p-3 rounded-lg border-2 cursor-pointer transition-all ${t.priority==="express"?"border-red-500 bg-red-100":"border-red-200 bg-red-50 hover:bg-red-100"}`,onClick:()=>a("priority","express"),"data-testid":"basic-information-priority-express-option",children:[e.jsx(Mc,{value:"express",id:"express"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(ki,{className:"w-4 h-4 text-red-600"}),e.jsx(X,{htmlFor:"express",className:"font-medium text-red-900 cursor-pointer",children:"Express"}),e.jsx(Q,{variant:"destructive",className:"text-xs",children:"URGENT"})]}),e.jsx("p",{className:"text-xs text-red-700",children:"Includes calendar days in TAT - faster processing timeline"})]})]}),e.jsxs("div",{className:`flex items-center space-x-3 p-3 rounded-lg border cursor-pointer transition-all ${t.priority==="standard"?"border-blue-500 bg-blue-50":"border-gray-200 hover:bg-gray-50"}`,onClick:()=>a("priority","standard"),"data-testid":"basic-information-priority-standard-option",children:[e.jsx(Mc,{value:"standard",id:"standard"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(De,{className:"w-4 h-4 text-blue-600"}),e.jsx(X,{htmlFor:"standard",className:"font-medium text-blue-900 cursor-pointer",children:"Standard"}),e.jsx(Q,{variant:"secondary",className:"text-xs",children:"DEFAULT"})]}),e.jsx("p",{className:"text-xs text-gray-600",children:"Includes working days in TAT - regular processing timeline"})]})]})]})]})}),((s==null?void 0:s.fields.amount)||(s==null?void 0:s.fields.vendor)||(s==null?void 0:s.fields.timeline)||(s==null?void 0:s.fields.impact))&&e.jsxs("div",{className:"border-t pt-6","data-testid":"basic-information-additional-details",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Additional Details"}),e.jsxs("div",{className:"space-y-6",children:[(s==null?void 0:s.fields.amount)&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4","data-testid":"basic-information-amount-field",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(X,{htmlFor:"amount",className:"text-base font-semibold",children:"Budget Amount"}),e.jsx(xe,{id:"amount",placeholder:"Enter amount",value:t.amount,onChange:r=>a("amount",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-amount-input"})]}),e.jsxs("div",{children:[e.jsx(X,{className:"text-base font-semibold",children:"Currency"}),e.jsxs(we,{value:t.currency,onValueChange:r=>a("currency",r),"data-testid":"basic-information-currency-select",children:[e.jsx(Se,{className:"h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm",children:e.jsx(Ce,{})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"USD",children:"USD ($)"}),e.jsx(V,{value:"EUR",children:"EUR (€)"}),e.jsx(V,{value:"GBP",children:"GBP (£)"}),e.jsx(V,{value:"INR",children:"INR (₹)"})]})]})]})]}),(s==null?void 0:s.fields.vendor)&&e.jsxs("div",{"data-testid":"basic-information-vendor-field",children:[e.jsx(X,{htmlFor:"vendor",className:"text-base font-semibold",children:"Vendor/Supplier"}),e.jsx(xe,{id:"vendor",placeholder:"Enter vendor or supplier name",value:t.vendor,onChange:r=>a("vendor",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-vendor-input"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{"data-testid":"basic-information-cost-center-field",children:[e.jsx(X,{htmlFor:"costCenter",className:"text-base font-semibold",children:"Cost Center"}),e.jsx(xe,{id:"costCenter",placeholder:"e.g., Marketing, IT, Operations",value:t.costCenter,onChange:r=>a("costCenter",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-cost-center-input"})]}),e.jsxs("div",{"data-testid":"basic-information-project-field",children:[e.jsx(X,{htmlFor:"project",className:"text-base font-semibold",children:"Related Project"}),e.jsx(xe,{id:"project",placeholder:"Associated project name or code",value:t.project,onChange:r=>a("project",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-project-input"})]})]})]})]})]})]})}function Hw(){const[t,s]=g.useState([]),[a,r]=g.useState(!1),n=g.useRef(null);return{searchResults:t,searchLoading:a,searchUsersDebounced:async(c,d=10)=>{if(n.current&&clearTimeout(n.current),!c||!c.startsWith("@")||c.length<2){s([]),r(!1);return}r(!0),n.current=setTimeout(async()=>{var m;try{const u=c.slice(1),x=((m=(await xs(u,d)).data)==null?void 0:m.data)||[];s(x)}catch(u){console.error("User search failed:",u),s([])}finally{r(!1)}},300)},clearSearch:()=>{n.current&&clearTimeout(n.current),s([]),r(!1)},ensureUser:async c=>{try{return await bs({userId:c.userId,email:c.email,displayName:c.displayName,firstName:c.firstName,lastName:c.lastName,department:c.department,phone:c.phone,mobilePhone:c.mobilePhone,designation:c.designation,jobTitle:c.jobTitle,manager:c.manager,employeeId:c.employeeId,employeeNumber:c.employeeNumber,secondEmail:c.secondEmail,location:c.location})}catch(d){throw console.error("Failed to ensure user exists:",d),d}}}}function qw(){const[t,s]=g.useState({}),[a,r]=g.useState({}),n=g.useRef({});return{userSearchResults:t,userSearchLoading:a,searchUsersForIndex:async(l,c,d=10)=>{if(n.current[l]&&clearTimeout(n.current[l]),!c||!c.startsWith("@")||c.length<2){s(m=>({...m,[l]:[]})),r(m=>({...m,[l]:!1}));return}r(m=>({...m,[l]:!0})),n.current[l]=setTimeout(async()=>{var m;try{const u=c.slice(1),x=((m=(await xs(u,d)).data)==null?void 0:m.data)||[];s(p=>({...p,[l]:x}))}catch(u){console.error(`User search failed for index ${l}:`,u),s(h=>({...h,[l]:[]}))}finally{r(u=>({...u,[l]:!1}))}},300)},clearSearchForIndex:l=>{n.current[l]&&clearTimeout(n.current[l]),s(c=>({...c,[l]:[]})),r(c=>({...c,[l]:!1}))}}}function Ww({formData:t,updateFormData:s,onValidationError:a}){const{userSearchResults:r,userSearchLoading:n,searchUsersForIndex:i,clearSearchForIndex:o}=qw();g.useEffect(()=>{const d=t.approverCount||1,m=t.approvers||[];if(m.lengthd&&s("approvers",m.slice(0,d))},[t.approverCount,s]);const l=(d,m)=>{var p,y,v,N,f;const u=[...t.approvers],x=((p=u[d])==null?void 0:p.email)!==m;if(u[d]={...u[d],email:m,level:d+1,userId:x||(y=u[d])==null?void 0:y.userId,name:x||(v=u[d])==null?void 0:v.name,department:x||(N=u[d])==null?void 0:N.department,avatar:x||(f=u[d])==null?void 0:f.avatar},s("approvers",u),!m||!m.startsWith("@")||m.length<2){o(d);return}i(d,m,10)},c=async(d,m)=>{var u,h;try{if((u=t.approvers)==null?void 0:u.some((N,f)=>{var b,j;return f!==d&&(N.userId===m.userId||((b=N.email)==null?void 0:b.toLowerCase())===((j=m.email)==null?void 0:j.toLowerCase()))})){a({type:"error",email:m.email,message:"This user is already added as an approver in another level."});return}if((h=t.spectators)==null?void 0:h.some(N=>{var f,b;return N.userId===m.userId||((f=N.email)==null?void 0:f.toLowerCase())===((b=m.email)==null?void 0:b.toLowerCase())})){a({type:"error",email:m.email,message:"This user is already added as a spectator. A user cannot be both an approver and a spectator."});return}const y=await bs({userId:m.userId,email:m.email,displayName:m.displayName,firstName:m.firstName,lastName:m.lastName,department:m.department,phone:m.phone,mobilePhone:m.mobilePhone,designation:m.designation,jobTitle:m.jobTitle,manager:m.manager,employeeId:m.employeeId,employeeNumber:m.employeeNumber,secondEmail:m.secondEmail,location:m.location}),v=[...t.approvers];v[d]={...v[d],email:m.email,name:m.displayName||[m.firstName,m.lastName].filter(Boolean).join(" "),userId:y.userId,level:d+1},s("approvers",v),o(d)}catch(x){console.error("Failed to ensure user exists:",x),a({type:"error",email:m.email,message:"Failed to validate user. Please try again."})}};return e.jsxs(St.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"space-y-6","data-testid":"approval-workflow-step",children:[e.jsxs("div",{className:"text-center mb-8","data-testid":"approval-workflow-header",children:[e.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-orange-500 to-red-600 rounded-2xl flex items-center justify-center mx-auto mb-4",children:e.jsx(at,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"approval-workflow-title",children:"Approval Workflow"}),e.jsx("p",{className:"text-gray-600","data-testid":"approval-workflow-description",children:"Define the approval hierarchy and assign approvers by email ID."})]}),e.jsxs("div",{className:"max-w-4xl mx-auto space-y-8","data-testid":"approval-workflow-content",children:[e.jsxs(G,{"data-testid":"approval-workflow-config-card",children:[e.jsxs(te,{children:[e.jsxs(se,{className:"flex items-center gap-2","data-testid":"approval-workflow-config-title",children:[e.jsx(la,{className:"w-5 h-5"}),"Approval Configuration"]}),e.jsx(he,{children:"Configure how many approvers you need and define the approval sequence."})]}),e.jsx(Y,{className:"space-y-6",children:e.jsxs("div",{"data-testid":"approval-workflow-count-field",children:[e.jsx(X,{className:"text-base font-semibold mb-4 block",children:"Number of Approvers *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(M,{type:"button",variant:"outline",size:"sm",onClick:()=>{const d=t.approverCount||1,m=Math.max(1,d-1);s("approverCount",m),t.approvers.length>m&&s("approvers",t.approvers.slice(0,m))},disabled:(t.approverCount||1)<=1,"data-testid":"approval-workflow-decrease-count",children:e.jsx(Ax,{className:"w-4 h-4"})}),e.jsx("span",{className:"text-2xl font-semibold w-12 text-center","data-testid":"approval-workflow-count-display",children:t.approverCount||1}),e.jsx(M,{type:"button",variant:"outline",size:"sm",onClick:()=>{const d=t.approverCount||1,m=Math.min(10,d+1);s("approverCount",m)},disabled:(t.approverCount||1)>=10,"data-testid":"approval-workflow-increase-count",children:e.jsx(Is,{className:"w-4 h-4"})})]}),e.jsx("p",{className:"text-sm text-gray-600 mt-2",children:"Maximum 10 approvers allowed. Each approver will review sequentially."})]})})]}),e.jsxs(G,{"data-testid":"approval-workflow-hierarchy-card",children:[e.jsxs(te,{children:[e.jsxs(se,{className:"flex items-center gap-2","data-testid":"approval-workflow-hierarchy-title",children:[e.jsx(Gt,{className:"w-5 h-5"}),"Approval Hierarchy *"]}),e.jsxs(he,{children:["Define the approval sequence. Each approver will review the request in order from Level 1 to Level ",t.approverCount||1,"."]})]}),e.jsxs(Y,{className:"space-y-6",children:[e.jsx("div",{className:"p-4 rounded-lg border-2 border-blue-200 bg-blue-50","data-testid":"approval-workflow-initiator-card",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-600 rounded-full flex items-center justify-center",children:e.jsx(rt,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold text-blue-900",children:"Request Initiator"}),e.jsx(Q,{variant:"secondary",className:"text-xs",children:"YOU"})]}),e.jsx("p",{className:"text-sm text-blue-700",children:"Creates and submits the request"})]})]})}),Array.from({length:t.approverCount||1},(d,m)=>{var p,y;const u=m+1,h=u===(t.approverCount||1),x=t.approvers[m]||{email:"",tat:""};return e.jsxs("div",{className:"space-y-3","data-testid":`approval-workflow-approver-level-${u}`,children:[e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"w-px h-6 bg-gray-300"})}),e.jsx("div",{className:`p-4 rounded-lg border-2 transition-all ${x.email?"border-green-200 bg-green-50":"border-gray-200 bg-gray-50"}`,children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${x.email?"bg-green-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold",children:u})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsxs("span",{className:"font-semibold text-gray-900",children:["Approver Level ",u]}),h&&e.jsx(Q,{variant:"destructive",className:"text-xs",children:"FINAL APPROVER"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{"data-testid":`approval-workflow-approver-${u}-email-field`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(X,{htmlFor:`approver-${u}`,className:"text-sm font-medium",children:"Email Address *"}),x.email&&x.userId&&e.jsxs(Q,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(ve,{className:"w-3 h-3 mr-1"}),"Verified"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(xe,{id:`approver-${u}`,type:"email",placeholder:"approver@royalenfield.com",value:x.email||"",onChange:v=>l(m,v.target.value),className:"h-10 border-2 border-gray-300 focus:border-blue-500 mt-1 w-full","data-testid":`approval-workflow-approver-${u}-email-input`}),(n[m]||(((p=r[m])==null?void 0:p.length)||0)>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg",children:n[m]?e.jsx("div",{className:"p-2 text-xs text-gray-500",children:"Searching..."}):e.jsx("ul",{className:"max-h-56 overflow-auto divide-y",children:(y=r[m])==null?void 0:y.map(v=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>c(m,v),"data-testid":`approval-workflow-approver-${u}-search-result-${v.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:v.displayName||v.email}),e.jsx("div",{className:"text-xs text-gray-600",children:v.email})]},v.userId))})})]})]}),e.jsxs("div",{"data-testid":`approval-workflow-approver-${u}-tat-field`,children:[e.jsx(X,{htmlFor:`tat-${u}`,className:"text-sm font-medium",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(xe,{id:`tat-${u}`,type:"number",placeholder:x.tatType==="days"?"7":"24",min:"1",max:x.tatType==="days"?"30":"720",value:x.tat||"",onChange:v=>{const N=[...t.approvers];N[m]={...N[m],tat:parseInt(v.target.value)||"",level:u,tatType:x.tatType||"hours"},s("approvers",N)},className:"h-10 border-2 border-gray-300 focus:border-blue-500 flex-1","data-testid":`approval-workflow-approver-${u}-tat-input`}),e.jsxs(we,{value:x.tatType||"hours",onValueChange:v=>{const N=[...t.approvers];N[m]={...N[m],tatType:v,level:u,tat:""},s("approvers",N)},"data-testid":`approval-workflow-approver-${u}-tat-type-select`,children:[e.jsx(Se,{className:"w-20 h-10 border-2 border-gray-300",children:e.jsx(Ce,{})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"hours",children:"Hours"}),e.jsx(V,{value:"days",children:"Days"})]})]})]})]})]})]})]})})]},u)})]})]})]})]})}function Kw({formData:t,updateFormData:s,onValidationError:a,initiatorEmail:r}){const[n,i]=g.useState(""),{searchResults:o,searchLoading:l,searchUsersDebounced:c,clearSearch:d,ensureUser:m}=Hw(),u=p=>{if(i(p),!p||!p.startsWith("@")||p.length<2){d();return}c(p,10)},h=async p=>{var y,v;if(p){if(p.email.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:p.email,message:"You cannot add yourself as a spectator."});return}const N=t.spectators.some(b=>{var j,C;return b.userId===p.userId||((j=b.email)==null?void 0:j.toLowerCase())===((C=p.email)==null?void 0:C.toLowerCase())}),f=(y=t.approvers)==null?void 0:y.some(b=>{var j,C;return b.userId===p.userId||((j=b.email)==null?void 0:j.toLowerCase())===((C=p.email)==null?void 0:C.toLowerCase())});if(N){a({type:"error",email:p.email,message:"This user is already added as a spectator."});return}if(f){a({type:"error",email:p.email,message:"This user is already added as an approver. A user cannot be both an approver and a spectator."});return}try{const b=await m(p),j={id:b.userId,userId:b.userId,name:b.displayName||p.email.split("@")[0],email:b.email,avatar:(b.displayName||b.email).substring(0,2).toUpperCase(),role:"Spectator",department:b.department||"",level:1,canClose:!1},C=[...t.spectators,j];s("spectators",C),i(""),d()}catch{a({type:"error",email:p.email,message:"Failed to validate user. Please try again."})}}else if(n&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)){if(n.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:n,message:"You cannot add yourself as a spectator."});return}const N=t.spectators.some(b=>{var j;return((j=b.email)==null?void 0:j.toLowerCase())===n.toLowerCase()}),f=(v=t.approvers)==null?void 0:v.some(b=>{var j;return((j=b.email)==null?void 0:j.toLowerCase())===n.toLowerCase()});if(N){a({type:"error",email:n,message:"This user is already added as a spectator."});return}if(f){a({type:"error",email:n,message:"This user is already added as an approver. A user cannot be both an approver and a spectator."});return}}},x=p=>{const y=t.spectators.filter(v=>v.id!==p);s("spectators",y)};return e.jsxs(St.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"space-y-6","data-testid":"participants-step",children:[e.jsxs("div",{className:"text-center mb-8","data-testid":"participants-header",children:[e.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-teal-500 to-green-600 rounded-2xl flex items-center justify-center mx-auto mb-4",children:e.jsx(At,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"participants-title",children:"Participants & Access"}),e.jsx("p",{className:"text-gray-600","data-testid":"participants-description",children:"Configure additional participants and visibility settings for your request."})]}),e.jsx("div",{className:"max-w-3xl mx-auto space-y-8","data-testid":"participants-content",children:e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:e.jsxs(G,{"data-testid":"participants-spectators-card",children:[e.jsxs(te,{children:[e.jsxs(se,{className:"flex items-center justify-between text-base","data-testid":"participants-spectators-title",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(At,{className:"w-4 h-4"}),"Spectators"]}),e.jsx(Q,{variant:"outline",className:"text-xs","data-testid":"participants-spectators-count",children:t.spectators.length})]}),e.jsx(he,{children:"Users who can view and comment but cannot approve"})]}),e.jsxs(Y,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2","data-testid":"participants-spectators-add-section",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative w-full",children:[e.jsx(xe,{placeholder:"Use @ sign to add a user",value:n,onChange:p=>u(p.target.value),onKeyPress:async p=>{p.key==="Enter"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)&&(p.preventDefault(),await h())},className:"text-sm w-full","data-testid":"participants-spectators-email-input"}),(l||o.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg",children:l?e.jsx("div",{className:"p-2 text-xs text-gray-500",children:"Searching..."}):e.jsx("ul",{className:"max-h-56 overflow-auto divide-y",children:o.map(p=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>h(p),"data-testid":`participants-spectators-search-result-${p.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:p.displayName||p.email}),e.jsx("div",{className:"text-xs text-gray-600",children:p.email})]},p.userId))})})]}),e.jsx(M,{size:"sm",onClick:()=>h(),disabled:!n||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n),"data-testid":"participants-spectators-add-button",children:"Add"})]}),e.jsxs("p",{className:"text-xs text-blue-600 bg-blue-50 border border-blue-200 rounded p-2 flex items-center gap-1",children:[e.jsx(Fr,{className:"w-3 h-3 flex-shrink-0"}),e.jsxs("span",{children:["Use ",e.jsx("span",{className:"font-mono bg-blue-100 px-1 rounded",children:"@"})," sign to search users, or type email directly (will be validated against organization directory)"]})]})]}),e.jsx("div",{className:"space-y-2 max-h-40 overflow-y-auto","data-testid":"participants-spectators-list",children:t.spectators.map(p=>e.jsxs("div",{className:"flex items-center justify-between p-2 bg-teal-50 rounded-lg","data-testid":`participants-spectator-${p.id}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jt,{className:"h-6 w-6",children:e.jsx(Nt,{className:"bg-teal-600 text-white text-xs",children:p.avatar})}),e.jsx("span",{className:"text-sm font-medium",children:p.name})]}),e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>x(p.id),"data-testid":`participants-spectator-${p.id}-remove`,children:e.jsx(ft,{className:"h-3 w-3"})})]},p.id))})]})]})})})]})}function Gw({documentPolicy:t,isEditing:s,documents:a,existingDocuments:r,documentsToDelete:n,onDocumentsChange:i,onExistingDocumentsChange:o,onDocumentsToDeleteChange:l,onPreviewDocument:c,onDocumentErrors:d,fileInputRef:m}){const u=y=>{const v=Array.from(y.target.files||[]);if(v.length===0)return;const N=t.maxFileSizeMB*1024*1024,f=[],b=[];v.forEach(j=>{if(j.size>N){f.push({fileName:j.name,reason:`File size exceeds the maximum allowed size of ${t.maxFileSizeMB}MB. Current size: ${(j.size/1048576).toFixed(2)}MB`});return}const C=j.name.toLowerCase(),R=C.substring(C.lastIndexOf(".")+1);if(!t.allowedFileTypes.includes(R)){f.push({fileName:j.name,reason:`File type "${R}" is not allowed. Allowed types: ${t.allowedFileTypes.join(", ")}`});return}b.push(j)}),b.length>0&&i([...a,...b]),f.length>0&&d&&d(f),y.target&&(y.target.value="")},h=y=>{const v=a.filter((N,f)=>f!==y);i(v)},x=y=>{l([...n,y])},p=(y,v=!1)=>{if(v){const N=(y.fileType||y.file_type||"").toLowerCase(),f=(y.originalFileName||y.fileName||"").toLowerCase();return N.includes("image")||N.includes("pdf")||f.endsWith(".jpg")||f.endsWith(".jpeg")||f.endsWith(".png")||f.endsWith(".gif")||f.endsWith(".pdf")}else{const N=(y.type||"").toLowerCase(),f=(y.name||"").toLowerCase();return N.includes("image")||N.includes("pdf")||f.endsWith(".jpg")||f.endsWith(".jpeg")||f.endsWith(".png")||f.endsWith(".gif")||f.endsWith(".pdf")}};return e.jsxs(St.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"space-y-6","data-testid":"documents-step",children:[e.jsxs("div",{className:"text-center mb-8","data-testid":"documents-header",children:[e.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-indigo-500 to-purple-600 rounded-2xl flex items-center justify-center mx-auto mb-4",children:e.jsx(ba,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"documents-title",children:"Documents & Attachments"}),e.jsx("p",{className:"text-gray-600","data-testid":"documents-description",children:"Upload supporting documents, files, and any additional materials for your request."})]}),e.jsxs("div",{className:"max-w-2xl mx-auto space-y-6","data-testid":"documents-content",children:[e.jsxs(G,{"data-testid":"documents-upload-card",children:[e.jsxs(te,{children:[e.jsxs(se,{className:"flex items-center gap-2","data-testid":"documents-upload-title",children:[e.jsx(Te,{className:"w-5 h-5"}),"File Upload"]}),e.jsxs(he,{children:["Attach supporting documents. Max ",t.maxFileSizeMB,"MB per file. Allowed types: ",t.allowedFileTypes.join(", ")]})]}),e.jsx(Y,{children:e.jsxs("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-gray-400 transition-colors","data-testid":"documents-upload-area",children:[e.jsx(ba,{className:"h-12 w-12 mx-auto mb-4 text-gray-400"}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Upload Files"}),e.jsx("p",{className:"text-gray-600 mb-4",children:"Drag and drop files here, or click to browse"}),e.jsx("input",{type:"file",multiple:!0,accept:t.allowedFileTypes.map(y=>`.${y}`).join(","),onChange:u,className:"hidden",id:"file-upload",ref:m,"data-testid":"documents-file-input"}),e.jsxs(M,{variant:"outline",size:"lg",type:"button",onClick:()=>{var y;return(y=m.current)==null?void 0:y.click()},"data-testid":"documents-browse-button",children:[e.jsx(Is,{className:"w-4 h-4 mr-2"}),"Browse Files"]}),e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Supported formats: ",t.allowedFileTypes.map(y=>y.toUpperCase()).join(", ")," (Max ",t.maxFileSizeMB,"MB per file)"]})]})})]}),s&&r.length>0&&e.jsxs(G,{"data-testid":"documents-existing-card",children:[e.jsx(te,{children:e.jsxs(se,{className:"flex items-center justify-between","data-testid":"documents-existing-title",children:[e.jsx("span",{children:"Existing Documents"}),e.jsxs(Q,{variant:"secondary","data-testid":"documents-existing-count",children:[r.filter(y=>!n.includes(y.documentId||y.document_id||"")).length," file",r.filter(y=>!n.includes(y.documentId||y.document_id||"")).length!==1?"s":""]})]})}),e.jsx(Y,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-existing-list",children:r.map(y=>{const v=y.documentId||y.document_id||"";return n.includes(v)?null:e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border bg-gray-50","data-testid":`documents-existing-${v}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center",children:e.jsx(Te,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:y.originalFileName||y.fileName||"Document"}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsx("span",{children:y.fileSize?(Number(y.fileSize)/(1024*1024)).toFixed(2)+" MB":"Unknown size"})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[p(y,!0)&&e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>c(y,!0),"data-testid":`documents-existing-${v}-preview`,children:e.jsx(At,{className:"h-4 w-4"})}),e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>x(v),"data-testid":`documents-existing-${v}-delete`,children:e.jsx(ft,{className:"h-4 w-4 text-red-600"})})]})]},v)})})})]}),a.length>0&&e.jsxs(G,{"data-testid":"documents-new-card",children:[e.jsx(te,{children:e.jsxs(se,{className:"flex items-center justify-between","data-testid":"documents-new-title",children:[e.jsx("span",{children:"New Files to Upload"}),e.jsxs(Q,{variant:"secondary","data-testid":"documents-new-count",children:[a.length," file",a.length!==1?"s":""]})]})}),e.jsx(Y,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-new-list",children:a.map((y,v)=>e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-lg border","data-testid":`documents-new-${v}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center",children:e.jsx(Te,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:y.name}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsxs("span",{children:[(y.size/(1024*1024)).toFixed(2)," MB"]})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[p(y,!1)&&e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>c(y,!1),"data-testid":`documents-new-${v}-preview`,children:e.jsx(At,{className:"h-4 w-4"})}),e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>h(v),"data-testid":`documents-new-${v}-remove`,children:e.jsx(ft,{className:"h-4 w-4"})})]})]},v))})})]})]})]})}const Yw=t=>{switch(t){case"high":return e.jsx(ls,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(it,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(Us,{className:"w-4 h-4 text-green-600"});default:return e.jsx(it,{className:"w-4 h-4 text-gray-600"})}};function Zw({formData:t,selectedTemplate:s}){return e.jsxs(St.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"space-y-6","data-testid":"review-submit-step",children:[e.jsxs("div",{className:"text-center mb-8","data-testid":"review-submit-header",children:[e.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-green-500 to-teal-600 rounded-2xl flex items-center justify-center mx-auto mb-4",children:e.jsx(ve,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"review-submit-title",children:"Review & Submit"}),e.jsx("p",{className:"text-gray-600","data-testid":"review-submit-description",children:"Please review all details before submitting your request for approval."})]}),e.jsxs("div",{className:"max-w-5xl mx-auto space-y-8","data-testid":"review-submit-content",children:[e.jsxs(G,{className:"border-2 border-green-200 bg-green-50/50","data-testid":"review-submit-overview-card",children:[e.jsx(te,{children:e.jsxs(se,{className:"flex items-center gap-2 text-green-900","data-testid":"review-submit-overview-title",children:[e.jsx(vd,{className:"w-5 h-5"}),"Request Overview"]})}),e.jsxs(Y,{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6","data-testid":"review-submit-overview-grid",children:[e.jsxs("div",{"data-testid":"review-submit-overview-type",children:[e.jsx(X,{className:"text-green-900 font-semibold",children:"Request Type"}),e.jsx("p",{className:"text-green-800 mt-1",children:s==null?void 0:s.name}),e.jsx(Q,{variant:"outline",className:"mt-2 text-xs border-green-300 text-green-700",children:s==null?void 0:s.category})]}),e.jsxs("div",{"data-testid":"review-submit-overview-priority",children:[e.jsx(X,{className:"text-green-900 font-semibold",children:"Priority"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[Yw(t.priority),e.jsx("span",{className:"text-green-800 capitalize",children:t.priority})]})]}),e.jsxs("div",{"data-testid":"review-submit-overview-workflow",children:[e.jsx(X,{className:"text-green-900 font-semibold",children:"Workflow Type"}),e.jsx("p",{className:"text-green-800 mt-1 capitalize",children:t.workflowType}),e.jsxs("p",{className:"text-sm text-green-700",children:[t.approverCount||1," Level",(t.approverCount||1)>1?"s":""]})]})]}),e.jsxs("div",{"data-testid":"review-submit-overview-title",children:[e.jsx(X,{className:"text-green-900 font-semibold",children:"Request Title"}),e.jsx("p",{className:"text-green-800 font-medium mt-1 text-lg",children:t.title})]})]})]}),e.jsxs(G,{"data-testid":"review-submit-basic-info-card",children:[e.jsx(te,{children:e.jsxs(se,{className:"flex items-center gap-2","data-testid":"review-submit-basic-info-title",children:[e.jsx(Te,{className:"w-5 h-5"}),"Basic Information"]})}),e.jsxs(Y,{className:"space-y-4",children:[e.jsxs("div",{"data-testid":"review-submit-basic-info-description",children:[e.jsx(X,{className:"font-semibold",children:"Description"}),e.jsx("div",{className:"mt-1 p-3 bg-gray-50 rounded-lg border",children:e.jsx(Ms,{content:t.description||""})})]}),t.amount&&e.jsxs("div",{className:"p-3 bg-blue-50 rounded-lg border border-blue-200","data-testid":"review-submit-basic-info-financial",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Tx,{className:"w-4 h-4 text-blue-600"}),e.jsx(X,{className:"font-semibold text-blue-900",children:"Financial Details"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-blue-700",children:"Amount"}),e.jsxs("p",{className:"font-semibold text-blue-900",children:[t.amount," ",t.currency]})]}),t.costCenter&&e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-blue-700",children:"Cost Center"}),e.jsx("p",{className:"font-medium text-blue-900",children:t.costCenter})]})]})]})]})]}),e.jsxs(G,{className:"border-2 border-orange-200 bg-orange-50/50","data-testid":"review-submit-approval-card",children:[e.jsxs(te,{children:[e.jsxs(se,{className:"flex items-center gap-2 text-orange-900","data-testid":"review-submit-approval-title",children:[e.jsx(at,{className:"w-5 h-5"}),"Approval Workflow"]}),e.jsx(he,{className:"text-orange-700",children:"Sequential approval hierarchy with TAT (Turn Around Time) for each level"})]}),e.jsx(Y,{className:"space-y-6",children:e.jsx("div",{className:"space-y-4","data-testid":"review-submit-approval-levels",children:Array.from({length:t.approverCount||1},(a,r)=>{const n=r+1,i=n===(t.approverCount||1),o=t.approvers[r];return e.jsx("div",{className:"p-4 bg-white rounded-lg border border-orange-200","data-testid":`review-submit-approval-level-${n}`,children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0 ${o!=null&&o.email?"bg-green-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold",children:n})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsxs("span",{className:"font-semibold text-gray-900",children:["Approver Level ",n]}),i&&e.jsx(Q,{variant:"destructive",className:"text-xs",children:"FINAL APPROVER"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Email Address"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:(o==null?void 0:o.email)||"Not assigned"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-gray-600",children:"TAT (Turn Around Time)"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:o!=null&&o.tat?`${o.tat} ${o.tatType==="days"?"day":"hour"}${o.tat!==1?"s":""}`:"Not set"})]})]})]})]})},n)})})})]}),e.jsxs(G,{"data-testid":"review-submit-participants-card",children:[e.jsx(te,{children:e.jsxs(se,{className:"flex items-center gap-2","data-testid":"review-submit-participants-title",children:[e.jsx(At,{className:"w-5 h-5"}),"Participants & Access Control"]})}),e.jsx(Y,{className:"space-y-4",children:t.spectators.length>0&&e.jsxs("div",{"data-testid":"review-submit-participants-spectators",children:[e.jsxs(X,{className:"font-semibold text-sm",children:["Spectators (",t.spectators.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:t.spectators.map(a=>e.jsxs(Q,{variant:"outline",className:"text-xs","data-testid":`review-submit-spectator-${a.id}`,children:[a.name," (",a.email,")"]},a.id))})]})})]}),t.documents.length>0&&e.jsxs(G,{"data-testid":"review-submit-documents-card",children:[e.jsxs(te,{children:[e.jsxs(se,{className:"flex items-center gap-2","data-testid":"review-submit-documents-title",children:[e.jsx(ba,{className:"w-5 h-5"}),"Documents & Attachments"]}),e.jsxs(he,{children:[t.documents.length," document",t.documents.length!==1?"s":""," attached to this request"]})]}),e.jsx(Y,{children:e.jsx("div",{className:"space-y-3","data-testid":"review-submit-documents-list",children:t.documents.map((a,r)=>e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-gray-50 rounded-lg border","data-testid":`review-submit-document-${r}`,children:[e.jsx(Te,{className:"w-5 h-5 text-gray-500 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:a.name}),e.jsx("div",{className:"flex items-center gap-3 text-xs text-gray-500 mt-1",children:e.jsxs("span",{children:[(a.size/(1024*1024)).toFixed(2)," MB"]})})]})]},r))})})]}),e.jsx(G,{className:"border-2 border-blue-200 bg-blue-50/50","data-testid":"review-submit-confirmation-card",children:e.jsx(Y,{className:"pt-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(ve,{className:"w-6 h-6 text-blue-600 mt-1 flex-shrink-0"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-blue-900 mb-2","data-testid":"review-submit-confirmation-title",children:"Ready to Submit Request"}),e.jsx("p",{className:"text-sm text-blue-700 mb-4","data-testid":"review-submit-confirmation-message",children:"Once submitted, your request will enter the approval workflow and notifications will be sent to all relevant participants."}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 text-sm","data-testid":"review-submit-confirmation-summary",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-blue-700",children:"Request Type:"}),e.jsx("p",{className:"font-medium text-blue-900",children:s==null?void 0:s.name})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-blue-700",children:"Approval Levels:"}),e.jsx("p",{className:"font-medium text-blue-900",children:t.approverCount||1})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-blue-700",children:"Documents:"}),e.jsxs("p",{className:"font-medium text-blue-900",children:[t.documents.length," attached"]})]})]})]})]})})})]})]})}function Xw({isEditing:t,currentStep:s,totalSteps:a,stepNames:r,onBack:n}){return e.jsx("div",{className:"bg-white border-b border-gray-200 px-3 sm:px-6 py-3 sm:py-4 flex-shrink-0","data-testid":"create-request-header",children:e.jsxs("div",{className:"flex items-center justify-between max-w-6xl mx-auto gap-2 sm:gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-4 flex-1 min-w-0",children:[e.jsx(M,{variant:"ghost",size:"icon",onClick:n,className:"shrink-0 h-8 w-8 sm:h-10 sm:w-10","data-testid":"create-request-back-button",children:e.jsx(_s,{className:"h-4 w-4 sm:h-5 sm:w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-base sm:text-xl md:text-2xl font-bold text-gray-900 truncate","data-testid":"create-request-title",children:t?"Edit Draft":"New Request"}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-600 hidden sm:block","data-testid":"create-request-step-info",children:["Step ",s," of ",a,": ",r[s-1]]})]})]}),e.jsx("div",{className:"hidden md:flex items-center gap-4","data-testid":"create-request-progress-info",children:e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-sm font-medium text-gray-900",children:[Math.round(s/a*100),"% Complete"]}),e.jsxs("p",{className:"text-xs text-gray-600",children:[a-s," steps remaining"]})]})})]})})}function Qw({children:t}){return e.jsx("div",{className:"flex-1 overflow-y-auto pb-24 sm:pb-4","data-testid":"create-request-content",children:e.jsx("div",{className:"max-w-6xl mx-auto p-3 sm:p-6 pb-6 sm:pb-6",children:e.jsx(Xr,{mode:"wait",children:t})})})}function Jw({modal:t,onClose:s}){return e.jsx(ot,{open:t.open,onOpenChange:a=>!a&&s(),"data-testid":"create-request-validation-modal",children:e.jsxs(Je,{className:"sm:max-w-md",children:[e.jsxs(lt,{children:[e.jsxs(et,{className:"flex items-center gap-2","data-testid":"validation-modal-title",children:[t.type==="self-assign"&&e.jsxs(e.Fragment,{children:[e.jsx(Re,{className:"w-5 h-5 text-amber-600"}),"Cannot Add Yourself"]}),t.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsx(Re,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}),t.type==="error"&&e.jsxs(e.Fragment,{children:[e.jsx(Re,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})]}),e.jsx(Zt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[t.type==="self-assign"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["You cannot add yourself (",e.jsx("strong",{children:t.email}),") as an approver."]}),e.jsx("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-amber-800",children:[e.jsx("strong",{children:"Why?"})," The initiator creates the request and cannot approve their own request. Please select a different user."]})})]}),t.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:t.email})," was not found in the organization directory."]}),e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3 space-y-2",children:[e.jsx("p",{className:"text-sm text-red-800 font-semibold",children:"Please verify:"}),e.jsxs("ul",{className:"text-sm text-red-700 space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"Email address is spelled correctly"}),e.jsx("li",{children:"User exists in Okta/SSO system"}),e.jsx("li",{children:"User has an active account"})]})]}),e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-blue-800 flex items-center gap-1",children:[e.jsx(Ur,{className:"w-4 h-4"}),e.jsx("strong",{children:"Tip:"})," Use"," ",e.jsx("span",{className:"font-mono bg-blue-100 px-1 rounded",children:"@"})," ","sign to search and select users from the directory for guaranteed results."]})})]}),t.type==="error"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:[t.email&&e.jsxs(e.Fragment,{children:["Failed to validate ",e.jsx("strong",{children:t.email}),"."]}),!t.email&&e.jsx(e.Fragment,{children:"An error occurred during validation."})]}),t.message&&e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-3",children:e.jsx("p",{className:"text-sm text-gray-700",children:t.message})})]})]})})]}),e.jsx(Tt,{children:e.jsx(M,{onClick:s,className:"w-full sm:w-auto","data-testid":"validation-modal-ok-button",children:t.type==="not-found"?"Fix Email":"OK"})})]})})}function e1({modal:t,documentPolicy:s,onClose:a}){return e.jsx(ot,{open:t.open,onOpenChange:r=>!r&&a(),"data-testid":"create-request-document-error-modal",children:e.jsxs(Je,{className:"sm:max-w-lg",children:[e.jsxs(lt,{children:[e.jsxs(et,{className:"flex items-center gap-2","data-testid":"document-error-modal-title",children:[e.jsx(Re,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Zt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-gray-700",children:"The following file(s) could not be uploaded due to policy violations:"}),e.jsx("div",{className:"space-y-2 max-h-60 overflow-y-auto",children:t.errors.map((r,n)=>e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3","data-testid":`document-error-${n}`,children:[e.jsx("p",{className:"font-medium text-red-900 text-sm",children:r.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:r.reason})]},n))}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-sm text-blue-800 font-semibold mb-1",children:"Document Policy:"}),e.jsxs("ul",{className:"text-xs text-blue-700 space-y-1 list-disc list-inside",children:[e.jsxs("li",{children:["Maximum file size: ",s.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types:"," ",s.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(Tt,{children:e.jsx(M,{onClick:a,className:"w-full sm:w-auto","data-testid":"document-error-modal-ok-button",children:"OK"})})]})})}function Ic({onBack:t,onSubmit:s,requestId:a,isEditMode:r=!1}){const n=Ja(),i=Bs(),o=n.requestId||a||"",l=r&&!!o,{user:c}=Bt(),{formData:d,updateFormData:m,selectedTemplate:u,setSelectedTemplate:h,loadingDraft:x,systemPolicy:p,documentPolicy:y,existingDocuments:v,setExistingDocuments:N}=Nw(l,o,Pc),{currentStep:f,totalSteps:b,stepNames:j,isStepValid:C,nextStep:R,prevStep:I}=ww(l,u,d),[T,E]=g.useState([]),[w,S]=g.useState([]),D=g.useRef(null),{validationModal:H,policyViolationModal:L,documentErrorModal:F,openValidationModal:A,closeValidationModal:k,closePolicyViolationModal:P,openDocumentErrorModal:_,closeDocumentErrorModal:W}=Cw(),{submitting:Z,savingDraft:ae,handleSubmit:$,handleSaveDraft:ne}=_w({formData:d,selectedTemplate:u,documents:T,documentsToDelete:w,user:c,isEditing:l,editRequestId:o,onSubmit:s}),{showTemplateModal:me,setShowTemplateModal:q,previewDocument:z,selectTemplate:re,handleTemplateSelection:K,nextStep:B,prevStep:J,handlePreviewDocument:ue,closePreview:be}=Ow({selectedTemplate:u,setSelectedTemplate:h,updateFormData:m,formData:d,currentStep:f,isStepValid:C,wizardNextStep:R,wizardPrevStep:I,user:c,openValidationModal:A,onSubmit:s}),Ie=g.useCallback(()=>{f===1||f===3||f===4?t?t():window.history.length>1?window.history.back():i("/dashboard",{replace:!0}):J()},[f,t,i,J]),Ve=g.useRef(!0),Oe=g.useRef(!1);g.useEffect(()=>{Ve.current&&d.documents&&d.documents.length>0&&!Oe.current&&(E(d.documents),Oe.current=!0),Ve.current=!1},[d.documents]);const Ue=g.useRef(!1),$e=g.useRef(T);g.useEffect(()=>{if(Ue.current){Ue.current=!1,$e.current=T;return}$e.current!==T&&(m("documents",T),$e.current=T)},[T]);const Dt=()=>{switch(f){case 1:return e.jsx(Vw,{templates:Pc,selectedTemplate:u,onSelectTemplate:re});case 2:return e.jsx(zw,{formData:d,selectedTemplate:u,updateFormData:m});case 3:return e.jsx(Ww,{formData:d,updateFormData:m,onValidationError:Fe=>A(Fe.type,Fe.email,Fe.message)});case 4:return e.jsx(Kw,{formData:d,updateFormData:m,onValidationError:Fe=>A(Fe.type,Fe.email,Fe.message),initiatorEmail:(c==null?void 0:c.email)||""});case 5:return e.jsx(Gw,{documentPolicy:y,isEditing:l,documents:T,existingDocuments:v,documentsToDelete:w,onDocumentsChange:E,onExistingDocumentsChange:N,onDocumentsToDeleteChange:S,onPreviewDocument:ue,onDocumentErrors:Fe=>_(Fe),fileInputRef:D});case 6:return e.jsx(Zw,{formData:d,selectedTemplate:u});default:return null}};return x?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center","data-testid":"create-request-loading",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading draft..."})]})}):e.jsxs("div",{className:"h-full flex flex-col bg-gradient-to-br from-gray-50 to-white","data-testid":"create-request",children:[e.jsx(Xw,{isEditing:l,currentStep:f,totalSteps:b,stepNames:j,onBack:Ie}),e.jsx($w,{currentStep:f,totalSteps:b,stepNames:j}),e.jsx(Qw,{children:Dt()}),e.jsx(Uw,{currentStep:f,totalSteps:b,isStepValid:C(),onPrev:J,onNext:B,onSubmit:$,onSaveDraft:ne,submitting:Z,savingDraft:ae,loadingDraft:x,isEditing:l}),e.jsx(bw,{open:me,onClose:()=>q(!1),onSelectTemplate:K}),z&&e.jsx(qi,{fileName:z.fileName,fileType:z.fileType,fileUrl:z.fileUrl,fileSize:z.fileSize,open:!!z,onClose:be,onDownload:async()=>{if(z.file){const Fe=document.createElement("a");Fe.href=z.fileUrl,Fe.download=z.fileName,document.body.appendChild(Fe),Fe.click(),document.body.removeChild(Fe)}else z.documentId&&await Tr(z.documentId)},attachmentId:z.documentId}),e.jsx(Jw,{modal:H,onClose:k}),e.jsx(e1,{modal:F,documentPolicy:y,onClose:W}),e.jsx(pm,{open:L.open,onClose:P,violations:L.violations,policyDetails:{maxApprovalLevels:p.maxApprovalLevels,maxParticipants:p.maxParticipants,allowSpectators:p.allowSpectators,maxSpectators:p.maxSpectators}})]})}var Ne=function(){return Ne=Object.assign||function(s){for(var a,r=1,n=arguments.length;r1&&(c||!d),u=s>1&&(d||!c),h=function(){r&&i(r)},x=function(){n&&i(n)};return e.jsx(M1,{displayMonth:t.displayMonth,hideNext:m,hidePrevious:u,nextMonth:n,previousMonth:r,onPreviousClick:h,onNextClick:x})}function I1(t){var s,a=Ke(),r=a.classNames,n=a.disableNavigation,i=a.styles,o=a.captionLayout,l=a.components,c=(s=l==null?void 0:l.CaptionLabel)!==null&&s!==void 0?s:sh,d;return n?d=e.jsx(c,{id:t.id,displayMonth:t.displayMonth}):o==="dropdown"?d=e.jsx(_c,{displayMonth:t.displayMonth,id:t.id}):o==="dropdown-buttons"?d=e.jsxs(e.Fragment,{children:[e.jsx(_c,{displayMonth:t.displayMonth,displayIndex:t.displayIndex,id:t.id}),e.jsx(Lc,{displayMonth:t.displayMonth,displayIndex:t.displayIndex,id:t.id})]}):d=e.jsxs(e.Fragment,{children:[e.jsx(c,{id:t.id,displayMonth:t.displayMonth,displayIndex:t.displayIndex}),e.jsx(Lc,{displayMonth:t.displayMonth,id:t.id})]}),e.jsx("div",{className:r.caption,style:i.caption,children:d})}function _1(t){var s=Ke(),a=s.footer,r=s.styles,n=s.classNames.tfoot;return a?e.jsx("tfoot",{className:n,style:r.tfoot,children:e.jsx("tr",{children:e.jsx("td",{colSpan:8,children:a})})}):e.jsx(e.Fragment,{})}function L1(t,s,a){for(var r=a?Ai(new Date):Ti(new Date,{locale:t,weekStartsOn:s}),n=[],i=0;i<7;i++){var o=Ht(r,i);n.push(o)}return n}function F1(){var t=Ke(),s=t.classNames,a=t.styles,r=t.showWeekNumber,n=t.locale,i=t.weekStartsOn,o=t.ISOWeek,l=t.formatters.formatWeekdayName,c=t.labels.labelWeekday,d=L1(n,i,o);return e.jsxs("tr",{style:a.head_row,className:s.head_row,children:[r&&e.jsx("td",{style:a.head_cell,className:s.head_cell}),d.map(function(m,u){return e.jsx("th",{scope:"col",className:s.head_cell,style:a.head_cell,"aria-label":c(m,{locale:n}),children:l(m,{locale:n})},u)})]})}function O1(){var t,s=Ke(),a=s.classNames,r=s.styles,n=s.components,i=(t=n==null?void 0:n.HeadRow)!==null&&t!==void 0?t:F1;return e.jsx("thead",{style:r.head,className:a.head,children:e.jsx(i,{})})}function $1(t){var s=Ke(),a=s.locale,r=s.formatters.formatDay;return e.jsx(e.Fragment,{children:r(t.date,{locale:a})})}var To=g.createContext(void 0);function U1(t){if(!nr(t.initialProps)){var s={selected:void 0,modifiers:{disabled:[]}};return e.jsx(To.Provider,{value:s,children:t.children})}return e.jsx(V1,{initialProps:t.initialProps,children:t.children})}function V1(t){var s=t.initialProps,a=t.children,r=s.selected,n=s.min,i=s.max,o=function(d,m,u){var h,x;(h=s.onDayClick)===null||h===void 0||h.call(s,d,m,u);var p=!!(m.selected&&n&&(r==null?void 0:r.length)===n);if(!p){var y=!!(!m.selected&&i&&(r==null?void 0:r.length)===i);if(!y){var v=r?eh([],r):[];if(m.selected){var N=v.findIndex(function(f){return $t(d,f)});v.splice(N,1)}else v.push(d);(x=s.onSelect)===null||x===void 0||x.call(s,v,d,m,u)}}},l={disabled:[]};r&&l.disabled.push(function(d){var m=i&&r.length>i-1,u=r.some(function(h){return $t(h,d)});return!!(m&&!u)});var c={selected:r,onDayClick:o,modifiers:l};return e.jsx(To.Provider,{value:c,children:a})}function ko(){var t=g.useContext(To);if(!t)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return t}function B1(t,s){var a=s||{},r=a.from,n=a.to;return r&&n?$t(n,t)&&$t(r,t)?void 0:$t(n,t)?{from:n,to:void 0}:$t(r,t)?void 0:zn(r,t)?{from:t,to:n}:{from:r,to:t}:n?zn(t,n)?{from:n,to:t}:{from:t,to:n}:r?nd(t,r)?{from:t,to:r}:{from:r,to:t}:{from:t,to:void 0}}var Ro=g.createContext(void 0);function z1(t){if(!ir(t.initialProps)){var s={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(Ro.Provider,{value:s,children:t.children})}return e.jsx(H1,{initialProps:t.initialProps,children:t.children})}function H1(t){var s=t.initialProps,a=t.children,r=s.selected,n=r||{},i=n.from,o=n.to,l=s.min,c=s.max,d=function(x,p,y){var v,N;(v=s.onDayClick)===null||v===void 0||v.call(s,x,p,y);var f=B1(x,r);(N=s.onSelect)===null||N===void 0||N.call(s,f,x,p,y)},m={range_start:[],range_end:[],range_middle:[],disabled:[]};if(i?(m.range_start=[i],o?(m.range_end=[o],$t(i,o)||(m.range_middle=[{after:i,before:o}])):m.range_end=[i]):o&&(m.range_start=[o],m.range_end=[o]),l&&(i&&!o&&m.disabled.push({after:nn(i,l-1),before:Ht(i,l-1)}),i&&o&&m.disabled.push({after:i,before:Ht(i,l-1)}),!i&&o&&m.disabled.push({after:nn(o,l-1),before:Ht(o,l-1)})),c){if(i&&!o&&(m.disabled.push({before:Ht(i,-c+1)}),m.disabled.push({after:Ht(i,c-1)})),i&&o){var u=vs(o,i)+1,h=c-u;m.disabled.push({before:nn(i,h)}),m.disabled.push({after:Ht(o,h)})}!i&&o&&(m.disabled.push({before:Ht(o,-c+1)}),m.disabled.push({after:Ht(o,c-1)}))}return e.jsx(Ro.Provider,{value:{selected:r,onDayClick:d,modifiers:m},children:a})}function Do(){var t=g.useContext(Ro);if(!t)throw new Error("useSelectRange must be used within a SelectRangeProvider");return t}function Cr(t){return Array.isArray(t)?eh([],t):t!==void 0?[t]:[]}function q1(t){var s={};return Object.entries(t).forEach(function(a){var r=a[0],n=a[1];s[r]=Cr(n)}),s}var os;(function(t){t.Outside="outside",t.Disabled="disabled",t.Selected="selected",t.Hidden="hidden",t.Today="today",t.RangeStart="range_start",t.RangeEnd="range_end",t.RangeMiddle="range_middle"})(os||(os={}));var W1=os.Selected,ys=os.Disabled,K1=os.Hidden,G1=os.Today,In=os.RangeEnd,_n=os.RangeMiddle,Ln=os.RangeStart,Y1=os.Outside;function Z1(t,s,a){var r,n=(r={},r[W1]=Cr(t.selected),r[ys]=Cr(t.disabled),r[K1]=Cr(t.hidden),r[G1]=[t.today],r[In]=[],r[_n]=[],r[Ln]=[],r[Y1]=[],r);return t.fromDate&&n[ys].push({before:t.fromDate}),t.toDate&&n[ys].push({after:t.toDate}),nr(t)?n[ys]=n[ys].concat(s.modifiers[ys]):ir(t)&&(n[ys]=n[ys].concat(a.modifiers[ys]),n[Ln]=a.modifiers[Ln],n[_n]=a.modifiers[_n],n[In]=a.modifiers[In]),n}var nh=g.createContext(void 0);function X1(t){var s=Ke(),a=ko(),r=Do(),n=Z1(s,a,r),i=q1(s.modifiers),o=Ne(Ne({},n),i);return e.jsx(nh.Provider,{value:o,children:t.children})}function ih(){var t=g.useContext(nh);if(!t)throw new Error("useModifiers must be used within a ModifiersProvider");return t}function Q1(t){return!!(t&&typeof t=="object"&&"before"in t&&"after"in t)}function J1(t){return!!(t&&typeof t=="object"&&"from"in t)}function eC(t){return!!(t&&typeof t=="object"&&"after"in t)}function tC(t){return!!(t&&typeof t=="object"&&"before"in t)}function sC(t){return!!(t&&typeof t=="object"&&"dayOfWeek"in t)}function aC(t,s){var a,r=s.from,n=s.to;if(r&&n){var i=vs(n,r)<0;i&&(a=[n,r],r=a[0],n=a[1]);var o=vs(t,r)>=0&&vs(n,t)>=0;return o}return n?$t(n,t):r?$t(r,t):!1}function rC(t){return ld(t)}function nC(t){return Array.isArray(t)&&t.every(ld)}function iC(t,s){return s.some(function(a){if(typeof a=="boolean")return a;if(rC(a))return $t(t,a);if(nC(a))return a.includes(t);if(J1(a))return aC(t,a);if(sC(a))return a.dayOfWeek.includes(t.getDay());if(Q1(a)){var r=vs(a.before,t),n=vs(a.after,t),i=r>0,o=n<0,l=zn(a.before,a.after);return l?o&&i:i||o}return eC(a)?vs(t,a.after)>0:tC(a)?vs(a.before,t)>0:typeof a=="function"?a(t):!1})}function Po(t,s,a){var r=Object.keys(s).reduce(function(i,o){var l=s[o];return iC(t,l)&&i.push(o),i},[]),n={};return r.forEach(function(i){return n[i]=!0}),a&&!Si(t,a)&&(n.outside=!0),n}function oC(t,s){for(var a=Kt(t[0]),r=Ci(t[t.length-1]),n,i,o=a;o<=r;){var l=Po(o,s),c=!l.disabled&&!l.hidden;if(!c){o=Ht(o,1);continue}if(l.selected)return o;l.today&&!i&&(i=o),n||(n=o),o=Ht(o,1)}return i||n}var lC=365;function oh(t,s){var a=s.moveBy,r=s.direction,n=s.context,i=s.modifiers,o=s.retry,l=o===void 0?{count:0,lastFocused:t}:o,c=n.weekStartsOn,d=n.fromDate,m=n.toDate,u=n.locale,h={day:Ht,week:Bn,month:us,year:Hp,startOfWeek:function(v){return n.ISOWeek?Ai(v):Ti(v,{locale:u,weekStartsOn:c})},endOfWeek:function(v){return n.ISOWeek?id(v):od(v,{locale:u,weekStartsOn:c})}},x=h[a](t,r==="after"?1:-1);r==="before"&&d?x=qp([d,x]):r==="after"&&m&&(x=Wp([m,x]));var p=!0;if(i){var y=Po(x,i);p=!y.disabled&&!y.hidden}return p?x:l.count>lC?l.lastFocused:oh(x,{moveBy:a,direction:r,context:n,modifiers:i,retry:Ne(Ne({},l),{count:l.count+1})})}var lh=g.createContext(void 0);function cC(t){var s=or(),a=ih(),r=g.useState(),n=r[0],i=r[1],o=g.useState(),l=o[0],c=o[1],d=oC(s.displayMonths,a),m=n??(l&&s.isDateDisplayed(l))?l:d,u=function(){c(n),i(void 0)},h=function(v){i(v)},x=Ke(),p=function(v,N){if(n){var f=oh(n,{moveBy:v,direction:N,context:x,modifiers:a});$t(n,f)||(s.goToDate(f,n),h(f))}},y={focusedDay:n,focusTarget:m,blur:u,focus:h,focusDayAfter:function(){return p("day","after")},focusDayBefore:function(){return p("day","before")},focusWeekAfter:function(){return p("week","after")},focusWeekBefore:function(){return p("week","before")},focusMonthBefore:function(){return p("month","before")},focusMonthAfter:function(){return p("month","after")},focusYearBefore:function(){return p("year","before")},focusYearAfter:function(){return p("year","after")},focusStartOfWeek:function(){return p("startOfWeek","before")},focusEndOfWeek:function(){return p("endOfWeek","after")}};return e.jsx(lh.Provider,{value:y,children:t.children})}function Eo(){var t=g.useContext(lh);if(!t)throw new Error("useFocusContext must be used within a FocusProvider");return t}function dC(t,s){var a=ih(),r=Po(t,a,s);return r}var Mo=g.createContext(void 0);function mC(t){if(!tn(t.initialProps)){var s={selected:void 0};return e.jsx(Mo.Provider,{value:s,children:t.children})}return e.jsx(uC,{initialProps:t.initialProps,children:t.children})}function uC(t){var s=t.initialProps,a=t.children,r=function(i,o,l){var c,d,m;if((c=s.onDayClick)===null||c===void 0||c.call(s,i,o,l),o.selected&&!s.required){(d=s.onSelect)===null||d===void 0||d.call(s,void 0,i,o,l);return}(m=s.onSelect)===null||m===void 0||m.call(s,i,i,o,l)},n={selected:s.selected,onDayClick:r};return e.jsx(Mo.Provider,{value:n,children:a})}function ch(){var t=g.useContext(Mo);if(!t)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return t}function hC(t,s){var a=Ke(),r=ch(),n=ko(),i=Do(),o=Eo(),l=o.focusDayAfter,c=o.focusDayBefore,d=o.focusWeekAfter,m=o.focusWeekBefore,u=o.blur,h=o.focus,x=o.focusMonthBefore,p=o.focusMonthAfter,y=o.focusYearBefore,v=o.focusYearAfter,N=o.focusStartOfWeek,f=o.focusEndOfWeek,b=function(k){var P,_,W,Z;tn(a)?(P=r.onDayClick)===null||P===void 0||P.call(r,t,s,k):nr(a)?(_=n.onDayClick)===null||_===void 0||_.call(n,t,s,k):ir(a)?(W=i.onDayClick)===null||W===void 0||W.call(i,t,s,k):(Z=a.onDayClick)===null||Z===void 0||Z.call(a,t,s,k)},j=function(k){var P;h(t),(P=a.onDayFocus)===null||P===void 0||P.call(a,t,s,k)},C=function(k){var P;u(),(P=a.onDayBlur)===null||P===void 0||P.call(a,t,s,k)},R=function(k){var P;(P=a.onDayMouseEnter)===null||P===void 0||P.call(a,t,s,k)},I=function(k){var P;(P=a.onDayMouseLeave)===null||P===void 0||P.call(a,t,s,k)},T=function(k){var P;(P=a.onDayPointerEnter)===null||P===void 0||P.call(a,t,s,k)},E=function(k){var P;(P=a.onDayPointerLeave)===null||P===void 0||P.call(a,t,s,k)},w=function(k){var P;(P=a.onDayTouchCancel)===null||P===void 0||P.call(a,t,s,k)},S=function(k){var P;(P=a.onDayTouchEnd)===null||P===void 0||P.call(a,t,s,k)},D=function(k){var P;(P=a.onDayTouchMove)===null||P===void 0||P.call(a,t,s,k)},H=function(k){var P;(P=a.onDayTouchStart)===null||P===void 0||P.call(a,t,s,k)},L=function(k){var P;(P=a.onDayKeyUp)===null||P===void 0||P.call(a,t,s,k)},F=function(k){var P;switch(k.key){case"ArrowLeft":k.preventDefault(),k.stopPropagation(),a.dir==="rtl"?l():c();break;case"ArrowRight":k.preventDefault(),k.stopPropagation(),a.dir==="rtl"?c():l();break;case"ArrowDown":k.preventDefault(),k.stopPropagation(),d();break;case"ArrowUp":k.preventDefault(),k.stopPropagation(),m();break;case"PageUp":k.preventDefault(),k.stopPropagation(),k.shiftKey?y():x();break;case"PageDown":k.preventDefault(),k.stopPropagation(),k.shiftKey?v():p();break;case"Home":k.preventDefault(),k.stopPropagation(),N();break;case"End":k.preventDefault(),k.stopPropagation(),f();break}(P=a.onDayKeyDown)===null||P===void 0||P.call(a,t,s,k)},A={onClick:b,onFocus:j,onBlur:C,onKeyDown:F,onKeyUp:L,onMouseEnter:R,onMouseLeave:I,onPointerEnter:T,onPointerLeave:E,onTouchCancel:w,onTouchEnd:S,onTouchMove:D,onTouchStart:H};return A}function pC(){var t=Ke(),s=ch(),a=ko(),r=Do(),n=tn(t)?s.selected:nr(t)?a.selected:ir(t)?r.selected:void 0;return n}function xC(t){return Object.values(os).includes(t)}function gC(t,s){var a=[t.classNames.day];return Object.keys(s).forEach(function(r){var n=t.modifiersClassNames[r];if(n)a.push(n);else if(xC(r)){var i=t.classNames["day_".concat(r)];i&&a.push(i)}}),a}function fC(t,s){var a=Ne({},t.styles.day);return Object.keys(s).forEach(function(r){var n;a=Ne(Ne({},a),(n=t.modifiersStyles)===null||n===void 0?void 0:n[r])}),a}function yC(t,s,a){var r,n,i,o=Ke(),l=Eo(),c=dC(t,s),d=hC(t,c),m=pC(),u=!!(o.onDayClick||o.mode!=="default");g.useEffect(function(){var R;c.outside||l.focusedDay&&u&&$t(l.focusedDay,t)&&((R=a.current)===null||R===void 0||R.focus())},[l.focusedDay,t,a,u,c.outside]);var h=gC(o,c).join(" "),x=fC(o,c),p=!!(c.outside&&!o.showOutsideDays||c.hidden),y=(i=(n=o.components)===null||n===void 0?void 0:n.DayContent)!==null&&i!==void 0?i:$1,v=e.jsx(y,{date:t,displayMonth:s,activeModifiers:c}),N={style:x,className:h,children:v,role:"gridcell"},f=l.focusTarget&&$t(l.focusTarget,t)&&!c.outside,b=l.focusedDay&&$t(l.focusedDay,t),j=Ne(Ne(Ne({},N),(r={disabled:c.disabled,role:"gridcell"},r["aria-selected"]=c.selected,r.tabIndex=b||f?0:-1,r)),d),C={isButton:u,isHidden:p,activeModifiers:c,selectedDays:m,buttonProps:j,divProps:N};return C}function vC(t){var s=g.useRef(null),a=yC(t.date,t.displayMonth,s);return a.isHidden?e.jsx("div",{role:"gridcell"}):a.isButton?e.jsx(Mr,Ne({name:"day",ref:s},a.buttonProps)):e.jsx("div",Ne({},a.divProps))}function bC(t){var s=t.number,a=t.dates,r=Ke(),n=r.onWeekNumberClick,i=r.styles,o=r.classNames,l=r.locale,c=r.labels.labelWeekNumber,d=r.formatters.formatWeekNumber,m=d(Number(s),{locale:l});if(!n)return e.jsx("span",{className:o.weeknumber,style:i.weeknumber,children:m});var u=c(Number(s),{locale:l}),h=function(x){n(s,a,x)};return e.jsx(Mr,{name:"week-number","aria-label":u,className:o.weeknumber,style:i.weeknumber,onClick:h,children:m})}function jC(t){var s,a,r=Ke(),n=r.styles,i=r.classNames,o=r.showWeekNumber,l=r.components,c=(s=l==null?void 0:l.Day)!==null&&s!==void 0?s:vC,d=(a=l==null?void 0:l.WeekNumber)!==null&&a!==void 0?a:bC,m;return o&&(m=e.jsx("td",{className:i.cell,style:n.cell,children:e.jsx(d,{number:t.weekNumber,dates:t.dates})})),e.jsxs("tr",{className:i.row,style:n.row,children:[m,t.dates.map(function(u){return e.jsx("td",{className:i.cell,style:n.cell,role:"presentation",children:e.jsx(c,{displayMonth:t.displayMonth,date:u})},zp(u))})]})}function Fc(t,s,a){for(var r=a!=null&&a.ISOWeek?id(s):od(s,a),n=a!=null&&a.ISOWeek?Ai(t):Ti(t,a),i=vs(r,n),o=[],l=0;l<=i;l++)o.push(Ht(n,l));var c=o.reduce(function(d,m){var u=a!=null&&a.ISOWeek?Yp(m):Zp(m,a),h=d.find(function(x){return x.weekNumber===u});return h?(h.dates.push(m),d):(d.push({weekNumber:u,dates:[m]}),d)},[]);return c}function NC(t,s){var a=Fc(Kt(t),Ci(t),s);if(s!=null&&s.useFixedWeeks){var r=Bp(t,s);if(r<6){var n=a[a.length-1],i=n.dates[n.dates.length-1],o=Bn(i,6-r),l=Fc(Bn(i,1),o,s);a.push.apply(a,l)}}return a}function wC(t){var s,a,r,n=Ke(),i=n.locale,o=n.classNames,l=n.styles,c=n.hideHead,d=n.fixedWeeks,m=n.components,u=n.weekStartsOn,h=n.firstWeekContainsDate,x=n.ISOWeek,p=NC(t.displayMonth,{useFixedWeeks:!!d,ISOWeek:x,locale:i,weekStartsOn:u,firstWeekContainsDate:h}),y=(s=m==null?void 0:m.Head)!==null&&s!==void 0?s:O1,v=(a=m==null?void 0:m.Row)!==null&&a!==void 0?a:jC,N=(r=m==null?void 0:m.Footer)!==null&&r!==void 0?r:_1;return e.jsxs("table",{id:t.id,className:o.table,style:l.table,role:"grid","aria-labelledby":t["aria-labelledby"],children:[!c&&e.jsx(y,{}),e.jsx("tbody",{className:o.tbody,style:l.tbody,children:p.map(function(f){return e.jsx(v,{displayMonth:t.displayMonth,dates:f.dates,weekNumber:f.weekNumber},f.weekNumber)})}),e.jsx(N,{displayMonth:t.displayMonth})]})}function CC(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var SC=CC()?g.useLayoutEffect:g.useEffect,Fn=!1,AC=0;function Oc(){return"react-day-picker-".concat(++AC)}function TC(t){var s,a=t??(Fn?Oc():null),r=g.useState(a),n=r[0],i=r[1];return SC(function(){n===null&&i(Oc())},[]),g.useEffect(function(){Fn===!1&&(Fn=!0)},[]),(s=t??n)!==null&&s!==void 0?s:void 0}function kC(t){var s,a,r=Ke(),n=r.dir,i=r.classNames,o=r.styles,l=r.components,c=or().displayMonths,d=TC(r.id?"".concat(r.id,"-").concat(t.displayIndex):void 0),m=r.id?"".concat(r.id,"-grid-").concat(t.displayIndex):void 0,u=[i.month],h=o.month,x=t.displayIndex===0,p=t.displayIndex===c.length-1,y=!x&&!p;n==="rtl"&&(s=[x,p],p=s[0],x=s[1]),x&&(u.push(i.caption_start),h=Ne(Ne({},h),o.caption_start)),p&&(u.push(i.caption_end),h=Ne(Ne({},h),o.caption_end)),y&&(u.push(i.caption_between),h=Ne(Ne({},h),o.caption_between));var v=(a=l==null?void 0:l.Caption)!==null&&a!==void 0?a:I1;return e.jsxs("div",{className:u.join(" "),style:h,children:[e.jsx(v,{id:d,displayMonth:t.displayMonth,displayIndex:t.displayIndex}),e.jsx(wC,{id:m,"aria-labelledby":d,displayMonth:t.displayMonth})]},t.displayIndex)}function RC(t){var s=Ke(),a=s.classNames,r=s.styles;return e.jsx("div",{className:a.months,style:r.months,children:t.children})}function DC(t){var s,a,r=t.initialProps,n=Ke(),i=Eo(),o=or(),l=g.useState(!1),c=l[0],d=l[1];g.useEffect(function(){n.initialFocus&&i.focusTarget&&(c||(i.focus(i.focusTarget),d(!0)))},[n.initialFocus,c,i.focus,i.focusTarget,i]);var m=[n.classNames.root,n.className];n.numberOfMonths>1&&m.push(n.classNames.multiple_months),n.showWeekNumber&&m.push(n.classNames.with_weeknumber);var u=Ne(Ne({},n.styles.root),n.style),h=Object.keys(r).filter(function(p){return p.startsWith("data-")}).reduce(function(p,y){var v;return Ne(Ne({},p),(v={},v[y]=r[y],v))},{}),x=(a=(s=r.components)===null||s===void 0?void 0:s.Months)!==null&&a!==void 0?a:RC;return e.jsx("div",Ne({className:m.join(" "),style:u,dir:n.dir,id:n.id,nonce:r.nonce,title:r.title,lang:r.lang},h,{children:e.jsx(x,{children:o.displayMonths.map(function(p,y){return e.jsx(kC,{displayIndex:y,displayMonth:p},y)})})}))}function PC(t){var s=t.children,a=t1(t,["children"]);return e.jsx(b1,{initialProps:a,children:e.jsx(D1,{children:e.jsx(mC,{initialProps:a,children:e.jsx(U1,{initialProps:a,children:e.jsx(z1,{initialProps:a,children:e.jsx(X1,{children:e.jsx(cC,{children:s})})})})})})})}function EC(t){return e.jsx(PC,Ne({},t,{children:e.jsx(DC,{initialProps:t})}))}function On({className:t,classNames:s,showOutsideDays:a=!0,...r}){return e.jsx(EC,{showOutsideDays:a,className:oe("p-3",t),classNames:{months:"flex flex-col sm:flex-row gap-2",month:"flex flex-col gap-4",caption:"flex justify-center pt-1 relative items-center w-full",caption_label:"text-sm font-medium",nav:"flex items-center gap-1",nav_button:oe(qa({variant:"outline"}),"size-7 bg-transparent p-0 opacity-50 hover:opacity-100"),nav_button_previous:"absolute left-1",nav_button_next:"absolute right-1",table:"w-full border-collapse space-x-1",head_row:"flex",head_cell:"text-muted-foreground rounded-md w-8 font-normal text-[0.8rem]",row:"flex w-full mt-2",cell:oe("relative p-0 text-center text-sm focus-within:relative focus-within:z-20 [&:has([aria-selected])]:bg-accent [&:has([aria-selected].day-range-end)]:rounded-r-md",r.mode==="range"?"[&:has(>.day-range-end)]:rounded-r-md [&:has(>.day-range-start)]:rounded-l-md first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md":"[&:has([aria-selected])]:rounded-md"),day:oe(qa({variant:"ghost"}),"size-8 p-0 font-normal aria-selected:opacity-100"),day_range_start:"day-range-start aria-selected:bg-primary aria-selected:text-primary-foreground",day_range_end:"day-range-end aria-selected:bg-primary aria-selected:text-primary-foreground",day_selected:"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",day_today:"bg-accent text-accent-foreground",day_outside:"day-outside text-muted-foreground aria-selected:text-muted-foreground",day_disabled:"text-muted-foreground opacity-50",day_range_middle:"aria-selected:bg-accent aria-selected:text-accent-foreground",day_hidden:"invisible",...s},components:{IconLeft:({className:n,...i})=>e.jsx(bd,{className:oe("size-4",n),...i}),IconRight:({className:n,...i})=>e.jsx(Di,{className:oe("size-4",n),...i})},...r})}const dh={"RE-MH-001":{code:"RE-MH-001",name:"Royal Motors Mumbai",email:"dealer@royalmotorsmumbai.com",phone:"+91 98765 12345",address:"Shop No. 12-15, Central Avenue, Andheri West",city:"Mumbai",state:"Maharashtra",region:"West",managerName:"Rahul Deshmukh"},"RE-DL-002":{code:"RE-DL-002",name:"Delhi Enfield Center",email:"contact@delhienfield.com",phone:"+91 98765 23456",address:"45-48, Rajouri Garden, Main Market",city:"New Delhi",state:"Delhi",region:"North",managerName:"Vikram Singh"},"RE-BLR-003":{code:"RE-BLR-003",name:"Bangalore Royal Bikes",email:"info@bangaloreroyalbikes.com",phone:"+91 98765 34567",address:"123, MG Road, Near Trinity Metro",city:"Bangalore",state:"Karnataka",region:"South",managerName:"Suresh Kumar"},"RE-CHN-004":{code:"RE-CHN-004",name:"Chennai Enfield Hub",email:"chennai@enfieldhub.com",phone:"+91 98765 45678",address:"78-80, Anna Salai, T Nagar",city:"Chennai",state:"Tamil Nadu",region:"South",managerName:"Venkat Ramanan"},"RE-HYD-005":{code:"RE-HYD-005",name:"Hyderabad Royal Motorcycles",email:"hyderabad@royalmotorcycles.com",phone:"+91 98765 56789",address:"234, Banjara Hills, Road No. 12",city:"Hyderabad",state:"Telangana",region:"South",managerName:"Anil Reddy"},"RE-KOL-006":{code:"RE-KOL-006",name:"Kolkata Enfield Motors",email:"kolkata@enfieldmotors.com",phone:"+91 98765 67890",address:"56-58, Park Street, Near Park Hotel",city:"Kolkata",state:"West Bengal",region:"East",managerName:"Amit Chatterjee"},"RE-PUN-007":{code:"RE-PUN-007",name:"Pune Royal Dealership",email:"pune@royaldealership.com",phone:"+91 98765 78901",address:"345, FC Road, Deccan Gymkhana",city:"Pune",state:"Maharashtra",region:"West",managerName:"Sandeep Patil"},"RE-AHM-008":{code:"RE-AHM-008",name:"Ahmedabad Enfield Plaza",email:"ahmedabad@enfieldplaza.com",phone:"+91 98765 89012",address:"123, CG Road, Navrangpura",city:"Ahmedabad",state:"Gujarat",region:"West",managerName:"Kiran Patel"},"RE-JP-009":{code:"RE-JP-009",name:"Jaipur Royal Enfield",email:"jaipur@royalenfield.com",phone:"+91 98765 90123",address:"67, MI Road, C-Scheme",city:"Jaipur",state:"Rajasthan",region:"North",managerName:"Rajesh Sharma"},"RE-LKO-010":{code:"RE-LKO-010",name:"Lucknow Enfield Showroom",email:"lucknow@enfieldshowroom.com",phone:"+91 98765 01234",address:"89, Hazratganj, Near Halwasiya Crossing",city:"Lucknow",state:"Uttar Pradesh",region:"North",managerName:"Ankit Verma"}};function MC(t){return dh[t]||null}function IC(){return Object.values(dh)}function _C(t){return`${t.address}, ${t.city}, ${t.state}`}const LC=["Marketing Activity","Promotional Event","Dealer Training","Infrastructure Development","Customer Experience Initiative","Service Campaign"],FC=IC(),$n=["Claim Details","Review & Submit"];function OC({onBack:t,onSubmit:s}){const[a,r]=g.useState(1),[n,i]=g.useState({activityName:"",activityType:"",dealerCode:"",dealerName:"",dealerEmail:"",dealerPhone:"",dealerAddress:"",activityDate:void 0,location:"",requestDescription:"",periodStartDate:void 0,periodEndDate:void 0,estimatedBudget:""}),o=$n.length,l=(p,y)=>{i(v=>({...v,[p]:y}))},c=()=>{switch(a){case 1:return n.activityName&&n.activityType&&n.dealerCode&&n.dealerName&&n.activityDate&&n.location&&n.requestDescription;case 2:return!0;default:return!1}},d=()=>{a{a>1&&r(a-1)},u=p=>{const y=MC(p);y&&(l("dealerCode",y.code),l("dealerName",y.name),l("dealerEmail",y.email),l("dealerPhone",y.phone),l("dealerAddress",_C(y)))},h=()=>{const p={...n,templateType:"claim-management",submittedAt:new Date().toISOString(),status:"pending",currentStep:"initiator-review",workflowSteps:[{step:1,name:"Initiator Evaluation",status:"pending",approver:"Current User (Initiator)",description:"Review and confirm all claim details and documents"},{step:2,name:"IO Confirmation",status:"waiting",approver:"System",description:"Automatic IO generation upon initiator approval"},{step:3,name:"Department Lead Approval",status:"waiting",approver:"Department Lead",description:"Budget blocking and final approval"},{step:4,name:"Document Submission",status:"waiting",approver:"Dealer",description:"Dealer submits completion documents"},{step:5,name:"Document Verification",status:"waiting",approver:"Initiator",description:"Verify completion documents"},{step:6,name:"E-Invoice Generation",status:"waiting",approver:"System",description:"Auto-generate e-invoice based on approved amount"},{step:7,name:"Credit Note Issuance",status:"waiting",approver:"Finance",description:"Issue credit note to dealer"}]};fe.success("Claim Request Created",{description:"Your claim management request has been submitted successfully."}),s&&s(p)},x=()=>{switch(a){case 1:return e.jsxs(St.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"space-y-6",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-2xl flex items-center justify-center mx-auto mb-4",children:e.jsx(Kn,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Claim Details"}),e.jsx("p",{className:"text-gray-600",children:"Provide comprehensive information about your claim request"})]}),e.jsxs("div",{className:"max-w-3xl mx-auto space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(X,{htmlFor:"activityName",className:"text-base font-semibold",children:"Activity Name *"}),e.jsx(xe,{id:"activityName",placeholder:"e.g., Himalayan Adventure Fest 2024",value:n.activityName,onChange:p=>l("activityName",p.target.value),className:"mt-2 h-12"})]}),e.jsxs("div",{children:[e.jsx(X,{htmlFor:"activityType",className:"text-base font-semibold",children:"Activity Type *"}),e.jsxs(we,{value:n.activityType,onValueChange:p=>l("activityType",p),children:[e.jsx(Se,{className:"mt-2 h-12",children:e.jsx(Ce,{placeholder:"Select activity type"})}),e.jsx(Ae,{children:LC.map(p=>e.jsx(V,{value:p,children:p},p))})]})]})]}),e.jsxs("div",{children:[e.jsx(X,{htmlFor:"dealer",className:"text-base font-semibold",children:"Dealer Code / Dealer Name *"}),e.jsxs(we,{value:n.dealerCode,onValueChange:u,children:[e.jsx(Se,{className:"mt-2 h-12",children:e.jsx(Ce,{placeholder:"Select dealer",children:n.dealerCode&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-sm",children:n.dealerCode}),e.jsx("span",{className:"text-gray-400",children:"•"}),e.jsx("span",{children:n.dealerName})]})})}),e.jsx(Ae,{children:FC.map(p=>e.jsx(V,{value:p.code,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-sm font-semibold",children:p.code}),e.jsx("span",{className:"text-gray-400",children:"•"}),e.jsx("span",{children:p.name})]})},p.code))})]}),n.dealerCode&&e.jsxs("p",{className:"text-sm text-gray-600 mt-2",children:["Selected: ",e.jsx("span",{className:"font-semibold",children:n.dealerName})," (",n.dealerCode,")"]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(X,{className:"text-base font-semibold",children:"Date *"}),e.jsxs(Ds,{children:[e.jsx(Ps,{asChild:!0,children:e.jsxs(M,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12",children:[e.jsx(qe,{className:"mr-2 h-4 w-4"}),n.activityDate?pe(n.activityDate,"PPP"):"Select date"]})}),e.jsx(Es,{className:"w-auto p-0",align:"start",children:e.jsx(On,{mode:"single",selected:n.activityDate,onSelect:p=>l("activityDate",p),initialFocus:!0})})]})]}),e.jsxs("div",{children:[e.jsx(X,{htmlFor:"location",className:"text-base font-semibold",children:"Location *"}),e.jsx(xe,{id:"location",placeholder:"e.g., Mumbai, Maharashtra",value:n.location,onChange:p=>l("location",p.target.value),className:"mt-2 h-12"})]})]}),e.jsxs("div",{children:[e.jsx(X,{htmlFor:"requestDescription",className:"text-base font-semibold",children:"Request in Detail - Brief Requirement *"}),e.jsx(Cs,{id:"requestDescription",placeholder:"Provide a detailed description of your claim requirement...",value:n.requestDescription,onChange:p=>l("requestDescription",p.target.value),className:"mt-2 min-h-[120px]"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Include key details about the claim, objectives, and expected outcomes"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(X,{className:"text-base font-semibold",children:"Period (If Any)"}),e.jsx(Q,{variant:"secondary",className:"text-xs",children:"Optional"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(X,{className:"text-sm text-gray-600",children:"Start Date"}),e.jsxs(Ds,{children:[e.jsx(Ps,{asChild:!0,children:e.jsxs(M,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12",children:[e.jsx(qe,{className:"mr-2 h-4 w-4"}),n.periodStartDate?pe(n.periodStartDate,"PPP"):"Start date"]})}),e.jsx(Es,{className:"w-auto p-0",align:"start",children:e.jsx(On,{mode:"single",selected:n.periodStartDate,onSelect:p=>l("periodStartDate",p),initialFocus:!0})})]})]}),e.jsxs("div",{children:[e.jsx(X,{className:"text-sm text-gray-600",children:"End Date"}),e.jsxs(Ds,{children:[e.jsx(Ps,{asChild:!0,children:e.jsxs(M,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12",children:[e.jsx(qe,{className:"mr-2 h-4 w-4"}),n.periodEndDate?pe(n.periodEndDate,"PPP"):"End date"]})}),e.jsx(Es,{className:"w-auto p-0",align:"start",children:e.jsx(On,{mode:"single",selected:n.periodEndDate,onSelect:p=>l("periodEndDate",p),initialFocus:!0})})]})]})]}),(n.periodStartDate||n.periodEndDate)&&e.jsx("p",{className:"text-xs text-gray-600 mt-2",children:n.periodStartDate&&n.periodEndDate?`Period: ${pe(n.periodStartDate,"MMM dd, yyyy")} - ${pe(n.periodEndDate,"MMM dd, yyyy")}`:"Please select both start and end dates for the period"})]})]})]});case 2:return e.jsxs(St.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"space-y-6",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-green-500 to-emerald-600 rounded-2xl flex items-center justify-center mx-auto mb-4",children:e.jsx(ve,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Review & Submit"}),e.jsx("p",{className:"text-gray-600",children:"Review your claim details before submission"})]}),e.jsxs("div",{className:"max-w-3xl mx-auto space-y-6",children:[e.jsxs(G,{className:"border-2",children:[e.jsx(te,{className:"bg-gradient-to-br from-blue-50 to-indigo-50",children:e.jsxs(se,{className:"flex items-center gap-2",children:[e.jsx(Kn,{className:"w-5 h-5 text-blue-600"}),"Activity Information"]})}),e.jsx(Y,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(X,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:n.activityName})]}),e.jsxs("div",{children:[e.jsx(X,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Type"}),e.jsx(Q,{variant:"secondary",className:"mt-1",children:n.activityType})]})]})})]}),e.jsxs(G,{className:"border-2",children:[e.jsx(te,{className:"bg-gradient-to-br from-green-50 to-emerald-50",children:e.jsxs(se,{className:"flex items-center gap-2",children:[e.jsx(kx,{className:"w-5 h-5 text-green-600"}),"Dealer Information"]})}),e.jsx(Y,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(X,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Code"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1 font-mono",children:n.dealerCode})]}),e.jsxs("div",{children:[e.jsx(X,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:n.dealerName})]}),e.jsxs("div",{children:[e.jsx(X,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Email"}),e.jsx("p",{className:"text-gray-900 mt-1",children:n.dealerEmail})]}),e.jsxs("div",{children:[e.jsx(X,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Phone"}),e.jsx("p",{className:"text-gray-900 mt-1",children:n.dealerPhone})]}),n.dealerAddress&&e.jsxs("div",{className:"col-span-2",children:[e.jsx(X,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Address"}),e.jsx("p",{className:"text-gray-900 mt-1",children:n.dealerAddress})]})]})})]}),e.jsxs(G,{className:"border-2",children:[e.jsx(te,{className:"bg-gradient-to-br from-purple-50 to-pink-50",children:e.jsxs(se,{className:"flex items-center gap-2",children:[e.jsx(qe,{className:"w-5 h-5 text-purple-600"}),"Date & Location"]})}),e.jsx(Y,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(X,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:n.activityDate?pe(n.activityDate,"PPP"):"N/A"})]}),e.jsxs("div",{children:[e.jsx(X,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Location"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Rx,{className:"w-4 h-4 text-gray-500"}),e.jsx("p",{className:"font-semibold text-gray-900",children:n.location})]})]}),n.estimatedBudget&&e.jsxs("div",{className:"col-span-2",children:[e.jsx(X,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Estimated Budget"}),e.jsx("p",{className:"text-xl font-bold text-blue-900 mt-1",children:n.estimatedBudget})]})]})})]}),e.jsxs(G,{className:"border-2",children:[e.jsx(te,{className:"bg-gradient-to-br from-orange-50 to-amber-50",children:e.jsxs(se,{className:"flex items-center gap-2",children:[e.jsx(Te,{className:"w-5 h-5 text-orange-600"}),"Request Details"]})}),e.jsx(Y,{className:"pt-6 space-y-4",children:e.jsxs("div",{children:[e.jsx(X,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Brief Requirement"}),e.jsx("div",{className:"mt-2 p-4 bg-gray-50 rounded-lg border",children:e.jsx("p",{className:"text-gray-900 whitespace-pre-wrap",children:n.requestDescription})})]})})]}),(n.periodStartDate||n.periodEndDate)&&e.jsxs(G,{className:"border-2",children:[e.jsx(te,{className:"bg-gradient-to-br from-cyan-50 to-blue-50",children:e.jsxs(se,{className:"flex items-center gap-2",children:[e.jsx(De,{className:"w-5 h-5 text-cyan-600"}),"Period"]})}),e.jsx(Y,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(X,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Start Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:n.periodStartDate?pe(n.periodStartDate,"PPP"):"Not specified"})]}),e.jsxs("div",{children:[e.jsx(X,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"End Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:n.periodEndDate?pe(n.periodEndDate,"PPP"):"Not specified"})]})]})})]}),e.jsx("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-6",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Fr,{className:"w-6 h-6 text-blue-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-blue-900 mb-1",children:"Ready to Submit"}),e.jsx("p",{className:"text-sm text-blue-800",children:"Please review all the information above. Once submitted, your claim request will enter the approval workflow."})]})]})})]})]});default:return null}};return e.jsx("div",{className:"w-full bg-gradient-to-br from-gray-50 to-gray-100 py-4 sm:py-6 lg:py-8 px-3 sm:px-4 lg:px-6 overflow-y-auto",children:e.jsxs("div",{className:"max-w-6xl mx-auto pb-8",children:[e.jsxs("div",{className:"mb-6 sm:mb-8",children:[e.jsxs(M,{variant:"ghost",onClick:t,className:"mb-3 sm:mb-4 gap-2 text-sm sm:text-base",children:[e.jsx(_s,{className:"w-3 h-3 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Back to Templates"}),e.jsx("span",{className:"sm:hidden",children:"Back"})]}),e.jsx("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-0",children:e.jsxs("div",{children:[e.jsx(Q,{variant:"secondary",className:"mb-2 text-xs",children:"Claim Management Template"}),e.jsx("h1",{className:"text-xl sm:text-2xl lg:text-3xl font-bold text-gray-900",children:"New Claim Request"}),e.jsxs("p",{className:"text-sm sm:text-base text-gray-600 mt-1",children:["Step ",a," of ",o,": ",e.jsx("span",{className:"hidden sm:inline",children:$n[a-1]})]})]})}),e.jsxs("div",{className:"mt-4 sm:mt-6",children:[e.jsx(hs,{value:a/o*100,className:"h-2"}),e.jsx("div",{className:"flex justify-between mt-2 px-1",children:$n.map((p,y)=>e.jsx("span",{className:`text-xs sm:text-sm ${y+1<=a?"text-blue-600 font-medium":"text-gray-400"}`,children:y+1},y))})]})]}),e.jsx(G,{className:"mb-6 sm:mb-8",children:e.jsx(Y,{className:"p-4 sm:p-6 lg:p-8",children:e.jsx(Xr,{mode:"wait",children:x()})})}),e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between gap-3 sm:gap-0 pb-4 sm:pb-0",children:[e.jsxs(M,{variant:"outline",onClick:m,disabled:a===1,className:"gap-2 w-full sm:w-auto order-2 sm:order-1",children:[e.jsx(_s,{className:"w-4 h-4"}),"Previous"]}),a{s&&s(r)};return e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-3 sm:gap-4","data-testid":"my-requests-stats",children:[e.jsx(qt,{label:"Total",value:t.total,icon:Te,iconColor:"text-blue-600",gradient:"bg-gradient-to-br from-blue-50 to-blue-100 border-blue-200",textColor:"text-blue-700",valueColor:"text-blue-900",testId:"stat-total",onClick:s?()=>a("all"):void 0}),e.jsx(qt,{label:"Pending",value:t.pending,icon:De,iconColor:"text-orange-600",gradient:"bg-gradient-to-br from-orange-50 to-orange-100 border-orange-200",textColor:"text-orange-700",valueColor:"text-orange-900",testId:"stat-pending",onClick:s?()=>a("pending"):void 0}),e.jsx(qt,{label:"Paused",value:t.paused,icon:Ls,iconColor:"text-amber-600",gradient:"bg-gradient-to-br from-amber-50 to-amber-100 border-amber-200",textColor:"text-amber-700",valueColor:"text-amber-900",testId:"stat-paused",onClick:s?()=>a("paused"):void 0}),e.jsx(qt,{label:"Approved",value:t.approved,icon:ve,iconColor:"text-green-600",gradient:"bg-gradient-to-br from-green-50 to-green-100 border-green-200",textColor:"text-green-700",valueColor:"text-green-900",testId:"stat-approved",onClick:s?()=>a("approved"):void 0}),e.jsx(qt,{label:"Rejected",value:t.rejected,icon:Ze,iconColor:"text-red-600",gradient:"bg-gradient-to-br from-red-50 to-red-100 border-red-200",textColor:"text-red-700",valueColor:"text-red-900",testId:"stat-rejected",onClick:s?()=>a("rejected"):void 0}),e.jsx(qt,{label:"Draft",value:t.draft,icon:Br,iconColor:"text-gray-600",gradient:"bg-gradient-to-br from-gray-50 to-gray-100 border-gray-200",textColor:"text-gray-700",valueColor:"text-gray-900",testId:"stat-draft",onClick:s?()=>a("draft"):void 0}),e.jsx(qt,{label:"Closed",value:t.closed,icon:zr,iconColor:"text-purple-600",gradient:"bg-gradient-to-br from-purple-50 to-purple-100 border-purple-200",textColor:"text-purple-700",valueColor:"text-purple-900",testId:"stat-closed",onClick:s?()=>a("closed"):void 0})]})}function UC({searchTerm:t,statusFilter:s,priorityFilter:a,onSearchChange:r,onStatusChange:n,onPriorityChange:i}){return e.jsx(G,{className:"border-gray-200","data-testid":"my-requests-filters",children:e.jsx(Y,{className:"p-3 sm:p-4 md:p-6",children:e.jsxs("div",{className:"flex flex-col md:flex-row gap-3 sm:gap-4 items-start md:items-center",children:[e.jsxs("div",{className:"flex-1 relative w-full",children:[e.jsx(Yt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx(xe,{placeholder:"Search requests by title, description, or ID...",value:t,onChange:o=>r(o.target.value),className:"pl-9 text-sm sm:text-base bg-white border-gray-300 hover:border-gray-400 focus:border-blue-400 focus:ring-1 focus:ring-blue-200 h-9 sm:h-10","data-testid":"search-input"})]}),e.jsxs("div",{className:"flex gap-2 sm:gap-3 w-full md:w-auto",children:[e.jsxs(we,{value:s,onValueChange:n,children:[e.jsx(Se,{className:"flex-1 md:w-28 lg:w-32 text-xs sm:text-sm bg-white border-gray-300 hover:border-gray-400 focus:border-blue-400 focus:ring-1 focus:ring-blue-200 h-9 sm:h-10","data-testid":"status-filter",children:e.jsx(Ce,{placeholder:"Status"})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"all",children:"All Status"}),e.jsx(V,{value:"draft",children:"Draft"}),e.jsx(V,{value:"pending",children:"Pending"}),e.jsx(V,{value:"paused",children:"Paused"}),e.jsx(V,{value:"approved",children:"Approved"}),e.jsx(V,{value:"rejected",children:"Rejected"}),e.jsx(V,{value:"closed",children:"Closed"})]})]}),e.jsxs(we,{value:a,onValueChange:i,children:[e.jsx(Se,{className:"flex-1 md:w-28 lg:w-32 text-xs sm:text-sm bg-white border-gray-300 hover:border-gray-400 focus:border-blue-400 focus:ring-1 focus:ring-blue-200 h-9 sm:h-10","data-testid":"priority-filter",children:e.jsx(Ce,{placeholder:"Priority"})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"all",children:"All Priority"}),e.jsx(V,{value:"express",children:"Express"}),e.jsx(V,{value:"standard",children:"Standard"})]})]})]})]})})})}function VC(t){switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:ls,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:it,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:it,iconColor:"text-gray-600"}}}function BC(t){switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:ve,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ze,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:De,iconColor:"text-yellow-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:ve,iconColor:"text-gray-600"};case"draft":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Br,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Re,iconColor:"text-gray-600"}}}const zC=t=>{if(!t)return"";if(typeof document>"u")return t.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim();const s=document.createElement("div");s.innerHTML=t;let a=s.textContent||s.innerText||"";return a=a.replace(/\s+/g," ").trim(),a};function HC({request:t,index:s,onViewRequest:a}){var l;const r=BC(t.status),n=VC(t.priority),i=r.icon,o=n.icon;return e.jsx(St.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:s*.1},children:e.jsx(G,{className:"group hover:shadow-lg transition-all duration-300 cursor-pointer border border-gray-200 shadow-sm hover:shadow-md",onClick:()=>a(t.id,t.title,t.status),"data-testid":`request-card-${t.id}`,children:e.jsx(Y,{className:"p-3 sm:p-6",children:e.jsxs("div",{className:"space-y-3 sm:space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"text-base sm:text-lg font-semibold text-gray-900 mb-2 group-hover:text-blue-600 transition-colors line-clamp-2","data-testid":"request-title",children:t.title}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2 mb-2",children:[e.jsxs(Q,{variant:"outline",className:`${r.color} border font-medium text-xs shrink-0`,"data-testid":"status-badge",children:[e.jsx(i,{className:"w-3 h-3 mr-1"}),e.jsx("span",{className:"capitalize",children:t.status})]}),(((l=t.pauseInfo)==null?void 0:l.isPaused)||t.isPaused)&&e.jsxs(Q,{variant:"outline",className:"bg-orange-50 text-orange-700 border-orange-300 font-medium text-xs shrink-0","data-testid":"pause-badge",children:[e.jsx(Ls,{className:"w-3 h-3 mr-1"}),"Paused"]}),e.jsxs(Q,{variant:"outline",className:`${n.color} border font-medium text-xs capitalize shrink-0`,"data-testid":"priority-badge",children:[e.jsx(o,{className:"w-3 h-3 mr-1"}),t.priority]}),t.templateType&&e.jsxs(Q,{variant:"secondary",className:"bg-purple-100 text-purple-700 text-xs shrink-0 hidden sm:inline-flex","data-testid":"template-badge",children:[e.jsx(Te,{className:"w-3 h-3 mr-1"}),"Template: ",t.templateName]})]}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 mb-2 sm:mb-3 line-clamp-2 leading-relaxed","data-testid":"request-description",children:zC(t.description||"")||"No description provided"}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-1 sm:gap-4 text-xs sm:text-sm text-gray-500",children:[e.jsxs("span",{className:"truncate","data-testid":"request-id-display",children:[e.jsx("span",{className:"font-medium",children:"ID:"})," ",t.displayId||t.id]}),e.jsxs("span",{className:"truncate","data-testid":"submitted-date",children:[e.jsx("span",{className:"font-medium",children:"Submitted:"})," ",ps(t.submittedDate)]})]})]}),e.jsx(wt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400 group-hover:text-blue-600 transition-colors flex-shrink-0 mt-1"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 sm:gap-4 pt-3 border-t border-gray-100",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(rt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-gray-400 flex-shrink-0"}),e.jsxs("span",{className:"text-xs sm:text-sm truncate","data-testid":"current-approver",children:[e.jsx("span",{className:"text-gray-500",children:"Current Approver:"})," ",e.jsx("span",{className:"text-gray-900 font-medium",children:t.currentApprover})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Us,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-gray-400 flex-shrink-0"}),e.jsxs("span",{className:"text-xs sm:text-sm","data-testid":"approval-level",children:[e.jsx("span",{className:"text-gray-500",children:"Approval Level:"})," ",e.jsx("span",{className:"text-gray-900 font-medium",children:t.approverLevel})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-gray-500",children:[e.jsx(De,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{"data-testid":"submitted-timestamp",children:["Submitted: ",ps(t.submittedDate)]})]})]})]})})})})}function qC({requests:t,loading:s,searchTerm:a,statusFilter:r,priorityFilter:n,onViewRequest:i}){if(s)return e.jsx(G,{"data-testid":"loading-state",children:e.jsx(Y,{className:"p-6 text-sm text-gray-600",children:"Loading your requests…"})});if(t.length===0){const o=a||r!=="all"||n!=="all";return e.jsx(G,{"data-testid":"empty-state",children:e.jsxs(Y,{className:"p-12 text-center",children:[e.jsx(Te,{className:"w-12 h-12 text-gray-400 mx-auto mb-4"}),e.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No requests found"}),e.jsx("p",{className:"text-gray-600",children:o?"Try adjusting your search or filters":"You haven't created any requests yet"})]})})}return e.jsx("div",{className:"space-y-4","data-testid":"my-requests-list",children:t.map((o,l)=>e.jsx(HC,{request:o,index:l,onViewRequest:i},o.id))})}function WC(t){var r,n;const s=t.submittedAt||t.submitted_at||t.createdAt||t.created_at,a=(t.priority||"").toString().toLowerCase();return{id:t.requestNumber||t.request_number||t.requestId||t.id||t.request_id,requestId:t.requestId||t.id||t.request_id,displayId:t.requestNumber||t.request_number||t.id,title:t.title,description:t.description,status:(t.status||"").toString().toLowerCase().replace("_","-"),priority:a,department:t.department,submittedDate:t.submittedAt||(t.createdAt?new Date(t.createdAt).toISOString().split("T")[0]:void 0),createdAt:s,currentApprover:((r=t.currentApprover)==null?void 0:r.name)||((n=t.currentApprover)==null?void 0:n.email)||"—",approverLevel:t.currentLevel&&t.totalLevels?`${t.currentLevel} of ${t.totalLevels}`:t.currentStep&&t.totalSteps?`${t.currentStep} of ${t.totalSteps}`:"—",templateType:t.templateType,templateName:t.templateName}}function uh(t){return Array.isArray(t)?t.map(WC):[]}function KC({itemsPerPage:t=10,initialFilters:s}={}){const[a,r]=g.useState([]),[n,i]=g.useState(!1),[o,l]=g.useState(!1),[c,d]=g.useState({currentPage:1,totalPages:1,totalRecords:0,itemsPerPage:t}),m=g.useRef(!0),u=g.useCallback(async(h=1,x)=>{try{h===1&&(i(!0),r([]));const p=await It.listMyInitiatedWorkflows({page:h,limit:t,search:x==null?void 0:x.search,status:x==null?void 0:x.status,priority:x==null?void 0:x.priority}),y=Array.isArray(p==null?void 0:p.data)?p.data:[],v=uh(y);r(v),l(!0);const N=p==null?void 0:p.pagination;N&&d({currentPage:N.page||1,totalPages:N.totalPages||1,totalRecords:N.total||0,itemsPerPage:t})}catch(p){console.error("[MyRequests] Error fetching requests:",p),r([]),l(!0)}finally{i(!1)}},[t]);return g.useEffect(()=>{m.current&&(u(1,s),m.current=!1)},[]),{requests:a,loading:n,hasFetchedFromApi:o,pagination:c,fetchMyRequests:u}}function GC({onFiltersChange:t,debounceMs:s=500}={}){const[a,r]=g.useState(""),[n,i]=g.useState("all"),[o,l]=g.useState("all"),c=g.useRef(null),d=g.useCallback(()=>({search:a,status:n,priority:o}),[a,n,o]);g.useEffect(()=>{c.current&&clearTimeout(c.current);const u=setTimeout(()=>{t&&t(d())},a?s:0);return c.current=u,()=>{c.current&&clearTimeout(c.current)}},[a,n,o,t,d,s]);const m=g.useCallback(()=>{r(""),i("all"),l("all")},[]);return{searchTerm:a,statusFilter:n,priorityFilter:o,setSearchTerm:r,setStatusFilter:i,setPriorityFilter:l,getFilters:d,resetFilters:m}}function YC({onViewRequest:t,dynamicRequests:s=[]}){const{user:a}=Bt(),r=KC({itemsPerPage:10}),n=g.useRef(r.fetchMyRequests);n.current=r.fetchMyRequests;const i=GC({onFiltersChange:g.useCallback(y=>{n.current(1,{search:y.search||void 0,status:y.status!=="all"?y.status:void 0,priority:y.priority!=="all"?y.priority:void 0})},[])}),[o,l]=g.useState(null),[c,d]=g.useState(!1),m=g.useCallback(async()=>{if(a!=null&&a.userId)try{d(!0);const y=await He.getRequestStats(void 0,void 0,void 0,void 0,i.priorityFilter!=="all"?i.priorityFilter:void 0,void 0,a.userId,void 0,void 0,i.searchTerm||void 0,void 0);l({total:y.totalRequests||0,pending:y.openRequests||0,paused:y.pausedRequests||0,approved:y.approvedRequests||0,rejected:y.rejectedRequests||0,draft:y.draftRequests||0,closed:y.closedRequests||0})}catch(y){console.error("Failed to fetch backend stats:",y),l(null)}finally{d(!1)}},[a==null?void 0:a.userId,i.searchTerm,i.priorityFilter]);g.useEffect(()=>{const y=setTimeout(()=>{m()},i.searchTerm?500:0);return()=>clearTimeout(y)},[i.searchTerm,i.priorityFilter,m]);const u=uh(s),h=r.hasFetchedFromApi?r.requests:u,x=g.useMemo(()=>o?{total:o.total||0,pending:o.pending||0,paused:o.paused||0,approved:o.approved||0,rejected:o.rejected||0,draft:o.draft||0,closed:o.closed||0}:{total:0,pending:0,paused:0,approved:0,rejected:0,draft:0,closed:0},[o]),p=g.useCallback(y=>{y>=1&&y<=r.pagination.totalPages&&r.fetchMyRequests(y,{search:i.searchTerm||void 0,status:i.statusFilter!=="all"?i.statusFilter:void 0,priority:i.priorityFilter!=="all"?i.priorityFilter:void 0})},[r,i]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"my-requests-page",children:[e.jsx(mh,{icon:Te,title:"My Requests",description:"Track and manage all your submitted requests",badge:{value:`${x.total} total`,label:"requests",loading:r.loading||c},testId:"my-requests-header"}),e.jsx($C,{stats:x,onStatusFilter:y=>{i.setStatusFilter(y)}}),e.jsx(UC,{searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,onSearchChange:i.setSearchTerm,onStatusChange:i.setStatusFilter,onPriorityChange:i.setPriorityFilter}),e.jsx(qC,{requests:h,loading:r.loading,searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,onViewRequest:t}),e.jsx(ca,{currentPage:r.pagination.currentPage,totalPages:r.pagination.totalPages,totalRecords:r.pagination.totalRecords,itemsPerPage:r.pagination.itemsPerPage,onPageChange:p,loading:r.loading,itemLabel:"requests",testIdPrefix:"my-requests-pagination"})]})}function hh({isOrgLevel:t,isAdmin:s,loading:a,exporting:r,onExport:n}){const i=()=>"All Requests",o=()=>t?"View and filter all organization-wide workflow requests":s?"Viewing requests where you are initiator, approver, or participant":"View and filter your workflow requests";return e.jsxs("div",{className:"flex items-start justify-between gap-4","data-testid":"requests-header-container",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(mh,{icon:Te,title:i(),description:o(),testId:"requests-header"}),e.jsx(Q,{variant:"outline",className:t?"bg-blue-50 text-blue-700 border-blue-200":"bg-green-50 text-green-700 border-green-200",children:t?"Organization":"Personal"})]}),e.jsx(M,{onClick:n,disabled:r||a,className:"bg-re-green hover:bg-re-green/90 text-white shrink-0",size:"sm","data-testid":"export-button",children:r?e.jsxs(e.Fragment,{children:[e.jsx(Lt,{className:"w-4 h-4 mr-2 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ns,{className:"w-4 h-4 mr-2"}),"Export"]})})]})}function ph({stats:t,onStatusFilter:s}){const a=r=>{s&&s(r)};return e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3 sm:gap-4","data-testid":"requests-stats",children:[e.jsx(qt,{label:"Total",value:t.total,icon:Te,iconColor:"text-blue-600",gradient:"bg-gradient-to-br from-blue-50 to-blue-100 border-blue-200",textColor:"text-blue-700",valueColor:"text-blue-900",testId:"stat-total",onClick:s?()=>a("all"):void 0}),e.jsx(qt,{label:"Pending",value:t.pending,icon:De,iconColor:"text-orange-600",gradient:"bg-gradient-to-br from-orange-50 to-orange-100 border-orange-200",textColor:"text-orange-700",valueColor:"text-orange-900",testId:"stat-pending",onClick:s?()=>a("pending"):void 0}),e.jsx(qt,{label:"Paused",value:t.paused,icon:Ls,iconColor:"text-amber-600",gradient:"bg-gradient-to-br from-amber-50 to-amber-100 border-amber-200",textColor:"text-amber-700",valueColor:"text-amber-900",testId:"stat-paused",onClick:s?()=>a("paused"):void 0}),e.jsx(qt,{label:"Approved",value:t.approved,icon:ve,iconColor:"text-green-600",gradient:"bg-gradient-to-br from-green-50 to-green-100 border-green-200",textColor:"text-green-700",valueColor:"text-green-900",testId:"stat-approved",onClick:s?()=>a("approved"):void 0}),e.jsx(qt,{label:"Rejected",value:t.rejected,icon:Ze,iconColor:"text-red-600",gradient:"bg-gradient-to-br from-red-50 to-red-100 border-red-200",textColor:"text-red-700",valueColor:"text-red-900",testId:"stat-rejected",onClick:s?()=>a("rejected"):void 0}),e.jsx(qt,{label:"Closed",value:t.closed,icon:zr,iconColor:"text-purple-600",gradient:"bg-gradient-to-br from-purple-50 to-purple-100 border-purple-200",textColor:"text-purple-700",valueColor:"text-purple-900",testId:"stat-closed",onClick:s?()=>a("closed"):void 0})]})}const ZC=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:ls,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:it,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:it,iconColor:"text-gray-600"}}},XC=t=>{switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:ve,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ze,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:De,iconColor:"text-yellow-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:ve,iconColor:"text-gray-600"};case"draft":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Br,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Re,iconColor:"text-gray-600"}}},QC=t=>{if(!t)return"";if(typeof document>"u")return t.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim();const s=document.createElement("div");s.innerHTML=t;let a=s.textContent||s.innerText||"";return a=a.replace(/\s+/g," ").trim(),a};function JC({request:t,index:s,onViewRequest:a}){var l;const r=XC(t.status),n=ZC(t.priority),i=r.icon,o=n.icon;return e.jsx(St.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:s*.1},children:e.jsx(G,{className:"group hover:shadow-lg transition-all duration-300 cursor-pointer border border-gray-200 shadow-sm hover:shadow-md",onClick:()=>a(t.id,t.title,t.status),"data-testid":`request-card-${t.id}`,children:e.jsx(Y,{className:"p-3 sm:p-6",children:e.jsxs("div",{className:"space-y-3 sm:space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"text-base sm:text-lg font-semibold text-gray-900 mb-2 group-hover:text-blue-600 transition-colors line-clamp-2","data-testid":"request-title",children:t.title}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2 mb-2",children:[e.jsxs(Q,{variant:"outline",className:`${r.color} border font-medium text-xs shrink-0`,"data-testid":"status-badge",children:[e.jsx(i,{className:"w-3 h-3 mr-1"}),e.jsx("span",{className:"capitalize",children:t.status})]}),(((l=t.pauseInfo)==null?void 0:l.isPaused)||t.isPaused)&&e.jsxs(Q,{variant:"outline",className:"bg-orange-50 text-orange-700 border-orange-300 font-medium text-xs shrink-0","data-testid":"pause-badge",children:[e.jsx(Ls,{className:"w-3 h-3 mr-1"}),"Paused"]}),e.jsxs(Q,{variant:"outline",className:`${n.color} border font-medium text-xs capitalize shrink-0`,"data-testid":"priority-badge",children:[e.jsx(o,{className:"w-3 h-3 mr-1"}),t.priority]}),t.department&&e.jsx(Q,{variant:"secondary",className:"bg-purple-100 text-purple-700 text-xs shrink-0","data-testid":"department-badge",children:t.department})]}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 mb-2 sm:mb-3 line-clamp-2 leading-relaxed","data-testid":"request-description",children:QC(t.description||"")||"No description provided"}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-1 sm:gap-4 text-xs sm:text-sm text-gray-500",children:[e.jsxs("span",{className:"truncate","data-testid":"request-id-display",children:[e.jsx("span",{className:"font-medium",children:"ID:"})," ",t.displayId||t.id]}),e.jsxs("span",{className:"truncate","data-testid":"submitted-date",children:[e.jsx("span",{className:"font-medium",children:"Submitted:"})," ",ps(t.submittedDate)]})]})]}),e.jsx(wt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400 group-hover:text-blue-600 transition-colors flex-shrink-0 mt-1"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 sm:gap-4 pt-3 border-t border-gray-100",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(rt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-gray-400 flex-shrink-0"}),e.jsxs("span",{className:"text-xs sm:text-sm truncate","data-testid":"current-approver",children:[e.jsx("span",{className:"text-gray-500",children:"Current Approver:"})," ",e.jsx("span",{className:"text-gray-900 font-medium",children:t.currentApprover})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Us,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-gray-400 flex-shrink-0"}),e.jsxs("span",{className:"text-xs sm:text-sm","data-testid":"approval-level",children:[e.jsx("span",{className:"text-gray-500",children:"Approval Level:"})," ",e.jsx("span",{className:"text-gray-900 font-medium",children:t.approverLevel})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-gray-500",children:[e.jsx(De,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{"data-testid":"submitted-timestamp",children:["Submitted: ",ps(t.submittedDate)]})]})]})]})})})})}function xh({requests:t,loading:s,hasActiveFilters:a,onViewRequest:r}){return s?e.jsx(G,{"data-testid":"loading-state",children:e.jsx(Y,{className:"p-6 text-sm text-gray-600",children:"Loading requests…"})}):t.length===0?e.jsx(G,{"data-testid":"empty-state",children:e.jsxs(Y,{className:"p-12 text-center",children:[e.jsx(Te,{className:"w-12 h-12 text-gray-400 mx-auto mb-4"}),e.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No requests found"}),e.jsx("p",{className:"text-gray-600",children:a?"Try adjusting your search or filters":"No requests match the current criteria"})]})}):e.jsx("div",{className:"space-y-4","data-testid":"requests-list",children:t.map((n,i)=>e.jsx(JC,{request:n,index:i,onViewRequest:r},n.id))})}function gh(){const[t,s]=Hr(),[a,r]=g.useState(t.get("search")||""),[n,i]=g.useState(t.get("status")||"all"),[o,l]=g.useState(t.get("priority")||"all"),[c,d]=g.useState(t.get("slaCompliance")||"all"),[m,u]=g.useState(t.get("department")||"all"),[h,x]=g.useState(t.get("initiator")||"all"),[p,y]=g.useState(t.get("approver")||"all"),[v,N]=g.useState(t.get("approverType")==="any"?"any":"current"),[f,b]=g.useState(t.get("dateRange")||"month"),[j,C]=g.useState(t.get("startDate")?new Date(t.get("startDate")):void 0),[R,I]=g.useState(t.get("endDate")?new Date(t.get("endDate")):void 0),[T,E]=g.useState(!1);g.useEffect(()=>{const F=new URLSearchParams;a&&F.set("search",a),n!=="all"&&F.set("status",n),o!=="all"&&F.set("priority",o),c!=="all"&&F.set("slaCompliance",c),m!=="all"&&F.set("department",m),h!=="all"&&F.set("initiator",h),p!=="all"&&(F.set("approver",p),F.set("approverType",v)),f&&F.set("dateRange",f),j&&F.set("startDate",j.toISOString()),R&&F.set("endDate",R.toISOString()),s(F,{replace:!0})},[a,n,o,c,m,h,p,v,f,j,R,s]);const w=g.useCallback(()=>({search:a||void 0,status:n!=="all"?n:void 0,priority:o!=="all"?o:void 0,slaCompliance:c!=="all"?c:void 0,department:m!=="all"?m:void 0,initiator:h!=="all"?h:void 0,approver:p!=="all"?p:void 0,approverType:p!=="all"?v:void 0,dateRange:f,startDate:j,endDate:R}),[a,n,o,c,m,h,p,v,f,j,R]),S=g.useCallback(()=>{r(""),i("all"),l("all"),d("all"),u("all"),x("all"),y("all"),N("current"),b("month"),C(void 0),I(void 0),E(!1)},[]),D=g.useCallback(F=>{const A=F;b(A),A!=="custom"?(C(void 0),I(void 0),E(!1)):E(!0)},[]),H=g.useCallback(()=>{if(j&&R){if(j>R){const F=j;C(R),I(F)}E(!1)}},[j,R]);return{searchTerm:a,statusFilter:n,priorityFilter:o,slaComplianceFilter:c,departmentFilter:m,initiatorFilter:h,approverFilter:p,approverFilterType:v,dateRange:f,customStartDate:j,customEndDate:R,showCustomDatePicker:T,hasActiveFilters:!!(a||n!=="all"||o!=="all"||c!=="all"||m!=="all"||h!=="all"||p!=="all"||f!=="month"||j||R),setSearchTerm:r,setStatusFilter:i,setPriorityFilter:l,setSlaComplianceFilter:d,setDepartmentFilter:u,setInitiatorFilter:x,setApproverFilter:y,setApproverFilterType:N,setDateRange:b,setCustomStartDate:C,setCustomEndDate:I,setShowCustomDatePicker:E,getFilters:w,clearFilters:S,handleDateRangeChange:D,handleApplyCustomDate:H}}function Ir({allUsers:t,filterValue:s,onFilterChange:a}){const[r,n]=g.useState(""),[i,o]=g.useState([]),[l,c]=g.useState(!1),[d,m]=g.useState(null),u=g.useRef(null);g.useEffect(()=>{if(s!=="all"&&t.length>0){const y=t.find(v=>v.userId===s);y&&(m(y),n(y.displayName||y.email))}},[s,t]),g.useEffect(()=>()=>{u.current&&clearTimeout(u.current)},[]);const h=g.useCallback(y=>{if(n(y),u.current&&clearTimeout(u.current),!y||y.trim().length<2){o([]),c(!1);return}u.current=setTimeout(()=>{const v=y.toLowerCase().trim(),N=t.filter(f=>{const b=(f.email||"").toLowerCase(),j=(f.displayName||"").toLowerCase();return b.includes(v)||j.includes(v)});o(N.slice(0,10)),c(N.length>0)},300)},[t]),x=g.useCallback(y=>{m(y),a(y.userId),n(y.displayName||y.email),c(!1),o([])},[a]),p=g.useCallback(()=>{m(null),a("all"),n(""),c(!1),o([])},[a]);return{searchQuery:r,searchResults:i,showResults:l,selectedUser:d,handleSearch:h,handleSelect:x,handleClear:p,setShowResults:c}}function e2(t){var d,m,u,h,x,p,y;const s=t.submittedAt||t.submitted_at||t.createdAt||t.created_at,a=(t.priority||"").toString().toLowerCase(),r=(t.status||"").toString().toUpperCase();let n="—",i="—";const o=t.currentApprover||t.current_approver||t.currentApproverData;if(o)n=o.name||o.approverName||o.displayName||o.email||o.approverEmail||"—";else if(t.approvals&&Array.isArray(t.approvals)&&t.approvals.length>0){const v=t.approvals.find(N=>{const f=(N.status||"").toString().toUpperCase();return f==="PENDING"||f==="IN_PROGRESS"});if(v)n=v.approverName||((d=v.approver)==null?void 0:d.name)||((m=v.approver)==null?void 0:m.displayName)||v.approverEmail||((u=v.approver)==null?void 0:u.email)||"—";else{const f=[...t.approvals].sort((b,j)=>{const C=b.levelNumber||b.level_number||0;return(j.levelNumber||j.level_number||0)-C})[0];f&&(n=f.approverName||((h=f.approver)==null?void 0:h.name)||((x=f.approver)==null?void 0:x.displayName)||f.approverEmail||((p=f.approver)==null?void 0:p.email)||"—")}}const l=t.currentLevel||t.current_level||t.currentLevelNumber||t.current_level_number,c=t.totalLevels||t.total_levels||t.totalLevelsCount||t.total_levels_count;if(l&&c)i=`${l} of ${c}`;else if(t.approvals&&Array.isArray(t.approvals)&&t.approvals.length>0){const v=t.approvals.find(N=>{const f=(N.status||"").toString().toUpperCase();return f==="PENDING"||f==="IN_PROGRESS"});if(v){const N=v.levelNumber||v.level_number||0,f=c||t.approvals.length;i=`${N} of ${f}`}else c&&(i=`${c} of ${c}`)}else t.currentStep&&t.totalSteps&&(i=`${t.currentStep} of ${t.totalSteps}`);return{id:t.requestNumber||t.request_number||t.requestId||t.id||t.request_id,requestId:t.requestId||t.id||t.request_id,displayId:t.requestNumber||t.request_number||t.id,title:t.title,description:t.description,status:r.toLowerCase().replace("_","-"),priority:a,department:t.department||((y=t.initiator)==null?void 0:y.department),submittedDate:t.submittedAt||(t.createdAt?new Date(t.createdAt).toISOString().split("T")[0]:void 0),createdAt:s,currentApprover:n,approverLevel:i,templateType:t.templateType,templateName:t.templateName}}function fh(t){return Array.isArray(t)?t.map(e2):[]}function t2(t,s,a,r,n,i){if(t.length>0){const o=t.length,l=t.filter(x=>{const p=(x.status||"").toString().toUpperCase();return p==="PENDING"||p==="IN_PROGRESS"}).length,c=t.filter(x=>(x.status||"").toString().toUpperCase()==="APPROVED").length,d=t.filter(x=>(x.status||"").toString().toUpperCase()==="REJECTED").length,m=t.filter(x=>(x.status||"").toString().toUpperCase()==="DRAFT").length,u=t.filter(x=>(x.status||"").toString().toUpperCase()==="CLOSED").length,h=t.filter(x=>(x.status||"").toString().toUpperCase()==="PAUSED").length;return{total:o,pending:l,paused:h,approved:c,rejected:d,draft:m,closed:u}}else return s&&a?{total:a.total,pending:a.pending,paused:a.paused||0,approved:a.approved,rejected:a.rejected,draft:a.draft,closed:a.closed}:{total:n||i.length,pending:i.filter(l=>l.status==="pending"||l.status==="in-progress").length,paused:i.filter(l=>l.status==="paused").length,approved:i.filter(l=>l.status==="approved").length,rejected:i.filter(l=>l.status==="rejected").length,draft:i.filter(l=>l.status==="draft").length,closed:i.filter(l=>l.status==="closed").length}}var yh={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(_r,function(){return function(a,r){r.prototype.isSameOrBefore=function(n,i){return this.isSame(n,i)||this.isBefore(n,i)}}})})(yh);var s2=yh.exports;const vh=Lr(s2);var bh={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(_r,function(){return function(a,r){r.prototype.isSameOrAfter=function(n,i){return this.isSame(n,i)||this.isAfter(n,i)}}})})(bh);var a2=bh.exports;const jh=Lr(a2);Xe.extend(jh);Xe.extend(vh);function r2(t,s){let a=[...t];if(s.search){const r=s.search.toLowerCase();a=a.filter(n=>{var i,o,l,c;return((i=n.title)==null?void 0:i.toLowerCase().includes(r))||((o=n.description)==null?void 0:o.toLowerCase().includes(r))||((l=n.requestNumber)==null?void 0:l.toLowerCase().includes(r))||((c=n.request_number)==null?void 0:c.toLowerCase().includes(r))})}if(s.status&&s.status!=="all")if(s.status.toLowerCase()==="pending")a=a.filter(r=>{var o;const n=(r.status||"").toString().toUpperCase(),i=((o=r.pauseInfo)==null?void 0:o.isPaused)||r.isPaused||!1;return(n==="PENDING"||n==="IN_PROGRESS")&&!i});else if(s.status.toLowerCase()==="paused")a=a.filter(r=>{var o;const n=(r.status||"").toString().toUpperCase(),i=((o=r.pauseInfo)==null?void 0:o.isPaused)||r.isPaused||!1;return n==="PAUSED"||i});else{const r=s.status.toUpperCase().replace("-","_");a=a.filter(n=>{var l;const i=(n.status||"").toString().toUpperCase(),o=((l=n.pauseInfo)==null?void 0:l.isPaused)||n.isPaused||!1;return r==="IN_PROGRESS"||r==="IN-PROGRESS"?i==="IN_PROGRESS"&&!o:i===r&&!o})}if(s.priority&&s.priority!=="all"&&(a=a.filter(r=>{var n;return(r.priority||"").toString().toLowerCase()===((n=s.priority)==null?void 0:n.toLowerCase())})),s.department&&s.department!=="all"&&(a=a.filter(r=>{var i;return(r.department||((i=r.initiator)==null?void 0:i.department)||"")===s.department})),s.initiator&&s.initiator!=="all"&&(a=a.filter(r=>{var i,o;return(r.initiatorId||r.initiator_id||((i=r.initiator)==null?void 0:i.userId)||((o=r.initiator)==null?void 0:o.user_id)||(r.initiator&&typeof r.initiator=="object"&&"userId"in r.initiator?r.initiator.userId:null))===s.initiator})),s.approver&&s.approver!=="all"&&((s.approverType||"current")==="current"?a=a.filter(n=>{var o,l,c,d,m,u;return(((o=n.currentApprover)==null?void 0:o.userId)||((l=n.currentApprover)==null?void 0:l.user_id)||((d=(c=n.approvals)==null?void 0:c.find(h=>{const x=(h.status||"").toString().toUpperCase();return x==="IN_PROGRESS"||x==="PENDING"}))==null?void 0:d.approverId)||((u=(m=n.approvals)==null?void 0:m.find(h=>{const x=(h.status||"").toString().toUpperCase();return x==="IN_PROGRESS"||x==="PENDING"}))==null?void 0:u.approver_id)||n.currentApproverId||n.current_approver_id)===s.approver}):a=a.filter(n=>{var o,l;const i=[];return(o=n.currentApprover)!=null&&o.userId&&i.push(n.currentApprover.userId),(l=n.currentApprover)!=null&&l.user_id&&i.push(n.currentApprover.user_id),Array.isArray(n.approvals)&&n.approvals.forEach(c=>{c.approverId&&i.push(c.approverId),c.approver_id&&i.push(c.approver_id)}),i.includes(s.approver||"")})),s.slaCompliance&&s.slaCompliance!=="all"&&(a=a.filter(r=>{var c,d,m,u,h,x,p,y,v,N,f,b;const n=s.slaCompliance||"";if(n.toLowerCase()==="compliant"){const j=(r.status||"").toString().toUpperCase();if(!(j==="APPROVED"||j==="REJECTED"||j==="CLOSED"))return!1;const R=((c=r.currentLevelSLA)==null?void 0:c.status)||((m=(d=r.currentApprover)==null?void 0:d.sla)==null?void 0:m.status)||((u=r.sla)==null?void 0:u.status)||((x=(h=r.summary)==null?void 0:h.sla)==null?void 0:x.status);return R?R!=="breached"&&R.toLowerCase()!=="breached":!0}const i=((p=r.currentLevelSLA)==null?void 0:p.status)||((v=(y=r.currentApprover)==null?void 0:y.sla)==null?void 0:v.status)||((N=r.sla)==null?void 0:N.status)||((b=(f=r.summary)==null?void 0:f.sla)==null?void 0:b.status);if(!i)return n==="on-track"||n==="on_track";const l={"on-track":"on_track",on_track:"on_track",approaching:"approaching",critical:"critical",breached:"breached"}[n.toLowerCase()]||n.toLowerCase();return i===l||i.toLowerCase()===l})),s.dateRange){let r=null,n=null;if(s.dateRange==="custom"&&s.startDate&&s.endDate)r=Xe(s.startDate).startOf("day").toDate(),n=Xe(s.endDate).endOf("day").toDate();else{const i=Xe();switch(s.dateRange){case"today":r=i.startOf("day").toDate(),n=i.endOf("day").toDate();break;case"week":r=i.startOf("week").toDate(),n=i.endOf("week").toDate();break;case"month":r=i.startOf("month").toDate(),n=i.endOf("month").toDate();break}}r&&n&&(a=a.filter(i=>{const o=i.submittedAt||i.submission_date||i.submitted_at;if(!o){const m=i.createdAt||i.created_at||i.created_date;if(!m)return!1;const u=Xe(m).startOf("day").toDate(),h=Xe(r).startOf("day").toDate(),x=Xe(n).endOf("day").toDate();return u>=h&&u<=x}const l=Xe(o).startOf("day").toDate(),c=Xe(r).startOf("day").toDate(),d=Xe(n).endOf("day").toDate();return l>=c&&l<=d}))}return a}Xe.extend(vh);Xe.extend(jh);function n2(t){if(!t)return"N/A";try{const s=typeof t=="string"?new Date(t):t;return pe(s,"yyyy-MM-dd HH:mm:ss")}catch{return"N/A"}}async function Nh(t,s){const a=r2(t,s),r=[["Request Number","Title","Status","Priority","Initiator","Department","Current Approver","Approval Level","Submitted Date","Description"].join(",")];a.forEach(c=>{var f,b,j,C,R;const d=(c.status||"").toString().toLowerCase().replace("_","-"),m=(c.priority||"").toString().toLowerCase(),u=((f=c.initiator)==null?void 0:f.displayName)||((b=c.initiator)==null?void 0:b.email)||c.initiatorName||"N/A",h=c.department||((j=c.initiator)==null?void 0:j.department)||"N/A",x=((C=c.currentApprover)==null?void 0:C.displayName)||((R=c.currentApprover)==null?void 0:R.email)||c.currentApproverName||"N/A",p=c.currentApproverLevel||c.approvalLevel||c.currentLevel||"N/A",y=n2(c.submittedAt||c.createdAt||c.submitted_at||c.created_at),v=(c.description||"").replace(/"/g,'""').replace(/\n/g," ").replace(/\r/g,""),N=[c.requestNumber||c.request_number||"",`"${(c.title||"").replace(/"/g,'""')}"`,d,m,`"${u.replace(/"/g,'""')}"`,`"${h.replace(/"/g,'""')}"`,`"${x.replace(/"/g,'""')}"`,p,y,`"${v}"`];r.push(N.join(","))});const n=r.join(` `),i=new Blob([n],{type:"text/csv;charset=utf-8;"}),o=document.createElement("a"),l=URL.createObjectURL(i);o.setAttribute("href",l),o.setAttribute("download",`requests-export-${new Date().toISOString().split("T")[0]}.csv`),o.style.visibility="hidden",document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(l)}async function i2({page:t,itemsPerPage:s,filters:a,isOrgLevel:r}){var n,i,o,l;if(r){const c={};a!=null&&a.search&&(c.search=a.search),a!=null&&a.status&&a.status!=="all"&&(c.status=a.status),a!=null&&a.priority&&a.priority!=="all"&&(c.priority=a.priority),a!=null&&a.department&&a.department!=="all"&&(c.department=a.department),a!=null&&a.initiator&&a.initiator!=="all"&&(c.initiator=a.initiator),a!=null&&a.approver&&a.approver!=="all"&&(c.approver=a.approver,c.approverType=a.approverType||"current"),a!=null&&a.slaCompliance&&a.slaCompliance!=="all"&&(c.slaCompliance=a.slaCompliance),a!=null&&a.dateRange&&(c.dateRange=a.dateRange),a!=null&&a.startDate&&(c.startDate=(n=a.startDate)==null?void 0:n.toISOString()),a!=null&&a.endDate&&(c.endDate=(i=a.endDate)==null?void 0:i.toISOString());const d=await It.listWorkflows({page:t,limit:s,...c});let m=[];Array.isArray(d==null?void 0:d.data)?m=d.data:Array.isArray(d)&&(m=d);const u=m.filter(p=>(p.status||"").toString().toUpperCase()!=="DRAFT"),h=(d==null?void 0:d.pagination)||{page:t,limit:s,total:u.length,totalPages:1};return{data:u,allData:[],filteredData:u,pagination:{page:h.page,limit:h.limit||s,total:h.total||u.length,totalPages:h.totalPages||1}}}else{const c={};a!=null&&a.search&&(c.search=a.search),a!=null&&a.status&&a.status!=="all"&&(c.status=a.status),a!=null&&a.priority&&a.priority!=="all"&&(c.priority=a.priority),a!=null&&a.department&&a.department!=="all"&&(c.department=a.department),a!=null&&a.initiator&&a.initiator!=="all"&&(c.initiator=a.initiator),a!=null&&a.slaCompliance&&a.slaCompliance!=="all"&&(c.slaCompliance=a.slaCompliance),a!=null&&a.dateRange&&(c.dateRange=a.dateRange),a!=null&&a.startDate&&(c.startDate=(o=a.startDate)==null?void 0:o.toISOString()),a!=null&&a.endDate&&(c.endDate=(l=a.endDate)==null?void 0:l.toISOString());const d=await It.listParticipantRequests({page:t,limit:s,...c});let m=[];Array.isArray(d==null?void 0:d.data)?m=d.data:Array.isArray(d)&&(m=d);const u=m.filter(x=>(x.status||"").toString().toUpperCase()!=="DRAFT"),h=(d==null?void 0:d.pagination)||{page:t,limit:s,total:u.length,totalPages:1};return{data:u,allData:[],filteredData:u,pagination:h}}}async function o2(t){const a=[];let r=1,n=!0;const i=100;for(;n&&r<=i;){const o=t?await It.listWorkflows({page:r,limit:100}):await It.listParticipantRequests({page:r,limit:100});let l=[];if(Array.isArray(o==null?void 0:o.data)?l=o.data:Array.isArray(o)&&(l=o),l.length>0){const c=l.filter(d=>(d.status||"").toString().toUpperCase()!=="DRAFT");a.push(...c),r++,o!=null&&o.pagination?n=r<=o.pagination.totalPages:n=l.length===100}else n=!1}return a}function l2({onViewRequest:t}){const{user:s}=Bt(),a=Vd($=>$.dashboard.viewAsUser),r=g.useMemo(()=>qr(s),[s]),n=g.useMemo(()=>r&&!a,[r,a]),i=gh(),[o,l]=g.useState([]),[c,d]=g.useState(!1),[m,u]=g.useState(!1),[h,x]=g.useState(null),[p,y]=g.useState([]),[v,N]=g.useState(!1),[f,b]=g.useState([]),[j,C]=g.useState(1),[R,I]=g.useState(1),[T,E]=g.useState(0),[w]=g.useState(10),S=Ir({allUsers:f,filterValue:i.initiatorFilter,onFilterChange:i.setInitiatorFilter}),D=Ir({allUsers:f,filterValue:i.approverFilter,onFilterChange:i.setApproverFilter}),H=g.useCallback(async($,ne,me,q)=>{try{const z=q==null?void 0:q.slaCompliance;if(z&&z!=="all"&&z!=="breached"&&z!=="compliant"){const K={};q!=null&&q.search&&(K.search=q.search),q!=null&&q.priority&&q.priority!=="all"&&(K.priority=q.priority),q!=null&&q.department&&q.department!=="all"&&(K.department=q.department),q!=null&&q.initiator&&q.initiator!=="all"&&(K.initiator=q.initiator),q!=null&&q.approver&&q.approver!=="all"&&(K.approver=q.approver,K.approverType=q.approverType||"current"),K.slaCompliance=z,$&&(K.dateRange=$),ne&&(K.startDate=ne.toISOString()),me&&(K.endDate=me.toISOString());const B=n?await It.listWorkflows({page:1,limit:1e3,...K}):await It.listParticipantRequests({page:1,limit:1e3,...K}),J=Array.isArray(B==null?void 0:B.data)?B.data:[],ue=J.length,be=J.filter(Ue=>{const $e=(Ue.status||"").toString().toUpperCase();return $e==="PENDING"||$e==="IN_PROGRESS"}).length,Ie=J.filter(Ue=>(Ue.status||"").toString().toUpperCase()==="APPROVED").length,Ve=J.filter(Ue=>(Ue.status||"").toString().toUpperCase()==="REJECTED").length,Oe=J.filter(Ue=>(Ue.status||"").toString().toUpperCase()==="CLOSED").length;x({total:ue,pending:be,paused:0,approved:Ie,rejected:Ve,draft:0,closed:Oe})}else{const K=await He.getRequestStats($,ne?ne.toISOString():void 0,me?me.toISOString():void 0,void 0,q==null?void 0:q.priority,q==null?void 0:q.department,q==null?void 0:q.initiator,q==null?void 0:q.approver,q==null?void 0:q.approverType,q==null?void 0:q.search,q==null?void 0:q.slaCompliance,!n);x({total:K.totalRequests||0,pending:K.openRequests||0,paused:K.pausedRequests||0,approved:K.approvedRequests||0,rejected:K.rejectedRequests||0,draft:K.draftRequests||0,closed:K.closedRequests||0})}}catch(z){console.error("Failed to fetch backend stats:",z)}finally{}},[n]),L=g.useCallback(async()=>{try{N(!0);const $=await He.getDepartments();y($)}catch{}finally{N(!1)}},[]),F=g.useCallback(async()=>{try{const ne=(await Wt.getAllUsers()).map(me=>({userId:me.userId,email:me.email,displayName:me.displayName||me.email}));b(ne)}catch($){console.error("Failed to fetch users:",$)}},[]),A=g.useRef(i),k=g.useRef(H);g.useEffect(()=>{A.current=i,k.current=H},[i,H]);const P=g.useCallback(async($=1)=>{try{$===1&&(d(!0),l([]));const ne=A.current.getFilters(),me=await i2({page:$,itemsPerPage:w,filters:ne,isOrgLevel:n});l(me.data),C(me.pagination.page),I(me.pagination.totalPages),E(me.pagination.total)}catch{l([])}finally{d(!1)}},[w,n]),_=g.useCallback(async()=>{try{u(!0);const $=await o2(n);await Nh($,i.getFilters())}catch($){console.error("Failed to export requests:",$),alert("Failed to export requests. Please try again.")}finally{u(!1)}},[n,i]);g.useEffect(()=>{L(),F()},[L,F]),g.useEffect(()=>{const $=setTimeout(()=>{const ne={priority:i.priorityFilter!=="all"?i.priorityFilter:void 0,department:i.departmentFilter!=="all"?i.departmentFilter:void 0,initiator:i.initiatorFilter!=="all"?i.initiatorFilter:void 0,approver:i.approverFilter!=="all"?i.approverFilter:void 0,approverType:i.approverFilter!=="all"?i.approverFilterType:void 0,search:i.searchTerm||void 0,slaCompliance:i.slaComplianceFilter!=="all"?i.slaComplianceFilter:void 0},me=i.dateRange||"month";k.current(me,i.customStartDate,i.customEndDate,ne)},i.searchTerm?500:0);return()=>clearTimeout($)},[n,i.dateRange,i.customStartDate,i.customEndDate,i.priorityFilter,i.departmentFilter,i.initiatorFilter,i.approverFilter,i.approverFilterType,i.searchTerm,i.slaComplianceFilter]),g.useEffect(()=>{const $=setTimeout(()=>{C(1),P(1)},i.searchTerm?500:0);return()=>clearTimeout($)},[n,i.searchTerm,i.statusFilter,i.priorityFilter,i.slaComplianceFilter,i.departmentFilter,i.initiatorFilter,i.approverFilter,i.approverFilterType,i.dateRange,i.customStartDate,i.customEndDate]);const W=g.useCallback($=>{$>=1&&$<=R&&(C($),P($))},[R,P]),Z=g.useMemo(()=>fh(o),[o]),ae=g.useMemo(()=>h?{total:h.total||0,pending:h.pending||0,paused:h.paused||0,approved:h.approved||0,rejected:h.rejected||0,draft:h.draft||0,closed:h.closed||0}:t2([],n,h,!1,T,Z),[n,h,T,Z]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"requests-page",children:[e.jsx(hh,{isOrgLevel:n,isAdmin:r,loading:c,exporting:m,onExport:_}),e.jsx(ph,{stats:ae,onStatusFilter:$=>{i.setStatusFilter($)}}),e.jsx(G,{className:"border-gray-200 shadow-md","data-testid":"requests-filters",children:e.jsx(Y,{className:"p-4 sm:p-6",children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qa,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),i.hasActiveFilters&&e.jsx(Q,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),i.hasActiveFilters&&e.jsxs(M,{variant:"ghost",size:"sm",onClick:i.clearFilters,className:"gap-2",children:[e.jsx(Lt,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(yt,{}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 lg:grid-cols-5 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative md:col-span-3 lg:col-span-1",children:[e.jsx(Yt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(xe,{placeholder:"Search requests...",value:i.searchTerm,onChange:$=>i.setSearchTerm($.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(we,{value:i.statusFilter,onValueChange:i.setStatusFilter,children:[e.jsx(Se,{className:"h-10","data-testid":"status-filter",children:e.jsx(Ce,{placeholder:"All Status"})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"all",children:"All Status"}),e.jsx(V,{value:"pending",children:"Pending"}),e.jsx(V,{value:"paused",children:"Paused"}),e.jsx(V,{value:"approved",children:"Approved"}),e.jsx(V,{value:"rejected",children:"Rejected"}),e.jsx(V,{value:"closed",children:"Closed"})]})]}),e.jsxs(we,{value:i.priorityFilter,onValueChange:i.setPriorityFilter,children:[e.jsx(Se,{className:"h-10","data-testid":"priority-filter",children:e.jsx(Ce,{placeholder:"All Priority"})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"all",children:"All Priority"}),e.jsx(V,{value:"express",children:"Express"}),e.jsx(V,{value:"standard",children:"Standard"})]})]}),e.jsxs(we,{value:i.departmentFilter,onValueChange:i.setDepartmentFilter,disabled:v||p.length===0,children:[e.jsx(Se,{className:"h-10","data-testid":"department-filter",children:e.jsx(Ce,{placeholder:v?"Loading...":"All Departments"})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"all",children:"All Departments"}),p.map($=>e.jsx(V,{value:$,children:$},$))]})]}),e.jsxs(we,{value:i.slaComplianceFilter,onValueChange:i.setSlaComplianceFilter,children:[e.jsx(Se,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(Ce,{placeholder:"All SLA Status"})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"all",children:"All SLA Status"}),e.jsx(V,{value:"compliant",children:"Compliant"}),e.jsx(V,{value:"on-track",children:"On Track"}),e.jsx(V,{value:"approaching",children:"Approaching"}),e.jsx(V,{value:"critical",children:"Critical"}),e.jsx(V,{value:"breached",children:"Breached"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx(X,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:S.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:S.selectedUser.displayName||S.selectedUser.email}),e.jsx(M,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:S.handleClear,children:e.jsx(ft,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(xe,{placeholder:"Search initiator...",value:S.searchQuery,onChange:$=>S.handleSearch($.target.value),onFocus:()=>{S.searchResults.length>0&&S.setShowResults(!0)},onBlur:()=>setTimeout(()=>S.setShowResults(!1),200),className:"h-10","data-testid":"initiator-search-input"}),S.showResults&&S.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:S.searchResults.map($=>e.jsx("button",{type:"button",onClick:()=>S.handleSelect($),className:"w-full px-4 py-2 text-left hover:bg-gray-50",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-medium text-gray-900",children:$.displayName||$.email}),$.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:$.email})]})},$.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(X,{className:"text-sm font-medium text-gray-700",children:"Approver"}),i.approverFilter!=="all"&&e.jsxs(we,{value:i.approverFilterType,onValueChange:$=>i.setApproverFilterType($),children:[e.jsx(Se,{className:"h-7 w-32 text-xs",children:e.jsx(Ce,{})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"current",children:"Current Only"}),e.jsx(V,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:D.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:D.selectedUser.displayName||D.selectedUser.email}),e.jsx(M,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:D.handleClear,children:e.jsx(ft,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(xe,{placeholder:"Search approver...",value:D.searchQuery,onChange:$=>D.handleSearch($.target.value),onFocus:()=>{D.searchResults.length>0&&D.setShowResults(!0)},onBlur:()=>setTimeout(()=>D.setShowResults(!1),200),className:"h-10","data-testid":"approver-search-input"}),D.showResults&&D.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:D.searchResults.map($=>e.jsx("button",{type:"button",onClick:()=>D.handleSelect($),className:"w-full px-4 py-2 text-left hover:bg-gray-50",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-medium text-gray-900",children:$.displayName||$.email}),$.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:$.email})]})},$.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(qe,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(we,{value:i.dateRange,onValueChange:i.handleDateRangeChange,children:[e.jsx(Se,{className:"w-[160px] h-10",children:e.jsx(Ce,{placeholder:"Date Range"})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"today",children:"Today"}),e.jsx(V,{value:"week",children:"This Week"}),e.jsx(V,{value:"month",children:"This Month"}),e.jsx(V,{value:"custom",children:"Custom Range"})]})]}),i.dateRange==="custom"&&e.jsxs(Ds,{open:i.showCustomDatePicker,onOpenChange:i.setShowCustomDatePicker,children:[e.jsx(Ps,{asChild:!0,children:e.jsxs(M,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(qe,{className:"w-4 h-4"}),i.customStartDate&&i.customEndDate?`${pe(i.customStartDate,"MMM d, yyyy")} - ${pe(i.customEndDate,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Es,{className:"w-auto p-4",align:"start",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"start-date",children:"Start Date"}),e.jsx(xe,{id:"start-date",type:"date",value:i.customStartDate?pe(i.customStartDate,"yyyy-MM-dd"):"",onChange:$=>{const ne=$.target.value?new Date($.target.value):void 0;ne?(i.setCustomStartDate(ne),i.customEndDate&&ne>i.customEndDate&&i.setCustomEndDate(ne)):i.setCustomStartDate(void 0)},max:pe(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"end-date",children:"End Date"}),e.jsx(xe,{id:"end-date",type:"date",value:i.customEndDate?pe(i.customEndDate,"yyyy-MM-dd"):"",onChange:$=>{const ne=$.target.value?new Date($.target.value):void 0;ne?(i.setCustomEndDate(ne),i.customStartDate&&ne{i.setShowCustomDatePicker(!1),i.setCustomStartDate(void 0),i.setCustomEndDate(void 0),i.setDateRange("month")},children:"Cancel"})]})]})})]})]})]})})}),e.jsx(xh,{requests:Z,loading:c,hasActiveFilters:i.hasActiveFilters,onViewRequest:t}),e.jsx(ca,{currentPage:j,totalPages:R,totalRecords:T,itemsPerPage:w,onPageChange:W,loading:c,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}async function c2({page:t,itemsPerPage:s,filters:a}){const r={};a!=null&&a.search&&(r.search=a.search),a!=null&&a.status&&a.status!=="all"&&(r.status=a.status),a!=null&&a.priority&&a.priority!=="all"&&(r.priority=a.priority),a!=null&&a.department&&a.department!=="all"&&(r.department=a.department),a!=null&&a.initiator&&a.initiator!=="all"&&(r.initiator=a.initiator),a!=null&&a.approver&&a.approver!=="all"&&(r.approver=a.approver,r.approverType=a.approverType||"current"),a!=null&&a.slaCompliance&&a.slaCompliance!=="all"&&(r.slaCompliance=a.slaCompliance),a!=null&&a.dateRange&&(r.dateRange=a.dateRange),a!=null&&a.startDate&&(r.startDate=a.startDate instanceof Date?a.startDate.toISOString():a.startDate),a!=null&&a.endDate&&(r.endDate=a.endDate instanceof Date?a.endDate.toISOString():a.endDate);const n=await It.listParticipantRequests({page:t,limit:s,...r});let i=[];Array.isArray(n==null?void 0:n.data)?i=n.data:Array.isArray(n)&&(i=n);const o=i.filter(c=>(c.status||"").toString().toUpperCase()!=="DRAFT"),l=(n==null?void 0:n.pagination)||{page:t,limit:s,total:o.length,totalPages:1};return{data:o,allData:[],filteredData:o,pagination:{page:l.page,limit:l.limit||s,total:l.total||o.length,totalPages:l.totalPages||1}}}const $c=100;async function d2(t){const s=[];let a=!0,r=1;const n=100,i={};for(t!=null&&t.search&&(i.search=t.search),t!=null&&t.status&&t.status!=="all"&&(i.status=t.status),t!=null&&t.priority&&t.priority!=="all"&&(i.priority=t.priority),t!=null&&t.department&&t.department!=="all"&&(i.department=t.department),t!=null&&t.initiator&&t.initiator!=="all"&&(i.initiator=t.initiator),t!=null&&t.approver&&t.approver!=="all"&&(i.approver=t.approver,i.approverType=t.approverType||"current"),t!=null&&t.slaCompliance&&t.slaCompliance!=="all"&&(i.slaCompliance=t.slaCompliance),t!=null&&t.dateRange&&(i.dateRange=t.dateRange),t!=null&&t.startDate&&(i.startDate=t.startDate instanceof Date?t.startDate.toISOString():t.startDate),t!=null&&t.endDate&&(i.endDate=t.endDate instanceof Date?t.endDate.toISOString():t.endDate);a&&r<=n;){const o=await It.listParticipantRequests({page:r,limit:$c,...i});let l=[];if(Array.isArray(o==null?void 0:o.data)?l=o.data:Array.isArray(o)&&(l=o),l.length===0)a=!1;else{const c=l.filter(d=>(d.status||"").toString().toUpperCase()!=="DRAFT");s.push(...c),r++,o!=null&&o.pagination?a=r<=o.pagination.totalPages:a=l.length===$c}}return s}function m2({onViewRequest:t}){const s=gh(),[a,r]=g.useState([]),[n,i]=g.useState(!1),[o,l]=g.useState(!1),[c,d]=g.useState(null),[m,u]=g.useState([]),[h,x]=g.useState(!1),[p,y]=g.useState([]),[v,N]=g.useState(1),[f,b]=g.useState(1),[j,C]=g.useState(0),[R]=g.useState(10),I=Ir({allUsers:p,filterValue:s.initiatorFilter,onFilterChange:s.setInitiatorFilter}),T=Ir({allUsers:p,filterValue:s.approverFilter,onFilterChange:s.setApproverFilter}),E=g.useCallback(async(_,W,Z,ae)=>{try{const $=await He.getRequestStats(_,W?W.toISOString():void 0,Z?Z.toISOString():void 0,void 0,ae==null?void 0:ae.priority,ae==null?void 0:ae.department,ae==null?void 0:ae.initiator,ae==null?void 0:ae.approver,ae==null?void 0:ae.approverType,ae==null?void 0:ae.search,ae==null?void 0:ae.slaCompliance,!0);d({total:$.totalRequests||0,pending:$.openRequests||0,paused:$.pausedRequests||0,approved:$.approvedRequests||0,rejected:$.rejectedRequests||0,draft:$.draftRequests||0,closed:$.closedRequests||0})}catch($){console.error("Failed to fetch backend stats:",$)}},[]),w=g.useCallback(async()=>{try{x(!0);const _=await He.getDepartments();u(_)}catch{}finally{x(!1)}},[]),S=g.useCallback(async()=>{try{const W=(await Wt.getAllUsers()).map(Z=>({userId:Z.userId,email:Z.email,displayName:Z.displayName||Z.email}));y(W)}catch(_){console.error("Failed to fetch users:",_)}},[]),D=g.useRef(s),H=g.useRef(E);g.useEffect(()=>{D.current=s,H.current=E},[s,E]);const L=g.useCallback(async(_=1)=>{try{_===1&&(i(!0),r([]));const W=D.current.getFilters(),Z=await c2({page:_,itemsPerPage:R,filters:W});r(Z.data),N(Z.pagination.page),b(Z.pagination.totalPages),C(Z.pagination.total)}catch{r([])}finally{i(!1)}},[R]),F=g.useCallback(async()=>{try{l(!0);const _=await d2(s.getFilters());await Nh(_,s.getFilters())}catch(_){console.error("Failed to export requests:",_),alert("Failed to export requests. Please try again.")}finally{l(!1)}},[s]);g.useEffect(()=>{w(),S()},[w,S]),g.useEffect(()=>{const _=setTimeout(()=>{const W={priority:s.priorityFilter!=="all"?s.priorityFilter:void 0,department:s.departmentFilter!=="all"?s.departmentFilter:void 0,initiator:s.initiatorFilter!=="all"?s.initiatorFilter:void 0,approver:s.approverFilter!=="all"?s.approverFilter:void 0,approverType:s.approverFilter!=="all"?s.approverFilterType:void 0,search:s.searchTerm||void 0,slaCompliance:s.slaComplianceFilter!=="all"?s.slaComplianceFilter:void 0},Z=s.dateRange||"month";H.current(Z,s.customStartDate,s.customEndDate,W)},s.searchTerm?500:0);return()=>clearTimeout(_)},[s.searchTerm,s.priorityFilter,s.slaComplianceFilter,s.departmentFilter,s.initiatorFilter,s.approverFilter,s.approverFilterType,s.dateRange,s.customStartDate,s.customEndDate]),g.useEffect(()=>{const _=setTimeout(()=>{N(1),L(1)},s.searchTerm?500:0);return()=>clearTimeout(_)},[s.searchTerm,s.statusFilter,s.priorityFilter,s.slaComplianceFilter,s.departmentFilter,s.initiatorFilter,s.approverFilter,s.approverFilterType,s.dateRange,s.customStartDate,s.customEndDate]);const A=g.useCallback(_=>{_>=1&&_<=f&&(N(_),L(_))},[f,L]),k=g.useMemo(()=>fh(a),[a]),P=g.useMemo(()=>{if(c)return{total:c.total||0,pending:c.pending||0,paused:c.paused||0,approved:c.approved||0,rejected:c.rejected||0,draft:c.draft||0,closed:c.closed||0};const _=k.filter(ne=>{const me=(ne.status||"").toString().toLowerCase();return me==="pending"||me==="in-progress"}).length,W=k.filter(ne=>(ne.status||"").toString().toLowerCase()==="paused").length,Z=k.filter(ne=>(ne.status||"").toString().toLowerCase()==="approved").length,ae=k.filter(ne=>(ne.status||"").toString().toLowerCase()==="rejected").length,$=k.filter(ne=>(ne.status||"").toString().toLowerCase()==="closed").length;return{total:j>0?j:k.length,pending:_,paused:W,approved:Z,rejected:ae,draft:0,closed:$}},[c,j,k]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"user-all-requests-page",children:[e.jsx(hh,{isOrgLevel:!1,isAdmin:!1,loading:n,exporting:o,onExport:F}),e.jsx(ph,{stats:P,onStatusFilter:_=>{s.setStatusFilter(_)}}),e.jsx(G,{className:"border-gray-200 shadow-md","data-testid":"requests-filters",children:e.jsx(Y,{className:"p-4 sm:p-6",children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qa,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),s.hasActiveFilters&&e.jsx(Q,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),s.hasActiveFilters&&e.jsxs(M,{variant:"ghost",size:"sm",onClick:s.clearFilters,className:"gap-2",children:[e.jsx(Lt,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(yt,{}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 lg:grid-cols-5 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative md:col-span-3 lg:col-span-1",children:[e.jsx(Yt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(xe,{placeholder:"Search requests...",value:s.searchTerm,onChange:_=>s.setSearchTerm(_.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(we,{value:s.statusFilter,onValueChange:s.setStatusFilter,children:[e.jsx(Se,{className:"h-10","data-testid":"status-filter",children:e.jsx(Ce,{placeholder:"All Status"})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"all",children:"All Status"}),e.jsx(V,{value:"pending",children:"Pending"}),e.jsx(V,{value:"paused",children:"Paused"}),e.jsx(V,{value:"approved",children:"Approved"}),e.jsx(V,{value:"rejected",children:"Rejected"}),e.jsx(V,{value:"closed",children:"Closed"})]})]}),e.jsxs(we,{value:s.priorityFilter,onValueChange:s.setPriorityFilter,children:[e.jsx(Se,{className:"h-10","data-testid":"priority-filter",children:e.jsx(Ce,{placeholder:"All Priority"})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"all",children:"All Priority"}),e.jsx(V,{value:"express",children:"Express"}),e.jsx(V,{value:"standard",children:"Standard"})]})]}),e.jsxs(we,{value:s.departmentFilter,onValueChange:s.setDepartmentFilter,disabled:h||m.length===0,children:[e.jsx(Se,{className:"h-10","data-testid":"department-filter",children:e.jsx(Ce,{placeholder:h?"Loading...":"All Departments"})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"all",children:"All Departments"}),m.map(_=>e.jsx(V,{value:_,children:_},_))]})]}),e.jsxs(we,{value:s.slaComplianceFilter,onValueChange:s.setSlaComplianceFilter,children:[e.jsx(Se,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(Ce,{placeholder:"All SLA Status"})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"all",children:"All SLA Status"}),e.jsx(V,{value:"compliant",children:"Compliant"}),e.jsx(V,{value:"on-track",children:"On Track"}),e.jsx(V,{value:"approaching",children:"Approaching"}),e.jsx(V,{value:"critical",children:"Critical"}),e.jsx(V,{value:"breached",children:"Breached"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx(X,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:I.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:I.selectedUser.displayName||I.selectedUser.email}),e.jsx(M,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:I.handleClear,children:e.jsx(ft,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(xe,{placeholder:"Search initiator...",value:I.searchQuery,onChange:_=>I.handleSearch(_.target.value),onFocus:()=>{I.searchResults.length>0&&I.setShowResults(!0)},onBlur:()=>setTimeout(()=>I.setShowResults(!1),200),className:"h-10","data-testid":"initiator-search-input"}),I.showResults&&I.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:I.searchResults.map(_=>e.jsx("button",{type:"button",onClick:()=>I.handleSelect(_),className:"w-full px-4 py-2 text-left hover:bg-gray-50",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-medium text-gray-900",children:_.displayName||_.email}),_.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:_.email})]})},_.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(X,{className:"text-sm font-medium text-gray-700",children:"Approver"}),s.approverFilter!=="all"&&e.jsxs(we,{value:s.approverFilterType,onValueChange:_=>s.setApproverFilterType(_),children:[e.jsx(Se,{className:"h-7 w-32 text-xs",children:e.jsx(Ce,{})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"current",children:"Current Only"}),e.jsx(V,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:T.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:T.selectedUser.displayName||T.selectedUser.email}),e.jsx(M,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:T.handleClear,children:e.jsx(ft,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(xe,{placeholder:"Search approver...",value:T.searchQuery,onChange:_=>T.handleSearch(_.target.value),onFocus:()=>{T.searchResults.length>0&&T.setShowResults(!0)},onBlur:()=>setTimeout(()=>T.setShowResults(!1),200),className:"h-10","data-testid":"approver-search-input"}),T.showResults&&T.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:T.searchResults.map(_=>e.jsx("button",{type:"button",onClick:()=>T.handleSelect(_),className:"w-full px-4 py-2 text-left hover:bg-gray-50",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-medium text-gray-900",children:_.displayName||_.email}),_.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:_.email})]})},_.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(qe,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(we,{value:s.dateRange,onValueChange:s.handleDateRangeChange,children:[e.jsx(Se,{className:"w-[160px] h-10",children:e.jsx(Ce,{placeholder:"Date Range"})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"today",children:"Today"}),e.jsx(V,{value:"week",children:"This Week"}),e.jsx(V,{value:"month",children:"This Month"}),e.jsx(V,{value:"custom",children:"Custom Range"})]})]}),s.dateRange==="custom"&&e.jsxs(Ds,{open:s.showCustomDatePicker,onOpenChange:s.setShowCustomDatePicker,children:[e.jsx(Ps,{asChild:!0,children:e.jsxs(M,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(qe,{className:"w-4 h-4"}),s.customStartDate&&s.customEndDate?`${pe(s.customStartDate,"MMM d, yyyy")} - ${pe(s.customEndDate,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Es,{className:"w-auto p-4",align:"start",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"start-date",children:"Start Date"}),e.jsx(xe,{id:"start-date",type:"date",value:s.customStartDate?pe(s.customStartDate,"yyyy-MM-dd"):"",onChange:_=>{const W=_.target.value?new Date(_.target.value):void 0;W?(s.setCustomStartDate(W),s.customEndDate&&W>s.customEndDate&&s.setCustomEndDate(W)):s.setCustomStartDate(void 0)},max:pe(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"end-date",children:"End Date"}),e.jsx(xe,{id:"end-date",type:"date",value:s.customEndDate?pe(s.customEndDate,"yyyy-MM-dd"):"",onChange:_=>{const W=_.target.value?new Date(_.target.value):void 0;W?(s.setCustomEndDate(W),s.customStartDate&&W{s.setShowCustomDatePicker(!1),s.setCustomStartDate(void 0),s.setCustomEndDate(void 0),s.setDateRange("month")},children:"Cancel"})]})]})})]})]})]})})}),e.jsx(xh,{requests:k,loading:n,hasActiveFilters:s.hasActiveFilters,onViewRequest:t}),e.jsx(ca,{currentPage:v,totalPages:f,totalRecords:j,itemsPerPage:R,onPageChange:A,loading:n,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}function u2(){const t=Bs();return e.jsx("div",{className:"flex-1 p-3 lg:p-6 overflow-auto min-w-0","data-testid":"approver-performance-empty",children:e.jsx("div",{className:"max-w-7xl mx-auto p-4",children:e.jsx(G,{children:e.jsxs(Y,{className:"p-8 text-center",children:[e.jsx(Re,{className:"w-12 h-12 text-yellow-500 mx-auto mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Approver ID Required"}),e.jsx("p",{className:"text-gray-600",children:"Please select an approver to view their performance details."}),e.jsxs(M,{onClick:()=>t(-1),className:"mt-4","data-testid":"back-button",children:[e.jsx(_s,{className:"w-4 h-4 mr-2"}),"Back"]})]})})})})}function h2({approverName:t,refreshing:s,onRefresh:a}){return e.jsxs("div",{className:"flex items-center justify-between","data-testid":"approver-performance-header",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-yellow-100 rounded-lg",children:e.jsx(at,{className:"h-6 w-6 text-yellow-600"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900",children:"Approver Performance Report"}),e.jsx("p",{className:"text-sm text-gray-600",children:t})]})]}),e.jsxs(M,{variant:"outline",size:"sm",onClick:a,disabled:s,className:"gap-2","data-testid":"refresh-button",children:[e.jsx(Lt,{className:`w-4 h-4 ${s?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:"Refresh"})]})]})}function p2({approverStats:t,calculatedStats:s}){if(!t)return null;const a=(t==null?void 0:t.tatCompliancePercent)??s.tatComplianceRate;return e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4","data-testid":"approver-stats-cards",children:[e.jsxs(G,{children:[e.jsx(te,{className:"pb-3",children:e.jsx(se,{className:"text-sm font-medium text-gray-600",children:"TAT Compliance"})}),e.jsxs(Y,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-3xl font-bold text-gray-900",children:[a,"%"]}),e.jsx("div",{className:`p-2 rounded-lg ${a>=95?"bg-green-100":a>=90?"bg-blue-100":a>=85?"bg-orange-100":"bg-red-100"}`,children:e.jsx(it,{className:`w-5 h-5 ${a>=95?"text-green-600":a>=90?"text-blue-600":a>=85?"text-orange-600":"text-red-600"}`})})]}),e.jsx(hs,{value:a,className:"mt-2 h-2"})]})]}),e.jsxs(G,{children:[e.jsx(te,{className:"pb-3",children:e.jsx(se,{className:"text-sm font-medium text-gray-600",children:"Total Approved"})}),e.jsxs(Y,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-3xl font-bold text-gray-900",children:t.totalApproved}),e.jsx("div",{className:"p-2 bg-blue-100 rounded-lg",children:e.jsx(ve,{className:"w-5 h-5 text-blue-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Requests handled"})]})]}),e.jsxs(G,{children:[e.jsx(te,{className:"pb-3",children:e.jsx(se,{className:"text-sm font-medium text-gray-600",children:"Avg Response Time"})}),e.jsxs(Y,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-3xl font-bold text-gray-900",children:[t.avgResponseHours.toFixed(1),"h"]}),e.jsx("div",{className:"p-2 bg-purple-100 rounded-lg",children:e.jsx(Pi,{className:"w-5 h-5 text-purple-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:t.avgResponseHours<24?`${(t.avgResponseHours/8).toFixed(1)} working days`:`${(t.avgResponseHours/24).toFixed(1)} days`})]})]}),e.jsxs(G,{children:[e.jsx(te,{className:"pb-3",children:e.jsx(se,{className:"text-sm font-medium text-gray-600",children:"Pending Actions"})}),e.jsxs(Y,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-3xl font-bold text-gray-900",children:t.pendingCount}),e.jsx("div",{className:"p-2 bg-orange-100 rounded-lg",children:e.jsx(De,{className:"w-5 h-5 text-orange-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Awaiting approval"})]})]})]})}function x2({approverName:t,approverStats:s,calculatedStats:a}){return e.jsxs(G,{"data-testid":"approver-actions-stats",children:[e.jsxs(te,{children:[e.jsx(se,{children:"Approver's Actions (Filtered)"}),e.jsxs(he,{children:["Statistics based on ",t,"'s actions with current filters applied"]})]}),e.jsxs(Y,{children:[e.jsxs("div",{className:"mb-6",children:[e.jsxs("h4",{className:"text-sm font-semibold text-gray-700 mb-3 flex items-center gap-2",children:[e.jsx(at,{className:"w-4 h-4"}),"Approver's Actions"]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 gap-3",children:[e.jsxs("div",{className:"p-4 bg-green-50 rounded-lg border border-green-200",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(ve,{className:"w-5 h-5 text-green-600"}),e.jsx("span",{className:"text-xs text-green-600 font-medium",children:a.completedActions>0?`${a.approvalRate}%`:"0%"})]}),e.jsx("div",{className:"text-2xl font-bold text-green-700",children:a.approvedByApprover}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"Approved by Approver"})]}),e.jsxs("div",{className:"p-4 bg-red-50 rounded-lg border border-red-200",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(Ze,{className:"w-5 h-5 text-red-600"}),e.jsx("span",{className:"text-xs text-red-600 font-medium",children:a.completedActions>0?`${a.rejectionRate}%`:"0%"})]}),e.jsx("div",{className:"text-2xl font-bold text-red-700",children:a.rejectedByApprover}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"Rejected by Approver"})]}),e.jsxs("div",{className:"p-4 bg-yellow-50 rounded-lg border border-yellow-200",children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsx(De,{className:"w-5 h-5 text-yellow-600"})}),e.jsx("div",{className:"text-2xl font-bold text-yellow-700",children:a.pendingByApprover}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"Pending Actions"})]}),e.jsxs("div",{className:"p-4 bg-gray-50 rounded-lg border border-gray-200",children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsx(zr,{className:"w-5 h-5 text-gray-600"})}),e.jsx("div",{className:"text-2xl font-bold text-gray-700",children:a.closedByApprover}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"Closed Requests"})]}),e.jsxs("div",{className:"p-4 bg-blue-50 rounded-lg border border-blue-200",children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsx(Te,{className:"w-5 h-5 text-blue-600"})}),e.jsx("div",{className:"text-2xl font-bold text-blue-700",children:a.total}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"Total Requests"})]})]})]}),e.jsxs("div",{className:"mb-6 pt-4 border-t",children:[e.jsxs("h4",{className:"text-sm font-semibold text-gray-700 mb-3 flex items-center gap-2",children:[e.jsx(it,{className:"w-4 h-4"}),"TAT Compliance"]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:[e.jsxs("div",{className:"p-4 bg-green-50 rounded-lg border border-green-200",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(Dx,{className:"w-5 h-5 text-green-600"}),e.jsx("span",{className:"text-xs text-green-600 font-medium",children:(s==null?void 0:s.tatCompliancePercent)!==void 0?`${s.tatCompliancePercent}%`:a.completedActions>0?`${a.tatComplianceRate}%`:"N/A"})]}),e.jsx("div",{className:"text-2xl font-bold text-green-700",children:a.compliant}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"TAT Compliant"})]}),e.jsxs("div",{className:"p-4 bg-red-50 rounded-lg border border-red-200",children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsx(Re,{className:"w-5 h-5 text-red-600"})}),e.jsx("div",{className:"text-2xl font-bold text-red-700",children:a.breached}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"TAT Breached"})]}),e.jsxs("div",{className:"p-4 bg-purple-50 rounded-lg border border-purple-200",children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsx(jd,{className:"w-5 h-5 text-purple-600"})}),e.jsx("div",{className:"text-2xl font-bold text-purple-700",children:a.completedActions}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"Completed Actions"})]})]})]})]})]})}function g2({searchTerm:t,statusFilter:s,priorityFilter:a,slaComplianceFilter:r,dateRange:n,customStartDate:i,customEndDate:o,showCustomDatePicker:l,tempCustomStartDate:c,tempCustomEndDate:d,onSearchChange:m,onStatusChange:u,onPriorityChange:h,onSlaComplianceChange:x,onDateRangeChange:p,onShowCustomDatePickerChange:y,onTempStartDateChange:v,onTempEndDateChange:N,onApplyCustomDate:f,onClearFilters:b}){return e.jsxs(G,{"data-testid":"approver-performance-filters",children:[e.jsx(te,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Filters"}),e.jsx(M,{variant:"ghost",size:"sm",onClick:b,className:"text-xs","data-testid":"clear-filters-button",children:"Clear All"})]})}),e.jsx(Y,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-6 gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Yt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(xe,{placeholder:"Search requests...",value:t,onChange:j=>m(j.target.value),className:"pl-10","data-testid":"search-input"})]}),e.jsxs(we,{value:s,onValueChange:u,children:[e.jsx(Se,{"data-testid":"status-filter",children:e.jsx(Ce,{placeholder:"Status"})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"all",children:"All Status"}),e.jsx(V,{value:"pending",children:"Pending"}),e.jsx(V,{value:"approved",children:"Approved"}),e.jsx(V,{value:"rejected",children:"Rejected"}),e.jsx(V,{value:"closed",children:"Closed"})]})]}),e.jsxs(we,{value:a,onValueChange:h,children:[e.jsx(Se,{"data-testid":"priority-filter",children:e.jsx(Ce,{placeholder:"Priority"})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"all",children:"All Priority"}),e.jsx(V,{value:"express",children:"Express"}),e.jsx(V,{value:"standard",children:"Standard"})]})]}),e.jsxs(we,{value:r,onValueChange:x,children:[e.jsx(Se,{"data-testid":"sla-compliance-filter",children:e.jsx(Ce,{placeholder:"SLA Compliance"})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"all",children:"All SLA"}),e.jsx(V,{value:"compliant",children:"Compliant"}),e.jsx(V,{value:"on-track",children:"On Track"}),e.jsx(V,{value:"approaching",children:"Approaching"}),e.jsx(V,{value:"critical",children:"Critical"}),e.jsx(V,{value:"breached",children:"Breached"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qe,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(we,{value:n,onValueChange:p,children:[e.jsx(Se,{className:"flex-1","data-testid":"date-range-filter",children:e.jsx(Ce,{placeholder:"Date Range"})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"today",children:"Today"}),e.jsx(V,{value:"week",children:"This Week"}),e.jsx(V,{value:"month",children:"This Month"}),e.jsx(V,{value:"custom",children:"Custom Range"})]})]}),n==="custom"&&e.jsxs(Ds,{open:l,onOpenChange:y,children:[e.jsx(Ps,{asChild:!0,children:e.jsxs(M,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(qe,{className:"w-4 h-4"}),c&&d?`${pe(c,"MMM d")} - ${pe(d,"MMM d")}`:"Select dates"]})}),e.jsx(Es,{className:"w-auto p-4",align:"start",sideOffset:8,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(xe,{id:"start-date",type:"date",value:c?pe(c,"yyyy-MM-dd"):"",onChange:j=>{const C=j.target.value?new Date(j.target.value):void 0;C?(v(C),d&&C>d&&N(C)):v(void 0)},max:pe(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(xe,{id:"end-date",type:"date",value:d?pe(d,"yyyy-MM-dd"):"",onChange:j=>{const C=j.target.value?new Date(j.target.value):void 0;C?(N(C),c&&C{y(!1),v(i),N(o),(!i||!o)&&p("month")},"data-testid":"cancel-date-button",children:"Cancel"})]})]})})]})]})]})})]})}const f2=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Us,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:it,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:it,iconColor:"text-gray-600"}}},y2=t=>{switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:ve,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ze,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:De,iconColor:"text-yellow-600"};case"in-progress":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:De,iconColor:"text-blue-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:ve,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Te,iconColor:"text-gray-600"}}},v2=t=>{switch(t){case"breached":return{color:"bg-red-100 text-red-800 border-red-200",label:"Breached"};case"critical":return{color:"bg-orange-100 text-orange-800 border-orange-200",label:"Critical"};case"approaching":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",label:"Approaching"};case"on_track":case"on-track":return{color:"bg-green-100 text-green-800 border-green-200",label:"On Track"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",label:"N/A"}}};function b2(t){if(!t)return"N/A";try{return pe(new Date(t),"MMM d, yyyy")}catch{return"N/A"}}function j2(t){if(!t)return"N/A";try{return pe(new Date(t),"MMM d, yyyy HH:mm")}catch{return"N/A"}}function N2({requests:t,loading:s,approverName:a,currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:o,onPageChange:l}){const c=Bs();return e.jsxs(G,{"data-testid":"approver-performance-request-list",children:[e.jsxs(te,{children:[e.jsx(se,{children:"Request Details"}),e.jsxs(he,{children:["All requests handled by ",a," with applied filters"]})]}),e.jsxs(Y,{children:[s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"loading-state",children:[e.jsx(Lt,{className:"w-6 h-6 animate-spin text-gray-400"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading requests..."})]}):t.length===0?e.jsxs("div",{className:"text-center py-12 text-gray-500","data-testid":"empty-state",children:[e.jsx(Te,{className:"w-12 h-12 mx-auto mb-4 text-gray-400"}),e.jsx("p",{className:"text-sm",children:"No requests found for this approver"})]}):e.jsx("div",{className:"space-y-4",children:t.map(d=>{const m=f2(d.priority),u=y2(d.status),h=v2(d.slaStatus||""),x=m.icon,p=u.icon;return e.jsx(G,{className:"hover:shadow-md transition-shadow cursor-pointer",onClick:()=>c(`/request/${d.requestId}`),"data-testid":`request-card-${d.requestId}`,children:e.jsx(Y,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-sm text-blue-600 hover:underline","data-testid":"request-number",children:d.requestNumber}),e.jsxs(Q,{className:m.color,"data-testid":"priority-badge",children:[e.jsx(x,{className:`w-3 h-3 mr-1 ${m.iconColor}`}),d.priority]}),e.jsxs(Q,{className:u.color,"data-testid":"status-badge",children:[e.jsx(p,{className:`w-3 h-3 mr-1 ${u.iconColor}`}),d.status]}),d.approvalStatus&&e.jsx(Q,{className:d.approvalStatus==="approved"||d.approvalStatus==="APPROVED"?"bg-green-100 text-green-800 border-green-200":d.approvalStatus==="rejected"||d.approvalStatus==="REJECTED"?"bg-red-100 text-red-800 border-red-200":"bg-yellow-100 text-yellow-800 border-yellow-200","data-testid":"approval-status-badge",children:d.approvalStatus==="approved"||d.approvalStatus==="APPROVED"?e.jsxs(e.Fragment,{children:[e.jsx(ve,{className:"w-3 h-3 mr-1"}),"Approved"]}):d.approvalStatus==="rejected"||d.approvalStatus==="REJECTED"?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-3 h-3 mr-1"}),"Rejected"]}):e.jsxs(e.Fragment,{children:[e.jsx(De,{className:"w-3 h-3 mr-1"}),"Pending"]})}),d.slaStatus&&e.jsx(Q,{className:h.color,"data-testid":"sla-status-badge",children:h.label})]}),e.jsx("h3",{className:"font-medium text-gray-900 mb-1 truncate","data-testid":"request-title",children:d.title}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-xs text-gray-500 mt-2",children:[e.jsxs("span",{className:"flex items-center gap-1","data-testid":"initiator-info",children:[e.jsx(rt,{className:"w-3 h-3"}),d.initiatorName,d.initiatorDepartment&&e.jsxs("span",{className:"ml-1",children:["(",d.initiatorDepartment,")"]})]}),e.jsxs("span",{className:"flex items-center gap-1","data-testid":"submission-date",children:[e.jsx(De,{className:"w-3 h-3"}),"Submitted: ",b2(d.submissionDate)]}),d.approvalActionDate&&e.jsxs("span",{className:"flex items-center gap-1","data-testid":"action-date",children:[e.jsx(ve,{className:"w-3 h-3"}),"Action: ",j2(d.approvalActionDate)]}),e.jsxs("span",{className:"flex items-center gap-1","data-testid":"approval-level",children:[e.jsx(it,{className:"w-3 h-3"}),"Level ",d.levelNumber," of ",d.totalLevels]}),d.levelElapsedHours&&d.levelElapsedHours>0&&e.jsxs("span",{className:"flex items-center gap-1","data-testid":"tat-info",children:[e.jsx(Pi,{className:"w-3 h-3"}),nt(d.levelElapsedHours)," / ",nt(d.levelTatHours||0)," TAT"]})]})]}),e.jsx(M,{variant:"ghost",size:"sm",onClick:y=>{y.stopPropagation(),c(`/request/${d.requestId}`)},"data-testid":"view-request-button",children:e.jsx(wt,{className:"w-4 h-4"})})]})})},d.requestId)})}),n>0&&e.jsx("div",{className:"mt-6","data-testid":"pagination-container",children:e.jsx(ca,{currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:o,onPageChange:l,itemLabel:"requests",testIdPrefix:"approver-performance"})})]})]})}function w2(){const[t]=Hr(),[s,a]=g.useState(""),[r,n]=g.useState(t.get("status")||"all"),[i,o]=g.useState(t.get("priority")||"all"),[l,c]=g.useState(t.get("slaCompliance")||"all"),[d,m]=g.useState(t.get("dateRange")||"month"),[u,h]=g.useState(t.get("startDate")?new Date(t.get("startDate")):void 0),[x,p]=g.useState(t.get("endDate")?new Date(t.get("endDate")):void 0),[y,v]=g.useState(!1),[N,f]=g.useState(void 0),[b,j]=g.useState(void 0),C=g.useCallback(()=>{a(""),n("all"),o("all"),c("all"),m("month"),h(void 0),p(void 0),f(void 0),j(void 0),v(!1)},[]),R=g.useCallback(T=>{const E=T;m(E),E!=="custom"?(h(void 0),p(void 0),f(void 0),j(void 0),v(!1)):(f(u),j(x),v(!0))},[u,x]),I=g.useCallback(()=>{if(N&&b){if(N>b){const T=N;h(b),p(T),f(b),j(T)}else h(N),p(b);v(!1)}},[N,b]);return{searchTerm:s,statusFilter:r,priorityFilter:i,slaComplianceFilter:l,dateRange:d,customStartDate:u,customEndDate:x,showCustomDatePicker:y,tempCustomStartDate:N,tempCustomEndDate:b,setSearchTerm:a,setStatusFilter:n,setPriorityFilter:o,setSlaComplianceFilter:c,setDateRange:m,setCustomStartDate:h,setCustomEndDate:p,setShowCustomDatePicker:v,setTempCustomStartDate:f,setTempCustomEndDate:j,clearFilters:C,handleDateRangeChange:R,handleApplyCustomDate:I}}function C2({approverId:t,dateRange:s,customStartDate:a,customEndDate:r,statusFilter:n,priorityFilter:i,slaComplianceFilter:o,searchTerm:l,itemsPerPage:c}){const[d,m]=g.useState([]),[u,h]=g.useState(null),[x,p]=g.useState([]),[y,v]=g.useState(!0),[N,f]=g.useState(!1),[b,j]=g.useState(1),[C,R]=g.useState(1),[I,T]=g.useState(0),E=g.useRef(!0),w=g.useCallback(async()=>{if(t)try{const F=(await He.getApproverPerformance(s,1,100,a,r)).performance.find(A=>A.approverId===t);F&&h(F)}catch(L){console.error("Failed to fetch approver stats:",L)}},[t,s,a,r]),S=g.useCallback(async(L=1)=>{if(!t){v(!1);return}try{v(!0);const F=await He.getRequestsByApprover(t,L,c,s,a,r,n!=="all"?n:void 0,i!=="all"?i:void 0,o!=="all"?o:void 0,l||void 0);m(F.requests),T(F.pagination.totalRecords),R(F.pagination.totalPages),j(L);const A=await He.getRequestsByApprover(t,1,1e4,s,a,r,n!=="all"?n:void 0,i!=="all"?i:void 0,o!=="all"?o:void 0,l||void 0);p(A.requests)}catch(F){console.error("Failed to fetch requests:",F)}finally{v(!1),f(!1)}},[t,s,a,r,n,i,o,l,c]);g.useEffect(()=>{E.current&&(E.current=!1,w(),S(1))},[]),g.useEffect(()=>{E.current||(w(),S(1))},[s,a,r,n,i,o,l]);const D=g.useCallback(()=>{f(!0),w(),S(1)},[w,S]),H=g.useCallback(L=>{j(L);const F=(L-1)*c,A=F+c,k=x.slice(F,A);m(k)},[x,c]);return g.useEffect(()=>{const L=(b-1)*c,F=L+c,A=x.slice(L,F);m(A),R(Math.ceil(x.length/c)),b>Math.ceil(x.length/c)&&x.length>0&&j(1)},[x,b,c]),{requests:d,approverStats:u,allFilteredRequests:x,loading:y,refreshing:N,currentPage:b,totalPages:C,totalRecords:I,handleRefresh:D,handlePageChange:H}}function S2(t){const s=t,a=s.filter(x=>(x.approvalStatus||"").toLowerCase()==="approved").length,r=s.filter(x=>(x.approvalStatus||"").toLowerCase()==="rejected").length,n=s.filter(x=>{const p=(x.approvalStatus||"").toLowerCase();return["pending","in_progress","in-progress"].includes(p)}).length,i=s.filter(x=>(x.status||"").toLowerCase()==="closed").length,o=s.filter(x=>{const p=x.isBreached===!0||x.isBreached===1,y=(x.slaStatus||"").toLowerCase()==="breached";return p||y}).length,l=s.filter(x=>{const p=(x.approvalStatus||"").toLowerCase(),y=p==="approved"||p==="rejected",v=["pending","in_progress","in-progress"].includes(p),N=!(x.isBreached===!0||x.isBreached===1)&&(x.slaStatus||"").toLowerCase()!=="breached";return y&&N||v&&N}).length,c=a+r,d=c>0?Math.round(a/c*100):0,m=c>0?Math.round(r/c*100):0,u=s.length,h=u>0?Math.floor(l/u*100):0;return{total:s.length,approvedByApprover:a,rejectedByApprover:r,pendingByApprover:n,closedByApprover:i,breached:o,compliant:l,approvalRate:d,rejectionRate:m,tatComplianceRate:h,completedActions:c}}const Uc=10;function A2(){const[t]=Hr(),s=t.get("approverId")||"",a=t.get("approverName")||"Unknown Approver",r=w2(),n=C2({approverId:s,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,slaComplianceFilter:r.slaComplianceFilter,searchTerm:r.searchTerm,itemsPerPage:Uc}),i=g.useMemo(()=>S2(n.allFilteredRequests),[n.allFilteredRequests]);return s?e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"approver-performance-page",children:[e.jsx(h2,{approverName:a,refreshing:n.refreshing,onRefresh:n.handleRefresh}),n.approverStats&&e.jsx(p2,{approverStats:n.approverStats,calculatedStats:i}),e.jsx(x2,{approverName:a,approverStats:n.approverStats,calculatedStats:i}),e.jsx(g2,{searchTerm:r.searchTerm,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,slaComplianceFilter:r.slaComplianceFilter,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate,showCustomDatePicker:r.showCustomDatePicker,tempCustomStartDate:r.tempCustomStartDate,tempCustomEndDate:r.tempCustomEndDate,onSearchChange:r.setSearchTerm,onStatusChange:r.setStatusFilter,onPriorityChange:r.setPriorityFilter,onSlaComplianceChange:r.setSlaComplianceFilter,onDateRangeChange:r.handleDateRangeChange,onShowCustomDatePickerChange:r.setShowCustomDatePicker,onTempStartDateChange:r.setTempCustomStartDate,onTempEndDateChange:r.setTempCustomEndDate,onApplyCustomDate:r.handleApplyCustomDate,onClearFilters:r.clearFilters}),e.jsx(N2,{requests:n.requests,loading:n.loading,approverName:a,currentPage:n.currentPage,totalPages:n.totalPages,totalRecords:n.totalRecords,itemsPerPage:Uc,onPageChange:n.handlePageChange})]}):e.jsx(u2,{})}function T2(){const{user:t}=Bt(),s=()=>{var a,r;if(t!=null&&t.displayName){const n=t.displayName.split(" ").filter(Boolean);return n.length>=2?`${((a=n[0])==null?void 0:a[0])||""}${((r=n[n.length-1])==null?void 0:r[0])||""}`.toUpperCase():t.displayName.substring(0,2).toUpperCase()}return t!=null&&t.email?t.email.substring(0,2).toUpperCase():"U"};return e.jsxs("div",{className:"space-y-6 max-w-7xl mx-auto",children:[e.jsxs(G,{className:"relative overflow-hidden shadow-xl border-0",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900"}),e.jsx(Y,{className:"relative z-10 p-8 lg:p-12",children:e.jsxs("div",{className:"flex flex-col md:flex-row items-start md:items-center gap-6",children:[e.jsxs("div",{className:"relative",children:[e.jsxs(jt,{className:"h-24 w-24 ring-4 ring-white/20 shadow-xl",children:[e.jsx(Wr,{src:(t==null?void 0:t.picture)||""}),e.jsx(Nt,{className:"bg-yellow-400 text-slate-900 text-2xl font-bold",children:s()})]}),Gs(t)&&e.jsx("div",{className:"absolute -bottom-2 -right-2 bg-yellow-400 rounded-full p-1.5 shadow-lg",children:e.jsx(Gt,{className:"w-4 h-4 text-slate-900"})})]}),e.jsx("div",{className:"flex-1 text-white",children:e.jsx("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-4",children:e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold mb-2",children:(t==null?void 0:t.displayName)||(t==null?void 0:t.name)||"User Profile"}),e.jsx("p",{className:"text-lg text-gray-200 mb-3",children:(t==null?void 0:t.email)||"No email provided"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[Gs(t)&&e.jsxs(Q,{className:"bg-yellow-400 text-slate-900 hover:bg-yellow-400 font-semibold",children:[e.jsx(Gt,{className:"w-3 h-3 mr-1"}),"Administrator"]}),Ma(t)&&e.jsxs(Q,{className:"bg-blue-400 text-slate-900 hover:bg-blue-400 font-semibold",children:[e.jsx(at,{className:"w-3 h-3 mr-1"}),"Management"]}),(t==null?void 0:t.employeeId)&&e.jsxs(Q,{variant:"outline",className:"border-white/30 text-white bg-white/10",children:["ID: ",t.employeeId]})]})]})})})]})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(G,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(te,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-blue-100 rounded-lg",children:e.jsx(rt,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(se,{className:"text-lg text-gray-900",children:"Personal Information"}),e.jsx(he,{className:"text-gray-600",children:"Your personal details"})]})]})}),e.jsx(Y,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx(pd,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"Email"}),e.jsx("p",{className:"text-base text-gray-900 break-words",children:(t==null?void 0:t.email)||"Not provided"})]})]}),(t==null?void 0:t.firstName)&&e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx(rt,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"First Name"}),e.jsx("p",{className:"text-base text-gray-900",children:t.firstName})]})]}),(t==null?void 0:t.lastName)&&e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx(rt,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"Last Name"}),e.jsx("p",{className:"text-base text-gray-900",children:t.lastName})]})]}),(t==null?void 0:t.displayName)&&e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx(rt,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"Display Name"}),e.jsx("p",{className:"text-base text-gray-900",children:t.displayName})]})]}),(t==null?void 0:t.phone)&&e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx(xd,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"Phone"}),e.jsx("p",{className:"text-base text-gray-900",children:t.phone})]})]})]})})]}),e.jsxs(G,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(te,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-emerald-100 rounded-lg",children:e.jsx(Ko,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsx(se,{className:"text-lg text-gray-900",children:"Professional Information"}),e.jsx(he,{className:"text-gray-600",children:"Work-related details"})]})]})}),e.jsx(Y,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[(t==null?void 0:t.employeeId)&&e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx(rt,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"Employee ID"}),e.jsx("p",{className:"text-base text-gray-900 font-medium",children:t.employeeId})]})]}),(t==null?void 0:t.department)&&e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx(dd,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"Department"}),e.jsx("p",{className:"text-base text-gray-900",children:t.department})]})]}),(t==null?void 0:t.designation)&&e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx(Ko,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"Designation"}),e.jsx("p",{className:"text-base text-gray-900",children:t.designation})]})]}),e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx(Gt,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"Role"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Q,{variant:Gs(t)||Ma(t)?"default":"secondary",className:Gs(t)?"bg-yellow-400 text-slate-900":Ma(t)?"bg-blue-400 text-slate-900":"",children:Gs(t)?"Administrator":Ma(t)?"Management":"User"}),(Gs(t)||Ma(t))&&e.jsx(ve,{className:"w-4 h-4 text-green-600"})]})]})]})]})})]})]}),e.jsxs(G,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(te,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-purple-100 rounded-lg",children:e.jsx(qe,{className:"h-5 w-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(se,{className:"text-lg text-gray-900",children:"Account Status"}),e.jsx(he,{className:"text-gray-600",children:"Account information and activity"})]})]})}),e.jsx(Y,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 bg-green-50 rounded-lg border border-green-200",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-green-500 rounded-full",children:e.jsx(ve,{className:"w-4 h-4 text-white"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:"Account Status"}),e.jsx("p",{className:"text-xs text-gray-600",children:"Active and verified"})]})]}),e.jsx(Q,{className:"bg-green-500 hover:bg-green-600 text-white",children:"Active"})]}),(t==null?void 0:t.userId)&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"p-4 bg-gray-50 rounded-lg",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500 mb-1",children:"User ID"}),e.jsx("p",{className:"text-sm text-gray-900 font-mono break-all",children:t.userId})]}),t.employeeId&&e.jsxs("div",{className:"p-4 bg-gray-50 rounded-lg",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500 mb-1",children:"Employee ID"}),e.jsx("p",{className:"text-sm text-gray-900 font-mono",children:t.employeeId})]})]})]})})]})]})}const gr="BBb78N3tSTEw6mPbBmvEDX2bhYEDKPc_zffL-vxPV8FBSmR1qSpy9gdV8zt-WFF-q2NPpVmL4BhbUzLSHVAPjcI",k2="https://re-workflow-nt-dev.siplsolutions.com";function Un(t){const s="=".repeat((4-t.length%4)%4),a=(t+s).replace(/-/g,"+").replace(/_/g,"/"),r=window.atob(a),n=new Uint8Array(r.length);for(let i=0;i{}),s=await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Un(gr)})}else try{s=await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Un(gr)})}catch(c){console.warn("[Push] Initial subscription failed, attempting to clear and retry...");try{const d=await t.pushManager.getSubscription();d&&await d.unsubscribe().catch(()=>{}),s=await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Un(gr)})}catch(d){const m=(c==null?void 0:c.message)||(d==null?void 0:d.message)||"Unknown error";throw m.includes("push service error")||m.includes("Registration failed")?new Error("Push service error: The browser's push service rejected the subscription. This may be due to an invalid VAPID key, network issues, or browser push service problems. Please verify your VAPID key configuration and try again."):new Error(`Failed to subscribe to push notifications: ${m}`)}}}catch(l){const c=(l==null?void 0:l.message)||"Unknown error";throw c.includes("push service error")||c.includes("Registration failed")?new Error("Push service error: The browser's push service rejected the subscription. Please verify your VAPID key is correct and matches the backend configuration. If the problem persists, try clearing your browser cache and service workers."):c.includes("Invalid key")?new Error("Invalid VAPID key format. Please verify that VITE_PUBLIC_VAPID_KEY is correctly set and matches the backend VAPID_PUBLIC_KEY."):new Error(`Failed to subscribe to push notifications: ${c}`)}const a=s.toJSON(),r=((i=(n=window==null?void 0:window.localStorage)==null?void 0:n.getItem)==null?void 0:i.call(n,"accessToken"))||((o=((document==null?void 0:document.cookie)||"").match(/accessToken=([^;]+)/))==null?void 0:o[1])||"";if(!r)throw new Error("Authentication token not found. Please log in again.");try{const l=await fetch(`${k2}/api/v1/workflows/notifications/subscribe`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(a)});if(!l.ok){const d=await l.json().catch(()=>({error:"Unknown error"}));throw new Error((d==null?void 0:d.error)||(d==null?void 0:d.message)||`Server error: ${l.status}`)}const c=await l.json();if(!c.success)throw new Error(c.error||"Failed to save subscription")}catch(l){throw l instanceof Error&&l.message.includes("Failed")?l:new Error(`Failed to save subscription to server: ${(l==null?void 0:l.message)||"Network error"}`)}return s}async function P2(){if(!("Notification"in window))throw new Error("Notifications are not supported in this browser");let t=Notification.permission;if(t==="denied")throw new Error("Notification permission was denied. Please enable notifications in your browser settings and try again.");if(t==="default"&&(t=await Notification.requestPermission(),t!=="granted"))throw new Error("Notification permission was denied. Please enable notifications in your browser settings and try again.");if(t!=="granted")throw new Error("Notification permission is required. Please grant permission and try again.");let s;try{s=await R2()}catch(a){throw new Error(`Service worker registration failed: ${(a==null?void 0:a.message)||"Unknown error"}`)}try{await D2(s)}catch(a){throw a}}function ji({className:t,defaultValue:s,value:a,min:r=0,max:n=100,...i}){const o=g.useMemo(()=>Array.isArray(a)?a:Array.isArray(s)?s:[r,n],[a,s,r,n]);return e.jsxs(Tp,{"data-slot":"slider",defaultValue:s,value:a,min:r,max:n,className:oe("relative flex w-full touch-none items-center select-none data-[disabled]:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",t),...i,children:[e.jsx(kp,{"data-slot":"slider-track",className:oe("bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-4 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5"),children:e.jsx(Rp,{"data-slot":"slider-range",className:oe("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full")})}),Array.from({length:o.length},(l,c)=>e.jsx(Dp,{"data-slot":"slider-thumb",className:"border-primary bg-background ring-ring/50 block size-4 shrink-0 rounded-full border shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50"},c))]})}function E2({onConfigUpdate:t}){const[s,a]=g.useState([]),[r,n]=g.useState(!0),[i,o]=g.useState(null),[l,c]=g.useState(null),[d,m]=g.useState({}),[u,h]=g.useState(null);g.useEffect(()=>{x()},[]);const x=async()=>{var w,S;try{n(!0),c(null);const D=await Yr();a(D)}catch(D){c(((S=(w=D.response)==null?void 0:w.data)==null?void 0:S.error)||"Failed to load configurations")}finally{n(!1)}},p=async w=>{var S,D;try{o(w.configKey),c(null);const H=d[w.configKey]??w.configValue;if(w.validationRules){const L=parseFloat(H);if(w.valueType==="NUMBER"){if(w.validationRules.min!==void 0&&Lw.validationRules.max)throw new Error(`Value must be at most ${w.validationRules.max}`)}}await bt(w.configKey,H),a(L=>L.map(F=>F.configKey===w.configKey?{...F,configValue:H}:F)),m(L=>{const F={...L};return delete F[w.configKey],F}),h(`${w.displayName} updated successfully`),setTimeout(()=>h(null),3e3),t&&t()}catch(H){c(H.message||((D=(S=H.response)==null?void 0:S.data)==null?void 0:D.error)||"Failed to save configuration")}finally{o(null)}},y=async w=>{var S,D;if(confirm(`Reset "${w.displayName}" to default value?`))try{o(w.configKey),c(null),await V0(w.configKey),a(H=>H.map(L=>L.configKey===w.configKey?{...L,configValue:L.defaultValue||""}:L)),m(H=>{const L={...H};return delete L[w.configKey],L}),h(`${w.displayName} reset to default`),setTimeout(()=>h(null),3e3)}catch(H){c(((D=(S=H.response)==null?void 0:S.data)==null?void 0:D.error)||"Failed to reset configuration")}finally{o(null)}},v=(w,S)=>{m(D=>({...D,[w]:S}))},N=w=>d[w.configKey]??w.configValue,f=w=>d[w.configKey]!==void 0&&d[w.configKey]!==w.configValue,b=w=>{var H,L,F,A;const S=N(w),D=i===w.configKey;if(!w.isEditable)return e.jsxs("div",{className:"p-3 bg-slate-100 border border-slate-200 rounded-md",children:[e.jsx("p",{className:"text-sm text-slate-700 font-mono",children:w.configValue}),e.jsxs("p",{className:"text-xs text-slate-500 mt-1.5 flex items-center gap-1",children:[e.jsx(Re,{className:"w-3 h-3"}),"This setting cannot be modified"]})]});switch(w.uiComponent||w.valueType.toLowerCase()){case"toggle":return e.jsxs("div",{className:"flex items-center justify-between p-3 bg-slate-50 border border-slate-200 rounded-md hover:bg-slate-100 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`w-2 h-2 rounded-full ${S==="true"?"bg-green-500":"bg-slate-400"}`}),e.jsx("span",{className:`text-sm font-medium ${S==="true"?"text-green-700":"text-slate-600"}`,children:S==="true"?"Enabled":"Disabled"})]}),e.jsx(ts,{checked:S==="true",onCheckedChange:W=>v(w.configKey,W?"true":"false"),disabled:D})]});case"slider":const k=parseInt(S)||0,P=((H=w.validationRules)==null?void 0:H.min)||0,_=((L=w.validationRules)==null?void 0:L.max)||100;return e.jsxs("div",{className:"space-y-3 p-3 bg-slate-50 border border-slate-200 rounded-md",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-lg font-semibold text-slate-900",children:[k,"%"]}),e.jsxs("span",{className:"text-xs text-slate-500 bg-slate-100 px-2 py-1 rounded-sm border border-slate-200",children:["Range: ",P,"-",_]})]}),e.jsx(ji,{value:[k],min:P,max:_,step:1,onValueChange:([W])=>{W!==void 0&&v(w.configKey,W.toString())},disabled:D,className:"w-full"})]});case"number":return e.jsx(xe,{type:"number",value:S,onChange:W=>v(w.configKey,W.target.value),disabled:D,min:(F=w.validationRules)==null?void 0:F.min,max:(A=w.validationRules)==null?void 0:A.max,className:"font-mono border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 rounded-md transition-all shadow-sm"});case"text":case"input":default:return e.jsx(xe,{type:"text",value:S,onChange:W=>v(w.configKey,W.target.value),disabled:D,className:"font-mono border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 rounded-md transition-all shadow-sm"})}},j=w=>{switch(w){case"TAT_SETTINGS":return e.jsx(De,{className:"w-5 h-5"});case"DOCUMENT_POLICY":return e.jsx(Te,{className:"w-5 h-5"});case"NOTIFICATION_RULES":return e.jsx(Ut,{className:"w-5 h-5"});case"AI_CONFIGURATION":return e.jsx(Vr,{className:"w-5 h-5"});case"WORKFLOW_SHARING":return e.jsx(wa,{className:"w-5 h-5"});default:return e.jsx(la,{className:"w-5 h-5"})}},C=["NOTIFICATION_RULES","DASHBOARD_LAYOUT"],R=["ALLOW_EXTERNAL_SHARING"],I=s.filter(w=>!C.includes(w.configCategory)&&!R.includes(w.configKey)),T=I.reduce((w,S)=>(w[S.configCategory]||(w[S.configCategory]=[]),w[S.configCategory].push(S),w),{});if(Object.keys(T).forEach(w=>{const S=T[w];S&&S.sort((D,H)=>D.sortOrder-H.sortOrder)}),r)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Le,{className:"w-8 h-8 animate-spin text-gray-400"})});if(I.length===0)return e.jsx(G,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(Y,{className:"p-12 text-center",children:[e.jsx("div",{className:"p-4 bg-slate-100 rounded-full w-20 h-20 flex items-center justify-center mx-auto mb-4",children:e.jsx(la,{className:"w-10 h-10 text-slate-400"})}),e.jsx("p",{className:"text-slate-700 font-medium text-lg",children:"No configurations found"}),e.jsx("p",{className:"text-sm text-slate-500 mt-2 max-w-md mx-auto",children:"System configurations will appear here once they are initialized"})]})});const E=Object.keys(T);return e.jsxs("div",{className:"space-y-6",children:[u&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-green-50 to-emerald-50 border border-green-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-green-500 rounded-md",children:e.jsx(ve,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-green-900",children:u})]}),l&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-red-50 to-rose-50 border border-red-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-red-500 rounded-md",children:e.jsx(Re,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:l}),e.jsx(M,{size:"sm",variant:"ghost",onClick:()=>c(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsxs(Kr,{defaultValue:E[0],className:"w-full",children:[e.jsx(Gr,{className:"flex flex-wrap w-full bg-slate-100/80 backdrop-blur-sm p-1 gap-1 rounded-md h-auto border border-slate-200 shadow-sm",children:E.map(w=>e.jsx(pt,{value:w,className:"flex-1 min-w-[120px] text-[10px] xs:text-xs sm:text-sm font-medium py-2 sm:py-2.5 px-2 sm:px-3 rounded-sm data-[state=active]:bg-white data-[state=active]:shadow-sm data-[state=active]:text-slate-900 transition-all",children:e.jsx("span",{className:"truncate block",children:w.replace(/_/g," ")})},w))}),E.map(w=>{var S,D,H;return e.jsx(xt,{value:w,className:"space-y-4 mt-6",children:e.jsxs(G,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(te,{className:"pb-4 border-b border-slate-100",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx("div",{className:"text-white",children:j(w)})}),e.jsxs("div",{children:[e.jsx(se,{className:"text-lg font-semibold text-slate-900",children:w.replace(/_/g," ")}),e.jsxs(he,{className:"text-sm",children:[((S=T[w])==null?void 0:S.length)||0," setting",(((D=T[w])==null?void 0:D.length)||0)!==1?"s":""," available"]})]})]})}),e.jsx(Y,{className:"space-y-6",children:(H=T[w])==null?void 0:H.map(L=>e.jsxs("div",{className:"space-y-3 pb-6 border-b border-slate-100 last:border-b-0 last:pb-0 hover:bg-slate-50/50 -mx-6 px-6 py-4 rounded-md transition-colors",children:[e.jsx("div",{className:"flex items-start justify-between gap-4",children:e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5 flex-wrap",children:[e.jsx(X,{className:"text-sm font-semibold text-slate-900",children:L.displayName}),f(L)&&e.jsx(Q,{variant:"outline",className:"text-xs bg-gradient-to-r from-yellow-50 to-amber-50 text-yellow-800 border-yellow-400 font-medium shadow-sm",children:"Modified"}),L.requiresRestart&&e.jsx(Q,{variant:"outline",className:"text-xs bg-gradient-to-r from-orange-50 to-red-50 text-orange-800 border-orange-400 font-medium shadow-sm",children:"Requires Restart"})]}),L.description&&e.jsx("p",{className:"text-xs text-slate-600 mt-1 leading-relaxed",children:L.description}),L.defaultValue&&e.jsxs("p",{className:"text-xs text-slate-500 mt-2",children:["Default: ",e.jsx("code",{className:"px-2 py-0.5 bg-slate-100 text-slate-700 rounded-sm font-mono text-xs border border-slate-200",children:L.defaultValue})]})]})}),b(L),L.isEditable&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(M,{size:"sm",onClick:()=>p(L),disabled:!f(L)||i===L.configKey,className:"gap-2 bg-re-green hover:bg-re-green/90 text-white shadow-sm disabled:opacity-50 disabled:cursor-not-allowed",children:i===L.configKey?e.jsxs(e.Fragment,{children:[e.jsx(Le,{className:"w-4 h-4 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Vs,{className:"w-4 h-4"}),"Save Changes"]})}),L.defaultValue&&e.jsxs(M,{size:"sm",variant:"outline",onClick:()=>y(L),disabled:i===L.configKey,className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(Px,{className:"w-4 h-4"}),"Reset to Default"]})]})]},L.configKey))})]})},w)})]})]})}function M2(){const[t,s]=g.useState([]),[a,r]=g.useState(!0),[n,i]=g.useState(new Date().getFullYear()),[o,l]=g.useState(!1),[c,d]=g.useState(null),[m,u]=g.useState(null),[h,x]=g.useState(null),[p,y]=g.useState({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1});g.useEffect(()=>{v()},[n]);const v=async()=>{var w,S;try{r(!0),u(null);const D=await B0(n);s(D)}catch(D){u(((S=(w=D.response)==null?void 0:w.data)==null?void 0:S.error)||"Failed to load holidays")}finally{r(!1)}},N=()=>{y({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1}),d(null),l(!0)},f=w=>{y({holidayDate:w.holidayDate,holidayName:w.holidayName,description:w.description||"",holidayType:w.holidayType,isRecurring:w.isRecurring}),d(w),l(!0)},b=()=>{if(c)return;const w=new Date;return w.setDate(w.getDate()+1),w.toISOString().split("T")[0]},j=async()=>{var w,S;try{if(u(null),!p.holidayDate||!p.holidayName){u("Holiday date and name are required");return}c?(await H0(c.holidayId,p),x("Holiday updated successfully")):(await z0(p),x("Holiday created successfully")),await v(),l(!1),setTimeout(()=>x(null),3e3)}catch(D){u(((S=(w=D.response)==null?void 0:w.data)==null?void 0:S.error)||"Failed to save holiday")}},C=async w=>{var S,D;if(confirm(`Delete "${w.holidayName}"?`))try{u(null),await q0(w.holidayId),x("Holiday deleted successfully"),await v(),setTimeout(()=>x(null),3e3)}catch(H){u(((D=(S=H.response)==null?void 0:S.data)==null?void 0:D.error)||"Failed to delete holiday")}},R=w=>{switch(w){case"NATIONAL":return"bg-gradient-to-r from-red-50 to-rose-50 text-red-800 border-red-300";case"REGIONAL":return"bg-gradient-to-r from-blue-50 to-cyan-50 text-blue-800 border-blue-300";case"ORGANIZATIONAL":return"bg-gradient-to-r from-purple-50 to-violet-50 text-purple-800 border-purple-300";case"OPTIONAL":return"bg-gradient-to-r from-slate-50 to-gray-50 text-slate-700 border-slate-300"}},I=Array.from({length:5},(w,S)=>new Date().getFullYear()-1+S),T=t.reduce((w,S)=>{const D=new Date(S.holidayDate).toLocaleString("default",{month:"long"});return w[D]||(w[D]=[]),w[D].push(S),w},{}),E=Object.keys(T).sort((w,S)=>{const D=new Date(Date.parse(w+" 1, 2000")).getMonth(),H=new Date(Date.parse(S+" 1, 2000")).getMonth();return D-H});return e.jsxs("div",{className:"space-y-6",children:[h&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-green-50 to-emerald-50 border border-green-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-green-500 rounded-md",children:e.jsx(ve,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-green-900",children:h})]}),m&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-red-50 to-rose-50 border border-red-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-red-500 rounded-md",children:e.jsx(Re,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:m}),e.jsx(M,{size:"sm",variant:"ghost",onClick:()=>u(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsx(G,{className:"shadow-lg border-0 rounded-md",children:e.jsx(te,{className:"border-b border-slate-100 py-4 sm:py-5",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(qe,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(se,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Holiday Calendar"}),e.jsx(he,{className:"text-sm",children:"Manage organization holidays for TAT calculations"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 w-full sm:w-auto",children:[e.jsxs(we,{value:n.toString(),onValueChange:w=>i(parseInt(w)),children:[e.jsx(Se,{className:"w-24 sm:w-32 border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 rounded-md transition-all shadow-sm",children:e.jsx(Ce,{})}),e.jsx(Ae,{className:"rounded-md",children:I.map(w=>e.jsx(V,{value:w.toString(),children:w},w))})]}),e.jsxs(M,{onClick:N,className:"gap-2 bg-re-green hover:bg-re-green/90 text-white shadow-sm flex-1 sm:flex-initial",children:[e.jsx(Is,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Add Holiday"}),e.jsx("span",{className:"xs:hidden",children:"Add"})]})]})]})})}),a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Le,{className:"w-8 h-8 animate-spin text-gray-400"})}):t.length===0?e.jsx(G,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(Y,{className:"p-12 text-center",children:[e.jsx("div",{className:"p-4 bg-slate-100 rounded-full w-20 h-20 flex items-center justify-center mx-auto mb-4",children:e.jsx(qe,{className:"w-10 h-10 text-slate-400"})}),e.jsxs("p",{className:"text-slate-700 font-medium text-lg",children:["No holidays found for ",n]}),e.jsx("p",{className:"text-sm text-slate-500 mt-2 mb-6",children:"Add holidays to exclude them from TAT calculations"}),e.jsxs(M,{onClick:N,variant:"outline",className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(Is,{className:"w-4 h-4"}),"Add First Holiday"]})]})}):e.jsx("div",{className:"space-y-4 sm:space-y-6",children:E.map(w=>{var S,D,H;return e.jsxs(G,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(te,{className:"pb-3 sm:pb-4 border-b border-slate-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(se,{className:"text-base sm:text-lg font-semibold text-slate-900",children:[w," ",n]}),e.jsxs(he,{className:"text-xs sm:text-sm",children:[((S=T[w])==null?void 0:S.length)||0," holiday",(((D=T[w])==null?void 0:D.length)||0)!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-blue-50 rounded-md",children:e.jsx(qe,{className:"w-4 h-4 text-blue-600"})})]})}),e.jsx(Y,{className:"space-y-3 pt-4",children:(H=T[w])==null?void 0:H.map(L=>e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3 sm:gap-4 p-3 sm:p-4 bg-slate-50 border border-slate-200 rounded-md hover:bg-slate-100 hover:border-slate-300 transition-all shadow-sm",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[e.jsx("p",{className:"font-semibold text-slate-900 text-sm sm:text-base truncate",children:L.holidayName}),e.jsx(Q,{variant:"outline",className:`${R(L.holidayType)} text-[10px] sm:text-xs font-medium shadow-sm`,children:L.holidayType}),L.isRecurring&&e.jsx(Q,{variant:"outline",className:"bg-gradient-to-r from-indigo-50 to-purple-50 text-indigo-700 border-indigo-300 text-[10px] sm:text-xs font-medium shadow-sm",children:"Recurring"})]}),e.jsx("p",{className:"text-xs sm:text-sm text-slate-600 font-medium",children:om(L.holidayDate)}),L.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-1.5 line-clamp-2",children:L.description})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-2 self-end sm:self-auto",children:[e.jsxs(M,{size:"sm",variant:"ghost",onClick:()=>f(L),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(Ex,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]}),e.jsxs(M,{size:"sm",variant:"ghost",onClick:()=>C(L),className:"gap-1.5 text-red-600 hover:text-red-700 hover:bg-red-50 border border-transparent hover:border-red-200 text-xs sm:text-sm",children:[e.jsx(Ei,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Delete"})]})]})]},L.holidayId))})]},w)})}),e.jsx(ot,{open:o,onOpenChange:l,children:e.jsxs(Je,{className:"sm:max-w-[550px] max-h-[90vh] rounded-lg flex flex-col p-0",children:[e.jsx(lt,{className:"pb-4 border-b border-slate-100 px-6 pt-6 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-lg shadow-md",children:e.jsx(qe,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(et,{className:"text-xl font-semibold text-slate-900",children:c?"Edit Holiday":"Add New Holiday"}),e.jsx(Zt,{className:"text-sm text-slate-600 mt-1",children:c?"Update holiday information":"Add a new holiday to the calendar for TAT calculations"})]})]})}),e.jsxs("div",{className:"space-y-5 py-6 px-6 overflow-y-auto flex-1 min-h-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(X,{htmlFor:"date",className:"text-sm font-semibold text-slate-900 flex items-center gap-1",children:["Date ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(xe,{id:"date",type:"date",value:p.holidayDate,onChange:w=>y({...p,holidayDate:w.target.value}),min:b(),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:c?"Select the holiday date":"Select the holiday date (minimum: tomorrow)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(X,{htmlFor:"name",className:"text-sm font-semibold text-slate-900 flex items-center gap-1",children:["Holiday Name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(xe,{id:"name",placeholder:"e.g., Diwali, Republic Day, Christmas",value:p.holidayName,onChange:w=>y({...p,holidayName:w.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Enter the official name of the holiday"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(X,{htmlFor:"description",className:"text-sm font-semibold text-slate-900",children:["Description ",e.jsx("span",{className:"text-slate-400 font-normal text-xs",children:"(Optional)"})]}),e.jsx(xe,{id:"description",placeholder:"Add additional details about this holiday...",value:p.description,onChange:w=>y({...p,description:w.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Optional description or notes about the holiday"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"type",className:"text-sm font-semibold text-slate-900",children:"Holiday Type"}),e.jsxs(we,{value:p.holidayType,onValueChange:w=>y({...p,holidayType:w}),children:[e.jsx(Se,{id:"type",className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm",children:e.jsx(Ce,{})}),e.jsxs(Ae,{className:"rounded-lg",children:[e.jsx(V,{value:"NATIONAL",className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-red-500"}),e.jsx("span",{children:"National"})]})}),e.jsx(V,{value:"REGIONAL",className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-blue-500"}),e.jsx("span",{children:"Regional"})]})}),e.jsx(V,{value:"ORGANIZATIONAL",className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-purple-500"}),e.jsx("span",{children:"Organizational"})]})}),e.jsx(V,{value:"OPTIONAL",className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-slate-500"}),e.jsx("span",{children:"Optional"})]})})]})]}),e.jsx("p",{className:"text-xs text-slate-500",children:"Select the category of this holiday"})]}),e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-gradient-to-br from-slate-50 to-slate-100/50 border-2 border-slate-200 rounded-lg hover:border-slate-300 hover:bg-slate-100 transition-all cursor-pointer group",onClick:()=>y({...p,isRecurring:!p.isRecurring}),children:[e.jsx("input",{type:"checkbox",id:"recurring",checked:p.isRecurring,onChange:w=>y({...p,isRecurring:w.target.checked}),className:"mt-0.5 rounded border-slate-300 text-re-green focus:ring-2 focus:ring-re-green/20 focus:ring-offset-0 w-4 h-4 cursor-pointer"}),e.jsxs("div",{className:"flex-1",children:[e.jsx(X,{htmlFor:"recurring",className:"font-semibold cursor-pointer text-sm text-slate-900 block mb-1",children:"Recurring Holiday"}),e.jsx("p",{className:"text-xs text-slate-600",children:"This holiday will automatically repeat every year on the same date"})]})]})]}),e.jsxs(Tt,{className:"gap-3 pt-4 border-t border-slate-100 px-6 pb-6 flex-shrink-0",children:[e.jsx(M,{variant:"outline",onClick:()=>l(!1),className:"h-11 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:"Cancel"}),e.jsxs(M,{onClick:j,disabled:!p.holidayDate||!p.holidayName,className:"h-11 bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx(qe,{className:"w-4 h-4 mr-2"}),c?"Update Holiday":"Add Holiday"]})]})]})})]})}function I2(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function _2(){const[t,s]=g.useState(""),[a,r]=g.useState([]),[n,i]=g.useState(!1),[o,l]=g.useState(null),[c,d]=g.useState("USER"),[m,u]=g.useState(!1),[h,x]=g.useState(null),[p,y]=g.useState([]),[v,N]=g.useState(!1),[f,b]=g.useState({admins:0,management:0,users:0}),[j,C]=g.useState("ELEVATED"),[R,I]=g.useState(1),[T,E]=g.useState(1),[w,S]=g.useState(0),D=10,H=g.useRef(null),L=g.useRef(null),F=g.useCallback(I2(async q=>{var z,re,K;if(!q||q.length<2){r([]);return}i(!0);try{const J=((z=(await Wt.searchUsers(q,20)).data)==null?void 0:z.data)||[];r(J)}catch(B){console.error("Search failed:",B),x({type:"error",text:((K=(re=B.response)==null?void 0:re.data)==null?void 0:K.message)||"Failed to search users"})}finally{i(!1)}},300),[]),A=q=>{const z=q.target.value;s(z),F(z)},k=async q=>{l(q),s(q.email),r([]);const z=p.find(re=>re.email.toLowerCase()===q.email.toLowerCase()||re.userId===q.userId);if(z&&z.role)d(z.role);else try{const K=(await Wt.getAllUsers()).find(B=>B.email&&B.email.toLowerCase()===q.email.toLowerCase()||B.userId&&B.userId===q.userId);K&&K.role?d(K.role):d("USER")}catch(re){console.error("Failed to check user role:",re),d("USER")}},P=async()=>{var q,z;if(!o||!c){x({type:"error",text:"Please select a user and role"});return}u(!0),x(null);try{await Wt.assignRole(o.email,c,o),x({type:"success",text:`Successfully assigned ${c} role to ${o.displayName||o.email}`}),l(null),s(""),d("USER"),await _(),await W()}catch(re){console.error("Role assignment failed:",re),x({type:"error",text:((z=(q=re.response)==null?void 0:q.data)==null?void 0:z.error)||"Failed to assign role"})}finally{u(!1)}},_=async(q=R)=>{var z,re,K,B,J,ue;N(!0);try{const be=await Wt.getUsersByRole(j,q,D),Ie=((re=(z=be.data)==null?void 0:z.data)==null?void 0:re.users)||[],Ve=(B=(K=be.data)==null?void 0:K.data)==null?void 0:B.pagination,Oe=(ue=(J=be.data)==null?void 0:J.data)==null?void 0:ue.summary;y(Ie),Ve&&(I(Ve.currentPage),E(Ve.totalPages),S(Ve.totalUsers)),Oe&&b({admins:Oe.ADMIN||0,management:Oe.MANAGEMENT||0,users:Oe.USER||0})}catch(be){console.error("Failed to fetch users:",be)}finally{N(!1)}},W=async()=>{var q,z,re,K,B,J;try{const ue=await Wt.getRoleStatistics(),be=((z=(q=ue.data)==null?void 0:q.data)==null?void 0:z.statistics)||((re=ue.data)==null?void 0:re.statistics)||[];b({admins:parseInt(((K=be.find(Ie=>Ie.role==="ADMIN"))==null?void 0:K.count)||"0"),management:parseInt(((B=be.find(Ie=>Ie.role==="MANAGEMENT"))==null?void 0:B.count)||"0"),users:parseInt(((J=be.find(Ie=>Ie.role==="USER"))==null?void 0:J.count)||"0")})}catch(ue){console.error("Failed to fetch statistics:",ue)}};g.useEffect(()=>{_(1),W()},[j]);const Z=q=>{C(q),I(1)},ae=q=>{_(q)},$=q=>{C(q),I(1),requestAnimationFrame(()=>{const z=L.current;z&&z.scrollIntoView({behavior:"smooth",block:"start"})})};g.useEffect(()=>{const q=z=>{H.current&&!H.current.contains(z.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",q),()=>{document.removeEventListener("mousedown",q)}},[a]);const ne=q=>{switch(q){case"ADMIN":return"bg-yellow-400 text-slate-800";case"MANAGEMENT":return"bg-blue-400 text-slate-800";default:return"bg-gray-400 text-slate-800"}},me=q=>{switch(q){case"ADMIN":return e.jsx(ua,{className:"w-5 h-5 text-slate-800"});case"MANAGEMENT":return e.jsx(at,{className:"w-5 h-5 text-slate-800"});default:return e.jsx(rt,{className:"w-5 h-5 text-slate-800"})}};return e.jsxs(G,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(te,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(Mx,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(se,{className:"text-lg font-semibold text-gray-900",children:"User Role Management"}),e.jsx(he,{className:"text-sm text-gray-600",children:"Search for users, assign roles, and manage user permissions across the system"})]})]})}),e.jsxs(Y,{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 sm:gap-6",children:[e.jsx(G,{className:`border-2 bg-gradient-to-br from-yellow-50 to-yellow-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${j==="ADMIN"?"border-yellow-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"admin-count-card",onClick:()=>$("ADMIN"),children:e.jsx(Y,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wide",children:"Administrators"}),e.jsx("p",{className:"text-3xl font-bold text-gray-900 mt-2","data-testid":"admin-count",children:f.admins}),e.jsx("p",{className:"text-xs text-yellow-700 mt-1 font-semibold",children:j==="ADMIN"?"✓ Viewing":"Click to view"})]}),e.jsx("div",{className:"p-3 bg-gradient-to-br from-yellow-400 to-yellow-500 rounded-xl shadow-md",children:e.jsx(ua,{className:"w-6 h-6 text-slate-800"})})]})})}),e.jsx(G,{className:`border-2 bg-gradient-to-br from-blue-50 to-blue-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${j==="MANAGEMENT"?"border-blue-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"management-count-card",onClick:()=>$("MANAGEMENT"),children:e.jsx(Y,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wide",children:"Management"}),e.jsx("p",{className:"text-3xl font-bold text-gray-900 mt-2","data-testid":"management-count",children:f.management}),e.jsx("p",{className:"text-xs text-blue-700 mt-1 font-semibold",children:j==="MANAGEMENT"?"✓ Viewing":"Click to view"})]}),e.jsx("div",{className:"p-3 bg-gradient-to-br from-blue-400 to-blue-500 rounded-xl shadow-md",children:e.jsx(at,{className:"w-6 h-6 text-slate-800"})})]})})}),e.jsx(G,{className:`border-2 bg-gradient-to-br from-gray-50 to-gray-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${j==="USER"?"border-gray-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"user-count-card",onClick:()=>$("USER"),children:e.jsx(Y,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wide",children:"Regular Users"}),e.jsx("p",{className:"text-3xl font-bold text-gray-900 mt-2","data-testid":"user-count",children:f.users}),e.jsx("p",{className:"text-xs text-gray-700 mt-1 font-semibold",children:j==="USER"?"✓ Viewing":"Click to view"})]}),e.jsx("div",{className:"p-3 bg-gradient-to-br from-gray-400 to-gray-500 rounded-xl shadow-md",children:e.jsx(rt,{className:"w-6 h-6 text-slate-800"})})]})})})]}),e.jsx(yt,{}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-gray-900 mb-1",children:"Assign User Role"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Search for a user in Okta and assign them a role"})]}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",ref:H,children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Search User"}),e.jsxs("div",{className:"relative",children:[e.jsx(Yt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none"}),e.jsx(xe,{type:"text",placeholder:"Type name or email address...",value:t,onChange:A,className:"pl-10 pr-10 border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20","data-testid":"user-search-input"}),n&&e.jsx(Le,{className:"absolute right-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-re-green animate-spin"})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Start typing to search across all Okta users"}),a.length>0&&e.jsxs("div",{className:"border border-purple-200 rounded-lg shadow-lg bg-white max-h-60 overflow-y-auto",children:[e.jsx("div",{className:"sticky top-0 bg-purple-50 px-4 py-2 border-b border-purple-100",children:e.jsxs("p",{className:"text-xs font-semibold text-purple-700",children:[a.length," user",a.length>1?"s":""," found"]})}),e.jsx("div",{className:"p-2",children:a.map(q=>e.jsxs("button",{onClick:()=>k(q),className:"w-full text-left p-2 hover:bg-purple-50 rounded-lg transition-colors mb-1 last:mb-0","data-testid":`user-result-${q.email}`,children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:q.displayName||q.email}),e.jsx("p",{className:"text-xs text-gray-600",children:q.email}),q.department&&e.jsxs("p",{className:"text-xs text-gray-500",children:[q.department,q.designation?` • ${q.designation}`:""]})]},q.userId))})]})]}),o&&e.jsx("div",{className:"border-2 border-slate-300 bg-gradient-to-br from-slate-100 to-slate-50 rounded-lg p-4 shadow-sm",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-gradient-to-br from-slate-700 to-slate-500 flex items-center justify-center text-white font-bold shadow-md",children:(o.displayName||o.email).charAt(0).toUpperCase()}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-slate-900",children:o.displayName||o.email}),e.jsx("p",{className:"text-sm text-slate-600",children:o.email}),o.department&&e.jsxs("p",{className:"text-xs text-slate-500 mt-1",children:[o.department,o.designation?` • ${o.designation}`:""]})]})]}),e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>{l(null),s("")},className:"hover:bg-slate-200",children:"Clear"})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Select Role"}),e.jsxs(we,{value:c,onValueChange:q=>d(q),children:[e.jsx(Se,{className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20","data-testid":"role-select",children:e.jsx(Ce,{placeholder:"Select role"})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rt,{className:"w-4 h-4 text-gray-600"}),e.jsx("span",{children:"User - Regular access"})]})}),e.jsx(V,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(at,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Management - Read all data"})]})}),e.jsx(V,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ua,{className:"w-4 h-4 text-yellow-600"}),e.jsx("span",{children:"Administrator - Full access"})]})})]})]})]}),e.jsx(M,{onClick:P,disabled:!o||m,className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"assign-role-button",children:m?e.jsxs(e.Fragment,{children:[e.jsx(Le,{className:"w-4 h-4 mr-2 animate-spin"}),"Assigning Role..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Gt,{className:"w-4 h-4 mr-2"}),"Assign Role"]})}),h&&e.jsx("div",{className:`border-2 rounded-lg p-4 ${h.type==="success"?"border-green-200 bg-green-50":"border-red-200 bg-red-50"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[h.type==="success"?e.jsx(ve,{className:"w-5 h-5 text-green-600 shrink-0 mt-0.5"}):e.jsx(Re,{className:"w-5 h-5 text-red-600 shrink-0 mt-0.5"}),e.jsx("p",{className:`text-sm ${h.type==="success"?"text-green-800":"text-red-800"}`,children:h.text})]})})]})]}),e.jsx(yt,{}),e.jsxs("div",{ref:L,children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-gray-900 mb-1",children:"User Management"}),e.jsxs("p",{className:"text-sm text-gray-600",children:["View and manage user roles (",w," ",j!=="ALL"&&j!=="ELEVATED"?j.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(we,{value:j,onValueChange:Z,children:[e.jsx(Se,{className:"w-[200px] h-10 border rounded-lg border-gray-300",children:e.jsx(Ce,{placeholder:"Filter by role"})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"ELEVATED",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gt,{className:"w-4 h-4 text-purple-600"}),e.jsxs("span",{children:["Elevated (",f.admins+f.management,")"]})]})}),e.jsx(V,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ua,{className:"w-4 h-4 text-yellow-600"}),e.jsxs("span",{children:["Admins (",f.admins,")"]})]})}),e.jsx(V,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(at,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Management (",f.management,")"]})]})}),e.jsx(V,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rt,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["Users (",f.users,")"]})]})}),e.jsx(V,{value:"ALL",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(at,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["All Users (",f.admins+f.management+f.users,")"]})]})})]})]})})]}),e.jsx("div",{className:"pt-2",children:v?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsx(Le,{className:"w-6 h-6 animate-spin text-purple-500 mb-2"}),e.jsx("p",{className:"text-sm text-gray-500",children:"Loading users..."})]}):p.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-gray-100 flex items-center justify-center mx-auto mb-3",children:e.jsx(at,{className:"w-6 h-6 text-gray-400"})}),e.jsx("p",{className:"font-medium text-gray-700",children:"No users found"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:j==="ELEVATED"?"Assign ADMIN or MANAGEMENT roles to see users here":"No users match the selected filter"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-2","data-testid":"users-list",children:p.map(q=>e.jsx("div",{className:"border border-gray-200 hover:border-re-green hover:shadow-sm transition-all rounded-lg bg-white p-4","data-testid":`user-${q.email}`,children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx("div",{className:`w-10 h-10 rounded-lg ${ne(q.role)} flex items-center justify-center shadow-sm`,children:me(q.role)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-semibold text-gray-900 truncate",children:q.displayName}),e.jsx("p",{className:"text-sm text-gray-600 truncate",children:q.email}),q.department&&e.jsxs("p",{className:"text-xs text-gray-500 mt-1 truncate",children:[q.department,q.designation?` • ${q.designation}`:""]})]})]}),e.jsx(Q,{className:`${ne(q.role)} shrink-0`,"data-testid":`role-badge-${q.role}`,children:q.role})]})},q.userId))}),T>1&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("div",{className:"text-sm text-gray-600",children:["Showing ",(R-1)*D+1," to ",Math.min(R*D,w)," of ",w," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(M,{variant:"outline",size:"sm",onClick:()=>ae(R-1),disabled:R===1,"data-testid":"prev-page-button",children:"Previous"}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,T)},(q,z)=>{let re;return T<=5||R<=3?re=z+1:R>=T-2?re=T-4+z:re=R-2+z,e.jsx(M,{variant:R===re?"default":"outline",size:"sm",onClick:()=>ae(re),className:`w-9 h-9 p-0 ${R===re?"bg-re-green hover:bg-re-green/90 text-white":""}`,"data-testid":`page-${re}-button`,children:re},re)})}),e.jsx(M,{variant:"outline",size:"sm",onClick:()=>ae(R+1),disabled:R===T,"data-testid":"next-page-button",children:"Next"})]})]})]})})]})]})]})}function L2({open:t,onClose:s,success:a,message:r}){return e.jsx(ot,{open:t,onOpenChange:s,children:e.jsxs(Je,{className:"sm:max-w-md",children:[e.jsxs(lt,{children:[e.jsxs(et,{className:"flex items-center gap-2",children:[e.jsx(Ut,{className:"w-5 h-5 text-blue-600"}),"Push Notifications"]}),e.jsx(Zt,{className:"sr-only",children:a?"Push notifications have been successfully enabled for your account.":"There was an error enabling push notifications. Please review the details below."})]}),e.jsx("div",{className:"py-6",children:e.jsx("div",{className:"flex flex-col items-center text-center",children:a?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mb-4",children:e.jsx(ve,{className:"w-8 h-8 text-green-600"})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Notifications Enabled!"}),e.jsx("p",{className:"text-sm text-gray-600 max-w-sm",children:r||"You will now receive push notifications for workflow updates, approvals, and TAT alerts."})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-red-100 flex items-center justify-center mb-4",children:e.jsx(Ze,{className:"w-8 h-8 text-red-600"})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Subscription Failed"}),e.jsx("p",{className:"text-sm text-gray-600 max-w-sm mb-4 whitespace-pre-line",children:r||"Unable to enable push notifications. Please check your browser settings and try again."}),e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-3 text-left w-full",children:[e.jsx("p",{className:"text-xs text-amber-800 font-medium mb-2",children:"💡 Troubleshooting Tips:"}),e.jsxs("ul",{className:"text-xs text-amber-700 space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"Check if notifications are blocked in browser settings"}),e.jsx("li",{children:"Ensure your browser supports push notifications"}),e.jsx("li",{children:"Try refreshing the page and enabling again"})]})]})]})})}),e.jsx(Tt,{children:e.jsx(M,{onClick:s,className:"w-full",children:a?"Done":"Close"})})]})})}function F2(){const{user:t}=Bt(),s=Gs(t),[a,r]=g.useState(!1),[n,i]=g.useState(!1),[o,l]=g.useState(),[c,d]=g.useState(!1),m=async()=>{d(!0),r(!1);try{if(!("Notification"in window)){i(!1),l("Notifications are not supported in this browser. Please use a modern browser like Chrome, Firefox, or Edge."),r(!0),d(!1);return}let u=Notification.permission;if(u==="denied"){i(!1),l(`Notification permission was previously denied. To enable notifications: 1. Click the lock icon (🔒) or info icon (ℹ️) in your browser's address bar 2. Find "Notifications" in the permissions list 3. Change it from "Block" to "Allow" 4. Refresh this page and try again Alternatively, you can enable notifications in your browser's site settings.`),r(!0),d(!1);return}if(u==="default"&&(u=await Notification.requestPermission(),u==="denied")){i(!1),l(`Notification permission was denied. To enable notifications: 1. Click the lock icon (🔒) or info icon (ℹ️) in your browser's address bar 2. Find "Notifications" in the permissions list 3. Change it from "Block" to "Allow" 4. Refresh this page and try again`),r(!0),d(!1);return}if(u!=="granted"){i(!1),l("Notification permission is required to enable push notifications. Please grant permission and try again."),r(!0),d(!1);return}await P2(),i(!0),l("Push notifications have been successfully enabled! You will now receive notifications for workflow updates, approvals, and TAT alerts."),r(!0)}catch(u){console.error("[Settings] Error enabling notifications:",u),i(!1);const h=(u==null?void 0:u.message)||"Unknown error occurred";l(h.includes("permission")?"Notification permission was denied. Please enable notifications in your browser settings and try again.":h.includes("Service worker")?"Service worker registration failed. Please refresh the page and try again.":h.includes("token")?"Authentication required. Please log in again and try enabling notifications.":`Unable to enable push notifications: ${h}`),r(!0)}finally{d(!1)}};return e.jsxs("div",{className:"min-h-screen pb-8",children:[e.jsxs("div",{className:"max-w-7xl mx-auto space-y-6",children:[e.jsxs(G,{className:"relative overflow-hidden shadow-2xl border-0 rounded-2xl",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900"}),e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_top_right,_var(--tw-gradient-stops))] from-yellow-400/20 via-transparent to-transparent"}),e.jsx(Y,{className:"relative z-10 p-6 sm:p-8 lg:p-12",children:e.jsxs("div",{className:"flex items-center gap-4 sm:gap-6",children:[e.jsx("div",{className:"w-14 h-14 sm:w-16 sm:h-16 bg-gradient-to-br from-yellow-400 to-yellow-500 rounded-2xl flex items-center justify-center shadow-xl transform hover:scale-105 transition-transform",children:e.jsx(la,{className:"w-7 h-7 sm:w-8 sm:h-8 text-slate-900"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl sm:text-3xl lg:text-4xl font-bold text-white mb-1 sm:mb-2",children:"Settings"}),e.jsx("p",{className:"text-sm sm:text-base lg:text-lg text-gray-300",children:"Manage your account and preferences"})]})]})})]}),s?e.jsxs(Kr,{defaultValue:"user",className:"w-full",children:[e.jsxs(Gr,{className:"grid w-full grid-cols-2 lg:grid-cols-4 mb-8 bg-slate-100 p-1 rounded-xl h-auto gap-1",children:[e.jsxs(pt,{value:"user",className:"flex items-center justify-center gap-2 py-3 rounded-lg data-[state=active]:bg-white data-[state=active]:shadow-md transition-all",children:[e.jsx(la,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"User Settings"}),e.jsx("span",{className:"sm:hidden",children:"User"})]}),e.jsxs(pt,{value:"roles",className:"flex items-center justify-center gap-2 py-3 rounded-lg data-[state=active]:bg-white data-[state=active]:shadow-md transition-all",children:[e.jsx(Gt,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"User Roles"}),e.jsx("span",{className:"sm:hidden",children:"Roles"})]}),e.jsxs(pt,{value:"system",className:"flex items-center justify-center gap-2 py-3 rounded-lg data-[state=active]:bg-white data-[state=active]:shadow-md transition-all",children:[e.jsx(Nd,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Configuration"}),e.jsx("span",{className:"sm:hidden",children:"Config"})]}),e.jsxs(pt,{value:"holidays",className:"flex items-center justify-center gap-2 py-3 rounded-lg data-[state=active]:bg-white data-[state=active]:shadow-md transition-all",children:[e.jsx(qe,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Holidays"}),e.jsx("span",{className:"sm:hidden",children:"Holidays"})]})]}),e.jsxs("div",{className:"w-full min-h-[600px]",children:[e.jsx(xt,{value:"user",className:"mt-0 space-y-0",children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6",children:[e.jsxs(G,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(te,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(Ut,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(se,{className:"text-lg font-semibold text-gray-900",children:"Notifications"}),e.jsx(he,{className:"text-sm text-gray-600",children:"Manage notification preferences"})]})]})}),e.jsx(Y,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs(M,{onClick:m,disabled:c,className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx(Ut,{className:`w-4 h-4 mr-2 ${c?"animate-pulse":""}`}),c?"Enabling...":"Enable Push Notifications"]})})})]}),e.jsxs(G,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(te,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(qn,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(se,{className:"text-lg font-semibold text-gray-900",children:"Security"}),e.jsx(he,{className:"text-sm text-gray-600",children:"Password and security settings"})]})]})}),e.jsx(Y,{children:e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-md border border-gray-200",children:e.jsx("p",{className:"text-sm text-gray-600 text-center",children:"Security settings will be available soon"})})})})]}),e.jsxs(G,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(te,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(Go,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(se,{className:"text-lg font-semibold text-gray-900",children:"Appearance"}),e.jsx(he,{className:"text-sm text-gray-600",children:"Theme and display preferences"})]})]})}),e.jsx(Y,{children:e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-md border border-gray-200",children:e.jsx("p",{className:"text-sm text-gray-600 text-center",children:"Appearance settings will be available soon"})})})})]}),e.jsxs(G,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(te,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(Gt,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(se,{className:"text-lg font-semibold text-gray-900",children:"Preferences"}),e.jsx(he,{className:"text-sm text-gray-600",children:"Application preferences"})]})]})}),e.jsx(Y,{children:e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-xl border border-gray-200",children:e.jsx("p",{className:"text-sm text-gray-600 text-center",children:"User preferences will be available soon"})})})})]})]})}),e.jsx(xt,{value:"roles",className:"mt-0",children:e.jsx(_2,{})}),e.jsx(xt,{value:"system",className:"mt-0",children:e.jsx(E2,{})}),e.jsx(xt,{value:"holidays",className:"mt-0",children:e.jsx(M2,{})})]})]}):e.jsx(e.Fragment,{children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6",children:[e.jsxs(G,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(te,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(Ut,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(se,{className:"text-lg font-semibold text-gray-900",children:"Notifications"}),e.jsx(he,{className:"text-sm text-gray-600",children:"Manage notification preferences"})]})]})}),e.jsx(Y,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs(M,{onClick:m,disabled:c,className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx(Ut,{className:`w-4 h-4 mr-2 ${c?"animate-pulse":""}`}),c?"Enabling...":"Enable Push Notifications"]})})})]}),e.jsxs(G,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(te,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(qn,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(se,{className:"text-lg font-semibold text-gray-900",children:"Security"}),e.jsx(he,{className:"text-sm text-gray-600",children:"Password and security settings"})]})]})}),e.jsx(Y,{children:e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-md border border-gray-200",children:e.jsx("p",{className:"text-sm text-gray-600 text-center",children:"Security settings will be available soon"})})})})]}),e.jsxs(G,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(te,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(Go,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(se,{className:"text-lg font-semibold text-gray-900",children:"Appearance"}),e.jsx(he,{className:"text-sm text-gray-600",children:"Theme and display preferences"})]})]})}),e.jsx(Y,{children:e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-md border border-gray-200",children:e.jsx("p",{className:"text-sm text-gray-600 text-center",children:"Appearance settings will be available soon"})})})})]}),e.jsxs(G,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(te,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(Gt,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(se,{className:"text-lg font-semibold text-gray-900",children:"Preferences"}),e.jsx(he,{className:"text-sm text-gray-600",children:"Application preferences"})]})]})}),e.jsx(Y,{children:e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-md border border-gray-200",children:e.jsx("p",{className:"text-sm text-gray-600 text-center",children:"User preferences will be available soon"})})})})]})]})})]}),e.jsx(L2,{open:a,onClose:()=>r(!1),success:n,message:o})]})}function O2({onNavigate:t}){const[s,a]=g.useState([]),[r,n]=g.useState(!0),[i,o]=g.useState(1),[l,c]=g.useState(1),[d,m]=g.useState(0),[u,h]=g.useState("all"),[x,p]=g.useState(!1),y=20,v=async(E=i,w=u==="unread")=>{var S,D;try{n(E===1);const H=await Js.list({page:E,limit:y,unreadOnly:w}),L=((S=H.data)==null?void 0:S.notifications)||[],F=((D=H.data)==null?void 0:D.total)||0;a(L),m(F),c(Math.ceil(F/y))}catch(H){console.error("[Notifications] Failed to fetch:",H)}finally{n(!1),p(!1)}};g.useEffect(()=>{v(1,u==="unread")},[u]);const N=async E=>{var w;try{if(E.isRead||(await Js.markAsRead(E.notificationId),a(S=>S.map(D=>D.notificationId===E.notificationId?{...D,isRead:!0}:D))),E.actionUrl&&t){const S=(w=E.metadata)==null?void 0:w.requestNumber;if(S){let D=`request/${S}`;(E.notificationType==="mention"||E.notificationType==="comment"||E.notificationType==="worknote")&&(D+="?tab=worknotes"),t(D)}}}catch(S){console.error("[Notifications] Error handling notification click:",S)}},f=async()=>{try{p(!0),await Js.markAllAsRead(),await v(i,u==="unread")}catch(E){console.error("[Notifications] Error marking all as read:",E),p(!1)}},b=async E=>{try{await Js.delete(E),a(w=>w.filter(S=>S.notificationId!==E)),m(w=>w-1)}catch(w){console.error("[Notifications] Error deleting notification:",w)}},j=()=>{p(!0),v(i,u==="unread")},C=E=>{E<1||E>l||(o(E),v(E,u==="unread"))},R=E=>{const w="w-6 h-6";switch(E){case"mention":case"comment":return e.jsx(ws,{className:`${w} text-blue-600`});case"worknote":return e.jsx(Te,{className:`${w} text-purple-600`});case"assignment":return e.jsx($r,{className:`${w} text-indigo-600`});case"approval":return e.jsx(ve,{className:`${w} text-green-600`});case"rejection":return e.jsx(Ze,{className:`${w} text-red-600`});case"tat_alert":return e.jsx(De,{className:`${w} text-orange-600`});case"tat_breach":return e.jsx(Re,{className:`${w} text-red-600`});case"tat_breach_initiator":return e.jsx(is,{className:`${w} text-amber-600`});default:return e.jsx(Ut,{className:`${w} text-gray-600`})}},I=E=>{switch(E==null?void 0:E.toUpperCase()){case"URGENT":return"bg-red-100 text-red-800 border-red-200";case"HIGH":return"bg-orange-100 text-orange-800 border-orange-200";case"MEDIUM":return"bg-blue-100 text-blue-800 border-blue-200";default:return"bg-gray-100 text-gray-800 border-gray-200"}},T=s.filter(E=>!E.isRead).length;return e.jsxs("div",{className:"max-w-6xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-3xl font-bold text-gray-900 flex items-center gap-3",children:[e.jsx(Ut,{className:"w-8 h-8 text-blue-600"}),"Notifications"]}),e.jsxs("p",{className:"text-gray-600 mt-1",children:[d," total notification",d!==1?"s":"",T>0&&` • ${T} unread`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(M,{variant:"outline",size:"sm",onClick:j,disabled:x,className:"gap-2",children:[e.jsx(Lt,{className:`w-4 h-4 ${x?"animate-spin":""}`}),"Refresh"]}),T>0&&e.jsxs(M,{variant:"outline",size:"sm",onClick:f,disabled:x,className:"gap-2",children:[e.jsx(Ix,{className:"w-4 h-4"}),"Mark All Read"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(M,{variant:u==="all"?"default":"outline",size:"sm",onClick:()=>{h("all"),o(1)},children:"All Notifications"}),e.jsxs(M,{variant:u==="unread"?"default":"outline",size:"sm",onClick:()=>{h("unread"),o(1)},children:["Unread",T>0&&e.jsx(Q,{className:"ml-2 bg-red-500 text-white",children:T})]})]}),e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsx(se,{children:"Recent Activity"}),e.jsx(he,{children:"Stay updated with all your workflow activities and mentions"})]}),e.jsx(Y,{children:r?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"})}):s.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Ut,{className:"w-16 h-16 text-gray-300 mx-auto mb-4"}),e.jsx("p",{className:"text-lg font-medium text-gray-900 mb-2",children:"No notifications"}),e.jsx("p",{className:"text-sm text-gray-500",children:u==="unread"?"You're all caught up! No unread notifications.":"You don't have any notifications yet."})]}):e.jsx("div",{className:"space-y-2",children:s.map(E=>{var w;return e.jsx("div",{className:`p-4 rounded-lg border transition-all cursor-pointer hover:shadow-md ${E.isRead?"bg-white border-gray-200 hover:bg-gray-50":"bg-blue-50 border-blue-200 hover:bg-blue-100"}`,onClick:()=>N(E),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"shrink-0 mt-0.5",children:R(E.notificationType)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-1",children:[e.jsx("h4",{className:`text-sm ${E.isRead?"font-semibold":"font-bold"} text-gray-900`,children:E.title}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[E.priority&&E.priority!=="LOW"&&e.jsx(Q,{variant:"outline",className:`text-xs ${I(E.priority)}`,children:E.priority}),!E.isRead&&e.jsx("div",{className:"w-2 h-2 rounded-full bg-blue-600"})]})]}),e.jsx("p",{className:"text-sm text-gray-700 mb-2 line-clamp-2",children:E.message}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:[rd(new Date(E.createdAt),{addSuffix:!0}),((w=E.metadata)==null?void 0:w.requestNumber)&&e.jsxs("span",{className:"ml-2",children:["• ",E.metadata.requestNumber]})]}),e.jsx(M,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-600",onClick:S=>{S.stopPropagation(),b(E.notificationId)},children:e.jsx(Ei,{className:"w-3.5 h-3.5"})})]})]})]})},E.notificationId)})})})]}),!r&&l>1&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-gray-600",children:["Showing ",(i-1)*y+1," to ",Math.min(i*y,d)," of ",d," notifications"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(M,{variant:"outline",size:"sm",onClick:()=>C(i-1),disabled:i===1,children:[e.jsx(bd,{className:"w-4 h-4"}),"Previous"]}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,l)},(E,w)=>{let S;return l<=5||i<=3?S=w+1:i>=l-2?S=l-4+w:S=i-2+w,e.jsx(M,{variant:i===S?"default":"outline",size:"sm",className:"w-9 h-9 p-0",onClick:()=>C(S),children:S},S)})}),e.jsxs(M,{variant:"outline",size:"sm",onClick:()=>C(i+1),disabled:i===l,children:["Next",e.jsx(Di,{className:"w-4 h-4"})]})]})]})]})}function $2({onBack:t}){return e.jsx("div",{className:"flex items-center justify-between","data-testid":"detailed-reports-header",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(M,{variant:"outline",onClick:t,className:"inline-flex items-center gap-2","data-testid":"back-button",children:[e.jsx(_s,{className:"w-4 h-4 mr-2"}),"Back to Dashboard"]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-purple-100 rounded-lg",children:e.jsx(Te,{className:"h-6 w-6 text-purple-600"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900",children:"Detailed Reports"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Comprehensive workflow and activity reports"})]})]})]})})}function Io({dateRange:t,customStartDate:s,customEndDate:a,showCustomDatePicker:r,tempCustomStartDate:n,tempCustomEndDate:i,onDateRangeChange:o,onShowCustomDatePickerChange:l,onStartDateChange:c,onEndDateChange:d,onApply:m,onCancel:u,testIdPrefix:h="date-filter"}){const x=s&&a?`${pe(s,"MMM d, yyyy")} - ${pe(a,"MMM d, yyyy")}`:"Select dates";return e.jsxs("div",{className:"flex items-center gap-2","data-testid":`${h}-container`,children:[e.jsx(qe,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(we,{value:t,onValueChange:o,"data-testid":`${h}-select`,children:[e.jsx(Se,{className:"w-[160px]",children:e.jsx(Ce,{placeholder:"Date Range"})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"today",children:"Today"}),e.jsx(V,{value:"week",children:"This Week"}),e.jsx(V,{value:"month",children:"This Month"}),e.jsx(V,{value:"custom",children:"Custom Range"})]})]}),t==="custom"&&e.jsxs(Ds,{open:r,onOpenChange:l,children:[e.jsx(Ps,{asChild:!0,children:e.jsxs(M,{variant:"outline",size:"sm",className:"gap-2","data-testid":`${h}-custom-trigger`,children:[e.jsx(qe,{className:"w-4 h-4"}),x]})}),e.jsx(Es,{className:"w-auto p-4",align:"start",sideOffset:8,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:`${h}-start-date`,className:"text-sm font-medium",children:"Start Date"}),e.jsx(xe,{id:`${h}-start-date`,type:"date",value:n?pe(n,"yyyy-MM-dd"):"",onChange:p=>{const y=p.target.value?new Date(p.target.value):void 0;c(y)},max:pe(new Date,"yyyy-MM-dd"),className:"w-full","data-testid":`${h}-start-input`})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:`${h}-end-date`,className:"text-sm font-medium",children:"End Date"}),e.jsx(xe,{id:`${h}-end-date`,type:"date",value:i?pe(i,"yyyy-MM-dd"):"",onChange:p=>{const y=p.target.value?new Date(p.target.value):void 0;d(y)},min:n?pe(n,"yyyy-MM-dd"):void 0,max:pe(new Date,"yyyy-MM-dd"),className:"w-full","data-testid":`${h}-end-input`})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(M,{size:"sm",onClick:m,disabled:!n||!i,className:"flex-1 bg-re-green hover:bg-re-green/90","data-testid":`${h}-apply-button`,children:"Apply"}),e.jsx(M,{size:"sm",variant:"outline",onClick:u,"data-testid":`${h}-cancel-button`,children:"Cancel"})]})]})})]})]})}function U2(t){switch(t){case"Login":return"text-blue-700 bg-blue-100 border-blue-200";case"Created Request":return"text-purple-700 bg-purple-100 border-purple-200";case"Approved Request":return"text-emerald-700 bg-emerald-100 border-emerald-200";case"Rejected Request":return"text-red-700 bg-red-100 border-red-200";case"Added Comment":return"text-amber-700 bg-amber-100 border-amber-200";case"Viewed Request":return"text-gray-700 bg-gray-100 border-gray-200";case"Uploaded Document":return"text-indigo-700 bg-indigo-100 border-indigo-200";default:return"text-gray-700 bg-gray-100 border-gray-200"}}function wh(t){switch(t){case"high":return"bg-red-100 text-red-800 border-red-200";case"medium":return"bg-orange-100 text-orange-800 border-orange-200";case"low":return"bg-green-100 text-green-800 border-green-200";default:return"bg-gray-100 text-gray-800 border-gray-200"}}function Ch(t){switch(t){case"Delayed":return"text-red-700 bg-red-100 border-red-200";case"On Time":return"text-emerald-700 bg-emerald-100 border-emerald-200";case"Pending":return"bg-orange-100 text-orange-800 border-orange-200";default:return"bg-gray-100 text-gray-800 border-gray-200"}}function V2(t){return t>=20?"bg-red-600":t>=10?"bg-orange-500":"bg-amber-500"}function B2({lifecycleRequests:t,loading:s,loadingPage:a,error:r,pagination:n,dateRange:i,customStartDate:o,customEndDate:l,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,exporting:u,onDateRangeChange:h,onShowCustomDatePickerChange:x,onStartDateChange:p,onEndDateChange:y,onApplyCustomDate:v,onCancelCustomDate:N,onPageChange:f,onExport:b,onViewRequest:j}){return e.jsxs(G,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"request-lifecycle-report",children:[e.jsxs(te,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-blue-100 rounded-lg",children:e.jsx(as,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(se,{className:"text-lg text-gray-900",children:"Request Lifecycle Report"}),e.jsx(he,{className:"text-gray-600",children:"End-to-end workflow status including all approval levels, approvers, dates, and TAT compliance"})]})]}),e.jsxs(M,{variant:"outline",size:"sm",className:"gap-2",onClick:b,disabled:u,"data-testid":"export-lifecycle-button",children:[e.jsx(ns,{className:"w-4 h-4"}),u?"Exporting...":"Download CSV"]})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(Io,{dateRange:i,customStartDate:o,customEndDate:l,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,onDateRangeChange:h,onShowCustomDatePickerChange:x,onStartDateChange:p,onEndDateChange:y,onApply:v,onCancel:N,testIdPrefix:"lifecycle"})})]}),e.jsxs(Y,{children:[s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"lifecycle-loading",children:[e.jsx(Le,{className:"w-6 h-6 animate-spin text-gray-400"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading lifecycle data..."})]}):r?e.jsxs("div",{className:"flex items-center justify-center py-12 text-red-600","data-testid":"lifecycle-error",children:[e.jsx(Re,{className:"w-5 h-5 mr-2"}),e.jsx("span",{className:"text-sm",children:r})]}):t.length===0?e.jsx("div",{className:"text-center py-12 text-gray-500","data-testid":"lifecycle-empty",children:e.jsx("p",{className:"text-sm",children:"No lifecycle data available"})}):e.jsx("div",{className:"space-y-4",children:t.map(C=>e.jsx("div",{className:"border rounded-xl overflow-hidden","data-testid":`lifecycle-request-${C.id}`,children:e.jsx("div",{className:"p-4 bg-gradient-to-r from-gray-50 to-white hover:bg-gray-100 cursor-pointer transition-all",onClick:()=>j(C.requestId||C.id),children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"flex items-center gap-4",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("button",{onClick:R=>{R.stopPropagation(),j(C.requestId||C.id)},className:"font-semibold text-sm text-blue-600 hover:text-blue-800 hover:underline cursor-pointer transition-colors","data-testid":`lifecycle-request-link-${C.id}`,children:C.id}),e.jsx(Q,{className:wh(C.priority),"data-testid":`lifecycle-priority-${C.id}`,children:C.priority}),e.jsx(Q,{className:Ch(C.status),"data-testid":`lifecycle-status-${C.id}`,children:C.status})]}),e.jsx("p",{className:"text-sm text-gray-700",children:C.title}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["Initiated by ",e.jsx("span",{className:"font-medium",children:C.initiator})," on ",C.initDate]}),C.currentStage&&!C.currentStage.includes("Level")&&e.jsxs("p",{className:"text-xs text-gray-400 mt-0.5",children:["Stage: ",C.currentStage]})]})}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Current Stage"}),e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:C.currentStage}),e.jsxs("p",{className:"text-xs text-gray-400 mt-0.5",children:["(Level ",C.currentLevel,"/",C.totalLevels,")"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Overall TAT"}),e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:C.overallTAT}),C.breachCount>0&&e.jsxs("p",{className:"text-xs text-red-500 mt-0.5",children:[C.breachCount," breach",C.breachCount>1?"es":""]})]}),e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>j(C.requestId||C.id),className:"gap-1.5","data-testid":`lifecycle-view-button-${C.id}`,children:e.jsx(Di,{className:"w-4 h-4"})})]})]})})},C.id))}),n.totalPages>1&&e.jsxs("div",{className:"flex items-center justify-between p-4 border-t relative","data-testid":"lifecycle-pagination",children:[a&&e.jsx("div",{className:"absolute inset-0 bg-white/80 flex items-center justify-center z-10 rounded-b-lg",children:e.jsx(Le,{className:"w-5 h-5 animate-spin text-gray-400"})}),e.jsxs("p",{className:"text-sm text-gray-600",children:["Showing page ",n.page," of ",n.totalPages," (",n.totalRecords," total records)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(M,{variant:"outline",size:"sm",onClick:()=>f(n.page-1),disabled:n.page<=1||a,"data-testid":"lifecycle-pagination-prev",children:"Previous"}),e.jsx(M,{variant:"outline",size:"sm",onClick:()=>f(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"lifecycle-pagination-next",children:"Next"})]})]})]})]})}function _o({className:t,...s}){return e.jsx("div",{"data-slot":"table-container",className:"relative w-full overflow-x-auto",children:e.jsx("table",{"data-slot":"table",className:oe("w-full caption-bottom text-sm",t),...s})})}function Lo({className:t,...s}){return e.jsx("thead",{"data-slot":"table-header",className:oe("[&_tr]:border-b",t),...s})}function Fo({className:t,...s}){return e.jsx("tbody",{"data-slot":"table-body",className:oe("[&_tr:last-child]:border-0",t),...s})}function oa({className:t,...s}){return e.jsx("tr",{"data-slot":"table-row",className:oe("hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",t),...s})}function gt({className:t,...s}){return e.jsx("th",{"data-slot":"table-head",className:oe("text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",t),...s})}function dt({className:t,...s}){return e.jsx("td",{"data-slot":"table-cell",className:oe("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",t),...s})}function z2({activityLog:t,loading:s,loadingPage:a,error:r,pagination:n,dateRange:i,customStartDate:o,customEndDate:l,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,filterCategory:u,filterSeverity:h,exporting:x,onDateRangeChange:p,onShowCustomDatePickerChange:y,onStartDateChange:v,onEndDateChange:N,onApplyCustomDate:f,onCancelCustomDate:b,onCategoryChange:j,onSeverityChange:C,onClearFilters:R,onPageChange:I,onExport:T,onViewRequest:E}){const w=u!=="all"||h!=="all"||i!=="month"||o||l;return e.jsxs(G,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"user-activity-log-report",children:[e.jsxs(te,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-indigo-100 rounded-lg",children:e.jsx(_x,{className:"h-5 w-5 text-indigo-600"})}),e.jsxs("div",{children:[e.jsx(se,{className:"text-lg text-gray-900",children:"User Activity Log Report"}),e.jsx(he,{className:"text-gray-600",children:"Consolidated user actions and activity history"})]})]}),e.jsxs(M,{variant:"outline",size:"sm",className:"gap-2",onClick:T,disabled:x,"data-testid":"export-activity-button",children:[e.jsx(ns,{className:"w-4 h-4"}),x?"Exporting...":"Download CSV"]})]}),e.jsxs("div",{className:"mt-4 flex items-center gap-4 flex-wrap",children:[e.jsx(Io,{dateRange:i,customStartDate:o,customEndDate:l,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,onDateRangeChange:p,onShowCustomDatePickerChange:y,onStartDateChange:v,onEndDateChange:N,onApply:f,onCancel:b,testIdPrefix:"activity"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-sm text-gray-600 whitespace-nowrap",children:"Category:"}),e.jsxs(we,{value:u,onValueChange:j,"data-testid":"activity-category-filter",children:[e.jsx(Se,{className:"w-40",children:e.jsx(Ce,{placeholder:"All Categories"})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"all",children:"All Categories"}),e.jsx(V,{value:"WORKFLOW",children:"Workflow"}),e.jsx(V,{value:"COLLABORATION",children:"Collaboration"}),e.jsx(V,{value:"DOCUMENT",children:"Document"}),e.jsx(V,{value:"AUTHENTICATION",children:"Authentication"}),e.jsx(V,{value:"SYSTEM",children:"System"}),e.jsx(V,{value:"OTHER",children:"Other"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-sm text-gray-600 whitespace-nowrap",children:"Severity:"}),e.jsxs(we,{value:h,onValueChange:C,"data-testid":"activity-severity-filter",children:[e.jsx(Se,{className:"w-40",children:e.jsx(Ce,{placeholder:"All Severities"})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"all",children:"All Severities"}),e.jsx(V,{value:"INFO",children:"Info"}),e.jsx(V,{value:"WARNING",children:"Warning"}),e.jsx(V,{value:"ERROR",children:"Error"}),e.jsx(V,{value:"CRITICAL",children:"Critical"})]})]})]}),w&&e.jsx(M,{variant:"ghost",size:"sm",onClick:R,className:"text-xs","data-testid":"activity-clear-filters",children:"Clear Filters"})]})]}),e.jsx(Y,{children:s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"activity-loading",children:[e.jsx(Le,{className:"w-6 h-6 animate-spin text-gray-400"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading activity data..."})]}):r?e.jsxs("div",{className:"flex items-center justify-center py-12 text-red-600","data-testid":"activity-error",children:[e.jsx(Re,{className:"w-5 h-5 mr-2"}),e.jsx("span",{className:"text-sm",children:r})]}):t.length===0?e.jsx("div",{className:"text-center py-12 text-gray-500","data-testid":"activity-empty",children:e.jsx("p",{className:"text-sm",children:"No activity data available"})}):e.jsxs("div",{className:"rounded-lg border",children:[e.jsxs(_o,{children:[e.jsx(Lo,{children:e.jsxs(oa,{className:"bg-gray-50",children:[e.jsx(gt,{className:"font-semibold",children:"Timestamp"}),e.jsx(gt,{className:"font-semibold",children:"User"}),e.jsx(gt,{className:"font-semibold",children:"Action"}),e.jsx(gt,{className:"font-semibold",children:"Details"}),e.jsx(gt,{className:"font-semibold",children:"IP Address"}),e.jsx(gt,{className:"font-semibold",children:"Request ID"})]})}),e.jsx(Fo,{children:t.map((S,D)=>e.jsxs(oa,{className:"hover:bg-gray-50","data-testid":`activity-row-${D}`,children:[e.jsx(dt,{className:"text-xs font-medium",children:S.timestamp}),e.jsx(dt,{className:"text-sm",children:S.user}),e.jsx(dt,{children:e.jsx(Q,{className:U2(S.action),"data-testid":`activity-action-${D}`,children:S.action})}),e.jsx(dt,{className:"text-sm text-gray-600",children:S.details}),e.jsx(dt,{className:"text-xs font-mono text-gray-500",children:S.ip&&S.ip!=="N/A"?e.jsx("span",{title:S.userAgent||"",children:S.ip}):e.jsx("span",{className:"text-gray-400 italic",title:"IP address not yet captured",children:"N/A"})}),e.jsx(dt,{children:S.requestId!=="-"&&S.requestId!=="System Login"?e.jsx("button",{onClick:()=>{const H=S.requestId;H&&E(H)},className:"hover:underline","data-testid":`activity-request-link-${D}`,children:e.jsx(Q,{variant:"outline",className:"text-xs cursor-pointer hover:bg-blue-50 hover:border-blue-300 transition-colors",children:S.requestId})}):e.jsx("span",{className:"text-xs text-gray-400",children:"-"})})]},D))})]}),n.totalPages>1&&e.jsxs("div",{className:"flex items-center justify-between p-4 border-t relative","data-testid":"activity-pagination",children:[a&&e.jsx("div",{className:"absolute inset-0 bg-white/80 flex items-center justify-center z-10 rounded-b-lg",children:e.jsx(Le,{className:"w-5 h-5 animate-spin text-gray-400"})}),e.jsxs("p",{className:"text-sm text-gray-600",children:["Showing page ",n.page," of ",n.totalPages," (",n.totalRecords," total records)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(M,{variant:"outline",size:"sm",onClick:()=>I(n.page-1),disabled:n.page<=1||a,"data-testid":"activity-pagination-prev",children:"Previous"}),e.jsx(M,{variant:"outline",size:"sm",onClick:()=>I(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"activity-pagination-next",children:"Next"})]})]})]})})]})}function H2({agingWorkflows:t,loading:s,loadingPage:a,error:r,pagination:n,threshold:i,thresholdError:o,dateRange:l,customStartDate:c,customEndDate:d,showCustomDatePicker:m,tempCustomStartDate:u,tempCustomEndDate:h,searchQuery:x,exporting:p,onThresholdChange:y,onThresholdBlur:v,onDateRangeChange:N,onShowCustomDatePickerChange:f,onStartDateChange:b,onEndDateChange:j,onApplyCustomDate:C,onCancelCustomDate:R,onSearchChange:I,onPageChange:T,onExport:E,onViewRequest:w}){return e.jsxs(G,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"workflow-aging-report",children:[e.jsxs(te,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-amber-100 rounded-lg",children:e.jsx(Pi,{className:"h-5 w-5 text-amber-600"})}),e.jsxs("div",{children:[e.jsx(se,{className:"text-lg text-gray-900",children:"Workflow Aging Report"}),e.jsx(he,{className:"text-gray-600",children:"Workflows exceeding aging threshold"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-sm text-gray-600 whitespace-nowrap",children:"Threshold:"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{type:"number",min:"1",value:i,onChange:S=>y(S.target.value),onBlur:v,className:`w-24 ${o?"border-red-500 focus:border-red-500 focus:ring-red-500":""}`,placeholder:"Days","data-testid":"aging-threshold-input"}),e.jsx("span",{className:"text-sm text-gray-600 whitespace-nowrap",children:"days"})]}),o&&e.jsx("span",{className:"text-xs text-red-600",children:o})]})]}),e.jsxs(Q,{variant:"outline",className:"font-semibold","data-testid":"aging-total-badge",children:[n.totalRecords," workflows"]}),e.jsxs(M,{variant:"outline",size:"sm",className:"gap-2",onClick:E,disabled:p,"data-testid":"export-aging-button",children:[e.jsx(ns,{className:"w-4 h-4"}),p?"Exporting...":"Download CSV"]})]})]}),e.jsxs("div",{className:"mt-4 flex items-center gap-4 flex-wrap",children:[e.jsx(Io,{dateRange:l,customStartDate:c,customEndDate:d,showCustomDatePicker:m,tempCustomStartDate:u,tempCustomEndDate:h,onDateRangeChange:N,onShowCustomDatePickerChange:f,onStartDateChange:b,onEndDateChange:j,onApply:C,onCancel:R,testIdPrefix:"aging"}),e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(Yt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(xe,{placeholder:"Search by Request ID, Title, or Initiator...",value:x,onChange:S=>I(S.target.value),className:"pl-10","data-testid":"aging-search-input"})]})]})]}),e.jsx(Y,{children:s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"aging-loading",children:[e.jsx(Le,{className:"w-6 h-6 animate-spin text-gray-400"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading aging data..."})]}):r?e.jsxs("div",{className:"flex items-center justify-center py-12 text-red-600","data-testid":"aging-error",children:[e.jsx(Re,{className:"w-5 h-5 mr-2"}),e.jsx("span",{className:"text-sm",children:r})]}):t.length===0?e.jsx("div",{className:"text-center py-12 text-gray-500","data-testid":"aging-empty",children:e.jsxs("p",{className:"text-sm",children:["No workflows found exceeding ",i," days threshold"]})}):e.jsxs("div",{className:"rounded-lg border",children:[e.jsxs(_o,{children:[e.jsx(Lo,{children:e.jsxs(oa,{className:"bg-gray-50",children:[e.jsx(gt,{className:"font-semibold",children:"Request ID"}),e.jsx(gt,{className:"font-semibold",children:"Title"}),e.jsx(gt,{className:"font-semibold",children:"Initiator"}),e.jsx(gt,{className:"font-semibold",children:"Start Date"}),e.jsx(gt,{className:"font-semibold",children:"Days Open"}),e.jsx(gt,{className:"font-semibold",children:"Current Stage"}),e.jsx(gt,{className:"font-semibold",children:"Assigned To"}),e.jsx(gt,{className:"font-semibold",children:"Priority"}),e.jsx(gt,{className:"font-semibold",children:"Status"})]})}),e.jsx(Fo,{children:t.map(S=>e.jsxs(oa,{className:"hover:bg-gray-50","data-testid":`aging-workflow-${S.id}`,children:[e.jsx(dt,{className:"font-medium text-sm",children:e.jsx("button",{onClick:()=>w(S.requestId||S.id),className:"text-blue-600 hover:text-blue-800 hover:underline cursor-pointer transition-colors","data-testid":`aging-request-link-${S.id}`,children:S.id})}),e.jsx(dt,{className:"text-sm",children:S.title}),e.jsx(dt,{className:"text-sm",children:S.initiator}),e.jsx(dt,{className:"text-sm text-gray-600",children:S.startDate}),e.jsx(dt,{children:e.jsxs(Q,{className:`${V2(S.daysOpen)} text-white border-transparent`,"data-testid":`aging-days-${S.id}`,children:[S.daysOpen," days",e.jsx("span",{className:"ml-1 text-xs opacity-75",children:"(business)"})]})}),e.jsx(dt,{className:"text-sm",children:S.currentStage}),e.jsx(dt,{className:"text-sm",children:S.assignedTo&&S.assignedTo!=="N/A"?S.assignedTo:e.jsx("span",{className:"text-gray-400 italic",title:"Assigned approver not available",children:"N/A"})}),e.jsx(dt,{children:e.jsx(Q,{className:wh(S.priority),"data-testid":`aging-priority-${S.id}`,children:S.priority})}),e.jsx(dt,{children:e.jsx(Q,{className:Ch(S.status),"data-testid":`aging-status-${S.id}`,children:S.status})})]},S.id))})]}),n.totalPages>1&&e.jsxs("div",{className:"flex items-center justify-between p-4 border-t relative","data-testid":"aging-pagination",children:[a&&e.jsx("div",{className:"absolute inset-0 bg-white/80 flex items-center justify-center z-10 rounded-b-lg",children:e.jsx(Le,{className:"w-5 h-5 animate-spin text-gray-400"})}),e.jsxs("p",{className:"text-sm text-gray-600",children:["Showing page ",n.page," of ",n.totalPages," (",n.totalRecords," total records)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(M,{variant:"outline",size:"sm",onClick:()=>T(n.page-1),disabled:n.page<=1||a,"data-testid":"aging-pagination-prev",children:"Previous"}),e.jsx(M,{variant:"outline",size:"sm",onClick:()=>T(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"aging-pagination-next",children:"Next"})]})]})]})})]})}function Vn(t="month"){const[s,a]=g.useState(t),[r,n]=g.useState(void 0),[i,o]=g.useState(void 0),[l,c]=g.useState(!1),[d,m]=g.useState(void 0),[u,h]=g.useState(void 0),x=g.useCallback(j=>{const C=j;a(C),C!=="custom"?(n(void 0),o(void 0),m(void 0),h(void 0),c(!1)):(m(r),h(i),c(!0))},[r,i]),p=g.useCallback(()=>{if(d&&u){if(d>u){const j=d;n(u),o(j),m(u),h(j)}else n(d),o(u);c(!1)}},[d,u]),y=g.useCallback(()=>{c(!1),m(r),h(i),(!r||!i)&&(n(void 0),o(void 0),a("month"))},[r,i]),v=g.useCallback(j=>{j?(m(j),u&&j>u&&h(j)):m(void 0)},[u]),N=g.useCallback(j=>{j?(h(j),d&&jr&&i?`${pe(r,"MMM d, yyyy")} - ${pe(i,"MMM d, yyyy")}`:"Select dates",[r,i]),b=g.useCallback(()=>{a("month"),n(void 0),o(void 0),c(!1),m(void 0),h(void 0)},[]);return{dateRange:s,customStartDate:r,customEndDate:i,showCustomDatePicker:l,tempCustomStartDate:d,tempCustomEndDate:u,setShowCustomDatePicker:c,handleDateRangeChange:x,handleApplyCustomDate:p,handleCancelCustomDate:y,handleStartDateChange:v,handleEndDateChange:N,getDisplayDateRange:f,reset:b}}function q2(t){if(!t&&t!==0)return"N/A";const s=8;if(t0?`${a}d ${nt(r)}`:`${a}d`}function Sh(t){if(!t)return"N/A";try{return new Date(t).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return t}}function Xs(t){if(!t)return"N/A";try{const s=new Date(t),a=s.getFullYear(),r=String(s.getMonth()+1).padStart(2,"0"),n=String(s.getDate()).padStart(2,"0"),i=String(s.getHours()).padStart(2,"0"),o=String(s.getMinutes()).padStart(2,"0");return`${a}-${r}-${n} ${i}:${o}`}catch{return t}}function Ah(t,s){const a=(t||"").toLowerCase();return a.includes("created")||a.includes("create")?"Created Request":a.includes("approval")||a.includes("approved")?"Approved Request":a.includes("rejection")||a.includes("rejected")?"Rejected Request":a.includes("comment")?"Added Comment":a.includes("view")||a.includes("viewed")?"Viewed Request":a.includes("upload")||a.includes("document")?"Uploaded Document":a.includes("login")?"Login":t||"Activity"}const W2=10;function K2({dateRange:t,customStartDate:s,customEndDate:a}){const[r,n]=g.useState([]),[i,o]=g.useState(!0),[l,c]=g.useState(!1),[d,m]=g.useState(null),[u,h]=g.useState({page:1,totalPages:1,totalRecords:0}),x=g.useRef(!0),p=g.useCallback(async(y=1)=>{const v=y===1&&x.current;try{v?o(!0):c(!0),m(null);const N=await He.getLifecycleReport(y,W2,t,s,a),f=N.lifecycleData.map(b=>{const j=q2(b.overallTATHours);return{id:b.requestNumber,requestId:b.requestId,title:b.title,priority:b.priority||"medium",status:b.status,initiator:b.initiatorName||"Unknown",initDate:Sh(b.submissionDate),currentStage:b.currentStageName||`Level ${b.currentLevel}`,overallTAT:j,currentLevel:b.currentLevel,totalLevels:b.totalLevels,breachCount:b.breachCount||0}});n(f),h({page:N.pagination.currentPage,totalPages:N.pagination.totalPages,totalRecords:N.pagination.totalRecords})}catch(N){console.error("Failed to fetch lifecycle data:",N),m((N==null?void 0:N.message)||"Failed to load lifecycle data")}finally{v?o(!1):c(!1)}v&&(x.current=!1)},[t,s,a]);return g.useEffect(()=>{t==="custom"&&(!s||!a)||p(1)},[t,s,a]),{lifecycleRequests:r,loading:i,loadingPage:l,error:d,pagination:u,fetchData:p}}const G2=20;function Y2({dateRange:t,customStartDate:s,customEndDate:a,filterCategory:r,filterSeverity:n}){const[i,o]=g.useState([]),[l,c]=g.useState(!0),[d,m]=g.useState(!1),[u,h]=g.useState(null),[x,p]=g.useState({page:1,totalPages:1,totalRecords:0}),y=g.useRef(!0),v=g.useCallback(async(N=1)=>{const f=N===1&&y.current;try{f?c(!0):m(!0),h(null);const b=await He.getActivityLogReport(N,G2,t,void 0,void 0,r&&r!=="all"?r:void 0,n&&n!=="all"?n:void 0,s,a),j=b.activities.map(C=>{const R=Ah(C.type||"",C.details),I=(C.type||"").toLowerCase()==="login"||C.requestId==="00000000-0000-0000-0000-000000000001"||C.requestId==="SYSTEM_LOGIN",T=I?C.details||"User login":C.requestTitle||C.requestNumber||C.details||"N/A";return{timestamp:C.timestamp?Sh(C.timestamp):"N/A",user:C.userName||"Unknown",action:R,details:T,ip:C.ipAddress||"N/A",userAgent:C.userAgent||null,requestId:I?"System Login":C.requestNumber||C.requestId||"-",userId:C.userId}});o(j),p({page:b.pagination.currentPage,totalPages:b.pagination.totalPages,totalRecords:b.pagination.totalRecords})}catch(b){console.error("Failed to fetch activity data:",b),h((b==null?void 0:b.message)||"Failed to load activity data")}finally{f?c(!1):m(!1)}f&&(y.current=!1)},[r,n,t,s,a]);return g.useEffect(()=>{t==="custom"&&(!s||!a)||v(1)},[r,n,t,s,a]),{activityLog:i,loading:l,loadingPage:d,error:u,pagination:x,fetchData:v}}const Z2=20;function X2({threshold:t,dateRange:s,customStartDate:a,customEndDate:r,searchQuery:n=""}){const[i,o]=g.useState([]),[l,c]=g.useState(!0),[d,m]=g.useState(!1),[u,h]=g.useState(null),[x,p]=g.useState({page:1,totalPages:1,totalRecords:0}),y=g.useRef(!0),v=g.useCallback(async(f=1)=>{const b=f===1&&y.current;try{b?c(!0):m(!0),h(null);const j=parseInt(t,10);if(isNaN(j)||j<1){h("Please enter a valid threshold (minimum 1 day)");return}const C=await He.getWorkflowAgingReport(j,f,Z2,s,a,r),R=C.agingData.map(I=>({id:I.requestNumber||I.requestId,requestId:I.requestId,title:I.title,initiator:I.initiatorName||"Unknown",startDate:I.submissionDate?new Date(I.submissionDate).toLocaleDateString():"N/A",daysOpen:I.daysOpen,currentStage:I.currentStageName||`Level ${I.currentLevel}`,assignedTo:I.currentApproverName||"N/A",priority:I.priority||"medium",status:I.status||"pending"}));o(R),p({page:C.pagination.currentPage,totalPages:C.pagination.totalPages,totalRecords:C.pagination.totalRecords})}catch(j){console.error("Failed to fetch aging data:",j),h((j==null?void 0:j.message)||"Failed to load aging data")}finally{b?c(!1):m(!1)}b&&(y.current=!1)},[t,s,a,r]),N=g.useMemo(()=>i.filter(f=>{var j,C,R;if(!n)return!0;const b=n.toLowerCase();return((j=f.id)==null?void 0:j.toLowerCase().includes(b))||((C=f.title)==null?void 0:C.toLowerCase().includes(b))||((R=f.initiator)==null?void 0:R.toLowerCase().includes(b))}),[i,n]);return g.useEffect(()=>{s==="custom"&&(!a||!r)||v(1)},[t,s,a,r]),{agingWorkflows:N,loading:l,loadingPage:d,error:u,pagination:x,fetchData:v}}function Q2(t="7"){const[s,a]=g.useState(t),[r,n]=g.useState(null),i=g.useCallback(l=>{if(l===""){a(""),n(null);return}const c=parseInt(l,10);isNaN(c)||c<1?(n("Minimum threshold is 1 day"),a(l)):(n(null),a(l))},[]),o=g.useCallback(()=>{(s===""||isNaN(parseInt(s,10))||parseInt(s,10)<1)&&(a("1"),n(null))},[s]);return{threshold:s,thresholdError:r,setThreshold:a,handleThresholdChange:i,handleThresholdBlur:o}}async function J2(t,s,a){const r=await He.getLifecycleReport(1,1e4,t,s,a),n=[["Request Number","Title","Priority","Overall Status","Initiator","Submission Date","Closure Date","Total Levels","Current Level","Overall TAT (Hours)","Overall TAT (Days)","Breach Count","Level Number","Level Name","Approver Name","Approver Email","Level Status","Level Start Date","Level Completion Date","Level TAT (Hours)","Level TAT (Days)","Level TAT Compliance","Level Elapsed Hours","Level Remaining Hours","Level TAT % Used"].join(",")];for(const i of r.lifecycleData)try{const o=await Rs(i.requestId||i.requestNumber),l=i.submissionDate?Xs(i.submissionDate):"N/A",c=i.closureDate?Xs(i.closureDate):"N/A",d=i.overallTATHours||0,m=d>0?(d/8).toFixed(2):"0",u=i.totalLevels||1,h=Math.min(Math.max(1,i.currentLevel||1),u),x=(o==null?void 0:o.approvals)||[];if(x.length===0){const p=[i.requestNumber||"",`"${(i.title||"").replace(/"/g,'""')}"`,i.priority||"medium",i.status||"",`"${(i.initiatorName||"Unknown").replace(/"/g,'""')}"`,l,c,u.toString(),h.toString(),d.toString(),m,(i.breachCount||0).toString(),"N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A"];n.push(p.join(","))}else x.forEach(p=>{const y=p.levelStartTime?Xs(p.levelStartTime):"N/A",v=p.levelEndTime||p.completedAt?Xs(p.levelEndTime||p.completedAt):"N/A",N=p.tatHours||0,f=p.tatDays||(N>0?(N/8).toFixed(2):"0");let b="N/A",j="N/A",C="N/A",R="N/A";if(p.levelStartTime){const T=new Date(p.levelStartTime);if(j=(((p.levelEndTime||p.completedAt?new Date(p.levelEndTime||p.completedAt):new Date).getTime()-T.getTime())/(1e3*60*60)).toFixed(2),N>0){const S=parseFloat(j);C=Math.max(0,N-S).toFixed(2),R=(S/N*100).toFixed(2),p.status==="APPROVED"||p.status==="REJECTED"?b=S<=N?"Compliant":"Breached":p.status==="IN_PROGRESS"||p.status==="PENDING"?b=S<=N?"On Track":"At Risk":b="N/A"}}const I=[i.requestNumber||"",`"${(i.title||"").replace(/"/g,'""')}"`,i.priority||"medium",i.status||"",`"${(i.initiatorName||"Unknown").replace(/"/g,'""')}"`,l,c,(i.totalLevels||0).toString(),(i.currentLevel||0).toString(),d.toString(),m,(i.breachCount||0).toString(),(p.levelNumber||"").toString(),`"${(p.levelName||`Level ${p.levelNumber}`).replace(/"/g,'""')}"`,`"${(p.approverName||"N/A").replace(/"/g,'""')}"`,`"${(p.approverEmail||"N/A").replace(/"/g,'""')}"`,p.status||"PENDING",y,v,N.toString(),f.toString(),b,j,C,R];n.push(I.join(","))})}catch(o){console.error(`Failed to fetch details for request ${i.requestNumber}:`,o);const l=i.submissionDate?Xs(i.submissionDate):"N/A",c=i.overallTATHours||0,d=c>0?(c/8).toFixed(2):"0",m=i.totalLevels||1,u=Math.min(Math.max(1,i.currentLevel||1),m),h=[i.requestNumber||"",`"${(i.title||"").replace(/"/g,'""')}"`,i.priority||"medium",i.status||"",`"${(i.initiatorName||"Unknown").replace(/"/g,'""')}"`,l,"N/A",m.toString(),u.toString(),c.toString(),d,(i.breachCount||0).toString(),"Error","Error fetching details","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A"];n.push(h.join(","))}Oo(n,`lifecycle-report-end-to-end-${new Date().toISOString().split("T")[0]}.csv`)}async function eS(t,s,a,r,n){const i=await He.getActivityLogReport(1,1e4,t,void 0,void 0,r&&r!=="all"?r:void 0,n&&n!=="all"?n:void 0,s,a),o=[["Timestamp","User","Action","Details","IP Address","User Agent","Request ID"].join(",")];i.activities.forEach(l=>{const c=Ah(l.type||"",l.details),m=[l.timestamp?Xs(l.timestamp):"N/A",`"${(l.userName||"Unknown").replace(/"/g,'""')}"`,`"${c.replace(/"/g,'""')}"`,`"${(l.requestTitle||l.requestNumber||l.details||"N/A").replace(/"/g,'""')}"`,l.ipAddress||"N/A",`"${(l.userAgent||"").replace(/"/g,'""')}"`,l.requestNumber||l.requestId||"-"];o.push(m.join(","))}),Oo(o,`activity-log-report-${new Date().toISOString().split("T")[0]}.csv`)}async function tS(t,s,a,r){const n=await He.getWorkflowAgingReport(t,1,1e4,s,a,r),i=[["Request ID","Title","Initiator","Start Date","Days Open (Business)","Current Stage","Assigned To","Priority","Status"].join(",")];n.agingData.forEach(o=>{const l=o.submissionDate?Xs(o.submissionDate):"N/A",c=[o.requestNumber||o.requestId||"",`"${(o.title||"").replace(/"/g,'""')}"`,`"${(o.initiatorName||"Unknown").replace(/"/g,'""')}"`,l,(o.daysOpen||0).toString(),`"${(o.currentStageName||`Level ${o.currentLevel}`).replace(/"/g,'""')}"`,`"${(o.currentApproverName||"N/A").replace(/"/g,'""')}"`,o.priority||"medium",o.status||"pending"];i.push(c.join(","))}),Oo(i,`workflow-aging-report-${new Date().toISOString().split("T")[0]}.csv`)}function Oo(t,s){const a=t.join(` `),r=new Blob([a],{type:"text/csv;charset=utf-8;"}),n=document.createElement("a"),i=URL.createObjectURL(r);n.setAttribute("href",i),n.setAttribute("download",s),n.style.visibility="hidden",document.body.appendChild(n),n.click(),document.body.removeChild(n)}function sS(){const[t,s]=g.useState(!1),[a,r]=g.useState(!1),[n,i]=g.useState(!1),o=g.useCallback(async(d,m,u)=>{try{s(!0),await J2(d,m,u)}catch(h){console.error("Failed to export lifecycle data:",h),alert("Failed to export lifecycle data. Please try again.")}finally{s(!1)}},[]),l=g.useCallback(async(d,m,u,h,x)=>{try{r(!0),await eS(d,m,u,h,x)}catch(p){console.error("Failed to export activity data:",p),alert("Failed to export activity data. Please try again.")}finally{r(!1)}},[]),c=g.useCallback(async(d,m,u,h)=>{try{i(!0),await tS(d,m,u,h)}catch(x){console.error("Failed to export aging data:",x),alert("Failed to export aging data. Please try again.")}finally{i(!1)}},[]);return{exportingLifecycle:t,exportingActivity:a,exportingAging:n,handleExportLifecycle:o,handleExportActivity:l,handleExportAging:c}}function aS({onBack:t}){const s=Bs(),[a,r]=g.useState(""),[n,i]=g.useState("all"),[o,l]=g.useState("all"),c=Vn("month"),d=Vn("month"),m=Vn("month"),u=Q2("7"),h=K2({dateRange:c.dateRange,customStartDate:c.customStartDate,customEndDate:c.customEndDate}),x=Y2({dateRange:d.dateRange,customStartDate:d.customStartDate,customEndDate:d.customEndDate,filterCategory:n,filterSeverity:o}),p=X2({threshold:u.threshold,dateRange:m.dateRange,customStartDate:m.customStartDate,customEndDate:m.customEndDate,searchQuery:a}),y=sS(),v=g.useCallback(()=>{t?t():s("/dashboard")},[t,s]),N=g.useCallback(R=>{s(`/request/${R}`)},[s]),f=g.useCallback(()=>{y.handleExportLifecycle(c.dateRange,c.customStartDate,c.customEndDate)},[y,c]),b=g.useCallback(()=>{y.handleExportActivity(d.dateRange,d.customStartDate,d.customEndDate,n,o)},[y,d,n,o]),j=g.useCallback(()=>{const R=parseInt(u.threshold,10);!isNaN(R)&&R>=1&&y.handleExportAging(R,m.dateRange,m.customStartDate,m.customEndDate)},[y,u.threshold,m]),C=g.useCallback(()=>{i("all"),l("all"),d.reset()},[d]);return e.jsx("div",{className:"flex-1 p-3 lg:p-6 overflow-auto min-w-0","data-testid":"detailed-reports",children:e.jsxs("div",{className:"space-y-6 max-w-7xl mx-auto p-4",children:[e.jsx($2,{onBack:v}),e.jsx(B2,{lifecycleRequests:h.lifecycleRequests,loading:h.loading,loadingPage:h.loadingPage,error:h.error,pagination:h.pagination,dateRange:c.dateRange,customStartDate:c.customStartDate,customEndDate:c.customEndDate,showCustomDatePicker:c.showCustomDatePicker,tempCustomStartDate:c.tempCustomStartDate,tempCustomEndDate:c.tempCustomEndDate,exporting:y.exportingLifecycle,onDateRangeChange:c.handleDateRangeChange,onShowCustomDatePickerChange:c.setShowCustomDatePicker,onStartDateChange:c.handleStartDateChange,onEndDateChange:c.handleEndDateChange,onApplyCustomDate:c.handleApplyCustomDate,onCancelCustomDate:c.handleCancelCustomDate,onPageChange:h.fetchData,onExport:f,onViewRequest:N}),e.jsx(z2,{activityLog:x.activityLog,loading:x.loading,loadingPage:x.loadingPage,error:x.error,pagination:x.pagination,dateRange:d.dateRange,customStartDate:d.customStartDate,customEndDate:d.customEndDate,showCustomDatePicker:d.showCustomDatePicker,tempCustomStartDate:d.tempCustomStartDate,tempCustomEndDate:d.tempCustomEndDate,filterCategory:n,filterSeverity:o,exporting:y.exportingActivity,onDateRangeChange:d.handleDateRangeChange,onShowCustomDatePickerChange:d.setShowCustomDatePicker,onStartDateChange:d.handleStartDateChange,onEndDateChange:d.handleEndDateChange,onApplyCustomDate:d.handleApplyCustomDate,onCancelCustomDate:d.handleCancelCustomDate,onCategoryChange:i,onSeverityChange:l,onClearFilters:C,onPageChange:x.fetchData,onExport:b,onViewRequest:N}),e.jsx(H2,{agingWorkflows:p.agingWorkflows,loading:p.loading,loadingPage:p.loadingPage,error:p.error,pagination:p.pagination,threshold:u.threshold,thresholdError:u.thresholdError,dateRange:m.dateRange,customStartDate:m.customStartDate,customEndDate:m.customEndDate,showCustomDatePicker:m.showCustomDatePicker,tempCustomStartDate:m.tempCustomStartDate,tempCustomEndDate:m.tempCustomEndDate,searchQuery:a,exporting:y.exportingAging,onThresholdChange:u.handleThresholdChange,onThresholdBlur:u.handleThresholdBlur,onDateRangeChange:m.handleDateRangeChange,onShowCustomDatePickerChange:m.setShowCustomDatePicker,onStartDateChange:m.handleStartDateChange,onEndDateChange:m.handleEndDateChange,onApplyCustomDate:m.handleApplyCustomDate,onCancelCustomDate:m.handleCancelCustomDate,onSearchChange:r,onPageChange:p.fetchData,onExport:j,onViewRequest:N})]})})}function rS({defaultPeriod:t,refreshInterval:s,onDefaultPeriodChange:a,onRefreshIntervalChange:r}){const n=["Today","This Week","This Month","Last Month","This Quarter","This Year","Custom Range"];return e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"default-period",children:"Default Reporting Period"}),e.jsxs(we,{value:t,onValueChange:a,children:[e.jsx(Se,{id:"default-period",children:e.jsx(Ce,{})}),e.jsx(Ae,{children:n.map(i=>e.jsx(V,{value:i,children:i},i))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"refresh-interval",children:"Auto-Refresh Interval (minutes)"}),e.jsx(xe,{id:"refresh-interval",type:"number",min:"1",max:"60",value:s,onChange:i=>r(parseInt(i.target.value)||5)})]})]})}function nS({autoRefresh:t,realTimeUpdates:s,dataExport:a,onAutoRefreshChange:r,onRealTimeUpdatesChange:n,onDataExportChange:i}){return e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"font-medium",children:"Data Features"}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Enable Auto-Refresh"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Automatically refresh dashboard data at set intervals"})]}),e.jsx(ts,{checked:t,onCheckedChange:r})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Enable Real-time Updates"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Show live updates when data changes occur"})]}),e.jsx(ts,{checked:s,onCheckedChange:n})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Enable Data Export"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Allow users to export analytics data and reports"})]}),e.jsx(ts,{checked:a,onCheckedChange:i})]})]})}const iS=["CSV","Excel","PDF","JSON"];function oS({exportFormats:t,onExportFormatsChange:s}){const a=(r,n)=>{s(n?[...t,r]:t.filter(i=>i!==r))};return e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{children:"Allowed Export Formats"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:iS.map(r=>e.jsxs("div",{className:"flex items-center space-x-2 p-2 bg-muted/50 rounded",children:[e.jsx(Hi,{id:`export-${r}`,checked:t.includes(r),onCheckedChange:n=>a(r,n)}),e.jsx(X,{htmlFor:`export-${r}`,className:"text-sm cursor-pointer",children:r})]},r))})]})}function lS({dataRetention:t,onDataRetentionChange:s}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"data-retention",children:"Historical Data Retention (months)"}),e.jsx(xe,{id:"data-retention",type:"number",min:"1",max:"120",value:t,onChange:a=>s(parseInt(a.target.value)||24)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Analytics data older than this will be archived or deleted"})]})}function cS(){const[t,s]=g.useState({defaultPeriod:"This Month",refreshInterval:5,autoRefresh:!0,realTimeUpdates:!0,dataExport:!0,exportFormats:["CSV","Excel","PDF"],dataRetention:24}),a=()=>{fe.success("Analytics configuration saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsx(se,{children:"Analytics & Reporting Configuration"}),e.jsx(he,{children:"Configure default reporting periods, auto-refresh, export settings, and data retention"})]}),e.jsxs(Y,{className:"space-y-6",children:[e.jsx(rS,{defaultPeriod:t.defaultPeriod,refreshInterval:t.refreshInterval,onDefaultPeriodChange:n=>r({defaultPeriod:n}),onRefreshIntervalChange:n=>r({refreshInterval:n})}),e.jsx(yt,{}),e.jsx(nS,{autoRefresh:t.autoRefresh,realTimeUpdates:t.realTimeUpdates,dataExport:t.dataExport,onAutoRefreshChange:n=>r({autoRefresh:n}),onRealTimeUpdatesChange:n=>r({realTimeUpdates:n}),onDataExportChange:n=>r({dataExport:n})}),e.jsx(yt,{}),e.jsx(oS,{exportFormats:t.exportFormats,onExportFormatsChange:n=>r({exportFormats:n})}),e.jsx(lS,{dataRetention:t.dataRetention,onDataRetentionChange:n=>r({dataRetention:n})}),e.jsxs(M,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(Vs,{className:"w-4 h-4 mr-2"}),"Save Analytics Configuration"]})]})]})}const dS=t=>{switch(t.toUpperCase()){case"ADMIN":return"bg-yellow-100 text-yellow-800 border-yellow-200";case"MANAGEMENT":return"bg-blue-100 text-blue-800 border-blue-200";case"USER":return"bg-gray-100 text-gray-800 border-gray-200";default:return"bg-gray-100 text-gray-800 border-gray-200"}},mS=t=>t.split(" ").map(s=>s[0]).join("").toUpperCase().substring(0,2);function uS({users:t,onEdit:s,onToggleStatus:a,onDelete:r}){return e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(_o,{children:[e.jsx(Lo,{children:e.jsxs(oa,{children:[e.jsx(gt,{children:"User"}),e.jsx(gt,{children:"Role"}),e.jsx(gt,{children:"Department"}),e.jsx(gt,{children:"Status"}),e.jsx(gt,{className:"text-right",children:"Actions"})]})}),e.jsx(Fo,{children:t.length===0?e.jsx(oa,{children:e.jsx(dt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No users found"})}):t.map(n=>e.jsxs(oa,{className:"hover:bg-muted/50",children:[e.jsx(dt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(jt,{className:"size-10",children:e.jsx(Nt,{className:"bg-re-green text-white",children:mS(n.name)})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:n.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:n.email})]})]})}),e.jsx(dt,{children:e.jsx(Q,{className:dS(n.role),children:n.role})}),e.jsx(dt,{children:n.department}),e.jsx(dt,{children:e.jsxs(Q,{className:"bg-green-100 text-green-800 border-green-200",children:[e.jsx(Hn,{className:"w-3 h-3 mr-1"}),n.status]})}),e.jsx(dt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>s(n.id),className:"h-8",children:e.jsx(Br,{className:"w-4 h-4"})}),e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>a(n.id),disabled:n.role.toUpperCase()==="ADMIN",className:"h-8",children:e.jsx(Lx,{className:"w-4 h-4"})}),e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>r(n.id),disabled:n.role.toUpperCase()==="ADMIN",className:"h-8 text-destructive hover:text-destructive",children:e.jsx(Ei,{className:"w-4 h-4"})})]})})]},n.id))})]})})}function hS({stats:t}){return e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"p-4 bg-muted/50 rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Total Users"}),e.jsx("p",{className:"text-2xl font-semibold",children:t.total})]}),e.jsxs("div",{className:"p-4 bg-green-50 rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Active"}),e.jsx("p",{className:"text-2xl font-semibold text-green-600",children:t.active})]}),e.jsxs("div",{className:"p-4 bg-red-50 rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Inactive"}),e.jsx("p",{className:"text-2xl font-semibold text-red-600",children:t.inactive})]}),e.jsxs("div",{className:"p-4 bg-purple-50 rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Admins"}),e.jsx("p",{className:"text-2xl font-semibold text-purple-600",children:t.admins})]})]})}function pS(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function xS(){const[t,s]=g.useState(""),[a,r]=g.useState([]),[n,i]=g.useState(!1),[o,l]=g.useState(null),[c,d]=g.useState("USER"),[m,u]=g.useState(!1),[h,x]=g.useState(!1),[p,y]=g.useState(null),[v,N]=g.useState([]),[f,b]=g.useState(!1),[j,C]=g.useState({admins:0,management:0,users:0,total:0,active:0,inactive:0}),[R,I]=g.useState("ELEVATED"),[T,E]=g.useState(1),[w,S]=g.useState(1),[D,H]=g.useState(0),L=10,F=g.useRef(null),A=g.useCallback(pS(async K=>{var B,J,ue;if(!K||K.length<2){r([]);return}i(!0);try{const Ie=((B=(await Wt.searchUsers(K,20)).data)==null?void 0:B.data)||[];r(Ie)}catch(be){console.error("Search failed:",be),y({type:"error",text:((ue=(J=be.response)==null?void 0:J.data)==null?void 0:ue.message)||"Failed to search users"})}finally{i(!1)}},300),[]),k=K=>{const B=K.target.value;s(B),A(B)},P=async K=>{var B,J;try{const ue=v.find(Oe=>Oe.email.toLowerCase()===K.toLowerCase());if(ue)return ue.role;const Ve=(((J=(B=(await Wt.getUsersByRole("ALL",1,1e3)).data)==null?void 0:B.data)==null?void 0:J.users)||[]).find(Oe=>{var Ue;return((Ue=Oe.email)==null?void 0:Ue.toLowerCase())===K.toLowerCase()});return Ve&&Ve.role?Ve.role:null}catch(ue){return console.error("Failed to fetch user role:",ue),null}},_=async K=>{l(K),s(K.email),r([]),x(!0);try{const B=await P(K.email);d(B||"USER")}catch(B){console.error("Failed to fetch user role:",B),d("USER")}finally{x(!1)}},W=async()=>{var K,B;if(!o||!c){y({type:"error",text:"Please select a user and role"});return}u(!0),y(null);try{await Wt.assignRole(o.email,c),y({type:"success",text:`Successfully assigned ${c} role to ${o.displayName||o.email}`}),l(null),s(""),d("USER"),await Z(),await ae(),fe.success("Role assigned successfully")}catch(J){console.error("Role assignment failed:",J);const ue=((B=(K=J.response)==null?void 0:K.data)==null?void 0:B.error)||"Failed to assign role";y({type:"error",text:ue}),fe.error(ue)}finally{u(!1)}},Z=async(K=T)=>{var B,J,ue,be,Ie,Ve;b(!0);try{const Oe=await Wt.getUsersByRole(R,K,L),Ue=((J=(B=Oe.data)==null?void 0:B.data)==null?void 0:J.users)||[],$e=(be=(ue=Oe.data)==null?void 0:ue.data)==null?void 0:be.pagination,Dt=(Ve=(Ie=Oe.data)==null?void 0:Ie.data)==null?void 0:Ve.summary;N(Ue.map(Fe=>({userId:Fe.userId,email:Fe.email,displayName:Fe.displayName||Fe.email,role:Fe.role||"USER",department:Fe.department,designation:Fe.designation,isActive:Fe.isActive!==!1}))),$e&&(E($e.currentPage),S($e.totalPages),H($e.totalUsers)),Dt&&C(Fe=>({...Fe,admins:Dt.ADMIN||0,management:Dt.MANAGEMENT||0,users:Dt.USER||0,total:(Dt.ADMIN||0)+(Dt.MANAGEMENT||0)+(Dt.USER||0)}))}catch(Oe){console.error("Failed to fetch users:",Oe),fe.error("Failed to load users")}finally{b(!1)}},ae=async()=>{var K,B,J,ue,be,Ie;try{const Ve=await Wt.getRoleStatistics(),Oe=((B=(K=Ve.data)==null?void 0:K.data)==null?void 0:B.statistics)||((J=Ve.data)==null?void 0:J.statistics)||[],Ue={admins:parseInt(((ue=Oe.find($e=>$e.role==="ADMIN"))==null?void 0:ue.count)||"0"),management:parseInt(((be=Oe.find($e=>$e.role==="MANAGEMENT"))==null?void 0:be.count)||"0"),users:parseInt(((Ie=Oe.find($e=>$e.role==="USER"))==null?void 0:Ie.count)||"0")};C($e=>({...$e,...Ue,total:Ue.admins+Ue.management+Ue.users,active:$e.active||Ue.admins+Ue.management+Ue.users,inactive:$e.inactive||0}))}catch(Ve){console.error("Failed to fetch statistics:",Ve)}};g.useEffect(()=>{Z(1),ae()},[R]);const $=K=>{I(K),E(1)},ne=K=>{Z(K)},me=async(K,B)=>{var J,ue;try{await Wt.updateUserRole(K,B),fe.success("User role updated successfully"),await Z(),await ae()}catch(be){console.error("Failed to update user role:",be),fe.error(((ue=(J=be.response)==null?void 0:J.data)==null?void 0:ue.error)||"Failed to update user role")}},q=async K=>{v.find(J=>J.userId===K)&&fe.info("User status toggle functionality coming soon")},z=async K=>{const B=v.find(J=>J.userId===K);if(B){if(B.role==="ADMIN"){fe.error("Cannot delete admin user");return}fe.info("User deletion functionality coming soon")}};g.useEffect(()=>{const K=B=>{F.current&&!F.current.contains(B.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",K),()=>{document.removeEventListener("mousedown",K)}},[a]);const re={total:j.total,active:j.active,inactive:j.inactive,admins:j.admins};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(hS,{stats:re}),e.jsxs(G,{children:[e.jsx(te,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Assign User Role"}),e.jsx(he,{children:"Search for a user in Okta and assign them a role"})]}),e.jsx(M,{onClick:W,disabled:!o||m,className:"bg-re-green hover:bg-re-green/90",children:m?e.jsxs(e.Fragment,{children:[e.jsx(Le,{className:"w-4 h-4 mr-2 animate-spin"}),"Assigning..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Is,{className:"w-4 h-4 mr-2"}),"Assign Role"]})})]})}),e.jsxs(Y,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",ref:F,children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Yt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(xe,{type:"text",placeholder:"Type name or email address...",value:t,onChange:k,className:"pl-10 border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),n&&e.jsx(Le,{className:"absolute right-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-re-green animate-spin"})]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Start typing to search across all Okta users"}),a.length>0&&e.jsxs("div",{className:"border rounded-lg shadow-lg bg-white max-h-60 overflow-y-auto",children:[e.jsx("div",{className:"sticky top-0 bg-muted px-4 py-2 border-b",children:e.jsxs("p",{className:"text-xs font-semibold text-muted-foreground",children:[a.length," user",a.length>1?"s":""," found"]})}),e.jsx("div",{className:"p-3",children:a.map(K=>e.jsxs("button",{onClick:()=>_(K),className:"w-full text-left p-3 hover:bg-muted rounded-lg transition-colors mb-1 last:mb-0",children:[e.jsx("p",{className:"font-medium text-gray-900",children:K.displayName||K.email}),e.jsx("p",{className:"text-sm text-muted-foreground",children:K.email}),K.department&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[K.department,K.designation?` • ${K.designation}`:""]})]},K.userId))})]})]}),o&&e.jsx("div",{className:"border-2 border-re-green/20 bg-re-green/5 rounded-lg p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-re-green flex items-center justify-center text-white font-bold shadow-md",children:(o.displayName||o.email).charAt(0).toUpperCase()}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-gray-900",children:o.displayName||o.email}),e.jsx("p",{className:"text-sm text-muted-foreground",children:o.email}),o.department&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[o.department,o.designation?` • ${o.designation}`:""]}),h&&e.jsxs("p",{className:"text-xs text-re-green mt-1 flex items-center gap-1",children:[e.jsx(Le,{className:"w-3 h-3 animate-spin"}),"Checking current role..."]})]})]}),e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>{l(null),s(""),d("USER"),x(!1)},children:"Clear"})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Select Role"}),e.jsxs(we,{value:c,onValueChange:K=>d(K),disabled:h,children:[e.jsx(Se,{className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Ce,{placeholder:h?"Loading current role...":"Select role"})}),e.jsxs(Ae,{className:"rounded-lg",children:[e.jsx(V,{value:"USER",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rt,{className:"w-4 h-4 text-gray-600"}),e.jsx("span",{children:"User - Regular access"})]})}),e.jsx(V,{value:"MANAGEMENT",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(at,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Management - Read all data"})]})}),e.jsx(V,{value:"ADMIN",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ua,{className:"w-4 h-4 text-yellow-600"}),e.jsx("span",{children:"Administrator - Full access"})]})})]})]})]}),p&&e.jsx("div",{className:`border-2 rounded-lg p-4 ${p.type==="success"?"border-green-200 bg-green-50":"border-red-200 bg-red-50"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[p.type==="success"?e.jsx(ve,{className:"w-5 h-5 text-green-600 shrink-0 mt-0.5"}):e.jsx(Re,{className:"w-5 h-5 text-red-600 shrink-0 mt-0.5"}),e.jsx("p",{className:`text-sm ${p.type==="success"?"text-green-800":"text-red-800"}`,children:p.text})]})})]})]}),e.jsxs(G,{children:[e.jsx(te,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs(se,{className:"flex items-center gap-2",children:[e.jsx(at,{className:"w-5 h-5 text-re-green"}),"User Management"]}),e.jsxs(he,{children:["View and manage user accounts and roles (",D," ",R!=="ALL"&&R!=="ELEVATED"?R.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(we,{value:R,onValueChange:$,children:[e.jsx(Se,{className:"w-[200px] border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Ce,{placeholder:"Filter by role"})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"ELEVATED",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gt,{className:"w-4 h-4 text-purple-600"}),e.jsxs("span",{children:["Elevated (",j.admins+j.management,")"]})]})}),e.jsx(V,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ua,{className:"w-4 h-4 text-yellow-600"}),e.jsxs("span",{children:["Admins (",j.admins,")"]})]})}),e.jsx(V,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(at,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Management (",j.management,")"]})]})}),e.jsx(V,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rt,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["Users (",j.users,")"]})]})}),e.jsx(V,{value:"ALL",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(at,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["All Users (",j.admins+j.management+j.users,")"]})]})})]})]})})]})}),e.jsx(Y,{className:"pt-6",children:f?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsx(Le,{className:"w-6 h-6 animate-spin text-re-green mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading users..."})]}):v.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-gray-100 flex items-center justify-center mx-auto mb-3",children:e.jsx(at,{className:"w-6 h-6 text-gray-400"})}),e.jsx("p",{className:"font-medium text-gray-700",children:"No users found"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:R==="ELEVATED"?"Assign ADMIN or MANAGEMENT roles to see users here":"No users match the selected filter"})]}):e.jsxs(e.Fragment,{children:[e.jsx(uS,{users:v.map(K=>({id:K.userId,name:K.displayName,email:K.email,role:K.role,department:K.department||"N/A",status:K.isActive?"active":"inactive"})),onEdit:K=>{const B=v.find(J=>J.userId===K);if(B){const J=B.role==="USER"?"MANAGEMENT":B.role==="MANAGEMENT"?"ADMIN":"USER";me(K,J)}},onToggleStatus:q,onDelete:z}),w>1&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t mt-4",children:[e.jsxs("div",{className:"text-sm text-gray-600",children:["Showing ",(T-1)*L+1," to ",Math.min(T*L,D)," of ",D," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(M,{variant:"outline",size:"sm",onClick:()=>ne(T-1),disabled:T===1,children:"Previous"}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,w)},(K,B)=>{let J;return w<=5||T<=3?J=B+1:T>=w-2?J=w-4+B:J=T-2+B,e.jsx(M,{variant:T===J?"default":"outline",size:"sm",onClick:()=>ne(J),className:`w-9 h-9 p-0 ${T===J?"bg-re-green hover:bg-re-green/90":""}`,children:J},J)})}),e.jsx(M,{variant:"outline",size:"sm",onClick:()=>ne(T+1),disabled:T===w,children:"Next"})]})]})]})})]})]})}function gS({expressHours:t,standardHours:s,onExpressChange:a,onStandardChange:r}){return e.jsxs(G,{className:"border-0 shadow-sm",children:[e.jsxs(te,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ki,{className:"w-5 h-5 text-re-green"}),e.jsx(se,{className:"text-base font-semibold",children:"Priority TAT Settings"})]}),e.jsx(he,{className:"text-sm",children:"Set default turnaround time in hours for each priority level"})]}),e.jsx(Y,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"tat-express",className:"text-sm font-medium",children:"Express Priority (hours)"}),e.jsx(xe,{id:"tat-express",type:"number",min:"1",max:"168",value:t,onChange:n=>a(parseInt(n.target.value)||24),className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(De,{className:"w-3 h-3"}),"Critical/Emergency requests (24/7, includes weekends)"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"tat-standard",className:"text-sm font-medium",children:"Standard Priority (hours)"}),e.jsx(xe,{id:"tat-standard",type:"number",min:"1",max:"720",value:s,onChange:n=>r(parseInt(n.target.value)||72),className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(De,{className:"w-3 h-3"}),"Regular priority requests (working hours only, excludes weekends & holidays)"]})]})]})})]})}function fS({reminderThreshold1:t,reminderThreshold2:s,onReminderThreshold1Change:a,onReminderThreshold2Change:r}){return e.jsxs(G,{className:"border-0 shadow-sm",children:[e.jsxs(te,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ut,{className:"w-5 h-5 text-re-green"}),e.jsx(se,{className:"text-base font-semibold",children:"Auto-Reminder & Escalation"})]}),e.jsx(he,{className:"text-sm",children:"Configure automatic reminder thresholds based on TAT percentage"})]}),e.jsx(Y,{className:"space-y-6",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(X,{htmlFor:"reminder-threshold-1",className:"text-sm font-medium",children:"First Reminder Threshold"}),e.jsxs("span",{className:"text-lg font-semibold text-re-green",children:[t,"%"]})]}),e.jsx(ji,{id:"reminder-threshold-1",value:[t],min:1,max:100,step:1,onValueChange:([n])=>{n!==void 0&&a(n)},className:"w-full"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ut,{className:"w-3 h-3"}),"Send first gentle reminder when ",t,"% of TAT elapsed"]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(X,{htmlFor:"reminder-threshold-2",className:"text-sm font-medium",children:"Second Reminder Threshold (Escalation)"}),e.jsxs("span",{className:"text-lg font-semibold text-re-green",children:[s,"%"]})]}),e.jsx(ji,{id:"reminder-threshold-2",value:[s],min:1,max:100,step:1,onValueChange:([n])=>{n!==void 0&&r(n)},className:"w-full"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(is,{className:"w-3 h-3"}),"Send escalation warning when ",s,"% of TAT elapsed"]})]})]})})]})}const Fa=[{value:1,label:"Monday"},{value:2,label:"Tuesday"},{value:3,label:"Wednesday"},{value:4,label:"Thursday"},{value:5,label:"Friday"},{value:6,label:"Saturday"},{value:7,label:"Sunday"}];function yS({workStartHour:t,workEndHour:s,workStartDay:a,workEndDay:r,onWorkStartHourChange:n,onWorkEndHourChange:i,onWorkStartDayChange:o,onWorkEndDayChange:l}){var c,d,m;return e.jsxs(G,{className:"border-0 shadow-sm",children:[e.jsxs(te,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qe,{className:"w-5 h-5 text-re-green"}),e.jsx(se,{className:"text-base font-semibold",children:"Working Hours Configuration"})]}),e.jsx(he,{className:"text-sm",children:"Define your organization's working hours and days for TAT calculations"})]}),e.jsxs(Y,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"work-start-hour",className:"text-sm font-medium",children:"Working Day Start Hour"}),e.jsx(xe,{id:"work-start-hour",type:"number",min:"0",max:"23",value:t,onChange:u=>n(parseInt(u.target.value)||9),className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(De,{className:"w-3 h-3"}),"24-hour format (0-23). Default: 9 AM"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"work-end-hour",className:"text-sm font-medium",children:"Working Day End Hour"}),e.jsx(xe,{id:"work-end-hour",type:"number",min:"0",max:"23",value:s,onChange:u=>i(parseInt(u.target.value)||18),className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(De,{className:"w-3 h-3"}),"24-hour format (0-23). Default: 6 PM"]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"work-start-day",className:"text-sm font-medium",children:"Working Week Start Day"}),e.jsxs(we,{value:a.toString(),onValueChange:u=>o(parseInt(u)),children:[e.jsx(Se,{id:"work-start-day",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Ce,{placeholder:"Select start day"})}),e.jsx(Ae,{children:Fa.map(u=>e.jsx(V,{value:u.value.toString(),children:u.label},u.value))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Day when the working week starts (1=Monday, 7=Sunday)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"work-end-day",className:"text-sm font-medium",children:"Working Week End Day"}),e.jsxs(we,{value:r.toString(),onValueChange:u=>l(parseInt(u)),children:[e.jsx(Se,{id:"work-end-day",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Ce,{placeholder:"Select end day"})}),e.jsx(Ae,{children:Fa.map(u=>e.jsx(V,{value:u.value.toString(),children:u.label},u.value))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Day when the working week ends (1=Monday, 7=Sunday)"})]})]}),e.jsx("div",{className:"p-4 bg-blue-50 border border-blue-200 rounded-md",children:e.jsxs("p",{className:"text-sm text-blue-900",children:[e.jsx("strong",{children:"Current Configuration:"})," Working hours are from ",t,":00 to ",s,":00,",a===r?` ${(c=Fa.find(u=>u.value===a))==null?void 0:c.label} only`:` ${(d=Fa.find(u=>u.value===a))==null?void 0:d.label} to ${(m=Fa.find(u=>u.value===r))==null?void 0:m.label}`]})})]})]})}function vS(){const[t,s]=g.useState(!0),[a,r]=g.useState(!1),[n,i]=g.useState({expressHours:24,standardHours:72,reminderThreshold1:50,reminderThreshold2:75,workStartHour:9,workEndHour:18,workStartDay:1,workEndDay:5});g.useEffect(()=>{o()},[]);const o=async()=>{try{s(!0);const d=await Yr("TAT_SETTINGS"),m={};d.forEach(u=>{m[u.configKey]=u.configValue}),i({expressHours:parseInt(m.DEFAULT_TAT_EXPRESS_HOURS||"24"),standardHours:parseInt(m.DEFAULT_TAT_STANDARD_HOURS||"72"),reminderThreshold1:parseInt(m.TAT_REMINDER_THRESHOLD_1||"50"),reminderThreshold2:parseInt(m.TAT_REMINDER_THRESHOLD_2||"75"),workStartHour:parseInt(m.WORK_START_HOUR||"9"),workEndHour:parseInt(m.WORK_END_HOUR||"18"),workStartDay:parseInt(m.WORK_START_DAY||"1"),workEndDay:parseInt(m.WORK_END_DAY||"5")})}catch(d){console.error("Failed to load TAT configurations:",d),fe.error("Failed to load TAT configurations")}finally{s(!1)}},l=async()=>{var d,m;try{r(!0),await Promise.all([bt("DEFAULT_TAT_EXPRESS_HOURS",n.expressHours.toString()),bt("DEFAULT_TAT_STANDARD_HOURS",n.standardHours.toString()),bt("TAT_REMINDER_THRESHOLD_1",n.reminderThreshold1.toString()),bt("TAT_REMINDER_THRESHOLD_2",n.reminderThreshold2.toString()),bt("WORK_START_HOUR",n.workStartHour.toString()),bt("WORK_END_HOUR",n.workEndHour.toString()),bt("WORK_START_DAY",n.workStartDay.toString()),bt("WORK_END_DAY",n.workEndDay.toString())]),fe.success("TAT configuration saved successfully"),await o()}catch(u){console.error("Failed to save TAT configuration:",u),fe.error(((m=(d=u.response)==null?void 0:d.data)==null?void 0:m.error)||"Failed to save TAT configuration")}finally{r(!1)}},c=d=>{i(m=>({...m,...d}))};return t?e.jsx(G,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(Y,{className:"p-12 text-center",children:[e.jsx(Le,{className:"w-8 h-8 animate-spin text-re-green mx-auto mb-4"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Loading TAT configuration..."})]})}):e.jsxs(G,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(te,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(De,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(se,{className:"text-lg font-semibold text-gray-900",children:"Turn Around Time (TAT) Configuration"}),e.jsx(he,{className:"text-sm text-gray-600",children:"Set default TAT hours per priority level, working hours, and configure auto-escalation thresholds"})]})]})}),e.jsxs(Y,{className:"space-y-6",children:[e.jsx(gS,{expressHours:n.expressHours,standardHours:n.standardHours,onExpressChange:d=>c({expressHours:d}),onStandardChange:d=>c({standardHours:d})}),e.jsx(yt,{}),e.jsx(yS,{workStartHour:n.workStartHour,workEndHour:n.workEndHour,workStartDay:n.workStartDay,workEndDay:n.workEndDay,onWorkStartHourChange:d=>c({workStartHour:d}),onWorkEndHourChange:d=>c({workEndHour:d}),onWorkStartDayChange:d=>c({workStartDay:d}),onWorkEndDayChange:d=>c({workEndDay:d})}),e.jsx(yt,{}),e.jsx(fS,{reminderThreshold1:n.reminderThreshold1,reminderThreshold2:n.reminderThreshold2,onReminderThreshold1Change:d=>c({reminderThreshold1:d}),onReminderThreshold2Change:d=>c({reminderThreshold2:d})}),e.jsx("div",{className:"flex justify-end pt-4",children:e.jsx(M,{onClick:l,disabled:a,className:"bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:a?e.jsxs(e.Fragment,{children:[e.jsx(Le,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Vs,{className:"w-4 h-4 mr-2"}),"Save TAT Settings"]})})})]})]})}function bS({emailNotifications:t,inAppNotifications:s,autoReminders:a,onEmailNotificationsChange:r,onInAppNotificationsChange:n,onAutoRemindersChange:i}){return e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"font-medium",children:"Notification Channels"}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Email Notifications"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Send notifications via email"})]}),e.jsx(ts,{checked:t,onCheckedChange:r})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"In-App Notifications"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Show notifications in the portal"})]}),e.jsx(ts,{checked:s,onCheckedChange:n})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Auto-Reminders"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Automatically send reminders for pending approvals"})]}),e.jsx(ts,{checked:a,onCheckedChange:i})]})]})}function jS({notificationFrequency:t,reminderFrequency:s,onNotificationFrequencyChange:a,onReminderFrequencyChange:r}){return e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"notification-frequency",children:"Notification Frequency"}),e.jsxs(we,{value:t,onValueChange:a,children:[e.jsx(Se,{id:"notification-frequency",children:e.jsx(Ce,{placeholder:"Select frequency"})}),e.jsxs(Ae,{children:[e.jsx(V,{value:"Immediate",children:"Immediate"}),e.jsx(V,{value:"Hourly",children:"Hourly"}),e.jsx(V,{value:"Daily",children:"Daily"}),e.jsx(V,{value:"Weekly",children:"Weekly"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"reminder-frequency",children:"Reminder Frequency (hours)"}),e.jsx(xe,{id:"reminder-frequency",type:"number",min:"1",max:"168",value:s,onChange:n=>r(parseInt(n.target.value)||12)})]})]})}function NS({emailTemplate:t,onEmailTemplateChange:s}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"email-template",children:"Email Template Message"}),e.jsx(Cs,{id:"email-template",rows:5,value:t,onChange:a=>s(a.target.value),className:"resize-none",placeholder:"Enter email template message..."}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Use placeholders: [Name], [Request ID], [TAT], [Status]"})]})}function wS(){const[t,s]=g.useState({emailNotifications:!0,inAppNotifications:!0,autoReminders:!0,notificationFrequency:"Immediate",reminderFrequency:12,emailTemplate:"Dear [Name], You have a pending approval request [Request ID] that requires your attention. TAT remaining: [TAT]. Please review at your earliest convenience."}),a=()=>{fe.success("Notification configuration saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsx(se,{children:"Notification Configuration"}),e.jsx(he,{children:"Configure notification channels, frequency, and message templates"})]}),e.jsxs(Y,{className:"space-y-6",children:[e.jsx(bS,{emailNotifications:t.emailNotifications,inAppNotifications:t.inAppNotifications,autoReminders:t.autoReminders,onEmailNotificationsChange:n=>r({emailNotifications:n}),onInAppNotificationsChange:n=>r({inAppNotifications:n}),onAutoRemindersChange:n=>r({autoReminders:n})}),e.jsx(yt,{}),e.jsx(jS,{notificationFrequency:t.notificationFrequency,reminderFrequency:t.reminderFrequency,onNotificationFrequencyChange:n=>r({notificationFrequency:n}),onReminderFrequencyChange:n=>r({reminderFrequency:n})}),e.jsx(NS,{emailTemplate:t.emailTemplate,onEmailTemplateChange:n=>r({emailTemplate:n})}),e.jsxs(M,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(Vs,{className:"w-4 h-4 mr-2"}),"Save Notification Settings"]})]})]})}function CS({maxFileSizeMB:t,retentionDays:s,onMaxFileSizeChange:a,onRetentionDaysChange:r}){const n=Math.round(s/365*10)/10;return e.jsxs(G,{className:"border-0 shadow-sm",children:[e.jsxs(te,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ba,{className:"w-5 h-5 text-re-green"}),e.jsx(se,{className:"text-base font-semibold",children:"Upload & Retention Settings"})]}),e.jsx(he,{className:"text-sm",children:"Configure file size limits and document retention period"})]}),e.jsx(Y,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"max-upload",className:"text-sm font-medium",children:"Maximum Upload Size (MB)"}),e.jsx(xe,{id:"max-upload",type:"number",min:"1",max:"100",value:t,onChange:i=>a(parseInt(i.target.value)||10),className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ba,{className:"w-3 h-3"}),"Maximum allowed file size for document uploads"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"retention",className:"text-sm font-medium",children:"Retention Period (Days)"}),e.jsx(xe,{id:"retention",type:"number",min:"30",max:"3650",value:s,onChange:i=>r(parseInt(i.target.value)||365),className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(zr,{className:"w-3 h-3"}),"Days to retain documents after workflow closure (",n," years)"]})]})]})})]})}const SS=[{label:"PDF Documents",extensions:["pdf"]},{label:"Microsoft Word",extensions:["doc","docx"]},{label:"Microsoft Excel",extensions:["xls","xlsx"]},{label:"Microsoft PowerPoint",extensions:["ppt","pptx"]},{label:"Images",extensions:["jpg","jpeg","png","gif","bmp","webp"]},{label:"CSV Files",extensions:["csv"]},{label:"Text Files",extensions:["txt","rtf"]}];function AS({allowedFileTypes:t,onAllowedFileTypesChange:s}){const a=t.split(",").map(o=>o.trim().toLowerCase()),r=(o,l)=>{const c=new Set(a);l?o.forEach(d=>c.add(d)):o.forEach(d=>c.delete(d)),s(Array.from(c).join(","))},n=o=>o.some(l=>a.includes(l)),i=o=>{s(o)};return e.jsxs(G,{className:"border-0 shadow-sm",children:[e.jsxs(te,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yd,{className:"w-5 h-5 text-re-green"}),e.jsx(se,{className:"text-base font-semibold",children:"Allowed File Types"})]}),e.jsx(he,{className:"text-sm",children:"Select which file types are allowed for upload"})]}),e.jsxs(Y,{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:SS.map(o=>{const l=n(o.extensions);return e.jsxs("div",{onClick:()=>r(o.extensions,!l),className:`flex items-center justify-between p-3 rounded-md border-2 cursor-pointer transition-all ${l?"bg-re-green/5 border-re-green/30 hover:border-re-green/50":"bg-gray-50 border-gray-200 hover:border-gray-300"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`w-4 h-4 rounded border-2 flex items-center justify-center ${l?"bg-re-green border-re-green":"bg-white border-gray-300"}`,children:l&&e.jsx("svg",{className:"w-3 h-3 text-white",fill:"currentColor",viewBox:"0 0 20 20",children:e.jsx("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})})}),e.jsx("span",{className:`text-sm font-medium ${l?"text-re-green":"text-gray-600"}`,children:o.label})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:o.extensions.join(", ")})]},o.label)})}),e.jsxs("div",{className:"space-y-2 pt-2",children:[e.jsx(X,{htmlFor:"file-types-manual",className:"text-sm font-medium",children:"File Extensions (comma-separated)"}),e.jsx(xe,{id:"file-types-manual",type:"text",value:t,onChange:o=>i(o.target.value),placeholder:"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20 font-mono text-sm"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Edit directly or use the checkboxes above. Separate extensions with commas."})]})]})]})}function TS(){const[t,s]=g.useState(!0),[a,r]=g.useState(!1),[n,i]=g.useState({maxFileSizeMB:10,retentionDays:365,allowedFileTypes:"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif"});g.useEffect(()=>{o()},[]);const o=async()=>{try{s(!0);const d=await Yr("DOCUMENT_POLICY"),m={};d.forEach(u=>{m[u.configKey]=u.configValue}),i({maxFileSizeMB:parseInt(m.MAX_FILE_SIZE_MB||"10"),retentionDays:parseInt(m.DOCUMENT_RETENTION_DAYS||"365"),allowedFileTypes:m.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif"})}catch(d){console.error("Failed to load document configurations:",d),fe.error("Failed to load document configurations")}finally{s(!1)}},l=async()=>{var d,m;try{r(!0),await Promise.all([bt("MAX_FILE_SIZE_MB",n.maxFileSizeMB.toString()),bt("DOCUMENT_RETENTION_DAYS",n.retentionDays.toString()),bt("ALLOWED_FILE_TYPES",n.allowedFileTypes)]),fe.success("Document policy saved successfully"),await o()}catch(u){console.error("Failed to save document configuration:",u),fe.error(((m=(d=u.response)==null?void 0:d.data)==null?void 0:m.error)||"Failed to save document configuration")}finally{r(!1)}},c=d=>{i(m=>({...m,...d}))};return t?e.jsx(G,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(Y,{className:"p-12 text-center",children:[e.jsx(Le,{className:"w-8 h-8 animate-spin text-re-green mx-auto mb-4"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Loading document policy configuration..."})]})}):e.jsxs(G,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(te,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(Te,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(se,{className:"text-lg font-semibold text-gray-900",children:"Document Upload Policy"}),e.jsx(he,{className:"text-sm text-gray-600",children:"Configure file upload limits, allowed types, and retention policies"})]})]})}),e.jsxs(Y,{className:"space-y-6",children:[e.jsx(CS,{maxFileSizeMB:n.maxFileSizeMB,retentionDays:n.retentionDays,onMaxFileSizeChange:d=>c({maxFileSizeMB:d}),onRetentionDaysChange:d=>c({retentionDays:d})}),e.jsx(yt,{}),e.jsx(AS,{allowedFileTypes:n.allowedFileTypes,onAllowedFileTypesChange:d=>c({allowedFileTypes:d})}),e.jsx("div",{className:"flex justify-end pt-4",children:e.jsx(M,{onClick:l,disabled:a,className:"bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:a?e.jsxs(e.Fragment,{children:[e.jsx(Le,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Vs,{className:"w-4 h-4 mr-2"}),"Save Document Policy"]})})})]})]})}function kS(){return e.jsx("div",{className:"p-4 bg-blue-50 border border-blue-200 rounded-lg",children:e.jsxs("p",{className:"text-sm text-blue-800",children:[e.jsx("strong",{children:"Note:"})," These settings control what information is visible to each role on their dashboard. Admins always have access to all metrics."]})})}const RS=["Total Requests","Open Requests","Approved Requests","Rejected Requests","My Pending Actions","TAT Compliance","Delayed Workflows","Average Cycle Time"],DS=t=>{switch(t){case"Initiator":return"bg-blue-100 text-blue-800";case"Approver":return"bg-green-100 text-green-800";case"Spectator":return"bg-gray-100 text-gray-800";default:return"bg-gray-100 text-gray-800"}};function PS({role:t,kpis:s,onKPIToggle:a}){return e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"font-medium flex items-center gap-2",children:e.jsxs(Q,{className:DS(t),children:[t," Dashboard"]})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-2 ml-4",children:RS.map(r=>e.jsxs("div",{className:"flex items-center space-x-2 p-2 bg-muted/50 rounded",children:[e.jsx(Hi,{id:`${t.toLowerCase()}-${r}`,checked:s[r]||!1,onCheckedChange:n=>a(r,n===!0)}),e.jsx("label",{htmlFor:`${t.toLowerCase()}-${r}`,className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer",children:r})]},r))})]})}function ES(){const[t,s]=g.useState({Initiator:{"Total Requests":!0,"Open Requests":!0,"Approved Requests":!0,"Rejected Requests":!0,"My Pending Actions":!0,"TAT Compliance":!0,"Delayed Workflows":!0,"Average Cycle Time":!0},Approver:{"Total Requests":!0,"Open Requests":!0,"Approved Requests":!0,"Rejected Requests":!0,"My Pending Actions":!0,"TAT Compliance":!0,"Delayed Workflows":!0,"Average Cycle Time":!0},Spectator:{"Total Requests":!0,"Open Requests":!0,"Approved Requests":!0,"Rejected Requests":!0,"My Pending Actions":!0,"TAT Compliance":!0,"Delayed Workflows":!0,"Average Cycle Time":!0}}),a=()=>{fe.success("Dashboard layout saved successfully")},r=(i,o,l)=>{s(c=>({...c,[i]:{...c[i],[o]:l}}))},n=["Initiator","Approver","Spectator"];return e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsx(se,{children:"Dashboard Layout Configuration"}),e.jsx(he,{children:"Control which KPI cards are visible for each user role"})]}),e.jsxs(Y,{className:"space-y-4",children:[e.jsx(kS,{}),e.jsx("div",{className:"space-y-6",children:n.map(i=>e.jsx(PS,{role:i,kpis:t[i]||{},onKPIToggle:(o,l)=>r(i,o,l)},i))}),e.jsxs(M,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(Vs,{className:"w-4 h-4 mr-2"}),"Save Dashboard Layout"]})]})]})}const MS=[{value:"claude",label:"Claude (Anthropic)",description:"Advanced AI by Anthropic"},{value:"openai",label:"OpenAI (GPT-4)",description:"GPT-4 by OpenAI"},{value:"gemini",label:"Gemini (Google)",description:"Gemini by Google"}];function IS({aiEnabled:t,aiProvider:s,claudeApiKey:a,openaiApiKey:r,geminiApiKey:n,showApiKeys:i,onAiEnabledChange:o,onProviderChange:l,onClaudeApiKeyChange:c,onOpenaiApiKeyChange:d,onGeminiApiKeyChange:m,onToggleApiKeyVisibility:u,maskApiKey:h}){return e.jsxs(G,{className:"border-0 shadow-sm",children:[e.jsxs(te,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wd,{className:"w-5 h-5 text-re-green"}),e.jsx(se,{className:"text-base font-semibold",children:"AI Provider & API Keys"})]}),e.jsx(he,{className:"text-sm",children:"Select your AI provider and configure API keys"})]}),e.jsxs(Y,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 border border-gray-200 rounded-md",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"Enable AI Features"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Master toggle to enable/disable all AI-powered features"})]}),e.jsx(ts,{checked:t,onCheckedChange:o})]}),t&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"ai-provider",className:"text-sm font-medium",children:"AI Provider"}),e.jsxs(we,{value:s,onValueChange:x=>l(x),children:[e.jsx(Se,{id:"ai-provider",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Ce,{placeholder:"Select AI provider"})}),e.jsx(Ae,{children:MS.map(x=>e.jsx(V,{value:x.value,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:x.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"-"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:x.description})]})},x.value))})]})]}),e.jsxs("div",{className:"space-y-4 pt-2",children:[e.jsxs(X,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Fx,{className:"w-4 h-4"}),"API Keys"]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"claude-key",className:"text-xs text-muted-foreground",children:"Claude API Key"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{id:"claude-key",type:i.claude?"text":"password",value:a,onChange:x=>c(x.target.value),placeholder:i.claude?"sk-ant-...":h(a)||"sk-ant-...",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20 font-mono text-sm"}),e.jsx(M,{type:"button",variant:"outline",size:"icon",onClick:()=>u("claude"),className:"border-gray-200",children:i.claude?e.jsx(fr,{className:"w-4 h-4"}):e.jsx(At,{className:"w-4 h-4"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Get your API key from console.anthropic.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"openai-key",className:"text-xs text-muted-foreground",children:"OpenAI API Key"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{id:"openai-key",type:i.openai?"text":"password",value:r,onChange:x=>d(x.target.value),placeholder:i.openai?"sk-...":h(r)||"sk-...",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20 font-mono text-sm"}),e.jsx(M,{type:"button",variant:"outline",size:"icon",onClick:()=>u("openai"),className:"border-gray-200",children:i.openai?e.jsx(fr,{className:"w-4 h-4"}):e.jsx(At,{className:"w-4 h-4"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Get your API key from platform.openai.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"gemini-key",className:"text-xs text-muted-foreground",children:"Gemini API Key"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{id:"gemini-key",type:i.gemini?"text":"password",value:n,onChange:x=>m(x.target.value),placeholder:i.gemini?"AIza...":h(n)||"AIza...",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20 font-mono text-sm"}),e.jsx(M,{type:"button",variant:"outline",size:"icon",onClick:()=>u("gemini"),className:"border-gray-200",children:i.gemini?e.jsx(fr,{className:"w-4 h-4"}):e.jsx(At,{className:"w-4 h-4"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Get your API key from ai.google.dev"})]})]})]})]})]})}function _S({aiRemarkGeneration:t,onRemarkGenerationChange:s}){return e.jsxs(G,{className:"border-0 shadow-sm",children:[e.jsxs(te,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vr,{className:"w-5 h-5 text-re-green"}),e.jsx(se,{className:"text-base font-semibold",children:"AI Features"})]}),e.jsx(he,{className:"text-sm",children:"Enable/disable specific AI-powered features"})]}),e.jsx(Y,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 border border-gray-200 rounded-md hover:bg-gray-100 transition-colors",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"AI Remark Generation"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Automatically generate conclusion remarks for workflow closures"})]}),e.jsx(ts,{checked:t,onCheckedChange:s})]})})})]})}function LS({maxRemarkChars:t,onMaxRemarkCharsChange:s}){return e.jsxs(G,{className:"border-0 shadow-sm",children:[e.jsxs(te,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nd,{className:"w-5 h-5 text-re-green"}),e.jsx(se,{className:"text-base font-semibold",children:"AI Parameters"})]}),e.jsx(he,{className:"text-sm",children:"Configure AI generation parameters"})]}),e.jsx(Y,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"max-remark-chars",className:"text-sm font-medium",children:"Maximum Remark Characters"}),e.jsx(xe,{id:"max-remark-chars",type:"number",min:"100",max:"2000",value:t,onChange:a=>s(parseInt(a.target.value)||500),className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Maximum character limit for AI-generated conclusion remarks (100-2000 characters)"})]})})]})}function FS(){const[t,s]=g.useState(!0),[a,r]=g.useState(!1),[n,i]=g.useState({claude:!1,openai:!1,gemini:!1}),[o,l]=g.useState({aiEnabled:!0,aiProvider:"claude",claudeApiKey:"",openaiApiKey:"",geminiApiKey:"",aiRemarkGeneration:!0,maxRemarkChars:500});g.useEffect(()=>{c()},[]);const c=async()=>{try{s(!0);const x=await Yr("AI_CONFIGURATION"),p={};x.forEach(y=>{p[y.configKey]=y.configValue}),l({aiEnabled:p.AI_ENABLED==="true",aiProvider:p.AI_PROVIDER||"claude",claudeApiKey:p.CLAUDE_API_KEY||"",openaiApiKey:p.OPENAI_API_KEY||"",geminiApiKey:p.GEMINI_API_KEY||"",aiRemarkGeneration:p.AI_REMARK_GENERATION_ENABLED==="true",maxRemarkChars:parseInt(p.AI_REMARK_MAX_CHARACTERS||"500")})}catch(x){console.error("Failed to load AI configurations:",x),fe.error("Failed to load AI configurations")}finally{s(!1)}},d=async()=>{var x,p;try{r(!0),await Promise.all([bt("AI_ENABLED",o.aiEnabled.toString()),bt("AI_PROVIDER",o.aiProvider),bt("CLAUDE_API_KEY",o.claudeApiKey),bt("OPENAI_API_KEY",o.openaiApiKey),bt("GEMINI_API_KEY",o.geminiApiKey),bt("AI_REMARK_GENERATION_ENABLED",o.aiRemarkGeneration.toString()),bt("AI_REMARK_MAX_CHARACTERS",o.maxRemarkChars.toString())]),fe.success("AI configuration saved successfully"),await c()}catch(y){console.error("Failed to save AI configuration:",y),fe.error(((p=(x=y.response)==null?void 0:x.data)==null?void 0:p.error)||"Failed to save AI configuration")}finally{r(!1)}},m=x=>{l(p=>({...p,...x}))},u=x=>{i(p=>({...p,[x]:!p[x]}))},h=x=>!x||x.length===0?"":x.length<=8?"••••••••":x.substring(0,4)+"••••••••"+x.substring(x.length-4);return t?e.jsx(G,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(Y,{className:"p-12 text-center",children:[e.jsx(Le,{className:"w-8 h-8 animate-spin text-re-green mx-auto mb-4"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Loading AI configuration..."})]})}):e.jsxs(G,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(te,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(Vr,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(se,{className:"text-lg font-semibold text-gray-900",children:"AI Features Configuration"}),e.jsx(he,{className:"text-sm text-gray-600",children:"Configure AI provider, API keys, and enable/disable AI-powered features"})]})]})}),e.jsxs(Y,{className:"space-y-6",children:[e.jsx(IS,{aiEnabled:o.aiEnabled,aiProvider:o.aiProvider,claudeApiKey:o.claudeApiKey,openaiApiKey:o.openaiApiKey,geminiApiKey:o.geminiApiKey,showApiKeys:n,onAiEnabledChange:x=>m({aiEnabled:x}),onProviderChange:x=>m({aiProvider:x}),onClaudeApiKeyChange:x=>m({claudeApiKey:x}),onOpenaiApiKeyChange:x=>m({openaiApiKey:x}),onGeminiApiKeyChange:x=>m({geminiApiKey:x}),onToggleApiKeyVisibility:u,maskApiKey:h}),e.jsx(yt,{}),e.jsx(_S,{aiRemarkGeneration:o.aiRemarkGeneration,onRemarkGenerationChange:x=>m({aiRemarkGeneration:x})}),e.jsx(yt,{}),e.jsx(LS,{maxRemarkChars:o.maxRemarkChars,onMaxRemarkCharsChange:x=>m({maxRemarkChars:x})}),e.jsx("div",{className:"flex justify-end pt-4",children:e.jsx(M,{onClick:d,disabled:a,className:"bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:a?e.jsxs(e.Fragment,{children:[e.jsx(Le,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Vs,{className:"w-4 h-4 mr-2"}),"Save AI Configuration"]})})})]})]})}const Vc=["Admin Only","Initiator Only","Approver Only","Initiator & Approver","Admin & Initiator","Admin & Approver","All Roles"];function OS({spectatorPermission:t,linkSharingPermission:s,onSpectatorPermissionChange:a,onLinkSharingPermissionChange:r}){return e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"spectator-permission",children:"Spectator Addition Permission"}),e.jsxs(we,{value:t,onValueChange:a,children:[e.jsx(Se,{id:"spectator-permission",children:e.jsx(Ce,{placeholder:"Select permission"})}),e.jsx(Ae,{children:Vc.map(n=>e.jsx(V,{value:n,children:n},n))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"link-sharing-permission",children:"Link Sharing Permission"}),e.jsxs(we,{value:s,onValueChange:r,children:[e.jsx(Se,{id:"link-sharing-permission",children:e.jsx(Ce,{placeholder:"Select permission"})}),e.jsx(Ae,{children:Vc.map(n=>e.jsx(V,{value:n,children:n},n))})]})]})]})}function $S({requirePassword:t,allowExternalSharing:s,onRequirePasswordChange:a,onAllowExternalSharingChange:r}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Require Password for Shared Links"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add password protection to workflow sharing links"})]}),e.jsx(ts,{checked:t,onCheckedChange:a})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Allow External Sharing"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Enable sharing workflows with external users outside the organization"})]}),e.jsx(ts,{checked:s,onCheckedChange:r})]})]})}function US(){const[t,s]=g.useState({spectatorPermission:"Initiator & Approver",linkSharingPermission:"Admin & Initiator",requirePassword:!0,allowExternalSharing:!1}),a=()=>{fe.success("Sharing policy saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsx(se,{children:"Workflow Sharing Policy"}),e.jsx(he,{children:"Control who can add spectators and share workflow links"})]}),e.jsxs(Y,{className:"space-y-6",children:[e.jsx(OS,{spectatorPermission:t.spectatorPermission,linkSharingPermission:t.linkSharingPermission,onSpectatorPermissionChange:n=>r({spectatorPermission:n}),onLinkSharingPermissionChange:n=>r({linkSharingPermission:n})}),e.jsx(yt,{}),e.jsx($S,{requirePassword:t.requirePassword,allowExternalSharing:t.allowExternalSharing,onRequirePasswordChange:n=>r({requirePassword:n}),onAllowExternalSharingChange:n=>r({allowExternalSharing:n})}),e.jsxs(M,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(Vs,{className:"w-4 h-4 mr-2"}),"Save Sharing Policy"]})]})]})}function VS(){const{user:t}=Bt(),[s,a]=g.useState(""),[r,n]=g.useState("sharing"),i=[{name:"Request Volume & Status",count:4,kpis:[{id:"total-requests",title:"Total Requests Created",description:"Count of all workflow requests created in a selected period.",value:5,change:12,changeType:"up",period:"Month",visibleTo:["Initiator","Management","Admin"],category:"Request Volume & Status",bgColor:"bg-blue-50",borderColor:"border-blue-200"},{id:"open-requests",title:"Open Requests",description:"Number of workflows currently in progress with age.",value:3,change:-5,changeType:"down",period:"Today",visibleTo:["Initiator","Management","Admin"],category:"Request Volume & Status",bgColor:"bg-blue-50",borderColor:"border-blue-200"},{id:"approved-requests",title:"Approved Requests",description:"Requests fully approved and closed.",value:1,change:8,changeType:"up",period:"Month",visibleTo:["Initiator","Management","Admin"],category:"Request Volume & Status",bgColor:"bg-blue-50",borderColor:"border-blue-200"},{id:"rejected-requests",title:"Rejected Requests",description:"Requests rejected at any approval stage.",value:1,period:"Month",visibleTo:["Initiator","Management","Admin"],category:"Request Volume & Status",bgColor:"bg-blue-50",borderColor:"border-blue-200"}]},{name:"TAT Efficiency",count:3,kpis:[{id:"avg-tat-compliance",title:"Average TAT Compliance %",description:"% of workflows completed within defined TAT vs breached ones at every level.",value:100,unit:"%",change:3,changeType:"up",period:"Month",visibleTo:["Initiator","Management","Admin"],category:"TAT Efficiency",bgColor:"bg-green-50",borderColor:"border-green-200"},{id:"avg-approval-cycle",title:"Avg Approval Cycle Time (Days)",description:"Average total time from creation to closure.",value:5.2,unit:" days",change:-15,changeType:"down",period:"Month",visibleTo:["Initiator","Management","Admin"],category:"TAT Efficiency",bgColor:"bg-green-50",borderColor:"border-green-200",thresholdBreached:!0},{id:"delayed-workflows",title:"Delayed Workflows",description:"Requests currently breaching their TAT.",value:0,change:-2,changeType:"down",period:"Today",visibleTo:["Initiator","Management","Admin"],category:"TAT Efficiency",bgColor:"bg-green-50",borderColor:"border-green-200"}]},{name:"Approver Load",count:2,kpis:[{id:"pending-actions",title:"Pending Actions (My Queue)",description:"Requests currently awaiting user's approval with age.",value:3,period:"Today",visibleTo:["Management","Admin"],category:"Approver Load",bgColor:"bg-orange-50",borderColor:"border-orange-200"},{id:"approvals-completed",title:"Approvals Completed (Today/Week)",description:"Count of actions taken within a time frame.",value:0,change:22,changeType:"up",period:"Week",visibleTo:["Management","Admin"],category:"Approver Load",bgColor:"bg-orange-50",borderColor:"border-orange-200"}]},{name:"Engagement & Quality",count:2,kpis:[{id:"comments-worknotes",title:"Comments / Work Notes Added",description:"Measures collaboration activity.",value:8,change:18,changeType:"up",period:"Week",visibleTo:["Management","Admin"],category:"Engagement & Quality",bgColor:"bg-purple-50",borderColor:"border-purple-200"},{id:"attachments-uploaded",title:"Attachments Uploaded",description:"Number of documents added to workflows.",value:16,change:10,changeType:"up",period:"Month",visibleTo:["Initiator","Management","Admin"],category:"Engagement & Quality",bgColor:"bg-purple-50",borderColor:"border-purple-200"}]},{name:"AI & Closure Insights",count:2,kpis:[{id:"avg-conclusion-length",title:"Avg Conclusion Remark Length",description:"Indicates depth of closure remarks (optional).",value:85,unit:" chars",change:5,changeType:"up",period:"Month",visibleTo:["Management","Admin"],category:"AI & Closure Insights",bgColor:"bg-pink-50",borderColor:"border-pink-200"},{id:"ai-summary-adoption",title:"AI Summary Adoption %",description:"How many closures used AI-generated text vs manual edits.",value:0,unit:"%",change:25,changeType:"up",period:"Month",visibleTo:["Management","Admin"],category:"AI & Closure Insights",bgColor:"bg-pink-50",borderColor:"border-pink-200"}]}],o=i.map(d=>({...d,kpis:d.kpis.filter(m=>m.title.toLowerCase().includes(s.toLowerCase())||m.description.toLowerCase().includes(s.toLowerCase())||m.category.toLowerCase().includes(s.toLowerCase()))})).filter(d=>d.kpis.length>0),l=i.reduce((d,m)=>d+m.count,0),c=d=>{switch(d){case"Initiator":return"bg-blue-100 text-blue-800 border-blue-200";case"Management":return"bg-orange-100 text-orange-800 border-orange-200";case"Admin":return"bg-purple-100 text-purple-800 border-purple-200";default:return"bg-gray-100 text-gray-800 border-gray-200"}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-re-black flex items-center gap-2",children:[e.jsx(Gt,{className:"w-8 h-8 text-re-green"}),"Admin Control Panel"]}),e.jsx("p",{className:"text-muted-foreground",children:"Manage users, configure system settings, and control portal behavior"})]}),e.jsxs(Q,{className:"bg-re-green/10 text-re-green border-re-green/20 px-4 py-2",children:[e.jsx(Gt,{className:"w-4 h-4 mr-2"}),"Administrator: ",(t==null?void 0:t.displayName)||"Admin User"]})]}),e.jsx(yt,{}),e.jsxs(Kr,{value:r,onValueChange:n,className:"flex flex-col gap-2 space-y-4",children:[e.jsxs(Gr,{className:"text-muted-foreground items-center justify-center rounded-xl p-[3px] bg-muted grid w-full grid-cols-9 h-auto",children:[e.jsxs(pt,{value:"kpi",className:"flex items-center gap-2",children:[e.jsx(jd,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"KPI Config"})]}),e.jsxs(pt,{value:"analytics",className:"flex items-center gap-2",children:[e.jsx(Us,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Analytics"})]}),e.jsxs(pt,{value:"users",className:"flex items-center gap-2",children:[e.jsx(at,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Users"})]}),e.jsxs(pt,{value:"tat",className:"flex items-center gap-2",children:[e.jsx(De,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"TAT"})]}),e.jsxs(pt,{value:"notifications",className:"flex items-center gap-2",children:[e.jsx(Ut,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Notify"})]}),e.jsxs(pt,{value:"documents",className:"flex items-center gap-2",children:[e.jsx(Te,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Docs"})]}),e.jsxs(pt,{value:"dashboard",className:"flex items-center gap-2",children:[e.jsx(Ox,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Dashboard"})]}),e.jsxs(pt,{value:"ai",className:"flex items-center gap-2",children:[e.jsx(wd,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"AI"})]}),e.jsxs(pt,{value:"sharing",className:"flex items-center gap-2",children:[e.jsx(wa,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Sharing"})]})]}),e.jsx(xt,{value:"kpi",className:"flex-1 outline-none space-y-4",children:e.jsxs(G,{children:[e.jsx(te,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{children:"KPI Configuration"}),e.jsx(he,{children:"Configure which KPIs are enabled, visible to specific roles, and set alert thresholds"})]}),e.jsxs(Q,{className:"bg-blue-50 text-blue-700",children:[l," / ",l," KPIs Active"]})]})}),e.jsxs(Y,{className:"space-y-6",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Yt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search KPIs by name, description, or category...",value:s,onChange:d=>a(d.target.value),className:"pl-10"})]})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:i.map(d=>e.jsxs("div",{className:"p-4 bg-muted/50 rounded-lg",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:d.name}),e.jsx("p",{className:"text-2xl font-semibold",children:d.count})]},d.name))}),o.map(d=>e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(as,{className:"w-5 h-5 text-re-green"}),e.jsx("h3",{className:"font-semibold",children:d.name}),e.jsxs(Q,{variant:"outline",className:"ml-auto",children:[d.kpis.length," Active"]})]}),e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3",children:d.kpis.map(m=>e.jsx("div",{className:`p-4 border rounded-lg ${m.bgColor} ${m.borderColor} transition-all hover:shadow-md ${m.thresholdBreached?"ring-2 ring-orange-500":""}`,children:e.jsx("div",{className:"flex items-start justify-between gap-4",children:e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("h4",{className:"font-medium text-sm mb-1",children:m.title}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:m.description})]}),e.jsx(Q,{className:"bg-green-100 text-green-800 text-xs",children:"Active"})]}),e.jsxs("div",{className:"flex items-end gap-3 py-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"flex items-baseline gap-1",children:[e.jsx("span",{className:"text-4xl font-bold text-re-black",children:m.value}),m.unit&&e.jsx("span",{className:"text-lg text-muted-foreground",children:m.unit})]})}),m.change!==void 0&&e.jsxs("div",{className:`flex items-center gap-1 text-xs px-2 py-1 rounded ${m.changeType==="up"?"bg-green-100 text-green-700":"bg-red-100 text-red-700"}`,children:[m.changeType==="up"?e.jsx($x,{className:"w-3 h-3"}):e.jsx(Ux,{className:"w-3 h-3"}),e.jsxs("span",{className:"font-semibold",children:[Math.abs(m.change),"%"]})]})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Visible:"}),m.visibleTo.map(u=>e.jsx(Q,{className:`${c(u)} text-xs px-1.5 py-0`,children:u},u))]}),e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:["Period: ",m.period]}),m.thresholdBreached&&e.jsxs("div",{className:"flex items-center gap-1 text-orange-600",children:[e.jsx(Re,{className:"w-3 h-3"}),e.jsx("span",{className:"font-medium",children:"Threshold Breached!"})]})]})]})]})})},m.id))})]},d.name))]})]})}),e.jsx(xt,{value:"analytics",className:"flex-1 outline-none space-y-4",children:e.jsx(cS,{})}),e.jsx(xt,{value:"users",className:"flex-1 outline-none space-y-4",children:e.jsx(xS,{})}),e.jsx(xt,{value:"tat",className:"flex-1 outline-none space-y-4",children:e.jsx(vS,{})}),e.jsx(xt,{value:"notifications",className:"flex-1 outline-none space-y-4",children:e.jsx(wS,{})}),e.jsx(xt,{value:"documents",className:"flex-1 outline-none space-y-4",children:e.jsx(TS,{})}),e.jsx(xt,{value:"dashboard",className:"flex-1 outline-none space-y-4",children:e.jsx(ES,{})}),e.jsx(xt,{value:"ai",className:"flex-1 outline-none space-y-4",children:e.jsx(FS,{})}),e.jsx(xt,{value:"sharing",className:"flex-1 outline-none space-y-4",children:e.jsx(US,{})})]})]})}function BS({isOpen:t,onClose:s,action:a,requestId:r,requestTitle:n,onSubmit:i}){const[o,l]=g.useState(""),[c,d]=g.useState(!1),m=async()=>{if(!(!o.trim()||o.length>500)){d(!0);try{await i(a,o.trim()),l(""),s()}catch(y){console.error("Error submitting approval action:",y)}finally{d(!1)}}},u=()=>{l(""),s()},x=a==="approve"?{title:"Approve Request",description:"Please provide your approval comments and remarks",icon:ve,iconColor:"text-green-600",buttonColor:"bg-green-600 hover:bg-green-700",badgeColor:"bg-green-100 text-green-800 border-green-200",placeholder:"Enter your approval comments and any conditions or notes..."}:{title:"Reject Request",description:"Please provide detailed reasons for rejection",icon:Ze,iconColor:"text-red-600",buttonColor:"bg-red-600 hover:bg-red-700",badgeColor:"bg-red-100 text-red-800 border-red-200",placeholder:"Enter detailed reasons for rejection and any suggestions for improvement..."},p=x.icon;return e.jsx(ot,{open:t,onOpenChange:u,children:e.jsxs(Je,{className:"max-w-2xl bg-white",children:[e.jsxs(lt,{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:`p-2 rounded-lg ${a==="approve"?"bg-green-100":"bg-red-100"}`,children:e.jsx(p,{className:`w-6 h-6 ${x.iconColor}`})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(et,{className:"text-xl",children:x.title}),e.jsx(Zt,{className:"mt-1",children:x.description})]})]}),e.jsxs("div",{className:"space-y-3 p-4 bg-gray-50 rounded-lg border",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium text-gray-900",children:"Request ID:"}),e.jsx(Q,{variant:"outline",className:"font-mono",children:r})]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-gray-900",children:"Title:"}),e.jsx("p",{className:"text-gray-700 mt-1",children:n})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-gray-900",children:"Action:"}),e.jsxs(Q,{className:x.badgeColor,variant:"outline",children:[e.jsx(p,{className:"w-3 h-3 mr-1"}),a==="approve"?"APPROVE":"REJECT"]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"comment",className:"text-sm font-semibold text-gray-900",children:"Comments & Remarks *"}),e.jsx(Cs,{id:"comment",placeholder:x.placeholder,value:o,onChange:y=>l(y.target.value.slice(0,500)),className:"min-h-[120px] resize-none",rows:6}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(is,{className:"w-3 h-3"}),"Comments are required and will be visible to all participants"]}),e.jsxs("span",{children:[o.length,"/500"]})]})]}),a==="reject"&&e.jsx("div",{className:"p-3 bg-orange-50 border border-orange-200 rounded-lg",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(is,{className:"w-4 h-4 text-orange-600 mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"font-medium text-orange-800",children:"Rejection Guidelines"}),e.jsx("p",{className:"text-orange-700 mt-1",children:"Please provide specific, actionable feedback to help the initiator improve their request."})]})]})}),a==="approve"&&e.jsx("div",{className:"p-3 bg-green-50 border border-green-200 rounded-lg",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(ve,{className:"w-4 h-4 text-green-600 mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"font-medium text-green-800",children:"Approval Confirmation"}),e.jsx("p",{className:"text-green-700 mt-1",children:"This request will be forwarded to the next approver or completed if this is the final step."})]})]})})]}),e.jsxs(Tt,{className:"gap-2",children:[e.jsx(M,{variant:"outline",onClick:u,disabled:c,children:"Cancel"}),e.jsx(M,{onClick:m,disabled:!o.trim()||c||o.length>500,className:x.buttonColor,children:c?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin mr-2"}),"Processing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(p,{className:"w-4 h-4 mr-2"}),a==="approve"?"Approve Request":"Reject Request"]})})]})]})})}var zS=(t,s,a,r,n,i,o,l)=>{let c=document.documentElement,d=["light","dark"];function m(x){(Array.isArray(t)?t:[t]).forEach(p=>{let y=p==="class",v=y&&i?n.map(N=>i[N]||N):n;y?(c.classList.remove(...v),c.classList.add(i&&i[x]?i[x]:x)):c.setAttribute(p,x)}),u(x)}function u(x){l&&d.includes(x)&&(c.style.colorScheme=x)}function h(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}if(r)m(r);else try{let x=localStorage.getItem(s)||a,p=o&&x==="system"?h():x;m(p)}catch{}},HS=g.createContext(void 0),qS={setTheme:t=>{},themes:[]},WS=()=>{var t;return(t=g.useContext(HS))!=null?t:qS};g.memo(({forcedTheme:t,storageKey:s,attribute:a,enableSystem:r,enableColorScheme:n,defaultTheme:i,value:o,themes:l,nonce:c,scriptProps:d})=>{let m=JSON.stringify([a,s,i,t,l,o,r,n]).slice(1,-1);return g.createElement("script",{...d,suppressHydrationWarning:!0,nonce:typeof window>"u"?c:"",dangerouslySetInnerHTML:{__html:`(${zS.toString()})(${m})`}})});const KS=({...t})=>{const{theme:s="system"}=WS();return e.jsx(Vx,{theme:s,className:"toaster group",style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)"},...t})};function GS({onViewRequest:t}){const{user:s}=Bt();return qr(s)?e.jsx(l2,{onViewRequest:t}):e.jsx(m2,{onViewRequest:t})}function YS({onLogout:t}){const s=Bs(),[a,r]=g.useState(null),[n,i]=g.useState([]),[o,l]=g.useState(""),[c,d]=g.useState("");g.useEffect(()=>{const f=localStorage.getItem("dynamicRequests");if(f)try{const b=JSON.parse(f);i(b)}catch(b){console.error("Error parsing dynamic requests:",b)}},[]),g.useEffect(()=>{n.length>0&&localStorage.setItem("dynamicRequests",JSON.stringify(n))},[n]);const m=f=>{if(f==="profile"){s("/profile");return}if(f==="settings"){s("/settings");return}f.startsWith("/")?s(f):s(`/${f}`)},u=async(f,b,j)=>{l(f),d(b||"Unknown Request");const C=(j==null?void 0:j.toLowerCase())==="draft"||j==="DRAFT";s(C?`/edit-request/${f}`:`/request/${f}`)},h=()=>{s(-1)},x=()=>{s("/new-request")},p=f=>{var C,R,I,T,E,w,S,D,H,L,F;if(f.templateType){f.templateType==="claim-management"&&s("/claim-management");return}const b=`RE-REQ-2024-${String(Object.keys(lm).length+n.length+1).padStart(3,"0")}`,j={id:b,title:f.title,description:f.description||"",category:f.category||"General",subcategory:f.subcategory||"",status:"pending",priority:f.priority||"standard",amount:f.budget||"N/A",slaProgress:0,slaRemaining:"5 days",slaEndDate:new Date(Date.now()+5*24*60*60*1e3).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0}),currentStep:1,totalSteps:((C=f.approvers)==null?void 0:C.length)||1,currentApprover:((I=(R=f.approvers)==null?void 0:R[0])==null?void 0:I.name)||((w=(E=(T=f.approvers)==null?void 0:T[0])==null?void 0:E.email)==null?void 0:w.split("@")[0])||"Pending Assignment",approverLevel:`1 of ${((S=f.approvers)==null?void 0:S.length)||1}`,template:"custom",initiator:{name:"Current User",role:f.initiatorRole||"Employee",department:f.department||"General",email:"current.user@royalenfield.com",phone:"+91 98765 43290",avatar:"CU"},department:f.department||"General",createdAt:new Date().toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0}),updatedAt:new Date().toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0}),dueDate:new Date(Date.now()+5*24*60*60*1e3).toISOString(),submittedDate:new Date().toISOString(),estimatedCompletion:new Date(Date.now()+5*24*60*60*1e3).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),conclusionRemark:"",approvalFlow:(f.approvers||[]).filter(A=>A).map((A,k)=>{var W;const P=(A==null?void 0:A.name)||((W=A==null?void 0:A.email)==null?void 0:W.split("@")[0])||`Approver ${k+1}`,_=(A==null?void 0:A.email)||"";return{step:k+1,approver:`${P}${_?` (${_})`:""}`,role:(A==null?void 0:A.role)||`Level ${(A==null?void 0:A.level)||k+1} Approver`,status:k===0?"pending":"waiting",tatHours:A!=null&&A.tat?typeof A.tat=="string"?parseInt(A.tat):A.tat:48,elapsedHours:0,assignedAt:k===0?new Date().toISOString():null,comment:null,timestamp:null}}),documents:[],spectators:(f.spectators||[]).filter(A=>A&&(A.name||A.email)).map(A=>{var P;const k=(A==null?void 0:A.name)||((P=A==null?void 0:A.email)==null?void 0:P.split("@")[0])||"Observer";return{name:k,role:(A==null?void 0:A.role)||(A==null?void 0:A.department)||"Observer",avatar:k.split(" ").map(_=>_[0]).join("").toUpperCase().slice(0,2)||"OB"}}),auditTrail:[{type:"created",action:"Request Created",details:`Custom request "${f.title}" created`,user:"Current User",timestamp:new Date().toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0})},{type:"assignment",action:"Assigned to Approver",details:`Request assigned to ${((H=(D=f.approvers)==null?void 0:D[0])==null?void 0:H.name)||((F=(L=f.approvers)==null?void 0:L[0])==null?void 0:F.email)||"first approver"}`,user:"System",timestamp:new Date().toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0})}],tags:f.tags||["custom-request"]};i([...n,j]),s("/my-requests"),fe.success("Request Submitted Successfully!",{description:`Your request "${f.title}" (${b}) has been created and sent for approval.`,duration:5e3})},y=(f,b)=>new Promise(j=>{setTimeout(()=>{f==="approve"?fe.success("Request Approved",{description:"The request has been approved and forwarded to the next step.",duration:5e3}):fe.error("Request Rejected",{description:"The request has been rejected and returned to the initiator.",duration:5e3}),r(null),j(!0)},1e3)}),v=()=>{r(null)},N=f=>{var C;const j={id:`RE-REQ-2024-CM-${String(n.length+2).padStart(3,"0")}`,title:`${f.activityName} - Claim Request`,description:f.requestDescription,category:"Dealer Operations",subcategory:"Claim Management",status:"pending",priority:"standard",amount:"TBD",slaProgress:0,slaRemaining:"7 days",slaEndDate:new Date(Date.now()+7*24*60*60*1e3).toISOString(),currentStep:1,totalSteps:8,templateType:"claim-management",templateName:"Claim Management",initiator:{name:"Current User",role:"Regional Marketing Coordinator",department:"Marketing",email:"current.user@royalenfield.com",phone:"+91 98765 43290",avatar:"CU"},department:"Marketing",createdAt:new Date().toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0}),updatedAt:new Date().toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0}),dueDate:new Date(Date.now()+7*24*60*60*1e3).toISOString(),conclusionRemark:"",claimDetails:{activityName:f.activityName,activityType:f.activityType,activityDate:f.activityDate?new Date(f.activityDate).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"",location:f.location,dealerCode:f.dealerCode,dealerName:f.dealerName,dealerEmail:f.dealerEmail||"N/A",dealerPhone:f.dealerPhone||"N/A",dealerAddress:f.dealerAddress||"N/A",requestDescription:f.requestDescription,estimatedBudget:f.estimatedBudget||"TBD",periodStart:f.periodStartDate?new Date(f.periodStartDate).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"",periodEnd:f.periodEndDate?new Date(f.periodEndDate).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):""},approvalFlow:f.workflowSteps||[{step:1,approver:`${f.dealerName} (Dealer)`,role:"Dealer - Document Upload",status:"pending",tatHours:72,elapsedHours:0,assignedAt:new Date().toISOString(),comment:null,timestamp:null,description:"Dealer uploads proposal document, cost breakup, timeline for closure, and other supporting documents"},{step:2,approver:"Current User (Initiator)",role:"Initiator Evaluation",status:"waiting",tatHours:48,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Initiator reviews dealer documents and approves or requests modifications"},{step:3,approver:"System Auto-Process",role:"IO Confirmation",status:"waiting",tatHours:1,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Automatic IO (Internal Order) confirmation generated upon initiator approval"},{step:4,approver:"Rajesh Kumar",role:"Department Lead Approval",status:"waiting",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Department head approves and blocks budget in IO for this activity"},{step:5,approver:`${f.dealerName} (Dealer)`,role:"Dealer - Completion Documents",status:"waiting",tatHours:120,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Dealer submits activity completion documents and description"},{step:6,approver:"Current User (Initiator)",role:"Initiator Verification",status:"waiting",tatHours:48,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Initiator verifies completion documents and can modify approved amount"},{step:7,approver:"System Auto-Process",role:"E-Invoice Generation",status:"waiting",tatHours:1,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Auto-generate e-invoice based on final approved amount"},{step:8,approver:"Finance Team",role:"Credit Note Issuance",status:"waiting",tatHours:48,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Finance team issues credit note to dealer"}],documents:[],spectators:[],auditTrail:[{type:"created",action:"Request Created",details:`Claim request for ${f.activityName} created`,user:"Current User",timestamp:new Date().toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0})}],tags:["claim-management","new-request",(C=f.activityType)==null?void 0:C.toLowerCase().replace(/\s+/g,"-")]};i(R=>[...R,j]),fe.success("Claim Request Submitted",{description:"Your claim management request has been created successfully."}),s("/my-requests")};return e.jsxs("div",{className:"min-h-screen h-screen flex flex-col overflow-hidden bg-background",children:[e.jsxs(qx,{children:[e.jsx(ut,{path:"/login/callback",element:e.jsx(Fd,{})}),e.jsx(ut,{path:"/",element:e.jsx(Et,{currentPage:"dashboard",onNavigate:m,onNewRequest:x,onLogout:t,children:e.jsx(ll,{onNavigate:m,onNewRequest:x})})}),e.jsx(ut,{path:"/dashboard",element:e.jsx(Et,{currentPage:"dashboard",onNavigate:m,onNewRequest:x,onLogout:t,children:e.jsx(ll,{onNavigate:m,onNewRequest:x})})}),e.jsx(ut,{path:"/open-requests",element:e.jsx(Et,{currentPage:"open-requests",onNavigate:m,onNewRequest:x,onLogout:t,children:e.jsx(b0,{onViewRequest:u})})}),e.jsx(ut,{path:"/closed-requests",element:e.jsx(Et,{currentPage:"closed-requests",onNavigate:m,onNewRequest:x,onLogout:t,children:e.jsx(I0,{onViewRequest:u})})}),e.jsx(ut,{path:"/shared-summaries",element:e.jsx(Et,{currentPage:"shared-summaries",onNavigate:m,onNewRequest:x,onLogout:t,children:e.jsx(Fy,{})})}),e.jsx(ut,{path:"/shared-summaries/:sharedSummaryId",element:e.jsx(Et,{currentPage:"shared-summaries",onNavigate:m,onNewRequest:x,onLogout:t,children:e.jsx(Oy,{})})}),e.jsx(ut,{path:"/my-requests",element:e.jsx(Et,{currentPage:"my-requests",onNavigate:m,onNewRequest:x,onLogout:t,children:e.jsx(YC,{onViewRequest:u,dynamicRequests:n})})}),e.jsx(ut,{path:"/requests",element:e.jsx(Et,{currentPage:"requests",onNavigate:m,onNewRequest:x,onLogout:t,children:e.jsx(GS,{onViewRequest:u})})}),e.jsx(ut,{path:"/approver-performance",element:e.jsx(Et,{currentPage:"approver-performance",onNavigate:m,onNewRequest:x,onLogout:t,children:e.jsx(A2,{})})}),e.jsx(ut,{path:"/request/:requestId",element:e.jsx(Et,{currentPage:"request-detail",onNavigate:m,onNewRequest:x,onLogout:t,children:e.jsx(Ly,{requestId:"",onBack:h,dynamicRequests:n})})}),e.jsx(ut,{path:"/work-notes/:requestId",element:e.jsx($y,{})}),e.jsx(ut,{path:"/new-request",element:e.jsx(Ic,{onBack:h,onSubmit:p})}),e.jsx(ut,{path:"/edit-request/:requestId",element:e.jsx(Ic,{onBack:h,onSubmit:p,requestId:void 0,isEditMode:!0})}),e.jsx(ut,{path:"/claim-management",element:e.jsx(OC,{onBack:h,onSubmit:N})}),e.jsx(ut,{path:"/profile",element:e.jsx(Et,{currentPage:"profile",onNavigate:m,onNewRequest:x,onLogout:t,children:e.jsx(T2,{})})}),e.jsx(ut,{path:"/settings",element:e.jsx(Et,{currentPage:"settings",onNavigate:m,onNewRequest:x,onLogout:t,children:e.jsx(F2,{})})}),e.jsx(ut,{path:"/notifications",element:e.jsx(Et,{currentPage:"notifications",onNavigate:m,onNewRequest:x,onLogout:t,children:e.jsx(O2,{onNavigate:m})})}),e.jsx(ut,{path:"/detailed-reports",element:e.jsx(Et,{currentPage:"detailed-reports",onNavigate:m,onNewRequest:x,onLogout:t,children:e.jsx(aS,{})})}),e.jsx(ut,{path:"/admin",element:e.jsx(Et,{currentPage:"admin",onNavigate:m,onNewRequest:x,onLogout:t,children:e.jsx(VS,{})})})]}),e.jsx(KS,{position:"top-right",toastOptions:{style:{background:"var(--card)",color:"var(--card-foreground)",border:"1px solid var(--border)"}}}),a&&e.jsx(BS,{isOpen:!!a,onClose:v,action:a,requestId:o,requestTitle:c,onSubmit:y})]})}function ZS(t){const{onLogout:s}=t||{};return e.jsx(Hx,{children:e.jsx(YS,{onLogout:s})})}function XS(){const{isAuthenticated:t,isLoading:s,error:a,user:r,logout:n}=Bt(),[i,o]=g.useState(!1),l=typeof window<"u"&&window.location.pathname==="/login/callback",c=async()=>{try{if(!n){console.error("🔵 ERROR: logout function is undefined!");return}await n()}catch(d){console.error("🔵 Logout error in handleLogout:",d);try{localStorage.clear(),sessionStorage.clear(),window.location.href="/"}catch(m){console.error("🔵 Error during emergency cleanup:",m)}}};return g.useEffect(()=>{},[t,s,a,r]),l?e.jsx(Fd,{}):s?e.jsx("div",{className:"flex items-center justify-center min-h-screen bg-gradient-to-br from-slate-50 to-slate-100",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-4 border-slate-900 border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading authentication..."})]})}):a?(console.error("Authentication Error:",a),e.jsx("div",{className:"flex items-center justify-center min-h-screen bg-gradient-to-br from-slate-50 to-slate-100",children:e.jsxs("div",{className:"bg-red-50 border border-red-200 text-red-700 px-6 py-4 rounded-lg max-w-md",children:[e.jsx("h3",{className:"font-semibold mb-2",children:"Authentication Error"}),e.jsx("p",{className:"text-sm mb-4",children:a.message}),e.jsx("button",{onClick:()=>window.location.reload(),className:"bg-red-600 text-white px-4 py-2 rounded hover:bg-red-700",children:"Retry"})]})})):t?e.jsxs(e.Fragment,{children:[e.jsx(ZS,{onLogout:c}),i&&e.jsx(mf,{isOpen:i,onClose:()=>o(!1)})]}):e.jsx(cf,{})}const QS={user:null,token:localStorage.getItem("token"),isAuthenticated:!1,isLoading:!1,error:null},Th=Cd({name:"auth",initialState:QS,reducers:{loginStart:t=>{t.isLoading=!0,t.error=null},loginSuccess:(t,s)=>{t.isLoading=!1,t.isAuthenticated=!0,t.user=s.payload.user,t.token=s.payload.token,t.error=null,localStorage.setItem("token",s.payload.token)},loginFailure:(t,s)=>{t.isLoading=!1,t.isAuthenticated=!1,t.user=null,t.token=null,t.error=s.payload,localStorage.removeItem("token")},logout:t=>{t.isAuthenticated=!1,t.user=null,t.token=null,t.error=null,localStorage.removeItem("token")},clearError:t=>{t.error=null},updateUser:(t,s)=>{t.user=s.payload}}}),{loginStart:cA,loginSuccess:dA,loginFailure:mA,logout:uA,clearError:hA,updateUser:pA}=Th.actions,JS=zx({reducer:{auth:Th.reducer,dashboard:Bd.reducer},middleware:t=>t({serializableCheck:{ignoredActions:["persist/PERSIST"]}}),devTools:!1});Gn.createRoot(document.getElementById("root")).render(e.jsx(Fp.StrictMode,{children:e.jsx(mg,{store:JS,children:e.jsx(Rg,{children:e.jsx(XS,{})})})}));export{ie as a}; //# sourceMappingURL=index-CePk9sgI.js.map