65 lines
1006 KiB
JavaScript
65 lines
1006 KiB
JavaScript
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/conclusionApi-D1TurBfA.js","assets/radix-vendor-C2EbRL2a.js","assets/charts-vendor-Cji9-Yri.js","assets/utils-vendor-DHm03ykU.js","assets/ui-vendor-BaYtMwB9.js","assets/socket-vendor-TjCxX7sJ.js","assets/redux-vendor-tbZCm13o.js","assets/router-vendor-CRr9x_Jp.js"])))=>i.map(i=>d[i]);
|
||
var wh=Object.defineProperty;var Ch=(t,s,a)=>s in t?wh(t,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[s]=a;var mn=(t,s,a)=>Ch(t,typeof s!="symbol"?s+"":s,a);import{j as e,S as Wc,R as Kc,I as Gc,F as Yc,a as Sh,T as Ah,P as Th,C as kh,b as Rh,O as Xc,c as Zc,d as Dh,e as Ph,f as Eh,D as Mh,g as Ih,A as Fh,h as _h,i as Lh,k as Oh,l as $h,m as Uh,n as Bh,V as Vh,o as zh,p as Hh,q as qh,r as Wh,s as Kh,t as Gh,u as Yh,v as Xh,w as Zh,x as Qh,y as Jh,z as ep,B as tp,E as sp,G as ap,H as rp,L as np,J as ip,K as op,M as Qc,N as Jc,Q as lp,U as ed,W as td,X as cp,Y as dp,Z as mp,_ as up,$ as hp,a0 as pp,a1 as xp,a2 as gp,a3 as fp,a4 as yp,a5 as vp,a6 as bp,a7 as jp,a8 as Np,a9 as wp,aa as Cp,ab as Sp}from"./radix-vendor-C2EbRL2a.js";import{a as Ap,r as x,c as sd,d as Pi,B as Tp,C as ad,X as rd,Y as nd,T as Ei,L as id,e as un,P as kp,f as Rp,g as Dp,h as Pp,i as Wo,j as zr,k as Hr,b as Ep}from"./charts-vendor-Cji9-Yri.js";import{a as od,f as ld,b as xe,d as Mp,c as Ip,e as Fp,s as Yt,g as Mi,h as Ko,i as _p,j as ps,k as Wa,l as Ii,m as cd,n as zt,o as Wt,p as hn,q as Ts,r as Lp,t as Jn,u as Op,v as ei,w as $p,x as Up,y as Bp,z as Vp,A as pn,B as Go,C as zp,D as dd,E as md,F as Fi,G as _i,H as Hp,I as qp,J as ud}from"./utils-vendor-DHm03ykU.js";import{L as Wp,C as Pe,a as ti,b as Ue,X as lt,H as Kp,c as hd,U as it,F as Ae,d as je,S as Sa,P as _s,e as Gp,f as Yp,B as Ft,g as Ls,h as xn,i as pd,j as xd,k as Aa,l as Xp,m as sr,n as We,R as Et,I as ar,T as ct,o as Ie,p as ls,q as Zp,A as Nt,r as is,M as vs,s as qr,t as as,u as Qp,D as ns,Z as Li,v as nt,w as Xt,x as gd,y as fd,z as Ka,E as Je,G as be,J as Wr,O as si,K as xs,N as Jp,Q as ex,V as tx,W as sx,Y as ax,_ as rx,$ as nx,a0 as ix,a1 as ox,a2 as lx,a3 as cx,a4 as dx,a5 as Oi,a6 as yd,a7 as Os,a8 as Ir,a9 as Yo,aa as fr,ab as vd,ac as mx,ad as Vs,ae as kt,af as Na,ag as ux,ah as hx,ai as px,aj as $i,ak as Kr,al as It,am as xx,an as gx,ao as fx,ap as yx,aq as vx,ar as bx,as as jx,at as bd,au as Ar,av as Gr,aw as ai,ax as Nx,ay as jd,az as wx,aA as Cx,aB as Sx,aC as Ui,aD as Nd,aE as Ax,aF as Tx,aG as Yr,aH as Xr,aI as Bi,aJ as kx,aK as wd,aL as Xo,aM as zs,aN as Rx,aO as Dx,aP as Vi,aQ as Px,aR as ha,aS as Cd,aT as Zo,aU as Ex,aV as Mx,aW as Ix,aX as Sd,aY as Fx,aZ as _x,a_ as Lx,a$ as Ox,b0 as $x}from"./ui-vendor-BaYtMwB9.js";import{l as Ux}from"./socket-vendor-TjCxX7sJ.js";import{c as Ta,a as Bx}from"./redux-vendor-tbZCm13o.js";import{u as rr,a as Hs,b as Ad,B as Vx,R as zx,c as ht}from"./router-vendor-CRr9x_Jp.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 ri={},Qo=Ap;ri.createRoot=Qo.createRoot,ri.hydrateRoot=Qo.hydrateRoot;var Td={exports:{}},kd={};/**
|
||
* @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 nr=x;function Hx(t,s){return t===s&&(t!==0||1/t===1/s)||t!==t&&s!==s}var qx=typeof Object.is=="function"?Object.is:Hx,Wx=nr.useSyncExternalStore,Kx=nr.useRef,Gx=nr.useEffect,Yx=nr.useMemo,Xx=nr.useDebugValue;kd.useSyncExternalStoreWithSelector=function(t,s,a,r,n){var i=Kx(null);if(i.current===null){var o={hasValue:!1,value:null};i.current=o}else o=i.current;i=Yx(function(){function c(p){if(!d){if(d=!0,m=p,p=r(p),n!==void 0&&o.hasValue){var g=o.value;if(n(g,p))return u=g}return u=p}if(g=u,qx(m,p))return g;var y=r(p);return n!==void 0&&n(g,y)?(m=p,g):(m=p,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=Wx(t,i[0],i[1]);return Gx(function(){o.hasValue=!0,o.value=l},[l]),Xx(l),l};Td.exports=kd;var Zx=Td.exports;function Qx(t){t()}function Jx(){let t=null,s=null;return{clear(){t=null,s=null},notify(){Qx(()=>{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 Jo={notify(){},get:()=>[]};function eg(t,s){let a,r=Jo,n=0,i=!1;function o(y){m();const v=r.subscribe(y);let w=!1;return()=>{w||(w=!0,v(),u())}}function l(){r.notify()}function c(){g.onStateChange&&g.onStateChange()}function d(){return i}function m(){n++,a||(a=t.subscribe(c),r=Jx())}function u(){n--,a&&n===0&&(a(),a=void 0,r.clear(),r=Jo)}function h(){i||(i=!0,m())}function p(){i&&(i=!1,u())}const g={addNestedSub:o,notifyNestedSubs:l,handleChangeWrapper:c,isSubscribed:d,trySubscribe:h,tryUnsubscribe:p,getListeners:()=>r};return g}var tg=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",sg=tg(),ag=()=>typeof navigator<"u"&&navigator.product==="ReactNative",rg=ag(),ng=()=>sg||rg?x.useLayoutEffect:x.useEffect,ig=ng(),gn=Symbol.for("react-redux-context"),fn=typeof globalThis<"u"?globalThis:{};function og(){if(!x.createContext)return{};const t=fn[gn]??(fn[gn]=new Map);let s=t.get(x.createContext);return s||(s=x.createContext(null),t.set(x.createContext,s)),s}var $s=og();function lg(t){const{children:s,context:a,serverState:r,store:n}=t,i=x.useMemo(()=>{const c=eg(n);return{store:n,subscription:c,getServerState:r?()=>r:void 0}},[n,r]),o=x.useMemo(()=>n.getState(),[n]);ig(()=>{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||$s;return x.createElement(l.Provider,{value:i},s)}var cg=lg;function zi(t=$s){return function(){return x.useContext(t)}}var Rd=zi();function Dd(t=$s){const s=t===$s?Rd:zi(t),a=()=>{const{store:r}=s();return r};return Object.assign(a,{withTypes:()=>a}),a}var dg=Dd();function mg(t=$s){const s=t===$s?dg:Dd(t),a=()=>s().dispatch;return Object.assign(a,{withTypes:()=>a}),a}var ug=mg(),hg=(t,s)=>t===s;function pg(t=$s){const s=t===$s?Rd:zi(t),a=(r,n={})=>{const{equalityFn:i=hg}=typeof n=="function"?{equalityFn:n}:n,o=s(),{store:l,subscription:c,getServerState:d}=o;x.useRef(!0);const m=x.useCallback({[r.name](h){return r(h)}}[r.name],[r]),u=Zx.useSyncExternalStoreWithSelector(c.addNestedSub,l.getState,d||l.getState,m,i);return x.useDebugValue(u),u};return Object.assign(a,{withTypes:()=>a}),a}var xg=pg(),ni=function(t,s){return ni=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])},ni(t,s)};function gg(t,s){if(typeof s!="function"&&s!==null)throw new TypeError("Class extends value "+String(s)+" is not a constructor or null");ni(t,s);function a(){this.constructor=t}t.prototype=s===null?Object.create(s):(a.prototype=s.prototype,new a)}var Fr=function(){return Fr=Object.assign||function(s){for(var a,r=1,n=arguments.length;r<n;r++){a=arguments[r];for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(s[i]=a[i])}return s},Fr.apply(this,arguments)};var Js=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Hi(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function qi(t,s){return t(s={exports:{}},s.exports),s.exports}var Xs=qi(function(t,s){Object.defineProperty(s,"__esModule",{value:!0});var a=function(){function r(){var n=this;this.locked=new Map,this.addToLocked=function(i,o){var l=n.locked.get(i);l===void 0?o===void 0?n.locked.set(i,[]):n.locked.set(i,[o]):o!==void 0&&(l.unshift(o),n.locked.set(i,l))},this.isLocked=function(i){return n.locked.has(i)},this.lock=function(i){return new Promise(function(o,l){n.isLocked(i)?n.addToLocked(i,o):(n.addToLocked(i),o())})},this.unlock=function(i){var o=n.locked.get(i);if(o!==void 0&&o.length!==0){var l=o.pop();n.locked.set(i,o),l!==void 0&&setTimeout(l,0)}else n.locked.delete(i)}}return r.getInstance=function(){return r.instance===void 0&&(r.instance=new r),r.instance},r}();s.default=function(){return a.getInstance()}});Hi(Xs);var fg=Hi(qi(function(t,s){var a=Js&&Js.__awaiter||function(m,u,h,p){return new(h||(h=Promise))(function(g,y){function v(C){try{f(p.next(C))}catch(b){y(b)}}function w(C){try{f(p.throw(C))}catch(b){y(b)}}function f(C){C.done?g(C.value):new h(function(b){b(C.value)}).then(v,w)}f((p=p.apply(m,u||[])).next())})},r=Js&&Js.__generator||function(m,u){var h,p,g,y,v={label:0,sent:function(){if(1&g[0])throw g[1];return g[1]},trys:[],ops:[]};return y={next:w(0),throw:w(1),return:w(2)},typeof Symbol=="function"&&(y[Symbol.iterator]=function(){return this}),y;function w(f){return function(C){return function(b){if(h)throw new TypeError("Generator is already executing.");for(;v;)try{if(h=1,p&&(g=2&b[0]?p.return:b[0]?p.throw||((g=p.return)&&g.call(p),0):p.next)&&!(g=g.call(p,b[1])).done)return g;switch(p=0,g&&(b=[2&b[0],g.value]),b[0]){case 0:case 1:g=b;break;case 4:return v.label++,{value:b[1],done:!1};case 5:v.label++,p=b[1],b=[0];continue;case 7:b=v.ops.pop(),v.trys.pop();continue;default:if(g=v.trys,!((g=g.length>0&&g[g.length-1])||b[0]!==6&&b[0]!==2)){v=0;continue}if(b[0]===3&&(!g||b[1]>g[0]&&b[1]<g[3])){v.label=b[1];break}if(b[0]===6&&v.label<g[1]){v.label=g[1],g=b;break}if(g&&v.label<g[2]){v.label=g[2],v.ops.push(b);break}g[2]&&v.ops.pop(),v.trys.pop();continue}b=u.call(m,v)}catch(N){b=[6,N],p=0}finally{h=g=0}if(5&b[0])throw b[1];return{value:b[0]?b[1]:void 0,done:!0}}([f,C])}}},n=Js;Object.defineProperty(s,"__esModule",{value:!0});var i="browser-tabs-lock-key",o={key:function(m){return a(n,void 0,void 0,function(){return r(this,function(u){throw new Error("Unsupported")})})},getItem:function(m){return a(n,void 0,void 0,function(){return r(this,function(u){throw new Error("Unsupported")})})},clear:function(){return a(n,void 0,void 0,function(){return r(this,function(m){return[2,window.localStorage.clear()]})})},removeItem:function(m){return a(n,void 0,void 0,function(){return r(this,function(u){throw new Error("Unsupported")})})},setItem:function(m,u){return a(n,void 0,void 0,function(){return r(this,function(h){throw new Error("Unsupported")})})},keySync:function(m){return window.localStorage.key(m)},getItemSync:function(m){return window.localStorage.getItem(m)},clearSync:function(){return window.localStorage.clear()},removeItemSync:function(m){return window.localStorage.removeItem(m)},setItemSync:function(m,u){return window.localStorage.setItem(m,u)}};function l(m){return new Promise(function(u){return setTimeout(u,m)})}function c(m){for(var u="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",h="",p=0;p<m;p++)h+=u[Math.floor(Math.random()*u.length)];return h}var d=function(){function m(u){this.acquiredIatSet=new Set,this.storageHandler=void 0,this.id=Date.now().toString()+c(15),this.acquireLock=this.acquireLock.bind(this),this.releaseLock=this.releaseLock.bind(this),this.releaseLock__private__=this.releaseLock__private__.bind(this),this.waitForSomethingToChange=this.waitForSomethingToChange.bind(this),this.refreshLockWhileAcquired=this.refreshLockWhileAcquired.bind(this),this.storageHandler=u,m.waiters===void 0&&(m.waiters=[])}return m.prototype.acquireLock=function(u,h){return h===void 0&&(h=5e3),a(this,void 0,void 0,function(){var p,g,y,v,w,f,C;return r(this,function(b){switch(b.label){case 0:p=Date.now()+c(4),g=Date.now()+h,y=i+"-"+u,v=this.storageHandler===void 0?o:this.storageHandler,b.label=1;case 1:return Date.now()<g?[4,l(30)]:[3,8];case 2:return b.sent(),v.getItemSync(y)!==null?[3,5]:(w=this.id+"-"+u+"-"+p,[4,l(Math.floor(25*Math.random()))]);case 3:return b.sent(),v.setItemSync(y,JSON.stringify({id:this.id,iat:p,timeoutKey:w,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,l(30)];case 4:return b.sent(),(f=v.getItemSync(y))!==null&&(C=JSON.parse(f)).id===this.id&&C.iat===p?(this.acquiredIatSet.add(p),this.refreshLockWhileAcquired(y,p),[2,!0]):[3,7];case 5:return m.lockCorrector(this.storageHandler===void 0?o:this.storageHandler),[4,this.waitForSomethingToChange(g)];case 6:b.sent(),b.label=7;case 7:return p=Date.now()+c(4),[3,1];case 8:return[2,!1]}})})},m.prototype.refreshLockWhileAcquired=function(u,h){return a(this,void 0,void 0,function(){var p=this;return r(this,function(g){return setTimeout(function(){return a(p,void 0,void 0,function(){var y,v,w;return r(this,function(f){switch(f.label){case 0:return[4,Xs.default().lock(h)];case 1:return f.sent(),this.acquiredIatSet.has(h)?(y=this.storageHandler===void 0?o:this.storageHandler,(v=y.getItemSync(u))===null?(Xs.default().unlock(h),[2]):((w=JSON.parse(v)).timeRefreshed=Date.now(),y.setItemSync(u,JSON.stringify(w)),Xs.default().unlock(h),this.refreshLockWhileAcquired(u,h),[2])):(Xs.default().unlock(h),[2])}})})},1e3),[2]})})},m.prototype.waitForSomethingToChange=function(u){return a(this,void 0,void 0,function(){return r(this,function(h){switch(h.label){case 0:return[4,new Promise(function(p){var g=!1,y=Date.now(),v=!1;function w(){if(v||(window.removeEventListener("storage",w),m.removeFromWaiting(w),clearTimeout(f),v=!0),!g){g=!0;var C=50-(Date.now()-y);C>0?setTimeout(p,C):p(null)}}window.addEventListener("storage",w),m.addToWaiting(w);var f=setTimeout(w,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,p,g,y;return r(this,function(v){switch(v.label){case 0:return h=this.storageHandler===void 0?o:this.storageHandler,p=i+"-"+u,(g=h.getItemSync(p))===null?[2]:(y=JSON.parse(g)).id!==this.id?[3,2]:[4,Xs.default().lock(y.iat)];case 1:v.sent(),this.acquiredIatSet.delete(y.iat),h.removeItemSync(p),Xs.default().unlock(y.iat),m.notifyWaiters(),v.label=2;case 2:return[2]}})})},m.lockCorrector=function(u){for(var h=Date.now()-5e3,p=u,g=[],y=0;;){var v=p.keySync(y);if(v===null)break;g.push(v),y++}for(var w=!1,f=0;f<g.length;f++){var C=g[f];if(C.includes(i)){var b=p.getItemSync(C);if(b!==null){var N=JSON.parse(b);(N.timeRefreshed===void 0&&N.timeAcquired<h||N.timeRefreshed!==void 0&&N.timeRefreshed<h)&&(p.removeItemSync(C),w=!0)}}}w&&m.notifyWaiters()},m.waiters=void 0,m}();s.default=d}));new TextEncoder;new TextDecoder;var ta=qi(function(t,s){var a=Js&&Js.__assign||function(){return a=Object.assign||function(c){for(var d,m=1,u=arguments.length;m<u;m++)for(var h in d=arguments[m])Object.prototype.hasOwnProperty.call(d,h)&&(c[h]=d[h]);return c},a.apply(this,arguments)};function r(c,d){if(!d)return"";var m="; "+c;return d===!0?m:m+"="+d}function n(c,d,m){return encodeURIComponent(c).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/\(/g,"%28").replace(/\)/g,"%29")+"="+encodeURIComponent(d).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent)+function(u){if(typeof u.expires=="number"){var h=new Date;h.setMilliseconds(h.getMilliseconds()+864e5*u.expires),u.expires=h}return r("Expires",u.expires?u.expires.toUTCString():"")+r("Domain",u.domain)+r("Path",u.path)+r("Secure",u.secure)+r("SameSite",u.sameSite)}(m)}function i(c){for(var d={},m=c?c.split("; "):[],u=/(%[\dA-F]{2})+/gi,h=0;h<m.length;h++){var p=m[h].split("="),g=p.slice(1).join("=");g.charAt(0)==='"'&&(g=g.slice(1,-1));try{d[p[0].replace(u,decodeURIComponent)]=g.replace(u,decodeURIComponent)}catch{}}return d}function o(){return i(document.cookie)}function l(c,d,m){document.cookie=n(c,d,a({path:"/"},m))}s.__esModule=!0,s.encode=n,s.parse=i,s.getAll=o,s.get=function(c){return o()[c]},s.set=l,s.remove=function(c,d){l(c,"",a(a({},d),{expires:-1}))}});Hi(ta),ta.encode,ta.parse,ta.getAll;ta.get;ta.set;ta.remove;var el;(function(t){t.Code="code",t.ConnectCode="connect_code"})(el||(el={}));var tl;(function(t){t.Bearer="Bearer",t.DPoP="DPoP"})(tl||(tl={}));new fg;var yg={isAuthenticated:!1,isLoading:!0,error:void 0,user:void 0},Bt=function(){throw new Error("You forgot to wrap your component in <Auth0Provider>.")},vg=Fr(Fr({},yg),{buildAuthorizeUrl:Bt,buildLogoutUrl:Bt,getAccessTokenSilently:Bt,getAccessTokenWithPopup:Bt,getIdTokenClaims:Bt,loginWithRedirect:Bt,loginWithPopup:Bt,connectAccountWithRedirect:Bt,logout:Bt,handleRedirectCallback:Bt,getDpopNonce:Bt,setDpopNonce:Bt,generateDpopProof:Bt,createFetcher:Bt}),bg=x.createContext(vg);(function(t){gg(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 jg=function(t){return t===void 0&&(t=bg),x.useContext(t)};const yn="idToken",vn="userData",Ng=()=>!0;class ze{static setAccessToken(s){}static getAccessToken(){return null}static setRefreshToken(s){}static getRefreshToken(){return null}static setIdToken(s){sessionStorage.setItem(yn,s)}static getIdToken(){return sessionStorage.getItem(yn)}static setUserData(s){localStorage.setItem(vn,JSON.stringify(s))}static getUserData(){const s=localStorage.getItem(vn);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(vn),sessionStorage.removeItem(yn)}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 Ng()}}function bn(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-i<o}catch{return!0}}const Pd="https://re-workflow-nt-dev.siplsolutions.com/api/v1",de=od.create({baseURL:Pd,headers:{"Content-Type":"application/json"},withCredentials:!0});de.interceptors.request.use(t=>t,t=>Promise.reject(t));de.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=ze.getRefreshToken(),o=await od.post(`${Pd}/auth/refresh`,n?{}:{refreshToken:i},{withCredentials:!0}),c=(o.data.data||o.data).accessToken;return de(s)}catch(i){return ze.clearAll(),window.location.href="/",Promise.reject(i)}}return Promise.reject(t)});async function wg(t,s){var a,r;try{const n=await de.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&&ze.setUserData(o.user),o.idToken&&ze.setIdToken(o.idToken),o.accessToken&&o.refreshToken&&(ze.setAccessToken(o.accessToken),ze.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 Cg(){var r;const t={},a=(await de.post("/auth/refresh",t)).data;if((r=a.data)!=null&&r.accessToken||a.accessToken,a.success!==!1)return"cookie-based-auth";throw new Error("Failed to refresh token")}async function yr(){const s=(await de.get("/auth/me")).data;return s.data||s}async function Sg(){var t,s;try{await de.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 Ed=x.createContext(void 0);function Ag({children:t}){const[s,a]=x.useState(!1),[r,n]=x.useState(!0),[i,o]=x.useState(null),[l,c]=x.useState(null),[d,m]=x.useState(!1);x.useEffect(()=>{const f=sessionStorage.getItem("__logout_in_progress__"),C=sessionStorage.getItem("__force_logout__");if(f==="true"||C==="true"){sessionStorage.removeItem("__logout_in_progress__"),sessionStorage.removeItem("__force_logout__"),ze.clearAll();try{localStorage.clear(),sessionStorage.clear()}catch(N){console.error("Error clearing storage:",N)}a(!1),o(null),n(!1),c(null);return}const b=new URLSearchParams(window.location.search);if(b.has("logout")||b.has("okta_logged_out")){ze.clearAll(),localStorage.clear(),sessionStorage.clear(),a(!1),o(null),n(!1);const N=new URLSearchParams;b.has("okta_logged_out")&&N.set("okta_logged_out","true");const R=N.toString()?`/?${N.toString()}`:"/";window.history.replaceState({},document.title,R);return}window.location.pathname!=="/login/callback"&&(ze.getUserData(),d?n(!1):h())},[d]),x.useEffect(()=>{if(!s)return;const f=async()=>{try{await v()}catch(N){console.error("Silent refresh failed:",N)}},C=10*60*1e3,b=setInterval(f,C);return()=>clearInterval(b)},[s]);const u=x.useRef(!1);x.useEffect(()=>{if(u.current||window.location.pathname!=="/login/callback")return;(async()=>{u.current=!0;const C=new URLSearchParams(window.location.search),b=C.get("code"),N=C.get("error");if(window.history.replaceState({},document.title,"/login/callback"),N){c(new Error(`Authentication error: ${N}`)),n(!1);return}if(!b){n(!1);return}try{n(!0),a(!1),c(null);const R=`${window.location.origin}/login/callback`,E=await wg(b,R);o(E.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()=>{var C;if(d){n(!1);return}const f=!0;try{if(n(!0),f){const R=ze.getUserData();try{const E=await yr();o(E),ze.setUserData(E),a(!0)}catch(E){if(((C=E==null?void 0:E.response)==null?void 0:C.status)===401)try{await v();const P=await yr();o(P),ze.setUserData(P),a(!0)}catch{ze.clearAll(),a(!1),o(null)}else E!=null&&E.isConnectionError?R?(o(R),a(!0)):(a(!1),o(null)):(ze.clearAll(),a(!1),o(null))}return}const b=ze.getAccessToken(),N=ze.getUserData();if(!b){a(!1),o(null),n(!1);return}if(bn(b))try{await v();const R=ze.getAccessToken();if(R&&!bn(R)){const E=ze.getUserData();if(E)o(E),a(!0);else try{const P=await yr();o(P),ze.setUserData(P),a(!0)}catch{ze.clearAll(),a(!1),o(null)}}else ze.clearAll(),a(!1),o(null)}catch{ze.clearAll(),a(!1),o(null)}else if(N)o(N),a(!0);else try{const R=await yr();o(R),ze.setUserData(R),a(!0)}catch{ze.clearAll(),a(!1),o(null)}}catch(b){console.error("Error checking auth status:",b),c(b),ze.clearAll(),a(!1),o(null)}finally{n(!1)}},p=async()=>{try{c(null);const f="https://dev-830839.oktapreview.com",C="0oa2j8slwj5S4bG5k0h8",b=`${window.location.origin}/login/callback`,N="code",R="openid profile email",E=Math.random().toString(36).substring(7),P=new URLSearchParams(window.location.search),I=P.has("logout")||P.has("okta_logged_out");let j=`${f}/oauth2/default/v1/authorize?client_id=${C}&redirect_uri=${encodeURIComponent(b)}&response_type=${N}&scope=${encodeURIComponent(R)}&state=${E}`;I&&(j+="&prompt=login"),window.location.href=j}catch(f){throw c(f),f}},g=async()=>{try{ze.getIdToken(),sessionStorage.setItem("__logout_in_progress__","true"),sessionStorage.setItem("__force_logout__","true"),m(!0),a(!1),o(null),c(null),n(!0);try{await Sg()}catch(N){console.error("🚪 Logout API error:",N),console.warn("🚪 Backend logout failed - httpOnly cookies may not be cleared")}const f=sessionStorage.getItem("__logout_in_progress__"),C=sessionStorage.getItem("__force_logout__");ze.clearAll(),f&&sessionStorage.setItem("__logout_in_progress__",f),C&&sessionStorage.setItem("__force_logout__",C),await new Promise(N=>setTimeout(N,100));const b=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(b)}catch(f){console.error("🚪 Logout error:",f);try{localStorage.clear(),sessionStorage.clear(),sessionStorage.setItem("__logout_in_progress__","true");const C=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(C)}catch{window.location.replace("/?logout="+Date.now())}}},y=async()=>{{if(s)return"cookie-based-auth";try{return await v(),s?"cookie-based-auth":null}catch{return null}}const f=ze.getAccessToken();if(f&&!bn(f))return f;try{return await v(),ze.getAccessToken()}catch{return null}},v=async()=>{try{const C=await Cg();return}catch(C){throw ze.clearAll(),a(!1),o(null),C}},w={isAuthenticated:s,isLoading:r,user:i,error:l,login:p,logout:g,getAccessTokenSilently:y,refreshTokenSilently:v};return e.jsx(Ed.Provider,{value:w,children:t})}function Tg({children:t}){return e.jsx(Ag,{children:t})}function Mt(){const t=x.useContext(Ed);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t}function Zs(t){return(t==null?void 0:t.role)==="ADMIN"}function Fa(t){return(t==null?void 0:t.role)==="MANAGEMENT"}function Zr(t){return(t==null?void 0:t.role)==="MANAGEMENT"||(t==null?void 0:t.role)==="ADMIN"}const sl=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,al=sd,Md=(t,s)=>a=>{var r;if((s==null?void 0:s.variants)==null)return al(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=sl(m)||sl(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,...p}=m;return Object.entries(p).every(g=>{let[y,v]=g;return Array.isArray(v)?v.includes({...i,...l}[y]):{...i,...l}[y]===v})?[...d,u,h]:d},[]);return al(t,o,c,a==null?void 0:a.class,a==null?void 0:a.className)},Wi="-",kg=t=>{const s=Dg(t),{conflictingClassGroups:a,conflictingClassGroupModifiers:r}=t;return{getClassGroupId:o=>{const l=o.split(Wi);return l[0]===""&&l.length!==1&&l.shift(),Id(l,s)||Rg(o)},getConflictingClassGroupIds:(o,l)=>{const c=a[o]||[];return l&&r[o]?[...c,...r[o]]:c}}},Id=(t,s)=>{var o;if(t.length===0)return s.classGroupId;const a=t[0],r=s.nextPart.get(a),n=r?Id(t.slice(1),r):void 0;if(n)return n;if(s.validators.length===0)return;const i=t.join(Wi);return(o=s.validators.find(({validator:l})=>l(i)))==null?void 0:o.classGroupId},rl=/^\[(.+)\]$/,Rg=t=>{if(rl.test(t)){const s=rl.exec(t)[1],a=s==null?void 0:s.substring(0,s.indexOf(":"));if(a)return"arbitrary.."+a}},Dg=t=>{const{theme:s,prefix:a}=t,r={nextPart:new Map,validators:[]};return Eg(Object.entries(t.classGroups),a).forEach(([i,o])=>{ii(o,r,i,s)}),r},ii=(t,s,a,r)=>{t.forEach(n=>{if(typeof n=="string"){const i=n===""?s:nl(s,n);i.classGroupId=a;return}if(typeof n=="function"){if(Pg(n)){ii(n(r),s,a,r);return}s.validators.push({validator:n,classGroupId:a});return}Object.entries(n).forEach(([i,o])=>{ii(o,nl(s,i),a,r)})})},nl=(t,s)=>{let a=t;return s.split(Wi).forEach(r=>{a.nextPart.has(r)||a.nextPart.set(r,{nextPart:new Map,validators:[]}),a=a.nextPart.get(r)}),a},Pg=t=>t.isThemeGetter,Eg=(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,Mg=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)}}},Fd="!",Ig=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;v<l.length;v++){let w=l[v];if(d===0){if(w===n&&(r||l.slice(v,v+i)===s)){c.push(l.slice(m,v)),m=v+i;continue}if(w==="/"){u=v;continue}}w==="["?d++:w==="]"&&d--}const h=c.length===0?l:l.substring(m),p=h.startsWith(Fd),g=p?h.substring(1):h,y=u&&u>m?u-m:void 0;return{modifiers:c,hasImportantModifier:p,baseClassName:g,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},_g=t=>({cache:Mg(t.cacheSize),parseClassName:Ig(t),...kg(t)}),Lg=/\s+/,Og=(t,s)=>{const{parseClassName:a,getClassGroupId:r,getConflictingClassGroupIds:n}=s,i=[],o=t.trim().split(Lg);let l="";for(let c=o.length-1;c>=0;c-=1){const d=o[c],{modifiers:m,hasImportantModifier:u,baseClassName:h,maybePostfixModifierPosition:p}=a(d);let g=!!p,y=r(g?h.substring(0,p):h);if(!y){if(!g){l=d+(l.length>0?" "+l:l);continue}if(y=r(h),!y){l=d+(l.length>0?" "+l:l);continue}g=!1}const v=Fg(m).join(":"),w=u?v+Fd:v,f=w+y;if(i.includes(f))continue;i.push(f);const C=n(y,g);for(let b=0;b<C.length;++b){const N=C[b];i.push(w+N)}l=d+(l.length>0?" "+l:l)}return l};function $g(){let t=0,s,a,r="";for(;t<arguments.length;)(s=arguments[t++])&&(a=_d(s))&&(r&&(r+=" "),r+=a);return r}const _d=t=>{if(typeof t=="string")return t;let s,a="";for(let r=0;r<t.length;r++)t[r]&&(s=_d(t[r]))&&(a&&(a+=" "),a+=s);return a};function Ug(t,...s){let a,r,n,i=o;function o(c){const d=s.reduce((m,u)=>u(m),t());return a=_g(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=Og(c,a);return n(c,m),m}return function(){return i($g.apply(null,arguments))}}const Ye=t=>{const s=a=>a[t]||[];return s.isThemeGetter=!0,s},Ld=/^\[(?:([a-z-]+):)?(.+)\]$/i,Bg=/^\d+\/\d+$/,Vg=new Set(["px","full","screen"]),zg=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Hg=/\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$/,qg=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,Wg=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Kg=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Cs=t=>va(t)||Vg.has(t)||Bg.test(t),Ps=t=>ka(t,"length",tf),va=t=>!!t&&!Number.isNaN(Number(t)),jn=t=>ka(t,"number",va),_a=t=>!!t&&Number.isInteger(Number(t)),Gg=t=>t.endsWith("%")&&va(t.slice(0,-1)),$e=t=>Ld.test(t),Es=t=>zg.test(t),Yg=new Set(["length","size","percentage"]),Xg=t=>ka(t,Yg,Od),Zg=t=>ka(t,"position",Od),Qg=new Set(["image","url"]),Jg=t=>ka(t,Qg,af),ef=t=>ka(t,"",sf),La=()=>!0,ka=(t,s,a)=>{const r=Ld.exec(t);return r?r[1]?typeof s=="string"?r[1]===s:s.has(r[1]):a(r[2]):!1},tf=t=>Hg.test(t)&&!qg.test(t),Od=()=>!1,sf=t=>Wg.test(t),af=t=>Kg.test(t),rf=()=>{const t=Ye("colors"),s=Ye("spacing"),a=Ye("blur"),r=Ye("brightness"),n=Ye("borderColor"),i=Ye("borderRadius"),o=Ye("borderSpacing"),l=Ye("borderWidth"),c=Ye("contrast"),d=Ye("grayscale"),m=Ye("hueRotate"),u=Ye("invert"),h=Ye("gap"),p=Ye("gradientColorStops"),g=Ye("gradientColorStopPositions"),y=Ye("inset"),v=Ye("margin"),w=Ye("opacity"),f=Ye("padding"),C=Ye("saturate"),b=Ye("scale"),N=Ye("sepia"),R=Ye("skew"),E=Ye("space"),P=Ye("translate"),I=()=>["auto","contain","none"],j=()=>["auto","hidden","clip","visible","scroll"],k=()=>["auto",$e,s],_=()=>[$e,s],Y=()=>["",Cs,Ps],F=()=>["auto",va,$e],L=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],A=()=>["solid","dashed","dotted","double","none"],S=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],T=()=>["start","end","center","between","around","evenly","stretch"],D=()=>["","0",$e],H=()=>["auto","avoid","all","avoid-page","page","left","right","column"],z=()=>[va,$e];return{cacheSize:500,separator:":",theme:{colors:[La],spacing:[Cs,Ps],blur:["none","",Es,$e],brightness:z(),borderColor:[t],borderRadius:["none","","full",Es,$e],borderSpacing:_(),borderWidth:Y(),contrast:z(),grayscale:D(),hueRotate:z(),invert:D(),gap:_(),gradientColorStops:[t],gradientColorStopPositions:[Gg,Ps],inset:k(),margin:k(),opacity:z(),padding:_(),saturate:z(),scale:z(),sepia:D(),skew:z(),space:_(),translate:_()},classGroups:{aspect:[{aspect:["auto","square","video",$e]}],container:["container"],columns:[{columns:[Es]}],"break-after":[{"break-after":H()}],"break-before":[{"break-before":H()}],"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:[...L(),$e]}],overflow:[{overflow:j()}],"overflow-x":[{"overflow-x":j()}],"overflow-y":[{"overflow-y":j()}],overscroll:[{overscroll:I()}],"overscroll-x":[{"overscroll-x":I()}],"overscroll-y":[{"overscroll-y":I()}],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",_a,$e]}],basis:[{basis:k()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",$e]}],grow:[{grow:D()}],shrink:[{shrink:D()}],order:[{order:["first","last","none",_a,$e]}],"grid-cols":[{"grid-cols":[La]}],"col-start-end":[{col:["auto",{span:["full",_a,$e]},$e]}],"col-start":[{"col-start":F()}],"col-end":[{"col-end":F()}],"grid-rows":[{"grid-rows":[La]}],"row-start-end":[{row:["auto",{span:[_a,$e]},$e]}],"row-start":[{"row-start":F()}],"row-end":[{"row-end":F()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",$e]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",$e]}],gap:[{gap:[h]}],"gap-x":[{"gap-x":[h]}],"gap-y":[{"gap-y":[h]}],"justify-content":[{justify:["normal",...T()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...T(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...T(),"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":[E]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[E]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",$e,s]}],"min-w":[{"min-w":[$e,s,"min","max","fit"]}],"max-w":[{"max-w":[$e,s,"none","full","min","max","fit","prose",{screen:[Es]},Es]}],h:[{h:[$e,s,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[$e,s,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[$e,s,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[$e,s,"auto","min","max","fit"]}],"font-size":[{text:["base",Es,Ps]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",jn]}],"font-family":[{font:[La]}],"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",$e]}],"line-clamp":[{"line-clamp":["none",va,jn]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Cs,$e]}],"list-image":[{"list-image":["none",$e]}],"list-style-type":[{list:["none","disc","decimal",$e]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[t]}],"placeholder-opacity":[{"placeholder-opacity":[w]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[t]}],"text-opacity":[{"text-opacity":[w]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...A(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Cs,Ps]}],"underline-offset":[{"underline-offset":["auto",Cs,$e]}],"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:_()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",$e]}],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",$e]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[w]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...L(),Zg]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",Xg]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},Jg]}],"bg-color":[{bg:[t]}],"gradient-from-pos":[{from:[g]}],"gradient-via-pos":[{via:[g]}],"gradient-to-pos":[{to:[g]}],"gradient-from":[{from:[p]}],"gradient-via":[{via:[p]}],"gradient-to":[{to:[p]}],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":[w]}],"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":[w]}],"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":[Cs,$e]}],"outline-w":[{outline:[Cs,Ps]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:Y()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[w]}],"ring-offset-w":[{"ring-offset":[Cs,Ps]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",Es,ef]}],"shadow-color":[{shadow:[La]}],opacity:[{opacity:[w]}],"mix-blend":[{"mix-blend":[...S(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":S()}],filter:[{filter:["","none"]}],blur:[{blur:[a]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",Es,$e]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[m]}],invert:[{invert:[u]}],saturate:[{saturate:[C]}],sepia:[{sepia:[N]}],"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":[w]}],"backdrop-saturate":[{"backdrop-saturate":[C]}],"backdrop-sepia":[{"backdrop-sepia":[N]}],"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",$e]}],duration:[{duration:z()}],ease:[{ease:["linear","in","out","in-out",$e]}],delay:[{delay:z()}],animate:[{animate:["none","spin","ping","pulse","bounce",$e]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[b]}],"scale-x":[{"scale-x":[b]}],"scale-y":[{"scale-y":[b]}],rotate:[{rotate:[_a,$e]}],"translate-x":[{"translate-x":[P]}],"translate-y":[{"translate-y":[P]}],"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",$e]}],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",$e]}],"caret-color":[{caret:[t]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":_()}],"scroll-mx":[{"scroll-mx":_()}],"scroll-my":[{"scroll-my":_()}],"scroll-ms":[{"scroll-ms":_()}],"scroll-me":[{"scroll-me":_()}],"scroll-mt":[{"scroll-mt":_()}],"scroll-mr":[{"scroll-mr":_()}],"scroll-mb":[{"scroll-mb":_()}],"scroll-ml":[{"scroll-ml":_()}],"scroll-p":[{"scroll-p":_()}],"scroll-px":[{"scroll-px":_()}],"scroll-py":[{"scroll-py":_()}],"scroll-ps":[{"scroll-ps":_()}],"scroll-pe":[{"scroll-pe":_()}],"scroll-pt":[{"scroll-pt":_()}],"scroll-pr":[{"scroll-pr":_()}],"scroll-pb":[{"scroll-pb":_()}],"scroll-pl":[{"scroll-pl":_()}],"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",$e]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[Cs,Ps,jn]}],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"]}}},nf=Ug(rf);function ce(...t){return nf(sd(t))}const Ga=Md("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=x.forwardRef(({className:t,variant:s,size:a,asChild:r=!1,...n},i)=>{const o=r?Wc:"button";return e.jsx(o,{"data-slot":"button",className:ce(Ga({variant:s,size:a,className:t})),ref:i,...n})});M.displayName="Button";function K({className:t,...s}){return e.jsx("div",{"data-slot":"card",className:ce("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border",t),...s})}function ae({className:t,...s}){return e.jsx("div",{"data-slot":"card-header",className:ce("@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 re({className:t,...s}){return e.jsx("h4",{"data-slot":"card-title",className:ce("leading-none",t),...s})}function ge({className:t,...s}){return e.jsx("p",{"data-slot":"card-description",className:ce("text-muted-foreground",t),...s})}function G({className:t,...s}){return e.jsx("div",{"data-slot":"card-content",className:ce("px-6 [&:last-child]:pb-6",t),...s})}const Ki="/assets/Re_Logo-By51taPS.png";function of(){const{login:t,isLoading:s,error:a}=Mt(),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(K,{className:"w-full max-w-md shadow-xl",children:[e.jsx(ae,{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:Ki,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(G,{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(Wp,{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 $d(){const{isAuthenticated:t,isLoading:s,error:a,user:r}=Mt(),[n,i]=x.useState("exchanging");x.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 r&&t&&i("complete")},[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:Ki,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(Pe,{className:"w-16 h-16 text-red-500"})}),e.jsx(Pe,{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(ti,{className:"w-16 h-16 text-green-500"})}),e.jsx(ti,{className:"w-16 h-16 text-green-500 relative"})]}):e.jsxs("div",{className:"relative",children:[e.jsx(Ue,{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"?"Loading 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 lf=Md("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 ee({className:t,variant:s,asChild:a=!1,...r}){const n=a?Wc:"span";return e.jsx(n,{"data-slot":"badge",className:ce(lf({variant:s}),t),...r})}function cf({isOpen:t,onClose:s}){const{user:a,isAuthenticated:r,isLoading:n,error:i}=jg();return x.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(K,{className:"w-full max-w-2xl max-h-[90vh] overflow-auto",children:[e.jsx(ae,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{children:"Authentication Debug Information"}),e.jsx(M,{variant:"ghost",size:"icon",onClick:s,children:e.jsx(lt,{className:"h-4 w-4"})})]})}),e.jsxs(G,{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(ee,{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 bt=x.forwardRef(({className:t,...s},a)=>e.jsx(Kc,{ref:a,"data-slot":"avatar",className:ce("relative flex size-10 shrink-0 overflow-hidden rounded-full",t),...s}));bt.displayName=Kc.displayName;const Qr=x.forwardRef(({className:t,...s},a)=>e.jsx(Gc,{ref:a,"data-slot":"avatar-image",className:ce("aspect-square size-full",t),...s}));Qr.displayName=Gc.displayName;const jt=x.forwardRef(({className:t,...s},a)=>e.jsx(Yc,{ref:a,"data-slot":"avatar-fallback",className:ce("bg-muted flex size-full items-center justify-center rounded-full",t),...s}));jt.displayName=Yc.displayName;function il({...t}){return e.jsx(Sh,{"data-slot":"dropdown-menu",...t})}function ol({...t}){return e.jsx(Ah,{"data-slot":"dropdown-menu-trigger",...t})}function ll({className:t,sideOffset:s=4,...a}){return e.jsx(Th,{children:e.jsx(kh,{"data-slot":"dropdown-menu-content",sideOffset:s,className:ce("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 Nn({className:t,inset:s,variant:a="default",...r}){return e.jsx(Rh,{"data-slot":"dropdown-menu-item","data-inset":s,"data-variant":a,className:ce("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 df({...t}){return e.jsx(Ph,{"data-slot":"alert-dialog",...t})}function mf({...t}){return e.jsx(Dh,{"data-slot":"alert-dialog-portal",...t})}const Ud=x.forwardRef(({className:t,...s},a)=>e.jsx(Xc,{"data-slot":"alert-dialog-overlay",className:ce("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}));Ud.displayName=Xc.displayName;const Bd=x.forwardRef(({className:t,...s},a)=>e.jsxs(mf,{children:[e.jsx(Ud,{}),e.jsx(Zc,{"data-slot":"alert-dialog-content",ref:a,className:ce("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})]}));Bd.displayName=Zc.displayName;function uf({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-header",className:ce("flex flex-col gap-2 text-center sm:text-left",t),...s})}function hf({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-footer",className:ce("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s})}function pf({className:t,...s}){return e.jsx(Eh,{"data-slot":"alert-dialog-title",className:ce("text-lg font-semibold",t),...s})}function xf({className:t,...s}){return e.jsx(Mh,{"data-slot":"alert-dialog-description",className:ce("text-muted-foreground text-sm",t),...s})}function gf({className:t,...s}){return e.jsx(Fh,{className:ce(Ga(),t),...s})}function ff({className:t,...s}){return e.jsx(Ih,{className:ce(Ga({variant:"outline"}),t),...s})}const Is={async list(t){return(await de.get("/notifications",{params:t})).data},async getUnreadCount(){return(await de.get("/notifications/unread-count")).data},async markAsRead(t){return(await de.patch(`/notifications/${t}/read`)).data},async markAllAsRead(){return(await de.post("/notifications/mark-all-read")).data},async delete(t){return(await de.delete(`/notifications/${t}`)).data}},yf=async()=>(await de.get("/notifications/subscriptions")).data.data.subscriptions;let Gs=null;function vf(){return"https://re-workflow-nt-dev.siplsolutions.com"}function Ya(t){const s=vf();return Gs||(Gs=Ux(s,{withCredentials:!0,transports:["websocket","polling"],path:"/socket.io",reconnection:!0,reconnectionDelay:1e3,reconnectionAttempts:5}),Gs.on("connect",()=>{}),Gs.on("connect_error",a=>{console.error("[Socket] Connection error:",a.message)}),Gs.on("disconnect",a=>{}),Gs)}function oi(t,s,a){a?t.emit("join:request",{requestId:s,userId:a}):t.emit("join:request",s)}function Vd(t,s){t.emit("leave:request",s)}function bf(t,s){t.emit("join:user",{userId:s})}function Dt({children:t,currentPage:s="dashboard",onNavigate:a,onNewRequest:r,onLogout:n}){const[i,o]=x.useState(!1),[l,c]=x.useState(!1),[d,m]=x.useState([]),[u,h]=x.useState(0),[p,g]=x.useState(!1),{user:y}=Mt(),v=()=>{var N,R;try{if(y!=null&&y.displayName&&typeof y.displayName=="string"){const E=y.displayName.split(" ").filter(Boolean);return E.length>=2?`${((N=E[0])==null?void 0:N[0])||""}${((R=E[E.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(E){return console.error("[PageLayout] Error getting user initials:",E),"U"}},w=x.useMemo(()=>{const N=[{id:"dashboard",label:"Dashboard",icon:Kp},{id:"requests",label:"All Requests",icon:hd}];return N.push({id:"my-requests",label:"My Requests",icon:it},{id:"open-requests",label:"Open Requests",icon:Ae},{id:"closed-requests",label:"Closed Requests",icon:je},{id:"shared-summaries",label:"Shared Summary",icon:Sa}),N},[]),f=()=>{o(!i)},C=async N=>{var R;try{if(N.isRead||(await Is.markAsRead(N.notificationId),m(E=>E.map(P=>P.notificationId===N.notificationId?{...P,isRead:!0}:P)),h(E=>Math.max(0,E-1))),N.actionUrl&&a){const E=(R=N.metadata)==null?void 0:R.requestNumber;if(E){let P=`request/${E}`;(N.notificationType==="mention"||N.notificationType==="comment"||N.notificationType==="worknote")&&(P+="?tab=worknotes"),a(P)}}g(!1)}catch(E){console.error("[PageLayout] Error handling notification click:",E)}},b=async()=>{try{await Is.markAllAsRead(),m(N=>N.map(R=>({...R,isRead:!0}))),h(0)}catch(N){console.error("[PageLayout] Error marking all as read:",N)}};return x.useEffect(()=>{const N=y==null?void 0:y.userId;if(!N)return;let R=!0;(async()=>{var I,j;try{const k=await Is.list({page:1,limit:4,unreadOnly:!1});if(!R)return;const _=((I=k.data)==null?void 0:I.notifications)||[];m(_),h(((j=k.data)==null?void 0:j.unreadCount)||0)}catch(k){console.error("[PageLayout] Failed to fetch notifications:",k)}})();const P=Ya();if(P){bf(P,N);const I=j=>{R&&(m(k=>[j.notification,...k].slice(0,4)),h(k=>k+1))};return P.on("notification:new",I),()=>{R=!1,P.off("notification:new",I)}}return()=>{R=!1}},[y]),x.useEffect(()=>{const N=()=>{window.innerWidth>=768?o(!0):o(!1)};return N(),window.addEventListener("resize",N),()=>window.removeEventListener("resize",N)},[]),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:Ki,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:w.map(N=>e.jsxs("button",{onClick:()=>{a==null||a(N.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===N.id?"bg-re-green text-white font-medium":"text-gray-300 hover:bg-gray-900 hover:text-white"}`,children:[e.jsx(N.icon,{className:"w-4 h-4 shrink-0"}),e.jsx("span",{className:"truncate",children:N.label})]},N.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(_s,{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(Gp,{className:"w-5 h-5 text-gray-600"}):e.jsx(Yp,{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(_s,{className:"w-4 h-4"}),"New Request"]}),e.jsxs(il,{open:p,onOpenChange:g,children:[e.jsx(ol,{asChild:!0,children:e.jsxs(M,{variant:"ghost",size:"icon",className:"relative shrink-0 h-10 w-10",children:[e.jsx(Ft,{className:"w-5 h-5"}),u>0&&e.jsx(ee,{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(ll,{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:N=>{N.stopPropagation(),b()},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(Ft,{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(N=>e.jsx("div",{className:`p-3 hover:bg-gray-50 cursor-pointer transition-colors ${N.isRead?"":"bg-blue-50"}`,onClick:()=>C(N),children:e.jsxs("div",{className:"flex gap-2",children:[!N.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 ${N.isRead?"font-medium":"font-semibold"}`,children:N.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-2",children:N.message}),e.jsx("p",{className:"text-xs text-gray-400 mt-1",children:ld(new Date(N.createdAt),{addSuffix:!0})})]})]})},N.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:()=>{g(!1),a==null||a("notifications")},children:"View all notifications"})})]})]}),e.jsxs(il,{children:[e.jsx(ol,{asChild:!0,children:e.jsxs(bt,{className:"cursor-pointer shrink-0 h-10 w-10",children:[e.jsx(Qr,{src:(y==null?void 0:y.picture)||""}),e.jsx(jt,{className:"bg-re-green text-white text-sm",children:v()})]})}),e.jsxs(ll,{align:"end",children:[e.jsxs(Nn,{onClick:()=>a==null?void 0:a("profile"),children:[e.jsx(it,{className:"w-4 h-4 mr-2"}),"Profile"]}),e.jsxs(Nn,{onClick:()=>a==null?void 0:a("settings"),children:[e.jsx(Ls,{className:"w-4 h-4 mr-2"}),"Settings"]}),e.jsxs(Nn,{onClick:()=>c(!0),className:"text-red-600 focus:text-red-600",children:[e.jsx(xn,{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(df,{open:l,onOpenChange:c,children:e.jsxs(Bd,{children:[e.jsxs(uf,{children:[e.jsxs(pf,{className:"flex items-center gap-2",children:[e.jsx(xn,{className:"w-5 h-5 text-red-600"}),"Confirm Logout"]}),e.jsx(xf,{className:"pt-2",children:"Are you sure you want to logout? You will need to sign in again to access your account."})]}),e.jsxs(hf,{children:[e.jsx(ff,{onClick:()=>c(!1),children:"Cancel"}),e.jsxs(gf,{onClick:async()=>{if(c(!1),n)try{await n()}catch(N){console.error("🔴 Error calling onLogout:",N)}else console.error("🔴 ERROR: onLogout is undefined!")},className:"bg-red-600 hover:bg-red-700 text-white focus:ring-red-600",children:[e.jsx(xn,{className:"w-4 h-4 mr-2"}),"Logout"]})]})]})})]})}const ir=()=>ug(),Ra=xg,jf=()=>{try{const t=localStorage.getItem("dashboard_viewAsUser");return t?JSON.parse(t):!1}catch{return!1}},Nf={viewAsUser:jf()},zd=Ta({name:"dashboard",initialState:Nf,reducers:{setViewAsUser:(t,s)=>{t.viewAsUser=s.payload,localStorage.setItem("dashboard_viewAsUser",JSON.stringify(s.payload))}}}),{setViewAsUser:wf}=zd.actions;function Cf(){const[t,s]=x.useState("all"),[a,r]=x.useState(void 0),[n,i]=x.useState(void 0),[o,l]=x.useState(!1),c=x.useCallback(u=>{const h=u;s(h),h!=="custom"?(r(void 0),i(void 0),l(!1)):l(!0)},[]),d=x.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=x.useCallback(()=>{r(void 0),i(void 0),l(!1),s("all")},[]);return{dateRange:t,customStartDate:a,customEndDate:n,showCustomDatePicker:o,setDateRange:s,setCustomStartDate:r,setCustomEndDate:i,setShowCustomDatePicker:l,handleDateRangeChange:c,handleApplyCustomDate:d,resetCustomDates:m}}function Sf(){const[t,s]=x.useState({page:1,totalPages:1,totalRecords:0}),[a,r]=x.useState({page:1,totalPages:1,totalRecords:0}),[n,i]=x.useState({page:1,totalPages:1,totalRecords:0}),[o,l]=x.useState({page:1,totalPages:1,totalRecords:0}),c=x.useCallback((v,w,f)=>{s({page:v,totalPages:w,totalRecords:f})},[]),d=x.useCallback((v,w,f)=>{r({page:v,totalPages:w,totalRecords:f})},[]),m=x.useCallback((v,w,f)=>{i({page:v,totalPages:w,totalRecords:f})},[]),u=x.useCallback((v,w,f)=>{l({page:v,totalPages:w,totalRecords:f})},[]),h=x.useCallback((v,w)=>{v>=1&&v<=t.totalPages&&(s(f=>({...f,page:v})),w(v))},[t.totalPages]),p=x.useCallback((v,w)=>{v>=1&&v<=a.totalPages&&(r(f=>({...f,page:v})),w(v))},[a.totalPages]),g=x.useCallback((v,w)=>{v>=1&&v<=n.totalPages&&(i(f=>({...f,page:v})),w(v))},[n.totalPages]),y=x.useCallback((v,w)=>{v>=1&&v<=o.totalPages&&(l(f=>({...f,page:v})),w(v))},[o.totalPages]);return{activity:t,critical:a,deadlines:n,approver:o,updateActivityPagination:c,updateCriticalPagination:d,updateDeadlinesPagination:m,updateApproverPagination:u,handleActivityPageChange:h,handleCriticalPageChange:p,handleDeadlinesPageChange:g,handleApproverPageChange:y}}class Af{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 de.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 p={dateRange:s};return s==="custom"&&a&&r&&(p.startDate=a,p.endDate=r),n&&n!=="all"&&(p.status=n),i&&i!=="all"&&(p.priority=i),o&&o!=="all"&&(p.department=o),l&&l!=="all"&&(p.initiator=l),c&&c!=="all"&&(p.approver=c),d&&(p.approverType=d),m&&(p.search=m),u&&u!=="all"&&(p.slaCompliance=u),h&&(p.viewAsUser="true"),(await de.get("/dashboard/stats/requests",{params:p})).data.data}catch(p){throw console.error("Failed to fetch request stats:",p),p}}async getTATEfficiency(s){try{return(await de.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 de.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 de.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 de.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 de.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 de.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 de.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 de.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 de.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 de.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,o,l){try{const c={dateRange:s,page:a,limit:r||10};s==="custom"&&n&&i&&(c.startDate=n.toISOString(),c.endDate=i.toISOString()),o&&o!=="all"&&(c.priority=o),l&&l!=="all"&&(c.slaCompliance=l),console.log("[Dashboard Service] Fetching approver performance with params:",c);const d=await de.get("/dashboard/stats/approver-performance",{params:c});return{performance:d.data.data,pagination:d.data.pagination}}catch(c){throw console.error("Failed to fetch approver performance:",c),c}}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 de.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 de.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 de.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 de.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 getSingleApproverStats(s,a,r,n,i,o){try{const l={approverId:s};return a&&(l.dateRange=a),a==="custom"&&r&&n&&(l.startDate=r.toISOString(),l.endDate=n.toISOString()),i&&i!=="all"&&(l.priority=i),o&&o!=="all"&&(l.slaCompliance=o),(await de.get("/dashboard/stats/single-approver",{params:l})).data.data}catch(l){throw console.error("Failed to fetch single approver stats:",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 de.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 Af;function Tf({isAdmin:t,viewAsUser:s=!1,userId:a,dateRange:r,customStartDate:n,customEndDate:i,onPaginationUpdate:o}){const[l,c]=x.useState(null),[d,m]=x.useState([]),[u,h]=x.useState([]),[p,g]=x.useState([]),[y,v]=x.useState([]),[w,f]=x.useState([]),[C,b]=x.useState(null),[N,R]=x.useState([]),[E,P]=x.useState(!0),[I,j]=x.useState(!1),k=x.useRef(o);k.current=o;const _=x.useCallback(async(S=!1)=>{try{S?j(!0):P(!0);const T=[He.getKPIs(r,n,i,s),He.getRecentActivity(1,10,s),He.getCriticalRequests(1,10,s),He.getUpcomingDeadlines(1,10,s)],D=!t&&a?He.getRequestStats(r,n==null?void 0:n.toISOString(),i==null?void 0:i.toISOString(),void 0,void 0,void 0,a,void 0,void 0,void 0,void 0):null,H=t?[He.getDepartmentStats(r,n,i),He.getPriorityDistribution(r,n,i),He.getAIRemarkUtilization(r,n,i),He.getApproverPerformance(r,1,10,n,i)]:[],[z,Z,O]=await Promise.all([Promise.all(T),D,Promise.all(H)]),se=z[0],te=z[1],$=z[2],X=z[3];if(!t&&Z&&(se.requestVolume=Z),c(se),m(te.activities),k.current.activity(te.pagination.currentPage,te.pagination.totalPages,te.pagination.totalRecords),h($.criticalRequests),k.current.critical($.pagination.currentPage,$.pagination.totalPages,$.pagination.totalRecords),f(X.deadlines),k.current.deadlines(X.pagination.currentPage,X.pagination.totalPages,X.pagination.totalRecords),t&&O.length>=4){const ne=O[0],q=O[1],Q=O[2],oe=O[3];g(ne),v(q),b(Q),R(oe.performance),k.current.approver(oe.pagination.currentPage,oe.pagination.totalPages,oe.pagination.totalRecords)}else t||(g([]),v([]),b(null),R([]))}catch(T){console.error("Failed to fetch dashboard data:",T)}finally{P(!1),j(!1)}},[t,s,a,r,n,i]),Y=x.useCallback(async(S=1)=>{try{const T=await He.getRecentActivity(S,10,s);m(T.activities),k.current.activity(T.pagination.currentPage,T.pagination.totalPages,T.pagination.totalRecords)}catch(T){console.error("Failed to fetch recent activities:",T)}},[s]),F=x.useCallback(async(S=1)=>{try{const T=await He.getCriticalRequests(S,10,s);h(T.criticalRequests),k.current.critical(T.pagination.currentPage,T.pagination.totalPages,T.pagination.totalRecords)}catch(T){console.error("Failed to fetch critical requests:",T)}},[s]),L=x.useCallback(async(S=1)=>{try{const T=await He.getUpcomingDeadlines(S,10,s);f(T.deadlines),k.current.deadlines(T.pagination.currentPage,T.pagination.totalPages,T.pagination.totalRecords)}catch(T){console.error("Failed to fetch upcoming deadlines:",T)}},[s]),A=x.useCallback(async(S=1)=>{try{const T=await He.getApproverPerformance(r,S,10,n,i);R(T.performance),k.current.approver(T.pagination.currentPage,T.pagination.totalPages,T.pagination.totalRecords)}catch(T){console.error("Failed to fetch approver performance:",T)}},[r,n,i]);return{kpis:l,recentActivity:d,criticalRequests:u,departmentStats:p,priorityDistribution:y,upcomingDeadlines:w,aiRemarkUtilization:C,approverPerformance:N,loading:E,refreshing:I,fetchDashboardData:_,fetchRecentActivities:Y,fetchCriticalRequests:F,fetchUpcomingDeadlines:L,fetchApproverPerformance:A}}const Ss={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 kf{constructor(){mn(this,"config",null);mn(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 de.get("/config"),r=((s=a.data)==null?void 0:s.data)||a.data;return{...Ss,...r,workingHours:{...Ss.workingHours,...r.workingHours},tat:{...Ss.tat,...r.tat},upload:{...Ss.upload,...r.upload},workflow:{...Ss.workflow,...r.workflow},workNotes:{...Ss.workNotes,...r.workNotes},features:{...Ss.features,...r.features},ui:{...Ss.ui,...r.ui}}}catch(a){return console.error("[ConfigService] ⚠️ Failed to fetch config from server, using defaults:",a),Ss}}async refreshConfig(){return this.config=null,this.loading=null,this.getConfig()}getCachedConfig(){return this.config}isLoaded(){return this.config!==null}}const Rf=new kf;let Df=9,Pf=18,Ef=1,Mf=5,cl=!1;async function If(){if(!cl)try{const t=await Rf.getConfig();Df=t.workingHours.START_HOUR,Pf=t.workingHours.END_HOUR,Ef=t.workingHours.START_DAY,Mf=t.workingHours.END_DAY,cl=!0}catch{console.warn("[SLA Tracker] ⚠️ Using default working hours (9 AM - 6 PM)")}}If().catch(()=>{});function ot(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 Ff(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 p=[`"${(h.approverName||"Unknown").replace(/"/g,'""')}"`,h.totalApproved||0,h.tatCompliancePercent||0,ot(h.avgResponseHours),h.pendingCount||0];l.push(p.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 Lf(){const[t,s]=x.useState(!1),[a,r]=x.useState(!1),n=x.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=x.useCallback(async(o,l,c)=>{try{r(!0),await Ff(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 Lt({className:t,...s}){return e.jsx(_h,{"data-slot":"switch",className:ce("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(Lh,{"data-slot":"switch-thumb",className:ce("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 J({className:t,...s}){return e.jsx(Oh,{"data-slot":"label",className:ce("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 Of({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(K,{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(G,{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(pd,{className:`w-3 h-3 sm:w-3.5 sm:h-3.5 ${a?"text-gray-300":"text-red-600"}`}),e.jsx(J,{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(Lt,{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(it,{className:`w-3 h-3 sm:w-3.5 sm:h-3.5 ${a?"text-red-600":"text-gray-300"}`}),e.jsx(J,{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 Te({...t}){return e.jsx($h,{"data-slot":"select",...t})}function ke({...t}){return e.jsx(Vh,{"data-slot":"select-value",...t})}function Re({className:t,size:s="default",children:a,...r}){return e.jsxs(Uh,{"data-slot":"select-trigger","data-size":s,className:ce("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(Bh,{asChild:!0,children:e.jsx(xd,{className:"size-4 opacity-50"})})]})}function De({className:t,children:s,position:a="popper",...r}){return e.jsx(zh,{children:e.jsxs(Hh,{"data-slot":"select-content",className:ce("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($f,{}),e.jsx(qh,{className:ce("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(Uf,{})]})})}function U({className:t,children:s,...a}){return e.jsxs(Wh,{"data-slot":"select-item",className:ce("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(Kh,{children:e.jsx(Aa,{className:"size-4"})})}),e.jsx(Gh,{children:s})]})}function $f({className:t,...s}){return e.jsx(Yh,{"data-slot":"select-scroll-up-button",className:ce("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(Xp,{className:"size-4"})})}function Uf({className:t,...s}){return e.jsx(Xh,{"data-slot":"select-scroll-down-button",className:ce("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(xd,{className:"size-4"})})}function dt({className:t,orientation:s="horizontal",decorative:a=!0,...r}){return e.jsx(Zh,{"data-slot":"separator-root",decorative:a,orientation:s,className:ce("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 cs({...t}){return e.jsx(Qh,{"data-slot":"popover",...t})}function ds({...t}){return e.jsx(Jh,{"data-slot":"popover-trigger",...t})}function ms({className:t,align:s="center",sideOffset:a=4,...r}){return e.jsx(ep,{children:e.jsx(tp,{"data-slot":"popover-content",align:s,sideOffset:a,className:ce("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 fe({className:t,type:s,...a}){return e.jsx("input",{type:s,"data-slot":"input",className:ce("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 Bf({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(K,{className:"shadow-md","data-testid":"dashboard-filters-bar",children:e.jsx(G,{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(sr,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Filters"}),t&&e.jsx(ee,{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(We,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Te,{value:s,onValueChange:o,"data-testid":"date-range-select",children:[e.jsx(Re,{className:"w-[140px]",children:e.jsx(ke,{placeholder:"Select period"})}),e.jsxs(De,{children:[e.jsx(U,{value:"all",children:"All Time"}),e.jsx(U,{value:"today",children:"Today"}),e.jsx(U,{value:"week",children:"This Week"}),e.jsx(U,{value:"month",children:"This Month"}),e.jsx(U,{value:"last7days",children:"Last 7 Days"}),e.jsx(U,{value:"last30days",children:"Last 30 Days"}),e.jsx(U,{value:"custom",children:"Custom Range"})]})]}),s==="custom"&&e.jsxs(cs,{open:n,onOpenChange:d,children:[e.jsx(ds,{asChild:!0,children:e.jsxs(M,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(We,{className:"w-4 h-4"}),a&&r?`${xe(a,"MMM d, yyyy")} - ${xe(r,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(ms,{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(J,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(fe,{id:"start-date",type:"date",value:a?xe(a,"yyyy-MM-dd"):"",onChange:p=>{const g=p.target.value?new Date(p.target.value):void 0;g?(l(g),r&&g>r&&c(g)):l(void 0)},max:xe(new Date,"yyyy-MM-dd"),className:"w-full","data-testid":"start-date-input"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(fe,{id:"end-date",type:"date",value:r?xe(r,"yyyy-MM-dd"):"",onChange:p=>{const g=p.target.value?new Date(p.target.value):void 0;g?(c(g),a&&g<a&&l(g)):c(void 0)},min:a?xe(a,"yyyy-MM-dd"):void 0,max:xe(new Date,"yyyy-MM-dd"),className:"w-full","data-testid":"end-date-input"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(M,{size:"sm",onClick:m,disabled:!a||!r,className:"flex-1 bg-re-green hover:bg-re-green/90","data-testid":"apply-custom-date",children:"Apply"}),e.jsx(M,{size:"sm",variant:"outline",onClick:u,"data-testid":"cancel-custom-date",children:"Cancel"})]})]})})]})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(We,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Te,{value:s,onValueChange:p=>o(p),"data-testid":"date-range-select-user",children:[e.jsx(Re,{className:"w-[140px]",children:e.jsx(ke,{placeholder:"Select period"})}),e.jsxs(De,{children:[e.jsx(U,{value:"all",children:"All Time"}),e.jsx(U,{value:"today",children:"Today"}),e.jsx(U,{value:"week",children:"This Week"}),e.jsx(U,{value:"month",children:"This Month"}),e.jsx(U,{value:"last7days",children:"Last 7 Days"}),e.jsx(U,{value:"last30days",children:"Last 30 Days"}),e.jsx(U,{value:"custom",children:"Custom Range"})]})]})]}),e.jsx(dt,{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(Et,{className:`w-4 h-4 ${i?"animate-spin":""}`}),e.jsx("span",{className:"inline-block w-[60px] text-center",children:i?"Refreshing...":"Refresh"})]})]})]})})})}function sa({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(K,{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(ae,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(re,{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(ar,{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(G,{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 At({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 gs({className:t,value:s,indicatorClassName:a,...r}){return e.jsx(sp,{"data-slot":"progress",className:ce("bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",t),...r,children:e.jsx(ap,{"data-slot":"progress-indicator",className:ce("bg-primary h-full w-full flex-1 transition-all",a),style:{transform:`translateX(-${100-(s||0)}%)`}})})}function Vf({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(sa,{title:"Total Requests",value:(t==null?void 0:t.requestVolume.totalRequests)||0,icon:Ae,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(At,{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(At,{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(At,{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(At,{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(At,{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(sa,{title:"SLA Compliance",value:`${(t==null?void 0:t.tatEfficiency.avgTATCompliance)||0}%`,icon:ct,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(gs,{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(At,{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(At,{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(sa,{title:"Avg Cycle Time",value:t!=null&&t.tatEfficiency.avgCycleTimeHours?ot(t.tatEfficiency.avgCycleTimeHours):"0 hours",icon:Ie,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(At,{label:"Express",value:(()=>{const l=s.find(d=>d.priority==="express"),c=l?Number(l.avgCycleTimeHours):0;return c>0?ot(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(At,{label:"Standard",value:(()=>{const l=s.find(d=>d.priority==="standard"),c=l?Number(l.avgCycleTimeHours):0;return c>0?ot(c):"N/A"})(),bgColor:"bg-blue-50",textColor:"text-blue-600",testId:"stat-standard-time",onClick:l=>{l.stopPropagation(),i({...o(),priority:"standard"})}})]})})})]})}function zf({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(sa,{title:"My Requests (Submitted)",value:(t==null?void 0:t.requestVolume.totalRequests)||0,icon:Ae,iconBgColor:"bg-blue-50",iconColor:"text-blue-600",testId:"kpi-my-requests",onClick:()=>i(d()),children:e.jsxs("div",{className:"grid grid-cols-3 gap-1.5 sm:gap-2",children:[e.jsx(At,{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(At,{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(At,{label:"Paused",value:(t==null?void 0:t.requestVolume.pausedRequests)||0,bgColor:"bg-amber-50",textColor:"text-amber-600",testId:"stat-user-paused",onClick:h=>{h.stopPropagation(),i({...d(),status:"paused"})}}),e.jsx(At,{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(At,{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(sa,{title:"Awaiting My Approval",value:(t==null?void 0:t.approverLoad.pendingActions)||0,icon:Ie,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(At,{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(At,{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(sa,{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(At,{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(At,{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(sa,{title:"Success Rate",value:`${u.toFixed(0)}%`,icon:je,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(gs,{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 Hf=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)))},qf=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 Wf({alert:t,onNavigate:s,testId:a="critical-alert-card"}){const r=Hf(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(Zp,{className:"h-3 w-3 text-red-500 flex-shrink-0","data-testid":`${a}-priority-icon`}),t.breachCount>0&&e.jsx(ee,{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(ee,{variant:"outline",className:"text-xs bg-white border-red-200 text-red-700 font-medium whitespace-nowrap","data-testid":`${a}-remaining-time`,children:qf(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(gs,{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 Kf(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 Gf(t){return t.filter(s=>{const a=Number(s.tatPercentageUsed)||0;return(Number(s.remainingHours)||0)>0&&a<100})}function Yf(t){if(t<=0)return"Just breached";if(t<1)return`${Math.round(t*60)} min`;const s=8;if(t<s){const n=Math.floor(t),i=Math.round((t-n)*60);return i>0?`${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 Xf(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 Hd(t,s,a=3){const r=[];let n=Math.max(1,t-Math.floor(a/2)),i=Math.min(s,n+a-1);i-n<a-1&&(n=Math.max(1,i-a+1));for(let o=n;o<=i;o++)r.push(o);return r}function Zf({isAdmin:t,breachedRequests:s,pagination:a,onPageChange:r,onNavigate:n}){return e.jsxs(K,{className:"lg:col-span-2 shadow-md hover:shadow-lg transition-shadow flex flex-col overflow-hidden",style:{height:"100%"},"data-testid":"critical-alerts-section",children:[e.jsx(ae,{className:"pb-3 sm:pb-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-3",children:[e.jsx("div",{className:"p-2 sm:p-3 bg-red-100 rounded-lg",children:e.jsx(ls,{className:"h-4 w-4 sm:h-5 sm:w-5 text-red-600"})}),e.jsxs("div",{children:[e.jsx(re,{className:"text-base sm:text-lg text-gray-900",children:"Critical Alerts"}),e.jsx(ge,{className:"text-xs sm:text-sm text-gray-600",children:t?"Organization-wide":"My requests"})]})]}),e.jsx(ee,{variant:"destructive",className:`font-semibold text-xs sm:text-sm ${a.totalRecords>0?"animate-pulse":""}`,"data-testid":"critical-count-badge",children:a.totalRecords})]})}),e.jsx(G,{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(je,{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(Wf,{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(Nt,{className:"h-3 w-3 rotate-180"})}),Hd(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(Nt,{className:"h-3 w-3"})})]})]})})]})}const Qf=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"}},Jf=t=>{const s=new Date,a=new Date(t),r=Mp(s,a);if(r<1)return"just now";if(r<60)return`${r} minute${r>1?"s":""} ago`;const n=Ip(s,a);if(n<24)return`${n} hour${n>1?"s":""} ago`;const i=Fp(s,a);return`${i} day${i>1?"s":""} ago`},e0=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()},t0=t=>{const s=t.toLowerCase();return s.includes("approv")?e.jsx(je,{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(vs,{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(Ae,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-purple-600"}):s.includes("document")?e.jsx(qr,{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 s0({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(bt,{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(Qr,{src:""}),e.jsx(jt,{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:t0(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(ee,{variant:"outline",className:`text-xs ${Qf(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:e0(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:Jf(t.timestamp)})]})]}),e.jsx(Nt,{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 a0({isAdmin:t,recentActivity:s,pagination:a,refreshing:r,onPageChange:n,onRefresh:i,onNavigate:o,currentUserId:l,currentUserDisplayName:c,currentUserEmail:d}){return e.jsxs(K,{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(ae,{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(re,{className:"text-base sm:text-lg text-gray-900",children:"Recent Activity"}),e.jsx(ge,{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(Et,{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(G,{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(s0,{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(Nt,{className:"h-3 w-3 rotate-180"})}),Hd(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(Nt,{className:"h-3 w-3"})})]})]})})]})}function r0({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(K,{className:"shadow-md hover:shadow-lg transition-shadow flex-1","data-testid":"active-levels-card",children:[e.jsx(ae,{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(re,{className:"text-sm",children:"Active Levels"})]})}),e.jsx(G,{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(dt,{}),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(K,{className:"shadow-md hover:shadow-lg transition-shadow flex-1","data-testid":"collaboration-card",children:[e.jsx(ae,{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(vs,{className:"h-4 w-4 text-indigo-600"})}),e.jsx(re,{className:"text-sm",children:"Collaboration"})]})}),e.jsx(G,{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(dt,{}),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(K,{className:"shadow-md hover:shadow-lg transition-shadow lg:col-span-2","data-testid":"department-stats-card",children:[e.jsx(ae,{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(Qp,{className:"h-5 w-5 sm:h-6 sm:w-6 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(re,{className:"text-base sm:text-lg lg:text-xl",children:"Department-wise Workflow Summary"}),e.jsx(ge,{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(G,{children:e.jsx(Pi,{width:"100%",height:400,children:e.jsxs(Tp,{data:r,children:[e.jsx(ad,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(rd,{dataKey:"department",stroke:"#999",tick:u=>{const{x:h,y:p,payload:g}=u;return e.jsx("g",{transform:`translate(${h},${p})`,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:g.value})},children:g.value})})}}),e.jsx(nd,{stroke:"#999",tick:{fontSize:11}}),e.jsx(Ei,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(id,{verticalAlign:"bottom",height:36,iconType:"square",wrapperStyle:{fontSize:"12px",paddingTop:"10px"}}),e.jsx(un,{dataKey:"approved",fill:"#10b981",name:"Approved"}),e.jsx(un,{dataKey:"inProgress",fill:"#f59e0b",name:"Pending"}),e.jsx(un,{dataKey:"rejected",fill:"#ef4444",name:"Rejected"})]})})})]})]})}function n0({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(K,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"user-activity-card",children:[e.jsx(ae,{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(vs,{className:"h-4 w-4 text-indigo-600"})}),e.jsx(re,{className:"text-sm",children:"My Activity"})]})}),e.jsx(G,{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(K,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"user-response-time-card",children:[e.jsx(ae,{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(Ie,{className:"h-4 w-4 text-purple-600"})}),e.jsx(re,{className:"text-sm",children:"Avg Response Time"})]})}),e.jsx(G,{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:ot(t.tatEfficiency.avgCycleTimeHours)})}),e.jsx(dt,{}),e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["≈ ",t.tatEfficiency.avgCycleTimeDays.toFixed(1)," working days"]})]})})]})]}):null}function i0({priorityDistribution:t,onNavigate:s}){return t.length===0?null:e.jsxs(K,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"priority-distribution-report",children:[e.jsx(ae,{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(ct,{className:"h-5 w-5 sm:h-6 sm:w-6 text-green-600"})}),e.jsxs("div",{children:[e.jsx(re,{className:"text-base sm:text-lg lg:text-xl",children:"Priority Distribution Report"}),e.jsx(ge,{className:"text-xs sm:text-sm",children:"Express vs Standard workflow analysis"})]})]})}),e.jsxs(G,{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: ",ot(n)," cycle"]})]},r)})}),e.jsx("div",{className:"flex justify-center",children:e.jsx(Pi,{width:"100%",height:300,children:e.jsxs(kp,{children:[e.jsx(Rp,{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(Dp,{fill:a.priority==="express"?"#ef4444":"#3b82f6",style:{cursor:"pointer"}},`cell-${r}`))}),e.jsx(Ei,{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 da({currentPage:t,totalPages:s,itemsPerPage:a,totalRecords:r,onPageChange:n,loading:i=!1,itemLabel:o="items",testIdPrefix:l="pagination"}){const c=()=>{const u=[];let p=Math.max(1,t-Math.floor(2.5)),g=Math.min(s,p+5-1);g-p<4&&(p=Math.max(1,g-5+1));for(let y=p;y<=g;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(K,{className:"shadow-md border-gray-200","data-testid":`${l}-container`,children:e.jsx(G,{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(K,{className:"shadow-md border-gray-200","data-testid":`${l}-container`,children:e.jsx(G,{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(Nt,{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)),t<s-2&&s>5&&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(Nt,{className:"h-4 w-4"})})]})]})})})}function o0(t,s,a,r="for"){return t==="custom"&&s&&a?`${r} ${xe(s,"MMM d, yyyy")} - ${xe(a,"MMM d, yyyy")}`:{all:"(All Time)",today:`${r} Today`,week:`${r} This Week`,month:`${r} This Month`,quarter:`${r} This Quarter`,year:`${r} This Year`,last30days:`${r} Last 30 Days`,custom:`${r} Custom Range`}[t]||`${r} Selected Period`}function l0(t,s,a){return t==="all"?"All historical data":t==="custom"&&s&&a?`Data from ${xe(s,"MMM d, yyyy")} to ${xe(a,"MMM d, yyyy")}`:{all:"All historical data",today:"Today's data",week:"This week data",month:"This month data",quarter:"This quarter data",year:"This year data",last30days:"Last 30 days data",custom:"Custom date range"}[t]||"Filtered data"}function c0({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(K,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"tat-breach-report",children:[e.jsx(ae,{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(re,{className:"text-base sm:text-lg lg:text-xl",children:"TAT Breach Report"}),e.jsxs(ge,{className:"text-xs sm:text-sm",children:["Requests that breached TAT - ",l0(a,r,n)]})]})]}),e.jsxs(ee,{variant:"destructive",className:"text-sm font-medium self-start sm:self-auto",children:[t.length," ",t.length===1?"Breach":"Breaches"]})]})}),e.jsxs(G,{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:Yf(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(ee,{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(da,{currentPage:s.page,totalPages:s.totalPages,totalRecords:s.totalRecords,itemsPerPage:10,onPageChange:i,itemLabel:"critical requests",testIdPrefix:"dashboard-critical-pagination"})})]})]})}function d0({isAdmin:t,upcomingDeadlines:s,pagination:a,onPageChange:r,onNavigate:n}){return s.length===0?null:e.jsxs(K,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"upcoming-deadlines-section",children:[e.jsx(ae,{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(We,{className:"h-4 w-4 sm:h-5 sm:w-5 text-orange-600"}),e.jsxs("div",{children:[e.jsx(re,{className:"text-base sm:text-lg",children:"Upcoming Deadlines"}),e.jsx(ge,{className:"text-xs sm:text-sm",children:t?"Current active levels organization-wide":"Requests awaiting your approval"})]})]})})}),e.jsxs(G,{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(ee,{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(ee,{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(gs,{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:[ot(c)," elapsed"]}),e.jsxs("span",{children:[ot(d)," left"]})]})]})]},o)})}),e.jsx("div",{className:"mt-4",children:e.jsx(da,{currentPage:a.page,totalPages:a.totalPages,totalRecords:a.totalRecords,itemsPerPage:10,onPageChange:r,itemLabel:"deadlines",testIdPrefix:"dashboard-deadlines-pagination"})})]})]})}function m0({aiRemarkUtilization:t}){return t?e.jsxs(K,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"ai-remark-utilization-report",children:[e.jsx(ae,{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(Li,{className:"h-5 w-5 sm:h-6 sm:w-6 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(re,{className:"text-base sm:text-lg lg:text-xl",children:"AI Remark Utilization Report"}),e.jsx(ge,{className:"text-xs sm:text-sm",children:"AI-generated remarks usage and edits"})]})]})}),e.jsxs(G,{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(Pi,{width:"100%",height:250,children:e.jsxs(Pp,{data:t.monthlyTrends,children:[e.jsx(ad,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(rd,{dataKey:"month",stroke:"#999",tick:{fontSize:11}}),e.jsx(nd,{stroke:"#999",tick:{fontSize:11}}),e.jsx(Ei,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(id,{verticalAlign:"bottom",height:36,iconType:"circle",wrapperStyle:{fontSize:"12px",paddingTop:"10px"}}),e.jsx(Wo,{type:"monotone",dataKey:"aiUsage",stroke:"#8b5cf6",strokeWidth:2,name:"AI Usage",dot:{fill:"#8b5cf6",r:4}}),e.jsx(Wo,{type:"monotone",dataKey:"manualEdits",stroke:"#ec4899",strokeWidth:2,name:"Manual Edits",dot:{fill:"#ec4899",r:4}})]})})]})]}):null}function u0({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(K,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"approver-performance-report",children:[e.jsx(ae,{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(nt,{className:"h-5 w-5 sm:h-6 sm:w-6 text-yellow-600"})}),e.jsxs("div",{children:[e.jsx(re,{className:"text-base sm:text-lg lg:text-xl",children:"Approver Performance Report"}),e.jsx(ge,{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(Et,{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(G,{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 p=new URLSearchParams;p.set("approverId",m.approverId),p.set("approverName",m.approverName),p.set("dateRange",a),a==="custom"&&r&&n&&(p.set("startDate",r.toISOString()),p.set("endDate",n.toISOString())),d==null||d(`/approver-performance?${p.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 ${Xf(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:ot(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(da,{currentPage:s.page,totalPages:s.totalPages,totalRecords:s.totalRecords,itemsPerPage:10,onPageChange:l,itemLabel:"approvers",testIdPrefix:"dashboard-approver-pagination"})})]})]})}function h0(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 p0(t,s,a){const r=[{label:"New Request",icon:Ae,action:()=>s==null?void 0:s(),color:"bg-emerald-600 hover:bg-emerald-700"},{label:"View Pending",icon:Ie,action:()=>a==null?void 0:a("open-requests"),color:"bg-blue-600 hover:bg-blue-700"},{label:"Settings",icon:Ls,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 dl({onNavigate:t,onNewRequest:s}){const{user:a}=Mt(),r=ir(),n=Ra(Ct=>Ct.dashboard.viewAsUser),i=x.useMemo(()=>Zr(a),[a]),o=i&&!n,l=x.useCallback(Ct=>{r(wf(Ct))},[r]),c=Cf(),{dateRange:d,customStartDate:m,customEndDate:u,showCustomDatePicker:h,handleDateRangeChange:p,handleApplyCustomDate:g,resetCustomDates:y,setCustomStartDate:v,setCustomEndDate:w,setShowCustomDatePicker:f}=c,C=Sf(),{activity:b,critical:N,deadlines:R,approver:E,updateActivityPagination:P,updateCriticalPagination:I,updateDeadlinesPagination:j,updateApproverPagination:k,handleActivityPageChange:_,handleCriticalPageChange:Y,handleDeadlinesPageChange:F,handleApproverPageChange:L}=C,A=Tf({isAdmin:o,viewAsUser:i&&n,userId:a==null?void 0:a.userId,dateRange:d,customStartDate:m,customEndDate:u,onPaginationUpdate:{activity:P,critical:I,deadlines:j,approver:k}}),{kpis:S,recentActivity:T,criticalRequests:D,departmentStats:H,priorityDistribution:z,upcomingDeadlines:Z,aiRemarkUtilization:O,approverPerformance:se,loading:te,refreshing:$,fetchDashboardData:X,fetchRecentActivities:ne,fetchCriticalRequests:q,fetchUpcomingDeadlines:Q,fetchApproverPerformance:oe}=A,W=Lf(),{exportingDeptStats:me,exportingApproverPerformance:we,handleExportDepartmentStats:Ee,handleExportApproverPerformance:Fe}=W,le=x.useMemo(()=>Kf(D),[D]),ye=x.useMemo(()=>Gf(Z),[Z]),Ve=x.useCallback(()=>{X(!0)},[d,m,u,X]),Le=x.useCallback(()=>{g(()=>{m&&u&&X(!1)})},[m,u,g,X]),Zt=x.useCallback(Ct=>{_(Ct,ne)},[_,ne]),js=x.useCallback(Ct=>{Y(Ct,q)},[Y,q]),Ws=x.useCallback(Ct=>{F(Ct,Q)},[F,Q]),ma=x.useCallback(Ct=>{L(Ct,()=>oe(Ct))},[L,oe]);x.useEffect(()=>{d==="custom"?m&&u&&X(!1):X(!1)},[d,m,u,n]);const Ma=x.useMemo(()=>p0(i,s,t),[i,s,t]),Ns=x.useCallback(Ct=>{const Ia=h0(Ct);t==null||t(Ia)},[t]);return te?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(Et,{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(Of,{isAdmin:i,effectiveIsAdmin:o,viewAsUser:n,onToggleView:l,quickActions:Ma,userDisplayName:a==null?void 0:a.displayName,userEmail:a==null?void 0:a.email}),e.jsx(Bf,{isAdmin:o,dateRange:d,customStartDate:m,customEndDate:u,showCustomDatePicker:h,refreshing:$,onDateRangeChange:p,onCustomStartDateChange:v,onCustomEndDateChange:w,onShowCustomDatePickerChange:f,onApplyCustomDate:Le,onResetCustomDates:y,onRefresh:Ve}),o?e.jsx(Vf,{kpis:S,priorityDistribution:z,dateRange:d,customStartDate:m,customEndDate:u,onKPIClick:Ns}):e.jsx(zf,{kpis:S,criticalRequests:D,dateRange:d,customStartDate:m,customEndDate:u,onKPIClick:Ns,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(Zf,{isAdmin:o,breachedRequests:le,pagination:N,onPageChange:js,onNavigate:t}),e.jsx(a0,{isAdmin:o,recentActivity:T,pagination:b,refreshing:$,onPageChange:Zt,onRefresh:Ve,onNavigate:t,currentUserId:a==null?void 0:a.userId,currentUserDisplayName:a==null?void 0:a.displayName,currentUserEmail:a==null?void 0:a.email})]}),o&&S&&e.jsx(r0,{kpis:S,upcomingDeadlines:Z,criticalRequests:D,departmentStats:H,dateRange:d,customStartDate:m,customEndDate:u,exportingDeptStats:me,onKPIClick:Ns,onExportDepartmentStats:Ee}),!o&&S&&e.jsx(n0,{kpis:S}),o&&z.length>0&&e.jsx(i0,{priorityDistribution:z,onNavigate:t}),o&&le.length>0&&e.jsx(c0,{breachedRequests:le,pagination:N,dateRange:d,customStartDate:m,customEndDate:u,onPageChange:js,onKPIClick:Ns,onNavigate:t}),ye.length>0&&e.jsx(d0,{isAdmin:o,upcomingDeadlines:ye,pagination:R,onPageChange:Ws,onNavigate:t}),o&&O&&e.jsx(m0,{aiRemarkUtilization:O}),o&&se.length>0&&e.jsx(u0,{approverPerformance:se,pagination:E,dateRange:d,customStartDate:m,customEndDate:u,loading:te,exportingApproverPerformance:we,onPageChange:ma,onExport:Fe,onNavigate:t})]})}const x0={searchTerm:"",statusFilter:"all",priorityFilter:"all",sortBy:"created",sortOrder:"desc",currentPage:1},qd=Ta({name:"openRequests",initialState:x0,reducers:{setSearchTerm:(t,s)=>{t.searchTerm=s.payload},setStatusFilter:(t,s)=>{t.statusFilter=s.payload},setPriorityFilter:(t,s)=>{t.priorityFilter=s.payload},setSortBy:(t,s)=>{t.sortBy=s.payload},setSortOrder:(t,s)=>{t.sortOrder=s.payload},setCurrentPage:(t,s)=>{t.currentPage=s.payload},clearFilters:t=>{t.searchTerm="",t.statusFilter="all",t.priorityFilter="all",t.currentPage=1}}}),{setSearchTerm:g0,setStatusFilter:f0,setPriorityFilter:y0,setSortBy:v0,setSortOrder:b0,setCurrentPage:j0,clearFilters:N0}=qd.actions;function w0(){const t=ir(),{searchTerm:s,statusFilter:a,priorityFilter:r,sortBy:n,sortOrder:i,currentPage:o}=Ra(y=>y.openRequests),l=x.useCallback(y=>t(g0(y)),[t]),c=x.useCallback(y=>t(f0(y)),[t]),d=x.useCallback(y=>t(y0(y)),[t]),m=x.useCallback(y=>t(v0(y)),[t]),u=x.useCallback(y=>t(b0(y)),[t]),h=x.useCallback(y=>t(j0(y)),[t]),p=x.useCallback(()=>t(N0()),[t]),g=[s,r!=="all"?r:null,a!=="all"?a:null].filter(Boolean).length;return{searchTerm:s,statusFilter:a,priorityFilter:r,sortBy:n,sortOrder:i,currentPage:o,setSearchTerm:l,setStatusFilter:c,setPriorityFilter:d,setSortBy:m,setSortOrder:u,setCurrentPage:h,clearFilters:p,activeFiltersCount:g}}function wn(){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 C0(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,p=u.tat??"";let g=0;typeof p=="number"&&(g=u.tatType==="days"?p*24:p);const y=u.email||"",v=u.name&&u.name.trim()||y.split("@")[0]||`Approver ${h}`;return{levelNumber:h,levelName:`Level ${h}`,approverId:wn(),approverEmail:y,approverName:v,tatHours:g>0?g:24,isFinalApprover:h===(t.approverCount||1)}}),r=[...(t.spectators||[]).map(c=>({userId:wn(),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:wn(),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 de.post("/workflows",n),o=((l=i.data)==null?void 0:l.data)||i.data;return{id:o.id||o.workflowId||""}}async function Wd(t,s,a="SUPPORTING"){var l;const r={templateType:t.templateType,title:t.title,description:t.description,priority:t.priorityUi.toUpperCase()==="EXPRESS"?"EXPRESS":"STANDARD",approvers:Array.from({length:t.approverCount||1},(c,d)=>{const m=t.approvers[d]||{},u=typeof m.tat=="number"?m.tat:0;if(!m.email||!m.email.trim())throw new Error(`Email is required for approver at level ${d+1}.`);return{email:m.email,tat:u,tatType:m.tatType||"hours"}})};t.spectators&&t.spectators.length>0&&(r.spectators=t.spectators.filter(c=>c==null?void 0:c.email).map(c=>({email:c.email})));const n=new FormData;n.append("payload",JSON.stringify(r)),n.append("category",a),s.forEach(c=>n.append("files",c));const i=await de.post("/workflows/multipart",n,{headers:{"Content-Type":"multipart/form-data"}}),o=((l=i.data)==null?void 0:l.data)||i.data;return{id:o==null?void 0:o.requestId}}async function S0(t={}){var g;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,p=await de.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((g=p.data)==null?void 0:g.data)||p.data}async function A0(t={}){var y,v,w,f,C;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:p}=t,g=await de.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:p}});return{data:((v=(y=g.data)==null?void 0:y.data)==null?void 0:v.data)||((w=g.data)==null?void 0:w.data)||[],pagination:((C=(f=g.data)==null?void 0:f.data)==null?void 0:C.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function T0(t={}){var g,y,v,w,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,p=await de.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=(g=p.data)==null?void 0:g.data)==null?void 0:y.data)||((v=p.data)==null?void 0:v.data)||[],pagination:((f=(w=p.data)==null?void 0:w.data)==null?void 0:f.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function k0(t={}){var h,p,g,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 de.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:((p=(h=u.data)==null?void 0:h.data)==null?void 0:p.data)||((g=u.data)==null?void 0:g.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 R0(t={}){var d,m,u,h,p;const{page:s=1,limit:a=20,search:r,status:n,priority:i,sortBy:o,sortOrder:l}=t,c=await de.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:((p=(h=c.data)==null?void 0:h.data)==null?void 0:p.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function D0(t={}){var d,m,u,h,p;const{page:s=1,limit:a=20,search:r,status:n,priority:i,sortBy:o,sortOrder:l}=t,c=await de.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:((p=(h=c.data)==null?void 0:h.data)==null?void 0:p.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function aa(t){var a;const s=await de.get(`/workflows/${t}/details`);return((a=s.data)==null?void 0:a.data)||s.data}async function ba(t){var a;const s=await de.get(`/workflows/${t}/work-notes`);return((a=s.data)==null?void 0:a.data)||s.data}async function Kd(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 de.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 Gd(t,s,a,r){var i;const n=await de.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 P0(t,s,a){var n;const r=await de.post(`/workflows/${t}/approvals/${s}/skip`,{reason:a});return((n=r.data)==null?void 0:n.data)||r.data}async function Yd(t,s){var r;const a=await de.post(`/workflows/${t}/participants/spectator`,{email:s});return((r=a.data)==null?void 0:r.data)||a.data}async function E0(t,s,a,r){var i;const n=await de.post(`/workflows/${t}/pause`,{levelId:s,reason:a,resumeDate:r.toISOString()});return((i=n.data)==null?void 0:i.data)||n.data}async function M0(t,s){var r;const a=await de.post(`/workflows/${t}/resume`,{notes:s});return((r=a.data)==null?void 0:r.data)||a.data}async function I0(t){var a;const s=await de.post(`/workflows/${t}/pause/retrigger`);return((a=s.data)==null?void 0:a.data)||s.data}async function ml(t){var a;const s=await de.get(`/workflows/${t}/pause`);return((a=s.data)==null?void 0:a.data)||s.data}function F0(t){return`https://re-workflow-nt-dev.siplsolutions.com/api/v1/workflows/work-notes/attachments/${t}/preview`}function Xd(t){return`https://re-workflow-nt-dev.siplsolutions.com/api/v1/workflows/documents/${t}/preview`}async function li(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 p=await o.text();throw new Error(`Download failed: ${o.status} - ${p}`)}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 ul(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 p=await o.text();throw new Error(`Download failed: ${o.status} - ${p}`)}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 Ot={createWorkflowFromForm:C0,createWorkflowMultipart:Wd,listWorkflows:S0,listParticipantRequests:A0,listMyWorkflows:T0,listMyInitiatedWorkflows:k0,listOpenForMe:R0,listClosedByMe:D0,submitWorkflow:Zd,getWorkflowDetails:aa,getWorkNotes:ba,createWorkNoteMultipart:Kd};async function Zd(t){var a;const s=await de.patch(`/workflows/${t}/submit`);return((a=s.data)==null?void 0:a.data)||s.data}async function _0(t,s){var r;const a=await de.put(`/workflows/${t}`,s);return((r=a.data)==null?void 0:r.data)||a.data}async function L0(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 de.put(`/workflows/${t}/multipart`,i,{headers:{"Content-Type":"multipart/form-data"}});return((l=o.data)==null?void 0:l.data)||o.data}async function O0(t,s,a){var n;const r=await de.patch(`/workflows/${t}/approvals/${s}/approve`,{action:"APPROVE",comments:a||""});return((n=r.data)==null?void 0:n.data)||r.data}async function $0(t,s,a,r){var i;const n=await de.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 U0(t,s){const a=await de.put(`/tat/breach-reason/${t}`,{breachReason:s});if(!a.data.success)throw new Error(a.data.error||"Failed to update breach reason")}function Vt(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 Qd(t){return Vt(t,{includeTime:!1,format:"short"})}function fs(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 B0=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:ct,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:ct,iconColor:"text-gray-600"}}},V0=t=>{switch(t){case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:Ie,iconColor:"text-yellow-600",label:"Pending"};case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:Pe,iconColor:"text-green-600",label:"Needs Closure"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:Je,iconColor:"text-red-600",label:"Rejected"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:je,iconColor:"text-gray-600",label:"Closed"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Pe,iconColor:"text-gray-600",label:t}}};function z0({onViewRequest:t}){const[s,a]=x.useState([]),[r,n]=x.useState(!1),[i,o]=x.useState(!1),[l,c]=x.useState(1),[d,m]=x.useState(0),[u]=x.useState(10),h=x.useRef(null),p=w0(),g=x.useCallback(async(b=1,N)=>{try{b===1&&(n(!0),a([]));const R=await Ot.listOpenForMe({page:b,limit:u,search:N==null?void 0:N.search,status:N==null?void 0:N.status,priority:N==null?void 0:N.priority,sortBy:N==null?void 0:N.sortBy,sortOrder:N==null?void 0:N.sortOrder}),E=Array.isArray(R==null?void 0:R.data)?R.data:[],P=R==null?void 0:R.pagination;P&&(p.setCurrentPage(P.page||1),c(P.totalPages||1),m(P.total||0));const I=E.map(j=>{var _,Y,F,L;const k=j.submittedAt||j.submitted_at||j.createdAt||j.created_at;return{id:j.requestNumber||j.request_number||j.requestId,requestId:j.requestId,displayId:j.requestNumber||j.request_number||j.requestId,title:j.title,description:j.description,status:(j.status||"").toString().toLowerCase().replace("_","-"),priority:(j.priority||"").toString().toLowerCase(),initiator:{name:((_=j.initiator)==null?void 0:_.displayName)||((Y=j.initiator)==null?void 0:Y.email)||"—",avatar:(((F=j.initiator)==null?void 0:F.displayName)||((L=j.initiator)==null?void 0:L.email)||"NA").split(" ").map(A=>A[0]).join("").slice(0,2).toUpperCase()},currentApprover:j.currentApprover?{name:j.currentApprover.name||j.currentApprover.email||"—",avatar:(j.currentApprover.name||j.currentApprover.email||"CA").split(" ").map(A=>A[0]).join("").slice(0,2).toUpperCase(),sla:j.currentApprover.sla}:void 0,createdAt:k||"—",approvalStep:j.currentLevel?`Step ${j.currentLevel} of ${j.totalLevels||"?"}`:void 0,department:j.department,currentLevelSLA:j.currentLevelSLA}});a(I)}finally{n(!1),o(!1)}},[u,p]);h.current=g;const y=()=>{o(!0),g(p.currentPage,{search:p.searchTerm||void 0,status:p.statusFilter!=="all"?p.statusFilter:void 0,priority:p.priorityFilter!=="all"?p.priorityFilter:void 0,sortBy:p.sortBy,sortOrder:p.sortOrder})},v=b=>{b>=1&&b<=l&&(p.setCurrentPage(b),g(b,{search:p.searchTerm||void 0,status:p.statusFilter!=="all"?p.statusFilter:void 0,priority:p.priorityFilter!=="all"?p.priorityFilter:void 0,sortBy:p.sortBy,sortOrder:p.sortOrder}))},w=()=>{const b=[];let R=Math.max(1,p.currentPage-Math.floor(2.5)),E=Math.min(l,R+5-1);E-R<4&&(R=Math.max(1,E-5+1));for(let P=R;P<=E;P++)b.push(P);return b},f=x.useRef(!1);x.useEffect(()=>{if(!f.current){f.current=!0;const b=p.currentPage||1;g(b,{search:p.searchTerm||void 0,status:p.statusFilter!=="all"?p.statusFilter:void 0,priority:p.priorityFilter!=="all"?p.priorityFilter:void 0,sortBy:p.sortBy,sortOrder:p.sortOrder})}},[]),x.useEffect(()=>{if(!f.current)return;const b=setTimeout(()=>{p.setCurrentPage(1),g(1,{search:p.searchTerm||void 0,status:p.statusFilter!=="all"?p.statusFilter:void 0,priority:p.priorityFilter!=="all"?p.priorityFilter:void 0,sortBy:p.sortBy,sortOrder:p.sortOrder})},p.searchTerm?500:0);return()=>clearTimeout(b)},[p.searchTerm,p.statusFilter,p.priorityFilter,p.sortBy,p.sortOrder]);const C=s;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(Ae,{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(ee,{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:[r?"Loading…":`${d||s.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:y,disabled:i,children:[e.jsx(Et,{className:`w-3.5 h-3.5 sm:w-4 sm:h-4 ${i?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:i?"Refreshing...":"Refresh"})]})]})]}),e.jsxs(K,{className:"shadow-lg border-0",children:[e.jsx(ae,{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(sr,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(re,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(ge,{className:"text-xs sm:text-sm",children:p.activeFiltersCount>0&&e.jsxs("span",{className:"text-blue-600 font-medium",children:[p.activeFiltersCount," filter",p.activeFiltersCount>1?"s":""," active"]})})]})]}),p.activeFiltersCount>0&&e.jsxs(M,{variant:"ghost",size:"sm",onClick:p.clearFilters,className:"text-red-600 hover:bg-red-50 gap-1 h-8 sm:h-9 px-2 sm:px-3",children:[e.jsx(lt,{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(G,{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(Xt,{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(fe,{placeholder:"Search requests, IDs...",value:p.searchTerm,onChange:b=>p.setSearchTerm(b.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(Te,{value:p.priorityFilter,onValueChange:p.setPriorityFilter,children:[e.jsx(Re,{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(ke,{placeholder:"All Priorities"})}),e.jsxs(De,{children:[e.jsx(U,{value:"all",children:"All Priorities"}),e.jsx(U,{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(U,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ct,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(Te,{value:p.statusFilter,onValueChange:p.setStatusFilter,children:[e.jsx(Re,{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(ke,{placeholder:"All Statuses"})}),e.jsxs(De,{children:[e.jsx(U,{value:"all",children:"All Statuses"}),e.jsx(U,{value:"pending",children:"Pending (In Approval)"}),e.jsx(U,{value:"approved",children:"Approved (Needs Closure)"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Te,{value:p.sortBy,onValueChange:b=>p.setSortBy(b),children:[e.jsx(Re,{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(ke,{placeholder:"Sort by"})}),e.jsxs(De,{children:[e.jsx(U,{value:"due",children:"Due Date"}),e.jsx(U,{value:"created",children:"Date Created"}),e.jsx(U,{value:"priority",children:"Priority"}),e.jsx(U,{value:"sla",children:"SLA Progress"})]})]}),e.jsx(M,{variant:"outline",size:"sm",onClick:()=>p.setSortOrder(p.sortOrder==="asc"?"desc":"asc"),className:"px-2 sm:px-3 h-9 sm:h-10 md:h-11",children:p.sortOrder==="asc"?e.jsx(gd,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(fd,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]}),e.jsx("div",{className:"space-y-3",children:C.map(b=>{const N=B0(b.priority),R=V0(b.status);return e.jsx(K,{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(b.id,b.title),children:e.jsx(G,{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 ${N.color} border shadow-sm`,children:e.jsx(N.icon,{className:`w-5 h-5 ${N.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:b.displayId||b.id}),e.jsxs(ee,{variant:"outline",className:`${R.color} text-xs px-2.5 py-0.5 font-semibold shrink-0`,children:[e.jsx(R.icon,{className:"w-3.5 h-3.5 mr-1"}),R.label||b.status]}),b.department&&e.jsx(ee,{variant:"secondary",className:"bg-blue-50 text-blue-700 text-xs px-2.5 py-0.5 hidden sm:inline-flex",children:b.department}),e.jsx(ee,{variant:"outline",className:`${N.color} text-xs px-2.5 py-0.5 capitalize hidden md:inline-flex`,children:b.priority})]}),e.jsx("h4",{className:"text-sm font-semibold text-gray-800 line-clamp-1 leading-relaxed",children:b.title}),b.currentLevelSLA&&(()=>{var k;const E=!!(b.isPaused||(k=b.pauseInfo)!=null&&k.isPaused||b.status==="paused"),P=b.currentLevelSLA.percentageUsed||0,j=E?{bg:"bg-gray-100 border border-gray-300",progress:"bg-gray-500",text:"text-gray-600",icon:"text-gray-600"}:P>=100?{bg:"bg-red-50 border border-red-200",progress:"bg-red-600",text:"text-red-600",icon:"text-blue-600"}:P>=75?{bg:"bg-orange-50 border border-orange-200",progress:"bg-orange-500",text:"text-orange-600",icon:"text-blue-600"}:P>=50?{bg:"bg-amber-50 border border-amber-200",progress:"bg-amber-500",text:"text-amber-600",icon:"text-blue-600"}:{bg:"bg-green-50 border border-green-200",progress:"bg-green-600",text:"text-gray-700",icon:"text-blue-600"};return e.jsxs("div",{className:`p-2 rounded-md ${j.bg}`,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?e.jsx(Ka,{className:`w-3.5 h-3.5 ${j.icon}`}):e.jsx(Ie,{className:`w-3.5 h-3.5 ${j.icon}`}),e.jsxs("span",{className:"text-xs font-medium text-gray-900",children:["TAT: ",P,"% ",E&&"(paused)"]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"text-gray-600",children:b.currentLevelSLA.elapsedText}),e.jsxs("span",{className:`font-semibold ${j.text}`,children:[b.currentLevelSLA.remainingText," left"]})]})]}),e.jsx(gs,{value:P,className:"h-1.5",indicatorClassName:j.progress})]})})(),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(bt,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(jt,{className:"bg-gradient-to-br from-slate-700 to-slate-900 text-white text-[10px] font-bold",children:b.initiator.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:b.initiator.name})]}),b.currentApprover&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(bt,{className:"h-6 w-6 ring-2 ring-yellow-200 shadow-sm",children:e.jsx(jt,{className:"bg-yellow-500 text-white text-[10px] font-bold",children:b.currentApprover.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:b.currentApprover.name})]}),b.approvalStep&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Pe,{className:"w-3.5 h-3.5 text-blue-500"}),e.jsx("span",{className:"font-medium",children:b.approvalStep})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(We,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",b.createdAt!=="—"?fs(b.createdAt):"—"]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(Nt,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})},b.id)})}),C.length===0&&e.jsx(K,{className:"shadow-lg border-0",children:e.jsxs(G,{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(Ae,{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:p.searchTerm||p.activeFiltersCount>0?"Try adjusting your filters or search terms to see more results.":"No open requests available at the moment."}),p.activeFiltersCount>0&&e.jsx(M,{variant:"outline",className:"mt-4",onClick:p.clearFilters,children:"Clear all filters"})]})}),l>1&&!r&&e.jsx(K,{className:"shadow-md",children:e.jsx(G,{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 ",(p.currentPage-1)*u+1," to ",Math.min(p.currentPage*u,d)," of ",d," open requests"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(M,{variant:"outline",size:"sm",onClick:()=>v(p.currentPage-1),disabled:p.currentPage===1,className:"h-8 w-8 p-0",children:e.jsx(Nt,{className:"h-4 w-4 rotate-180"})}),p.currentPage>3&&l>5&&e.jsxs(e.Fragment,{children:[e.jsx(M,{variant:"outline",size:"sm",onClick:()=>v(1),className:"h-8 w-8 p-0",children:"1"}),e.jsx("span",{className:"text-muted-foreground",children:"..."})]}),w().map(b=>e.jsx(M,{variant:b===p.currentPage?"default":"outline",size:"sm",onClick:()=>v(b),className:`h-8 w-8 p-0 ${b===p.currentPage?"bg-re-green text-white hover:bg-re-green/90":""}`,children:b},b)),p.currentPage<l-2&&l>5&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"..."}),e.jsx(M,{variant:"outline",size:"sm",onClick:()=>v(l),className:"h-8 w-8 p-0",children:l})]}),e.jsx(M,{variant:"outline",size:"sm",onClick:()=>v(p.currentPage+1),disabled:p.currentPage===l,className:"h-8 w-8 p-0",children:e.jsx(Nt,{className:"h-4 w-4"})})]})]})})})]})}function H0({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(Ae,{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(ee,{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(Et,{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 q0({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(K,{className:"shadow-lg border-0","data-testid":"closed-requests-filters",children:[e.jsx(ae,{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(sr,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(re,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(ge,{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(lt,{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(G,{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(Xt,{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(fe,{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(Te,{value:s,onValueChange:l,children:[e.jsx(Re,{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(ke,{placeholder:"All Priorities"})}),e.jsxs(De,{children:[e.jsx(U,{value:"all",children:"All Priorities"}),e.jsx(U,{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(U,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ct,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(Te,{value:a,onValueChange:c,children:[e.jsx(Re,{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(ke,{placeholder:"Closure Type"})}),e.jsxs(De,{children:[e.jsx(U,{value:"all",children:"All Closures"}),e.jsx(U,{value:"approved",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(je,{className:"w-4 h-4 text-green-600"}),e.jsx("span",{children:"Closed After Approval"})]})}),e.jsx(U,{value:"rejected",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Je,{className:"w-4 h-4 text-red-600"}),e.jsx("span",{children:"Closed After Rejection"})]})})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Te,{value:r,onValueChange:h=>d(h),children:[e.jsx(Re,{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(ke,{placeholder:"Sort by"})}),e.jsxs(De,{children:[e.jsx(U,{value:"due",children:"Due Date"}),e.jsx(U,{value:"created",children:"Date Created"}),e.jsx(U,{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(gd,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(fd,{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:ct,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:ct,iconColor:"text-gray-600"}}}function K0(t){switch(t){case"closed":return{color:"bg-slate-100 text-slate-800 border-slate-300",icon:je,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:Je,iconColor:"text-red-600",label:"Rejected",description:"Request was declined"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Pe,iconColor:"text-gray-600",label:t,description:""}}}function G0({request:t,onViewRequest:s}){const a=W0(t.priority),r=K0(t.status),n=a.icon,i=r.icon;return e.jsx(K,{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(G,{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(ee,{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(ee,{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(ee,{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(bt,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(jt,{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(je,{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(We,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",t.createdAt!=="—"?fs(t.createdAt,!0):"—"]})]}),t.dueDate&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(je,{className:"w-3.5 h-3.5 text-slate-600"}),e.jsxs("span",{className:"font-medium",children:["Closed: ",fs(t.dueDate,!0)]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(Nt,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})})}function Y0({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(G0,{request:r,onViewRequest:a},r.id))})}function X0({searchTerm:t,activeFiltersCount:s,onClearFilters:a}){return e.jsx(K,{className:"shadow-lg border-0","data-testid":"closed-requests-empty",children:e.jsxs(G,{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(Ae,{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 Z0(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 Q0({pagination:t,onPageChange:s}){const{currentPage:a,totalPages:r,totalRecords:n,itemsPerPage:i}=t;if(r<=1)return null;const o=Z0(a,r);return e.jsx(K,{className:"shadow-md","data-testid":"closed-requests-pagination",children:e.jsx(G,{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(Nt,{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)),a<r-2&&r>5&&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(Nt,{className:"h-4 w-4"})})]})]})})})}function J0(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 ey(t){return t.map(J0)}function ty({itemsPerPage:t=10}={}){const[s,a]=x.useState([]),[r,n]=x.useState(!1),[i,o]=x.useState(!1),[l,c]=x.useState({currentPage:1,totalPages:1,totalRecords:0,itemsPerPage:t}),d=x.useCallback(async(u=1,h)=>{try{u===1&&(n(!0),a([]));const p=await Ot.listClosedByMe({page:u,limit:t,search:h==null?void 0:h.search,status:h!=null&&h.status&&h.status!=="all"?h.status:void 0,priority:h==null?void 0:h.priority,sortBy:h==null?void 0:h.sortBy,sortOrder:h==null?void 0:h.sortOrder}),g=Array.isArray(p==null?void 0:p.data)?p.data:[],y=ey(g);a(y);const v=p==null?void 0:p.pagination;v&&c({currentPage:v.page||1,totalPages:v.totalPages||1,totalRecords:v.total||0,itemsPerPage:t})}catch(p){console.error("[ClosedRequests] Error fetching requests:",p),a([])}finally{n(!1),o(!1)}},[t]),m=x.useCallback(u=>{o(!0),d(l.currentPage,u)},[d,l.currentPage]);return{requests:s,loading:r,refreshing:i,pagination:l,fetchRequests:d,handleRefresh:m}}const sy={searchTerm:"",statusFilter:"all",priorityFilter:"all",sortBy:"created",sortOrder:"desc",currentPage:1},Jd=Ta({name:"closedRequests",initialState:sy,reducers:{setSearchTerm:(t,s)=>{t.searchTerm=s.payload},setStatusFilter:(t,s)=>{t.statusFilter=s.payload},setPriorityFilter:(t,s)=>{t.priorityFilter=s.payload},setSortBy:(t,s)=>{t.sortBy=s.payload},setSortOrder:(t,s)=>{t.sortOrder=s.payload},setCurrentPage:(t,s)=>{t.currentPage=s.payload},clearFilters:t=>{t.searchTerm="",t.statusFilter="all",t.priorityFilter="all",t.currentPage=1}}}),{setSearchTerm:ay,setStatusFilter:ry,setPriorityFilter:ny,setSortBy:iy,setSortOrder:oy,setCurrentPage:ly,clearFilters:cy}=Jd.actions;function dy({onFiltersChange:t,debounceMs:s=500}={}){const a=ir(),r=x.useRef(null),n=x.useRef(!0),{searchTerm:i,statusFilter:o,priorityFilter:l,sortBy:c,sortOrder:d,currentPage:m}=Ra(b=>b.closedRequests),u=x.useCallback(b=>a(ay(b)),[a]),h=x.useCallback(b=>a(ry(b)),[a]),p=x.useCallback(b=>a(ny(b)),[a]),g=x.useCallback(b=>a(iy(b)),[a]),y=x.useCallback(b=>a(oy(b)),[a]),v=x.useCallback(b=>a(ly(b)),[a]),w=x.useCallback(()=>({search:i,status:o,priority:l,sortBy:c,sortOrder:d}),[i,o,l,c,d]);x.useEffect(()=>{if(n.current){n.current=!1;return}r.current&&clearTimeout(r.current);const b=setTimeout(()=>{t&&t(w())},i?s:0);return r.current=b,()=>{r.current&&clearTimeout(r.current)}},[i,o,l,c,d,t,w,s]);const f=x.useCallback(()=>{a(cy())},[a]),C=[i,l!=="all"?l:null,o!=="all"?o:null].filter(Boolean).length;return{searchTerm:i,priorityFilter:l,statusFilter:o,sortBy:c,sortOrder:d,currentPage:m,setSearchTerm:u,setPriorityFilter:p,setStatusFilter:h,setSortBy:g,setSortOrder:y,setCurrentPage:v,clearFilters:f,activeFiltersCount:C,getFilters:w}}function my({onViewRequest:t}){const s=ty({itemsPerPage:10}),a=x.useRef(s.fetchRequests);a.current=s.fetchRequests;const r=dy(),n=x.useRef({searchTerm:r.searchTerm,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,sortBy:r.sortBy,sortOrder:r.sortOrder}),i=x.useRef(!1);x.useEffect(()=>{const c=r.currentPage||1;a.current(c,{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}),i.current=!0},[]),x.useEffect(()=>{if(!i.current)return;const c=n.current;if(!(c.searchTerm!==r.searchTerm||c.statusFilter!==r.statusFilter||c.priorityFilter!==r.priorityFilter||c.sortBy!==r.sortBy||c.sortOrder!==r.sortOrder))return;const m=setTimeout(()=>{r.setCurrentPage(1),a.current(1,{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}),n.current={searchTerm:r.searchTerm,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,sortBy:r.sortBy,sortOrder:r.sortOrder}},r.searchTerm!==c.searchTerm?500:0);return()=>clearTimeout(m)},[r.searchTerm,r.statusFilter,r.priorityFilter,r.sortBy,r.sortOrder]);const o=x.useCallback(c=>{c>=1&&c<=s.pagination.totalPages&&(r.setCurrentPage(c),s.fetchRequests(c,{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]),l=x.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(H0,{totalRecords:s.pagination.totalRecords,loading:s.loading,refreshing:s.refreshing,onRefresh:l}),e.jsx(q0,{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(Y0,{requests:s.requests,loading:s.loading,onViewRequest:t}),s.requests.length===0&&!s.loading&&e.jsx(X0,{searchTerm:r.searchTerm,activeFiltersCount:r.activeFiltersCount,onClearFilters:r.clearFilters}),!s.loading&&e.jsx(Q0,{pagination:s.pagination,onPageChange:o})]})}function Jr({className:t,...s}){return e.jsx(rp,{"data-slot":"tabs",className:ce("flex flex-col gap-2",t),...s})}function en({className:t,...s}){return e.jsx(np,{"data-slot":"tabs-list",className:ce("bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-xl p-[3px] flex",t),...s})}function xt({className:t,...s}){return e.jsx(ip,{"data-slot":"tabs-trigger",className:ce("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 gt({className:t,...s}){return e.jsx(op,{"data-slot":"tabs-content",className:ce("flex-1 outline-none",t),...s})}const em={"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"]}},uy={"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 hy(t,s=[],a){const[r,n]=x.useState(null),[i,o]=x.useState(!1),[l,c]=x.useState(!0),[d,m]=x.useState(null),[u,h]=x.useState(null),[p,g]=x.useState(!1),y=(N,R)=>(N||R||"NA").toString().split(" ").map(P=>P[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),v=N=>{const R=(N||"").toUpperCase();return R==="IN_PROGRESS"?"in-review":R==="PENDING"?"pending":R==="APPROVED"?"approved":R==="REJECTED"?"rejected":R==="CLOSED"?"closed":R==="SKIPPED"?"skipped":(N||"").toLowerCase()},w=x.useCallback(async()=>{var N,R,E,P,I,j,k,_,Y;o(!0);try{const F=await Ot.getWorkflowDetails(t);if(!F){console.warn("[useRequestDetails] No details returned from API");return}const L=F.workflow||{},A=Array.isArray(F.approvals)?F.approvals:[],S=Array.isArray(F.participants)?F.participants:[],T=Array.isArray(F.documents)?F.documents:[],D=F.summary||{},H=Array.isArray(F.tatAlerts)?F.tatAlerts:[];H.length>0;const z=(D==null?void 0:D.currentLevel)||L.currentLevel||1,Z=A.map(W=>{const me=W.levelNumber||0,we=(W.status||"").toString().toUpperCase(),Ee=W.levelId||W.level_id;let Fe=v(W.status);me>z&&we!=="APPROVED"&&we!=="REJECTED"?Fe="waiting":me===z&&we==="PENDING"&&(Fe="pending");const le=H.filter(ye=>ye.levelId===Ee);return{step:me,levelId:Ee,role:W.levelName||W.approverName||"Approver",status:Fe,approver:W.approverName||W.approverEmail,approverId:W.approverId||W.approver_id,approverEmail:W.approverEmail,tatHours:Number(W.tatHours||0),elapsedHours:Number(W.elapsedHours||0),remainingHours:Number(W.remainingHours||0),tatPercentageUsed:Number(W.tatPercentageUsed||0),actualHours:W.levelEndTime&&W.levelStartTime?Math.max(0,(new Date(W.levelEndTime).getTime()-new Date(W.levelStartTime).getTime())/(1e3*60*60)):void 0,comment:W.comments||void 0,timestamp:W.actionDate||void 0,levelStartTime:W.levelStartTime||W.tatStartTime,tatAlerts:le,skipReason:W.skipReason||void 0,isSkipped:we==="SKIPPED"||W.isSkipped||!1}}),O=S.filter(W=>(W.participantType||W.participant_type||"").toUpperCase()==="SPECTATOR").map(W=>({name:W.userName||W.user_name||W.userEmail||W.user_email,role:"Spectator",email:W.userEmail||W.user_email,avatar:y(W.userName||W.user_name,W.userEmail||W.user_email)})),se=W=>{var we,Ee;if(!W)return;const me=S.find(Fe=>Fe.userId===W||Fe.user_id===W);return me!=null&&me.userName||me!=null&&me.user_name?me.userName||me.user_name:L.initiatorId===W?((we=L.initiator)==null?void 0:we.displayName)||((Ee=L.initiator)==null?void 0:Ee.email):W},te=T.map(W=>{const me=Number(W.fileSize||W.file_size||0),we=(me/(1024*1024)).toFixed(2)+" MB";return{documentId:W.documentId||W.document_id,name:W.originalFileName||W.fileName||W.file_name,fileType:W.fileType||W.file_type||"",size:we,sizeBytes:me,uploadedBy:se(W.uploadedBy||W.uploaded_by),uploadedAt:W.uploadedAt||W.uploaded_at}}),$=Array.isArray(F.activities)?F.activities.filter(W=>(W.type||"").toLowerCase()!=="sla_warning"):[];let X=null;try{X=await ml(L.requestId)}catch(W){console.debug("Pause details not available:",W)}const ne={...L,id:L.requestNumber||L.requestId,requestId:L.requestId,requestNumber:L.requestNumber,title:L.title,description:L.description,status:v(L.status),priority:(L.priority||"").toString().toLowerCase(),approvalFlow:Z,approvals:A,participants:S,documents:te,spectators:O,summary:D,initiator:{name:((N=L.initiator)==null?void 0:N.displayName)||((R=L.initiator)==null?void 0:R.email),role:((E=L.initiator)==null?void 0:E.designation)||void 0,department:((P=L.initiator)==null?void 0:P.department)||void 0,email:((I=L.initiator)==null?void 0:I.email)||void 0,phone:((j=L.initiator)==null?void 0:j.phone)||void 0,avatar:y((k=L.initiator)==null?void 0:k.displayName,(_=L.initiator)==null?void 0:_.email)},createdAt:L.createdAt,updatedAt:L.updatedAt,totalSteps:L.totalLevels||1,currentStepRaw:(D==null?void 0:D.currentLevel)||L.currentLevel||1,currentStep:Math.min(Math.max(1,(D==null?void 0:D.currentLevel)||L.currentLevel||1),L.totalLevels||1),auditTrail:$,conclusionRemark:L.conclusionRemark||null,closureDate:L.closureDate||null,pauseInfo:X||null};n(ne);const q=(Y=a==null?void 0:a.email)==null?void 0:Y.toLowerCase(),Q=A.find(W=>{const me=(W.status||"").toString().toUpperCase(),we=(W.approverEmail||"").toLowerCase(),Ee=W.levelNumber||0;return(me==="PENDING"||me==="IN_PROGRESS"||me==="PAUSED")&&we===q&&Ee===z});h(Q||null);const oe=a==null?void 0:a.userId;if(oe){const W=S.some(me=>(me.participantType||me.participant_type||"").toUpperCase()==="SPECTATOR"&&(me.userId||me.user_id)===oe);g(W)}else g(!1)}catch(F){console.error("[useRequestDetails] Error refreshing details:",F),alert("Failed to refresh request details. Please try again.")}finally{o(!1)}},[t,a]);x.useEffect(()=>{if(!t){c(!1);return}let N=!0;return c(!0),m(null),(async()=>{var R,E,P,I,j,k,_,Y,F,L,A,S;try{const T=await Ot.getWorkflowDetails(t);if(!N||!T){N&&c(!1);return}const D=T.workflow||{},H=Array.isArray(T.approvals)?T.approvals:[],z=Array.isArray(T.participants)?T.participants:[],Z=Array.isArray(T.documents)?T.documents:[],O=T.summary||{},se=Array.isArray(T.tatAlerts)?T.tatAlerts:[],te=(D.priority||"").toString().toLowerCase(),$=(O==null?void 0:O.currentLevel)||D.currentLevel||1,X=H.map(le=>{const ye=le.levelNumber||0,Ve=(le.status||"").toString().toUpperCase(),Le=le.levelId||le.level_id;let Zt=v(le.status);Ve==="PAUSED"?Zt="paused":ye>$&&Ve!=="APPROVED"&&Ve!=="REJECTED"?Zt="waiting":ye===$&&(Ve==="PENDING"||Ve==="IN_PROGRESS")&&(Zt=Ve==="IN_PROGRESS"?"in-review":"pending");const js=se.filter(Ws=>Ws.levelId===Le);return{step:ye,levelId:Le,role:le.levelName||le.approverName||"Approver",status:Zt,approver:le.approverName||le.approverEmail,approverId:le.approverId||le.approver_id,approverEmail:le.approverEmail,tatHours:Number(le.tatHours||0),elapsedHours:Number(le.elapsedHours||0),remainingHours:Number(le.remainingHours||0),tatPercentageUsed:Number(le.tatPercentageUsed||0),actualHours:le.elapsedHours!==void 0&&le.elapsedHours!==null?Number(le.elapsedHours):void 0,comment:le.comments||void 0,timestamp:le.actionDate||void 0,levelStartTime:le.levelStartTime||le.tatStartTime,tatAlerts:js}}),ne=z.filter(le=>(le.participantType||"").toUpperCase()==="SPECTATOR").map(le=>({name:le.userName||le.userEmail,role:"Spectator",avatar:y(le.userName,le.userEmail)})),q=le=>{var Ve,Le;if(!le)return;const ye=z.find(Zt=>Zt.userId===le);return ye!=null&&ye.userName?ye.userName:D.initiatorId===le?((Ve=D.initiator)==null?void 0:Ve.displayName)||((Le=D.initiator)==null?void 0:Le.email):le},Q=Z.map(le=>{const ye=Number(le.fileSize||0),Ve=(ye/(1024*1024)).toFixed(2)+" MB";return{documentId:le.documentId||le.document_id,name:le.originalFileName||le.fileName,fileType:le.fileType||le.file_type||"",size:Ve,sizeBytes:ye,uploadedBy:q(le.uploadedBy),uploadedAt:le.uploadedAt}}),oe=Array.isArray(T.activities)?T.activities.filter(le=>(le.type||"").toLowerCase()!=="sla_warning"):[];let W=null;try{W=await ml(D.requestId)}catch(le){console.debug("Pause details not available:",le)}const me={id:D.requestNumber||D.requestId,requestId:D.requestId,title:D.title,description:D.description,priority:te,status:v(D.status),summary:O,initiator:{name:((R=D.initiator)==null?void 0:R.displayName)||((E=D.initiator)==null?void 0:E.email),role:((P=D.initiator)==null?void 0:P.designation)||void 0,department:((I=D.initiator)==null?void 0:I.department)||void 0,email:((j=D.initiator)==null?void 0:j.email)||void 0,phone:((k=D.initiator)==null?void 0:k.phone)||void 0,avatar:y((_=D.initiator)==null?void 0:_.displayName,(Y=D.initiator)==null?void 0:Y.email)},createdAt:D.createdAt,updatedAt:D.updatedAt,totalSteps:D.totalLevels||1,currentStepRaw:(O==null?void 0:O.currentLevel)||D.currentLevel||1,currentStep:Math.min(Math.max(1,(O==null?void 0:O.currentLevel)||D.currentLevel||1),D.totalLevels||1),approvalFlow:X,approvals:H,documents:Q,spectators:ne,auditTrail:oe,conclusionRemark:D.conclusionRemark||null,closureDate:D.closureDate||null,pauseInfo:W||null};n(me);const we=(F=a==null?void 0:a.email)==null?void 0:F.toLowerCase(),Ee=H.find(le=>{const ye=(le.status||"").toString().toUpperCase(),Ve=(le.approverEmail||"").toLowerCase(),Le=le.levelNumber||0;return(ye==="PENDING"||ye==="IN_PROGRESS"||ye==="PAUSED")&&Ve===we&&Le===$});h(Ee||null);const Fe=a==null?void 0:a.userId;if(Fe){const le=z.some(ye=>(ye.participantType||"").toUpperCase()==="SPECTATOR"&&ye.userId===Fe);g(le)}else g(!1)}catch(T){if(console.error("[useRequestDetails] Error loading request details:",T),N){if(((L=T==null?void 0:T.response)==null?void 0:L.status)===403){const D=((S=(A=T==null?void 0:T.response)==null?void 0:A.data)==null?void 0:S.message)||"You do not have permission to view this request. Access is restricted to the initiator, approvers, and spectators of this request.";m({denied:!0,message:D})}n(null)}}finally{N&&c(!1)}})(),()=>{N=!1}},[t,a]);const f=x.useMemo(()=>{if(r)return r;const N=em[t];if(N)return N;const R=uy[t];if(R)return R;const E=s.find(P=>P.id===t||P.requestNumber===t||P.request_number===t);return E||null},[t,s,r]),C=x.useMemo(()=>{var E,P,I;if(!f||!a)return!1;const N=(E=a==null?void 0:a.email)==null?void 0:E.toLowerCase(),R=(I=(P=f.initiator)==null?void 0:P.email)==null?void 0:I.toLowerCase();return N===R},[f,a]),b=x.useMemo(()=>{var R;if(!f)return[];const N=[];return(R=f.initiator)!=null&&R.email&&N.push({email:f.initiator.email.toLowerCase(),participantType:"INITIATOR",name:f.initiator.name}),f.approvalFlow&&Array.isArray(f.approvalFlow)&&f.approvalFlow.forEach(E=>{E.approverEmail&&N.push({email:E.approverEmail.toLowerCase(),participantType:"APPROVER",name:E.approver})}),f.spectators&&Array.isArray(f.spectators)&&f.spectators.forEach(E=>{E.email&&N.push({email:E.email.toLowerCase(),participantType:"SPECTATOR",name:E.name})}),f.participants&&Array.isArray(f.participants)&&f.participants.forEach(E=>{const P=(E.userEmail||E.email||"").toLowerCase(),I=(E.participantType||E.participant_type||"").toUpperCase(),j=E.userName||E.user_name||E.name;P&&I&&!N.find(k=>k.email===P)&&N.push({email:P,participantType:I,name:j})}),N},[f]);return x.useEffect(()=>{if(!t||!r)return;const N=Ya();if(!N){console.warn("[useRequestDetails] Socket not available");return}console.log("[useRequestDetails] Setting up socket listener for request:",r.requestId);const R=E=>{console.log("[useRequestDetails] 📡 Received request:updated event:",E),(E==null?void 0:E.requestId)===r.requestId||(E==null?void 0:E.requestNumber)===t?(console.log("[useRequestDetails] 🔄 Request updated remotely, refreshing silently..."),w()):console.log("[useRequestDetails] ⚠️ Event for different request, ignoring")};return N.on("request:updated",R),console.log("[useRequestDetails] ✅ Registered listener for request:updated"),()=>{console.log("[useRequestDetails] 🧹 Cleaning up socket listener"),N.off("request:updated",R)}},[t,r,w]),{request:f,apiRequest:r,loading:l,refreshing:i,refreshDetails:w,currentApprovalLevel:u,isSpectator:p,isInitiator:C,existingParticipants:b,accessDenied:d}}function py(t,s,a,r){const[n,i]=x.useState([]),[o,l]=x.useState(0),[c,d]=x.useState([]);return x.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 Ot.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=Ya();if(!h){console.error("[useRequestSocket] Socket not available");return}const p=r==null?void 0:r.userId,g=()=>{oi(h,u,p)};return h.connected?g():h.on("connect",g),()=>{m&&(h.off("connect",g),Vd(h,u))}})(),()=>{m=!1}},[t,r]),x.useEffect(()=>{!t||!s||(async()=>{try{const m=await ba(t),u=s.auditTrail||[],h=[...m,...u];h.sort((p,g)=>{const y=new Date(p.createdAt||p.created_at||p.timestamp||0).getTime(),v=new Date(g.createdAt||g.created_at||g.timestamp||0).getTime();return y-v}),i(h)}catch(m){console.error("[useRequestSocket] Failed to fetch and merge messages:",m)}})()},[t,s]),x.useEffect(()=>{if(!t)return;const m=Ya();if(!m)return;const u=p=>{a!=="worknotes"&&l(g=>g+1),(async()=>{try{const g=await ba(t),y=(s==null?void 0:s.auditTrail)||[],v=[...g,...y].sort((w,f)=>{const C=new Date(w.createdAt||w.created_at||w.timestamp||0).getTime(),b=new Date(f.createdAt||f.created_at||f.timestamp||0).getTime();return C-b});i(v)}catch(g){console.error("[useRequestSocket] Failed to refresh messages:",g)}})()},h=p=>{const g=p.type==="breach"?"⏰":p.type==="threshold2"?"⚠️":"⏳";(async()=>{try{const y=await Ot.getWorkflowDetails(t);y&&(Array.isArray(y.tatAlerts)&&y.tatAlerts,"Notification"in window&&Notification.permission==="granted"&&new Notification(`${g} TAT Alert`,{body:p.message,icon:"/favicon.ico",tag:`tat-${p.requestId}-${p.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]),x.useEffect(()=>{a==="worknotes"&&l(0)},[a]),{mergedMessages:n,unreadWorkNotes:o,workNoteAttachments:c,setWorkNoteAttachments:d}}async function xy(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 de.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 ia=async t=>{const s=t?{category:t}:{};return(await de.get("/users/configurations",{params:s})).data.data},tn=async t=>{const s=t?{category:t}:{};return(await de.get("/admin/configurations",{params:s})).data.data},vt=async(t,s)=>{await de.put(`/admin/configurations/${t}`,{configValue:s})},gy=async t=>{await de.post(`/admin/configurations/${t}/reset`)},fy=async t=>{const s=t?{year:t}:{};return(await de.get("/admin/holidays",{params:s})).data.data},yy=async t=>(await de.post("/admin/holidays",t)).data.data,vy=async(t,s)=>(await de.put(`/admin/holidays/${t}`,s)).data.data,by=async t=>{await de.delete(`/admin/holidays/${t}`)};function jy(t,s){const[a,r]=x.useState(!1),[n,i]=x.useState(null),[o,l]=x.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[c,d]=x.useState({show:!1,errors:[]});x.useEffect(()=>{(async()=>{try{const g=await ia("DOCUMENT_POLICY"),y={};g.forEach(C=>{y[C.configKey]=C.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(C=>C.trim().toLowerCase());l({maxFileSizeMB:v,allowedFileTypes:f})}catch(g){console.error("Failed to load document policy:",g)}})()},[]);const m=p=>{const g=o.maxFileSizeMB*1024*1024;if(p.size>g)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${o.maxFileSizeMB}MB. Current size: ${(p.size/(1024*1024)).toFixed(2)}MB`};const y=p.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 p=>{var f,C;const g=p.target.files;if(!g||g.length===0)return;const y=Array.from(g),v=[],w=[];if(y.forEach(b=>{const N=m(b);N.valid?w.push(b):v.push({fileName:b.name,reason:N.reason||"Unknown validation error"})}),v.length>0&&d({show:!0,errors:v}),w.length===0){p.target&&(p.target.value="");return}r(!0);try{const b=w[0],N=t==null?void 0:t.requestId;if(!N){be.error("Request ID not found");return}b&&await xy(b,N,"SUPPORTING"),await s(),w.length<y.length?be.warning(`${w.length} of ${y.length} file(s) were uploaded. ${v.length} file(s) were rejected.`):be.success("Document uploaded successfully")}catch(b){console.error("[useDocumentUpload] Upload error:",b),be.error(((C=(f=b==null?void 0:b.response)==null?void 0:f.data)==null?void 0:C.error)||"Failed to upload document")}finally{r(!1),p.target&&(p.target.value="")}};return{uploadingDocument:a,handleDocumentUpload:u,triggerFileInput:()=>{const p=document.createElement("input");p.type="file",p.accept=o.allowedFileTypes.map(g=>`.${g}`).join(","),p.onchange=u,p.click()},previewDocument:n,setPreviewDocument:i,documentPolicy:o,documentError:c,setDocumentError:d}}const Ny="modulepreload",wy=function(t){return"/"+t},hl={},Cn=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=wy(c),c in hl)return;hl[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":Ny,d||(u.as="script"),u.crossOrigin="",u.href=c,l&&u.setAttribute("nonce",l),document.head.appendChild(u),d)return new Promise((h,p)=>{u.addEventListener("load",h),u.addEventListener("error",()=>p(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)})};function Cy(t,s,a,r,n,i,o){const[l,c]=x.useState(""),[d,m]=x.useState(!1),[u,h]=x.useState(!1),[p,g]=x.useState(!1),y=async()=>{try{const{getConclusion:f}=await Cn(async()=>{const{getConclusion:b}=await import("./conclusionApi-D1TurBfA.js");return{getConclusion:b}},__vite__mapDeps([0,1,2,3,4,5,6,7])),C=await f(t.requestId||s);C&&C.aiGeneratedRemark&&(c(C.finalRemark||C.aiGeneratedRemark),g(!!C.aiGeneratedRemark))}catch{}},v=async()=>{try{m(!0);const{generateConclusion:f}=await Cn(async()=>{const{generateConclusion:b}=await import("./conclusionApi-D1TurBfA.js");return{generateConclusion:b}},__vite__mapDeps([0,1,2,3,4,5,6,7])),C=await f(t.requestId||s);c(C.aiGeneratedRemark),g(!0)}catch(f){console.error("[useConclusionRemark] AI generation failed:",f),c(""),g(!1)}finally{m(!1)}},w=async()=>{var C,b;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:N}=await Cn(async()=>{const{finalizeConclusion:R}=await import("./conclusionApi-D1TurBfA.js");return{finalizeConclusion:R}},__vite__mapDeps([0,1,2,3,4,5,6,7]));await N(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(N){i==null||i({success:!1,title:"Error",message:((b=(C=N.response)==null?void 0:C.data)==null?void 0:b.error)||"Failed to finalize conclusion"}),o==null||o(!0)}finally{h(!1)}};return x.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:p,handleGenerateConclusion:v,handleFinalizeConclusion:w}}function Sy(t,s,a){const[r,n]=x.useState(!1),[i,o]=x.useState(!1),[l,c]=x.useState(!1),[d,m]=x.useState(!1),[u,h]=x.useState(!1),[p,g]=x.useState(!1),[y,v]=x.useState(null),[w,f]=x.useState(null);return{showApproveModal:r,setShowApproveModal:n,showRejectModal:i,setShowRejectModal:o,showAddApproverModal:l,setShowAddApproverModal:c,showAddSpectatorModal:d,setShowAddSpectatorModal:m,showSkipApproverModal:u,setShowSkipApproverModal:h,showActionStatusModal:p,setShowActionStatusModal:g,skipApproverData:y,setSkipApproverData:v,actionStatus:w,setActionStatus:f,handleApproveConfirm:async P=>{var j,k;const I=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!I){alert("Approval level not found");return}await O0(t,I,P||""),await a(),(j=window==null?void 0:window.closeModal)==null||j.call(window),(k=window==null?void 0:window.toast)==null||k.call(window,"Approved successfully")},handleRejectConfirm:async P=>{var j,k;if(!(P!=null&&P.trim())){alert("Comments & remarks are required");return}const I=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!I){alert("Approval level not found");return}await $0(t,I,P.trim(),P.trim()),await a(),(j=window==null?void 0:window.closeModal)==null||j.call(window),(k=window==null?void 0:window.toast)==null||k.call(window,"Rejected successfully")},handleAddApprover:async(P,I,j)=>{var k,_;try{await Gd(t,P,I,j),await a(),c(!1),f==null||f({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${j} with ${I}h TAT`}),g==null||g(!0)}catch(Y){throw f==null||f({success:!1,title:"Failed to Add Approver",message:((_=(k=Y==null?void 0:Y.response)==null?void 0:k.data)==null?void 0:_.error)||"Failed to add approver. Please try again."}),g==null||g(!0),Y}},handleSkipApprover:async P=>{var I,j;if(y)try{await P0(t,y.levelId,P),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."}),g==null||g(!0)}catch(k){throw f==null||f({success:!1,title:"Failed to Skip Approver",message:((j=(I=k==null?void 0:k.response)==null?void 0:I.data)==null?void 0:j.error)||"Failed to skip approver. Please try again."}),g==null||g(!0),k}},handleAddSpectator:async P=>{var I,j;try{await Yd(t,P),await a(),m(!1),f==null||f({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),g==null||g(!0)}catch(k){throw f==null||f({success:!1,title:"Failed to Add Spectator",message:((j=(I=k==null?void 0:k.response)==null?void 0:I.data)==null?void 0:j.error)||"Failed to add spectator. Please try again."}),g==null||g(!0),k}}}}const Ay=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"}}},Ty=t=>{switch(t){case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",label:"pending"};case"paused":return{color:"bg-gray-400 text-gray-100 border-gray-500",label:"paused"};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}}},ky=t=>{switch(t){case"approval":case"approved":return e.jsx(je,{className:"w-5 h-5 text-green-600"});case"rejection":case"rejected":return e.jsx(Je,{className:"w-5 h-5 text-red-600"});case"comment":return e.jsx(vs,{className:"w-5 h-5 text-blue-600"});case"status_change":case"updated":return e.jsx(Et,{className:"w-5 h-5 text-orange-600"});case"assignment":return e.jsx(Wr,{className:"w-5 h-5 text-purple-600"});case"created":return e.jsx(Ae,{className:"w-5 h-5 text-blue-600"});case"reminder":return e.jsx(Ie,{className:"w-5 h-5 text-yellow-600"});case"document_added":return e.jsx(qr,{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 Ry({sla:t,requestStatus:s,isPaused:a=!1,testId:r="sla-progress"}){if(!t||s==="approved"||s==="rejected"||s==="closed")return e.jsxs("div",{className:"flex items-center gap-2","data-testid":`${r}-status-only`,children:[s==="closed"?e.jsx(Ka,{className:"h-4 w-4 text-gray-600"}):s==="approved"?e.jsx(je,{className:"h-4 w-4 text-green-600"}):s==="rejected"?e.jsx(Je,{className:"h-4 w-4 text-red-600"}):e.jsx(Ie,{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"})]});const n=t.percentageUsed||0,i=t.status||"on_track",l=a?{badge:"bg-gray-500 text-white",progress:"bg-gray-500",text:"text-gray-600",icon:"text-gray-500"}:n>=100?{badge:"bg-red-600 text-white animate-pulse",progress:"bg-red-600",text:"text-red-600",icon:"text-blue-600"}:n>=75?{badge:"bg-orange-500 text-white",progress:"bg-orange-500",text:"text-orange-600",icon:"text-blue-600"}:n>=50?{badge:"bg-amber-500 text-white",progress:"bg-amber-500",text:"text-amber-600",icon:"text-blue-600"}:{badge:"bg-green-600 text-white",progress:"bg-green-600",text:"text-gray-700",icon:"text-blue-600"},c=i==="on_track"||i==="normal"?"normal":i;return e.jsxs("div",{"data-testid":r,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[a?e.jsx(Ka,{className:`h-4 w-4 ${l.icon}`}):e.jsx(Ie,{className:`h-4 w-4 ${l.icon}`}),e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:a?"SLA Progress (Paused)":"SLA Progress"})]}),e.jsxs(ee,{className:`text-xs ${l.badge}`,"data-testid":`${r}-badge`,children:[t.percentageUsed||0,"% elapsed ",a&&"(frozen)"]})]}),e.jsx(gs,{value:t.percentageUsed||0,className:"h-3 mb-2",indicatorClassName:l.progress,"data-testid":`${r}-bar`}),e.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[e.jsxs("span",{className:"text-gray-600","data-testid":`${r}-elapsed`,children:[t.elapsedText||ot(t.elapsedHours||0)," elapsed"]}),e.jsxs("span",{className:`font-semibold ${c==="breached"||c==="critical"?l.text:"text-gray-700"}`,"data-testid":`${r}-remaining`,children:[ot(t.remainingHours||0)," remaining"]})]}),t.deadline&&e.jsxs("p",{className:"text-xs text-gray-500","data-testid":`${r}-deadline`,children:["Due: ",fs(t.deadline,!0)," • ",t.percentageUsed||0,"% elapsed"]}),c==="critical"&&e.jsxs("p",{className:"text-xs text-orange-600 font-semibold mt-1 flex items-center gap-1.5","data-testid":`${r}-warning-critical`,children:[e.jsx(is,{className:"h-3.5 w-3.5"}),"Approaching Deadline"]}),c==="breached"&&e.jsxs("p",{className:"text-xs text-red-600 font-semibold mt-1 flex items-center gap-1.5","data-testid":`${r}-warning-breached`,children:[e.jsx(si,{className:"h-3.5 w-3.5"}),"URGENT - Deadline Passed"]})]})}function Dy({request:t,refreshing:s,onBack:a,onRefresh:r,onShareSummary:n,isInitiator:i}){var d,m,u;const o=Ay((t==null?void 0:t.priority)||"standard"),l=Ty((t==null?void 0:t.status)||"pending"),c=((d=t==null?void 0:t.pauseInfo)==null?void 0:d.isPaused)||!1;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(xs,{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(Ae,{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(ee,{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(ee,{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&&((m=t==null?void 0:t.status)==null?void 0:m.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(Sa,{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(Et,{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 border-b border-gray-200 ${c?"bg-gradient-to-r from-gray-100 to-gray-200":"bg-gradient-to-r from-blue-50 to-indigo-50"}`,"data-testid":"sla-section",children:e.jsx(Ry,{sla:((u=t.summary)==null?void 0:u.sla)||t.sla,requestStatus:t.status,isPaused:c,testId:"request-sla"})})]})}function et({...t}){return e.jsx(dp,{"data-slot":"dialog",...t})}function Py({...t}){return e.jsx(cp,{"data-slot":"dialog-portal",...t})}const tm=x.forwardRef(({className:t,...s},a)=>e.jsx(Qc,{ref:a,"data-slot":"dialog-overlay",className:ce("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}));tm.displayName=Qc.displayName;const Xe=x.forwardRef(({className:t,children:s,...a},r)=>e.jsxs(Py,{"data-slot":"dialog-portal",children:[e.jsx(tm,{}),e.jsxs(Jc,{ref:r,"data-slot":"dialog-content",className:ce("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(lp,{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(lt,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Xe.displayName=Jc.displayName;const tt=x.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,"data-slot":"dialog-header",className:ce("flex flex-col gap-2 text-center sm:text-left",t),...s}));tt.displayName="DialogHeader";const wt=x.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,"data-slot":"dialog-footer",className:ce("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s}));wt.displayName="DialogFooter";const Ze=x.forwardRef(({className:t,...s},a)=>e.jsx(ed,{ref:a,"data-slot":"dialog-title",className:ce("text-lg leading-none font-semibold",t),...s}));Ze.displayName=ed.displayName;const qt=x.forwardRef(({className:t,...s},a)=>e.jsx(td,{ref:a,"data-slot":"dialog-description",className:ce("text-muted-foreground text-sm",t),...s}));qt.displayName=td.displayName;function Gi({className:t,...s}){return e.jsx(mp,{"data-slot":"checkbox",className:ce("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(up,{"data-slot":"checkbox-indicator",className:"flex items-center justify-center text-current transition-none",children:e.jsx(Aa,{className:"size-3.5"})})})}async function sm(t){return(await de.get(`/summaries/${t}`)).data.data}async function Ey(t,s){return(await de.post(`/summaries/${t}/share`,{userIds:s})).data.data}async function My(t={}){var n,i;const{page:s=1,limit:a=20}=t,r=await de.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 am(t){await de.patch(`/summaries/shared/${t}/view`)}async function Iy(t){var s;try{return(await de.get(`/summaries/request/${t}`)).data.data}catch(a){return((s=a==null?void 0:a.response)==null?void 0:s.status)===404,null}}async function Fy(t){return(await de.get(`/summaries/${t}/recipients`)).data.data||[]}async function ys(t,s=10){return await de.get("/users/search",{params:{q:t,limit:s}})}async function ks(t){var a;const s=await de.post("/users/ensure",t);return((a=s.data)==null?void 0:a.data)||s.data}async function _y(t,s){return await de.post("/admin/users/assign-role",{email:t,role:s})}async function Ly(t,s){return await de.put(`/admin/users/${t}/role`,{role:s})}async function Oy(t,s=1,a=10){return await de.get("/admin/users/by-role",{params:{role:t||"ELEVATED",page:s,limit:a}})}async function $y(){return await de.get("/admin/users/role-statistics")}async function Uy(){var s,a;return((a=(s=(await de.get("/users")).data)==null?void 0:s.data)==null?void 0:a.users)||[]}const Gt={searchUsers:ys,ensureUserExists:ks,assignRole:_y,updateUserRole:Ly,getUsersByRole:Oy,getRoleStatistics:$y,getAllUsers:Uy};function By({isOpen:t,onClose:s,summaryId:a,requestTitle:r,onSuccess:n}){const[i,o]=x.useState(""),[l,c]=x.useState([]),[d,m]=x.useState(new Set),[u,h]=x.useState(!1),[p,g]=x.useState(!1);x.useEffect(()=>{if(!t){c([]);return}if(!i||!i.startsWith("@")||i.length<2){c([]),h(!1);return}const f=setTimeout(async()=>{var C;try{h(!0);const b=i.slice(1),N=await ys(b,10),R=((C=N==null?void 0:N.data)==null?void 0:C.data)||(N==null?void 0:N.data)||[];c(Array.isArray(R)?R:[])}catch(b){console.error("Failed to search users:",b),be.error("Failed to search users")}finally{h(!1)}},300);return()=>clearTimeout(f)},[i,t]);const y=f=>{m(C=>{const b=new Set(C);return b.has(f)?b.delete(f):b.add(f),b})},v=async()=>{var f,C;if(d.size===0){be.error("Please select at least one user to share with");return}try{g(!0),await Ey(a,Array.from(d)),be.success(`Summary shared with ${d.size} user(s)`),m(new Set),o(""),c([]),n==null||n(),s()}catch(b){console.error("Failed to share summary:",b),be.error(((C=(f=b==null?void 0:b.response)==null?void 0:f.data)==null?void 0:C.message)||"Failed to share summary")}finally{g(!1)}},w=()=>{m(new Set),o(""),c([]),s()};return e.jsx(et,{open:t,onOpenChange:w,children:e.jsxs(Xe,{className:"sm:max-w-[500px]",children:[e.jsx(tt,{children:e.jsx(Ze,{children:"Share Summary"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{children:[e.jsx(J,{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(J,{htmlFor:"user-search",className:"text-sm font-medium text-gray-700",children:"Search Users"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(Xt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(fe,{id:"user-search",placeholder:"Type @ to search users...",value:i,onChange:f=>o(f.target.value),className:"pl-10"})]}),i&&!i.startsWith("@")&&e.jsx("p",{className:"text-xs text-gray-500 mt-1 ml-1",children:"Start with @ to search users (e.g., @john)"})]}),u&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Ue,{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 C=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:b=>b.stopPropagation(),onMouseDown:b=>b.stopPropagation(),className:"flex items-center",children:e.jsx(Gi,{checked:C,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(it,{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&&i.startsWith("@")&&l.length===0&&e.jsx("div",{className:"text-center py-8 text-gray-500 text-sm",children:"No users found"}),!u&&i&&!i.startsWith("@")&&e.jsx("div",{className:"text-center py-8 text-gray-500 text-sm",children:"Start typing with @ to search users"}),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 C=l.find(b=>b.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:(C==null?void 0:C.displayName)||(C==null?void 0:C.email)||f}),e.jsx("button",{onClick:()=>y(f),className:"ml-1 hover:text-red-600",children:e.jsx(lt,{className:"h-3 w-3"})})]},f)})})]})]}),e.jsxs(wt,{children:[e.jsx(M,{variant:"outline",onClick:w,disabled:p,children:"Cancel"}),e.jsx(M,{onClick:v,disabled:p||d.size===0,children:p?e.jsxs(e.Fragment,{children:[e.jsx(Ue,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):`Share with ${d.size} user(s)`})]})]})})}const vr=[{name:"No Color",value:"transparent",class:"bg-gray-200 border-2 border-gray-400",icon:"×"},{name:"Yellow",value:"#FFEB3B",class:"bg-yellow-400"},{name:"Green",value:"#4CAF50",class:"bg-green-400"},{name:"Blue",value:"#2196F3",class:"bg-blue-400"},{name:"Red",value:"#F44336",class:"bg-red-400"},{name:"Orange",value:"#FF9800",class:"bg-orange-400"},{name:"Purple",value:"#9C27B0",class:"bg-purple-400"},{name:"Pink",value:"#E91E63",class:"bg-pink-400"},{name:"Cyan",value:"#00BCD4",class:"bg-cyan-400"},{name:"Teal",value:"#009688",class:"bg-teal-400"},{name:"Amber",value:"#FFC107",class:"bg-amber-400"},{name:"Indigo",value:"#3F51B5",class:"bg-indigo-400"}];function rm({value:t,onChange:s,placeholder:a="Enter text...",className:r,minHeight:n="120px",...i}){const o=x.useRef(null),[l,c]=x.useState(!1),[d,m]=x.useState(new Set),[u,h]=x.useState(!1),[p,g]=x.useState(null),[y,v]=x.useState("#FFEB3B"),[w,f]=x.useState(!1),[C,b]=x.useState(null),[N,R]=x.useState("#000000");x.useEffect(()=>{o.current&&o.current.innerHTML!==t&&o.current.innerHTML!==t&&(o.current.innerHTML=t||"")},[t]);const E=x.useCallback(S=>(S=S.replace(/<!--[\s\S]*?-->/g,""),S=S.replace(/<style[^>]*>[\s\S]*?<\/style>/gi,""),S=S.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,""),S=S.replace(/<meta[^>]*>/gi,""),S=S.replace(/\s*class="Mso[^"]*"/gi,""),S=S.replace(/\s*class="mso[^"]*"/gi,""),S=S.replace(/\s*style="[^"]*mso-[^"]*"/gi,""),S=S.replace(/\s*style="[^"]*font-family:[^"]*"/gi,""),S=S.replace(/\s*xmlns[^=]*="[^"]*"/gi,""),S=S.replace(/<\/?o:p[^>]*>/gi,""),S=S.replace(/<v:[^>]*>[\s\S]*?<\/v:[^>]*>/gi,""),S=S.replace(/<v:[^>]*\/>/gi,""),S=S.replace(/<p[^>]*>\s*<\/p>/gi,""),S=S.replace(/<div[^>]*>\s*<\/div>/gi,""),S=S.replace(/\s+/g," "),S=S.trim(),S),[]),P=x.useCallback(S=>{S.preventDefault();const T=S.clipboardData;let D=T.getData("text/html")||T.getData("text/plain");if((D.includes("<!--")||D.includes("<style")||D.includes("MsoNormal"))&&(D=E(D)),!o.current)return;const H=window.getSelection();if(!H||H.rangeCount===0)return;const z=H.getRangeAt(0);z.deleteContents();const Z=document.createElement("div");Z.innerHTML=D;const O=document.createDocumentFragment();Array.from(Z.childNodes).forEach(se=>{if(se.nodeType===Node.ELEMENT_NODE){const te=se;if(te.tagName==="UL"||te.tagName==="OL"){const $=te.cloneNode(!0);$.removeAttribute("style"),$.removeAttribute("class"),$.querySelectorAll("li").forEach(X=>{X.removeAttribute("style"),X.removeAttribute("class");const ne=X.textContent||"";ne.trim()&&(X.textContent=ne.trim())}),O.appendChild($)}else if(te.tagName==="TABLE"){const $=te.cloneNode(!0);$.removeAttribute("style"),$.removeAttribute("class"),$.querySelectorAll("td, th").forEach(ne=>{ne.removeAttribute("style"),ne.removeAttribute("class")});const X=document.createElement("div");X.className="table-wrapper",X.style.overflowX="auto",X.style.maxWidth="100%",X.style.margin="8px 0",X.appendChild($),O.appendChild(X)}else if(te.tagName==="P"||te.tagName==="DIV"){const $=document.createElement("p"),ne=te.innerHTML.replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<!--[\s\S]*?-->/g,"");$.innerHTML=ne,$.removeAttribute("style"),$.removeAttribute("class"),O.appendChild($)}else if(te.tagName==="BR")O.appendChild(te.cloneNode(!0));else{const $=te.textContent||"";if($.trim()){const X=document.createElement("p");X.textContent=$.trim(),O.appendChild(X)}}}else if(se.nodeType===Node.TEXT_NODE){const te=se.textContent||"";if(te.trim()){const $=document.createElement("p");$.textContent=te.trim(),O.appendChild($)}}}),O.childNodes.length===0&&T.getData("text/plain").split(`
|
||
`).forEach($=>{if($.trim()){const X=document.createElement("p");X.textContent=$.trim(),O.appendChild(X)}else O.appendChild(document.createElement("br"))}),z.insertNode(O),z.collapse(!1),H.removeAllRanges(),H.addRange(z),o.current&&s(o.current.innerHTML)},[s,E]),I=x.useCallback(()=>{if(!o.current||!l)return;const S=new Set,T=window.getSelection();if(T&&T.rangeCount>0){const H=T.getRangeAt(0).commonAncestorContainer;let z=null;for(H.nodeType===Node.TEXT_NODE?z=H.parentElement:z=H;z&&z!==o.current;){const Z=z.tagName.toLowerCase();(Z==="strong"||Z==="b")&&S.add("bold"),(Z==="em"||Z==="i")&&S.add("italic"),Z==="u"&&S.add("underline"),Z==="h1"&&S.add("h1"),Z==="h2"&&S.add("h2"),Z==="h3"&&S.add("h3"),Z==="ul"&&S.add("ul"),Z==="ol"&&S.add("ol");const O=window.getComputedStyle(z);O.textAlign==="center"&&S.add("center"),O.textAlign==="right"&&S.add("right"),O.textAlign==="left"&&S.add("left");const se=ne=>{if(ne.startsWith("#"))return ne.toUpperCase();const q=ne.match(/\d+/g);if(!q||q.length<3)return null;const Q=q[0],oe=q[1],W=q[2];if(!Q||!oe||!W)return null;const me=parseInt(Q).toString(16).padStart(2,"0"),we=parseInt(oe).toString(16).padStart(2,"0"),Ee=parseInt(W).toString(16).padStart(2,"0");return`#${me}${we}${Ee}`.toUpperCase()},te=O.backgroundColor;if(te&&te!=="rgba(0, 0, 0, 0)"&&te!=="transparent"&&te!=="rgb(255, 255, 255)"&&te!=="#ffffff"&&te!=="#FFFFFF"){S.add("highlight");const ne=se(te);if(ne){const q=vr.find(Q=>Q.value==="transparent"?!1:Q.value.toUpperCase()===ne);g(q?q.value:ne)}}else S.has("highlight")||g(null);const $=O.color,X=se($);if($&&X&&$!=="rgba(0, 0, 0, 0)"&&X!=="#000000"){S.add("textColor");const ne=vr.find(q=>q.value==="transparent"?!1:q.value.toUpperCase()===X);b(ne?ne.value:X)}else S.has("textColor")||b(X==="#000000"||!X?"#000000":null);z=z.parentElement}}m(S)},[l]),j=x.useCallback((S,T)=>{if(!o.current)return;l||o.current.focus();const D=window.getSelection();if(!D||D.rangeCount===0){o.current.focus();return}document.execCommand(S,!1,T),o.current&&s(o.current.innerHTML),setTimeout(I,10)},[l,s,I]),k=x.useCallback(S=>{if(!o.current)return;l||o.current.focus();const T=window.getSelection();if(!T||T.rangeCount===0){o.current.focus();return}let D=!1;if(T.rangeCount>0){const Z=T.getRangeAt(0).commonAncestorContainer;let O=null;for(Z.nodeType===Node.TEXT_NODE?O=Z.parentElement:O=Z;O&&O!==o.current;){const te=window.getComputedStyle(O).backgroundColor;if(te&&te!=="rgba(0, 0, 0, 0)"&&te!=="transparent"&&te!=="rgb(255, 255, 255)"&&te!=="#ffffff"&&te!=="#FFFFFF"){const X=(ne=>{if(ne.startsWith("#"))return ne.toUpperCase();const q=ne.match(/\d+/g);if(!q||q.length<3)return null;const Q=q[0],oe=q[1],W=q[2];if(!Q||!oe||!W)return null;const me=parseInt(Q).toString(16).padStart(2,"0"),we=parseInt(oe).toString(16).padStart(2,"0"),Ee=parseInt(W).toString(16).padStart(2,"0");return`#${me}${we}${Ee}`.toUpperCase()})(te);if(X&&X===S.toUpperCase()){D=!0;break}}O=O.parentElement}}if(S==="transparent"||D){const z=T.getRangeAt(0);if(z.collapsed)document.execCommand("removeFormat",!1);else{const Z=z.extractContents(),O=document.createDocumentFragment(),se=te=>{if(te.nodeType===Node.TEXT_NODE)return te.cloneNode(!0);if(te.nodeType===Node.ELEMENT_NODE){const $=te,X=document.createElement($.tagName.toLowerCase());return Array.from($.attributes).forEach(ne=>{ne.name!=="style"&&ne.name!=="class"&&X.setAttribute(ne.name,ne.value)}),Array.from($.childNodes).forEach(ne=>{const q=se(ne);q&&X.appendChild(q)}),$.style.backgroundColor&&(X.style.backgroundColor=""),X}return null};Array.from(Z.childNodes).forEach(te=>{const $=se(te);$&&O.appendChild($)}),z.insertNode(O),document.execCommand("removeFormat",!1)}g(null),v("#FFEB3B")}else if(T.rangeCount>0&&!T.getRangeAt(0).collapsed)document.execCommand("backColor",!1,S),g(S),S!=="transparent"&&/^#[0-9A-Fa-f]{6}$/i.test(S)&&v(S);else return;const H=window.getSelection();H&&H.removeAllRanges(),o.current&&s(o.current.innerHTML),h(!1),setTimeout(()=>{o.current&&o.current.focus(),I()},50)},[l,s,I]),_=x.useCallback(S=>{if(!o.current)return;l||o.current.focus();const T=window.getSelection();if(!T||T.rangeCount===0){o.current.focus();return}let D=!1;if(T.rangeCount>0){const z=T.getRangeAt(0).commonAncestorContainer;let Z=null;for(z.nodeType===Node.TEXT_NODE?Z=z.parentElement:Z=z;Z&&Z!==o.current;){const se=window.getComputedStyle(Z).color;if(se){const $=(X=>{if(X.startsWith("#"))return X.toUpperCase();const ne=X.match(/\d+/g);if(!ne||ne.length<3)return null;const q=ne[0],Q=ne[1],oe=ne[2];if(!q||!Q||!oe)return null;const W=parseInt(q).toString(16).padStart(2,"0"),me=parseInt(Q).toString(16).padStart(2,"0"),we=parseInt(oe).toString(16).padStart(2,"0");return`#${W}${me}${we}`.toUpperCase()})(se);if(S==="#000000"){if($==="#000000"||!$){D=!0;break}}else if($&&$===S.toUpperCase()){D=!0;break}}Z=Z.parentElement}}if(S==="transparent"||S==="default"||D){if(S==="#000000"&&D){f(!1);return}document.execCommand("removeFormat",!1),b(null),R("#000000")}else document.execCommand("foreColor",!1,S),b(S),S!=="transparent"&&/^#[0-9A-Fa-f]{6}$/i.test(S)&&R(S);o.current&&s(o.current.innerHTML),f(!1),setTimeout(I,10)},[l,s,I]),Y=x.useCallback(()=>{o.current&&s(o.current.innerHTML),I()},[s,I]),F=x.useCallback(S=>{if(S.ctrlKey&&S.key==="b"){S.preventDefault(),j("bold");return}if(S.ctrlKey&&S.key==="i"){S.preventDefault(),j("italic");return}if(S.ctrlKey&&S.key==="u"){S.preventDefault(),j("underline");return}},[j]),L=x.useCallback(()=>{c(!0)},[]),A=x.useCallback(()=>{c(!1),o.current&&s(o.current.innerHTML)},[s]);return x.useEffect(()=>{if(!l)return;const S=()=>{I()};return document.addEventListener("selectionchange",S),()=>{document.removeEventListener("selectionchange",S)}},[l,I]),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:ce("h-7 w-7 p-0",d.has("bold")&&"bg-blue-100 text-blue-700"),onClick:()=>j("bold"),title:"Bold (Ctrl+B)",children:e.jsx(Jp,{className:"h-4 w-4"})}),e.jsx(M,{type:"button",variant:"ghost",size:"sm",className:ce("h-7 w-7 p-0",d.has("italic")&&"bg-blue-100 text-blue-700"),onClick:()=>j("italic"),title:"Italic (Ctrl+I)",children:e.jsx(ex,{className:"h-4 w-4"})}),e.jsx(M,{type:"button",variant:"ghost",size:"sm",className:ce("h-7 w-7 p-0",d.has("underline")&&"bg-blue-100 text-blue-700"),onClick:()=>j("underline"),title:"Underline (Ctrl+U)",children:e.jsx(tx,{className:"h-4 w-4"})}),e.jsxs(cs,{open:u,onOpenChange:h,children:[e.jsx(ds,{asChild:!0,children:e.jsx(M,{type:"button",variant:"ghost",size:"sm",className:ce("h-7 w-7 p-0",d.has("highlight")&&"bg-blue-100 text-blue-700"),title:"Text Highlight",children:e.jsx(sx,{className:"h-4 w-4"})})}),e.jsx(ms,{className:"w-auto p-2",align:"start",onPointerDownOutside:S=>{S.target.closest("[data-popover-content]")&&S.preventDefault()},children:e.jsxs("div",{className:"space-y-2 relative",onClick:S=>S.stopPropagation(),children:[e.jsx(M,{type:"button",variant:"ghost",size:"sm",className:"absolute top-0 right-0 h-6 w-6 p-0 hover:bg-gray-100",onClick:S=>{S.stopPropagation(),h(!1)},title:"Close",children:e.jsx(lt,{className:"h-4 w-4 text-gray-500"})}),e.jsx("div",{className:"text-xs font-semibold text-gray-700 mb-2 pr-6",children:"Highlight Color"}),e.jsx("div",{className:"grid grid-cols-6 gap-1.5 pr-1 mb-2",children:vr.map(S=>{const T=p===S.value,D=S.value==="transparent";return e.jsxs("button",{type:"button",onClick:H=>{H.preventDefault(),H.stopPropagation(),k(T&&!D?"transparent":S.value)},className:ce("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md relative",S.class,T&&"ring-2 ring-blue-600 ring-offset-1 border-blue-600",D&&"border-gray-400 bg-white",!D&&!T&&"border-gray-300"),title:T&&!D?`${S.name} (Click to remove)`:S.name,style:D?{}:{backgroundColor:S.value},children:[D&&e.jsx("span",{className:"text-[10px] text-gray-600 font-bold",children:"×"}),T&&!D&&e.jsx("span",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("span",{className:"w-2 h-2 bg-white rounded-full shadow-sm"})})]},S.value)})}),p&&p!=="transparent"&&e.jsx("div",{className:"mb-2",children:e.jsx(M,{type:"button",variant:"outline",size:"sm",className:"w-full h-7 text-xs",onClick:S=>{S.stopPropagation(),k("transparent")},title:"Remove highlight color",children:"Remove Highlight"})}),e.jsxs("div",{className:"border-t border-gray-200 pt-2 mt-2",children:[e.jsx("div",{className:"text-xs font-semibold text-gray-700 mb-1.5",children:"Custom Color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:p&&p!=="transparent"?p:y,onChange:S=>{const T=S.target.value;v(T);const D=window.getSelection();D&&D.rangeCount>0&&!D.getRangeAt(0).collapsed&&k(T)},className:"w-8 h-8 rounded border border-gray-300 cursor-pointer",title:"Pick a custom color"}),e.jsx("input",{type:"text",value:p&&p!=="transparent"?p:y,onChange:S=>{S.stopPropagation();const T=S.target.value;v(T)},onKeyDown:S=>{if(S.stopPropagation(),S.key==="Enter"){S.preventDefault();const T=S.currentTarget.value.trim();/^#[0-9A-Fa-f]{6}$/i.test(T)&&k(T)}},onPaste:S=>{S.stopPropagation();const T=S.clipboardData.getData("text").trim();S.preventDefault(),setTimeout(()=>{if(/^#[0-9A-Fa-f]{6}$/i.test(T)){v(T);const D=window.getSelection();D&&D.rangeCount>0&&!D.getRangeAt(0).collapsed&&k(T)}else{const D=T.match(/^([0-9A-Fa-f]{6})$/);if(D){const H=`#${D[1]}`;v(H);const z=window.getSelection();z&&z.rangeCount>0&&!z.getRangeAt(0).collapsed&&k(H)}}},0)},onClick:S=>{S.stopPropagation()},onFocus:S=>{S.stopPropagation(),S.target.select()},onBlur:S=>{const T=S.target.value.trim();if(/^#[0-9A-Fa-f]{6}$/i.test(T)){const D=window.getSelection();D&&D.rangeCount>0&&!D.getRangeAt(0).collapsed&&k(T)}else v(T===""?p||"#FFEB3B":T)},placeholder:"#FFEB3B",className:"flex-1 h-7 px-2 text-xs border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500",title:"Enter hex color code (Press Enter or click Apply). Supports copy-paste.",autoComplete:"off",spellCheck:"false"}),e.jsx(M,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>{const S=y.trim();/^#[0-9A-Fa-f]{6}$/i.test(S)?k(S):v(p||"#FFEB3B")},title:"Apply custom color",children:"Apply"})]})]})]})})]}),e.jsxs(cs,{open:w,onOpenChange:f,children:[e.jsx(ds,{asChild:!0,children:e.jsx(M,{type:"button",variant:"ghost",size:"sm",className:ce("h-7 w-7 p-0",d.has("textColor")&&"bg-blue-100 text-blue-700"),title:"Text Color",children:e.jsx(ax,{className:"h-4 w-4"})})}),e.jsx(ms,{className:"w-auto p-2",align:"start",onPointerDownOutside:S=>{S.target.closest("[data-popover-content]")&&S.preventDefault()},children:e.jsxs("div",{className:"space-y-2 relative",onClick:S=>S.stopPropagation(),children:[e.jsx(M,{type:"button",variant:"ghost",size:"sm",className:"absolute top-0 right-0 h-6 w-6 p-0 hover:bg-gray-100",onClick:S=>{S.stopPropagation(),f(!1)},title:"Close",children:e.jsx(lt,{className:"h-4 w-4 text-gray-500"})}),e.jsx("div",{className:"text-xs font-semibold text-gray-700 mb-2 pr-6",children:"Text Color"}),e.jsxs("div",{className:"grid grid-cols-6 gap-1.5 pr-1 mb-2",children:[e.jsxs("button",{type:"button",onClick:S=>{S.preventDefault(),S.stopPropagation(),C==="#000000"||!C&&!d.has("textColor")||_("#000000")},className:ce("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md flex items-center justify-center bg-black",(C==="#000000"||!C&&!d.has("textColor"))&&"ring-2 ring-blue-600 ring-offset-1 border-blue-600",C!=="#000000"&&(C||d.has("textColor"))&&"border-gray-300"),title:"Default (Black)",children:[e.jsx("span",{className:"text-[10px] text-white font-bold",children:"A"}),(C==="#000000"||!C&&!d.has("textColor"))&&e.jsx("span",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("span",{className:"w-2 h-2 bg-white rounded-full shadow-sm"})})]}),vr.filter(S=>S.value!=="transparent").map(S=>{const T=C===S.value;return e.jsxs("button",{type:"button",onClick:D=>{D.preventDefault(),D.stopPropagation(),_(T?"#000000":S.value)},className:ce("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md flex items-center justify-center relative",T&&"ring-2 ring-blue-600 ring-offset-1 border-blue-600",!T&&"border-gray-300"),title:T?`${S.name} (Click to reset to default)`:S.name,style:{color:S.value,borderColor:T?"#2563eb":S.value},children:[e.jsx("span",{className:"text-xs font-bold",children:"A"}),T&&e.jsx("span",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("span",{className:"w-2 h-2 bg-white rounded-full shadow-sm"})})]},`text-${S.value}`)})]}),C&&C!=="#000000"&&e.jsx("div",{className:"mb-2",children:e.jsx(M,{type:"button",variant:"outline",size:"sm",className:"w-full h-7 text-xs",onClick:S=>{S.stopPropagation(),_("#000000")},title:"Reset to default black",children:"Reset to Default"})}),e.jsxs("div",{className:"border-t border-gray-200 pt-2 mt-2",children:[e.jsx("div",{className:"text-xs font-semibold text-gray-700 mb-1.5",children:"Custom Color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:C||N,onChange:S=>{const T=S.target.value;R(T),_(T)},className:"w-8 h-8 rounded border border-gray-300 cursor-pointer",title:"Pick a custom text color"}),e.jsx("input",{type:"text",value:C||N,onChange:S=>{const T=S.target.value;R(T)},onKeyDown:S=>{if(S.key==="Enter"){S.preventDefault();const T=S.currentTarget.value;/^#[0-9A-Fa-f]{6}$/.test(T)&&_(T)}},onBlur:S=>{const T=S.target.value;/^#[0-9A-Fa-f]{6}$/.test(T)?_(T):T===""&&R(C||"#000000")},placeholder:"#000000",className:"flex-1 h-7 px-2 text-xs border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500",title:"Enter hex color code (Press Enter or click Apply)"}),e.jsx(M,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>_(N),title:"Apply custom text color",children:"Apply"})]})]})]})})]})]}),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:ce("h-7 w-7 p-0",d.has("h1")&&"bg-blue-100 text-blue-700"),onClick:()=>j("formatBlock","<h1>"),title:"Heading 1",children:e.jsx(rx,{className:"h-4 w-4"})}),e.jsx(M,{type:"button",variant:"ghost",size:"sm",className:ce("h-7 w-7 p-0",d.has("h2")&&"bg-blue-100 text-blue-700"),onClick:()=>j("formatBlock","<h2>"),title:"Heading 2",children:e.jsx(nx,{className:"h-4 w-4"})}),e.jsx(M,{type:"button",variant:"ghost",size:"sm",className:ce("h-7 w-7 p-0",d.has("h3")&&"bg-blue-100 text-blue-700"),onClick:()=>j("formatBlock","<h3>"),title:"Heading 3",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:ce("h-7 w-7 p-0",d.has("ul")&&"bg-blue-100 text-blue-700"),onClick:()=>j("insertUnorderedList"),title:"Bullet List",children:e.jsx(hd,{className:"h-4 w-4"})}),e.jsx(M,{type:"button",variant:"ghost",size:"sm",className:ce("h-7 w-7 p-0",d.has("ol")&&"bg-blue-100 text-blue-700"),onClick:()=>j("insertOrderedList"),title:"Numbered List",children:e.jsx(ox,{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:ce("h-7 w-7 p-0",d.has("left")&&"bg-blue-100 text-blue-700"),onClick:()=>j("justifyLeft"),title:"Align Left",children:e.jsx(lx,{className:"h-4 w-4"})}),e.jsx(M,{type:"button",variant:"ghost",size:"sm",className:ce("h-7 w-7 p-0",d.has("center")&&"bg-blue-100 text-blue-700"),onClick:()=>j("justifyCenter"),title:"Align Center",children:e.jsx(cx,{className:"h-4 w-4"})}),e.jsx(M,{type:"button",variant:"ghost",size:"sm",className:ce("h-7 w-7 p-0",d.has("right")&&"bg-blue-100 text-blue-700"),onClick:()=>j("justifyRight"),title:"Align Right",children:e.jsx(dx,{className:"h-4 w-4"})})]})]}),e.jsx("div",{ref:o,contentEditable:!0,onPaste:P,onInput:Y,onFocus:L,onBlur:A,onKeyDown:F,onMouseUp:I,onKeyUp:I,"data-placeholder":a,className:ce("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","[&_span[style*='background']]:px-0.5 [&_span[style*='background']]:rounded","[&_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 Fs({content:t,className:s}){const a=x.useMemo(()=>{if(!t)return"";let r=t;const n=/<table[^>]*>[\s\S]*?<\/table>/gi;return r=r.replace(n,i=>i.includes("table-wrapper")?i:`<div class="table-wrapper" style="overflow-x: auto; max-width: 100%; margin: 8px 0;">${i}</div>`),r},[t]);return t?e.jsx("div",{className:ce("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 nm={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(zr,function(){var a=1e3,r=6e4,n=36e5,i="millisecond",o="second",l="minute",c="hour",d="day",m="week",u="month",h="quarter",p="year",g="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+)?$/,w=/\[([^\]]+)]|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(F){var L=["th","st","nd","rd"],A=F%100;return"["+F+(L[(A-20)%10]||L[A]||L[0])+"]"}},C=function(F,L,A){var S=String(F);return!S||S.length>=L?F:""+Array(L+1-S.length).join(A)+F},b={s:C,z:function(F){var L=-F.utcOffset(),A=Math.abs(L),S=Math.floor(A/60),T=A%60;return(L<=0?"+":"-")+C(S,2,"0")+":"+C(T,2,"0")},m:function F(L,A){if(L.date()<A.date())return-F(A,L);var S=12*(A.year()-L.year())+(A.month()-L.month()),T=L.clone().add(S,u),D=A-T<0,H=L.clone().add(S+(D?-1:1),u);return+(-(S+(A-T)/(D?T-H:H-T))||0)},a:function(F){return F<0?Math.ceil(F)||0:Math.floor(F)},p:function(F){return{M:u,y:p,w:m,d,D:g,h:c,m:l,s:o,ms:i,Q:h}[F]||String(F||"").toLowerCase().replace(/s$/,"")},u:function(F){return F===void 0}},N="en",R={};R[N]=f;var E="$isDayjsObject",P=function(F){return F instanceof _||!(!F||!F[E])},I=function F(L,A,S){var T;if(!L)return N;if(typeof L=="string"){var D=L.toLowerCase();R[D]&&(T=D),A&&(R[D]=A,T=D);var H=L.split("-");if(!T&&H.length>1)return F(H[0])}else{var z=L.name;R[z]=L,T=z}return!S&&T&&(N=T),T||!S&&N},j=function(F,L){if(P(F))return F.clone();var A=typeof L=="object"?L:{};return A.date=F,A.args=arguments,new _(A)},k=b;k.l=I,k.i=P,k.w=function(F,L){return j(F,{locale:L.$L,utc:L.$u,x:L.$x,$offset:L.$offset})};var _=function(){function F(A){this.$L=I(A.locale,null,!0),this.parse(A),this.$x=this.$x||A.x||{},this[E]=!0}var L=F.prototype;return L.parse=function(A){this.$d=function(S){var T=S.date,D=S.utc;if(T===null)return new Date(NaN);if(k.u(T))return new Date;if(T instanceof Date)return new Date(T);if(typeof T=="string"&&!/Z$/i.test(T)){var H=T.match(v);if(H){var z=H[2]-1||0,Z=(H[7]||"0").substring(0,3);return D?new Date(Date.UTC(H[1],z,H[3]||1,H[4]||0,H[5]||0,H[6]||0,Z)):new Date(H[1],z,H[3]||1,H[4]||0,H[5]||0,H[6]||0,Z)}}return new Date(T)}(A),this.init()},L.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()},L.$utils=function(){return k},L.isValid=function(){return this.$d.toString()!==y},L.isSame=function(A,S){var T=j(A);return this.startOf(S)<=T&&T<=this.endOf(S)},L.isAfter=function(A,S){return j(A)<this.startOf(S)},L.isBefore=function(A,S){return this.endOf(S)<j(A)},L.$g=function(A,S,T){return k.u(A)?this[S]:this.set(T,A)},L.unix=function(){return Math.floor(this.valueOf()/1e3)},L.valueOf=function(){return this.$d.getTime()},L.startOf=function(A,S){var T=this,D=!!k.u(S)||S,H=k.p(A),z=function(q,Q){var oe=k.w(T.$u?Date.UTC(T.$y,Q,q):new Date(T.$y,Q,q),T);return D?oe:oe.endOf(d)},Z=function(q,Q){return k.w(T.toDate()[q].apply(T.toDate("s"),(D?[0,0,0,0]:[23,59,59,999]).slice(Q)),T)},O=this.$W,se=this.$M,te=this.$D,$="set"+(this.$u?"UTC":"");switch(H){case p:return D?z(1,0):z(31,11);case u:return D?z(1,se):z(0,se+1);case m:var X=this.$locale().weekStart||0,ne=(O<X?O+7:O)-X;return z(D?te-ne:te+(6-ne),se);case d:case g:return Z($+"Hours",0);case c:return Z($+"Minutes",1);case l:return Z($+"Seconds",2);case o:return Z($+"Milliseconds",3);default:return this.clone()}},L.endOf=function(A){return this.startOf(A,!1)},L.$set=function(A,S){var T,D=k.p(A),H="set"+(this.$u?"UTC":""),z=(T={},T[d]=H+"Date",T[g]=H+"Date",T[u]=H+"Month",T[p]=H+"FullYear",T[c]=H+"Hours",T[l]=H+"Minutes",T[o]=H+"Seconds",T[i]=H+"Milliseconds",T)[D],Z=D===d?this.$D+(S-this.$W):S;if(D===u||D===p){var O=this.clone().set(g,1);O.$d[z](Z),O.init(),this.$d=O.set(g,Math.min(this.$D,O.daysInMonth())).$d}else z&&this.$d[z](Z);return this.init(),this},L.set=function(A,S){return this.clone().$set(A,S)},L.get=function(A){return this[k.p(A)]()},L.add=function(A,S){var T,D=this;A=Number(A);var H=k.p(S),z=function(se){var te=j(D);return k.w(te.date(te.date()+Math.round(se*A)),D)};if(H===u)return this.set(u,this.$M+A);if(H===p)return this.set(p,this.$y+A);if(H===d)return z(1);if(H===m)return z(7);var Z=(T={},T[l]=r,T[c]=n,T[o]=a,T)[H]||1,O=this.$d.getTime()+A*Z;return k.w(O,this)},L.subtract=function(A,S){return this.add(-1*A,S)},L.format=function(A){var S=this,T=this.$locale();if(!this.isValid())return T.invalidDate||y;var D=A||"YYYY-MM-DDTHH:mm:ssZ",H=k.z(this),z=this.$H,Z=this.$m,O=this.$M,se=T.weekdays,te=T.months,$=T.meridiem,X=function(Q,oe,W,me){return Q&&(Q[oe]||Q(S,D))||W[oe].slice(0,me)},ne=function(Q){return k.s(z%12||12,Q,"0")},q=$||function(Q,oe,W){var me=Q<12?"AM":"PM";return W?me.toLowerCase():me};return D.replace(w,function(Q,oe){return oe||function(W){switch(W){case"YY":return String(S.$y).slice(-2);case"YYYY":return k.s(S.$y,4,"0");case"M":return O+1;case"MM":return k.s(O+1,2,"0");case"MMM":return X(T.monthsShort,O,te,3);case"MMMM":return X(te,O);case"D":return S.$D;case"DD":return k.s(S.$D,2,"0");case"d":return String(S.$W);case"dd":return X(T.weekdaysMin,S.$W,se,2);case"ddd":return X(T.weekdaysShort,S.$W,se,3);case"dddd":return se[S.$W];case"H":return String(z);case"HH":return k.s(z,2,"0");case"h":return ne(1);case"hh":return ne(2);case"a":return q(z,Z,!0);case"A":return q(z,Z,!1);case"m":return String(Z);case"mm":return k.s(Z,2,"0");case"s":return String(S.$s);case"ss":return k.s(S.$s,2,"0");case"SSS":return k.s(S.$ms,3,"0");case"Z":return H}return null}(Q)||H.replace(":","")})},L.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},L.diff=function(A,S,T){var D,H=this,z=k.p(S),Z=j(A),O=(Z.utcOffset()-this.utcOffset())*r,se=this-Z,te=function(){return k.m(H,Z)};switch(z){case p:D=te()/12;break;case u:D=te();break;case h:D=te()/3;break;case m:D=(se-O)/6048e5;break;case d:D=(se-O)/864e5;break;case c:D=se/n;break;case l:D=se/r;break;case o:D=se/a;break;default:D=se}return T?D:k.a(D)},L.daysInMonth=function(){return this.endOf(u).$D},L.$locale=function(){return R[this.$L]},L.locale=function(A,S){if(!A)return this.$L;var T=this.clone(),D=I(A,S,!0);return D&&(T.$L=D),T},L.clone=function(){return k.w(this.$d,this)},L.toDate=function(){return new Date(this.valueOf())},L.toJSON=function(){return this.isValid()?this.toISOString():null},L.toISOString=function(){return this.$d.toISOString()},L.toString=function(){return this.$d.toUTCString()},F}(),Y=_.prototype;return j.prototype=Y,[["$ms",i],["$s",o],["$m",l],["$H",c],["$W",d],["$M",u],["$y",p],["$D",g]].forEach(function(F){Y[F[1]]=function(L){return this.$g(L,F[0],F[1])}}),j.extend=function(F,L){return F.$i||(F(L,_,j),F.$i=!0),j},j.locale=I,j.isDayjs=P,j.unix=function(F){return j(1e3*F)},j.en=R[N],j.Ls=R,j.p={},j})})(nm);var Vy=nm.exports;const st=Hr(Vy);var im={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(zr,function(){return function(a,r,n){a=a||{};var i=r.prototype,o={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function l(d,m,u,h){return i.fromToBase(d,m,u,h)}n.en.relativeTime=o,i.fromToBase=function(d,m,u,h,p){for(var g,y,v,w=u.$locale().relativeTime||o,f=a.thresholds||[{l:"s",r:44,d:"second"},{l:"m",r:89},{l:"mm",r:44,d:"minute"},{l:"h",r:89},{l:"hh",r:21,d:"hour"},{l:"d",r:35},{l:"dd",r:25,d:"day"},{l:"M",r:45},{l:"MM",r:10,d:"month"},{l:"y",r:17},{l:"yy",d:"year"}],C=f.length,b=0;b<C;b+=1){var N=f[b];N.d&&(g=h?n(d).diff(u,N.d,!0):u.diff(d,N.d,!0));var R=(a.rounding||Math.round)(Math.abs(g));if(v=g>0,R<=N.r||!N.r){R<=1&&b>0&&(N=f[b-1]);var E=w[N.l];p&&(R=p(""+R)),y=typeof E=="string"?E.replace("%d",R):E(R,m,N.l,v);break}}if(m)return y;var P=v?w.future:w.past;return typeof P=="function"?P(y):P.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)}}})})(im);var zy=im.exports;const Hy=Hr(zy);st.extend(Hy);function qy({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:p=!1,pausedByUserId:g,currentUserId:y}){var E,P,I,j,k,_,Y,F;const{user:v}=Mt(),w=t==null?void 0:t.pauseInfo,f=(w==null?void 0:w.isPaused)||!1,C=(E=w==null?void 0:w.pausedBy)==null?void 0:E.userId,b=(v==null?void 0:v.userId)||"",N=f&&u&&(p||s),R=f&&s&&C&&C!==b&&h;return e.jsxs("div",{className:"space-y-4 sm:space-y-6","data-testid":"overview-tab-content",children:[e.jsxs(K,{"data-testid":"initiator-card",children:[e.jsx(ae,{className:"pb-3 sm:pb-4",children:e.jsxs(re,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(it,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Initiator"]})}),e.jsx(G,{children:e.jsxs("div",{className:"flex items-start gap-3 sm:gap-4",children:[e.jsx(bt,{className:"h-10 w-10 sm:h-12 sm:w-12 ring-2 ring-white shadow-sm flex-shrink-0",children:e.jsx(jt,{className:"bg-gray-700 text-white font-semibold text-sm",children:((P=t.initiator)==null?void 0:P.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:((I=t.initiator)==null?void 0:I.name)||"N/A"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 truncate",children:((j=t.initiator)==null?void 0:j.role)||"N/A"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-500 truncate",children:((k=t.initiator)==null?void 0:k.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(Oi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:((_=t.initiator)==null?void 0:_.email)||"N/A"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs sm:text-sm text-gray-600",children:[e.jsx(yd,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{children:((Y=t.initiator)==null?void 0:Y.phone)||"N/A"})]})]})]})]})})]}),e.jsxs(K,{"data-testid":"request-details-card",children:[e.jsx(ae,{className:"pb-3 sm:pb-4",children:e.jsxs(re,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Ae,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Details"]})}),e.jsxs(G,{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(Fs,{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:Vt(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:Vt(t.updatedAt)})]})]})]})]}),f&&w&&e.jsxs(K,{className:"border-orange-300 bg-orange-50/50","data-testid":"pause-status-card",children:[e.jsx(ae,{className:"pb-3 sm:pb-4",children:e.jsxs(re,{className:"flex items-center gap-2 text-sm sm:text-base text-orange-800",children:[e.jsx(Os,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Workflow Paused"]})}),e.jsxs(G,{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:[w.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:w.pauseReason})]}),w.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:w.pausedBy.name||w.pausedBy.email})]}),w.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:[Vt(w.pauseResumeDate),st(w.pauseResumeDate).isAfter(st())&&e.jsxs("span",{className:"ml-2 text-xs text-gray-500",children:["(",st(w.pauseResumeDate).fromNow(),")"]})]})]}),w.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:Vt(w.pausedAt)})]})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-2 border-t border-orange-200",children:[N&&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(Ir,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-1.5"}),"Resume Now"]}),R&&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(Pe,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-1.5"}),"Request Resume"]})]})]})]}),t.claimDetails&&e.jsxs(K,{children:[e.jsx(ae,{className:"pb-4",children:e.jsxs(re,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ae,{className:"w-5 h-5 text-purple-600"}),"Claim Management Details"]})}),e.jsxs(G,{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?Qd(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(Fs,{content:t.claimDetails.requestDescription,className:"text-sm"})})]})]})]}),t.status==="closed"&&t.conclusionRemark&&e.jsxs(K,{children:[e.jsxs(ae,{className:"bg-gradient-to-r from-gray-50 to-slate-50 border-b border-gray-200",children:[e.jsxs(re,{className:"flex items-center gap-2 text-base",children:[e.jsx(je,{className:"w-5 h-5 text-gray-600"}),"Conclusion Remark"]}),e.jsx(ge,{className:"mt-1 text-xs sm:text-sm",children:"Final summary of this closed request"})]}),e.jsxs(G,{className:"pt-4",children:[e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-4",children:e.jsx(Fs,{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 ",Vt(t.closureDate)]}),e.jsxs("span",{children:["By ",((F=t.initiator)==null?void 0:F.name)||"Initiator"]})]})]})]}),a&&e.jsxs(K,{"data-testid":"conclusion-remark-card",children:[e.jsx(ae,{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(re,{className:`flex items-center gap-2 text-base sm:text-lg ${t.status==="rejected"?"text-red-700":"text-green-700"}`,children:[e.jsx(je,{className:`w-5 h-5 ${t.status==="rejected"?"text-red-600":"text-green-600"}`}),"Conclusion Remark - Final Step"]}),e.jsx(ge,{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(Et,{className:`w-3.5 h-3.5 ${i?"animate-spin":""}`}),l?"Regenerate":"Generate with AI"]})]})}),e.jsx(G,{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(Ue,{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(rm,{value:r,onChange:L=>n(L),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. Use highlight and text color tools in the toolbar for emphasis."}),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(Ue,{className:"w-4 h-4 mr-2 animate-spin"}),"Finalizing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(je,{className:"w-4 h-4 mr-2"}),"Finalize & Close Request"]})})})]})})]})]})}function Tr({delayDuration:t=0,...s}){return e.jsx(hp,{"data-slot":"tooltip-provider",delayDuration:t,...s})}function Sn({...t}){return e.jsx(Tr,{children:e.jsx(pp,{"data-slot":"tooltip",...t})})}function An({...t}){return e.jsx(xp,{"data-slot":"tooltip-trigger",...t})}function Tn({className:t,sideOffset:s=0,children:a,...r}){return e.jsx(gp,{children:e.jsxs(fp,{"data-slot":"tooltip-content",sideOffset:s,className:ce("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(yp,{className:"bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function bs({className:t,...s}){return e.jsx("textarea",{"data-slot":"textarea",className:ce("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 pl=t=>{if(t<8)return ot(t);const a=Math.floor(t/8),r=t%8;return r>0?`${a}d ${ot(r)}`:`${a}d`},Wy=(t,s)=>{if(s)return e.jsx(Pe,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"});switch(t){case"approved":return e.jsx(je,{className:"w-4 h-4 sm:w-5 sm:w-5 text-green-600"});case"rejected":return e.jsx(Je,{className:"w-4 h-4 sm:w-5 sm:h-5 text-red-600"});case"paused":return e.jsx(vd,{className:"w-4 h-4 sm:w-5 sm:h-5 text-yellow-600"});case"pending":case"in-review":return e.jsx(Ie,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"});case"waiting":return e.jsx(Ie,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400"});default:return e.jsx(Ie,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400"})}};function Ky({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}=Mt(),[m,u]=x.useState(!1),[h,p]=x.useState(""),[g,y]=x.useState(!1),v=(a==null?void 0:a.breachReason)||(t==null?void 0:t.breachReason)||"";x.useEffect(()=>{m||p("")},[m]);const w=t.status==="pending"||t.status==="in-review",f=t.status==="approved",C=t.status==="rejected",b=t.status==="waiting",N=t.status==="paused",R=Number(t.tatHours||0),E=t.actualHours??0,P=f&&E?Math.max(0,R-E):0,I=R>0?E/R*100:0,j=I>=100,k=(d==null?void 0:d.role)==="ADMIN",_=Zr(d),Y=t.approverId===(d==null?void 0:d.userId),F=k||_||Y,L=async()=>{var A,S;if(!h.trim()){be.error("Breach Reason Required",{description:"Please enter a reason for the breach."});return}y(!0);try{await U0(t.levelId,h.trim()),u(!1),p(""),be.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(T){console.error("Error updating breach reason:",T);const D=((S=(A=T==null?void 0:T.response)==null?void 0:A.data)==null?void 0:S.error)||(T==null?void 0:T.message)||"Failed to update breach reason. Please try again.";be.error("Failed to Update Breach Reason",{description:D,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":w?"border-blue-500 bg-blue-50 shadow-md":f?"border-green-500 bg-green-50":C?"border-red-500 bg-red-50":b?"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":N?"bg-yellow-100":w?"bg-blue-100":f?"bg-green-100":C?"bg-red-100":b?"bg-gray-200":"bg-gray-100"}`,children:Wy(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(ee,{variant:"outline",className:`text-xs shrink-0 capitalize ${t.isSkipped?"bg-orange-100 text-orange-800 border-orange-200":w?"bg-yellow-100 text-yellow-800 border-yellow-200":f?"bg-green-100 text-green-800 border-green-200":C?"bg-red-100 text-red-800 border-red-200":b?"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(Tr,{delayDuration:200,children:e.jsxs(Sn,{children:[e.jsx(An,{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(Pe,{className:"w-4 h-4 text-orange-600"})})}),e.jsxs(Tn,{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(Yo,{className:"w-3 h-3"}),"Skip Reason:"]}),e.jsx("p",{className:"text-xs text-gray-700",children:t.skipReason})]})]})}),f&&E&&e.jsx(ee,{className:"bg-green-600 text-white text-xs","data-testid":`${c}-completion-time`,children:pl(E)})]}),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&&E!==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?Vt(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:pl(E)})]}),e.jsx("div",{className:"space-y-2",children:(()=>{const A=Math.min(100,I),S=()=>j?"bg-red-600":I>=75?"bg-orange-500":I>=50?"bg-amber-500":"bg-green-600",T=()=>j?"text-red-600":I>=75?"text-orange-600":I>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(gs,{value:A,className:"h-2 bg-gray-200",indicatorClassName:S(),"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 ${T()}`,children:[Math.round(A),"% of TAT used"]}),j&&F&&e.jsx(Tr,{children:e.jsxs(Sn,{children:[e.jsx(An,{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:()=>{p(v),u(!0)},children:e.jsx(fr,{className:"w-3 h-3"})})}),e.jsx(Tn,{children:e.jsx("p",{children:v?"Edit breach reason":"Add breach reason"})})]})})]}),P>0&&e.jsxs("span",{className:"text-green-600 font-semibold",children:["Saved ",ot(P)]})]})]})})()}),j&&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(fr,{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(vs,{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&&(w||N)&&(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?fs(a.sla.deadline,!0):"Not set"})]}),e.jsxs("div",{className:`border rounded-lg p-3 ${N?"bg-gray-100 border-gray-300":(a.sla.percentageUsed||0)>=100?"bg-red-50 border-red-200":(a.sla.percentageUsed||0)>=75?"bg-orange-50 border-orange-200":(a.sla.percentageUsed||0)>=50?"bg-amber-50 border-amber-200":"bg-green-50 border-green-200"}`,children:[e.jsxs("p",{className:"text-xs font-semibold text-gray-900 mb-3 flex items-center gap-2",children:[e.jsx(Ie,{className:"w-4 h-4"}),"Current Approver - Time Tracking ",N&&"(Paused)"]}),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," / ",ot(R)," allocated"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[(()=>{const A=a.sla.percentageUsed||0,S=()=>N?"bg-gray-500":A>=100?"bg-red-600":A>=75?"bg-orange-500":A>=50?"bg-amber-500":"bg-green-600",T=()=>N?"text-gray-600":A>=100?"text-red-600":A>=75?"text-orange-600":A>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(gs,{value:a.sla.percentageUsed,className:"h-3",indicatorClassName:S(),"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 ${T()}`,children:["Progress: ",Math.min(100,a.sla.percentageUsed),"% of TAT used"]}),a.sla.status==="breached"&&F&&e.jsx(Tr,{children:e.jsxs(Sn,{children:[e.jsx(An,{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:()=>{p(v),u(!0)},children:e.jsx(fr,{className:"w-3 h-3"})})}),e.jsx(Tn,{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(si,{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(fr,{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"]})]})]})]}),b&&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(vd,{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"]})]})}),C&&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(Je,{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(Yo,{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 ",Vt(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,S)=>{var T,D,H,z,Z,O;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-${S}`,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(mx,{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(si,{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 ",S+1," - ",A.thresholdPercentage||0,"% TAT"]}),e.jsx(ee,{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:ot(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:[ot(Number(A.tatHoursElapsed||0)),((T=A.metadata)==null?void 0:T.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:[ot(Number(A.tatHoursRemaining||0)),((D=A.metadata)==null?void 0:D.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?fs(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"}),(((H=A.metadata)==null?void 0:H.testMode)||((z=A.metadata)==null?void 0:z.tatTestMode))&&e.jsx(ee,{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?Vt(A.alertSentAt):"N/A"]}),(((Z=A.metadata)==null?void 0:Z.testMode)||((O=A.metadata)==null?void 0:O.tatTestMode))&&e.jsx("p",{className:"text-[10px] text-purple-600 mt-1 italic",children:"Note: Test mode active (1 hour = 1 minute)"})]})]})]})},S)})}),t.timestamp&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:[f?"Approved":C?"Rejected":"Actioned"," on ",Vt(t.timestamp)]}),n&&!N&&(w||t.status==="pending")&&!f&&!C&&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(Pe,{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:N?"Skip this approver to resume the workflow and move to next level":"Skip if approver is unavailable and move to next level"})]})]})]}),e.jsx(et,{open:m,onOpenChange:u,children:e.jsxs(Xe,{className:"sm:max-w-[500px]",children:[e.jsxs(tt,{children:[e.jsx(Ze,{children:v?"Edit Breach Reason":"Add Breach Reason"}),e.jsx(qt,{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(bs,{placeholder:"Enter the reason for the breach...",value:h,onChange:A=>p(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(wt,{children:[e.jsx(M,{variant:"outline",onClick:()=>{u(!1),p("")},disabled:g,children:"Cancel"}),e.jsx(M,{onClick:L,disabled:!h.trim()||g,className:"bg-red-600 hover:bg-red-700",children:g?"Saving...":"Save Reason"})]})]})})]})}function Gy({request:t,user:s,isInitiator:a,onSkipApprover:r,onRefresh:n}){return e.jsxs(K,{children:[e.jsx(ae,{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(re,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Vs,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Approval Workflow"]}),e.jsx(ge,{className:"mt-1 sm:mt-2 text-xs sm:text-sm",children:"Track the approval progress through each step"})]}),t.totalSteps&&(()=>{var p;const i=t.totalSteps||1,o=t.currentStepRaw!==void 0?t.currentStepRaw:t.currentStep||1,l=((p=t.approvalFlow)==null?void 0:p.filter(g=>{const y=(g.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(ee,{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(ee,{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(ee,{variant:"outline",className:"font-medium text-xs sm:text-sm shrink-0",children:["Step ",h," of ",i," - ",l," completed"]})})()]})}),e.jsx(G,{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 p,g,y;const l=(p=t.approvals)==null?void 0:p.find(v=>v.levelId===i.levelId),c=(g=s==null?void 0:s.email)==null?void 0:g.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(Ky,{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 Yy=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 xl({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(Ae,{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 ",Vt(t.uploadedAt)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&Yy(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(kt,{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 Xy({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(K,{children:[e.jsx(ae,{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(re,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Ae,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Documents"]}),e.jsx(ge,{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(Na,{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(G,{children:t.documents&&t.documents.length>0?e.jsx("div",{className:"space-y-3",children:t.documents.map((l,c)=>e.jsx(xl,{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(K,{children:[e.jsxs(ae,{children:[e.jsxs(re,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(vs,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"Work Note Attachments"]}),e.jsx(ge,{className:"text-xs sm:text-sm",children:"Files shared in work notes discussions"})]}),e.jsx(G,{children:s&&s.length>0?e.jsx("div",{className:"space-y-3",children:s.map((l,c)=>e.jsx(xl,{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 Zy({request:t}){return e.jsxs(K,{children:[e.jsxs(ae,{children:[e.jsxs(re,{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(ge,{className:"text-xs sm:text-sm",children:"Complete audit trail of all request activities"})]}),e.jsx(G,{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:ky(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:Vt(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 Yi({fileName:t,fileType:s,fileUrl:a,fileSize:r,attachmentId:n,onDownload:i,open:o,onClose:l}){const[c,d]=x.useState(100),[m,u]=x.useState(0),[h,p]=x.useState(null),[g,y]=x.useState(!1),[v,w]=x.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"),C=s.toLowerCase().includes("pdf"),b=f||C;x.useEffect(()=>{if(!o||!b||!a){p(null);return}return(async()=>{y(!0),w(null);try{let _=a;a.startsWith("/")&&!a.startsWith("//")&&(_=`${window.location.origin}${a}`);const F=await fetch(_,{headers:{Accept:C?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!F.ok){const S=await F.text().catch(()=>"");throw new Error(`Failed to load file: ${F.status} ${F.statusText}. ${S}`)}const L=await F.blob();if(L.size===0)throw new Error("File is empty or could not be loaded");C&&!L.type.includes("pdf")&&L.type!=="application/octet-stream"&&console.warn(`Expected PDF but got ${L.type}`);const A=window.URL.createObjectURL(L);p(A)}catch(j){console.error("Failed to load file for preview:",j),w(j instanceof Error?j.message:"Failed to load file for preview")}finally{y(!1)}})(),()=>{h&&(window.URL.revokeObjectURL(h),p(null))}},[o,a,b,C]);const N=async()=>{if(i&&n)try{await i(n)}catch{alert("Failed to download file")}},R=()=>d(I=>Math.min(I+25,200)),E=()=>d(I=>Math.max(I-25,50)),P=()=>u(I=>(I+90)%360);return e.jsx(et,{open:o,onOpenChange:l,children:e.jsx(Xe,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(tt,{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(kt,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(Ze,{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:E,disabled:c<=50,title:"Zoom out",className:"h-8 w-8 p-0",children:e.jsx(ux,{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(hx,{className:"h-4 w-4"})}),e.jsx(M,{variant:"ghost",size:"sm",onClick:P,title:"Rotate",className:"h-8 w-8 p-0",children:e.jsx(px,{className:"h-4 w-4"})})]}),i&&n&&e.jsxs(M,{variant:"outline",size:"sm",onClick:N,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:g?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full",children:[e.jsx(Ue,{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(lt,{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:N,className:"gap-2",children:[e.jsx(ns,{className:"h-4 w-4"}),"Download ",t]})]}):b&&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"})}),C&&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:()=>{w("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(kt,{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:N,className:"gap-2",children:[e.jsx(ns,{className:"h-4 w-4"}),"Download ",t]})]})})]})})})}function om({open:t,onClose:s,success:a,title:r,message:n}){return e.jsx(et,{open:t,onOpenChange:s,children:e.jsxs(Xe,{className:"sm:max-w-md",children:[e.jsx(tt,{children:e.jsxs(Ze,{className:"flex items-center gap-2",children:[a?e.jsx(je,{className:"w-5 h-5 text-green-600"}):e.jsx(Pe,{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(je,{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(Je,{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(wt,{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 lm({open:t,onClose:s,violations:a,policyDetails:r}){return e.jsx(et,{open:t,onOpenChange:s,children:e.jsxs(Xe,{className:"sm:max-w-lg",children:[e.jsxs(tt,{children:[e.jsxs(Ze,{className:"flex items-center gap-2",children:[e.jsx(Pe,{className:"w-5 h-5 text-red-600"}),"Policy Violation"]}),e.jsx(qt,{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(wt,{children:e.jsx(M,{onClick:s,className:"w-full sm:w-auto",children:"OK"})})]})})}function cm({open:t,onClose:s,onConfirm:a,existingParticipants:r=[]}){const[n,i]=x.useState(""),[o,l]=x.useState(!1),[c,d]=x.useState([]),[m,u]=x.useState(!1),[h,p]=x.useState(null),g=x.useRef(null),y=x.useRef(null),[v,w]=x.useState({open:!1,type:"error",email:"",message:""}),[f,C]=x.useState({open:!1,violations:[]}),[b,N]=x.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20});x.useEffect(()=>{t&&(async()=>{var k;try{const _=await ia("WORKFLOW_SHARING"),Y=await ia("TAT_SETTINGS"),F=[..._,...Y],L={};F.forEach(A=>{L[A.configKey]=A.configValue}),N({maxApprovalLevels:parseInt(L.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(L.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((k=L.ALLOW_ADD_SPECTATOR)==null?void 0:k.toLowerCase())==="true",maxSpectators:parseInt(L.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(_){console.error("Failed to load system policy:",_)}})()},[t]);const R=async()=>{var S,T;const j=n.trim().toLowerCase();if(!j){w({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(j)){w({open:!0,type:"error",email:j,message:"Please enter a valid email address"});return}const _=r.find(D=>(D.email||"").toLowerCase()===j);if(_){const D=((S=_.participantType)==null?void 0:S.toUpperCase())||"PARTICIPANT",H=_.name||j;if(D==="INITIATOR"){w({open:!0,type:"error",email:j,message:`${H} is the request initiator and cannot be added as a spectator.`});return}else if(D==="APPROVER"){w({open:!0,type:"error",email:j,message:`${H} is already an approver on this request and cannot be added as a spectator.`});return}else if(D==="SPECTATOR"){w({open:!0,type:"error",email:j,message:`${H} is already a spectator on this request.`});return}else{w({open:!0,type:"error",email:j,message:`${H} is already a participant on this request.`});return}}const Y=[];b.allowSpectators||Y.push({type:"Spectators Not Allowed",message:"Adding spectators is not allowed by system policy."});const L=r.filter(D=>(D.participantType||"").toUpperCase()==="SPECTATOR").length;L>=b.maxSpectators&&Y.push({type:"Maximum Spectators Exceeded",message:"This request has reached the maximum number of spectators allowed.",currentValue:L,maxValue:b.maxSpectators});const A=r.length+1;if(A>b.maxParticipants&&Y.push({type:"Maximum Participants Exceeded",message:"Adding this spectator would exceed the maximum participants limit.",currentValue:A,maxValue:b.maxParticipants}),Y.length>0){C({open:!0,violations:Y});return}if(!h||h.email.toLowerCase()!==j)try{const H=((T=(await ys(j,1)).data)==null?void 0:T.data)||[];if(H.length===0){w({open:!0,type:"not-found",email:j,message:""});return}const z=H[0];await ks({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(D){console.error("Failed to validate spectator:",D),w({open:!0,type:"error",email:j,message:"Failed to validate user. Please try again."});return}try{l(!0),await a(j),i(""),p(null),s()}catch(D){console.error("Failed to add spectator:",D)}finally{l(!1)}},E=()=>{o||(i(""),p(null),d([]),u(!1),s())};x.useEffect(()=>{c.length>0&&y.current&&y.current.scrollTo({top:y.current.scrollHeight,behavior:"smooth"})},[c.length]),x.useEffect(()=>()=>{g.current&&clearTimeout(g.current)},[]);const P=j=>{if(i(j),h&&h.email.toLowerCase()!==j.toLowerCase()&&p(null),g.current&&clearTimeout(g.current),!j||!j.startsWith("@")||j.length<2){d([]),u(!1);return}u(!0),g.current=setTimeout(async()=>{var k;try{const _=j.slice(1),F=((k=(await ys(_,10)).data)==null?void 0:k.data)||[];d(F)}catch(_){console.error("Search failed:",_),d([])}finally{u(!1)}},300)},I=async j=>{try{await ks({userId:j.userId,email:j.email,displayName:j.displayName,firstName:j.firstName,lastName:j.lastName,department:j.department,phone:j.phone,mobilePhone:j.mobilePhone,designation:j.designation,jobTitle:j.jobTitle,manager:j.manager,employeeId:j.employeeId,employeeNumber:j.employeeNumber,secondEmail:j.secondEmail,location:j.location}),i(j.email),p(j),d([]),u(!1)}catch(k){console.error("Failed to ensure user exists:",k),w({open:!0,type:"error",email:j.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(et,{open:t,onOpenChange:E,children:[e.jsxs(Xe,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:E,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(lt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(tt,{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(kt,{className:"w-5 h-5 text-purple-600"})}),e.jsx(Ze,{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($i,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(fe,{type:"text",placeholder:"@username or user@example.com",value:n,onChange:j=>P(j.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(j=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>I(j),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(bt,{className:"h-8 w-8",children:e.jsx(jt,{className:"bg-purple-100 text-purple-800 text-xs font-semibold",children:(j.displayName||j.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:j.displayName||[j.firstName,j.lastName].filter(Boolean).join(" ")||j.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:j.email}),j.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:j.designation})]})]})},j.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:E,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(kt,{className:"w-4 h-4 mr-2"}),o?"Adding...":"Add Spectator"]})]})]}),e.jsx(et,{open:v.open,onOpenChange:j=>w(k=>({...k,open:j})),children:e.jsxs(Xe,{className:"sm:max-w-md",children:[e.jsxs(tt,{children:[e.jsx(Ze,{className:"flex items-center gap-2",children:v.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(Pe,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Pe,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(qt,{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(Kr,{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(wt,{children:e.jsx(M,{onClick:()=>w(j=>({...j,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(lm,{open:f.open,onClose:()=>C({open:!1,violations:[]}),violations:f.violations,policyDetails:{maxApprovalLevels:b.maxApprovalLevels,maxParticipants:b.maxParticipants,allowSpectators:b.allowSpectators,maxSpectators:b.maxSpectators}})]})}function dm({open:t,onClose:s,onConfirm:a,existingParticipants:r=[],currentLevels:n=[]}){const[i,o]=x.useState(""),[l,c]=x.useState(24),[d,m]=x.useState(null),[u,h]=x.useState(!1),[p,g]=x.useState([]),[y,v]=x.useState(!1),[w,f]=x.useState(null),C=x.useRef(null),b=x.useRef(null),[N,R]=x.useState({open:!1,type:"error",email:"",message:""}),E=n.filter(A=>A&&(A.status==="approved"||A.status==="rejected"||A.status==="skipped")),P=Math.max(1,E.length+1),I=Math.max(1,n.length+1),j=I>=P?Array.from({length:I-P+1},(A,S)=>P+S):[P];x.useEffect(()=>{j.length>0&&d===null&&m(j[0]||null)},[j.length,d]);const k=async()=>{var D,H;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<P){R({open:!0,type:"error",email:"",message:`Cannot add approver at level ${d}. Minimum allowed level is ${P} (after completed levels)`});return}const T=r.find(z=>(z.email||"").toLowerCase()===A);if(T){const z=((D=T.participantType)==null?void 0:D.toUpperCase())||"PARTICIPANT",Z=T.name||A;if(z==="INITIATOR"){R({open:!0,type:"error",email:A,message:`${Z} is the request initiator and cannot be added as an approver.`});return}else if(z==="APPROVER"){R({open:!0,type:"error",email:A,message:`${Z} is already an approver on this request.`});return}else if(z==="SPECTATOR"){R({open:!0,type:"error",email:A,message:`${Z} 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:`${Z} is already a participant on this request.`});return}}if(!w||w.email.toLowerCase()!==A)try{const Z=((H=(await ys(A,1)).data)==null?void 0:H.data)||[];if(Z.length===0){R({open:!0,type:"not-found",email:A,message:""});return}const O=Z[0];await ks({userId:O.userId,email:O.email,displayName:O.displayName,firstName:O.firstName,lastName:O.lastName,department:O.department,phone:O.phone,mobilePhone:O.mobilePhone,designation:O.designation,jobTitle:O.jobTitle,manager:O.manager,employeeId:O.employeeId,employeeNumber:O.employeeNumber,secondEmail:O.secondEmail,location:O.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)}},_=()=>{u||(o(""),c(24),m(null),f(null),g([]),v(!1),s())},Y=A=>{const S=A.toLowerCase();return S==="approved"?e.jsx(je,{className:"w-4 h-4 text-green-600"}):S==="rejected"?e.jsx(Je,{className:"w-4 h-4 text-red-600"}):S==="skipped"?e.jsx(Pe,{className:"w-4 h-4 text-orange-600"}):S==="in-review"||S==="pending"?e.jsx(Ie,{className:"w-4 h-4 text-blue-600"}):e.jsx(Ie,{className:"w-4 h-4 text-gray-400"})};x.useEffect(()=>{p.length>0&&b.current&&b.current.scrollTo({top:b.current.scrollHeight,behavior:"smooth"})},[p.length]),x.useEffect(()=>()=>{C.current&&clearTimeout(C.current)},[]);const F=A=>{if(o(A),w&&w.email.toLowerCase()!==A.toLowerCase()&&f(null),C.current&&clearTimeout(C.current),!A||!A.startsWith("@")||A.length<2){g([]),v(!1);return}v(!0),C.current=setTimeout(async()=>{var S;try{const T=A.slice(1),H=((S=(await ys(T,10)).data)==null?void 0:S.data)||[];g(H)}catch(T){console.error("Search failed:",T),g([])}finally{v(!1)}},300)},L=async A=>{try{await ks({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),g([]),v(!1)}catch(S){console.error("Failed to ensure user exists:",S),R({open:!0,type:"error",email:A.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(et,{open:t,onOpenChange:_,children:[e.jsxs(Xe,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:_,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(lt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(tt,{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(nt,{className:"w-5 h-5 text-blue-600"})}),e.jsx(Ze,{className:"text-xl font-bold text-gray-900",children:"Add Approver"})]})}),e.jsxs("div",{ref:b,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(J,{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:[Y(A.status),e.jsx(ee,{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 ",P," or higher (after completed levels)"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{className:"text-sm font-medium text-gray-700",children:"Approval Level *"}),e.jsxs(Te,{value:(d==null?void 0:d.toString())||"",onValueChange:A=>m(Number(A)),disabled:u,children:[e.jsx(Re,{className:"h-11 border-gray-300",children:e.jsx(ke,{placeholder:"Select level"})}),e.jsx(De,{children:j.map(A=>e.jsx(U,{value:A.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(It,{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(J,{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(fe,{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(Ie,{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($i,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(fe,{type:"text",placeholder:"@username or user@example.com",value:i,onChange:A=>F(A.target.value),className:"pl-10 h-11 border-gray-300",disabled:u,autoFocus:!0}),(y||p.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..."}):p.length>0?e.jsx("ul",{className:"divide-y",children:p.map(A=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>L(A),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(bt,{className:"h-8 w-8",children:e.jsx(jt,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:(A.displayName||A.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: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:_,className:"flex-1 h-11 border-gray-300",disabled:u,children:"Cancel"}),e.jsxs(M,{type:"button",onClick:k,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:u||!i.trim()||!d||!l,children:[e.jsx(nt,{className:"w-4 h-4 mr-2"}),u?"Adding...":`Add at Level ${d||"?"}`]})]})]}),e.jsx(et,{open:N.open,onOpenChange:A=>R(S=>({...S,open:A})),children:e.jsxs(Xe,{className:"sm:max-w-md",children:[e.jsxs(tt,{children:[e.jsx(Ze,{className:"flex items-center gap-2",children:N.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(Pe,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Pe,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(qt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[N.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:N.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(Kr,{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."]})})]}),N.type==="error"&&e.jsxs(e.Fragment,{children:[N.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:N.email}),"."]}),N.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:N.message})})]})]})})]}),e.jsx(wt,{children:e.jsx(M,{onClick:()=>R(A=>({...A,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const Qy=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"}},ev=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)?'<span class="inline-flex items-center px-2.5 py-0.5 rounded-md bg-blue-50 text-blue-800 font-black text-base border-2 border-blue-400 shadow-sm">@'+a+"</span>":s}).replace(/\n/g,"<br />"),tv=t=>t<1024?t+" B":t<1024*1024?(t/1024).toFixed(1)+" KB":(t/(1024*1024)).toFixed(1)+" MB",gl=({type:t})=>{const s="w-4 h-4",a=t.toLowerCase();return a.includes("pdf")?e.jsx(Ae,{className:`${s} text-red-600`}):a.includes("excel")||a.includes("spreadsheet")||a.includes("xlsx")?e.jsx(yx,{className:`${s} text-green-600`}):a.includes("powerpoint")||a.includes("presentation")||a.includes("pptx")?e.jsx(Ae,{className:`${s} text-orange-600`}):a.includes("word")||a.includes("document")||a.includes("docx")?e.jsx(Ae,{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(vx,{className:`${s} text-purple-600`}):e.jsx(qr,{className:`${s} text-gray-600`})};function mm({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=rr(),u=t||m.requestId||"",[h,p]=x.useState(""),[g,y]=x.useState(""),[v,w]=x.useState(!1),[f,C]=x.useState([]),[b,N]=x.useState(!1),[R,E]=x.useState([]),[P,I]=x.useState(null),[j,k]=x.useState(null),[_,Y]=x.useState(!1),[F,L]=x.useState(!1),[A,S]=x.useState(!1),[T,D]=x.useState({success:!0,title:"",message:""}),H=x.useRef(null),z=x.useRef(null),Z=x.useRef(null),O=x.useRef(!1),[se,te]=x.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[$,X]=x.useState({open:!1,errors:[]}),ne=x.useMemo(()=>({id:u,title:n||"Request Details"}),[u,n]),[q,Q]=x.useState([]),oe=q.filter(V=>V.status==="online"),W=f.filter(V=>V.content.toLowerCase().includes(g.toLowerCase())||V.user.name.toLowerCase().includes(g.toLowerCase())),me=x.useMemo(()=>l!==void 0?l:!P||q.length===0?!1:q.some(V=>{const ie=V.userId||V.user_id,B=(V.role||"").toString().toUpperCase(),he=(V.participantType||V.participant_type||"").toString().toUpperCase();return ie===P&&(B==="SPECTATOR"||he==="SPECTATOR")}),[l,P,q]);x.useEffect(()=>{},[q]),x.useEffect(()=>{!u||!P||s||(async()=>{try{const V=await ba(u),ie=Array.isArray(V)?V.map(B=>{const he=B.userId||B.user_id;return{id:B.noteId||B.id||String(Math.random()),user:{name:B.userName||"User",avatar:(B.userName||"U").slice(0,2).toUpperCase(),role:B.userRole||"Participant"},content:B.message||"",timestamp:B.createdAt||new Date().toISOString(),isCurrentUser:he===P,attachments:Array.isArray(B.attachments)?B.attachments.map(ue=>({attachmentId:ue.attachmentId||ue.attachment_id,name:ue.fileName||ue.file_name||ue.name,fileName:ue.fileName||ue.file_name||ue.name,url:ue.storageUrl||ue.storage_url||ue.url||"#",type:ue.fileType||ue.file_type||ue.type||"file",fileType:ue.fileType||ue.file_type||ue.type||"file",fileSize:ue.fileSize||ue.file_size})):void 0}}):[];C(ie)}catch(V){console.error("[WorkNoteChat] Failed to load messages:",V)}})()},[u,P,s]);const we=x.useMemo(()=>{const V=[];return f.forEach(ie=>{ie.attachments&&ie.attachments.length>0&&ie.attachments.forEach(B=>{V.push({attachmentId:B.attachmentId||B.attachment_id,name:B.fileName||B.file_name||B.name||"Untitled",fileName:B.fileName||B.file_name||B.name||"Untitled",size:B.fileSize||B.file_size,type:B.fileType||B.file_type||B.type||"file",uploadedBy:ie.user.name,uploadedAt:ie.timestamp,url:B.storageUrl||B.storage_url||B.url||"#"})})}),V},[f]);x.useEffect(()=>{i&&we.length>=0&&i(we)},[we,i]);const Ee=x.useMemo(()=>q.map(V=>({email:(V.email||"").toLowerCase(),participantType:V.role==="Initiator"?"INITIATOR":V.role==="Approver"?"APPROVER":V.role==="Spectator"?"SPECTATOR":"PARTICIPANT",name:V.name})),[q]),Fe=V=>{if(!V)return"Participant";switch(V.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return V.charAt(0).toUpperCase()+V.slice(1).toLowerCase()}},le=()=>{var V;(V=H.current)==null||V.scrollIntoView({behavior:"smooth"})};x.useEffect(()=>{le()},[f]);const ye=V=>{switch(V.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return V.charAt(0).toUpperCase()+V.slice(1).toLowerCase()}};x.useEffect(()=>{O.current||u&&(async()=>{try{const V=await aa(u),ie=Array.isArray(V==null?void 0:V.participants)?V.participants:[];if(ie.length===0)return;const B=ie.map(pe=>{const Me=pe.participantType||pe.participant_type||"participant",ve=pe.userId||pe.user_id||"";return{name:pe.userName||pe.user_name||pe.user_email||pe.userEmail||"User",avatar:(pe.userName||pe.user_name||pe.user_email||"U").toString().split(" ").map(_e=>_e[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:ye(Me.toString()),status:"offline",email:pe.userEmail||pe.user_email||"",permissions:["read","write","mention"],userId:ve}});O.current=!0,Q(B);let he=0;const ue=3,Ne=()=>{Z.current&&Z.current.connected?(Z.current.emit("request:online-users",{requestId:u}),he++,he<ue&&setTimeout(Ne,500)):(he++,he<ue&&setTimeout(Ne,200))};setTimeout(Ne,100)}catch(V){console.error("[WorkNoteChat] ❌ Failed to load participants:",V)}})()},[u]),x.useEffect(()=>()=>{u&&(O.current=!1)},[u]),x.useEffect(()=>{const V=localStorage.getItem("userData");if(V)try{const ie=JSON.parse(V),B=(ie==null?void 0:ie.id)||(ie==null?void 0:ie.userId)||(ie==null?void 0:ie.user_id)||null;I(B)}catch(ie){console.error("[WorkNoteChat] Failed to parse userData:",ie)}},[]),x.useEffect(()=>{(async()=>{try{const ie=await ia("DOCUMENT_POLICY"),B={};ie.forEach(pe=>{B[pe.configKey]=pe.configValue});const he=parseInt(B.MAX_FILE_SIZE_MB||"10"),Ne=(B.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(pe=>pe.trim().toLowerCase());te({maxFileSizeMB:he,allowedFileTypes:Ne})}catch(ie){console.error("Failed to load document policy:",ie)}})()},[]),x.useEffect(()=>{if(!P)return;let V=u;return(async()=>{var ie;try{const B=await aa(u);(ie=B==null?void 0:B.workflow)!=null&&ie.requestId&&(V=B.workflow.requestId)}catch{}try{const B=Ya();r?Q(Be=>Be.map(qe=>qe.userId===P?{...qe,status:"online"}:qe)):(oi(B,V,P),Q(Be=>Be.map(qe=>qe.userId===P?{...qe,status:"online"}:qe)));const he=Be=>{const Oe=(Be==null?void 0:Be.note)||Be;if(!Oe)return;const qe=Oe.noteId||Oe.id;C($t=>{if($t.some(Ke=>Ke.id===qe))return $t;const yt=Oe.userName||Oe.user_name||"User",Ks=Oe.userRole||Oe.user_role,ua=Fe(Ks),xr=Oe.userId||Oe.user_id,gr={id:qe||String(Date.now()),user:{name:yt,avatar:yt.split(" ").map(Ke=>Ke[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:ua},content:Oe.message||"",timestamp:Oe.createdAt||new Date().toISOString(),isCurrentUser:xr===P,attachments:Array.isArray(Oe.attachments)?Oe.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};return[...$t,gr]})},ue=Be=>{Q(Oe=>Oe.length===0||!Oe.find(yt=>yt.userId===Be.userId)?Oe:Oe.map(yt=>yt.userId===Be.userId?{...yt,status:"online"}:yt))},Ne=Be=>{Be.userId!==P&&Q(Oe=>Oe.length===0||!Oe.find(yt=>yt.userId===Be.userId)?Oe:Oe.map(yt=>yt.userId===Be.userId?{...yt,status:"offline"}:yt))},pe=Be=>{Q(Oe=>Oe.length===0?Oe:Oe.map($t=>{const yt=$t.userId||"";if(yt===P)return{...$t,status:"online"};const ua=Be.userIds.includes(yt);return{...$t,status:ua?"online":"offline"}}))},Me=()=>{Q(Be=>Be.map(qe=>qe.userId===P?{...qe,status:"online"}:qe)),r||oi(B,V,P),O.current&&(B.emit("request:online-users",{requestId:V}),setTimeout(()=>B.emit("request:online-users",{requestId:V}),300),setTimeout(()=>B.emit("request:online-users",{requestId:V}),800))},ve=Be=>{console.error("[WorkNoteChat] ❌ Socket error:",Be)},_e=Be=>{console.warn("[WorkNoteChat] ⚠️ Socket disconnected:",Be),Q(Oe=>Oe.map(qe=>qe.userId===P?qe:{...qe,status:"offline"}))},Qt=Be=>{Be.includes("presence")||Be.includes("worknote")||Be.includes("request")};B.on("connect",Me),B.on("disconnect",_e),B.on("error",ve),B.on("worknote:new",he),B.on("presence:join",ue),B.on("presence:leave",Ne),B.on("presence:online",pe),B.onAny(Qt),Z.current=B,B.connected&&O.current&&(B.emit("request:online-users",{requestId:V}),setTimeout(()=>{B.emit("request:online-users",{requestId:V})},300),setTimeout(()=>{B.emit("request:online-users",{requestId:V})},800),setTimeout(()=>{B.emit("request:online-users",{requestId:V})},1500));const St=()=>{B.off("connect",Me),B.off("disconnect",_e),B.off("error",ve),B.off("worknote:new",he),B.off("presence:join",ue),B.off("presence:leave",Ne),B.off("presence:online",pe),B.offAny(Qt),r||Vd(B,V),Z.current=null};window.__wn_cleanup=St}catch{}})(),()=>{var ie;try{(ie=window.__wn_cleanup)==null||ie.call(window)}catch{}}},[u,P,r]);const Ve=async()=>{if(h.trim()||R.length>0){const V=Ia(h),ie=V.map(ue=>{const Ne=q.find(pe=>pe.name.toLowerCase().includes(ue.toLowerCase()));return Ne==null?void 0:Ne.userId}).filter(Boolean),B=R.map(ue=>({name:ue.name,url:URL.createObjectURL(ue),type:ue.type.split("/")[1]||"file"})),he={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:V,isHighPriority:h.includes("!important")||h.includes("urgent"),attachments:B.length>0?B:void 0,isCurrentUser:!0};if(a)try{await a(h,R)}catch{}else try{await Kd(u,{message:h,mentions:ie},R);const ue=await ba(u),Ne=Array.isArray(ue)?ue.map(pe=>{const Me=pe.userId||pe.user_id;return{id:pe.noteId||pe.id||String(Math.random()),user:{name:pe.userName||"User",avatar:(pe.userName||"U").slice(0,2).toUpperCase(),role:pe.userRole||"Participant"},content:pe.message||"",timestamp:pe.createdAt||new Date().toISOString(),isCurrentUser:Me===P,attachments:Array.isArray(pe.attachments)?pe.attachments.map(ve=>({attachmentId:ve.attachmentId||ve.attachment_id,name:ve.fileName||ve.file_name||ve.name,fileName:ve.fileName||ve.file_name||ve.name,url:ve.storageUrl||ve.storage_url||ve.url||"#",type:ve.fileType||ve.file_type||ve.type||"file",fileType:ve.fileType||ve.file_type||ve.type||"file",fileSize:ve.fileSize||ve.file_size})):void 0}}):[];C(Ne)}catch{C(ue=>[...ue,he])}p(""),E([])}};x.useEffect(()=>{if(s&&Array.isArray(s))try{const ie=s.filter(B=>(B.type||"").toLowerCase()!=="sla_warning").map(B=>{var ue;if(B.type||B.activityType||B.isSystem)return{id:B.id||`activity-${B.timestamp||Date.now()}-${Math.random()}`,user:{name:"System",avatar:"SY",role:"System"},content:B.details||B.action||B.content||"",timestamp:B.timestamp||B.createdAt||B.created_at||new Date().toISOString(),isSystem:!0,isCurrentUser:!1};{const Ne=B.userName||B.user_name||((ue=B.user)==null?void 0:ue.name)||"User",pe=B.userRole||B.user_role,Me=Fe(pe),ve=B.userId||B.user_id;return{id:B.noteId||B.note_id||B.id||String(Math.random()),user:{name:Ne,avatar:Ne.split(" ").map(_e=>_e[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Me},content:B.message||B.content||"",timestamp:B.createdAt||B.created_at||B.timestamp||new Date().toISOString(),isSystem:!1,attachments:Array.isArray(B.attachments)?B.attachments.map(_e=>({attachmentId:_e.attachmentId||_e.attachment_id,name:_e.fileName||_e.file_name||_e.name,fileName:_e.fileName||_e.file_name||_e.name,url:_e.storageUrl||_e.storage_url||_e.url||"#",type:_e.fileType||_e.file_type||_e.type||"file",fileType:_e.fileType||_e.file_type||_e.type||"file",fileSize:_e.fileSize||_e.file_size})):void 0,isCurrentUser:ve===P}}}).sort((B,he)=>new Date(B.timestamp).getTime()-new Date(he.timestamp).getTime());C(ie)}catch(V){console.error("[WorkNoteChat] Error mapping messages:",V)}else(async()=>{try{const V=await ba(u),ie=Array.isArray(V)?V.map(B=>{const he=B.userName||B.user_name||"User",ue=B.userRole||B.user_role,Ne=Fe(ue),pe=B.userId||B.user_id;return{id:B.noteId||B.note_id||B.id||String(Math.random()),user:{name:he,avatar:he.split(" ").map(Me=>Me[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ne},content:B.message||"",timestamp:B.createdAt||B.created_at||new Date().toISOString(),attachments:Array.isArray(B.attachments)?B.attachments.map(Me=>({attachmentId:Me.attachmentId||Me.attachment_id,name:Me.fileName||Me.file_name||Me.name,fileName:Me.fileName||Me.file_name||Me.name,url:Me.storageUrl||Me.storage_url||Me.url||"#",type:Me.fileType||Me.file_type||Me.type||"file",fileType:Me.fileType||Me.file_type||Me.type||"file",fileSize:Me.fileSize||Me.file_size})):void 0,isCurrentUser:pe===P}}):[];C(ie)}catch(V){console.error("[WorkNoteChat] Error loading work notes:",V)}})()},[s,u,q]);const Le=V=>{const ie=se.maxFileSizeMB*1024*1024;if(V.size>ie)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${se.maxFileSizeMB}MB. Current size: ${(V.size/(1024*1024)).toFixed(2)}MB`};const B=V.name.toLowerCase(),he=B.substring(B.lastIndexOf(".")+1);return se.allowedFileTypes.includes(he)?{valid:!0}:{valid:!1,reason:`File type "${he}" is not allowed. Allowed types: ${se.allowedFileTypes.join(", ")}`}},Zt=V=>{if(!V.target.files||V.target.files.length===0)return;const ie=Array.from(V.target.files),B=[],he=[];ie.forEach(ue=>{const Ne=Le(ue);Ne.valid?he.push(ue):B.push({fileName:ue.name,reason:Ne.reason||"Unknown validation error"})}),B.length>0&&X({open:!0,errors:B}),he.length>0&&(E(ue=>[...ue,...he]),he.length<ie.length?be.warning(`${he.length} of ${ie.length} file(s) were added. ${B.length} file(s) were rejected.`):be.success(`${he.length} file(s) added successfully`)),V.target&&(V.target.value="")},js=V=>{E(ie=>ie.filter((B,he)=>he!==V)),z.current&&(z.current.value="")},Ws=V=>{p(ie=>ie+V),w(!1)},ma=()=>{var V;(V=z.current)==null||V.click()},Ma=async V=>{var ie,B;try{await Yd(u,V);const he=await aa(u),ue=Array.isArray(he==null?void 0:he.participants)?he.participants:[];if(ue.length){const Ne=ue.map(pe=>{const Me=pe.participantType||pe.participant_type||"participant",ve=pe.userId||pe.user_id||"",_e=pe.userName||pe.user_name||pe.userEmail||pe.user_email||"User",Qt=pe.userEmail||pe.user_email||"",St=_e.split(" ").map(Be=>Be[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:_e,avatar:St,role:ye(Me),status:"offline",email:Qt,lastSeen:void 0,permissions:["read"],userId:ve}});Q(Ne),Z.current&&Z.current.connected&&Z.current.emit("request:online-users",{requestId:u})}Y(!1),D({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),S(!0)}catch(he){throw console.error("Failed to add spectator:",he),D({success:!1,title:"Failed to Add Spectator",message:((B=(ie=he==null?void 0:he.response)==null?void 0:ie.data)==null?void 0:B.error)||"Failed to add spectator. Please try again."}),S(!0),he}},Ns=async(V,ie,B)=>{var he,ue;if(d)await d(V,ie,B),L(!1);else try{await Gd(u,V,ie,B);const Ne=await aa(u),pe=Array.isArray(Ne==null?void 0:Ne.participants)?Ne.participants:[];if(pe.length){const Me=pe.map(ve=>{const _e=ve.participantType||ve.participant_type||"participant",Qt=ve.userId||ve.user_id||"",St=ve.userName||ve.user_name||ve.userEmail||ve.user_email||"User",Be=ve.userEmail||ve.user_email||"",Oe=St.split(" ").map(qe=>qe[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:St,avatar:Oe,role:ye(_e),status:"offline",email:Be,lastSeen:void 0,permissions:["read"],userId:Qt}});Q(Me),Z.current&&Z.current.connected&&Z.current.emit("request:online-users",{requestId:u})}L(!1),D({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${B} with ${ie}h TAT`}),S(!0)}catch(Ne){throw console.error("Failed to add approver:",Ne),D({success:!1,title:"Failed to Add Approver",message:((ue=(he=Ne==null?void 0:Ne.response)==null?void 0:he.data)==null?void 0:ue.error)||"Failed to add approver. Please try again."}),S(!0),Ne}},Ct=["😊","😂","🤣","😁","😃","😄","😅","😆","😉","😌","😍","🥰","😘","😗","😙","😚","🙂","🤗","🤩","🤔","🤨","😐","😑","😶","🙄","😏","😒","🙃","😬","🤐","😴","😪","😵","🤯","🤪","😜","😝","😛","🤤","😋","😎","🤓","🧐","😕","😟","🙁","☹️","😮","😯","😲","😳","🥺","😦","😧","😨","😰","😥","😢","😭","😱","😖","😣","😞","😓","😩","😫","🥱","😤","😡","😠","🤬","😈","👿","💀","☠️","💩","🤡","👹","👺","👻","👋","🤚","🖐️","✋","🖖","👌","🤌","🤏","✌️","🤞","🤟","🤘","🤙","👈","👉","👆","🖕","👇","☝️","👍","👎","✊","👊","🤛","🤜","👏","🙌","👐","🤲","🤝","🙏","💪","🦾","🦿","🦵","🦶","👂","🦻","👃","🧠","❤️","🧡","💛","💚","💙","💜","🖤","🤍","🤎","💔","❣️","💕","💞","💓","💗","💖","💘","💝","💟","❤️🔥","💼","📊","📈","📉","💻","⌨️","🖥️","🖨️","🖱️","💾","💿","📱","☎️","📞","📟","📠","📧","✉️","📨","📩","📮","📪","📫","📬","📭","📄","📃","📑","📝","✏️","✒️","🖊️","🖋️","📏","📐","📌","📍","🗂️","📁","📂","✅","✔️","☑️","🎯","🎖️","🏆","🥇","🥈","🥉","⭐","🌟","✨","💫","🔥","💥","⚡","💯","🎉","🎊","🎈","⚠️","🚫","❌","⛔","🚷","🚯","🚱","🚳","🔞","📵","❗","❓","❕","❔","‼️","⁉️","💢","💬","💭","🗯️","⏰","⏱️","⏲️","⏳","⌛","📅","📆","🗓️","📇","🕐","🕑","🕒","🕓","🕔","🕕","🕖","🕗","🕘","🕙","🕚","🚀","🎯","🎲","🎰","🧩","🔍","🔎","🔑","🗝️","🔒","🔓","🔐","🔏","🔔","🔕","📣","📢","💡","🔦","🏮","➕","➖","✖️","➗","♾️","‼️","⁉️","❓","❔","❕","🔄","🔃","🔂","▶️","⏸️","⏯️","⏹️","⏺️","⏭️","⏮️","⏩","⏪","⏫","⏬","◀️","🔼","🔽","➡️","⬅️","⬆️","⬇️","↗️","↘️","↙️","↖️","↕️","↔️","↪️","↩️","⤴️"],Ia=V=>{const ie=/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,B=[];let he;for(;(he=ie.exec(V))!==null;)if(he[1]){const ue=he.index+he[0].length,Ne=V.slice(ue),pe=V[ue];(Ne.startsWith("@")||!pe||/\s|[.,!?;:]|@/.test(pe))&&B.push(he[1].trim())}return B},pr=V=>{V.key==="Enter"&&!V.shiftKey&&(V.preventDefault(),Ve())},cn=(V,ie)=>{C(B=>B.map(he=>{if(he.id===V){const ue=he.reactions||[],Ne=ue.find(pe=>pe.emoji===ie);if(Ne)if(Ne.users.includes("You")){if(Ne.users=Ne.users.filter(pe=>pe!=="You"),Ne.users.length===0)return{...he,reactions:ue.filter(pe=>pe.emoji!==ie)}}else Ne.users.push("You");else ue.push({emoji:ie,users:["You"]});return{...he,reactions:ue}}return he}))};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(vs,{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(ee,{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:[oe.slice(0,3).map((V,ie)=>e.jsx(bt,{className:"h-8 w-8 ring-2 ring-white shadow-sm",children:e.jsx(jt,{className:"bg-blue-500 text-white text-xs font-semibold",children:V.avatar})},ie)),oe.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:["+",oe.length-3]})]})}),e.jsx(M,{variant:"outline",size:"sm",onClick:()=>N(!b),className:"lg:hidden",children:e.jsx(nt,{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(Xt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(fe,{placeholder:"Search messages...",value:g,onChange:V=>y(V.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:[W.map(V=>{const ie=V.isCurrentUser||!1;return e.jsxs("div",{className:`flex gap-2 sm:gap-3 lg:gap-4 ${V.isSystem?"justify-center":ie?"justify-end":""}`,children:[!V.isSystem&&!ie&&e.jsx(bt,{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(jt,{className:`text-white font-semibold text-xs sm:text-sm ${V.user.role==="Initiator"?"bg-green-600":V.user.role==="Current User"?"bg-blue-500":V.user.role==="System"?"bg-gray-500":"bg-slate-600"}`,children:V.user.avatar})}),e.jsx("div",{className:`${ie?"max-w-[70%]":"flex-1"} min-w-0 ${V.isSystem?"text-center max-w-xs sm:max-w-md mx-auto":""}`,children:V.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:V.content}),e.jsx("span",{className:"text-xs text-gray-500 hidden sm:inline",children:Vt(V.timestamp)})]}):e.jsxs("div",{children:[e.jsxs("div",{className:`flex items-center gap-2 sm:gap-3 mb-1 sm:mb-2 flex-wrap ${ie?"justify-end":""}`,children:[e.jsxs("span",{className:"font-semibold text-gray-900 text-sm sm:text-base truncate",children:[V.user.name," ",ie&&e.jsx("span",{className:"text-xs text-gray-500 font-normal",children:"(you)"})]}),e.jsx(ee,{variant:"outline",className:"text-xs flex-shrink-0",children:V.user.role}),e.jsxs("span",{className:"text-xs text-gray-500 flex items-center gap-1 flex-shrink-0",children:[e.jsx(Ie,{className:"w-3 h-3"}),Vt(V.timestamp)]}),V.isHighPriority&&e.jsxs(ee,{variant:"destructive",className:"text-xs flex-shrink-0",children:[e.jsx(xx,{className:"w-3 h-3 mr-1"}),"Priority"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 sm:p-4 shadow-sm ${ie?"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:ev(V.content)}}),V.attachments&&V.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:V.attachments.map((B,he)=>{const ue=B.fileSize||B.file_size,Ne=B.fileName||B.file_name||B.name,pe=B.fileType||B.file_type||B.type||"",Me=B.attachmentId||B.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(gl,{type:pe})}),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:Ne}),ue&&e.jsx("p",{className:"text-xs text-gray-500",children:tv(ue)})]}),Me&&(()=>{const ve=(pe||"").toLowerCase();return ve.includes("image")||ve.includes("pdf")||ve.includes("jpg")||ve.includes("jpeg")||ve.includes("png")||ve.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:ve=>{ve.preventDefault(),ve.stopPropagation();const _e=F0(Me);k({fileName:Ne,fileType:pe,fileUrl:_e,fileSize:ue,attachmentId:Me})},title:"Preview file",children:e.jsx(kt,{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 ve=>{if(ve.preventDefault(),ve.stopPropagation(),!Me){be.error("Cannot download: Attachment ID missing");return}try{await ul(Me)}catch{be.error("Failed to download file")}},title:"Download file",children:e.jsx(ns,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]},he)})})}),V.reactions&&V.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:[V.reactions.map((B,he)=>e.jsxs("button",{onClick:()=>cn(V.id,B.emoji),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs sm:text-sm transition-colors flex-shrink-0 ${B.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:B.emoji}),e.jsx("span",{className:"text-xs font-medium",children:B.users.length})]},he)),e.jsx(M,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-7 sm:w-7 p-0 flex-shrink-0",onClick:()=>w(!v),children:e.jsx(_s,{className:"w-2 h-2 sm:w-3 sm:h-3"})})]})]})]})}),!V.isSystem&&ie&&e.jsx(bt,{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(jt,{className:"bg-blue-500 text-white font-semibold text-xs sm:text-sm",children:V.user.avatar})})]},V.id)}),e.jsx("div",{ref:H})]})}),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:z,onChange:Zt,className:"hidden",multiple:!0,accept:se.allowedFileTypes.map(V=>`.${V}`).join(",")}),R.length>0&&e.jsx("div",{className:"mb-3 space-y-2 max-h-32 overflow-y-auto pr-2",children:R.map((V,ie)=>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(gl,{type:V.type.split("/")[1]||"file"})}),e.jsx("span",{className:"text-sm text-gray-700 flex-1 truncate min-w-0",children:V.name}),e.jsxs("span",{className:"text-xs text-gray-500 flex-shrink-0",children:[(V.size/1024).toFixed(1)," KB"]}),e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>js(ie),className:"h-6 w-6 p-0 hover:bg-red-100 flex-shrink-0",children:e.jsx(lt,{className:"h-3 w-3 text-red-600"})})]},ie))}),e.jsxs("div",{className:"relative mb-2",children:[(()=>{const V=h.lastIndexOf("@"),ie=V>=0;if(!ie)return null;const B=h.slice(V+1),he=B.trim(),ue=B.endsWith(" "),Ne=he.length>0,pe=he.includes(" ")&&!ue,Me=ue&&Ne;if(!(ie&&B.length<=20&&!pe&&!Me))return null;const _e=he.toLowerCase(),Qt=q.filter(St=>St.userId===P?!1:_e?St.name.toLowerCase().includes(_e):!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:Qt.length>0?Qt.map((St,Be)=>e.jsxs("button",{type:"button",onClick:Oe=>{Oe.preventDefault(),Oe.stopPropagation();const qe=h.lastIndexOf("@"),$t=h.slice(0,qe);p($t+"@"+St.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(bt,{className:"h-10 w-10",children:e.jsx(jt,{className:`text-white text-sm font-semibold ${St.role==="Initiator"?"bg-green-600":St.role==="Approver"?"bg-purple-600":"bg-blue-500"}`,children:St.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:St.name}),e.jsx("p",{className:"text-xs text-gray-600",children:St.role})]})]},Be)):e.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:_e?`No participants found matching "${_e}"`:"No other participants available"})})]})})(),e.jsx(bs,{placeholder:"Type your message... Use @username to mention someone",value:h,onChange:V=>p(V.target.value),onKeyPress:pr,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:()=>w(!1),className:"h-6 w-6 p-0",children:e.jsx(lt,{className:"h-3 w-3"})})]}),e.jsx("div",{className:"grid grid-cols-8 sm:grid-cols-10 gap-1",children:Ct.map((V,ie)=>e.jsx("button",{onClick:()=>Ws(V),className:"text-xl sm:text-2xl hover:bg-gray-100 rounded p-1 transition-colors flex items-center justify-center",title:V,children:V},ie))})]})]}),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:ma,title:"Attach file",children:e.jsx(qr,{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:()=>w(!v),title:"Add emoji",children:e.jsx(gx,{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:()=>p(V=>V+"@"),title:"Mention someone",children:e.jsx($i,{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(fx,{className:"h-4 w-4 sm:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Send"})]})]})]})]})})]}),b&&e.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 z-40 lg:hidden",onClick:()=>N(!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
|
||
${b?"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:()=>N(!1),className:"lg:hidden h-8 w-8 p-0",children:e.jsx(lt,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-3 sm:space-y-4 overflow-y-auto flex-1 pr-2",children:q.map((V,ie)=>{const B=V.userId===P;return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(bt,{className:"h-9 w-9 sm:h-10 sm:w-10",children:e.jsx(jt,{className:`text-white font-semibold text-sm ${V.role==="Initiator"?"bg-green-600":B?"bg-blue-500":"bg-slate-600"}`,children:V.avatar})}),e.jsx("div",{className:`absolute -bottom-1 -right-1 w-3 h-3 rounded-full border-2 border-white ${Qy(V.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:[V.name," ",B&&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:V.role}),e.jsx("span",{className:"text-xs text-gray-400",children:"•"}),e.jsx("p",{className:"text-xs text-gray-500",children:Jy(V.status)})]}),V.lastSeen&&V.status==="offline"&&e.jsx("p",{className:"text-xs text-gray-400",children:V.lastSeen})]})]},ie)})})]}),!me&&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:()=>L(!0),children:[e.jsx(Wr,{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:()=>Y(!0),children:[e.jsx(kt,{className:"h-4 w-4"}),"Add Spectator"]})]})]})]})]}),j&&e.jsx(Yi,{fileName:j.fileName,fileType:j.fileType,fileUrl:j.fileUrl,fileSize:j.fileSize,attachmentId:j.attachmentId,onDownload:ul,open:!!j,onClose:()=>k(null)}),!me&&e.jsx(cm,{open:_,onClose:()=>Y(!1),onConfirm:Ma,requestIdDisplay:u,requestTitle:ne.title,existingParticipants:Ee}),!me&&o&&e.jsx(dm,{open:F,onClose:()=>L(!1),onConfirm:Ns,requestIdDisplay:u,requestTitle:ne.title,existingParticipants:Ee,currentLevels:c}),e.jsx(et,{open:$.open,onOpenChange:V=>X(ie=>({...ie,open:V})),children:e.jsxs(Xe,{className:"sm:max-w-lg",children:[e.jsxs(tt,{children:[e.jsxs(Ze,{className:"flex items-center gap-2",children:[e.jsx(Pe,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(qt,{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:$.errors.map((V,ie)=>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:V.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:V.reason})]},ie))}),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: ",se.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",se.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(wt,{children:e.jsx(M,{onClick:()=>X({open:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(om,{open:A,onClose:()=>S(!1),success:T.success,title:T.title,message:T.message})]})}function sv({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(mm,{requestId:t,requestTitle:s,skipSocketJoin:!0,messages:a,onAttachmentsExtracted:r,isInitiator:n,isSpectator:i,currentLevels:o,onAddApprover:l})})}function av({summary:t,loading:s,onShare:a,isInitiator:r}){const n=l=>{const c=l.toLowerCase();return c==="approved"?e.jsx(je,{className:"h-4 w-4 text-green-600"}):c==="rejected"?e.jsx(Je,{className:"h-4 w-4 text-red-600"}):c==="pending"||c==="in progress"?e.jsx(Ie,{className:"h-4 w-4 text-orange-600"}):e.jsx(Ae,{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(Ue,{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(Sa,{className:"w-4 h-4"}),e.jsx("span",{children:"Share"})]}):e.jsxs(ee,{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(Fs,{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:xe(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:xe(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(ee,{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(Fs,{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(Ae,{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 rv({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}){var k,_,Y;const{user:p}=Mt(),[g,y]=x.useState([]),[v,w]=x.useState(!1),[f,C]=x.useState(!1),b=(t==null?void 0:t.status)==="closed",N=((k=t==null?void 0:t.pauseInfo)==null?void 0:k.isPaused)||!1,R=(Y=(_=t==null?void 0:t.pauseInfo)==null?void 0:_.pausedBy)==null?void 0:Y.userId,E=(p==null?void 0:p.userId)||"",P=!N&&!b&&(r||s),I=N&&d&&(r||s),j=N&&s&&R&&R!==E&&m;return x.useEffect(()=>{if(!N||!r||!(t!=null&&t.requestId)){C(!1);return}(async()=>{var L;try{const T=(((L=(await Is.list({page:1,limit:50,unreadOnly:!0})).data)==null?void 0:L.notifications)||[]).some(D=>D.requestId===t.requestId&&D.notificationType==="pause_retrigger_request");C(T)}catch(A){console.error("Failed to check retrigger notifications:",A),C(!1)}})()},[N,r,t==null?void 0:t.requestId,h]),x.useEffect(()=>{(async()=>{if(!b||!u||!s){y([]);return}try{w(!0);const L=await Fy(u);y(L)}catch(L){console.error("Failed to fetch shared recipients:",L),y([])}finally{w(!1)}})()},[b,u,s,h]),e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[!a&&t.status!=="closed"&&e.jsxs(K,{"data-testid":"quick-actions-card",children:[e.jsx(ae,{className:"pb-2",children:e.jsx(re,{className:"text-sm sm:text-base",children:"Quick Actions"})}),e.jsxs(G,{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(Wr,{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(kt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Add Spectator"]}),P&&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(Os,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Pause Workflow"]}),I&&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(Ir,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Resume Workflow"]}),j&&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(Pe,{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&&!N&&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(je,{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(Je,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Reject Request"]})]}),N&&e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-3 text-center",children:R===E?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-xs text-orange-800 font-medium flex items-center justify-center gap-1.5",children:[f&&e.jsx(Pe,{className:"w-3.5 h-3.5"}),f?"Initiator has requested you to resume":"You paused this workflow"]}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:f?"Please review and resume if appropriate":'Click "Resume Workflow" to continue'})]}):r&&R!==E&&f?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-xs text-orange-800 font-medium flex items-center justify-center gap-1.5",children:[e.jsx(Pe,{className:"w-3.5 h-3.5"}),"Initiator has requested resume"]}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:"Please review and resume if appropriate"})]}):r&&R!==E?e.jsxs(e.Fragment,{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:"You can resume to continue approval"})]}):s&&R&&R!==E?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-orange-800 font-medium",children:"Approver has paused this workflow"}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:j?'Click "Request Resume" to notify approver':"Resume request sent - Waiting for approver"})]}):e.jsxs(e.Fragment,{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(K,{"data-testid":"spectators-card",children:[e.jsx(ae,{className:"pb-2",children:e.jsx(re,{className:"text-sm sm:text-base",children:"Spectators"})}),e.jsx(G,{className:"space-y-3",children:t.spectators&&t.spectators.length>0?t.spectators.map((F,L)=>e.jsxs("div",{className:"flex items-center gap-3","data-testid":`spectator-${L}`,children:[e.jsx(bt,{className:"h-8 w-8",children:e.jsx(jt,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:F.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:F.name}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:F.role})]})]},L)):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(K,{"data-testid":"shared-recipients-card",children:[e.jsx(ae,{className:"pb-2",children:e.jsxs(re,{className:"text-sm sm:text-base flex items-center gap-2",children:[e.jsx(Sa,{className:"w-4 h-4"}),"Summary Shared With"]})}),e.jsx(G,{className:"space-y-3",children:v?e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Loading..."})}):g.length>0?g.map((F,L)=>{const A=(F.displayName||"NA").split(" ").map(S=>S[0]).join("").slice(0,2).toUpperCase();return e.jsxs("div",{className:"flex items-center gap-3","data-testid":`shared-recipient-${L}`,children:[e.jsx(bt,{className:"h-8 w-8",children:e.jsx(jt,{className:"bg-green-100 text-green-800 text-xs font-semibold",children:A})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:F.displayName}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:F.email}),F.isRead&&e.jsx("p",{className:"text-xs text-green-600 mt-0.5",children:"Viewed"})]})]},F.userId||L)}):e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Summary not shared yet"})})})]})]})}function nv({open:t,onClose:s,onConfirm:a,defaultDescription:r="",title:n="Approve Request",requestIdDisplay:i,requestTitle:o}){const[l,c]=x.useState(r),[d,m]=x.useState(!1),u=(l==null?void 0:l.length)||0,h=x.useMemo(()=>l.slice(0,500),[l]),p=async()=>{try{m(!0),await a(h),s()}finally{m(!1)}};return e.jsx(et,{open:t,onOpenChange:g=>!g&&s(),children:e.jsxs(Xe,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(tt,{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(je,{className:"w-7 h-7 text-green-600"})}),e.jsxs("div",{children:[e.jsx(Ze,{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(ee,{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(bs,{value:h,onChange:g=>c(g.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(je,{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(wt,{className:"mt-4",children:[e.jsx(M,{variant:"outline",onClick:s,disabled:d,children:"Cancel"}),e.jsxs(M,{onClick:p,disabled:d,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(je,{className:"w-4 h-4 mr-2"}),d?"Approving...":"Approve Request"]})]})]})})}function iv({open:t,onClose:s,onConfirm:a,defaultDescription:r="",title:n="Reject Request",requestIdDisplay:i,requestTitle:o}){const[l,c]=x.useState(r),[d,m]=x.useState(!1),u=(l==null?void 0:l.length)||0,h=x.useMemo(()=>l.slice(0,500),[l]),p=async()=>{if(!h.trim()){alert("Comments & remarks are required");return}try{m(!0),await a(h),s()}finally{m(!1)}};return e.jsx(et,{open:t,onOpenChange:g=>!g&&s(),children:e.jsxs(Xe,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(tt,{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(Je,{className:"w-7 h-7 text-red-600"})}),e.jsxs("div",{children:[e.jsx(Ze,{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(ee,{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(bs,{value:h,onChange:g=>c(g.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(Pe,{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(wt,{className:"mt-4",children:[e.jsx(M,{variant:"outline",onClick:s,disabled:d,children:"Cancel"}),e.jsxs(M,{variant:"destructive",onClick:p,disabled:d,children:[e.jsx(Je,{className:"w-4 h-4 mr-2"}),d?"Rejecting...":"Reject Request"]})]})]})})}function ov({open:t,onClose:s,onConfirm:a,approverName:r,levelNumber:n,requestIdDisplay:i,requestTitle:o}){const[l,c]=x.useState(""),[d,m]=x.useState(!1),u=async()=>{if(l.trim())try{m(!0),await a(l.trim()),c(""),s()}catch(p){console.error("Failed to skip approver:",p)}finally{m(!1)}},h=()=>{d||(c(""),s())};return e.jsx(et,{open:t,onOpenChange:h,children:e.jsxs(Xe,{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(lt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(tt,{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(Pe,{className:"w-5 h-5 text-orange-600"})}),e.jsx(Ze,{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(Pe,{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(J,{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(J,{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(J,{htmlFor:"skip-reason",className:"text-sm font-semibold text-gray-700",children:"Reason for Skipping *"}),e.jsx(bs,{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:p=>c(p.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(Pe,{className:"w-4 h-4 mr-2"}),d?"Skipping...":"Skip Approver"]})]})]})})}function lv({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:p,setShowRejectModal:g,setShowAddApproverModal:y,setShowAddSpectatorModal:v,setShowSkipApproverModal:w,setShowActionStatusModal:f,setPreviewDocument:C,setDocumentError:b,setSkipApproverData:N,setActionStatus:R,handleApproveConfirm:E,handleRejectConfirm:P,handleAddApprover:I,handleAddSpectator:j,handleSkipApprover:k,downloadDocument:_,documentPolicy:Y}){return e.jsxs(e.Fragment,{children:[e.jsx(nv,{open:t,onClose:()=>p(!1),onConfirm:E,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(iv,{open:s,onClose:()=>g(!1),onConfirm:P,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(dm,{open:a,onClose:()=>y(!1),onConfirm:I,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:u,currentLevels:h}),e.jsx(cm,{open:r,onClose:()=>v(!1),onConfirm:j,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:u}),e.jsx(ov,{open:n,onClose:()=>{w(!1),N(null)},onConfirm:k,approverName:d==null?void 0:d.approverName,levelNumber:d==null?void 0:d.levelNumber,requestIdDisplay:c.id,requestTitle:c.title}),o&&e.jsx(Yi,{fileName:o.fileName,fileType:o.fileType,fileUrl:Xd(o.documentId),fileSize:o.fileSize,attachmentId:o.documentId,onDownload:_,open:!!o,onClose:()=>C(null)}),m&&e.jsx(om,{open:i,onClose:()=>{f(!1),R(null)},success:m.success,title:m.title,message:m.message}),e.jsx(et,{open:l.show,onOpenChange:F=>b(L=>({...L,show:F})),children:e.jsxs(Xe,{className:"sm:max-w-lg",children:[e.jsxs(tt,{children:[e.jsxs(Ze,{className:"flex items-center gap-2",children:[e.jsx(Pe,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(qt,{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((F,L)=>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:F.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:F.reason})]},L))}),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: ",Y.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",Y.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(wt,{children:e.jsx(M,{onClick:()=>b({show:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})})]})}function cv({isOpen:t,onClose:s,requestId:a,levelId:r,onSuccess:n}){const[i,o]=x.useState(""),[l,c]=x.useState(""),[d,m]=x.useState(!1),u=()=>st().add(1,"month").format("YYYY-MM-DD"),h=()=>st().add(1,"month").format("YYYY-MM-DD"),p=()=>st().add(1,"day").format("YYYY-MM-DD");x.useEffect(()=>{t&&!l&&c(u())},[t]);const g=async()=>{var C,b,N,R;if(!i.trim()){be.error("Please provide a reason for pausing");return}if(!l){be.error("Please select a resume date");return}const v=st(l),w=st().add(1,"month"),f=st().add(1,"day");if(v.isAfter(w)){be.error("Resume date cannot be more than 1 month from now");return}if(v.isBefore(f,"day")){be.error("Resume date must be at least 1 day from now");return}try{m(!0),await E0(a,r,i.trim(),v.toDate()),be.success("Workflow paused successfully"),n&&await n(),o(""),c(u()),s()}catch(E){console.error("Failed to pause workflow:",E),be.error(((b=(C=E==null?void 0:E.response)==null?void 0:C.data)==null?void 0:b.error)||((R=(N=E==null?void 0:E.response)==null?void 0:N.data)==null?void 0:R.message)||"Failed to pause workflow")}finally{m(!1)}},y=()=>{d||(o(""),c(u()),s())};return e.jsx(et,{open:t,onOpenChange:y,children:e.jsxs(Xe,{className:"sm:max-w-[500px]",children:[e.jsx(tt,{children:e.jsxs(Ze,{className:"flex items-center gap-2",children:[e.jsx(Os,{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(J,{htmlFor:"pause-reason",className:"text-sm font-medium",children:["Reason for Pausing ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(bs,{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(J,{htmlFor:"resume-date",className:"text-sm font-medium",children:["Resume Date ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(fe,{id:"resume-date",type:"date",value:l,onChange:v=>c(v.target.value),min:p(),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(wt,{children:[e.jsx(M,{variant:"outline",onClick:y,disabled:d,children:"Cancel"}),e.jsx(M,{onClick:g,disabled:d||!i.trim()||!l,className:"bg-orange-600 hover:bg-orange-700 text-white",children:d?e.jsxs(e.Fragment,{children:[e.jsx(Ue,{className:"w-4 h-4 mr-2 animate-spin"}),"Pausing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Os,{className:"w-4 h-4 mr-2"}),"Pause Workflow"]})})]})]})})}function dv({isOpen:t,onClose:s,requestId:a,onSuccess:r}){const[n,i]=x.useState(""),[o,l]=x.useState(!1),c=async()=>{var m,u,h,p;try{l(!0),await M0(a,n.trim()||void 0),be.success("Workflow resumed successfully"),r&&await r(),i(""),s()}catch(g){console.error("Failed to resume workflow:",g),be.error(((u=(m=g==null?void 0:g.response)==null?void 0:m.data)==null?void 0:u.error)||((p=(h=g==null?void 0:g.response)==null?void 0:h.data)==null?void 0:p.message)||"Failed to resume workflow")}finally{l(!1)}},d=()=>{o||(i(""),s())};return e.jsx(et,{open:t,onOpenChange:d,children:e.jsxs(Xe,{className:"sm:max-w-[500px]",children:[e.jsx(tt,{children:e.jsxs(Ze,{className:"flex items-center gap-2",children:[e.jsx(Ir,{className:"w-5 h-5 text-green-600"}),"Resume Workflow"]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("div",{className:"bg-green-50 border border-green-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-green-800",children:[e.jsx("strong",{children:"Note:"})," Resuming will restart TAT calculations and notifications. The workflow will continue from where it was paused."]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"resume-notes",className:"text-sm font-medium",children:"Notes (Optional)"}),e.jsx(bs,{id:"resume-notes",value:n,onChange:m=>i(m.target.value),placeholder:"Add any notes about why you're resuming this workflow...",className:"min-h-[100px] text-sm",disabled:o}),e.jsxs("p",{className:"text-xs text-gray-500",children:[n.length," / 1000 characters"]})]})]}),e.jsxs(wt,{children:[e.jsx(M,{variant:"outline",onClick:d,disabled:o,children:"Cancel"}),e.jsx(M,{onClick:c,disabled:o,className:"bg-green-600 hover:bg-green-700 text-white",children:o?e.jsxs(e.Fragment,{children:[e.jsx(Ue,{className:"w-4 h-4 mr-2 animate-spin"}),"Resuming..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ir,{className:"w-4 h-4 mr-2"}),"Resume Workflow"]})})]})]})})}function mv({isOpen:t,onClose:s,requestId:a,approverName:r,onSuccess:n}){const[i,o]=x.useState(!1),l=async()=>{var c,d,m,u;try{o(!0),await I0(a),be.success("Retrigger request sent to approver"),n&&await n(),s()}catch(h){console.error("Failed to retrigger pause:",h),be.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(et,{open:t,onOpenChange:s,children:e.jsxs(Xe,{className:"sm:max-w-[450px]",children:[e.jsx(tt,{children:e.jsxs(Ze,{className:"flex items-center gap-2",children:[e.jsx(Pe,{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(wt,{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(Ue,{className:"w-4 h-4 mr-2 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Pe,{className:"w-4 h-4 mr-2"}),"Send Request"]})})]})]})})}class uv extends x.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 hv({requestId:t,onBack:s,dynamicRequests:a=[]}){var xr,gr,Ke,zo,Ho,qo;const n=rr().requestId||t||"",o=new URLSearchParams(window.location.search).get("tab")||"overview",[l,c]=x.useState(o),[d,m]=x.useState(!1),[u,h]=x.useState(null),[p,g]=x.useState(null),[y,v]=x.useState(!1),[w,f]=x.useState(0),[C,b]=x.useState(!1),[N,R]=x.useState(!1),[E,P]=x.useState(!1),{user:I}=Mt(),{request:j,apiRequest:k,loading:_,refreshing:Y,refreshDetails:F,currentApprovalLevel:L,isSpectator:A,isInitiator:S,existingParticipants:T,accessDenied:D}=hy(n,a,I),{mergedMessages:H,unreadWorkNotes:z,workNoteAttachments:Z,setWorkNoteAttachments:O}=py(n,k,l,I),{uploadingDocument:se,triggerFileInput:te,previewDocument:$,setPreviewDocument:X,documentPolicy:ne,documentError:q,setDocumentError:Q}=jy(k,F),{showApproveModal:oe,setShowApproveModal:W,showRejectModal:me,setShowRejectModal:we,showAddApproverModal:Ee,setShowAddApproverModal:Fe,showAddSpectatorModal:le,setShowAddSpectatorModal:ye,showSkipApproverModal:Ve,setShowSkipApproverModal:Le,showActionStatusModal:Zt,setShowActionStatusModal:js,skipApproverData:Ws,setSkipApproverData:ma,actionStatus:Ma,setActionStatus:Ns,handleApproveConfirm:Ct,handleRejectConfirm:Ia,handleAddApprover:pr,handleSkipApprover:cn,handleAddSpectator:V}=Sy(n,L,F),{conclusionRemark:ie,setConclusionRemark:B,conclusionLoading:he,conclusionSubmitting:ue,aiGenerated:Ne,handleGenerateConclusion:pe,handleFinalizeConclusion:Me}=Cy(j,n,S,F,s,Ns,js);x.useEffect(()=>{const ws=new URLSearchParams(window.location.search).get("tab");ws&&c(ws)},[n]);const ve=()=>{F()},_e=()=>{b(!0)},Qt=()=>{R(!0)},St=async()=>{await F()},Be=()=>{P(!0)},Oe=async()=>{await F()},qe=async()=>{await F()},$t=async()=>{if(!(k!=null&&k.requestId)){be.error("Request ID not found");return}if(!u){be.error("Summary not available. Please ensure the request is closed and the summary has been generated.");return}m(!0)},yt=((j==null?void 0:j.status)==="approved"||(j==null?void 0:j.status)==="rejected")&&S,Ks=(j==null?void 0:j.status)==="closed"||(j==null?void 0:j.status)==="approved"&&!S||(j==null?void 0:j.status)==="rejected"&&!S;x.useEffect(()=>{(async()=>{if(!Ks||!(k!=null&&k.requestId)){g(null),h(null);return}try{v(!0);const ws=await Iy(k.requestId);if(ws!=null&&ws.summaryId){h(ws.summaryId);try{const dn=await sm(ws.summaryId);g(dn)}catch(dn){console.error("Failed to fetch summary details:",dn),g(null),h(null)}}else g(null),h(null)}catch{g(null),h(null)}finally{v(!1)}})()},[Ks,k==null?void 0:k.requestId]);const ua=((j==null?void 0:j.approvalFlow)||[]).filter(Ut=>Ut&&typeof Ut.step=="number").map(Ut=>({levelNumber:Ut.step||0,approverName:Ut.approver||"Unknown",status:Ut.status||"pending",tatHours:Ut.tatHours||24}));return _&&!j&&!k?e.jsx("div",{className:"flex items-center justify-center h-screen bg-gray-50","data-testid":"loading-state",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Et,{className:"w-12 h-12 text-blue-600 animate-spin mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading request details..."})]})}):D!=null&&D.denied?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-6","data-testid":"access-denied-state",children:e.jsxs("div",{className:"max-w-lg w-full bg-white rounded-2xl shadow-xl p-8 text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-6",children:e.jsx(bx,{className:"w-10 h-10 text-red-500"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-3",children:"Access Denied"}),e.jsx("p",{className:"text-gray-600 mb-6 leading-relaxed",children:D.message}),e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-4 mb-6 text-left",children:[e.jsx("p",{className:"text-sm text-amber-800",children:e.jsx("strong",{children:"Who can access this request?"})}),e.jsxs("ul",{className:"text-sm text-amber-700 mt-2 space-y-1",children:[e.jsx("li",{children:"• The person who created this request (Initiator)"}),e.jsx("li",{children:"• Designated approvers at any level"}),e.jsx("li",{children:"• Added spectators or participants"}),e.jsx("li",{children:"• Organization administrators"})]})]}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsxs(M,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(xs,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(M,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})}):j?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(Dy,{request:j,refreshing:Y,onBack:s||(()=>window.history.back()),onRefresh:ve,onShareSummary:$t,isInitiator:S}),e.jsxs(Jr,{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(en,{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(xt,{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(jx,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Overview"})]}),Ks&&p&&e.jsxs(xt,{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(bd,{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(xt,{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(Vs,{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(xt,{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(Ae,{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(xt,{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(xt,{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(vs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Work Notes"}),z>0&&e.jsx(ee,{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:z>9?"9+":z})]})]})}),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(gt,{value:"overview",className:"mt-0","data-testid":"overview-tab-content",children:e.jsx(qy,{request:j,isInitiator:S,needsClosure:yt,conclusionRemark:ie,setConclusionRemark:B,conclusionLoading:he,conclusionSubmitting:ue,aiGenerated:Ne,handleGenerateConclusion:pe,handleFinalizeConclusion:Me,onPause:_e,onResume:Qt,onRetrigger:Be,currentUserIsApprover:!!L,pausedByUserId:(gr=(xr=j==null?void 0:j.pauseInfo)==null?void 0:xr.pausedBy)==null?void 0:gr.userId,currentUserId:I==null?void 0:I.userId})}),Ks&&e.jsx(gt,{value:"summary",className:"mt-0","data-testid":"summary-tab-content",children:e.jsx(av,{summary:p,loading:y,onShare:$t,isInitiator:S})}),e.jsx(gt,{value:"workflow",className:"mt-0",children:e.jsx(Gy,{request:j,user:I,isInitiator:S,onSkipApprover:Ut=>{if(!Ut.levelId){alert("Level ID not available");return}ma(Ut),Le(!0)},onRefresh:F})}),e.jsx(gt,{value:"documents",className:"mt-0",children:e.jsx(Xy,{request:j,workNoteAttachments:Z,uploadingDocument:se,documentPolicy:ne,triggerFileInput:te,setPreviewDocument:X,downloadDocument:li})}),e.jsx(gt,{value:"activity",className:"mt-0",children:e.jsx(Zy,{request:j})}),e.jsx(gt,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:l!=="worknotes",children:e.jsx(sv,{requestId:n,requestTitle:j.title,mergedMessages:H,setWorkNoteAttachments:O,isInitiator:S,isSpectator:A,currentLevels:ua,onAddApprover:pr})})]}),l!=="worknotes"&&e.jsx(rv,{request:j,isInitiator:S,isSpectator:A,currentApprovalLevel:L,onAddApprover:()=>Fe(!0),onAddSpectator:()=>ye(!0),onApprove:()=>W(!0),onReject:()=>we(!0),onPause:_e,onResume:Qt,onRetrigger:Be,summaryId:u,refreshTrigger:w,pausedByUserId:(zo=(Ke=j==null?void 0:j.pauseInfo)==null?void 0:Ke.pausedBy)==null?void 0:zo.userId,currentUserId:I==null?void 0:I.userId})]})]})]})}),d&&u&&e.jsx(By,{isOpen:d,onClose:()=>m(!1),summaryId:u,requestTitle:(j==null?void 0:j.title)||"N/A",onSuccess:()=>{F(),f(Ut=>Ut+1)}}),C&&(k==null?void 0:k.requestId)&&e.jsx(cv,{isOpen:C,onClose:()=>b(!1),requestId:k.requestId,levelId:(L==null?void 0:L.levelId)||null,onSuccess:Oe}),N&&(k==null?void 0:k.requestId)&&e.jsx(dv,{isOpen:N,onClose:()=>R(!1),requestId:k.requestId,onSuccess:St}),E&&(k==null?void 0:k.requestId)&&e.jsx(mv,{isOpen:E,onClose:()=>P(!1),requestId:k.requestId,approverName:(qo=(Ho=j==null?void 0:j.pauseInfo)==null?void 0:Ho.pausedBy)==null?void 0:qo.name,onSuccess:qe}),e.jsx(lv,{showApproveModal:oe,showRejectModal:me,showAddApproverModal:Ee,showAddSpectatorModal:le,showSkipApproverModal:Ve,showActionStatusModal:Zt,previewDocument:$,documentError:q,request:j,skipApproverData:Ws,actionStatus:Ma,existingParticipants:T,currentLevels:ua,setShowApproveModal:W,setShowRejectModal:we,setShowAddApproverModal:Fe,setShowAddSpectatorModal:ye,setShowSkipApproverModal:Le,setShowActionStatusModal:js,setPreviewDocument:X,setDocumentError:Q,setSkipApproverData:ma,setActionStatus:Ns,handleApproveConfirm:Ct,handleRejectConfirm:Ia,handleAddApprover:pr,handleAddSpectator:V,handleSkipApprover:cn,downloadDocument:li,documentPolicy:ne})]}):e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-6","data-testid":"not-found-state",children:e.jsxs("div",{className:"max-w-md w-full bg-white rounded-2xl shadow-xl p-8 text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-6",children:e.jsx(Ae,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-3",children:"Request Not Found"}),e.jsx("p",{className:"text-gray-600 mb-6",children:"The request you're looking for doesn't exist or may have been deleted."}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsxs(M,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(xs,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(M,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})})}function pv(t){return e.jsx(uv,{children:e.jsx(hv,{...t})})}function xv({onViewSummary:t}){const s=Hs(),[a,r]=x.useState([]),[n,i]=x.useState(!0),[o,l]=x.useState(""),[c,d]=x.useState(1),[m,u]=x.useState(1),[h,p]=x.useState(0),g=10,y=x.useCallback(async(C=1)=>{try{i(!0);const b=await My({page:C,limit:g});r(b.data||[]),u(b.pagination.totalPages||1),p(b.pagination.total||0),d(b.pagination.page||1)}catch(b){console.error("Failed to fetch shared summaries:",b),be.error("Failed to load shared summaries")}finally{i(!1)}},[]);x.useEffect(()=>{y(1)},[y]);const v=async C=>{try{await am(C),r(b=>b.map(N=>N.sharedSummaryId===C?{...N,isRead:!0,viewedAt:new Date().toISOString()}:N)),t?t(C):s(`/shared-summaries/${C}`)}catch(b){console.error("Failed to mark as viewed:",b),t?t(C):s(`/shared-summaries/${C}`)}},w=C=>{C>=1&&C<=m&&y(C)},f=a.filter(C=>{var N,R,E,P;if(!o)return!0;const b=o.toLowerCase();return((N=C.title)==null?void 0:N.toLowerCase().includes(b))||((R=C.requestNumber)==null?void 0:R.toLowerCase().includes(b))||((E=C.initiatorName)==null?void 0:E.toLowerCase().includes(b))||((P=C.sharedByName)==null?void 0:P.toLowerCase().includes(b))});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(Xt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(fe,{placeholder:"Search by title, request number, or user...",value:o,onChange:C=>l(C.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(Ue,{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(Ae,{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(C=>e.jsx("div",{className:`bg-white rounded-lg shadow-sm border-2 transition-all cursor-pointer hover:shadow-md ${C.isRead?"border-gray-200":"border-blue-300 bg-blue-50"}`,onClick:()=>v(C.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:[C.isRead?e.jsx(Ar,{className:"h-4 w-4 text-gray-400 flex-shrink-0"}):e.jsx(kt,{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:C.title}),!C.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:C.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(it,{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:C.initiatorName})]})]}),e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(it,{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:C.sharedByName})]})]}),e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(We,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Shared: ",xe(new Date(C.sharedAt),"MMM dd, yyyy HH:mm")]})]}),C.viewedAt&&e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(kt,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Viewed: ",xe(new Date(C.viewedAt),"MMM dd, yyyy HH:mm")]})]})]})]}),e.jsx(M,{variant:"outline",size:"sm",className:"w-full sm:w-auto flex-shrink-0",onClick:b=>{b.stopPropagation(),v(C.sharedSummaryId)},children:"View"})]})})},C.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)*g+1," to ",Math.min(c*g,h)," of ",h," summaries"]}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.jsx(M,{variant:"outline",size:"sm",onClick:()=>w(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:()=>w(c+1),disabled:c===m,className:"text-xs sm:text-sm",children:"Next"})]})]})]})]})})}function gv(){const{sharedSummaryId:t}=rr(),s=Hs(),[a,r]=x.useState(null),[n,i]=x.useState(!0);x.useEffect(()=>{if(!t){s("/shared-summaries");return}(async()=>{var m,u;try{i(!0);try{await am(t)}catch(p){console.warn("Failed to mark as viewed:",p)}const h=await sm(t);r(h)}catch(h){console.error("Failed to fetch summary details:",h),be.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(je,{className:"h-4 w-4 text-green-600"}):m==="rejected"?e.jsx(Je,{className:"h-4 w-4 text-red-600"}):m==="pending"||m==="in progress"?e.jsx(Ie,{className:"h-4 w-4 text-orange-600"}):e.jsx(Ae,{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(Ue,{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(xs,{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(ee,{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(Fs,{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:xe(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:xe(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(ee,{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(Fs,{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(Ae,{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 fv(){const{requestId:t}=rr(),s=Hs(),a=i=>{s(`/${i}`)},r=()=>{s("/new-request")},n=()=>{s("/login")};return e.jsx(Dt,{currentPage:"work-notes",onNavigate:a,onNewRequest:r,onLogout:n,children:e.jsx("div",{className:"h-full w-full overflow-hidden",children:e.jsx(mm,{requestId:t||""})})})}const Xi=x.createContext({});function Zi(t){const s=x.useRef(null);return s.current===null&&(s.current=t()),s.current}const Qi=typeof window<"u",um=Qi?x.useLayoutEffect:x.useEffect,sn=x.createContext(null);function Ji(t,s){t.indexOf(s)===-1&&t.push(s)}function eo(t,s){const a=t.indexOf(s);a>-1&&t.splice(a,1)}const Rs=(t,s,a)=>a>s?s:a<t?t:a;let to=()=>{};const Ds={},hm=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function pm(t){return typeof t=="object"&&t!==null}const xm=t=>/^0[^.\s]+$/u.test(t);function so(t){let s;return()=>(s===void 0&&(s=t()),s)}const ss=t=>t,yv=(t,s)=>a=>s(t(a)),or=(...t)=>t.reduce(yv),Xa=(t,s,a)=>{const r=s-t;return r===0?1:(a-t)/r};class ao{constructor(){this.subscriptions=[]}add(s){return Ji(this.subscriptions,s),()=>eo(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;i<n;i++){const o=this.subscriptions[i];o&&o(s,a,r)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const us=t=>t*1e3,ts=t=>t/1e3;function gm(t,s){return s?t*(1e3/s):0}const fm=(t,s,a)=>(((1-3*a+3*s)*t+(3*a-6*s))*t+3*s)*t,vv=1e-7,bv=12;function jv(t,s,a,r,n){let i,o,l=0;do o=s+(a-s)/2,i=fm(o,r,n)-t,i>0?a=o:s=o;while(Math.abs(i)>vv&&++l<bv);return o}function lr(t,s,a,r){if(t===s&&a===r)return ss;const n=i=>jv(i,0,1,t,a);return i=>i===0||i===1?i:fm(n(i),s,r)}const ym=t=>s=>s<=.5?t(2*s)/2:(2-t(2*(1-s)))/2,vm=t=>s=>1-t(1-s),bm=lr(.33,1.53,.69,.99),ro=vm(bm),jm=ym(ro),Nm=t=>(t*=2)<1?.5*ro(t):.5*(2-Math.pow(2,-10*(t-1))),no=t=>1-Math.sin(Math.acos(t)),wm=vm(no),Cm=ym(no),Nv=lr(.42,0,1,1),wv=lr(0,0,.58,1),Sm=lr(.42,0,.58,1),Cv=t=>Array.isArray(t)&&typeof t[0]!="number",Am=t=>Array.isArray(t)&&typeof t[0]=="number",Sv={linear:ss,easeIn:Nv,easeInOut:Sm,easeOut:wv,circIn:no,circInOut:Cm,circOut:wm,backIn:ro,backInOut:jm,backOut:bm,anticipate:Nm},Av=t=>typeof t=="string",fl=t=>{if(Am(t)){to(t.length===4);const[s,a,r,n]=t;return lr(s,a,r,n)}else if(Av(t))return Sv[t];return t},br=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function Tv(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 g=h&&n?a:r;return u&&o.add(m),g.has(m)||g.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 kv=40;function Tm(t,s){let a=!1,r=!0;const n={delta:0,timestamp:0,isProcessing:!1},i=()=>a=!0,o=br.reduce((C,b)=>(C[b]=Tv(i),C),{}),{setup:l,read:c,resolveKeyframes:d,preUpdate:m,update:u,preRender:h,render:p,postRender:g}=o,y=()=>{const C=Ds.useManualTiming?n.timestamp:performance.now();a=!1,Ds.useManualTiming||(n.delta=r?1e3/60:Math.max(Math.min(C-n.timestamp,kv),1)),n.timestamp=C,n.isProcessing=!0,l.process(n),c.process(n),d.process(n),m.process(n),u.process(n),h.process(n),p.process(n),g.process(n),n.isProcessing=!1,a&&s&&(r=!1,t(y))},v=()=>{a=!0,r=!0,n.isProcessing||t(y)};return{schedule:br.reduce((C,b)=>{const N=o[b];return C[b]=(R,E=!1,P=!1)=>(a||v(),N.schedule(R,E,P)),C},{}),cancel:C=>{for(let b=0;b<br.length;b++)o[br[b]].cancel(C)},state:n,steps:o}}const{schedule:Qe,cancel:Us,state:Rt,steps:kn}=Tm(typeof requestAnimationFrame<"u"?requestAnimationFrame:ss,!0);let kr;function Rv(){kr=void 0}const Ht={now:()=>(kr===void 0&&Ht.set(Rt.isProcessing||Ds.useManualTiming?Rt.timestamp:performance.now()),kr),set:t=>{kr=t,queueMicrotask(Rv)}},km=t=>s=>typeof s=="string"&&s.startsWith(t),io=km("--"),Dv=km("var(--"),oo=t=>Dv(t)?Pv.test(t.split("/*")[0].trim()):!1,Pv=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,Da={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},Za={...Da,transform:t=>Rs(0,1,t)},jr={...Da,default:1},Ba=t=>Math.round(t*1e5)/1e5,lo=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Ev(t){return t==null}const Mv=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,co=(t,s)=>a=>!!(typeof a=="string"&&Mv.test(a)&&a.startsWith(t)||s&&!Ev(a)&&Object.prototype.hasOwnProperty.call(a,s)),Rm=(t,s,a)=>r=>{if(typeof r!="string")return r;const[n,i,o,l]=r.match(lo);return{[t]:parseFloat(n),[s]:parseFloat(i),[a]:parseFloat(o),alpha:l!==void 0?parseFloat(l):1}},Iv=t=>Rs(0,255,t),Rn={...Da,transform:t=>Math.round(Iv(t))},ra={test:co("rgb","red"),parse:Rm("red","green","blue"),transform:({red:t,green:s,blue:a,alpha:r=1})=>"rgba("+Rn.transform(t)+", "+Rn.transform(s)+", "+Rn.transform(a)+", "+Ba(Za.transform(r))+")"};function Fv(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 ci={test:co("#"),parse:Fv,transform:ra.transform},cr=t=>({test:s=>typeof s=="string"&&s.endsWith(t)&&s.split(" ").length===1,parse:parseFloat,transform:s=>`${s}${t}`}),Ms=cr("deg"),hs=cr("%"),Ce=cr("px"),_v=cr("vh"),Lv=cr("vw"),yl={...hs,parse:t=>hs.parse(t)/100,transform:t=>hs.transform(t*100)},pa={test:co("hsl","hue"),parse:Rm("hue","saturation","lightness"),transform:({hue:t,saturation:s,lightness:a,alpha:r=1})=>"hsla("+Math.round(t)+", "+hs.transform(Ba(s))+", "+hs.transform(Ba(a))+", "+Ba(Za.transform(r))+")"},pt={test:t=>ra.test(t)||ci.test(t)||pa.test(t),parse:t=>ra.test(t)?ra.parse(t):pa.test(t)?pa.parse(t):ci.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?ra.transform(t):pa.transform(t),getAnimatableNone:t=>{const s=pt.parse(t);return s.alpha=0,pt.transform(s)}},Ov=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function $v(t){var s,a;return isNaN(t)&&typeof t=="string"&&(((s=t.match(lo))==null?void 0:s.length)||0)+(((a=t.match(Ov))==null?void 0:a.length)||0)>0}const Dm="number",Pm="color",Uv="var",Bv="var(",vl="${}",Vv=/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 Qa(t){const s=t.toString(),a=[],r={color:[],number:[],var:[]},n=[];let i=0;const l=s.replace(Vv,c=>(pt.test(c)?(r.color.push(i),n.push(Pm),a.push(pt.parse(c))):c.startsWith(Bv)?(r.var.push(i),n.push(Uv),a.push(c)):(r.number.push(i),n.push(Dm),a.push(parseFloat(c))),++i,vl)).split(vl);return{values:a,split:l,indexes:r,types:n}}function Em(t){return Qa(t).values}function Mm(t){const{split:s,types:a}=Qa(t),r=s.length;return n=>{let i="";for(let o=0;o<r;o++)if(i+=s[o],n[o]!==void 0){const l=a[o];l===Dm?i+=Ba(n[o]):l===Pm?i+=pt.transform(n[o]):i+=n[o]}return i}}const zv=t=>typeof t=="number"?0:pt.test(t)?pt.getAnimatableNone(t):t;function Hv(t){const s=Em(t);return Mm(t)(s.map(zv))}const Bs={test:$v,parse:Em,createTransformer:Mm,getAnimatableNone:Hv};function Dn(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 qv({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=Dn(c,l,t+1/3),i=Dn(c,l,t),o=Dn(c,l,t-1/3)}return{red:Math.round(n*255),green:Math.round(i*255),blue:Math.round(o*255),alpha:r}}function _r(t,s){return a=>a>0?s:t}const at=(t,s,a)=>t+(s-t)*a,Pn=(t,s,a)=>{const r=t*t,n=a*(s*s-r)+r;return n<0?0:Math.sqrt(n)},Wv=[ci,ra,pa],Kv=t=>Wv.find(s=>s.test(t));function bl(t){const s=Kv(t);if(!s)return!1;let a=s.parse(t);return s===pa&&(a=qv(a)),a}const jl=(t,s)=>{const a=bl(t),r=bl(s);if(!a||!r)return _r(t,s);const n={...a};return i=>(n.red=Pn(a.red,r.red,i),n.green=Pn(a.green,r.green,i),n.blue=Pn(a.blue,r.blue,i),n.alpha=at(a.alpha,r.alpha,i),ra.transform(n))},di=new Set(["none","hidden"]);function Gv(t,s){return di.has(t)?a=>a<=0?t:s:a=>a>=1?s:t}function Yv(t,s){return a=>at(t,s,a)}function mo(t){return typeof t=="number"?Yv:typeof t=="string"?oo(t)?_r:pt.test(t)?jl:Qv:Array.isArray(t)?Im:typeof t=="object"?pt.test(t)?jl:Xv:_r}function Im(t,s){const a=[...t],r=a.length,n=t.map((i,o)=>mo(i)(i,s[o]));return i=>{for(let o=0;o<r;o++)a[o]=n[o](i);return a}}function Xv(t,s){const a={...t,...s},r={};for(const n in a)t[n]!==void 0&&s[n]!==void 0&&(r[n]=mo(t[n])(t[n],s[n]));return n=>{for(const i in r)a[i]=r[i](n);return a}}function Zv(t,s){const a=[],r={color:0,var:0,number:0};for(let n=0;n<s.values.length;n++){const i=s.types[n],o=t.indexes[i][r[i]],l=t.values[o]??0;a[n]=l,r[i]++}return a}const Qv=(t,s)=>{const a=Bs.createTransformer(s),r=Qa(t),n=Qa(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?di.has(t)&&!n.values.length||di.has(s)&&!r.values.length?Gv(t,s):or(Im(Zv(r,n),n.values),a):_r(t,s)};function Fm(t,s,a){return typeof t=="number"&&typeof s=="number"&&typeof a=="number"?at(t,s,a):mo(t)(t,s)}const Jv=t=>{const s=({timestamp:a})=>t(a);return{start:(a=!0)=>Qe.update(s,a),stop:()=>Us(s),now:()=>Rt.isProcessing?Rt.timestamp:Ht.now()}},_m=(t,s,a=10)=>{let r="";const n=Math.max(Math.round(s/a),2);for(let i=0;i<n;i++)r+=Math.round(t(i/(n-1))*1e4)/1e4+", ";return`linear(${r.substring(0,r.length-2)})`},Lr=2e4;function uo(t){let s=0;const a=50;let r=t.next(s);for(;!r.done&&s<Lr;)s+=a,r=t.next(s);return s>=Lr?1/0:s}function eb(t,s=100,a){const r=a({...t,keyframes:[0,s]}),n=Math.min(uo(r),Lr);return{type:"keyframes",ease:i=>r.next(n*i).value/s,duration:ts(n)}}const tb=5;function Lm(t,s,a){const r=Math.max(s-tb,0);return gm(a-t(r),s-r)}const rt={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},En=.001;function sb({duration:t=rt.duration,bounce:s=rt.bounce,velocity:a=rt.velocity,mass:r=rt.mass}){let n,i,o=1-s;o=Rs(rt.minDamping,rt.maxDamping,o),t=Rs(rt.minDuration,rt.maxDuration,ts(t)),o<1?(n=d=>{const m=d*o,u=m*t,h=m-a,p=mi(d,o),g=Math.exp(-u);return En-h/p*g},i=d=>{const u=d*o*t,h=u*a+a,p=Math.pow(o,2)*Math.pow(d,2)*t,g=Math.exp(-u),y=mi(Math.pow(d,2),o);return(-n(d)+En>0?-1:1)*((h-p)*g)/y}):(n=d=>{const m=Math.exp(-d*t),u=(d-a)*t+1;return-En+m*u},i=d=>{const m=Math.exp(-d*t),u=(a-d)*(t*t);return m*u});const l=5/t,c=rb(n,i,l);if(t=us(t),isNaN(c))return{stiffness:rt.stiffness,damping:rt.damping,duration:t};{const d=Math.pow(c,2)*r;return{stiffness:d,damping:o*2*Math.sqrt(r*d),duration:t}}}const ab=12;function rb(t,s,a){let r=a;for(let n=1;n<ab;n++)r=r-t(r)/s(r);return r}function mi(t,s){return t*Math.sqrt(1-s*s)}const nb=["duration","bounce"],ib=["stiffness","damping","mass"];function Nl(t,s){return s.some(a=>t[a]!==void 0)}function ob(t){let s={velocity:rt.velocity,stiffness:rt.stiffness,damping:rt.damping,mass:rt.mass,isResolvedFromDuration:!1,...t};if(!Nl(t,ib)&&Nl(t,nb))if(t.visualDuration){const a=t.visualDuration,r=2*Math.PI/(a*1.2),n=r*r,i=2*Rs(.05,1,1-(t.bounce||0))*Math.sqrt(n);s={...s,mass:rt.mass,stiffness:n,damping:i}}else{const a=sb(t);s={...s,...a,mass:rt.mass},s.isResolvedFromDuration=!0}return s}function Or(t=rt.visualDuration,s=rt.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:p}=ob({...a,velocity:-ts(a.velocity||0)}),g=h||0,y=d/(2*Math.sqrt(c*m)),v=o-i,w=ts(Math.sqrt(c/m)),f=Math.abs(v)<5;r||(r=f?rt.restSpeed.granular:rt.restSpeed.default),n||(n=f?rt.restDelta.granular:rt.restDelta.default);let C;if(y<1){const N=mi(w,y);C=R=>{const E=Math.exp(-y*w*R);return o-E*((g+y*w*v)/N*Math.sin(N*R)+v*Math.cos(N*R))}}else if(y===1)C=N=>o-Math.exp(-w*N)*(v+(g+w*v)*N);else{const N=w*Math.sqrt(y*y-1);C=R=>{const E=Math.exp(-y*w*R),P=Math.min(N*R,300);return o-E*((g+y*w*v)*Math.sinh(P)+N*v*Math.cosh(P))/N}}const b={calculatedDuration:p&&u||null,next:N=>{const R=C(N);if(p)l.done=N>=u;else{let E=N===0?g:0;y<1&&(E=N===0?us(g):Lm(C,N,R));const P=Math.abs(E)<=r,I=Math.abs(o-R)<=n;l.done=P&&I}return l.value=l.done?o:R,l},toString:()=>{const N=Math.min(uo(b),Lr),R=_m(E=>b.next(N*E).value,N,30);return N+"ms "+R},toTransition:()=>{}};return b}Or.applyToOptions=t=>{const s=eb(t,100,Or);return t.ease=s.ease,t.duration=us(s.duration),t.type="keyframes",t};function ui({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},p=P=>l!==void 0&&P<l||c!==void 0&&P>c,g=P=>l===void 0?c:c===void 0||Math.abs(l-P)<Math.abs(c-P)?l:c;let y=a*s;const v=u+y,w=o===void 0?v:o(v);w!==v&&(y=w-u);const f=P=>-y*Math.exp(-P/r),C=P=>w+f(P),b=P=>{const I=f(P),j=C(P);h.done=Math.abs(I)<=d,h.value=h.done?w:j};let N,R;const E=P=>{p(h.value)&&(N=P,R=Or({keyframes:[h.value,g(h.value)],velocity:Lm(C,P,h.value),damping:n,stiffness:i,restDelta:d,restSpeed:m}))};return E(0),{calculatedDuration:null,next:P=>{let I=!1;return!R&&N===void 0&&(I=!0,b(P),E(P)),N!==void 0&&P>=N?R.next(P-N):(!I&&b(P),h)}}}function lb(t,s,a){const r=[],n=a||Ds.mix||Fm,i=t.length-1;for(let o=0;o<i;o++){let l=n(t[o],t[o+1]);if(s){const c=Array.isArray(s)?s[o]||ss:s;l=or(c,l)}r.push(l)}return r}function cb(t,s,{clamp:a=!0,ease:r,mixer:n}={}){const i=t.length;if(to(i===s.length),i===1)return()=>s[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=lb(s,r,n),c=l.length,d=m=>{if(o&&m<t[0])return s[0];let u=0;if(c>1)for(;u<t.length-2&&!(m<t[u+1]);u++);const h=Xa(t[u],t[u+1],m);return l[u](h)};return a?m=>d(Rs(t[0],t[i-1],m)):d}function db(t,s){const a=t[t.length-1];for(let r=1;r<=s;r++){const n=Xa(0,s,r);t.push(at(a,1,n))}}function mb(t){const s=[0];return db(s,t.length-1),s}function ub(t,s){return t.map(a=>a*s)}function hb(t,s){return t.map(()=>s||Sm).splice(0,t.length-1)}function Va({duration:t=300,keyframes:s,times:a,ease:r="easeInOut"}){const n=Cv(r)?r.map(fl):fl(r),i={done:!1,value:s[0]},o=ub(a&&a.length===s.length?a:mb(s),t),l=cb(o,s,{ease:Array.isArray(n)?n:hb(s,n)});return{calculatedDuration:t,next:c=>(i.value=l(c),i.done=c>=t,i)}}const pb=t=>t!==null;function ho(t,{repeat:s,repeatType:a="loop"},r,n=1){const i=t.filter(pb),l=n<0||s&&a!=="loop"&&s%2===1?0:i.length-1;return!l||r===void 0?i[l]:r}const xb={decay:ui,inertia:ui,tween:Va,keyframes:Va,spring:Or};function Om(t){typeof t.type=="string"&&(t.type=xb[t.type])}class po{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 gb=t=>t/100;class xo extends po{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!==Ht.now()&&this.tick(Ht.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;Om(s);const{type:a=Va,repeat:r=0,repeatDelay:n=0,repeatType:i,velocity:o=0}=s;let{keyframes:l}=s;const c=a||Va;c!==Va&&typeof l[0]!="number"&&(this.mixKeyframes=or(gb,Fm(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=uo(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:p,type:g,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 w=this.currentTime-d*(this.playbackSpeed>=0?1:-1),f=this.playbackSpeed>=0?w<0:w>n;this.currentTime=Math.max(w,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=n);let C=this.currentTime,b=r;if(u){const P=Math.min(this.currentTime,n)/l;let I=Math.floor(P),j=P%1;!j&&P>=1&&(j=1),j===1&&I--,I=Math.min(I,u+1),!!(I%2)&&(h==="reverse"?(j=1-j,p&&(j-=p/l)):h==="mirror"&&(b=o)),C=Rs(0,1,j)*l}const N=f?{done:!1,value:m[0]}:b.next(C);i&&(N.value=i(N.value));let{done:R}=N;!f&&c!==null&&(R=this.playbackSpeed>=0?this.currentTime>=n:this.currentTime<=0);const E=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&R);return E&&g!==ui&&(N.value=ho(m,this.options,v,this.speed)),y&&y(N.value),E&&this.finish(),N}then(s,a){return this.finished.then(s,a)}get duration(){return ts(this.calculatedDuration)}get iterationDuration(){const{delay:s=0}=this.options||{};return this.duration+ts(s)}get time(){return ts(this.currentTime)}set time(s){var a;s=us(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(Ht.now());const a=this.playbackSpeed!==s;this.playbackSpeed=s,a&&(this.time=ts(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(Ht.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 fb(t){for(let s=1;s<t.length;s++)t[s]??(t[s]=t[s-1])}const na=t=>t*180/Math.PI,hi=t=>{const s=na(Math.atan2(t[1],t[0]));return pi(s)},yb={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:hi,rotateZ:hi,skewX:t=>na(Math.atan(t[1])),skewY:t=>na(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},pi=t=>(t=t%360,t<0&&(t+=360),t),wl=hi,Cl=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),Sl=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),vb={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Cl,scaleY:Sl,scale:t=>(Cl(t)+Sl(t))/2,rotateX:t=>pi(na(Math.atan2(t[6],t[5]))),rotateY:t=>pi(na(Math.atan2(-t[2],t[0]))),rotateZ:wl,rotate:wl,skewX:t=>na(Math.atan(t[4])),skewY:t=>na(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function xi(t){return t.includes("scale")?1:0}function gi(t,s){if(!t||t==="none")return xi(s);const a=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,n;if(a)r=vb,n=a;else{const l=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=yb,n=l}if(!n)return xi(s);const i=r[s],o=n[1].split(",").map(jb);return typeof i=="function"?i(o):o[i]}const bb=(t,s)=>{const{transform:a="none"}=getComputedStyle(t);return gi(a,s)};function jb(t){return parseFloat(t.trim())}const Pa=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Ea=new Set(Pa),Al=t=>t===Da||t===Ce,Nb=new Set(["x","y","z"]),wb=Pa.filter(t=>!Nb.has(t));function Cb(t){const s=[];return wb.forEach(a=>{const r=t.getValue(a);r!==void 0&&(s.push([a,r.get()]),r.set(a.startsWith("scale")?1:0))}),s}const oa={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})=>gi(s,"x"),y:(t,{transform:s})=>gi(s,"y")};oa.translateX=oa.x;oa.translateY=oa.y;const la=new Set;let fi=!1,yi=!1,vi=!1;function $m(){if(yi){const t=Array.from(la).filter(r=>r.needsMeasurement),s=new Set(t.map(r=>r.element)),a=new Map;s.forEach(r=>{const n=Cb(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)})}yi=!1,fi=!1,la.forEach(t=>t.complete(vi)),la.clear()}function Um(){la.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(yi=!0)})}function Sb(){vi=!0,Um(),$m(),vi=!1}class go{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?(la.add(this),fi||(fi=!0,Qe.read(Um),Qe.resolveKeyframes($m))):(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])}fb(s)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(s=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,s),la.delete(this)}cancel(){this.state==="scheduled"&&(la.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Ab=t=>t.startsWith("--");function Tb(t,s,a){Ab(s)?t.style.setProperty(s,a):t.style[s]=a}const kb=so(()=>window.ScrollTimeline!==void 0),Rb={};function Db(t,s){const a=so(t);return()=>Rb[s]??a()}const Bm=Db(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Ua=([t,s,a,r])=>`cubic-bezier(${t}, ${s}, ${a}, ${r})`,Tl={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Ua([0,.65,.55,1]),circOut:Ua([.55,0,1,.45]),backIn:Ua([.31,.01,.66,-.59]),backOut:Ua([.33,1.53,.69,.99])};function Vm(t,s){if(t)return typeof t=="function"?Bm()?_m(t,s):"ease-out":Am(t)?Ua(t):Array.isArray(t)?t.map(a=>Vm(a,s)||Tl.easeOut):Tl[t]}function Pb(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=Vm(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 zm(t){return typeof t=="function"&&"applyToOptions"in t}function Eb({type:t,...s}){return zm(t)&&Bm()?t.applyToOptions(s):(s.duration??(s.duration=300),s.ease??(s.ease="easeOut"),s)}class Mb extends po{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,to(typeof s.type!="string");const d=Eb(s);this.animation=Pb(a,r,n,d,i),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const m=ho(n,this.options,l,this.speed);this.updateMotionValue?this.updateMotionValue(m):Tb(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 ts(Number(s))}get iterationDuration(){const{delay:s=0}=this.options||{};return this.duration+ts(s)}get time(){return ts(Number(this.animation.currentTime)||0)}set time(s){this.finishedTime=null,this.animation.currentTime=us(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&&kb()?(this.animation.timeline=s,ss):a(this)}}const Hm={anticipate:Nm,backInOut:jm,circInOut:Cm};function Ib(t){return t in Hm}function Fb(t){typeof t.ease=="string"&&Ib(t.ease)&&(t.ease=Hm[t.ease])}const kl=10;class _b extends Mb{constructor(s){Fb(s),Om(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 xo({...o,autoplay:!1}),c=us(this.finishedTime??this.time);a.setWithVelocity(l.sample(c-kl).value,l.sample(c).value,kl),l.stop()}}const Rl=(t,s)=>s==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(Bs.test(t)||t==="0")&&!t.startsWith("url("));function Lb(t){const s=t[0];if(t.length===1)return!0;for(let a=0;a<t.length;a++)if(t[a]!==s)return!0}function Ob(t,s,a,r){const n=t[0];if(n===null)return!1;if(s==="display"||s==="visibility")return!0;const i=t[t.length-1],o=Rl(n,s),l=Rl(i,s);return!o||!l?!1:Lb(t)||(a==="spring"||zm(a))&&r}function bi(t){t.duration=0,t.type="keyframes"}const $b=new Set(["opacity","clipPath","filter","transform"]),Ub=so(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function Bb(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 Ub()&&a&&$b.has(a)&&(a!=="transform"||!d)&&!c&&!r&&n!=="mirror"&&i!==0&&o!=="inertia"}const Vb=40;class zb extends po{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 g;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=Ht.now();const h={autoplay:s,delay:a,type:r,repeat:n,repeatDelay:i,repeatType:o,name:c,motionValue:d,element:m,...u},p=(m==null?void 0:m.KeyframeResolver)||go;this.keyframeResolver=new p(l,(y,v,w)=>this.onKeyframesResolved(y,v,h,!w),c,d,m),(g=this.keyframeResolver)==null||g.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=Ht.now(),Ob(s,i,o,l)||((Ds.instantAnimations||!c)&&(m==null||m(ho(s,r,a))),s[0]=s[s.length-1],bi(r),r.repeat=0);const h={startTime:n?this.resolvedAt?this.resolvedAt-this.createdAt>Vb?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:a,...r,keyframes:s},p=!d&&Bb(h)?new _b({...h,element:h.motionValue.owner.current}):new xo(h);p.finished.then(()=>this.notifyFinished()).catch(ss),this.pendingTimeline&&(this.stopTimeline=p.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=p}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(),Sb()),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 Hb=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function qb(t){const s=Hb.exec(t);if(!s)return[,];const[,a,r,n]=s;return[`--${a??r}`,n]}function qm(t,s,a=1){const[r,n]=qb(t);if(!r)return;const i=window.getComputedStyle(s).getPropertyValue(r);if(i){const o=i.trim();return hm(o)?parseFloat(o):o}return oo(n)?qm(n,s,a+1):n}function fo(t,s){return(t==null?void 0:t[s])??(t==null?void 0:t.default)??t}const Wm=new Set(["width","height","top","left","right","bottom",...Pa]),Wb={test:t=>t==="auto",parse:t=>t},Km=t=>s=>s.test(t),Gm=[Da,Ce,hs,Ms,Lv,_v,Wb],Dl=t=>Gm.find(Km(t));function Kb(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||xm(t):!0}const Gb=new Set(["brightness","contrast","saturate","opacity"]);function Yb(t){const[s,a]=t.slice(0,-1).split("(");if(s==="drop-shadow")return t;const[r]=a.match(lo)||[];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 Xb=/\b([a-z-]*)\(.*?\)/gu,ji={...Bs,getAnimatableNone:t=>{const s=t.match(Xb);return s?s.map(Yb).join(" "):t}},Pl={...Da,transform:Math.round},Zb={rotate:Ms,rotateX:Ms,rotateY:Ms,rotateZ:Ms,scale:jr,scaleX:jr,scaleY:jr,scaleZ:jr,skew:Ms,skewX:Ms,skewY:Ms,distance:Ce,translateX:Ce,translateY:Ce,translateZ:Ce,x:Ce,y:Ce,z:Ce,perspective:Ce,transformPerspective:Ce,opacity:Za,originX:yl,originY:yl,originZ:Ce},yo={borderWidth:Ce,borderTopWidth:Ce,borderRightWidth:Ce,borderBottomWidth:Ce,borderLeftWidth:Ce,borderRadius:Ce,radius:Ce,borderTopLeftRadius:Ce,borderTopRightRadius:Ce,borderBottomRightRadius:Ce,borderBottomLeftRadius:Ce,width:Ce,maxWidth:Ce,height:Ce,maxHeight:Ce,top:Ce,right:Ce,bottom:Ce,left:Ce,padding:Ce,paddingTop:Ce,paddingRight:Ce,paddingBottom:Ce,paddingLeft:Ce,margin:Ce,marginTop:Ce,marginRight:Ce,marginBottom:Ce,marginLeft:Ce,backgroundPositionX:Ce,backgroundPositionY:Ce,...Zb,zIndex:Pl,fillOpacity:Za,strokeOpacity:Za,numOctaves:Pl},Qb={...yo,color:pt,backgroundColor:pt,outlineColor:pt,fill:pt,stroke:pt,borderColor:pt,borderTopColor:pt,borderRightColor:pt,borderBottomColor:pt,borderLeftColor:pt,filter:ji,WebkitFilter:ji},Ym=t=>Qb[t];function Xm(t,s){let a=Ym(t);return a!==ji&&(a=Bs),a.getAnimatableNone?a.getAnimatableNone(s):void 0}const Jb=new Set(["auto","none","0"]);function ej(t,s,a){let r=0,n;for(;r<t.length&&!n;){const i=t[r];typeof i=="string"&&!Jb.has(i)&&Qa(i).values.length&&(n=t[r]),r++}if(n&&a)for(const i of s)t[i]=Xm(a,n)}class tj extends go{constructor(s,a,r,n,i){super(s,a,r,n,i,!0)}readKeyframes(){const{unresolvedKeyframes:s,element:a,name:r}=this;if(!a||!a.current)return;super.readKeyframes();for(let c=0;c<s.length;c++){let d=s[c];if(typeof d=="string"&&(d=d.trim(),oo(d))){const m=qm(d,a.current);m!==void 0&&(s[c]=m),c===s.length-1&&(this.finalKeyframe=d)}}if(this.resolveNoneKeyframes(),!Wm.has(r)||s.length!==2)return;const[n,i]=s,o=Dl(n),l=Dl(i);if(o!==l)if(Al(o)&&Al(l))for(let c=0;c<s.length;c++){const d=s[c];typeof d=="string"&&(s[c]=parseFloat(d))}else oa[r]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:s,name:a}=this,r=[];for(let n=0;n<s.length;n++)(s[n]===null||Kb(s[n]))&&r.push(n);r.length&&ej(s,r,a)}measureInitialState(){const{element:s,unresolvedKeyframes:a,name:r}=this;if(!s||!s.current)return;r==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=oa[r](s.measureViewportBox(),window.getComputedStyle(s.current)),a[0]=this.measuredOrigin;const n=a[a.length-1];n!==void 0&&s.getValue(r,n).jump(n,!1)}measureEndState(){var l;const{element:s,name:a,unresolvedKeyframes:r}=this;if(!s||!s.current)return;const n=s.getValue(a);n&&n.jump(this.measuredOrigin,!1);const i=r.length-1,o=r[i];r[i]=oa[a](s.measureViewportBox(),window.getComputedStyle(s.current)),o!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=o),(l=this.removedTransforms)!=null&&l.length&&this.removedTransforms.forEach(([c,d])=>{s.getValue(c).set(d)}),this.resolveNoneKeyframes()}}function sj(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 Zm=(t,s)=>s&&typeof t=="number"?s.transform(t):t;function Qm(t){return pm(t)&&"offsetHeight"in t}const El=30,aj=t=>!isNaN(parseFloat(t));class rj{constructor(s,a={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=r=>{var i;const n=Ht.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=Ht.now(),this.canTrackVelocity===null&&s!==void 0&&(this.canTrackVelocity=aj(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 ao);const r=this.events[s].add(a);return s==="change"?()=>{r(),Qe.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=Ht.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||s-this.updatedAt>El)return 0;const a=Math.min(this.updatedAt-this.prevUpdatedAt,El);return gm(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 wa(t,s){return new rj(t,s)}const{schedule:vo}=Tm(queueMicrotask,!1),rs={x:!1,y:!1};function Jm(){return rs.x||rs.y}function nj(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 eu(t,s){const a=sj(t),r=new AbortController,n={passive:!0,...s,signal:r.signal};return[a,n,()=>r.abort()]}function Ml(t){return!(t.pointerType==="touch"||Jm())}function ij(t,s,a={}){const[r,n,i]=eu(t,a),o=l=>{if(!Ml(l))return;const{target:c}=l,d=s(c,l);if(typeof d!="function"||!c)return;const m=u=>{Ml(u)&&(d(u),c.removeEventListener("pointerleave",m))};c.addEventListener("pointerleave",m,n)};return r.forEach(l=>{l.addEventListener("pointerenter",o,n)}),i}const tu=(t,s)=>s?t===s?!0:tu(t,s.parentElement):!1,bo=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,oj=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function lj(t){return oj.has(t.tagName)||t.tabIndex!==-1}const Rr=new WeakSet;function Il(t){return s=>{s.key==="Enter"&&t(s)}}function Mn(t,s){t.dispatchEvent(new PointerEvent("pointer"+s,{isPrimary:!0,bubbles:!0}))}const cj=(t,s)=>{const a=t.currentTarget;if(!a)return;const r=Il(()=>{if(Rr.has(a))return;Mn(a,"down");const n=Il(()=>{Mn(a,"up")}),i=()=>Mn(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 Fl(t){return bo(t)&&!Jm()}function dj(t,s,a={}){const[r,n,i]=eu(t,a),o=l=>{const c=l.currentTarget;if(!Fl(l))return;Rr.add(c);const d=s(c,l),m=(p,g)=>{window.removeEventListener("pointerup",u),window.removeEventListener("pointercancel",h),Rr.has(c)&&Rr.delete(c),Fl(p)&&typeof d=="function"&&d(p,{success:g})},u=p=>{m(p,c===window||c===document||a.useGlobalTarget||tu(c,p.target))},h=p=>{m(p,!1)};window.addEventListener("pointerup",u,n),window.addEventListener("pointercancel",h,n)};return r.forEach(l=>{(a.useGlobalTarget?window:l).addEventListener("pointerdown",o,n),Qm(l)&&(l.addEventListener("focus",d=>cj(d,n)),!lj(l)&&!l.hasAttribute("tabindex")&&(l.tabIndex=0))}),i}function su(t){return pm(t)&&"ownerSVGElement"in t}function mj(t){return su(t)&&t.tagName==="svg"}const Pt=t=>!!(t&&t.getVelocity),uj=[...Gm,pt,Bs],hj=t=>uj.find(Km(t)),jo=x.createContext({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});function _l(t,s){if(typeof t=="function")return t(s);t!=null&&(t.current=s)}function pj(...t){return s=>{let a=!1;const r=t.map(n=>{const i=_l(n,s);return!a&&typeof i=="function"&&(a=!0),i});if(a)return()=>{for(let n=0;n<r.length;n++){const i=r[n];typeof i=="function"?i():_l(t[n],null)}}}}function xj(...t){return x.useCallback(pj(...t),t)}class gj extends x.Component{getSnapshotBeforeUpdate(s){const a=this.props.childRef.current;if(a&&s.isPresent&&!this.props.isPresent){const r=a.offsetParent,n=Qm(r)&&r.offsetWidth||0,i=this.props.sizeRef.current;i.height=a.offsetHeight||0,i.width=a.offsetWidth||0,i.top=a.offsetTop,i.left=a.offsetLeft,i.right=n-i.width-i.left}return null}componentDidUpdate(){}render(){return this.props.children}}function fj({children:t,isPresent:s,anchorX:a,root:r}){const n=x.useId(),i=x.useRef(null),o=x.useRef({width:0,height:0,top:0,left:0,right:0}),{nonce:l}=x.useContext(jo),c=xj(i,t==null?void 0:t.ref);return x.useInsertionEffect(()=>{const{width:d,height:m,top:u,left:h,right:p}=o.current;if(s||!i.current||!d||!m)return;const g=a==="left"?`left: ${h}`:`right: ${p}`;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;
|
||
${g}px !important;
|
||
top: ${u}px !important;
|
||
}
|
||
`),()=>{v.contains(y)&&v.removeChild(y)}},[s]),e.jsx(gj,{isPresent:s,childRef:i,sizeRef:o,children:x.cloneElement(t,{ref:c})})}const yj=({children:t,initial:s,isPresent:a,onExitComplete:r,custom:n,presenceAffectsLayout:i,mode:o,anchorX:l,root:c})=>{const d=Zi(vj),m=x.useId();let u=!0,h=x.useMemo(()=>(u=!1,{id:m,initial:s,isPresent:a,custom:n,onExitComplete:p=>{d.set(p,!0);for(const g of d.values())if(!g)return;r&&r()},register:p=>(d.set(p,!1),()=>d.delete(p))}),[a,d,r]);return i&&u&&(h={...h}),x.useMemo(()=>{d.forEach((p,g)=>d.set(g,!1))},[a]),x.useEffect(()=>{!a&&!d.size&&r&&r()},[a]),o==="popLayout"&&(t=e.jsx(fj,{isPresent:a,anchorX:l,root:c,children:t})),e.jsx(sn.Provider,{value:h,children:t})};function vj(){return new Map}function au(t=!0){const s=x.useContext(sn);if(s===null)return[!0,null];const{isPresent:a,onExitComplete:r,register:n}=s,i=x.useId();x.useEffect(()=>{if(t)return n(i)},[t]);const o=x.useCallback(()=>t&&r&&r(i),[i,r,t]);return!a&&r?[!1,o]:[!0]}const Nr=t=>t.key||"";function Ll(t){const s=[];return x.Children.forEach(t,a=>{x.isValidElement(a)&&s.push(a)}),s}const an=({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]=au(o),u=x.useMemo(()=>Ll(t),[t]),h=o&&!d?[]:u.map(Nr),p=x.useRef(!0),g=x.useRef(u),y=Zi(()=>new Map),[v,w]=x.useState(u),[f,C]=x.useState(u);um(()=>{p.current=!1,g.current=u;for(let R=0;R<f.length;R++){const E=Nr(f[R]);h.includes(E)?y.delete(E):y.get(E)!==!0&&y.set(E,!1)}},[f,h.length,h.join("-")]);const b=[];if(u!==v){let R=[...u];for(let E=0;E<f.length;E++){const P=f[E],I=Nr(P);h.includes(I)||(R.splice(E,0,P),b.push(P))}return i==="wait"&&b.length&&(R=b),C(Ll(R)),w(u),null}const{forceRender:N}=x.useContext(Xi);return e.jsx(e.Fragment,{children:f.map(R=>{const E=Nr(R),P=o&&!d?!1:u===f||h.includes(E),I=()=>{if(y.has(E))y.set(E,!0);else return;let j=!0;y.forEach(k=>{k||(j=!1)}),j&&(N==null||N(),C(g.current),o&&(m==null||m()),r&&r())};return e.jsx(yj,{isPresent:P,initial:!p.current||a?void 0:!1,custom:s,presenceAffectsLayout:n,mode:i,root:c,onExitComplete:P?void 0:I,anchorX:l,children:R},E)})})},ru=x.createContext({strict:!1}),Ol={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"]},Ca={};for(const t in Ol)Ca[t]={isEnabled:s=>Ol[t].some(a=>!!s[a])};function bj(t){for(const s in t)Ca[s]={...Ca[s],...t[s]}}const jj=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 $r(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||jj.has(t)}let nu=t=>!$r(t);function Nj(t){typeof t=="function"&&(nu=s=>s.startsWith("on")?!$r(s):t(s))}try{Nj(require("@emotion/is-prop-valid").default)}catch{}function wj(t,s,a){const r={};for(const n in t)n==="values"&&typeof t.values=="object"||(nu(n)||a===!0&&$r(n)||!s&&!$r(n)||t.draggable&&n.startsWith("onDrag"))&&(r[n]=t[n]);return r}const rn=x.createContext({});function nn(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function Ja(t){return typeof t=="string"||Array.isArray(t)}const No=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],wo=["initial",...No];function on(t){return nn(t.animate)||wo.some(s=>Ja(t[s]))}function iu(t){return!!(on(t)||t.variants)}function Cj(t,s){if(on(t)){const{initial:a,animate:r}=t;return{initial:a===!1||Ja(a)?a:void 0,animate:Ja(r)?r:void 0}}return t.inherit!==!1?s:{}}function Sj(t){const{initial:s,animate:a}=Cj(t,x.useContext(rn));return x.useMemo(()=>({initial:s,animate:a}),[$l(s),$l(a)])}function $l(t){return Array.isArray(t)?t.join(" "):t}const er={};function Aj(t){for(const s in t)er[s]=t[s],io(s)&&(er[s].isCSSVariable=!0)}function ou(t,{layout:s,layoutId:a}){return Ea.has(t)||t.startsWith("origin")||(s||a!==void 0)&&(!!er[t]||t==="opacity")}const Tj={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},kj=Pa.length;function Rj(t,s,a){let r="",n=!0;for(let i=0;i<kj;i++){const o=Pa[i],l=t[o];if(l===void 0)continue;let c=!0;if(typeof l=="number"?c=l===(o.startsWith("scale")?1:0):c=parseFloat(l)===0,!c||a){const d=Zm(l,yo[o]);if(!c){n=!1;const m=Tj[o]||o;r+=`${m}(${d}) `}a&&(s[o]=d)}}return r=r.trim(),a?r=a(s,n?"":r):n&&(r="none"),r}function Co(t,s,a){const{style:r,vars:n,transformOrigin:i}=t;let o=!1,l=!1;for(const c in s){const d=s[c];if(Ea.has(c)){o=!0;continue}else if(io(c)){n[c]=d;continue}else{const m=Zm(d,yo[c]);c.startsWith("origin")?(l=!0,i[c]=m):r[c]=m}}if(s.transform||(o||a?r.transform=Rj(s,t.transform,a):r.transform&&(r.transform="none")),l){const{originX:c="50%",originY:d="50%",originZ:m=0}=i;r.transformOrigin=`${c} ${d} ${m}`}}const So=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function lu(t,s,a){for(const r in s)!Pt(s[r])&&!ou(r,a)&&(t[r]=s[r])}function Dj({transformTemplate:t},s){return x.useMemo(()=>{const a=So();return Co(a,s,t),Object.assign({},a.vars,a.style)},[s])}function Pj(t,s){const a=t.style||{},r={};return lu(r,a,t),Object.assign(r,Dj(t,s)),r}function Ej(t,s){const a={},r=Pj(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 Mj={offset:"stroke-dashoffset",array:"stroke-dasharray"},Ij={offset:"strokeDashoffset",array:"strokeDasharray"};function Fj(t,s,a=1,r=0,n=!0){t.pathLength=1;const i=n?Mj:Ij;t[i.offset]=Ce.transform(-r);const o=Ce.transform(s),l=Ce.transform(a);t[i.array]=`${o} ${l}`}function cu(t,{attrX:s,attrY:a,attrScale:r,pathLength:n,pathSpacing:i=1,pathOffset:o=0,...l},c,d,m){if(Co(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&&Fj(u,n,i,o,!1)}const du=()=>({...So(),attrs:{}}),mu=t=>typeof t=="string"&&t.toLowerCase()==="svg";function _j(t,s,a,r){const n=x.useMemo(()=>{const i=du();return cu(i,s,mu(r),t.transformTemplate,t.style),{...i.attrs,style:{...i.style}}},[s]);if(t.style){const i={};lu(i,t.style,t),n.style={...i,...n.style}}return n}const Lj=["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 Ao(t){return typeof t!="string"||t.includes("-")?!1:!!(Lj.indexOf(t)>-1||/[A-Z]/u.test(t))}function Oj(t,s,a,{latestValues:r},n,i=!1){const l=(Ao(t)?_j:Ej)(s,r,n,t),c=wj(s,typeof t=="string",i),d=t!==x.Fragment?{...c,...l,ref:a}:{},{children:m}=s,u=x.useMemo(()=>Pt(m)?m.get():m,[m]);return x.createElement(t,{...d,children:u})}function Ul(t){const s=[{},{}];return t==null||t.values.forEach((a,r)=>{s[0][r]=a.get(),s[1][r]=a.getVelocity()}),s}function To(t,s,a,r){if(typeof s=="function"){const[n,i]=Ul(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]=Ul(r);s=s(a!==void 0?a:t.custom,n,i)}return s}function Dr(t){return Pt(t)?t.get():t}function $j({scrapeMotionValuesFromProps:t,createRenderState:s},a,r,n){return{latestValues:Uj(a,r,n,t),renderState:s()}}function Uj(t,s,a,r){const n={},i=r(t,{});for(const h in i)n[h]=Dr(i[h]);let{initial:o,animate:l}=t;const c=on(t),d=iu(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"&&!nn(u)){const h=Array.isArray(u)?u:[u];for(let p=0;p<h.length;p++){const g=To(t,h[p]);if(g){const{transitionEnd:y,transition:v,...w}=g;for(const f in w){let C=w[f];if(Array.isArray(C)){const b=m?C.length-1:0;C=C[b]}C!==null&&(n[f]=C)}for(const f in y)n[f]=y[f]}}}return n}const uu=t=>(s,a)=>{const r=x.useContext(rn),n=x.useContext(sn),i=()=>$j(t,s,r,n);return a?i():Zi(i)};function ko(t,s,a){var i;const{style:r}=t,n={};for(const o in r)(Pt(r[o])||s.style&&Pt(s.style[o])||ou(o,t)||((i=a==null?void 0:a.getValue(o))==null?void 0:i.liveStyle)!==void 0)&&(n[o]=r[o]);return n}const Bj=uu({scrapeMotionValuesFromProps:ko,createRenderState:So});function hu(t,s,a){const r=ko(t,s,a);for(const n in t)if(Pt(t[n])||Pt(s[n])){const i=Pa.indexOf(n)!==-1?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n;r[i]=t[n]}return r}const Vj=uu({scrapeMotionValuesFromProps:hu,createRenderState:du}),zj=Symbol.for("motionComponentSymbol");function xa(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function Hj(t,s,a){return x.useCallback(r=>{r&&t.onMount&&t.onMount(r),s&&(r?s.mount(r):s.unmount()),a&&(typeof a=="function"?a(r):xa(a)&&(a.current=r))},[s])}const Ro=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),qj="framerAppearId",pu="data-"+Ro(qj),xu=x.createContext({});function Wj(t,s,a,r,n){var y,v;const{visualElement:i}=x.useContext(rn),o=x.useContext(ru),l=x.useContext(sn),c=x.useContext(jo).reducedMotion,d=x.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=x.useContext(xu);m&&!m.projection&&n&&(m.type==="html"||m.type==="svg")&&Kj(d.current,a,n,u);const h=x.useRef(!1);x.useInsertionEffect(()=>{m&&h.current&&m.update(a,l)});const p=a[pu],g=x.useRef(!!p&&!((y=window.MotionHandoffIsComplete)!=null&&y.call(window,p))&&((v=window.MotionHasOptimisedAnimation)==null?void 0:v.call(window,p)));return um(()=>{m&&(h.current=!0,window.MotionIsMounted=!0,m.updateFeatures(),m.scheduleRenderMicrotask(),g.current&&m.animationState&&m.animationState.animateChanges())}),x.useEffect(()=>{m&&(!g.current&&m.animationState&&m.animationState.animateChanges(),g.current&&(queueMicrotask(()=>{var w;(w=window.MotionHandoffMarkAsComplete)==null||w.call(window,p)}),g.current=!1),m.enteringChildren=void 0)}),m}function Kj(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:gu(t.parent)),t.projection.setOptions({layoutId:n,layout:i,alwaysMeasureLayout:!!o||l&&xa(l),visualElement:t,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:m,layoutScroll:c,layoutRoot:d})}function gu(t){if(t)return t.options.allowProjection!==!1?t.projection:gu(t.parent)}function In(t,{forwardMotionProps:s=!1}={},a,r){a&&bj(a);const n=Ao(t)?Vj:Bj;function i(l,c){let d;const m={...x.useContext(jo),...l,layoutId:Gj(l)},{isStatic:u}=m,h=Sj(l),p=n(l,u);if(!u&&Qi){Yj();const g=Xj(m);d=g.MeasureLayout,h.visualElement=Wj(t,p,m,r,g.ProjectionNode)}return e.jsxs(rn.Provider,{value:h,children:[d&&h.visualElement?e.jsx(d,{visualElement:h.visualElement,...m}):null,Oj(t,l,Hj(p,h.visualElement,c),p,u,s)]})}i.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const o=x.forwardRef(i);return o[zj]=t,o}function Gj({layoutId:t}){const s=x.useContext(Xi).id;return s&&t!==void 0?s+"-"+t:t}function Yj(t,s){x.useContext(ru).strict}function Xj(t){const{drag:s,layout:a}=Ca;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 Zj(t,s){if(typeof Proxy>"u")return In;const a=new Map,r=(i,o)=>In(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,In(o,void 0,t,s)),a.get(o))})}function fu({top:t,left:s,right:a,bottom:r}){return{x:{min:s,max:a},y:{min:t,max:r}}}function Qj({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 Fn(t){return t===void 0||t===1}function Ni({scale:t,scaleX:s,scaleY:a}){return!Fn(t)||!Fn(s)||!Fn(a)}function Qs(t){return Ni(t)||yu(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function yu(t){return Bl(t.x)||Bl(t.y)}function Bl(t){return t&&t!=="0%"}function Ur(t,s,a){const r=t-a,n=s*r;return a+n}function Vl(t,s,a,r,n){return n!==void 0&&(t=Ur(t,n,r)),Ur(t,a,r)+s}function wi(t,s=0,a=1,r,n){t.min=Vl(t.min,s,a,r,n),t.max=Vl(t.max,s,a,r,n)}function vu(t,{x:s,y:a}){wi(t.x,s.translate,s.scale,s.originPoint),wi(t.y,a.translate,a.scale,a.originPoint)}const zl=.999999999999,Hl=1.0000000000001;function eN(t,s,a,r=!1){const n=a.length;if(!n)return;s.x=s.y=1;let i,o;for(let l=0;l<n;l++){i=a[l],o=i.projectionDelta;const{visualElement:c}=i.options;c&&c.props.style&&c.props.style.display==="contents"||(r&&i.options.layoutScroll&&i.scroll&&i!==i.root&&fa(t,{x:-i.scroll.offset.x,y:-i.scroll.offset.y}),o&&(s.x*=o.x.scale,s.y*=o.y.scale,vu(t,o)),r&&Qs(i.latestValues)&&fa(t,i.latestValues))}s.x<Hl&&s.x>zl&&(s.x=1),s.y<Hl&&s.y>zl&&(s.y=1)}function ga(t,s){t.min=t.min+s,t.max=t.max+s}function ql(t,s,a,r,n=.5){const i=at(t.min,t.max,n);wi(t,s,a,i,r)}function fa(t,s){ql(t.x,s.x,s.scaleX,s.scale,s.originX),ql(t.y,s.y,s.scaleY,s.scale,s.originY)}function bu(t,s){return fu(Jj(t.getBoundingClientRect(),s))}function tN(t,s,a){const r=bu(t,a),{scroll:n}=s;return n&&(ga(r.x,n.offset.x),ga(r.y,n.offset.y)),r}const Wl=()=>({translate:0,scale:1,origin:0,originPoint:0}),ya=()=>({x:Wl(),y:Wl()}),Kl=()=>({min:0,max:0}),mt=()=>({x:Kl(),y:Kl()}),Ci={current:null},ju={current:!1};function sN(){if(ju.current=!0,!!Qi)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),s=()=>Ci.current=t.matches;t.addEventListener("change",s),s()}else Ci.current=!1}const aN=new WeakMap;function rN(t,s,a){for(const r in s){const n=s[r],i=a[r];if(Pt(n))t.addValue(r,n);else if(Pt(i))t.addValue(r,wa(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,wa(o!==void 0?o:n,{owner:t}))}}for(const r in a)s[r]===void 0&&t.removeValue(r);return s}const Gl=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class nN{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=go,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=Ht.now();this.renderScheduledAt<h&&(this.renderScheduledAt=h,Qe.render(this.render,!1,!0))};const{latestValues:c,renderState:d}=o;this.latestValues=c,this.baseTarget={...c},this.initialValues=a.initial?{...c}:{},this.renderState=d,this.parent=s,this.props=a,this.presenceContext=r,this.depth=s?s.depth+1:0,this.reducedMotionConfig=n,this.options=l,this.blockInitialAnimation=!!i,this.isControllingVariants=on(a),this.isVariantNode=iu(a),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(s&&s.current);const{willChange:m,...u}=this.scrapeMotionValuesFromProps(a,{},this);for(const h in u){const p=u[h];c[h]!==void 0&&Pt(p)&&p.set(c[h])}}mount(s){var a;this.current=s,aN.set(s,this),this.projection&&!this.projection.instance&&this.projection.mount(s),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((r,n)=>this.bindToMotionValue(n,r)),ju.current||sN(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Ci.current,(a=this.parent)==null||a.addChild(this),this.update(this.props,this.presenceContext)}unmount(){var s;this.projection&&this.projection.unmount(),Us(this.notifyUpdate),Us(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=Ea.has(s);r&&this.onBindTransform&&this.onBindTransform();const n=a.on("change",o=>{this.latestValues[s]=o,this.props.onUpdate&&Qe.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 Ca){const a=Ca[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):mt()}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;r<Gl.length;r++){const n=Gl[r];this.propEventSubscriptions[n]&&(this.propEventSubscriptions[n](),delete this.propEventSubscriptions[n]);const i="on"+n,o=s[i];o&&(this.propEventSubscriptions[n]=this.on(n,o))}this.prevMotionValues=rN(this,this.scrapeMotionValuesFromProps(s,this.prevProps,this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(s){return this.props.variants?this.props.variants[s]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(s){const a=this.getClosestVariantNode();if(a)return a.variantChildren&&a.variantChildren.add(s),()=>a.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=wa(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"&&(hm(r)||xm(r))?r=parseFloat(r):!hj(r)&&Bs.test(a)&&(r=Xm(s,a)),this.setBaseTarget(s,Pt(r)?r.get():r)),Pt(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=To(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&&!Pt(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 ao),this.events[s].add(a)}notify(s,...a){this.events[s]&&this.events[s].notify(...a)}scheduleRenderMicrotask(){vo.render(this.render)}}class Nu extends nN{constructor(){super(...arguments),this.KeyframeResolver=tj}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;Pt(s)&&(this.childSubscription=s.on("change",a=>{this.current&&(this.current.textContent=`${a}`)}))}}function wu(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 iN(t){return window.getComputedStyle(t)}class oN extends Nu{constructor(){super(...arguments),this.type="html",this.renderInstance=wu}readValueFromInstance(s,a){var r;if(Ea.has(a))return(r=this.projection)!=null&&r.isProjecting?xi(a):bb(s,a);{const n=iN(s),i=(io(a)?n.getPropertyValue(a):n[a])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(s,{transformPagePoint:a}){return bu(s,a)}build(s,a,r){Co(s,a,r.transformTemplate)}scrapeMotionValuesFromProps(s,a,r){return ko(s,a,r)}}const Cu=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 lN(t,s,a,r){wu(t,s,void 0,r);for(const n in s.attrs)t.setAttribute(Cu.has(n)?n:Ro(n),s.attrs[n])}class cN extends Nu{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=mt}getBaseTargetFromProps(s,a){return s[a]}readValueFromInstance(s,a){if(Ea.has(a)){const r=Ym(a);return r&&r.default||0}return a=Cu.has(a)?a:Ro(a),s.getAttribute(a)}scrapeMotionValuesFromProps(s,a,r){return hu(s,a,r)}build(s,a,r){cu(s,a,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(s,a,r,n){lN(s,a,r,n)}mount(s){this.isSVGTag=mu(s.tagName),super.mount(s)}}const dN=(t,s)=>Ao(t)?new cN(s):new oN(s,{allowProjection:t!==x.Fragment});function ja(t,s,a){const r=t.getProps();return To(r,s,a!==void 0?a:r.custom,t)}const Si=t=>Array.isArray(t);function mN(t,s,a){t.hasValue(s)?t.getValue(s).set(a):t.addValue(s,wa(a))}function uN(t){return Si(t)?t[t.length-1]||0:t}function hN(t,s){const a=ja(t,s);let{transitionEnd:r={},transition:n={},...i}=a||{};i={...i,...r};for(const o in i){const l=uN(i[o]);mN(t,o,l)}}function pN(t){return!!(Pt(t)&&t.add)}function Ai(t,s){const a=t.getValue("willChange");if(pN(a))return a.add(s);if(!a&&Ds.WillChange){const r=new Ds.WillChange("auto");t.addValue("willChange",r),r.add(s)}}function Su(t){return t.props[pu]}const xN=t=>t!==null;function gN(t,{repeat:s,repeatType:a="loop"},r){const n=t.filter(xN),i=s&&a!=="loop"&&s%2===1?0:n.length-1;return n[i]}const fN={type:"spring",stiffness:500,damping:25,restSpeed:10},yN=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),vN={type:"keyframes",duration:.8},bN={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},jN=(t,{keyframes:s})=>s.length>2?vN:Ea.has(t)?t.startsWith("scale")?yN(s[1]):fN:bN;function NN({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 Do=(t,s,a,r={},n,i)=>o=>{const l=fo(r,t)||{},c=l.delay||r.delay||0;let{elapsed:d=0}=r;d=d-us(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};NN(l)||Object.assign(m,jN(t,m)),m.duration&&(m.duration=us(m.duration)),m.repeatDelay&&(m.repeatDelay=us(m.repeatDelay)),m.from!==void 0&&(m.keyframes[0]=m.from);let u=!1;if((m.type===!1||m.duration===0&&!m.repeatDelay)&&(bi(m),m.delay===0&&(u=!0)),(Ds.instantAnimations||Ds.skipAnimations)&&(u=!0,bi(m),m.delay=0),m.allowFlatten=!l.type&&!l.ease,u&&!i&&s.get()!==void 0){const h=gN(m.keyframes,l);if(h!==void 0){Qe.update(()=>{m.onUpdate(h),m.onComplete()});return}}return l.isSync?new xo(m):new zb(m)};function wN({protectedKeys:t,needsAnimating:s},a){const r=t.hasOwnProperty(a)&&s[a]!==!0;return s[a]=!1,r}function Au(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&&wN(d,m))continue;const p={delay:a,...fo(i||{},m)},g=u.get();if(g!==void 0&&!u.isAnimating&&!Array.isArray(h)&&h===g&&!p.velocity)continue;let y=!1;if(window.MotionHandoffAnimation){const w=Su(t);if(w){const f=window.MotionHandoffAnimation(w,m,Qe);f!==null&&(p.startTime=f,y=!0)}}Ai(t,m),u.start(Do(m,u,h,t.shouldReduceMotion&&Wm.has(m)?{type:!1}:p,t,y));const v=u.animation;v&&c.push(v)}return o&&Promise.all(c).then(()=>{Qe.update(()=>{o&&hN(t,o)})}),c}function Tu(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 Ti(t,s,a={}){var c;const r=ja(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(Au(t,r,a)):()=>Promise.resolve(),o=t.variantChildren&&t.variantChildren.size?(d=0)=>{const{delayChildren:m=0,staggerChildren:u,staggerDirection:h}=n;return CN(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 CN(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(Ti(c,s,{...o,delay:a+(typeof r=="function"?0:r)+Tu(t.variantChildren,c,r,n,i)}).then(()=>c.notify("AnimationComplete",s)));return Promise.all(l)}function SN(t,s,a={}){t.notify("AnimationStart",s);let r;if(Array.isArray(s)){const n=s.map(i=>Ti(t,i,a));r=Promise.all(n)}else if(typeof s=="string")r=Ti(t,s,a);else{const n=typeof s=="function"?ja(t,s,a.custom):s;r=Promise.all(Au(t,n,a))}return r.then(()=>{t.notify("AnimationComplete",s)})}function ku(t,s){if(!Array.isArray(s))return!1;const a=s.length;if(a!==t.length)return!1;for(let r=0;r<a;r++)if(s[r]!==t[r])return!1;return!0}const AN=wo.length;function Ru(t){if(!t)return;if(!t.isControllingVariants){const a=t.parent?Ru(t.parent)||{}:{};return t.props.initial!==void 0&&(a.initial=t.props.initial),a}const s={};for(let a=0;a<AN;a++){const r=wo[a],n=t.props[r];(Ja(n)||n===!1)&&(s[r]=n)}return s}const TN=[...No].reverse(),kN=No.length;function RN(t){return s=>Promise.all(s.map(({animation:a,options:r})=>SN(t,a,r)))}function DN(t){let s=RN(t),a=Yl(),r=!0;const n=c=>(d,m)=>{var h;const u=ja(t,m,c==="exit"?(h=t.presenceContext)==null?void 0:h.custom:void 0);if(u){const{transition:p,transitionEnd:g,...y}=u;d={...d,...y,...g}}return d};function i(c){s=c(t)}function o(c){const{props:d}=t,m=Ru(t.parent)||{},u=[],h=new Set;let p={},g=1/0;for(let v=0;v<kN;v++){const w=TN[v],f=a[w],C=d[w]!==void 0?d[w]:m[w],b=Ja(C),N=w===c?f.isActive:null;N===!1&&(g=v);let R=C===m[w]&&C!==d[w]&&b;if(R&&r&&t.manuallyAnimateOnMount&&(R=!1),f.protectedKeys={...p},!f.isActive&&N===null||!C&&!f.prevProp||nn(C)||typeof C=="boolean")continue;const E=PN(f.prevProp,C);let P=E||w===c&&f.isActive&&!R&&b||v>g&&b,I=!1;const j=Array.isArray(C)?C:[C];let k=j.reduce(n(w),{});N===!1&&(k={});const{prevResolvedValues:_={}}=f,Y={..._,...k},F=S=>{P=!0,h.has(S)&&(I=!0,h.delete(S)),f.needsAnimating[S]=!0;const T=t.getValue(S);T&&(T.liveStyle=!1)};for(const S in Y){const T=k[S],D=_[S];if(p.hasOwnProperty(S))continue;let H=!1;Si(T)&&Si(D)?H=!ku(T,D):H=T!==D,H?T!=null?F(S):h.add(S):T!==void 0&&h.has(S)?F(S):f.protectedKeys[S]=!0}f.prevProp=C,f.prevResolvedValues=k,f.isActive&&(p={...p,...k}),r&&t.blockInitialAnimation&&(P=!1);const L=R&&E;P&&(!L||I)&&u.push(...j.map(S=>{const T={type:w};if(typeof S=="string"&&r&&!L&&t.manuallyAnimateOnMount&&t.parent){const{parent:D}=t,H=ja(D,S);if(D.enteringChildren&&H){const{delayChildren:z}=H.transition||{};T.delay=Tu(D.enteringChildren,t,z)}}return{animation:S,options:T}}))}if(h.size){const v={};if(typeof d.initial!="boolean"){const w=ja(t,Array.isArray(d.initial)?d.initial[0]:d.initial);w&&w.transition&&(v.transition=w.transition)}h.forEach(w=>{const f=t.getBaseTarget(w),C=t.getValue(w);C&&(C.liveStyle=!0),v[w]=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 p;return(p=h.animationState)==null?void 0:p.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=Yl()}}}function PN(t,s){return typeof s=="string"?s!==t:Array.isArray(s)?!ku(s,t):!1}function Ys(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Yl(){return{animate:Ys(!0),whileInView:Ys(),whileHover:Ys(),whileTap:Ys(),whileDrag:Ys(),whileFocus:Ys(),exit:Ys()}}class qs{constructor(s){this.isMounted=!1,this.node=s}update(){}}class EN extends qs{constructor(s){super(s),s.animationState||(s.animationState=DN(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();nn(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 MN=0;class IN extends qs{constructor(){super(...arguments),this.id=MN++}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 FN={animation:{Feature:EN},exit:{Feature:IN}};function tr(t,s,a,r={passive:!0}){return t.addEventListener(s,a,r),()=>t.removeEventListener(s,a)}function dr(t){return{point:{x:t.pageX,y:t.pageY}}}const _N=t=>s=>bo(s)&&t(s,dr(s));function za(t,s,a,r){return tr(t,s,_N(a),r)}const Du=1e-4,LN=1-Du,ON=1+Du,Pu=.01,$N=0-Pu,UN=0+Pu;function _t(t){return t.max-t.min}function BN(t,s,a){return Math.abs(t-s)<=a}function Xl(t,s,a,r=.5){t.origin=r,t.originPoint=at(s.min,s.max,t.origin),t.scale=_t(a)/_t(s),t.translate=at(a.min,a.max,t.origin)-t.originPoint,(t.scale>=LN&&t.scale<=ON||isNaN(t.scale))&&(t.scale=1),(t.translate>=$N&&t.translate<=UN||isNaN(t.translate))&&(t.translate=0)}function Ha(t,s,a,r){Xl(t.x,s.x,a.x,r?r.originX:void 0),Xl(t.y,s.y,a.y,r?r.originY:void 0)}function Zl(t,s,a){t.min=a.min+s.min,t.max=t.min+_t(s)}function VN(t,s,a){Zl(t.x,s.x,a.x),Zl(t.y,s.y,a.y)}function Ql(t,s,a){t.min=s.min-a.min,t.max=t.min+_t(s)}function qa(t,s,a){Ql(t.x,s.x,a.x),Ql(t.y,s.y,a.y)}function es(t){return[t("x"),t("y")]}const Eu=({current:t})=>t?t.ownerDocument.defaultView:null,Jl=(t,s)=>Math.abs(t-s);function zN(t,s){const a=Jl(t.x,s.x),r=Jl(t.y,s.y);return Math.sqrt(a**2+r**2)}class Mu{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=Ln(this.lastMoveEventInfo,this.history),p=this.startEvent!==null,g=zN(h.offset,{x:0,y:0})>=this.distanceThreshold;if(!p&&!g)return;const{point:y}=h,{timestamp:v}=Rt;this.history.push({...y,timestamp:v});const{onStart:w,onMove:f}=this.handlers;p||(w&&w(this.lastMoveEvent,h),this.startEvent=this.lastMoveEvent),f&&f(this.lastMoveEvent,h)},this.handlePointerMove=(h,p)=>{this.lastMoveEvent=h,this.lastMoveEventInfo=_n(p,this.transformPagePoint),Qe.update(this.updatePoint,!0)},this.handlePointerUp=(h,p)=>{this.end();const{onEnd:g,onSessionEnd:y,resumeAnimation:v}=this.handlers;if(this.dragSnapToOrigin&&v&&v(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const w=Ln(h.type==="pointercancel"?this.lastMoveEventInfo:_n(p,this.transformPagePoint),this.history);this.startEvent&&g&&g(h,w),y&&y(h,w)},!bo(s))return;this.dragSnapToOrigin=i,this.handlers=a,this.transformPagePoint=r,this.distanceThreshold=o,this.contextWindow=n||window;const l=dr(s),c=_n(l,this.transformPagePoint),{point:d}=c,{timestamp:m}=Rt;this.history=[{...d,timestamp:m}];const{onSessionStart:u}=a;u&&u(s,Ln(c,this.history)),this.removeListeners=or(za(this.contextWindow,"pointermove",this.handlePointerMove),za(this.contextWindow,"pointerup",this.handlePointerUp),za(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(s){this.handlers=s}end(){this.removeListeners&&this.removeListeners(),Us(this.updatePoint)}}function _n(t,s){return s?{point:s(t.point)}:t}function ec(t,s){return{x:t.x-s.x,y:t.y-s.y}}function Ln({point:t},s){return{point:t,delta:ec(t,Iu(s)),offset:ec(t,HN(s)),velocity:qN(s,.1)}}function HN(t){return t[0]}function Iu(t){return t[t.length-1]}function qN(t,s){if(t.length<2)return{x:0,y:0};let a=t.length-1,r=null;const n=Iu(t);for(;a>=0&&(r=t[a],!(n.timestamp-r.timestamp>us(s)));)a--;if(!r)return{x:0,y:0};const i=ts(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 WN(t,{min:s,max:a},r){return s!==void 0&&t<s?t=r?at(s,t,r.min):Math.max(t,s):a!==void 0&&t>a&&(t=r?at(a,t,r.max):Math.min(t,a)),t}function tc(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 KN(t,{top:s,left:a,bottom:r,right:n}){return{x:tc(t.x,a,n),y:tc(t.y,s,r)}}function sc(t,s){let a=s.min-t.min,r=s.max-t.max;return s.max-s.min<t.max-t.min&&([a,r]=[r,a]),{min:a,max:r}}function GN(t,s){return{x:sc(t.x,s.x),y:sc(t.y,s.y)}}function YN(t,s){let a=.5;const r=_t(t),n=_t(s);return n>r?a=Xa(s.min,s.max-r,t.min):r>n&&(a=Xa(t.min,t.max-n,s.min)),Rs(0,1,a)}function XN(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 ki=.35;function ZN(t=ki){return t===!1?t=0:t===!0&&(t=ki),{x:ac(t,"left","right"),y:ac(t,"top","bottom")}}function ac(t,s,a){return{min:rc(t,s),max:rc(t,a)}}function rc(t,s){return typeof t=="number"?t:t[s]||0}const QN=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=mt(),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(dr(u).point)},o=(u,h)=>{const{drag:p,dragPropagation:g,onDragStart:y}=this.getProps();if(p&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=nj(p),!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),es(w=>{let f=this.getAxisMotionValue(w).get()||0;if(hs.test(f)){const{projection:C}=this.visualElement;if(C&&C.layout){const b=C.layout.layoutBox[w];b&&(f=_t(b)*(parseFloat(f)/100))}}this.originPoint[w]=f}),y&&Qe.postRender(()=>y(u,h)),Ai(this.visualElement,"transform");const{animationState:v}=this.visualElement;v&&v.setActive("whileDrag",!0)},l=(u,h)=>{this.latestPointerEvent=u,this.latestPanInfo=h;const{dragPropagation:p,dragDirectionLock:g,onDirectionLock:y,onDrag:v}=this.getProps();if(!p&&!this.openDragLock)return;const{offset:w}=h;if(g&&this.currentDirection===null){this.currentDirection=ew(w),this.currentDirection!==null&&y&&y(this.currentDirection);return}this.updateAxis("x",h.point,w),this.updateAxis("y",h.point,w),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=()=>es(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 Mu(s,{onSessionStart:i,onStart:o,onMove:l,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:m,distanceThreshold:r,contextWindow:Eu(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&&Qe.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||!wr(s,n,this.currentDirection))return;const i=this.getAxisMotionValue(s);let o=this.originPoint[s]+r[s];this.constraints&&this.constraints[s]&&(o=WN(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&&xa(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&r?this.constraints=KN(r.layoutBox,s):this.constraints=!1,this.elastic=ZN(a),n!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&es(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=XN(r.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:s,onMeasureDragConstraints:a}=this.getProps();if(!s||!xa(s))return!1;const r=s.current,{projection:n}=this.visualElement;if(!n||!n.layout)return!1;const i=tN(r,n.root,this.visualElement.getTransformPagePoint());let o=GN(n.layout.layoutBox,i);if(a){const l=a(Qj(o));this.hasMutatedConstraints=!!l,l&&(o=fu(l))}return o}startAnimation(s){const{drag:a,dragMomentum:r,dragElastic:n,dragTransition:i,dragSnapToOrigin:o,onDragTransitionEnd:l}=this.getProps(),c=this.constraints||{},d=es(m=>{if(!wr(m,a,this.currentDirection))return;let u=c&&c[m]||{};o&&(u={min:0,max:0});const h=n?200:1e6,p=n?40:1e7,g={type:"inertia",velocity:r?s[m]:0,bounceStiffness:h,bounceDamping:p,timeConstant:750,restDelta:1,restSpeed:10,...i,...u};return this.startAxisValueAnimation(m,g)});return Promise.all(d).then(l)}startAxisValueAnimation(s,a){const r=this.getAxisMotionValue(s);return Ai(this.visualElement,s),r.start(Do(s,r,0,a,this.visualElement,!1))}stopAnimation(){es(s=>this.getAxisMotionValue(s).stop())}pauseAnimation(){es(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){es(a=>{const{drag:r}=this.getProps();if(!wr(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]-at(o,l,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:s,dragConstraints:a}=this.getProps(),{projection:r}=this.visualElement;if(!xa(a)||!r||!this.constraints)return;this.stopAnimation();const n={x:0,y:0};es(o=>{const l=this.getAxisMotionValue(o);if(l&&this.constraints!==!1){const c=l.get();n[o]=YN({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(),es(o=>{if(!wr(o,s,null))return;const l=this.getAxisMotionValue(o),{min:c,max:d}=this.constraints[o];l.set(at(c,d,n[o]))})}addListeners(){if(!this.visualElement.current)return;QN.set(this.visualElement,this);const s=this.visualElement.current,a=za(s,"pointerdown",c=>{const{drag:d,dragListener:m=!0}=this.getProps();d&&m&&this.start(c)}),r=()=>{const{dragConstraints:c}=this.getProps();xa(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()),Qe.read(r);const o=tr(window,"resize",()=>this.scalePositionWithinConstraints()),l=n.addEventListener("didUpdate",({delta:c,hasLayoutChanged:d})=>{this.isDragging&&d&&(es(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=ki,dragMomentum:l=!0}=s;return{...s,drag:a,dragDirectionLock:r,dragPropagation:n,dragConstraints:i,dragElastic:o,dragMomentum:l}}}function wr(t,s,a){return(s===!0||s===t)&&(a===null||a===t)}function ew(t,s=10){let a=null;return Math.abs(t.y)>s?a="y":Math.abs(t.x)>s&&(a="x"),a}class tw extends qs{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 nc=t=>(s,a)=>{t&&Qe.postRender(()=>t(s,a))};class sw extends qs{constructor(){super(...arguments),this.removePointerDownListener=ss}onPointerDown(s){this.session=new Mu(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Eu(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:a,onPan:r,onPanEnd:n}=this.node.getProps();return{onSessionStart:nc(s),onStart:nc(a),onMove:r,onEnd:(i,o)=>{delete this.session,n&&Qe.postRender(()=>n(i,o))}}}mount(){this.removePointerDownListener=za(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 Pr={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function ic(t,s){return s.max===s.min?0:t/(s.max-s.min)*100}const Oa={correct:(t,s)=>{if(!s.target)return t;if(typeof t=="string")if(Ce.test(t))t=parseFloat(t);else return t;const a=ic(t,s.target.x),r=ic(t,s.target.y);return`${a}% ${r}%`}},aw={correct:(t,{treeScale:s,projectionDelta:a})=>{const r=t,n=Bs.parse(t);if(n.length>5)return r;const i=Bs.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=at(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 On=!1;class rw extends x.Component{componentDidMount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r,layoutId:n}=this.props,{projection:i}=s;Aj(nw),i&&(a.group&&a.group.add(i),r&&r.register&&n&&r.register(i),On&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,onExitComplete:()=>this.safeToRemove()})),Pr.hasEverUpdated=!0}getSnapshotBeforeUpdate(s){const{layoutDependency:a,visualElement:r,drag:n,isPresent:i}=this.props,{projection:o}=r;return o&&(o.isPresent=i,On=!0,n||s.layoutDependency!==a||a===void 0||s.isPresent!==i?o.willUpdate():this.safeToRemove(),s.isPresent!==i&&(i?o.promote():o.relegate()||Qe.postRender(()=>{const l=o.getStack();(!l||!l.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:s}=this.props.visualElement;s&&(s.root.didUpdate(),vo.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r}=this.props,{projection:n}=s;On=!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 Fu(t){const[s,a]=au(),r=x.useContext(Xi);return e.jsx(rw,{...t,layoutGroup:r,switchLayoutGroup:x.useContext(xu),isPresent:s,safeToRemove:a})}const nw={borderRadius:{...Oa,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Oa,borderTopRightRadius:Oa,borderBottomLeftRadius:Oa,borderBottomRightRadius:Oa,boxShadow:aw};function iw(t,s,a){const r=Pt(t)?t:wa(t);return r.start(Do("",r,s,a)),r.animation}const ow=(t,s)=>t.depth-s.depth;class lw{constructor(){this.children=[],this.isDirty=!1}add(s){Ji(this.children,s),this.isDirty=!0}remove(s){eo(this.children,s),this.isDirty=!0}forEach(s){this.isDirty&&this.children.sort(ow),this.isDirty=!1,this.children.forEach(s)}}function cw(t,s){const a=Ht.now(),r=({timestamp:n})=>{const i=n-a;i>=s&&(Us(r),t(i-s))};return Qe.setup(r,!0),()=>Us(r)}const _u=["TopLeft","TopRight","BottomLeft","BottomRight"],dw=_u.length,oc=t=>typeof t=="string"?parseFloat(t):t,lc=t=>typeof t=="number"||Ce.test(t);function mw(t,s,a,r,n,i){n?(t.opacity=at(0,a.opacity??1,uw(r)),t.opacityExit=at(s.opacity??1,0,hw(r))):i&&(t.opacity=at(s.opacity??1,a.opacity??1,r));for(let o=0;o<dw;o++){const l=`border${_u[o]}Radius`;let c=cc(s,l),d=cc(a,l);if(c===void 0&&d===void 0)continue;c||(c=0),d||(d=0),c===0||d===0||lc(c)===lc(d)?(t[l]=Math.max(at(oc(c),oc(d),r),0),(hs.test(d)||hs.test(c))&&(t[l]+="%")):t[l]=d}(s.rotate||a.rotate)&&(t.rotate=at(s.rotate||0,a.rotate||0,r))}function cc(t,s){return t[s]!==void 0?t[s]:t.borderRadius}const uw=Lu(0,.5,wm),hw=Lu(.5,.95,ss);function Lu(t,s,a){return r=>r<t?0:r>s?1:a(Xa(t,s,r))}function dc(t,s){t.min=s.min,t.max=s.max}function Jt(t,s){dc(t.x,s.x),dc(t.y,s.y)}function mc(t,s){t.translate=s.translate,t.scale=s.scale,t.originPoint=s.originPoint,t.origin=s.origin}function uc(t,s,a,r,n){return t-=s,t=Ur(t,1/a,r),n!==void 0&&(t=Ur(t,1/n,r)),t}function pw(t,s=0,a=1,r=.5,n,i=t,o=t){if(hs.test(s)&&(s=parseFloat(s),s=at(o.min,o.max,s/100)-o.min),typeof s!="number")return;let l=at(i.min,i.max,r);t===i&&(l-=s),t.min=uc(t.min,s,a,l,n),t.max=uc(t.max,s,a,l,n)}function hc(t,s,[a,r,n],i,o){pw(t,s[a],s[r],s[n],s.scale,i,o)}const xw=["x","scaleX","originX"],gw=["y","scaleY","originY"];function pc(t,s,a,r){hc(t.x,s,xw,a?a.x:void 0,r?r.x:void 0),hc(t.y,s,gw,a?a.y:void 0,r?r.y:void 0)}function xc(t){return t.translate===0&&t.scale===1}function Ou(t){return xc(t.x)&&xc(t.y)}function gc(t,s){return t.min===s.min&&t.max===s.max}function fw(t,s){return gc(t.x,s.x)&&gc(t.y,s.y)}function fc(t,s){return Math.round(t.min)===Math.round(s.min)&&Math.round(t.max)===Math.round(s.max)}function $u(t,s){return fc(t.x,s.x)&&fc(t.y,s.y)}function yc(t){return _t(t.x)/_t(t.y)}function vc(t,s){return t.translate===s.translate&&t.scale===s.scale&&t.originPoint===s.originPoint}class yw{constructor(){this.members=[]}add(s){Ji(this.members,s),s.scheduleRender()}remove(s){if(eo(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 vw(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:p,skewY:g}=a;d&&(r=`perspective(${d}px) ${r}`),m&&(r+=`rotate(${m}deg) `),u&&(r+=`rotateX(${u}deg) `),h&&(r+=`rotateY(${h}deg) `),p&&(r+=`skewX(${p}deg) `),g&&(r+=`skewY(${g}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 $n=["","X","Y","Z"],bw=1e3;let jw=0;function Un(t,s,a,r){const{latestValues:n}=s;n[t]&&(a[t]=n[t],s.setStaticValue(t,0),r&&(r[t]=0))}function Uu(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:s}=t.options;if(!s)return;const a=Su(s);if(window.MotionHasOptimisedAnimation(a,"transform")){const{layout:n,layoutId:i}=t.options;window.MotionCancelOptimisedAnimation(a,"transform",Qe,!(n||i))}const{parent:r}=t;r&&!r.hasCheckedOptimisedAppear&&Uu(r)}function Bu({attachResizeListener:t,defaultParent:s,measureScroll:a,checkIsScrollRoot:r,resetTransform:n}){return class{constructor(o={},l=s==null?void 0:s()){this.id=jw++,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(Cw),this.nodes.forEach(kw),this.nodes.forEach(Rw),this.nodes.forEach(Sw)},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;c<this.path.length;c++)this.path[c].shouldResetTransform=!0;this.root===this&&(this.nodes=new lw)}addEventListener(o,l){return this.eventHandlers.has(o)||this.eventHandlers.set(o,new ao),this.eventHandlers.get(o).add(l)}notifyListeners(o,...l){const c=this.eventHandlers.get(o);c&&c.notify(...l)}hasListeners(o){return this.eventHandlers.has(o)}mount(o){if(this.instance)return;this.isSVG=su(o)&&!mj(o),this.instance=o;const{layoutId:l,layout:c,visualElement:d}=this.options;if(d&&!d.current&&d.mount(o),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(c||l)&&(this.isLayoutDirty=!0),t){let m,u=0;const h=()=>this.root.updateBlockedByResize=!1;Qe.read(()=>{u=window.innerWidth}),t(o,()=>{const p=window.innerWidth;p!==u&&(u=p,this.root.updateBlockedByResize=!0,m&&m(),m=cw(h,250),Pr.hasAnimatedSinceResize&&(Pr.hasAnimatedSinceResize=!1,this.nodes.forEach(Nc)))})}l&&this.root.registerSharedNode(l,this),this.options.animate!==!1&&d&&(l||c)&&this.addEventListener("didUpdate",({delta:m,hasLayoutChanged:u,hasRelativeLayoutChanged:h,layout:p})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const g=this.options.transition||d.getDefaultTransition()||Iw,{onLayoutAnimationStart:y,onLayoutAnimationComplete:v}=d.getProps(),w=!this.targetLayout||!$u(this.targetLayout,p),f=!u&&h;if(this.options.layoutRoot||this.resumeFrom||f||u&&(w||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const C={...fo(g,"layout"),onPlay:y,onComplete:v};(d.shouldReduceMotion||this.options.layoutRoot)&&(C.delay=0,C.type=!1),this.startAnimation(C),this.setAnimationOrigin(m,f)}else u||Nc(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=p})}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(),Us(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(Dw),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&&Uu(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let m=0;m<this.path.length;m++){const u=this.path[m];u.shouldResetTransform=!0,u.updateScroll("snapshot"),u.options.layoutRoot&&u.willUpdate(!1)}const{layoutId:l,layout:c}=this.options;if(l===void 0&&!c)return;const d=this.getTransformTemplate();this.prevTransformTemplateValue=d?d(this.latestValues,""):void 0,this.updateSnapshot(),o&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(bc);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(jc);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(Tw),this.nodes.forEach(Nw),this.nodes.forEach(ww)):this.nodes.forEach(jc),this.clearAllSnapshots();const l=Ht.now();Rt.delta=Rs(0,1e3/60,l-Rt.timestamp),Rt.timestamp=l,Rt.isProcessing=!0,kn.update.process(Rt),kn.preRender.process(Rt),kn.render.process(Rt),Rt.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,vo.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Aw),this.sharedNodes.forEach(Pw)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,Qe.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){Qe.postRender(()=>{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<this.path.length;c++)this.path[c].updateScroll();const o=this.layout;this.layout=this.measure(!1),this.layoutCorrected=mt(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);const{visualElement:l}=this.options;l&&l.notify("LayoutMeasure",this.layout.layoutBox,o?o.layoutBox:void 0)}updateScroll(o="measure"){let l=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===o&&(l=!1),l&&this.instance){const c=r(this.instance);this.scroll={animationId:this.root.animationId,phase:o,isRoot:c,offset:a(this.instance),wasRoot:this.scroll?this.scroll.isRoot:c}}}resetTransform(){if(!n)return;const o=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,l=this.projectionDelta&&!Ou(this.projectionDelta),c=this.getTransformTemplate(),d=c?c(this.latestValues,""):void 0,m=d!==this.prevTransformTemplateValue;o&&this.instance&&(l||Qs(this.latestValues)||m)&&(n(this.instance,d),this.shouldResetTransform=!1,this.scheduleRender())}measure(o=!0){const l=this.measurePageBox();let c=this.removeElementScroll(l);return o&&(c=this.removeTransform(c)),Fw(c),{animationId:this.root.animationId,measuredBox:l,layoutBox:c,latestValues:{},source:this.id}}measurePageBox(){var d;const{visualElement:o}=this.options;if(!o)return mt();const l=o.measureViewportBox();if(!(((d=this.scroll)==null?void 0:d.wasRoot)||this.path.some(_w))){const{scroll:m}=this.root;m&&(ga(l.x,m.offset.x),ga(l.y,m.offset.y))}return l}removeElementScroll(o){var c;const l=mt();if(Jt(l,o),(c=this.scroll)!=null&&c.wasRoot)return l;for(let d=0;d<this.path.length;d++){const m=this.path[d],{scroll:u,options:h}=m;m!==this.root&&u&&h.layoutScroll&&(u.wasRoot&&Jt(l,o),ga(l.x,u.offset.x),ga(l.y,u.offset.y))}return l}applyTransform(o,l=!1){const c=mt();Jt(c,o);for(let d=0;d<this.path.length;d++){const m=this.path[d];!l&&m.options.layoutScroll&&m.scroll&&m!==m.root&&fa(c,{x:-m.scroll.offset.x,y:-m.scroll.offset.y}),Qs(m.latestValues)&&fa(c,m.latestValues)}return Qs(this.latestValues)&&fa(c,this.latestValues),c}removeTransform(o){const l=mt();Jt(l,o);for(let c=0;c<this.path.length;c++){const d=this.path[c];if(!d.instance||!Qs(d.latestValues))continue;Ni(d.latestValues)&&d.updateSnapshot();const m=mt(),u=d.measurePageBox();Jt(m,u),pc(l,d.latestValues,d.snapshot?d.snapshot.layoutBox:void 0,m)}return Qs(this.latestValues)&&pc(l,this.latestValues),l}setTargetDelta(o){this.targetDelta=o,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(o){this.options={...this.options,...o,crossfade:o.crossfade!==void 0?o.crossfade:!0}}clearMeasurements(){this.scroll=void 0,this.layout=void 0,this.snapshot=void 0,this.prevTransformTemplateValue=void 0,this.targetDelta=void 0,this.target=void 0,this.isLayoutDirty=!1}forceRelativeParentToResolveTarget(){this.relativeParent&&this.relativeParent.resolvedRelativeTargetAt!==Rt.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(o=!1){var h;const l=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=l.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=l.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=l.isSharedProjectionDirty);const c=!!this.resumingFrom||this!==l;if(!(o||c&&this.isSharedProjectionDirty||this.isProjectionDirty||(h=this.parent)!=null&&h.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:m,layoutId:u}=this.options;if(!(!this.layout||!(m||u))){if(this.resolvedRelativeTargetAt=Rt.timestamp,!this.targetDelta&&!this.relativeTarget){const p=this.getClosestProjectingParent();p&&p.layout&&this.animationProgress!==1?(this.relativeParent=p,this.forceRelativeParentToResolveTarget(),this.relativeTarget=mt(),this.relativeTargetOrigin=mt(),qa(this.relativeTargetOrigin,this.layout.layoutBox,p.layout.layoutBox),Jt(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=mt(),this.targetWithTransforms=mt()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),VN(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):Jt(this.target,this.layout.layoutBox),vu(this.target,this.targetDelta)):Jt(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const p=this.getClosestProjectingParent();p&&!!p.resumingFrom==!!this.resumingFrom&&!p.options.layoutScroll&&p.target&&this.animationProgress!==1?(this.relativeParent=p,this.forceRelativeParentToResolveTarget(),this.relativeTarget=mt(),this.relativeTargetOrigin=mt(),qa(this.relativeTargetOrigin,this.target,p.target),Jt(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Ni(this.parent.latestValues)||yu(this.parent.latestValues)))return this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}calcProjection(){var g;const o=this.getLead(),l=!!this.resumingFrom||this!==o;let c=!0;if((this.isProjectionDirty||(g=this.parent)!=null&&g.isProjectionDirty)&&(c=!1),l&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(c=!1),this.resolvedRelativeTargetAt===Rt.timestamp&&(c=!1),c)return;const{layout:d,layoutId:m}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(d||m))return;Jt(this.layoutCorrected,this.layout.layoutBox);const u=this.treeScale.x,h=this.treeScale.y;eN(this.layoutCorrected,this.treeScale,this.path,l),o.layout&&!o.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(o.target=o.layout.layoutBox,o.targetWithTransforms=mt());const{target:p}=o;if(!p){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(mc(this.prevProjectionDelta.x,this.projectionDelta.x),mc(this.prevProjectionDelta.y,this.projectionDelta.y)),Ha(this.projectionDelta,this.layoutCorrected,p,this.latestValues),(this.treeScale.x!==u||this.treeScale.y!==h||!vc(this.projectionDelta.x,this.prevProjectionDelta.x)||!vc(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",p))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(o=!0){var l;if((l=this.options.visualElement)==null||l.scheduleRender(),o){const c=this.getStack();c&&c.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=ya(),this.projectionDelta=ya(),this.projectionDeltaWithTransform=ya()}setAnimationOrigin(o,l=!1){const c=this.snapshot,d=c?c.latestValues:{},m={...this.latestValues},u=ya();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!l;const h=mt(),p=c?c.source:void 0,g=this.layout?this.layout.source:void 0,y=p!==g,v=this.getStack(),w=!v||v.members.length<=1,f=!!(y&&!w&&this.options.crossfade===!0&&!this.path.some(Mw));this.animationProgress=0;let C;this.mixTargetDelta=b=>{const N=b/1e3;wc(u.x,o.x,N),wc(u.y,o.y,N),this.setTargetDelta(u),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(qa(h,this.layout.layoutBox,this.relativeParent.layout.layoutBox),Ew(this.relativeTarget,this.relativeTargetOrigin,h,N),C&&fw(this.relativeTarget,C)&&(this.isProjectionDirty=!1),C||(C=mt()),Jt(C,this.relativeTarget)),y&&(this.animationValues=m,mw(m,d,this.latestValues,N,f,w)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=N},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&&(Us(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Qe.update(()=>{Pr.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=wa(0)),this.currentAnimation=iw(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(bw),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&&Vu(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||mt();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}Jt(l,c),fa(l,m),Ha(this.projectionDeltaWithTransform,this.layoutCorrected,l,m)}}registerSharedNode(o,l){this.sharedNodes.has(o)||this.sharedNodes.set(o,new yw),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&&Un("z",o,d,this.animationValues);for(let m=0;m<$n.length;m++)Un(`rotate${$n[m]}`,o,d,this.animationValues),Un(`skew${$n[m]}`,o,d,this.animationValues);o.render();for(const m in d)o.setStaticValue(m,d[m]),this.animationValues&&(this.animationValues[m]=d[m]);o.scheduleRender()}applyProjectionStyles(o,l){if(!this.instance||this.isSVG)return;if(!this.isVisible){o.visibility="hidden";return}const c=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,o.visibility="",o.opacity="",o.pointerEvents=Dr(l==null?void 0:l.pointerEvents)||"",o.transform=c?c(this.latestValues,""):"none";return}const d=this.getLead();if(!this.projectionDelta||!this.layout||!d.target){this.options.layoutId&&(o.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,o.pointerEvents=Dr(l==null?void 0:l.pointerEvents)||""),this.hasProjected&&!Qs(this.latestValues)&&(o.transform=c?c({},""):"none",this.hasProjected=!1);return}o.visibility="";const m=d.animationValues||d.latestValues;this.applyTransformsToTarget();let u=vw(this.projectionDeltaWithTransform,this.treeScale,m);c&&(u=c(m,u)),o.transform=u;const{x:h,y:p}=this.projectionDelta;o.transformOrigin=`${h.origin*100}% ${p.origin*100}% 0`,d.animationValues?o.opacity=d===this?m.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:m.opacityExit:o.opacity=d===this?m.opacity!==void 0?m.opacity:"":m.opacityExit!==void 0?m.opacityExit:0;for(const g in er){if(m[g]===void 0)continue;const{correct:y,applyTo:v,isCSSVariable:w}=er[g],f=u==="none"?m[g]:y(m[g],d);if(v){const C=v.length;for(let b=0;b<C;b++)o[v[b]]=f}else w?this.options.visualElement.renderState.vars[g]=f:o[g]=f}this.options.layoutId&&(o.pointerEvents=d===this?Dr(l==null?void 0:l.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(o=>{var l;return(l=o.currentAnimation)==null?void 0:l.stop()}),this.root.nodes.forEach(bc),this.root.sharedNodes.clear()}}}function Nw(t){t.updateLayout()}function ww(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"?es(u=>{const h=o?s.measuredBox[u]:s.layoutBox[u],p=_t(h);h.min=r[u].min,h.max=h.min+p}):Vu(i,s.layoutBox,r)&&es(u=>{const h=o?s.measuredBox[u]:s.layoutBox[u],p=_t(r[u]);h.max=h.min+p,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[u].max=t.relativeTarget[u].min+p)});const l=ya();Ha(l,r,s.layoutBox);const c=ya();o?Ha(c,t.applyTransform(n,!0),s.measuredBox):Ha(c,r,s.layoutBox);const d=!Ou(l);let m=!1;if(!t.resumeFrom){const u=t.getClosestProjectingParent();if(u&&!u.resumeFrom){const{snapshot:h,layout:p}=u;if(h&&p){const g=mt();qa(g,s.layoutBox,h.layoutBox);const y=mt();qa(y,r,p.layoutBox),$u(g,y)||(m=!0),u.options.layoutRoot&&(t.relativeTarget=y,t.relativeTargetOrigin=g,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 Cw(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 Sw(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function Aw(t){t.clearSnapshot()}function bc(t){t.clearMeasurements()}function jc(t){t.isLayoutDirty=!1}function Tw(t){const{visualElement:s}=t.options;s&&s.getProps().onBeforeLayoutMeasure&&s.notify("BeforeLayoutMeasure"),t.resetTransform()}function Nc(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function kw(t){t.resolveTargetDelta()}function Rw(t){t.calcProjection()}function Dw(t){t.resetSkewAndRotation()}function Pw(t){t.removeLeadSnapshot()}function wc(t,s,a){t.translate=at(s.translate,0,a),t.scale=at(s.scale,1,a),t.origin=s.origin,t.originPoint=s.originPoint}function Cc(t,s,a,r){t.min=at(s.min,a.min,r),t.max=at(s.max,a.max,r)}function Ew(t,s,a,r){Cc(t.x,s.x,a.x,r),Cc(t.y,s.y,a.y,r)}function Mw(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const Iw={duration:.45,ease:[.4,0,.1,1]},Sc=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),Ac=Sc("applewebkit/")&&!Sc("chrome/")?Math.round:ss;function Tc(t){t.min=Ac(t.min),t.max=Ac(t.max)}function Fw(t){Tc(t.x),Tc(t.y)}function Vu(t,s,a){return t==="position"||t==="preserve-aspect"&&!BN(yc(s),yc(a),.2)}function _w(t){var s;return t!==t.root&&((s=t.scroll)==null?void 0:s.wasRoot)}const Lw=Bu({attachResizeListener:(t,s)=>tr(t,"resize",s),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Bn={current:void 0},zu=Bu({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!Bn.current){const t=new Lw({});t.mount(window),t.setOptions({layoutScroll:!0}),Bn.current=t}return Bn.current},resetTransform:(t,s)=>{t.style.transform=s!==void 0?s:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),Ow={pan:{Feature:sw},drag:{Feature:tw,ProjectionNode:zu,MeasureLayout:Fu}};function kc(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&&Qe.postRender(()=>i(s,dr(s)))}class $w extends qs{mount(){const{current:s}=this.node;s&&(this.unmount=ij(s,(a,r)=>(kc(this.node,r,"Start"),n=>kc(this.node,n,"End"))))}unmount(){}}class Uw extends qs{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=or(tr(this.node.current,"focus",()=>this.onFocus()),tr(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Rc(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&&Qe.postRender(()=>i(s,dr(s)))}class Bw extends qs{mount(){const{current:s}=this.node;s&&(this.unmount=dj(s,(a,r)=>(Rc(this.node,r,"Start"),(n,{success:i})=>Rc(this.node,n,i?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Ri=new WeakMap,Vn=new WeakMap,Vw=t=>{const s=Ri.get(t.target);s&&s(t)},zw=t=>{t.forEach(Vw)};function Hw({root:t,...s}){const a=t||document;Vn.has(a)||Vn.set(a,{});const r=Vn.get(a),n=JSON.stringify(s);return r[n]||(r[n]=new IntersectionObserver(zw,{root:t,...s})),r[n]}function qw(t,s,a){const r=Hw(s);return Ri.set(t,a),r.observe(t),()=>{Ri.delete(t),r.unobserve(t)}}const Ww={some:0,all:1};class Kw extends qs{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:Ww[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 qw(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 Yw={inView:{Feature:Kw},tap:{Feature:Bw},focus:{Feature:Uw},hover:{Feature:$w}},Xw={layout:{ProjectionNode:zu,MeasureLayout:Fu}},Zw={...FN,...Yw,...Ow,...Xw},Tt=Zj(Zw,dN),Dc=[{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:ai,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:Nx,color:"from-green-500 to-emerald-600",estimatedTime:"3-5 days",steps:5,features:["PO matching","Invoice verification","Multi-level approvals","Payment scheduling"]}];function Qw({open:t,onClose:s,onSelectTemplate:a}){var l;const[r,n]=x.useState(null),i=c=>{n(c)},o=()=>{r&&(a(r),s())};return e.jsx(et,{open:t,onOpenChange:s,children:e.jsxs(Xe,{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(Ze,{className:"sr-only",children:"Select a Template"}),e.jsx(qt,{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(lt,{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(Tt.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(Gr,{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:Dc.map((c,d)=>{const m=c.icon,u=r===c.id;return e.jsx(Tt.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(K,{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(ae,{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(Tt.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(Aa,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsx(re,{className:"text-xl mb-2",children:c.name}),e.jsx(ge,{className:"text-sm leading-relaxed",children:c.description})]})]}),e.jsxs(G,{className:"pt-0 space-y-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(ee,{variant:"secondary",className:"text-xs",children:c.category})}),e.jsx(dt,{}),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(Ie,{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(ct,{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,p)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-600",children:[e.jsx(je,{className:"w-3 h-3 text-green-600 flex-shrink-0"}),e.jsx("span",{children:h})]},p)),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(Tt.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(Nt,{className:"w-4 h-4"})]})]}),e.jsx(an,{children:r&&e.jsx(Tt.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=Dc.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 e1(t,s,a){const[r,n]=x.useState(Jw),[i,o]=x.useState(null),[l,c]=x.useState(t),[d,m]=x.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[u,h]=x.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[p,g]=x.useState([]);return x.useEffect(()=>{(async()=>{var w;try{const f=await ia("DOCUMENT_POLICY"),C={};f.forEach(k=>{C[k.configKey]=k.configValue});const b=parseInt(C.MAX_FILE_SIZE_MB||"10"),R=(C.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(k=>k.trim().toLowerCase());h({maxFileSizeMB:b,allowedFileTypes:R});const E=await ia("WORKFLOW_SHARING"),P=await ia("TAT_SETTINGS"),I=[...E,...P],j={};I.forEach(k=>{j[k.configKey]=k.configValue}),m({maxApprovalLevels:parseInt(j.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(j.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((w=j.ALLOW_ADD_SPECTATOR)==null?void 0:w.toLowerCase())==="true",maxSpectators:parseInt(j.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(f){console.error("Failed to load policies:",f)}})()},[]),x.useEffect(()=>{if(!t||!s)return;let v=!0;return(async()=>{try{c(!0);const w=await aa(s);if(!v||!w)return;const f=w.workflow||{},C=Array.isArray(w.approvals)?w.approvals:[],b=Array.isArray(w.participants)?w.participants:[],N=Array.isArray(w.documents)?w.documents.filter(_=>!_.isDeleted):[];g(N);const R=(f.priority||"").toString().toLowerCase(),E={standard:"standard",express:"express"},P=f.templateType==="TEMPLATE"?"existing-template":"custom",I=a.find(_=>_.id===P)||a[0]||null;o(I);const j=C.sort((_,Y)=>(_.levelNumber||0)-(Y.levelNumber||0)).map(_=>{const Y=Number(_.tatHours||24),F=Math.floor(Y/24),L=Y%24;return{id:_.approverId||`temp-${_.levelNumber}`,name:_.approverName||_.approverEmail||"",email:_.approverEmail||"",role:_.levelName||`Level ${_.levelNumber}`,department:"",avatar:(_.approverName||_.approverEmail||"XX").substring(0,2).toUpperCase(),level:_.levelNumber||1,canClose:!1,tat:F>0?F:L,tatType:F>0?"days":"hours",userId:_.approverId}}),k=b.filter(_=>(_.participantType||_.participant_type||"").toString().toUpperCase().trim()==="SPECTATOR"?!!(_.userEmail||_.user_email||_.email):!1).map((_,Y)=>{const F=_.userId||_.user_id||_.id,L=_.userName||_.user_name||_.name||"",A=_.userEmail||_.user_email||_.email||"",T=(L||A||"XX").split(" ").map(D=>D[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{id:F||`spectator-${s}-${Y}-${Date.now()}`,userId:F,name:L||A||"Spectator",email:A,role:"Spectator",department:_.department||"",avatar:T,level:1,canClose:!1}});n(_=>({..._,template:P,title:f.title||"",description:f.description||"",priority:E[R]||"standard",approvers:j,approverCount:j.length||1,spectators:k,maxLevel:Math.max(...j.map(Y=>Y.level||1),1)}))}catch(w){console.error("Failed to load draft:",w)}finally{v&&c(!1)}})(),()=>{v=!1}},[t,s,a]),{formData:r,setFormData:n,updateFormData:(v,w)=>{n(f=>({...f,[v]:w}))},selectedTemplate:i,setSelectedTemplate:o,loadingDraft:l,systemPolicy:d,documentPolicy:u,existingDocuments:p,setExistingDocuments:g}}const Pc=["Template Selection","Basic Information","Approval Workflow","Participants & Access","Documents & Attachments","Review & Submit"];function t1(t,s,a){const[r,n]=x.useState(t?2:1),i=Pc.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:Pc,isStepValid:l,nextStep:()=>{l()&&(window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}),r<i&&n(r+1))},prevStep:()=>{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 s1(){const[t,s]=x.useState({open:!1,type:"error",email:"",message:""}),[a,r]=x.useState({open:!1,violations:[]}),[n,i]=x.useState({open:!1,errors:[]});return{validationModal:t,policyViolationModal:a,documentErrorModal:n,openValidationModal:(h,p,g="")=>{s({open:!0,type:h,email:p,message:g})},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 a1(t,s){const a=typeof t=="number"?t:parseInt(String(t))||0;return s==="days"?a*24:a||24}function r1(t,s,a){var n;const r=a1(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 n1(t,s){return t.slice(0,s).map((a,r)=>{const n=r+1;return r1(a,n,n===s)})}function Ec(t,s,a){const r=new Set((t.approvers||[]).map(i=>{var o;return(o=i==null?void 0:i.email)==null?void 0:o.toLowerCase()}).filter(Boolean)),n=(t.spectators||[]).filter(i=>(i==null?void 0:i.email)&&!r.has(i.email.toLowerCase()));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=>({userId:(i==null?void 0:i.userId)||"",name:(i==null?void 0:i.name)||"",email:(i==null?void 0:i.email)||""})),ccList:[],participants:[]}}function Mc(t,s,a){const r=n1(t.approvers||[],t.approverCount||1);return{title:t.title,description:t.description,priority:t.priority==="express"?"EXPRESS":"STANDARD",approvalLevels:r,participants:[],deleteDocumentIds:a.length>0?a:void 0}}function i1(t,s){const a=t.slice(0,s);if(a.some(o=>!(o!=null&&o.email)||!o.email.trim()))return{valid:!1,message:"Please provide email addresses for all approvers."};const n=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return a.some(o=>!n.test((o==null?void 0:o.email)||""))?{valid:!1,message:"Please provide valid email addresses for all approvers."}:{valid:!0}}async function Hu(t,s){return{id:(await Wd(t,s||[],"SUPPORTING")).id}}async function qu(t,s,a,r){const n=a&&a.length>0,i=r.length>0;n||i?await L0(t,s,a||[],r):await _0(t,s)}async function Wu(t){await Zd(t)}async function o1(t,s){const a=await Hu(t,s);return await Wu(a.id),a}async function l1(t,s,a,r){await qu(t,s,a,r),await Wu(t)}function c1({formData:t,selectedTemplate:s,documents:a,documentsToDelete:r,user:n,isEditing:i,editRequestId:o,onSubmit:l}){const[c,d]=x.useState(!1),[m,u]=x.useState(!1);return{submitting:c,savingDraft:m,handleSubmit:async()=>{if(c||m)return;const g=i1(t.approvers||[],t.approverCount||1);if(!g.valid){alert(g.message);return}d(!0);try{if(i&&o){const y=Mc(t,n,r);await l1(o,y,a,r),l==null||l({...t,backendId:o,template:s})}else{const y=Ec(t,s,n),v=await o1(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 g=Mc(t,n,r);await qu(o,g,a,r),l==null||l({...t,backendId:o,template:s})}else{const g=Ec(t,s,n),y=await Hu(g,a);l==null||l({...t,backendId:y.id,template:s})}}catch(g){console.error("Failed to save draft:",g),u(!1)}}}}}async function d1(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 ys(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 ks({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 m1(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<r.length;i++){const o=r[i];if(o.userId||!o.email)continue;const l=await d1(o,s);if(!l.success)return{success:!1,error:l.error};try{const m=(((n=(await ys(o.email,1)).data)==null?void 0:n.data)||[])[0];if(m){const u=await ks({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});r[i]={...o,userId:u.userId,name:u.displayName||o.name,department:u.department||o.department,avatar:(u.displayName||u.email).substring(0,2).toUpperCase()}}}catch(c){console.error(`Failed to update approver ${o.email}:`,c)}}return{success:!0,validatedApprovers:r}}function u1({selectedTemplate:t,setSelectedTemplate:s,updateFormData:a,formData:r,currentStep:n,isStepValid:i,wizardNextStep:o,wizardPrevStep:l,user:c,openValidationModal:d,onSubmit:m}){const[u,h]=x.useState(!1),[p,g]=x.useState(null);return{showTemplateModal:u,setShowTemplateModal:h,previewDocument:p,selectTemplate:N=>{s(N),a("template",N.id),a("category",N.category),a("priority",N.priority);const R=new Date;R.setDate(R.getDate()+N.suggestedSLA),a("slaEndDate",R),N.id==="existing-template"&&h(!0)},handleTemplateSelection:N=>{m&&m({templateType:N})},nextStep:async()=>{var N;if(i()){if(window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}),n===3){const R=((N=c==null?void 0:c.email)==null?void 0:N.toLowerCase())||"",E=await m1(r.approvers,R);if(!E.success&&E.error){d(E.error.type,E.error.email,E.error.message);return}E.validatedApprovers&&a("approvers",E.validatedApprovers)}o()}},prevStep:()=>{l(),window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"})},handlePreviewDocument:(N,R)=>{if(R){const E=N.documentId||N.document_id||"";g({fileName:N.originalFileName||N.fileName||"Document",fileType:N.fileType||N.file_type||"application/octet-stream",fileUrl:Xd(E),fileSize:Number(N.fileSize||N.file_size||0),documentId:E})}else{const E=URL.createObjectURL(N);g({fileName:N.name,fileType:N.type||"application/octet-stream",fileUrl:E,fileSize:N.size,file:N})}},closePreview:()=>{p!=null&&p.fileUrl&&(p!=null&&p.file)&&URL.revokeObjectURL(p.fileUrl),g(null)}}}const Ic=[{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:Kr,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:Ae,estimatedTime:"1-2 days",commonApprovers:["Department Head","Manager"],suggestedSLA:2,priority:"medium",fields:{timeline:!0}}];function h1({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+1<t?"bg-green-600 text-white":i+1===t?"bg-blue-600 text-white":"bg-gray-200 text-gray-600"}`,"data-testid":`wizard-stepper-desktop-step-${i+1}-indicator`,children:i+1<t?e.jsx(Aa,{className:"w-4 h-4"}):i+1}),i<a.length-1&&e.jsx("div",{className:`w-8 md:w-12 lg:w-16 h-1 mx-1 md:mx-2 ${i+1<t?"bg-green-600":"bg-gray-200"}`,"data-testid":`wizard-stepper-desktop-step-${i+1}-connector`})]},i))}),e.jsx("div",{className:"hidden lg:flex justify-between text-xs text-gray-600 mt-2","data-testid":"wizard-stepper-desktop-labels",children:a.map((n,i)=>e.jsx("span",{className:`${i+1===t?"font-semibold text-blue-600":""}`,"data-testid":`wizard-stepper-desktop-label-${i+1}`,children:n},i))})]})]})})}function p1({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(xs,{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(Ue,{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(Ue,{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(jd,{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(Nt,{className:"h-3 w-3 sm:h-4 sm:w-4 ml-1 sm:ml-2"})]})]})]})})}const Fc=t=>{switch(t){case"high":return e.jsx(ls,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(ct,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(Vs,{className:"w-4 h-4 text-green-600"});default:return e.jsx(ct,{className:"w-4 h-4 text-gray-600"})}};function x1({templates:t,selectedTemplate:s,onSelectTemplate:a}){return e.jsxs(Tt.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(Tt.div,{whileHover:{scale:1.03},whileTap:{scale:.98},transition:{type:"spring",stiffness:300,damping:20},"data-testid":`template-card-${r.id}`,children:e.jsxs(K,{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(ae,{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(Tt.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(Aa,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsx(re,{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(ee,{variant:"secondary",className:"text-xs","data-testid":`template-card-${r.id}-category`,children:r.category}),Fc(r.priority)]})]})]}),e.jsxs(G,{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(dt,{}),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(Ie,{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(nt,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[r.commonApprovers.length," approvers"]})]})]})]})]})},r.id))}),e.jsx(an,{children:s&&e.jsx(Tt.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(K,{className:"bg-gradient-to-br from-blue-50 to-indigo-50 border-2 border-blue-200",children:[e.jsx(ae,{children:e.jsxs(re,{className:"flex items-center gap-2 text-blue-900","data-testid":"template-details-title",children:[e.jsx(ar,{className:"w-5 h-5"}),s.name," - Template Details"]})}),e.jsxs(G,{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(J,{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(J,{className:"text-blue-900 font-semibold",children:"Priority Level"}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[Fc(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(J,{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(J,{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(ee,{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 g1({className:t,...s}){return e.jsx(vp,{"data-slot":"radio-group",className:ce("grid gap-3",t),...s})}function _c({className:t,...s}){return e.jsx(bp,{"data-slot":"radio-group-item",className:ce("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(jp,{"data-slot":"radio-group-indicator",className:"relative flex items-center justify-center",children:e.jsx(wx,{className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}function f1({formData:t,selectedTemplate:s,updateFormData:a}){return e.jsxs(Tt.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(Ae,{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(J,{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(fe,{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(J,{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(rm,{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(J,{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(g1,{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(_c,{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(Li,{className:"w-4 h-4 text-red-600"}),e.jsx(J,{htmlFor:"express",className:"font-medium text-red-900 cursor-pointer",children:"Express"}),e.jsx(ee,{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(_c,{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(Ie,{className:"w-4 h-4 text-blue-600"}),e.jsx(J,{htmlFor:"standard",className:"font-medium text-blue-900 cursor-pointer",children:"Standard"}),e.jsx(ee,{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(J,{htmlFor:"amount",className:"text-base font-semibold",children:"Budget Amount"}),e.jsx(fe,{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(J,{className:"text-base font-semibold",children:"Currency"}),e.jsxs(Te,{value:t.currency,onValueChange:r=>a("currency",r),"data-testid":"basic-information-currency-select",children:[e.jsx(Re,{className:"h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm",children:e.jsx(ke,{})}),e.jsxs(De,{children:[e.jsx(U,{value:"USD",children:"USD ($)"}),e.jsx(U,{value:"EUR",children:"EUR (€)"}),e.jsx(U,{value:"GBP",children:"GBP (£)"}),e.jsx(U,{value:"INR",children:"INR (₹)"})]})]})]})]}),(s==null?void 0:s.fields.vendor)&&e.jsxs("div",{"data-testid":"basic-information-vendor-field",children:[e.jsx(J,{htmlFor:"vendor",className:"text-base font-semibold",children:"Vendor/Supplier"}),e.jsx(fe,{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(J,{htmlFor:"costCenter",className:"text-base font-semibold",children:"Cost Center"}),e.jsx(fe,{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(J,{htmlFor:"project",className:"text-base font-semibold",children:"Related Project"}),e.jsx(fe,{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 y1(){const[t,s]=x.useState([]),[a,r]=x.useState(!1),n=x.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),p=((m=(await ys(u,d)).data)==null?void 0:m.data)||[];s(p)}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 ks({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 v1(){const[t,s]=x.useState({}),[a,r]=x.useState({}),n=x.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),p=((m=(await ys(u,d)).data)==null?void 0:m.data)||[];s(g=>({...g,[l]:p}))}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 b1({formData:t,updateFormData:s,onValidationError:a}){var d;const{userSearchResults:r,userSearchLoading:n,searchUsersForIndex:i,clearSearchForIndex:o}=v1();x.useEffect(()=>{const m=t.approverCount||1,u=t.approvers||[];if(u.length<m){const h=[...u];for(let p=u.length;p<m;p++)h[p]||(h[p]={email:"",name:"",level:p+1,tat:""});s("approvers",h)}else u.length>m&&s("approvers",u.slice(0,m))},[t.approverCount,s]);const l=(m,u)=>{var y,v,w,f,C;const h=[...t.approvers],g=((y=h[m])==null?void 0:y.email)!==u;if(h[m]={...h[m],email:u,level:m+1,userId:g||(v=h[m])==null?void 0:v.userId,name:g||(w=h[m])==null?void 0:w.name,department:g||(f=h[m])==null?void 0:f.department,avatar:g||(C=h[m])==null?void 0:C.avatar},s("approvers",h),!u||!u.startsWith("@")||u.length<2){o(m);return}i(m,u,10)},c=async(m,u)=>{var h,p;try{if((h=t.approvers)==null?void 0:h.some((f,C)=>{var b,N;return C!==m&&(f.userId===u.userId||((b=f.email)==null?void 0:b.toLowerCase())===((N=u.email)==null?void 0:N.toLowerCase()))})){a({type:"error",email:u.email,message:"This user is already added as an approver in another level."});return}if((p=t.spectators)==null?void 0:p.some(f=>{var C,b;return f.userId===u.userId||((C=f.email)==null?void 0:C.toLowerCase())===((b=u.email)==null?void 0:b.toLowerCase())})){a({type:"error",email:u.email,message:"This user is already added as a spectator. A user cannot be both an approver and a spectator."});return}const v=await ks({userId:u.userId,email:u.email,displayName:u.displayName,firstName:u.firstName,lastName:u.lastName,department:u.department,phone:u.phone,mobilePhone:u.mobilePhone,designation:u.designation,jobTitle:u.jobTitle,manager:u.manager,employeeId:u.employeeId,employeeNumber:u.employeeNumber,secondEmail:u.secondEmail,location:u.location}),w=[...t.approvers];w[m]={...w[m],email:u.email,name:u.displayName||[u.firstName,u.lastName].filter(Boolean).join(" "),userId:v.userId,level:m+1},s("approvers",w),o(m)}catch(g){console.error("Failed to ensure user exists:",g),a({type:"error",email:u.email,message:"Failed to validate user. Please try again."})}};return e.jsxs(Tt.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(nt,{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(K,{"data-testid":"approval-workflow-config-card",children:[e.jsxs(ae,{children:[e.jsxs(re,{className:"flex items-center gap-2","data-testid":"approval-workflow-config-title",children:[e.jsx(Ls,{className:"w-5 h-5"}),"Approval Configuration"]}),e.jsx(ge,{children:"Configure how many approvers you need and define the approval sequence."})]}),e.jsx(G,{className:"space-y-6",children:e.jsxs("div",{"data-testid":"approval-workflow-count-field",children:[e.jsx(J,{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 m=t.approverCount||1,u=Math.max(1,m-1);s("approverCount",u),t.approvers.length>u&&s("approvers",t.approvers.slice(0,u))},disabled:(t.approverCount||1)<=1,"data-testid":"approval-workflow-decrease-count",children:e.jsx(Cx,{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 m=t.approverCount||1,u=Math.min(10,m+1);s("approverCount",u)},disabled:(t.approverCount||1)>=10,"data-testid":"approval-workflow-increase-count",children:e.jsx(_s,{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(K,{"data-testid":"approval-workflow-hierarchy-card",children:[e.jsxs(ae,{children:[e.jsxs(re,{className:"flex items-center gap-2","data-testid":"approval-workflow-hierarchy-title",children:[e.jsx(It,{className:"w-5 h-5"}),"Approval Hierarchy *"]}),e.jsxs(ge,{children:["Define the approval sequence. Each approver will review the request in order from Level 1 to Level ",t.approverCount||1,"."]})]}),e.jsxs(G,{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(it,{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(ee,{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},(m,u)=>{var y,v;const h=u+1,p=h===(t.approverCount||1),g=t.approvers[u]||{email:"",tat:""};return e.jsxs("div",{className:"space-y-3","data-testid":`approval-workflow-approver-level-${h}`,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 ${g.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 ${g.email?"bg-green-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold",children:h})}),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 ",h]}),p&&e.jsx(ee,{variant:"destructive",className:"text-xs",children:"FINAL APPROVER"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{"data-testid":`approval-workflow-approver-${h}-email-field`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(J,{htmlFor:`approver-${h}`,className:"text-sm font-medium",children:"Email Address *"}),g.email&&g.userId&&e.jsxs(ee,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(je,{className:"w-3 h-3 mr-1"}),"Verified"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(fe,{id:`approver-${h}`,type:"email",placeholder:"approver@royalenfield.com",value:g.email||"",onChange:w=>l(u,w.target.value),className:"h-10 border-2 border-gray-300 focus:border-blue-500 mt-1 w-full","data-testid":`approval-workflow-approver-${h}-email-input`}),(n[u]||(((y=r[u])==null?void 0:y.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[u]?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:(v=r[u])==null?void 0:v.map(w=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>c(u,w),"data-testid":`approval-workflow-approver-${h}-search-result-${w.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:w.displayName||w.email}),e.jsx("div",{className:"text-xs text-gray-600",children:w.email})]},w.userId))})})]})]}),e.jsxs("div",{"data-testid":`approval-workflow-approver-${h}-tat-field`,children:[e.jsx(J,{htmlFor:`tat-${h}`,className:"text-sm font-medium",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(fe,{id:`tat-${h}`,type:"number",placeholder:g.tatType==="days"?"7":"24",min:"1",max:g.tatType==="days"?"30":"720",value:g.tat||"",onChange:w=>{const f=[...t.approvers];f[u]={...f[u],tat:parseInt(w.target.value)||"",level:h,tatType:g.tatType||"hours"},s("approvers",f)},className:"h-10 border-2 border-gray-300 focus:border-blue-500 flex-1","data-testid":`approval-workflow-approver-${h}-tat-input`}),e.jsxs(Te,{value:g.tatType||"hours",onValueChange:w=>{const f=[...t.approvers];f[u]={...f[u],tatType:w,level:h,tat:""},s("approvers",f)},"data-testid":`approval-workflow-approver-${h}-tat-type-select`,children:[e.jsx(Re,{className:"w-20 h-10 border-2 border-gray-300",children:e.jsx(ke,{})}),e.jsxs(De,{children:[e.jsx(U,{value:"hours",children:"Hours"}),e.jsx(U,{value:"days",children:"Days"})]})]})]})]})]})]})]})})]},h)})]})]}),e.jsxs("div",{className:"mt-6 space-y-4",children:[e.jsx("div",{className:"p-4 bg-blue-50 rounded-lg border border-blue-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ar,{className:"w-5 h-5 text-blue-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-blue-900 mb-1",children:"Approval Flow Summary"}),e.jsxs("p",{className:"text-sm text-blue-700",children:["Your request will follow this sequence: ",e.jsx("strong",{children:"You (Initiator)"})," → ",Array.from({length:t.approverCount||1},(m,u)=>`Level ${u+1} Approver`).join(" → "),". The final approver can close the request."]})]})]})}),e.jsx("div",{className:"p-4 bg-gradient-to-r from-emerald-50 to-teal-50 rounded-lg border border-emerald-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ie,{className:"w-5 h-5 text-emerald-600 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"font-semibold text-emerald-900",children:"TAT Summary"}),e.jsx("div",{className:"text-right",children:(()=>{var h;const m=((h=t.approvers)==null?void 0:h.reduce((p,g)=>{const y=Number(g.tat||0);return(g.tatType||"hours")==="days"?p+y:p+y/24},0))||0,u=Math.ceil(m);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-lg font-bold text-emerald-800",children:[u," ",u===1?"Day":"Days"]}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Total Duration"})]})})()})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:(d=t.approvers)==null?void 0:d.map((m,u)=>{const h=Number(m.tat||0),g=(m.tatType||"hours")==="days"?h*24:h;return h?e.jsx("div",{className:"bg-white/60 p-2 rounded border border-emerald-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-sm font-medium text-emerald-900",children:["Level ",u+1]}),e.jsxs("span",{className:"text-sm text-emerald-700",children:[g," ",g===1?"hour":"hours"]})]})},u):null})}),(()=>{var h;const m=((h=t.approvers)==null?void 0:h.reduce((p,g)=>{const y=Number(g.tat||0);return(g.tatType||"hours")==="days"?p+y*24:p+y},0))||0,u=Math.ceil(m/8);return m===0?null:e.jsxs("div",{className:"bg-white/80 p-3 rounded border border-emerald-200",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-center",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-lg font-bold text-emerald-800",children:[m,"h"]}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Total Hours"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-lg font-bold text-emerald-800",children:u}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Working Days*"})]})]}),e.jsx("p",{className:"text-xs text-emerald-600 mt-2 text-center",children:"*Based on 8-hour working days"})]})})()]})]})]})})]})]})]})}function j1({formData:t,updateFormData:s,onValidationError:a,initiatorEmail:r}){const[n,i]=x.useState(""),{searchResults:o,searchLoading:l,searchUsersDebounced:c,clearSearch:d,ensureUser:m}=y1(),u=g=>{if(i(g),!g||!g.startsWith("@")||g.length<2){d();return}c(g,10)},h=async g=>{var y,v;if(g){if(g.email.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:g.email,message:"You cannot add yourself as a spectator."});return}const w=t.spectators.some(C=>{var b,N;return C.userId===g.userId||((b=C.email)==null?void 0:b.toLowerCase())===((N=g.email)==null?void 0:N.toLowerCase())}),f=(y=t.approvers)==null?void 0:y.some(C=>{var b,N;return C.userId===g.userId||((b=C.email)==null?void 0:b.toLowerCase())===((N=g.email)==null?void 0:N.toLowerCase())});if(w){a({type:"error",email:g.email,message:"This user is already added as a spectator."});return}if(f){a({type:"error",email:g.email,message:"This user is already added as an approver. A user cannot be both an approver and a spectator."});return}try{const C=await m(g),b={id:C.userId,userId:C.userId,name:C.displayName||g.email.split("@")[0],email:C.email,avatar:(C.displayName||C.email).substring(0,2).toUpperCase(),role:"Spectator",department:C.department||"",level:1,canClose:!1},N=[...t.spectators,b];s("spectators",N),i(""),d()}catch{a({type:"error",email:g.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 w=t.spectators.some(C=>{var b;return((b=C.email)==null?void 0:b.toLowerCase())===n.toLowerCase()}),f=(v=t.approvers)==null?void 0:v.some(C=>{var b;return((b=C.email)==null?void 0:b.toLowerCase())===n.toLowerCase()});if(w){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}}},p=g=>{const y=t.spectators.filter(v=>v.id!==g);s("spectators",y)};return e.jsxs(Tt.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(kt,{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(K,{"data-testid":"participants-spectators-card",children:[e.jsxs(ae,{children:[e.jsxs(re,{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(kt,{className:"w-4 h-4"}),"Spectators"]}),e.jsx(ee,{variant:"outline",className:"text-xs","data-testid":"participants-spectators-count",children:t.spectators.length})]}),e.jsx(ge,{children:"Users who can view and comment but cannot approve"})]}),e.jsxs(G,{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(fe,{placeholder:"Use @ sign to add a user",value:n,onChange:g=>u(g.target.value),onKeyPress:async g=>{g.key==="Enter"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)&&(g.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(g=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>h(g),"data-testid":`participants-spectators-search-result-${g.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:g.displayName||g.email}),e.jsx("div",{className:"text-xs text-gray-600",children:g.email})]},g.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(ar,{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(g=>e.jsxs("div",{className:"flex items-center justify-between p-2 bg-teal-50 rounded-lg","data-testid":`participants-spectator-${g.id}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bt,{className:"h-6 w-6",children:e.jsx(jt,{className:"bg-teal-600 text-white text-xs",children:g.avatar})}),e.jsx("span",{className:"text-sm font-medium",children:g.name})]}),e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>p(g.id),"data-testid":`participants-spectator-${g.id}-remove`,children:e.jsx(lt,{className:"h-3 w-3"})})]},g.id))})]})]})})})]})}function N1({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 w=t.maxFileSizeMB*1024*1024,f=[],C=[];v.forEach(b=>{if(b.size>w){f.push({fileName:b.name,reason:`File size exceeds the maximum allowed size of ${t.maxFileSizeMB}MB. Current size: ${(b.size/1048576).toFixed(2)}MB`});return}const N=b.name.toLowerCase(),R=N.substring(N.lastIndexOf(".")+1);if(!t.allowedFileTypes.includes(R)){f.push({fileName:b.name,reason:`File type "${R}" is not allowed. Allowed types: ${t.allowedFileTypes.join(", ")}`});return}C.push(b)}),C.length>0&&i([...a,...C]),f.length>0&&d&&d(f),y.target&&(y.target.value="")},h=y=>{const v=a.filter((w,f)=>f!==y);i(v)},p=y=>{l([...n,y])},g=(y,v=!1)=>{if(v){const w=(y.fileType||y.file_type||"").toLowerCase(),f=(y.originalFileName||y.fileName||"").toLowerCase();return w.includes("image")||w.includes("pdf")||f.endsWith(".jpg")||f.endsWith(".jpeg")||f.endsWith(".png")||f.endsWith(".gif")||f.endsWith(".pdf")}else{const w=(y.type||"").toLowerCase(),f=(y.name||"").toLowerCase();return w.includes("image")||w.includes("pdf")||f.endsWith(".jpg")||f.endsWith(".jpeg")||f.endsWith(".png")||f.endsWith(".gif")||f.endsWith(".pdf")}};return e.jsxs(Tt.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(Na,{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(K,{"data-testid":"documents-upload-card",children:[e.jsxs(ae,{children:[e.jsxs(re,{className:"flex items-center gap-2","data-testid":"documents-upload-title",children:[e.jsx(Ae,{className:"w-5 h-5"}),"File Upload"]}),e.jsxs(ge,{children:["Attach supporting documents. Max ",t.maxFileSizeMB,"MB per file. Allowed types: ",t.allowedFileTypes.join(", ")]})]}),e.jsx(G,{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(Na,{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(_s,{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(K,{"data-testid":"documents-existing-card",children:[e.jsx(ae,{children:e.jsxs(re,{className:"flex items-center justify-between","data-testid":"documents-existing-title",children:[e.jsx("span",{children:"Existing Documents"}),e.jsxs(ee,{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(G,{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(Ae,{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:[g(y,!0)&&e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>c(y,!0),"data-testid":`documents-existing-${v}-preview`,children:e.jsx(kt,{className:"h-4 w-4"})}),e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>p(v),"data-testid":`documents-existing-${v}-delete`,children:e.jsx(lt,{className:"h-4 w-4 text-red-600"})})]})]},v)})})})]}),a.length>0&&e.jsxs(K,{"data-testid":"documents-new-card",children:[e.jsx(ae,{children:e.jsxs(re,{className:"flex items-center justify-between","data-testid":"documents-new-title",children:[e.jsx("span",{children:"New Files to Upload"}),e.jsxs(ee,{variant:"secondary","data-testid":"documents-new-count",children:[a.length," file",a.length!==1?"s":""]})]})}),e.jsx(G,{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(Ae,{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:[g(y,!1)&&e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>c(y,!1),"data-testid":`documents-new-${v}-preview`,children:e.jsx(kt,{className:"h-4 w-4"})}),e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>h(v),"data-testid":`documents-new-${v}-remove`,children:e.jsx(lt,{className:"h-4 w-4"})})]})]},v))})})]})]})]})}const w1=t=>{switch(t){case"high":return e.jsx(ls,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(ct,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(Vs,{className:"w-4 h-4 text-green-600"});default:return e.jsx(ct,{className:"w-4 h-4 text-gray-600"})}};function C1({formData:t,selectedTemplate:s}){return e.jsxs(Tt.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(je,{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(K,{className:"border-2 border-green-200 bg-green-50/50","data-testid":"review-submit-overview-card",children:[e.jsx(ae,{children:e.jsxs(re,{className:"flex items-center gap-2 text-green-900","data-testid":"review-submit-overview-title",children:[e.jsx(jd,{className:"w-5 h-5"}),"Request Overview"]})}),e.jsxs(G,{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(J,{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(ee,{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(J,{className:"text-green-900 font-semibold",children:"Priority"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[w1(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(J,{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(J,{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(K,{"data-testid":"review-submit-basic-info-card",children:[e.jsx(ae,{children:e.jsxs(re,{className:"flex items-center gap-2","data-testid":"review-submit-basic-info-title",children:[e.jsx(Ae,{className:"w-5 h-5"}),"Basic Information"]})}),e.jsxs(G,{className:"space-y-4",children:[e.jsxs("div",{"data-testid":"review-submit-basic-info-description",children:[e.jsx(J,{className:"font-semibold",children:"Description"}),e.jsx("div",{className:"mt-1 p-3 bg-gray-50 rounded-lg border",children:e.jsx(Fs,{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(Sx,{className:"w-4 h-4 text-blue-600"}),e.jsx(J,{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(K,{className:"border-2 border-orange-200 bg-orange-50/50","data-testid":"review-submit-approval-card",children:[e.jsxs(ae,{children:[e.jsxs(re,{className:"flex items-center gap-2 text-orange-900","data-testid":"review-submit-approval-title",children:[e.jsx(nt,{className:"w-5 h-5"}),"Approval Workflow"]}),e.jsx(ge,{className:"text-orange-700",children:"Sequential approval hierarchy with TAT (Turn Around Time) for each level"})]}),e.jsx(G,{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(ee,{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(K,{"data-testid":"review-submit-participants-card",children:[e.jsx(ae,{children:e.jsxs(re,{className:"flex items-center gap-2","data-testid":"review-submit-participants-title",children:[e.jsx(kt,{className:"w-5 h-5"}),"Participants & Access Control"]})}),e.jsx(G,{className:"space-y-4",children:t.spectators.length>0&&e.jsxs("div",{"data-testid":"review-submit-participants-spectators",children:[e.jsxs(J,{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(ee,{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(K,{"data-testid":"review-submit-documents-card",children:[e.jsxs(ae,{children:[e.jsxs(re,{className:"flex items-center gap-2","data-testid":"review-submit-documents-title",children:[e.jsx(Na,{className:"w-5 h-5"}),"Documents & Attachments"]}),e.jsxs(ge,{children:[t.documents.length," document",t.documents.length!==1?"s":""," attached to this request"]})]}),e.jsx(G,{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(Ae,{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(K,{className:"border-2 border-blue-200 bg-blue-50/50","data-testid":"review-submit-confirmation-card",children:e.jsx(G,{className:"pt-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(je,{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 S1({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(xs,{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 A1({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(an,{mode:"wait",children:t})})})}function T1({modal:t,onClose:s}){return e.jsx(et,{open:t.open,onOpenChange:a=>!a&&s(),"data-testid":"create-request-validation-modal",children:e.jsxs(Xe,{className:"sm:max-w-md",children:[e.jsxs(tt,{children:[e.jsxs(Ze,{className:"flex items-center gap-2","data-testid":"validation-modal-title",children:[t.type==="self-assign"&&e.jsxs(e.Fragment,{children:[e.jsx(Pe,{className:"w-5 h-5 text-amber-600"}),"Cannot Add Yourself"]}),t.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsx(Pe,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}),t.type==="error"&&e.jsxs(e.Fragment,{children:[e.jsx(Pe,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})]}),e.jsx(qt,{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(Kr,{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(wt,{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 k1({modal:t,documentPolicy:s,onClose:a}){return e.jsx(et,{open:t.open,onOpenChange:r=>!r&&a(),"data-testid":"create-request-document-error-modal",children:e.jsxs(Xe,{className:"sm:max-w-lg",children:[e.jsxs(tt,{children:[e.jsxs(Ze,{className:"flex items-center gap-2","data-testid":"document-error-modal-title",children:[e.jsx(Pe,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(qt,{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(wt,{children:e.jsx(M,{onClick:a,className:"w-full sm:w-auto","data-testid":"document-error-modal-ok-button",children:"OK"})})]})})}function Lc({onBack:t,onSubmit:s,requestId:a,isEditMode:r=!1}){const n=rr(),i=Hs(),o=n.requestId||a||"",l=r&&!!o,{user:c}=Mt(),{formData:d,updateFormData:m,selectedTemplate:u,setSelectedTemplate:h,loadingDraft:p,systemPolicy:g,documentPolicy:y,existingDocuments:v,setExistingDocuments:w}=e1(l,o,Ic),{currentStep:f,totalSteps:C,stepNames:b,isStepValid:N,nextStep:R,prevStep:E}=t1(l,u,d),[P,I]=x.useState([]),[j,k]=x.useState([]),_=x.useRef(null),{validationModal:Y,policyViolationModal:F,documentErrorModal:L,openValidationModal:A,closeValidationModal:S,closePolicyViolationModal:T,openDocumentErrorModal:D,closeDocumentErrorModal:H}=s1(),{submitting:z,savingDraft:Z,handleSubmit:O,handleSaveDraft:se}=c1({formData:d,selectedTemplate:u,documents:P,documentsToDelete:j,user:c,isEditing:l,editRequestId:o,onSubmit:s}),{showTemplateModal:te,setShowTemplateModal:$,previewDocument:X,selectTemplate:ne,handleTemplateSelection:q,nextStep:Q,prevStep:oe,handlePreviewDocument:W,closePreview:me}=u1({selectedTemplate:u,setSelectedTemplate:h,updateFormData:m,formData:d,currentStep:f,isStepValid:N,wizardNextStep:R,wizardPrevStep:E,user:c,openValidationModal:A,onSubmit:s}),we=x.useCallback(()=>{f===1||f===3||f===4?t?t():window.history.length>1?window.history.back():i("/dashboard",{replace:!0}):oe()},[f,t,i,oe]),Ee=x.useRef(!0),Fe=x.useRef(!1);x.useEffect(()=>{Ee.current&&d.documents&&d.documents.length>0&&!Fe.current&&(I(d.documents),Fe.current=!0),Ee.current=!1},[d.documents]);const le=x.useRef(!1),ye=x.useRef(P);x.useEffect(()=>{if(le.current){le.current=!1,ye.current=P;return}ye.current!==P&&(m("documents",P),ye.current=P)},[P]);const Ve=()=>{switch(f){case 1:return e.jsx(x1,{templates:Ic,selectedTemplate:u,onSelectTemplate:ne});case 2:return e.jsx(f1,{formData:d,selectedTemplate:u,updateFormData:m});case 3:return e.jsx(b1,{formData:d,updateFormData:m,onValidationError:Le=>A(Le.type,Le.email,Le.message)});case 4:return e.jsx(j1,{formData:d,updateFormData:m,onValidationError:Le=>A(Le.type,Le.email,Le.message),initiatorEmail:(c==null?void 0:c.email)||""});case 5:return e.jsx(N1,{documentPolicy:y,isEditing:l,documents:P,existingDocuments:v,documentsToDelete:j,onDocumentsChange:I,onExistingDocumentsChange:w,onDocumentsToDeleteChange:k,onPreviewDocument:W,onDocumentErrors:Le=>D(Le),fileInputRef:_});case 6:return e.jsx(C1,{formData:d,selectedTemplate:u});default:return null}};return p?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(S1,{isEditing:l,currentStep:f,totalSteps:C,stepNames:b,onBack:we}),e.jsx(h1,{currentStep:f,totalSteps:C,stepNames:b}),e.jsx(A1,{children:Ve()}),e.jsx(p1,{currentStep:f,totalSteps:C,isStepValid:N(),onPrev:oe,onNext:Q,onSubmit:O,onSaveDraft:se,submitting:z,savingDraft:Z,loadingDraft:p,isEditing:l}),e.jsx(Qw,{open:te,onClose:()=>$(!1),onSelectTemplate:q}),X&&e.jsx(Yi,{fileName:X.fileName,fileType:X.fileType,fileUrl:X.fileUrl,fileSize:X.fileSize,open:!!X,onClose:me,onDownload:async()=>{if(X.file){const Le=document.createElement("a");Le.href=X.fileUrl,Le.download=X.fileName,document.body.appendChild(Le),Le.click(),document.body.removeChild(Le)}else X.documentId&&await li(X.documentId)},attachmentId:X.documentId}),e.jsx(T1,{modal:Y,onClose:S}),e.jsx(k1,{modal:L,documentPolicy:y,onClose:H}),e.jsx(lm,{open:F.open,onClose:T,violations:F.violations,policyDetails:{maxApprovalLevels:g.maxApprovalLevels,maxParticipants:g.maxParticipants,allowSpectators:g.allowSpectators,maxSpectators:g.maxSpectators}})]})}var Se=function(){return Se=Object.assign||function(s){for(var a,r=1,n=arguments.length;r<n;r++){a=arguments[r];for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(s[i]=a[i])}return s},Se.apply(this,arguments)};function R1(t,s){var a={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&s.indexOf(r)<0&&(a[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,r=Object.getOwnPropertySymbols(t);n<r.length;n++)s.indexOf(r[n])<0&&Object.prototype.propertyIsEnumerable.call(t,r[n])&&(a[r[n]]=t[r[n]]);return a}function Ku(t,s,a){for(var r=0,n=s.length,i;r<n;r++)(i||!(r in s))&&(i||(i=Array.prototype.slice.call(s,0,r)),i[r]=s[r]);return t.concat(i||Array.prototype.slice.call(s))}function mr(t){return t.mode==="multiple"}function ur(t){return t.mode==="range"}function ln(t){return t.mode==="single"}var D1={root:"rdp",multiple_months:"rdp-multiple_months",with_weeknumber:"rdp-with_weeknumber",vhidden:"rdp-vhidden",button_reset:"rdp-button_reset",button:"rdp-button",caption:"rdp-caption",caption_start:"rdp-caption_start",caption_end:"rdp-caption_end",caption_between:"rdp-caption_between",caption_label:"rdp-caption_label",caption_dropdowns:"rdp-caption_dropdowns",dropdown:"rdp-dropdown",dropdown_month:"rdp-dropdown_month",dropdown_year:"rdp-dropdown_year",dropdown_icon:"rdp-dropdown_icon",months:"rdp-months",month:"rdp-month",table:"rdp-table",tbody:"rdp-tbody",tfoot:"rdp-tfoot",head:"rdp-head",head_row:"rdp-head_row",head_cell:"rdp-head_cell",nav:"rdp-nav",nav_button:"rdp-nav_button",nav_button_previous:"rdp-nav_button_previous",nav_button_next:"rdp-nav_button_next",nav_icon:"rdp-nav_icon",row:"rdp-row",weeknumber:"rdp-weeknumber",cell:"rdp-cell",day:"rdp-day",day_today:"rdp-day_today",day_outside:"rdp-day_outside",day_selected:"rdp-day_selected",day_disabled:"rdp-day_disabled",day_hidden:"rdp-day_hidden",day_range_start:"rdp-day_range_start",day_range_end:"rdp-day_range_end",day_range_middle:"rdp-day_range_middle"};function P1(t,s){return xe(t,"LLLL y",s)}function E1(t,s){return xe(t,"d",s)}function M1(t,s){return xe(t,"LLLL",s)}function I1(t){return"".concat(t)}function F1(t,s){return xe(t,"cccccc",s)}function _1(t,s){return xe(t,"yyyy",s)}var L1=Object.freeze({__proto__:null,formatCaption:P1,formatDay:E1,formatMonthCaption:M1,formatWeekNumber:I1,formatWeekdayName:F1,formatYearCaption:_1}),O1=function(t,s,a){return xe(t,"do MMMM (EEEE)",a)},$1=function(){return"Month: "},U1=function(){return"Go to next month"},B1=function(){return"Go to previous month"},V1=function(t,s){return xe(t,"cccc",s)},z1=function(t){return"Week n. ".concat(t)},H1=function(){return"Year: "},q1=Object.freeze({__proto__:null,labelDay:O1,labelMonthDropdown:$1,labelNext:U1,labelPrevious:B1,labelWeekNumber:z1,labelWeekday:V1,labelYearDropdown:H1});function W1(){var t="buttons",s=D1,a=_p,r={},n={},i=1,o={},l=new Date;return{captionLayout:t,classNames:s,formatters:L1,labels:q1,locale:a,modifiersClassNames:r,modifiers:n,numberOfMonths:i,styles:o,today:l,mode:"default"}}function K1(t){var s=t.fromYear,a=t.toYear,r=t.fromMonth,n=t.toMonth,i=t.fromDate,o=t.toDate;return r?i=Yt(r):s&&(i=new Date(s,0,1)),n?o=Mi(n):a&&(o=new Date(a,11,31)),{fromDate:i?Ko(i):void 0,toDate:o?Ko(o):void 0}}var Gu=x.createContext(void 0);function G1(t){var s,a=t.initialProps,r=W1(),n=K1(a),i=n.fromDate,o=n.toDate,l=(s=a.captionLayout)!==null&&s!==void 0?s:r.captionLayout;l!=="buttons"&&(!i||!o)&&(l="buttons");var c;(ln(a)||mr(a)||ur(a))&&(c=a.onSelect);var d=Se(Se(Se({},r),a),{captionLayout:l,classNames:Se(Se({},r.classNames),a.classNames),components:Se({},a.components),formatters:Se(Se({},r.formatters),a.formatters),fromDate:i,labels:Se(Se({},r.labels),a.labels),mode:a.mode||r.mode,modifiers:Se(Se({},r.modifiers),a.modifiers),modifiersClassNames:Se(Se({},r.modifiersClassNames),a.modifiersClassNames),onSelect:c,styles:Se(Se({},r.styles),a.styles),toDate:o});return e.jsx(Gu.Provider,{value:d,children:t.children})}function Ge(){var t=x.useContext(Gu);if(!t)throw new Error("useDayPicker must be used within a DayPickerProvider.");return t}function Yu(t){var s=Ge(),a=s.locale,r=s.classNames,n=s.styles,i=s.formatters.formatCaption;return e.jsx("div",{className:r.caption_label,style:n.caption_label,"aria-live":"polite",role:"presentation",id:t.id,children:i(t.displayMonth,{locale:a})})}function Y1(t){return e.jsx("svg",Se({width:"8px",height:"8px",viewBox:"0 0 120 120","data-testid":"iconDropdown"},t,{children:e.jsx("path",{d:"M4.22182541,48.2218254 C8.44222828,44.0014225 15.2388494,43.9273804 19.5496459,47.9996989 L19.7781746,48.2218254 L60,88.443 L100.221825,48.2218254 C104.442228,44.0014225 111.238849,43.9273804 115.549646,47.9996989 L115.778175,48.2218254 C119.998577,52.4422283 120.07262,59.2388494 116.000301,63.5496459 L115.778175,63.7781746 L67.7781746,111.778175 C63.5577717,115.998577 56.7611506,116.07262 52.4503541,112.000301 L52.2218254,111.778175 L4.22182541,63.7781746 C-0.0739418023,59.4824074 -0.0739418023,52.5175926 4.22182541,48.2218254 Z",fill:"currentColor",fillRule:"nonzero"})}))}function Xu(t){var s,a,r=t.onChange,n=t.value,i=t.children,o=t.caption,l=t.className,c=t.style,d=Ge(),m=(a=(s=d.components)===null||s===void 0?void 0:s.IconDropdown)!==null&&a!==void 0?a:Y1;return e.jsxs("div",{className:l,style:c,children:[e.jsx("span",{className:d.classNames.vhidden,children:t["aria-label"]}),e.jsx("select",{name:t.name,"aria-label":t["aria-label"],className:d.classNames.dropdown,style:d.styles.dropdown,value:n,onChange:r,children:i}),e.jsxs("div",{className:d.classNames.caption_label,style:d.styles.caption_label,"aria-hidden":"true",children:[o,e.jsx(m,{className:d.classNames.dropdown_icon,style:d.styles.dropdown_icon})]})]})}function X1(t){var s,a=Ge(),r=a.fromDate,n=a.toDate,i=a.styles,o=a.locale,l=a.formatters.formatMonthCaption,c=a.classNames,d=a.components,m=a.labels.labelMonthDropdown;if(!r)return e.jsx(e.Fragment,{});if(!n)return e.jsx(e.Fragment,{});var u=[];if(Vp(r,n))for(var h=Yt(r),p=r.getMonth();p<=n.getMonth();p++)u.push(pn(h,p));else for(var h=Yt(new Date),p=0;p<=11;p++)u.push(pn(h,p));var g=function(v){var w=Number(v.target.value),f=pn(Yt(t.displayMonth),w);t.onChange(f)},y=(s=d==null?void 0:d.Dropdown)!==null&&s!==void 0?s:Xu;return e.jsx(y,{name:"months","aria-label":m(),className:c.dropdown_month,style:i.dropdown_month,onChange:g,value:t.displayMonth.getMonth(),caption:l(t.displayMonth,{locale:o}),children:u.map(function(v){return e.jsx("option",{value:v.getMonth(),children:l(v,{locale:o})},v.getMonth())})})}function Z1(t){var s,a=t.displayMonth,r=Ge(),n=r.fromDate,i=r.toDate,o=r.locale,l=r.styles,c=r.classNames,d=r.components,m=r.formatters.formatYearCaption,u=r.labels.labelYearDropdown,h=[];if(!n)return e.jsx(e.Fragment,{});if(!i)return e.jsx(e.Fragment,{});for(var p=n.getFullYear(),g=i.getFullYear(),y=p;y<=g;y++)h.push(Go(zp(new Date),y));var v=function(f){var C=Go(Yt(a),Number(f.target.value));t.onChange(C)},w=(s=d==null?void 0:d.Dropdown)!==null&&s!==void 0?s:Xu;return e.jsx(w,{name:"years","aria-label":u(),className:c.dropdown_year,style:l.dropdown_year,onChange:v,value:a.getFullYear(),caption:m(a,{locale:o}),children:h.map(function(f){return e.jsx("option",{value:f.getFullYear(),children:m(f,{locale:o})},f.getFullYear())})})}function Q1(t,s){var a=x.useState(t),r=a[0],n=a[1],i=s===void 0?r:s;return[i,n]}function J1(t){var s=t.month,a=t.defaultMonth,r=t.today,n=s||a||r||new Date,i=t.toDate,o=t.fromDate,l=t.numberOfMonths,c=l===void 0?1:l;if(i&&Wa(i,n)<0){var d=-1*(c-1);n=ps(i,d)}return o&&Wa(n,o)<0&&(n=o),Yt(n)}function eC(){var t=Ge(),s=J1(t),a=Q1(s,t.month),r=a[0],n=a[1],i=function(o){var l;if(!t.disableNavigation){var c=Yt(o);n(c),(l=t.onMonthChange)===null||l===void 0||l.call(t,c)}};return[r,i]}function tC(t,s){for(var a=s.reverseMonths,r=s.numberOfMonths,n=Yt(t),i=Yt(ps(n,r)),o=Wa(i,n),l=[],c=0;c<o;c++){var d=ps(n,c);l.push(d)}return a&&(l=l.reverse()),l}function sC(t,s){if(!s.disableNavigation){var a=s.toDate,r=s.pagedNavigation,n=s.numberOfMonths,i=n===void 0?1:n,o=r?i:1,l=Yt(t);if(!a)return ps(l,o);var c=Wa(a,t);if(!(c<i))return ps(l,o)}}function aC(t,s){if(!s.disableNavigation){var a=s.fromDate,r=s.pagedNavigation,n=s.numberOfMonths,i=n===void 0?1:n,o=r?i:1,l=Yt(t);if(!a)return ps(l,-o);var c=Wa(l,a);if(!(c<=0))return ps(l,-o)}}var Zu=x.createContext(void 0);function rC(t){var s=Ge(),a=eC(),r=a[0],n=a[1],i=tC(r,s),o=sC(r,s),l=aC(r,s),c=function(u){return i.some(function(h){return Ii(u,h)})},d=function(u,h){c(u)||(h&&cd(u,h)?n(ps(u,1+s.numberOfMonths*-1)):n(u))},m={currentMonth:r,displayMonths:i,goToMonth:n,goToDate:d,previousMonth:l,nextMonth:o,isDateDisplayed:c};return e.jsx(Zu.Provider,{value:m,children:t.children})}function hr(){var t=x.useContext(Zu);if(!t)throw new Error("useNavigation must be used within a NavigationProvider");return t}function Oc(t){var s,a=Ge(),r=a.classNames,n=a.styles,i=a.components,o=hr().goToMonth,l=function(m){o(ps(m,t.displayIndex?-t.displayIndex:0))},c=(s=i==null?void 0:i.CaptionLabel)!==null&&s!==void 0?s:Yu,d=e.jsx(c,{id:t.id,displayMonth:t.displayMonth});return e.jsxs("div",{className:r.caption_dropdowns,style:n.caption_dropdowns,children:[e.jsx("div",{className:r.vhidden,children:d}),e.jsx(X1,{onChange:l,displayMonth:t.displayMonth}),e.jsx(Z1,{onChange:l,displayMonth:t.displayMonth})]})}function nC(t){return e.jsx("svg",Se({width:"16px",height:"16px",viewBox:"0 0 120 120"},t,{children:e.jsx("path",{d:"M69.490332,3.34314575 C72.6145263,0.218951416 77.6798462,0.218951416 80.8040405,3.34314575 C83.8617626,6.40086786 83.9268205,11.3179931 80.9992143,14.4548388 L80.8040405,14.6568542 L35.461,60 L80.8040405,105.343146 C83.8617626,108.400868 83.9268205,113.317993 80.9992143,116.454839 L80.8040405,116.656854 C77.7463184,119.714576 72.8291931,119.779634 69.6923475,116.852028 L69.490332,116.656854 L18.490332,65.6568542 C15.4326099,62.5991321 15.367552,57.6820069 18.2951583,54.5451612 L18.490332,54.3431458 L69.490332,3.34314575 Z",fill:"currentColor",fillRule:"nonzero"})}))}function iC(t){return e.jsx("svg",Se({width:"16px",height:"16px",viewBox:"0 0 120 120"},t,{children:e.jsx("path",{d:"M49.8040405,3.34314575 C46.6798462,0.218951416 41.6145263,0.218951416 38.490332,3.34314575 C35.4326099,6.40086786 35.367552,11.3179931 38.2951583,14.4548388 L38.490332,14.6568542 L83.8333725,60 L38.490332,105.343146 C35.4326099,108.400868 35.367552,113.317993 38.2951583,116.454839 L38.490332,116.656854 C41.5480541,119.714576 46.4651794,119.779634 49.602025,116.852028 L49.8040405,116.656854 L100.804041,65.6568542 C103.861763,62.5991321 103.926821,57.6820069 100.999214,54.5451612 L100.804041,54.3431458 L49.8040405,3.34314575 Z",fill:"currentColor"})}))}var Br=x.forwardRef(function(t,s){var a=Ge(),r=a.classNames,n=a.styles,i=[r.button_reset,r.button];t.className&&i.push(t.className);var o=i.join(" "),l=Se(Se({},n.button_reset),n.button);return t.style&&Object.assign(l,t.style),e.jsx("button",Se({},t,{ref:s,type:"button",className:o,style:l}))});function oC(t){var s,a,r=Ge(),n=r.dir,i=r.locale,o=r.classNames,l=r.styles,c=r.labels,d=c.labelPrevious,m=c.labelNext,u=r.components;if(!t.nextMonth&&!t.previousMonth)return e.jsx(e.Fragment,{});var h=d(t.previousMonth,{locale:i}),p=[o.nav_button,o.nav_button_previous].join(" "),g=m(t.nextMonth,{locale:i}),y=[o.nav_button,o.nav_button_next].join(" "),v=(s=u==null?void 0:u.IconRight)!==null&&s!==void 0?s:iC,w=(a=u==null?void 0:u.IconLeft)!==null&&a!==void 0?a:nC;return e.jsxs("div",{className:o.nav,style:l.nav,children:[!t.hidePrevious&&e.jsx(Br,{name:"previous-month","aria-label":h,className:p,style:l.nav_button_previous,disabled:!t.previousMonth,onClick:t.onPreviousClick,children:n==="rtl"?e.jsx(v,{className:o.nav_icon,style:l.nav_icon}):e.jsx(w,{className:o.nav_icon,style:l.nav_icon})}),!t.hideNext&&e.jsx(Br,{name:"next-month","aria-label":g,className:y,style:l.nav_button_next,disabled:!t.nextMonth,onClick:t.onNextClick,children:n==="rtl"?e.jsx(w,{className:o.nav_icon,style:l.nav_icon}):e.jsx(v,{className:o.nav_icon,style:l.nav_icon})})]})}function $c(t){var s=Ge().numberOfMonths,a=hr(),r=a.previousMonth,n=a.nextMonth,i=a.goToMonth,o=a.displayMonths,l=o.findIndex(function(g){return Ii(t.displayMonth,g)}),c=l===0,d=l===o.length-1,m=s>1&&(c||!d),u=s>1&&(d||!c),h=function(){r&&i(r)},p=function(){n&&i(n)};return e.jsx(oC,{displayMonth:t.displayMonth,hideNext:m,hidePrevious:u,nextMonth:n,previousMonth:r,onPreviousClick:h,onNextClick:p})}function lC(t){var s,a=Ge(),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:Yu,d;return n?d=e.jsx(c,{id:t.id,displayMonth:t.displayMonth}):o==="dropdown"?d=e.jsx(Oc,{displayMonth:t.displayMonth,id:t.id}):o==="dropdown-buttons"?d=e.jsxs(e.Fragment,{children:[e.jsx(Oc,{displayMonth:t.displayMonth,displayIndex:t.displayIndex,id:t.id}),e.jsx($c,{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($c,{displayMonth:t.displayMonth,id:t.id})]}),e.jsx("div",{className:r.caption,style:i.caption,children:d})}function cC(t){var s=Ge(),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 dC(t,s,a){for(var r=a?Fi(new Date):_i(new Date,{locale:t,weekStartsOn:s}),n=[],i=0;i<7;i++){var o=Wt(r,i);n.push(o)}return n}function mC(){var t=Ge(),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=dC(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 uC(){var t,s=Ge(),a=s.classNames,r=s.styles,n=s.components,i=(t=n==null?void 0:n.HeadRow)!==null&&t!==void 0?t:mC;return e.jsx("thead",{style:r.head,className:a.head,children:e.jsx(i,{})})}function hC(t){var s=Ge(),a=s.locale,r=s.formatters.formatDay;return e.jsx(e.Fragment,{children:r(t.date,{locale:a})})}var Po=x.createContext(void 0);function pC(t){if(!mr(t.initialProps)){var s={selected:void 0,modifiers:{disabled:[]}};return e.jsx(Po.Provider,{value:s,children:t.children})}return e.jsx(xC,{initialProps:t.initialProps,children:t.children})}function xC(t){var s=t.initialProps,a=t.children,r=s.selected,n=s.min,i=s.max,o=function(d,m,u){var h,p;(h=s.onDayClick)===null||h===void 0||h.call(s,d,m,u);var g=!!(m.selected&&n&&(r==null?void 0:r.length)===n);if(!g){var y=!!(!m.selected&&i&&(r==null?void 0:r.length)===i);if(!y){var v=r?Ku([],r):[];if(m.selected){var w=v.findIndex(function(f){return zt(d,f)});v.splice(w,1)}else v.push(d);(p=s.onSelect)===null||p===void 0||p.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 zt(h,d)});return!!(m&&!u)});var c={selected:r,onDayClick:o,modifiers:l};return e.jsx(Po.Provider,{value:c,children:a})}function Eo(){var t=x.useContext(Po);if(!t)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return t}function gC(t,s){var a=s||{},r=a.from,n=a.to;return r&&n?zt(n,t)&&zt(r,t)?void 0:zt(n,t)?{from:n,to:void 0}:zt(r,t)?void 0:ei(r,t)?{from:t,to:n}:{from:r,to:t}:n?ei(t,n)?{from:n,to:t}:{from:t,to:n}:r?cd(t,r)?{from:t,to:r}:{from:r,to:t}:{from:t,to:void 0}}var Mo=x.createContext(void 0);function fC(t){if(!ur(t.initialProps)){var s={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(Mo.Provider,{value:s,children:t.children})}return e.jsx(yC,{initialProps:t.initialProps,children:t.children})}function yC(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(p,g,y){var v,w;(v=s.onDayClick)===null||v===void 0||v.call(s,p,g,y);var f=gC(p,r);(w=s.onSelect)===null||w===void 0||w.call(s,f,p,g,y)},m={range_start:[],range_end:[],range_middle:[],disabled:[]};if(i?(m.range_start=[i],o?(m.range_end=[o],zt(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:hn(i,l-1),before:Wt(i,l-1)}),i&&o&&m.disabled.push({after:i,before:Wt(i,l-1)}),!i&&o&&m.disabled.push({after:hn(o,l-1),before:Wt(o,l-1)})),c){if(i&&!o&&(m.disabled.push({before:Wt(i,-c+1)}),m.disabled.push({after:Wt(i,c-1)})),i&&o){var u=Ts(o,i)+1,h=c-u;m.disabled.push({before:hn(i,h)}),m.disabled.push({after:Wt(o,h)})}!i&&o&&(m.disabled.push({before:Wt(o,-c+1)}),m.disabled.push({after:Wt(o,c-1)}))}return e.jsx(Mo.Provider,{value:{selected:r,onDayClick:d,modifiers:m},children:a})}function Io(){var t=x.useContext(Mo);if(!t)throw new Error("useSelectRange must be used within a SelectRangeProvider");return t}function Er(t){return Array.isArray(t)?Ku([],t):t!==void 0?[t]:[]}function vC(t){var s={};return Object.entries(t).forEach(function(a){var r=a[0],n=a[1];s[r]=Er(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 bC=os.Selected,As=os.Disabled,jC=os.Hidden,NC=os.Today,zn=os.RangeEnd,Hn=os.RangeMiddle,qn=os.RangeStart,wC=os.Outside;function CC(t,s,a){var r,n=(r={},r[bC]=Er(t.selected),r[As]=Er(t.disabled),r[jC]=Er(t.hidden),r[NC]=[t.today],r[zn]=[],r[Hn]=[],r[qn]=[],r[wC]=[],r);return t.fromDate&&n[As].push({before:t.fromDate}),t.toDate&&n[As].push({after:t.toDate}),mr(t)?n[As]=n[As].concat(s.modifiers[As]):ur(t)&&(n[As]=n[As].concat(a.modifiers[As]),n[qn]=a.modifiers[qn],n[Hn]=a.modifiers[Hn],n[zn]=a.modifiers[zn]),n}var Qu=x.createContext(void 0);function SC(t){var s=Ge(),a=Eo(),r=Io(),n=CC(s,a,r),i=vC(s.modifiers),o=Se(Se({},n),i);return e.jsx(Qu.Provider,{value:o,children:t.children})}function Ju(){var t=x.useContext(Qu);if(!t)throw new Error("useModifiers must be used within a ModifiersProvider");return t}function AC(t){return!!(t&&typeof t=="object"&&"before"in t&&"after"in t)}function TC(t){return!!(t&&typeof t=="object"&&"from"in t)}function kC(t){return!!(t&&typeof t=="object"&&"after"in t)}function RC(t){return!!(t&&typeof t=="object"&&"before"in t)}function DC(t){return!!(t&&typeof t=="object"&&"dayOfWeek"in t)}function PC(t,s){var a,r=s.from,n=s.to;if(r&&n){var i=Ts(n,r)<0;i&&(a=[n,r],r=a[0],n=a[1]);var o=Ts(t,r)>=0&&Ts(n,t)>=0;return o}return n?zt(n,t):r?zt(r,t):!1}function EC(t){return ud(t)}function MC(t){return Array.isArray(t)&&t.every(ud)}function IC(t,s){return s.some(function(a){if(typeof a=="boolean")return a;if(EC(a))return zt(t,a);if(MC(a))return a.includes(t);if(TC(a))return PC(t,a);if(DC(a))return a.dayOfWeek.includes(t.getDay());if(AC(a)){var r=Ts(a.before,t),n=Ts(a.after,t),i=r>0,o=n<0,l=ei(a.before,a.after);return l?o&&i:i||o}return kC(a)?Ts(t,a.after)>0:RC(a)?Ts(a.before,t)>0:typeof a=="function"?a(t):!1})}function Fo(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&&!Ii(t,a)&&(n.outside=!0),n}function FC(t,s){for(var a=Yt(t[0]),r=Mi(t[t.length-1]),n,i,o=a;o<=r;){var l=Fo(o,s),c=!l.disabled&&!l.hidden;if(!c){o=Wt(o,1);continue}if(l.selected)return o;l.today&&!i&&(i=o),n||(n=o),o=Wt(o,1)}return i||n}var _C=365;function eh(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:Wt,week:Jn,month:ps,year:$p,startOfWeek:function(v){return n.ISOWeek?Fi(v):_i(v,{locale:u,weekStartsOn:c})},endOfWeek:function(v){return n.ISOWeek?dd(v):md(v,{locale:u,weekStartsOn:c})}},p=h[a](t,r==="after"?1:-1);r==="before"&&d?p=Up([d,p]):r==="after"&&m&&(p=Bp([m,p]));var g=!0;if(i){var y=Fo(p,i);g=!y.disabled&&!y.hidden}return g?p:l.count>_C?l.lastFocused:eh(p,{moveBy:a,direction:r,context:n,modifiers:i,retry:Se(Se({},l),{count:l.count+1})})}var th=x.createContext(void 0);function LC(t){var s=hr(),a=Ju(),r=x.useState(),n=r[0],i=r[1],o=x.useState(),l=o[0],c=o[1],d=FC(s.displayMonths,a),m=n??(l&&s.isDateDisplayed(l))?l:d,u=function(){c(n),i(void 0)},h=function(v){i(v)},p=Ge(),g=function(v,w){if(n){var f=eh(n,{moveBy:v,direction:w,context:p,modifiers:a});zt(n,f)||(s.goToDate(f,n),h(f))}},y={focusedDay:n,focusTarget:m,blur:u,focus:h,focusDayAfter:function(){return g("day","after")},focusDayBefore:function(){return g("day","before")},focusWeekAfter:function(){return g("week","after")},focusWeekBefore:function(){return g("week","before")},focusMonthBefore:function(){return g("month","before")},focusMonthAfter:function(){return g("month","after")},focusYearBefore:function(){return g("year","before")},focusYearAfter:function(){return g("year","after")},focusStartOfWeek:function(){return g("startOfWeek","before")},focusEndOfWeek:function(){return g("endOfWeek","after")}};return e.jsx(th.Provider,{value:y,children:t.children})}function _o(){var t=x.useContext(th);if(!t)throw new Error("useFocusContext must be used within a FocusProvider");return t}function OC(t,s){var a=Ju(),r=Fo(t,a,s);return r}var Lo=x.createContext(void 0);function $C(t){if(!ln(t.initialProps)){var s={selected:void 0};return e.jsx(Lo.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(Lo.Provider,{value:n,children:a})}function sh(){var t=x.useContext(Lo);if(!t)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return t}function BC(t,s){var a=Ge(),r=sh(),n=Eo(),i=Io(),o=_o(),l=o.focusDayAfter,c=o.focusDayBefore,d=o.focusWeekAfter,m=o.focusWeekBefore,u=o.blur,h=o.focus,p=o.focusMonthBefore,g=o.focusMonthAfter,y=o.focusYearBefore,v=o.focusYearAfter,w=o.focusStartOfWeek,f=o.focusEndOfWeek,C=function(S){var T,D,H,z;ln(a)?(T=r.onDayClick)===null||T===void 0||T.call(r,t,s,S):mr(a)?(D=n.onDayClick)===null||D===void 0||D.call(n,t,s,S):ur(a)?(H=i.onDayClick)===null||H===void 0||H.call(i,t,s,S):(z=a.onDayClick)===null||z===void 0||z.call(a,t,s,S)},b=function(S){var T;h(t),(T=a.onDayFocus)===null||T===void 0||T.call(a,t,s,S)},N=function(S){var T;u(),(T=a.onDayBlur)===null||T===void 0||T.call(a,t,s,S)},R=function(S){var T;(T=a.onDayMouseEnter)===null||T===void 0||T.call(a,t,s,S)},E=function(S){var T;(T=a.onDayMouseLeave)===null||T===void 0||T.call(a,t,s,S)},P=function(S){var T;(T=a.onDayPointerEnter)===null||T===void 0||T.call(a,t,s,S)},I=function(S){var T;(T=a.onDayPointerLeave)===null||T===void 0||T.call(a,t,s,S)},j=function(S){var T;(T=a.onDayTouchCancel)===null||T===void 0||T.call(a,t,s,S)},k=function(S){var T;(T=a.onDayTouchEnd)===null||T===void 0||T.call(a,t,s,S)},_=function(S){var T;(T=a.onDayTouchMove)===null||T===void 0||T.call(a,t,s,S)},Y=function(S){var T;(T=a.onDayTouchStart)===null||T===void 0||T.call(a,t,s,S)},F=function(S){var T;(T=a.onDayKeyUp)===null||T===void 0||T.call(a,t,s,S)},L=function(S){var T;switch(S.key){case"ArrowLeft":S.preventDefault(),S.stopPropagation(),a.dir==="rtl"?l():c();break;case"ArrowRight":S.preventDefault(),S.stopPropagation(),a.dir==="rtl"?c():l();break;case"ArrowDown":S.preventDefault(),S.stopPropagation(),d();break;case"ArrowUp":S.preventDefault(),S.stopPropagation(),m();break;case"PageUp":S.preventDefault(),S.stopPropagation(),S.shiftKey?y():p();break;case"PageDown":S.preventDefault(),S.stopPropagation(),S.shiftKey?v():g();break;case"Home":S.preventDefault(),S.stopPropagation(),w();break;case"End":S.preventDefault(),S.stopPropagation(),f();break}(T=a.onDayKeyDown)===null||T===void 0||T.call(a,t,s,S)},A={onClick:C,onFocus:b,onBlur:N,onKeyDown:L,onKeyUp:F,onMouseEnter:R,onMouseLeave:E,onPointerEnter:P,onPointerLeave:I,onTouchCancel:j,onTouchEnd:k,onTouchMove:_,onTouchStart:Y};return A}function VC(){var t=Ge(),s=sh(),a=Eo(),r=Io(),n=ln(t)?s.selected:mr(t)?a.selected:ur(t)?r.selected:void 0;return n}function zC(t){return Object.values(os).includes(t)}function HC(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(zC(r)){var i=t.classNames["day_".concat(r)];i&&a.push(i)}}),a}function qC(t,s){var a=Se({},t.styles.day);return Object.keys(s).forEach(function(r){var n;a=Se(Se({},a),(n=t.modifiersStyles)===null||n===void 0?void 0:n[r])}),a}function WC(t,s,a){var r,n,i,o=Ge(),l=_o(),c=OC(t,s),d=BC(t,c),m=VC(),u=!!(o.onDayClick||o.mode!=="default");x.useEffect(function(){var R;c.outside||l.focusedDay&&u&&zt(l.focusedDay,t)&&((R=a.current)===null||R===void 0||R.focus())},[l.focusedDay,t,a,u,c.outside]);var h=HC(o,c).join(" "),p=qC(o,c),g=!!(c.outside&&!o.showOutsideDays||c.hidden),y=(i=(n=o.components)===null||n===void 0?void 0:n.DayContent)!==null&&i!==void 0?i:hC,v=e.jsx(y,{date:t,displayMonth:s,activeModifiers:c}),w={style:p,className:h,children:v,role:"gridcell"},f=l.focusTarget&&zt(l.focusTarget,t)&&!c.outside,C=l.focusedDay&&zt(l.focusedDay,t),b=Se(Se(Se({},w),(r={disabled:c.disabled,role:"gridcell"},r["aria-selected"]=c.selected,r.tabIndex=C||f?0:-1,r)),d),N={isButton:u,isHidden:g,activeModifiers:c,selectedDays:m,buttonProps:b,divProps:w};return N}function KC(t){var s=x.useRef(null),a=WC(t.date,t.displayMonth,s);return a.isHidden?e.jsx("div",{role:"gridcell"}):a.isButton?e.jsx(Br,Se({name:"day",ref:s},a.buttonProps)):e.jsx("div",Se({},a.divProps))}function GC(t){var s=t.number,a=t.dates,r=Ge(),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(p){n(s,a,p)};return e.jsx(Br,{name:"week-number","aria-label":u,className:o.weeknumber,style:i.weeknumber,onClick:h,children:m})}function YC(t){var s,a,r=Ge(),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:KC,d=(a=l==null?void 0:l.WeekNumber)!==null&&a!==void 0?a:GC,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})},Op(u))})]})}function Uc(t,s,a){for(var r=a!=null&&a.ISOWeek?dd(s):md(s,a),n=a!=null&&a.ISOWeek?Fi(t):_i(t,a),i=Ts(r,n),o=[],l=0;l<=i;l++)o.push(Wt(n,l));var c=o.reduce(function(d,m){var u=a!=null&&a.ISOWeek?Hp(m):qp(m,a),h=d.find(function(p){return p.weekNumber===u});return h?(h.dates.push(m),d):(d.push({weekNumber:u,dates:[m]}),d)},[]);return c}function XC(t,s){var a=Uc(Yt(t),Mi(t),s);if(s!=null&&s.useFixedWeeks){var r=Lp(t,s);if(r<6){var n=a[a.length-1],i=n.dates[n.dates.length-1],o=Jn(i,6-r),l=Uc(Jn(i,1),o,s);a.push.apply(a,l)}}return a}function ZC(t){var s,a,r,n=Ge(),i=n.locale,o=n.classNames,l=n.styles,c=n.hideHead,d=n.fixedWeeks,m=n.components,u=n.weekStartsOn,h=n.firstWeekContainsDate,p=n.ISOWeek,g=XC(t.displayMonth,{useFixedWeeks:!!d,ISOWeek:p,locale:i,weekStartsOn:u,firstWeekContainsDate:h}),y=(s=m==null?void 0:m.Head)!==null&&s!==void 0?s:uC,v=(a=m==null?void 0:m.Row)!==null&&a!==void 0?a:YC,w=(r=m==null?void 0:m.Footer)!==null&&r!==void 0?r:cC;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:g.map(function(f){return e.jsx(v,{displayMonth:t.displayMonth,dates:f.dates,weekNumber:f.weekNumber},f.weekNumber)})}),e.jsx(w,{displayMonth:t.displayMonth})]})}function QC(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var JC=QC()?x.useLayoutEffect:x.useEffect,Wn=!1,e2=0;function Bc(){return"react-day-picker-".concat(++e2)}function t2(t){var s,a=t??(Wn?Bc():null),r=x.useState(a),n=r[0],i=r[1];return JC(function(){n===null&&i(Bc())},[]),x.useEffect(function(){Wn===!1&&(Wn=!0)},[]),(s=t??n)!==null&&s!==void 0?s:void 0}function s2(t){var s,a,r=Ge(),n=r.dir,i=r.classNames,o=r.styles,l=r.components,c=hr().displayMonths,d=t2(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,p=t.displayIndex===0,g=t.displayIndex===c.length-1,y=!p&&!g;n==="rtl"&&(s=[p,g],g=s[0],p=s[1]),p&&(u.push(i.caption_start),h=Se(Se({},h),o.caption_start)),g&&(u.push(i.caption_end),h=Se(Se({},h),o.caption_end)),y&&(u.push(i.caption_between),h=Se(Se({},h),o.caption_between));var v=(a=l==null?void 0:l.Caption)!==null&&a!==void 0?a:lC;return e.jsxs("div",{className:u.join(" "),style:h,children:[e.jsx(v,{id:d,displayMonth:t.displayMonth,displayIndex:t.displayIndex}),e.jsx(ZC,{id:m,"aria-labelledby":d,displayMonth:t.displayMonth})]},t.displayIndex)}function a2(t){var s=Ge(),a=s.classNames,r=s.styles;return e.jsx("div",{className:a.months,style:r.months,children:t.children})}function r2(t){var s,a,r=t.initialProps,n=Ge(),i=_o(),o=hr(),l=x.useState(!1),c=l[0],d=l[1];x.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=Se(Se({},n.styles.root),n.style),h=Object.keys(r).filter(function(g){return g.startsWith("data-")}).reduce(function(g,y){var v;return Se(Se({},g),(v={},v[y]=r[y],v))},{}),p=(a=(s=r.components)===null||s===void 0?void 0:s.Months)!==null&&a!==void 0?a:a2;return e.jsx("div",Se({className:m.join(" "),style:u,dir:n.dir,id:n.id,nonce:r.nonce,title:r.title,lang:r.lang},h,{children:e.jsx(p,{children:o.displayMonths.map(function(g,y){return e.jsx(s2,{displayIndex:y,displayMonth:g},y)})})}))}function n2(t){var s=t.children,a=R1(t,["children"]);return e.jsx(G1,{initialProps:a,children:e.jsx(rC,{children:e.jsx($C,{initialProps:a,children:e.jsx(pC,{initialProps:a,children:e.jsx(fC,{initialProps:a,children:e.jsx(SC,{children:e.jsx(LC,{children:s})})})})})})})}function i2(t){return e.jsx(n2,Se({},t,{children:e.jsx(r2,{initialProps:t})}))}function Kn({className:t,classNames:s,showOutsideDays:a=!0,...r}){return e.jsx(i2,{showOutsideDays:a,className:ce("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:ce(Ga({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:ce("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:ce(Ga({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(Nd,{className:ce("size-4",n),...i}),IconRight:({className:n,...i})=>e.jsx(Ui,{className:ce("size-4",n),...i})},...r})}const ah={"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 o2(t){return ah[t]||null}function l2(){return Object.values(ah)}function c2(t){return`${t.address}, ${t.city}, ${t.state}`}const d2=["Marketing Activity","Promotional Event","Dealer Training","Infrastructure Development","Customer Experience Initiative","Service Campaign"],m2=l2(),Gn=["Claim Details","Review & Submit"];function u2({onBack:t,onSubmit:s}){const[a,r]=x.useState(1),[n,i]=x.useState({activityName:"",activityType:"",dealerCode:"",dealerName:"",dealerEmail:"",dealerPhone:"",dealerAddress:"",activityDate:void 0,location:"",requestDescription:"",periodStartDate:void 0,periodEndDate:void 0,estimatedBudget:""}),o=Gn.length,l=(g,y)=>{i(v=>({...v,[g]: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<o&&c()&&r(a+1)},m=()=>{a>1&&r(a-1)},u=g=>{const y=o2(g);y&&(l("dealerCode",y.code),l("dealerName",y.name),l("dealerEmail",y.email),l("dealerPhone",y.phone),l("dealerAddress",c2(y)))},h=()=>{const g={...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"}]};be.success("Claim Request Created",{description:"Your claim management request has been submitted successfully."}),s&&s(g)},p=()=>{switch(a){case 1:return e.jsxs(Tt.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(ai,{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(J,{htmlFor:"activityName",className:"text-base font-semibold",children:"Activity Name *"}),e.jsx(fe,{id:"activityName",placeholder:"e.g., Himalayan Adventure Fest 2024",value:n.activityName,onChange:g=>l("activityName",g.target.value),className:"mt-2 h-12"})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"activityType",className:"text-base font-semibold",children:"Activity Type *"}),e.jsxs(Te,{value:n.activityType,onValueChange:g=>l("activityType",g),children:[e.jsx(Re,{className:"mt-2 h-12",children:e.jsx(ke,{placeholder:"Select activity type"})}),e.jsx(De,{children:d2.map(g=>e.jsx(U,{value:g,children:g},g))})]})]})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"dealer",className:"text-base font-semibold",children:"Dealer Code / Dealer Name *"}),e.jsxs(Te,{value:n.dealerCode,onValueChange:u,children:[e.jsx(Re,{className:"mt-2 h-12",children:e.jsx(ke,{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(De,{children:m2.map(g=>e.jsx(U,{value:g.code,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-sm font-semibold",children:g.code}),e.jsx("span",{className:"text-gray-400",children:"•"}),e.jsx("span",{children:g.name})]})},g.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(J,{className:"text-base font-semibold",children:"Date *"}),e.jsxs(cs,{children:[e.jsx(ds,{asChild:!0,children:e.jsxs(M,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12",children:[e.jsx(We,{className:"mr-2 h-4 w-4"}),n.activityDate?xe(n.activityDate,"PPP"):"Select date"]})}),e.jsx(ms,{className:"w-auto p-0",align:"start",children:e.jsx(Kn,{mode:"single",selected:n.activityDate,onSelect:g=>l("activityDate",g),initialFocus:!0})})]})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"location",className:"text-base font-semibold",children:"Location *"}),e.jsx(fe,{id:"location",placeholder:"e.g., Mumbai, Maharashtra",value:n.location,onChange:g=>l("location",g.target.value),className:"mt-2 h-12"})]})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"requestDescription",className:"text-base font-semibold",children:"Request in Detail - Brief Requirement *"}),e.jsx(bs,{id:"requestDescription",placeholder:"Provide a detailed description of your claim requirement...",value:n.requestDescription,onChange:g=>l("requestDescription",g.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(J,{className:"text-base font-semibold",children:"Period (If Any)"}),e.jsx(ee,{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(J,{className:"text-sm text-gray-600",children:"Start Date"}),e.jsxs(cs,{children:[e.jsx(ds,{asChild:!0,children:e.jsxs(M,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12",children:[e.jsx(We,{className:"mr-2 h-4 w-4"}),n.periodStartDate?xe(n.periodStartDate,"PPP"):"Start date"]})}),e.jsx(ms,{className:"w-auto p-0",align:"start",children:e.jsx(Kn,{mode:"single",selected:n.periodStartDate,onSelect:g=>l("periodStartDate",g),initialFocus:!0})})]})]}),e.jsxs("div",{children:[e.jsx(J,{className:"text-sm text-gray-600",children:"End Date"}),e.jsxs(cs,{children:[e.jsx(ds,{asChild:!0,children:e.jsxs(M,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12",children:[e.jsx(We,{className:"mr-2 h-4 w-4"}),n.periodEndDate?xe(n.periodEndDate,"PPP"):"End date"]})}),e.jsx(ms,{className:"w-auto p-0",align:"start",children:e.jsx(Kn,{mode:"single",selected:n.periodEndDate,onSelect:g=>l("periodEndDate",g),initialFocus:!0})})]})]})]}),(n.periodStartDate||n.periodEndDate)&&e.jsx("p",{className:"text-xs text-gray-600 mt-2",children:n.periodStartDate&&n.periodEndDate?`Period: ${xe(n.periodStartDate,"MMM dd, yyyy")} - ${xe(n.periodEndDate,"MMM dd, yyyy")}`:"Please select both start and end dates for the period"})]})]})]});case 2:return e.jsxs(Tt.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(je,{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(K,{className:"border-2",children:[e.jsx(ae,{className:"bg-gradient-to-br from-blue-50 to-indigo-50",children:e.jsxs(re,{className:"flex items-center gap-2",children:[e.jsx(ai,{className:"w-5 h-5 text-blue-600"}),"Activity Information"]})}),e.jsx(G,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(J,{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(J,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Type"}),e.jsx(ee,{variant:"secondary",className:"mt-1",children:n.activityType})]})]})})]}),e.jsxs(K,{className:"border-2",children:[e.jsx(ae,{className:"bg-gradient-to-br from-green-50 to-emerald-50",children:e.jsxs(re,{className:"flex items-center gap-2",children:[e.jsx(Ax,{className:"w-5 h-5 text-green-600"}),"Dealer Information"]})}),e.jsx(G,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(J,{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(J,{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(J,{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(J,{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(J,{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(K,{className:"border-2",children:[e.jsx(ae,{className:"bg-gradient-to-br from-purple-50 to-pink-50",children:e.jsxs(re,{className:"flex items-center gap-2",children:[e.jsx(We,{className:"w-5 h-5 text-purple-600"}),"Date & Location"]})}),e.jsx(G,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(J,{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?xe(n.activityDate,"PPP"):"N/A"})]}),e.jsxs("div",{children:[e.jsx(J,{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(Tx,{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(J,{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(K,{className:"border-2",children:[e.jsx(ae,{className:"bg-gradient-to-br from-orange-50 to-amber-50",children:e.jsxs(re,{className:"flex items-center gap-2",children:[e.jsx(Ae,{className:"w-5 h-5 text-orange-600"}),"Request Details"]})}),e.jsx(G,{className:"pt-6 space-y-4",children:e.jsxs("div",{children:[e.jsx(J,{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(K,{className:"border-2",children:[e.jsx(ae,{className:"bg-gradient-to-br from-cyan-50 to-blue-50",children:e.jsxs(re,{className:"flex items-center gap-2",children:[e.jsx(Ie,{className:"w-5 h-5 text-cyan-600"}),"Period"]})}),e.jsx(G,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(J,{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?xe(n.periodStartDate,"PPP"):"Not specified"})]}),e.jsxs("div",{children:[e.jsx(J,{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?xe(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(ar,{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(xs,{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(ee,{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:Gn[a-1]})]})]})}),e.jsxs("div",{className:"mt-4 sm:mt-6",children:[e.jsx(gs,{value:a/o*100,className:"h-2"}),e.jsx("div",{className:"flex justify-between mt-2 px-1",children:Gn.map((g,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(K,{className:"mb-6 sm:mb-8",children:e.jsx(G,{className:"p-4 sm:p-6 lg:p-8",children:e.jsx(an,{mode:"wait",children:p()})})}),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(xs,{className:"w-4 h-4"}),"Previous"]}),a<o?e.jsxs(M,{onClick:d,disabled:!c(),className:"gap-2 w-full sm:w-auto order-1 sm:order-2",children:["Next",e.jsx(Nt,{className:"w-4 h-4"})]}):e.jsxs(M,{onClick:h,disabled:!c(),className:"gap-2 bg-green-600 hover:bg-green-700 w-full sm:w-auto order-1 sm:order-2",children:[e.jsx(Aa,{className:"w-4 h-4"}),"Submit Claim Request"]})]})]})})}function rh({icon:t,title:s,description:a,badge:r,actions:n,testId:i="page-header"}){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":i,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","data-testid":`${i}-icon-container`,children:e.jsx(t,{className:"w-5 h-5 sm:w-6 sm:h-6 text-white","data-testid":`${i}-icon`})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl sm:text-2xl md:text-3xl font-bold text-gray-900","data-testid":`${i}-title`,children:s}),e.jsx("p",{className:"text-sm sm:text-base text-gray-600","data-testid":`${i}-description`,children:a})]})]})}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[r&&e.jsxs(ee,{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":`${i}-badge`,children:[r.loading?"Loading…":r.value,e.jsx("span",{className:"hidden sm:inline ml-1",children:r.label})]}),n]})]})}function Kt({label:t,value:s,icon:a,iconColor:r,gradient:n,textColor:i,valueColor:o,testId:l="stats-card",onClick:c}){return e.jsx(K,{className:`${n} border transition-shadow ${c?"cursor-pointer hover:shadow-lg":"hover:shadow-md"}`,"data-testid":l,onClick:c,children:e.jsx(G,{className:"p-3 sm:p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:`text-xs sm:text-sm font-medium ${i}`,"data-testid":`${l}-label`,children:t}),e.jsx("p",{className:`text-xl sm:text-2xl font-bold ${o}`,"data-testid":`${l}-value`,children:s})]}),e.jsx(a,{className:`w-6 h-6 sm:w-8 sm:h-8 ${r}`,"data-testid":`${l}-icon`})]})})})}function h2({stats:t,onStatusFilter:s}){const a=r=>{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(Kt,{label:"Total",value:t.total,icon:Ae,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(Kt,{label:"Pending",value:t.pending,icon:Ie,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(Kt,{label:"Paused",value:t.paused,icon:Os,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(Kt,{label:"Approved",value:t.approved,icon:je,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(Kt,{label:"Rejected",value:t.rejected,icon:Je,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(Kt,{label:"Draft",value:t.draft,icon:Yr,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(Kt,{label:"Closed",value:t.closed,icon:Xr,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 p2({searchTerm:t,statusFilter:s,priorityFilter:a,onSearchChange:r,onStatusChange:n,onPriorityChange:i}){return e.jsx(K,{className:"border-gray-200","data-testid":"my-requests-filters",children:e.jsx(G,{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(Xt,{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(fe,{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(Te,{value:s,onValueChange:n,children:[e.jsx(Re,{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(ke,{placeholder:"Status"})}),e.jsxs(De,{children:[e.jsx(U,{value:"all",children:"All Status"}),e.jsx(U,{value:"draft",children:"Draft"}),e.jsx(U,{value:"pending",children:"Pending"}),e.jsx(U,{value:"paused",children:"Paused"}),e.jsx(U,{value:"approved",children:"Approved"}),e.jsx(U,{value:"rejected",children:"Rejected"}),e.jsx(U,{value:"closed",children:"Closed"})]})]}),e.jsxs(Te,{value:a,onValueChange:i,children:[e.jsx(Re,{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(ke,{placeholder:"Priority"})}),e.jsxs(De,{children:[e.jsx(U,{value:"all",children:"All Priority"}),e.jsx(U,{value:"express",children:"Express"}),e.jsx(U,{value:"standard",children:"Standard"})]})]})]})]})})})}function x2(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:ct,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:ct,iconColor:"text-gray-600"}}}function g2(t){switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:je,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:Je,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:Ie,iconColor:"text-yellow-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:je,iconColor:"text-gray-600"};case"draft":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Yr,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Pe,iconColor:"text-gray-600"}}}const f2=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 y2({request:t,index:s,onViewRequest:a}){var l;const r=g2(t.status),n=x2(t.priority),i=r.icon,o=n.icon;return e.jsx(Tt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:s*.1},children:e.jsx(K,{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(G,{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(ee,{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(ee,{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(Os,{className:"w-3 h-3 mr-1"}),"Paused"]}),e.jsxs(ee,{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(ee,{variant:"secondary",className:"bg-purple-100 text-purple-700 text-xs shrink-0 hidden sm:inline-flex","data-testid":"template-badge",children:[e.jsx(Ae,{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:f2(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:"})," ",fs(t.submittedDate)]})]})]}),e.jsx(Nt,{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(it,{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(Vs,{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(Ie,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{"data-testid":"submitted-timestamp",children:["Submitted: ",fs(t.submittedDate)]})]})]})]})})})})}function v2({requests:t,loading:s,searchTerm:a,statusFilter:r,priorityFilter:n,onViewRequest:i}){if(s)return e.jsx(K,{"data-testid":"loading-state",children:e.jsx(G,{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(K,{"data-testid":"empty-state",children:e.jsxs(G,{className:"p-12 text-center",children:[e.jsx(Ae,{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(y2,{request:o,index:l,onViewRequest:i},o.id))})}function b2(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 nh(t){return Array.isArray(t)?t.map(b2):[]}function j2({itemsPerPage:t=10}={}){const[s,a]=x.useState([]),[r,n]=x.useState(!1),[i,o]=x.useState(!1),[l,c]=x.useState({currentPage:1,totalPages:1,totalRecords:0,itemsPerPage:t}),d=x.useCallback(async(m=1,u)=>{try{m===1&&(n(!0),a([]));const h=await Ot.listMyInitiatedWorkflows({page:m,limit:t,search:u==null?void 0:u.search,status:u==null?void 0:u.status,priority:u==null?void 0:u.priority}),p=Array.isArray(h==null?void 0:h.data)?h.data:[],g=nh(p);a(g),o(!0);const y=h==null?void 0:h.pagination;y&&c({currentPage:y.page||1,totalPages:y.totalPages||1,totalRecords:y.total||0,itemsPerPage:t})}catch(h){console.error("[MyRequests] Error fetching requests:",h),a([]),o(!0)}finally{n(!1)}},[t]);return{requests:s,loading:r,hasFetchedFromApi:i,pagination:l,fetchMyRequests:d}}const N2={searchTerm:"",statusFilter:"all",priorityFilter:"all",currentPage:1},ih=Ta({name:"myRequests",initialState:N2,reducers:{setSearchTerm:(t,s)=>{t.searchTerm=s.payload},setStatusFilter:(t,s)=>{t.statusFilter=s.payload},setPriorityFilter:(t,s)=>{t.priorityFilter=s.payload,t.currentPage=1},setCurrentPage:(t,s)=>{t.currentPage=s.payload},clearFilters:t=>{t.searchTerm="",t.statusFilter="all",t.priorityFilter="all",t.currentPage=1}}}),{setSearchTerm:w2,setStatusFilter:C2,setPriorityFilter:S2,setCurrentPage:A2,clearFilters:T2}=ih.actions;function k2({onFiltersChange:t,debounceMs:s=500}={}){const a=ir(),r=x.useRef(null),n=x.useRef(!0),{searchTerm:i,statusFilter:o,priorityFilter:l,currentPage:c}=Ra(y=>y.myRequests),d=x.useCallback(y=>a(w2(y)),[a]),m=x.useCallback(y=>a(C2(y)),[a]),u=x.useCallback(y=>a(S2(y)),[a]),h=x.useCallback(y=>a(A2(y)),[a]),p=x.useCallback(()=>({search:i,status:o,priority:l}),[i,o,l]);x.useEffect(()=>{if(n.current){n.current=!1;return}r.current&&clearTimeout(r.current);const y=setTimeout(()=>{t&&t(p())},i?s:0);return r.current=y,()=>{r.current&&clearTimeout(r.current)}},[i,o,l,t,p,s]);const g=x.useCallback(()=>{a(T2())},[a]);return{searchTerm:i,statusFilter:o,priorityFilter:l,currentPage:c,setSearchTerm:d,setStatusFilter:m,setPriorityFilter:u,setCurrentPage:h,getFilters:p,resetFilters:g}}function R2({onViewRequest:t,dynamicRequests:s=[]}){const{user:a}=Mt(),r=j2({itemsPerPage:10}),n=x.useRef(r.fetchMyRequests);n.current=r.fetchMyRequests;const i=k2(),o=x.useRef({searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter}),l=x.useRef(!1);x.useEffect(()=>{const w=i.currentPage||1;n.current(w,{search:i.searchTerm||void 0,status:i.statusFilter!=="all"?i.statusFilter:void 0,priority:i.priorityFilter!=="all"?i.priorityFilter:void 0}),l.current=!0},[]),x.useEffect(()=>{if(!l.current)return;const w=o.current;if(!(w.searchTerm!==i.searchTerm||w.statusFilter!==i.statusFilter||w.priorityFilter!==i.priorityFilter))return;const C=setTimeout(()=>{i.setCurrentPage(1),n.current(1,{search:i.searchTerm||void 0,status:i.statusFilter!=="all"?i.statusFilter:void 0,priority:i.priorityFilter!=="all"?i.priorityFilter:void 0}),o.current={searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter}},i.searchTerm!==w.searchTerm?500:0);return()=>clearTimeout(C)},[i.searchTerm,i.statusFilter,i.priorityFilter]);const[c,d]=x.useState(null),[m,u]=x.useState(!1),h=x.useCallback(async()=>{if(a!=null&&a.userId)try{u(!0);const w=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);d({total:w.totalRequests||0,pending:w.openRequests||0,paused:w.pausedRequests||0,approved:w.approvedRequests||0,rejected:w.rejectedRequests||0,draft:w.draftRequests||0,closed:w.closedRequests||0})}catch(w){console.error("Failed to fetch backend stats:",w),d(null)}finally{u(!1)}},[a==null?void 0:a.userId,i.searchTerm,i.priorityFilter]);x.useEffect(()=>{const w=setTimeout(()=>{h()},i.searchTerm?500:0);return()=>clearTimeout(w)},[i.searchTerm,i.priorityFilter,h]);const p=nh(s),g=r.hasFetchedFromApi?r.requests:p,y=x.useMemo(()=>c?{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}:{total:0,pending:0,paused:0,approved:0,rejected:0,draft:0,closed:0},[c]),v=x.useCallback(w=>{w>=1&&w<=r.pagination.totalPages&&(i.setCurrentPage(w),r.fetchMyRequests(w,{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(rh,{icon:Ae,title:"My Requests",description:"Track and manage all your submitted requests",badge:{value:`${y.total} total`,label:"requests",loading:r.loading||m},testId:"my-requests-header"}),e.jsx(h2,{stats:y,onStatusFilter:w=>{i.setStatusFilter(w)}}),e.jsx(p2,{searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,onSearchChange:i.setSearchTerm,onStatusChange:i.setStatusFilter,onPriorityChange:i.setPriorityFilter}),e.jsx(v2,{requests:g,loading:r.loading,searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,onViewRequest:t}),e.jsx(da,{currentPage:i.currentPage||r.pagination.currentPage,totalPages:r.pagination.totalPages,totalRecords:r.pagination.totalRecords,itemsPerPage:r.pagination.itemsPerPage,onPageChange:v,loading:r.loading,itemLabel:"requests",testIdPrefix:"my-requests-pagination"})]})}function oh({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(rh,{icon:Ae,title:i(),description:o(),testId:"requests-header"}),e.jsx(ee,{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(Et,{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 lh({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(Kt,{label:"Total",value:t.total,icon:Ae,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(Kt,{label:"Pending",value:t.pending,icon:Ie,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(Kt,{label:"Paused",value:t.paused,icon:Os,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(Kt,{label:"Approved",value:t.approved,icon:je,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(Kt,{label:"Rejected",value:t.rejected,icon:Je,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(Kt,{label:"Closed",value:t.closed,icon:Xr,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 D2=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:ct,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:ct,iconColor:"text-gray-600"}}},P2=t=>{switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:je,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:Je,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:Ie,iconColor:"text-yellow-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:je,iconColor:"text-gray-600"};case"draft":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Yr,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Pe,iconColor:"text-gray-600"}}},E2=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 M2({request:t,index:s,onViewRequest:a}){var l;const r=P2(t.status),n=D2(t.priority),i=r.icon,o=n.icon;return e.jsx(Tt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:s*.1},children:e.jsx(K,{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(G,{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(ee,{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(ee,{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(Os,{className:"w-3 h-3 mr-1"}),"Paused"]}),e.jsxs(ee,{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(ee,{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:E2(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:"})," ",fs(t.submittedDate)]})]})]}),e.jsx(Nt,{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(it,{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(Vs,{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(Ie,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{"data-testid":"submitted-timestamp",children:["Submitted: ",fs(t.submittedDate)]})]})]})]})})})})}function ch({requests:t,loading:s,hasActiveFilters:a,onViewRequest:r}){return s?e.jsx(K,{"data-testid":"loading-state",children:e.jsx(G,{className:"p-6 text-sm text-gray-600",children:"Loading requests…"})}):t.length===0?e.jsx(K,{"data-testid":"empty-state",children:e.jsxs(G,{className:"p-12 text-center",children:[e.jsx(Ae,{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(M2,{request:n,index:i,onViewRequest:r},n.id))})}const I2={searchTerm:"",statusFilter:"all",priorityFilter:"all",slaComplianceFilter:"all",departmentFilter:"all",initiatorFilter:"all",approverFilter:"all",approverFilterType:"current",dateRange:"all",customStartDate:void 0,customEndDate:void 0,showCustomDatePicker:!1,currentPage:1},dh=Ta({name:"requests",initialState:I2,reducers:{setSearchTerm:(t,s)=>{t.searchTerm=s.payload},setStatusFilter:(t,s)=>{t.statusFilter=s.payload},setPriorityFilter:(t,s)=>{t.priorityFilter=s.payload},setSlaComplianceFilter:(t,s)=>{t.slaComplianceFilter=s.payload},setDepartmentFilter:(t,s)=>{t.departmentFilter=s.payload},setInitiatorFilter:(t,s)=>{t.initiatorFilter=s.payload},setApproverFilter:(t,s)=>{t.approverFilter=s.payload},setApproverFilterType:(t,s)=>{t.approverFilterType=s.payload},setDateRange:(t,s)=>{t.dateRange=s.payload},setCustomStartDate:(t,s)=>{t.customStartDate=s.payload},setCustomEndDate:(t,s)=>{t.customEndDate=s.payload},setShowCustomDatePicker:(t,s)=>{t.showCustomDatePicker=s.payload},setCurrentPage:(t,s)=>{t.currentPage=s.payload},clearFilters:t=>{t.searchTerm="",t.statusFilter="all",t.priorityFilter="all",t.slaComplianceFilter="all",t.departmentFilter="all",t.initiatorFilter="all",t.approverFilter="all",t.approverFilterType="current",t.dateRange="all",t.customStartDate=void 0,t.customEndDate=void 0,t.showCustomDatePicker=!1,t.currentPage=1}}}),{setSearchTerm:F2,setStatusFilter:_2,setPriorityFilter:L2,setSlaComplianceFilter:O2,setDepartmentFilter:$2,setInitiatorFilter:U2,setApproverFilter:B2,setApproverFilterType:V2,setDateRange:Vc,setCustomStartDate:Yn,setCustomEndDate:Xn,setShowCustomDatePicker:Cr,setCurrentPage:z2,clearFilters:H2}=dh.actions;function mh(){const t=ir(),{searchTerm:s,statusFilter:a,priorityFilter:r,slaComplianceFilter:n,departmentFilter:i,initiatorFilter:o,approverFilter:l,approverFilterType:c,dateRange:d,customStartDate:m,customEndDate:u,showCustomDatePicker:h,currentPage:p}=Ra(A=>A.requests),g=x.useCallback(A=>t(F2(A)),[t]),y=x.useCallback(A=>t(_2(A)),[t]),v=x.useCallback(A=>t(L2(A)),[t]),w=x.useCallback(A=>t(O2(A)),[t]),f=x.useCallback(A=>t($2(A)),[t]),C=x.useCallback(A=>t(U2(A)),[t]),b=x.useCallback(A=>t(B2(A)),[t]),N=x.useCallback(A=>t(V2(A)),[t]),R=x.useCallback(A=>t(Vc(A)),[t]),E=x.useCallback(A=>t(Yn(A)),[t]),P=x.useCallback(A=>t(Xn(A)),[t]),I=x.useCallback(A=>t(Cr(A)),[t]),j=x.useCallback(A=>t(z2(A)),[t]),k=x.useCallback(()=>({search:s||void 0,status:a!=="all"?a:void 0,priority:r!=="all"?r:void 0,slaCompliance:n!=="all"?n:void 0,department:i!=="all"?i:void 0,initiator:o!=="all"?o:void 0,approver:l!=="all"?l:void 0,approverType:l!=="all"?c:void 0,dateRange:d,startDate:m,endDate:u}),[s,a,r,n,i,o,l,c,d,m,u]),_=x.useCallback(()=>{t(H2())},[t]),Y=x.useCallback(A=>{const S=A;t(Vc(S)),S!=="custom"?(t(Yn(void 0)),t(Xn(void 0)),t(Cr(!1))):t(Cr(!0))},[t]),F=x.useCallback(()=>{m&&u&&(m>u&&(t(Yn(u)),t(Xn(m))),t(Cr(!1)))},[m,u,t]);return{searchTerm:s,statusFilter:a,priorityFilter:r,slaComplianceFilter:n,departmentFilter:i,initiatorFilter:o,approverFilter:l,approverFilterType:c,dateRange:d,customStartDate:m,customEndDate:u,showCustomDatePicker:h,currentPage:p,hasActiveFilters:!!(s||a!=="all"||r!=="all"||n!=="all"||i!=="all"||o!=="all"||l!=="all"||d!=="all"||m||u),setSearchTerm:g,setStatusFilter:y,setPriorityFilter:v,setSlaComplianceFilter:w,setDepartmentFilter:f,setInitiatorFilter:C,setApproverFilter:b,setApproverFilterType:N,setDateRange:R,setCustomStartDate:E,setCustomEndDate:P,setShowCustomDatePicker:I,setCurrentPage:j,getFilters:k,clearFilters:_,handleDateRangeChange:Y,handleApplyCustomDate:F}}function Vr({allUsers:t,filterValue:s,onFilterChange:a}){const[r,n]=x.useState(""),[i,o]=x.useState([]),[l,c]=x.useState(!1),[d,m]=x.useState(null),u=x.useRef(null);x.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]),x.useEffect(()=>()=>{u.current&&clearTimeout(u.current)},[]);const h=x.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(),w=t.filter(f=>{const C=(f.email||"").toLowerCase(),b=(f.displayName||"").toLowerCase();return C.includes(v)||b.includes(v)});o(w.slice(0,10)),c(w.length>0)},300)},[t]),p=x.useCallback(y=>{m(y),a(y.userId),n(y.displayName||y.email),c(!1),o([])},[a]),g=x.useCallback(()=>{m(null),a("all"),n(""),c(!1),o([])},[a]);return{searchQuery:r,searchResults:i,showResults:l,selectedUser:d,handleSearch:h,handleSelect:p,handleClear:g,setShowResults:c}}function q2(t){var d,m,u,h,p,g,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(w=>{const f=(w.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((C,b)=>{const N=C.levelNumber||C.level_number||0;return(b.levelNumber||b.level_number||0)-N})[0];f&&(n=f.approverName||((h=f.approver)==null?void 0:h.name)||((p=f.approver)==null?void 0:p.displayName)||f.approverEmail||((g=f.approver)==null?void 0:g.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(w=>{const f=(w.status||"").toString().toUpperCase();return f==="PENDING"||f==="IN_PROGRESS"});if(v){const w=v.levelNumber||v.level_number||0,f=c||t.approvals.length;i=`${w} 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 uh(t){return Array.isArray(t)?t.map(q2):[]}function W2(t,s,a,r,n,i){if(t.length>0){const o=t.length,l=t.filter(p=>{const g=(p.status||"").toString().toUpperCase();return g==="PENDING"||g==="IN_PROGRESS"}).length,c=t.filter(p=>(p.status||"").toString().toUpperCase()==="APPROVED").length,d=t.filter(p=>(p.status||"").toString().toUpperCase()==="REJECTED").length,m=t.filter(p=>(p.status||"").toString().toUpperCase()==="DRAFT").length,u=t.filter(p=>(p.status||"").toString().toUpperCase()==="CLOSED").length,h=t.filter(p=>(p.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 hh={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(zr,function(){return function(a,r){r.prototype.isSameOrBefore=function(n,i){return this.isSame(n,i)||this.isBefore(n,i)}}})})(hh);var K2=hh.exports;const ph=Hr(K2);var xh={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(zr,function(){return function(a,r){r.prototype.isSameOrAfter=function(n,i){return this.isSame(n,i)||this.isAfter(n,i)}}})})(xh);var G2=xh.exports;const gh=Hr(G2);st.extend(gh);st.extend(ph);function Y2(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 p=(h.status||"").toString().toUpperCase();return p==="IN_PROGRESS"||p==="PENDING"}))==null?void 0:d.approverId)||((u=(m=n.approvals)==null?void 0:m.find(h=>{const p=(h.status||"").toString().toUpperCase();return p==="IN_PROGRESS"||p==="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,p,g,y,v,w,f,C;const n=s.slaCompliance||"";if(n.toLowerCase()==="compliant"){const b=(r.status||"").toString().toUpperCase();if(!(b==="APPROVED"||b==="REJECTED"||b==="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)||((p=(h=r.summary)==null?void 0:h.sla)==null?void 0:p.status);return R?R!=="breached"&&R.toLowerCase()!=="breached":!0}const i=((g=r.currentLevelSLA)==null?void 0:g.status)||((v=(y=r.currentApprover)==null?void 0:y.sla)==null?void 0:v.status)||((w=r.sla)==null?void 0:w.status)||((C=(f=r.summary)==null?void 0:f.sla)==null?void 0:C.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=st(s.startDate).startOf("day").toDate(),n=st(s.endDate).endOf("day").toDate();else{const i=st();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=st(m).startOf("day").toDate(),h=st(r).startOf("day").toDate(),p=st(n).endOf("day").toDate();return u>=h&&u<=p}const l=st(o).startOf("day").toDate(),c=st(r).startOf("day").toDate(),d=st(n).endOf("day").toDate();return l>=c&&l<=d}))}return a}st.extend(ph);st.extend(gh);function X2(t){if(!t)return"N/A";try{const s=typeof t=="string"?new Date(t):t;return xe(s,"yyyy-MM-dd HH:mm:ss")}catch{return"N/A"}}async function fh(t,s){const a=Y2(t,s),r=[["Request Number","Title","Status","Priority","Initiator","Department","Current Approver","Approval Level","Submitted Date","Description"].join(",")];a.forEach(c=>{var f,C,b,N,R;const d=(c.status||"").toString().toLowerCase().replace("_","-"),m=(c.priority||"").toString().toLowerCase(),u=((f=c.initiator)==null?void 0:f.displayName)||((C=c.initiator)==null?void 0:C.email)||c.initiatorName||"N/A",h=c.department||((b=c.initiator)==null?void 0:b.department)||"N/A",p=((N=c.currentApprover)==null?void 0:N.displayName)||((R=c.currentApprover)==null?void 0:R.email)||c.currentApproverName||"N/A",g=c.currentApproverLevel||c.approvalLevel||c.currentLevel||"N/A",y=X2(c.submittedAt||c.createdAt||c.submitted_at||c.created_at),v=(c.description||"").replace(/"/g,'""').replace(/\n/g," ").replace(/\r/g,""),w=[c.requestNumber||c.request_number||"",`"${(c.title||"").replace(/"/g,'""')}"`,d,m,`"${u.replace(/"/g,'""')}"`,`"${h.replace(/"/g,'""')}"`,`"${p.replace(/"/g,'""')}"`,g,y,`"${v}"`];r.push(w.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 Z2({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 Ot.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(g=>(g.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 Ot.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(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:h}}}async function Q2(t){const a=[];let r=1,n=!0;const i=100;for(;n&&r<=i;){const o=t?await Ot.listWorkflows({page:r,limit:100}):await Ot.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 J2({onViewRequest:t}){const{user:s}=Mt(),a=Ra(O=>O.dashboard.viewAsUser),r=x.useMemo(()=>Zr(s),[s]),n=x.useMemo(()=>r&&!a,[r,a]),i=mh(),[o,l]=x.useState([]),[c,d]=x.useState(!1),[m,u]=x.useState(!1),[h,p]=x.useState(null),[g,y]=x.useState([]),[v,w]=x.useState(!1),[f,C]=x.useState([]),[b,N]=x.useState(1),[R,E]=x.useState(0),[P]=x.useState(10),I=Vr({allUsers:f,filterValue:i.initiatorFilter,onFilterChange:i.setInitiatorFilter}),j=Vr({allUsers:f,filterValue:i.approverFilter,onFilterChange:i.setApproverFilter}),k=x.useCallback(async(O,se,te,$)=>{try{const X=$==null?void 0:$.slaCompliance;if(X&&X!=="all"&&X!=="breached"&&X!=="compliant"){const q={};$!=null&&$.search&&(q.search=$.search),$!=null&&$.priority&&$.priority!=="all"&&(q.priority=$.priority),$!=null&&$.department&&$.department!=="all"&&(q.department=$.department),$!=null&&$.initiator&&$.initiator!=="all"&&(q.initiator=$.initiator),$!=null&&$.approver&&$.approver!=="all"&&(q.approver=$.approver,q.approverType=$.approverType||"current"),q.slaCompliance=X,O&&(q.dateRange=O),se&&(q.startDate=se.toISOString()),te&&(q.endDate=te.toISOString());const Q=n?await Ot.listWorkflows({page:1,limit:1e3,...q}):await Ot.listParticipantRequests({page:1,limit:1e3,...q}),oe=Array.isArray(Q==null?void 0:Q.data)?Q.data:[],W=oe.length,me=oe.filter(le=>{const ye=(le.status||"").toString().toUpperCase();return ye==="PENDING"||ye==="IN_PROGRESS"}).length,we=oe.filter(le=>(le.status||"").toString().toUpperCase()==="APPROVED").length,Ee=oe.filter(le=>(le.status||"").toString().toUpperCase()==="REJECTED").length,Fe=oe.filter(le=>(le.status||"").toString().toUpperCase()==="CLOSED").length;p({total:W,pending:me,paused:0,approved:we,rejected:Ee,draft:0,closed:Fe})}else{const q=await He.getRequestStats(O,se?se.toISOString():void 0,te?te.toISOString():void 0,void 0,$==null?void 0:$.priority,$==null?void 0:$.department,$==null?void 0:$.initiator,$==null?void 0:$.approver,$==null?void 0:$.approverType,$==null?void 0:$.search,$==null?void 0:$.slaCompliance,!n);p({total:q.totalRequests||0,pending:q.openRequests||0,paused:q.pausedRequests||0,approved:q.approvedRequests||0,rejected:q.rejectedRequests||0,draft:q.draftRequests||0,closed:q.closedRequests||0})}}catch(X){console.error("Failed to fetch backend stats:",X)}finally{}},[n]),_=x.useCallback(async()=>{try{w(!0);const O=await He.getDepartments();y(O)}catch{}finally{w(!1)}},[]),Y=x.useCallback(async()=>{try{const se=(await Gt.getAllUsers()).map(te=>({userId:te.userId,email:te.email,displayName:te.displayName||te.email}));C(se)}catch(O){console.error("Failed to fetch users:",O)}},[]),F=x.useRef(i),L=x.useRef(k);x.useEffect(()=>{F.current=i,L.current=k},[i,k]);const A=x.useCallback(async(O=1)=>{try{O===1&&(d(!0),l([]));const se=F.current.getFilters(),te=await Z2({page:O,itemsPerPage:P,filters:se,isOrgLevel:n});l(te.data),i.setCurrentPage(te.pagination.page),N(te.pagination.totalPages),E(te.pagination.total)}catch{l([])}finally{d(!1)}},[P,n]),S=x.useCallback(async()=>{try{u(!0);const O=await Q2(n);await fh(O,i.getFilters())}catch(O){console.error("Failed to export requests:",O),alert("Failed to export requests. Please try again.")}finally{u(!1)}},[n,i]);x.useEffect(()=>{_(),Y()},[_,Y]),x.useEffect(()=>{const O=setTimeout(()=>{const se={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},te=i.dateRange||"all";L.current(te,i.customStartDate,i.customEndDate,se)},i.searchTerm?500:0);return()=>clearTimeout(O)},[n,i.dateRange,i.customStartDate,i.customEndDate,i.priorityFilter,i.departmentFilter,i.initiatorFilter,i.approverFilter,i.approverFilterType,i.searchTerm,i.slaComplianceFilter]);const T=x.useRef({searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,slaComplianceFilter:i.slaComplianceFilter,departmentFilter:i.departmentFilter,initiatorFilter:i.initiatorFilter,approverFilter:i.approverFilter,approverFilterType:i.approverFilterType,dateRange:i.dateRange,customStartDate:i.customStartDate,customEndDate:i.customEndDate,isOrgLevel:n}),D=x.useRef(!1);x.useEffect(()=>{const O=i.currentPage||1;A(O),D.current=!0},[]),x.useEffect(()=>{if(!D.current)return;const O=T.current;if(!(O.searchTerm!==i.searchTerm||O.statusFilter!==i.statusFilter||O.priorityFilter!==i.priorityFilter||O.slaComplianceFilter!==i.slaComplianceFilter||O.departmentFilter!==i.departmentFilter||O.initiatorFilter!==i.initiatorFilter||O.approverFilter!==i.approverFilter||O.approverFilterType!==i.approverFilterType||O.dateRange!==i.dateRange||O.customStartDate!==i.customStartDate||O.customEndDate!==i.customEndDate||O.isOrgLevel!==n))return;const te=setTimeout(()=>{i.setCurrentPage(1),A(1),T.current={searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,slaComplianceFilter:i.slaComplianceFilter,departmentFilter:i.departmentFilter,initiatorFilter:i.initiatorFilter,approverFilter:i.approverFilter,approverFilterType:i.approverFilterType,dateRange:i.dateRange,customStartDate:i.customStartDate,customEndDate:i.customEndDate,isOrgLevel:n}},i.searchTerm!==O.searchTerm?500:0);return()=>clearTimeout(te)},[n,i.searchTerm,i.statusFilter,i.priorityFilter,i.slaComplianceFilter,i.departmentFilter,i.initiatorFilter,i.approverFilter,i.approverFilterType,i.dateRange,i.customStartDate,i.customEndDate]);const H=x.useCallback(O=>{O>=1&&O<=b&&(i.setCurrentPage(O),A(O))},[b,A,i]),z=x.useMemo(()=>uh(o),[o]),Z=x.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}:W2([],n,h,!1,R,z),[n,h,R,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(oh,{isOrgLevel:n,isAdmin:r,loading:c,exporting:m,onExport:S}),e.jsx(lh,{stats:Z,onStatusFilter:O=>{i.setStatusFilter(O)}}),e.jsx(K,{className:"border-gray-200 shadow-md","data-testid":"requests-filters",children:e.jsx(G,{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(sr,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),i.hasActiveFilters&&e.jsx(ee,{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(Et,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(dt,{}),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(Xt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(fe,{placeholder:"Search requests...",value:i.searchTerm,onChange:O=>i.setSearchTerm(O.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(Te,{value:i.statusFilter,onValueChange:i.setStatusFilter,children:[e.jsx(Re,{className:"h-10","data-testid":"status-filter",children:e.jsx(ke,{placeholder:"All Status"})}),e.jsxs(De,{children:[e.jsx(U,{value:"all",children:"All Status"}),e.jsx(U,{value:"pending",children:"Pending"}),e.jsx(U,{value:"paused",children:"Paused"}),e.jsx(U,{value:"approved",children:"Approved"}),e.jsx(U,{value:"rejected",children:"Rejected"}),e.jsx(U,{value:"closed",children:"Closed"})]})]}),e.jsxs(Te,{value:i.priorityFilter,onValueChange:i.setPriorityFilter,children:[e.jsx(Re,{className:"h-10","data-testid":"priority-filter",children:e.jsx(ke,{placeholder:"All Priority"})}),e.jsxs(De,{children:[e.jsx(U,{value:"all",children:"All Priority"}),e.jsx(U,{value:"express",children:"Express"}),e.jsx(U,{value:"standard",children:"Standard"})]})]}),e.jsxs(Te,{value:i.departmentFilter,onValueChange:i.setDepartmentFilter,disabled:v||g.length===0,children:[e.jsx(Re,{className:"h-10","data-testid":"department-filter",children:e.jsx(ke,{placeholder:v?"Loading...":"All Departments"})}),e.jsxs(De,{children:[e.jsx(U,{value:"all",children:"All Departments"}),g.map(O=>e.jsx(U,{value:O,children:O},O))]})]}),e.jsxs(Te,{value:i.slaComplianceFilter,onValueChange:i.setSlaComplianceFilter,children:[e.jsx(Re,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(ke,{placeholder:"All SLA Status"})}),e.jsxs(De,{children:[e.jsx(U,{value:"all",children:"All SLA Status"}),e.jsx(U,{value:"compliant",children:"Compliant"}),e.jsx(U,{value:"on-track",children:"On Track"}),e.jsx(U,{value:"approaching",children:"Approaching"}),e.jsx(U,{value:"critical",children:"Critical"}),e.jsx(U,{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(J,{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(lt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(fe,{placeholder:"Search initiator...",value:I.searchQuery,onChange:O=>I.handleSearch(O.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(O=>e.jsx("button",{type:"button",onClick:()=>I.handleSelect(O),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:O.displayName||O.email}),O.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:O.email})]})},O.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(J,{className:"text-sm font-medium text-gray-700",children:"Approver"}),i.approverFilter!=="all"&&e.jsxs(Te,{value:i.approverFilterType,onValueChange:O=>i.setApproverFilterType(O),children:[e.jsx(Re,{className:"h-7 w-32 text-xs",children:e.jsx(ke,{})}),e.jsxs(De,{children:[e.jsx(U,{value:"current",children:"Current Only"}),e.jsx(U,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:j.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:j.selectedUser.displayName||j.selectedUser.email}),e.jsx(M,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:j.handleClear,children:e.jsx(lt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(fe,{placeholder:"Search approver...",value:j.searchQuery,onChange:O=>j.handleSearch(O.target.value),onFocus:()=>{j.searchResults.length>0&&j.setShowResults(!0)},onBlur:()=>setTimeout(()=>j.setShowResults(!1),200),className:"h-10","data-testid":"approver-search-input"}),j.showResults&&j.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:j.searchResults.map(O=>e.jsx("button",{type:"button",onClick:()=>j.handleSelect(O),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:O.displayName||O.email}),O.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:O.email})]})},O.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(We,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Te,{value:i.dateRange,onValueChange:i.handleDateRangeChange,children:[e.jsx(Re,{className:"w-[160px] h-10",children:e.jsx(ke,{placeholder:"Date Range"})}),e.jsxs(De,{children:[e.jsx(U,{value:"all",children:"All Time"}),e.jsx(U,{value:"today",children:"Today"}),e.jsx(U,{value:"week",children:"This Week"}),e.jsx(U,{value:"month",children:"This Month"}),e.jsx(U,{value:"last7days",children:"Last 7 Days"}),e.jsx(U,{value:"last30days",children:"Last 30 Days"}),e.jsx(U,{value:"custom",children:"Custom Range"})]})]}),i.dateRange==="custom"&&e.jsxs(cs,{open:i.showCustomDatePicker,onOpenChange:i.setShowCustomDatePicker,children:[e.jsx(ds,{asChild:!0,children:e.jsxs(M,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(We,{className:"w-4 h-4"}),i.customStartDate&&i.customEndDate?`${xe(i.customStartDate,"MMM d, yyyy")} - ${xe(i.customEndDate,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(ms,{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(J,{htmlFor:"start-date",children:"Start Date"}),e.jsx(fe,{id:"start-date",type:"date",value:i.customStartDate?xe(i.customStartDate,"yyyy-MM-dd"):"",onChange:O=>{const se=O.target.value?new Date(O.target.value):void 0;se?(i.setCustomStartDate(se),i.customEndDate&&se>i.customEndDate&&i.setCustomEndDate(se)):i.setCustomStartDate(void 0)},max:xe(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"end-date",children:"End Date"}),e.jsx(fe,{id:"end-date",type:"date",value:i.customEndDate?xe(i.customEndDate,"yyyy-MM-dd"):"",onChange:O=>{const se=O.target.value?new Date(O.target.value):void 0;se?(i.setCustomEndDate(se),i.customStartDate&&se<i.customStartDate&&i.setCustomStartDate(se)):i.setCustomEndDate(void 0)},min:i.customStartDate?xe(i.customStartDate,"yyyy-MM-dd"):void 0,max:xe(new Date,"yyyy-MM-dd"),className:"w-full"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(M,{size:"sm",onClick:i.handleApplyCustomDate,disabled:!i.customStartDate||!i.customEndDate,className:"flex-1 bg-re-green hover:bg-re-green/90",children:"Apply"}),e.jsx(M,{size:"sm",variant:"outline",onClick:()=>{i.setShowCustomDatePicker(!1),i.setCustomStartDate(void 0),i.setCustomEndDate(void 0),i.setDateRange("month")},children:"Cancel"})]})]})})]})]})]})})}),e.jsx(ch,{requests:z,loading:c,hasActiveFilters:i.hasActiveFilters,onViewRequest:t}),e.jsx(da,{currentPage:i.currentPage||1,totalPages:b,totalRecords:R,itemsPerPage:P,onPageChange:H,loading:c,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}async function eS({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 Ot.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 zc=100;async function tS(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 Ot.listParticipantRequests({page:r,limit:zc,...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===zc}}return s}function sS({onViewRequest:t}){const s=mh(),[a,r]=x.useState([]),[n,i]=x.useState(!1),[o,l]=x.useState(!1),[c,d]=x.useState(null),[m,u]=x.useState([]),[h,p]=x.useState(!1),[g,y]=x.useState([]),[v,w]=x.useState(1),[f,C]=x.useState(0),[b]=x.useState(10),N=Vr({allUsers:g,filterValue:s.initiatorFilter,onFilterChange:s.setInitiatorFilter}),R=Vr({allUsers:g,filterValue:s.approverFilter,onFilterChange:s.setApproverFilter}),E=x.useCallback(async(D,H,z,Z)=>{try{const O=await He.getRequestStats(D,H?H.toISOString():void 0,z?z.toISOString():void 0,void 0,Z==null?void 0:Z.priority,Z==null?void 0:Z.department,Z==null?void 0:Z.initiator,Z==null?void 0:Z.approver,Z==null?void 0:Z.approverType,Z==null?void 0:Z.search,Z==null?void 0:Z.slaCompliance,!0);d({total:O.totalRequests||0,pending:O.openRequests||0,paused:O.pausedRequests||0,approved:O.approvedRequests||0,rejected:O.rejectedRequests||0,draft:O.draftRequests||0,closed:O.closedRequests||0})}catch(O){console.error("Failed to fetch backend stats:",O)}},[]),P=x.useCallback(async()=>{try{p(!0);const D=await He.getDepartments();u(D)}catch{}finally{p(!1)}},[]),I=x.useCallback(async()=>{try{const H=(await Gt.getAllUsers()).map(z=>({userId:z.userId,email:z.email,displayName:z.displayName||z.email}));y(H)}catch(D){console.error("Failed to fetch users:",D)}},[]),j=x.useRef(s),k=x.useRef(E);x.useEffect(()=>{j.current=s,k.current=E},[s,E]);const _=x.useCallback(async(D=1)=>{try{D===1&&(i(!0),r([]));const H=j.current.getFilters(),z=await eS({page:D,itemsPerPage:b,filters:H});r(z.data),s.setCurrentPage(z.pagination.page),w(z.pagination.totalPages),C(z.pagination.total)}catch{r([])}finally{i(!1)}},[b]),Y=x.useCallback(async()=>{try{l(!0);const D=await tS(s.getFilters());await fh(D,s.getFilters())}catch(D){console.error("Failed to export requests:",D),alert("Failed to export requests. Please try again.")}finally{l(!1)}},[s]);x.useEffect(()=>{P(),I()},[P,I]),x.useEffect(()=>{const D=setTimeout(()=>{const H={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";k.current(z,s.customStartDate,s.customEndDate,H)},s.searchTerm?500:0);return()=>clearTimeout(D)},[s.searchTerm,s.priorityFilter,s.slaComplianceFilter,s.departmentFilter,s.initiatorFilter,s.approverFilter,s.approverFilterType,s.dateRange,s.customStartDate,s.customEndDate]);const F=x.useRef({searchTerm:s.searchTerm,statusFilter:s.statusFilter,priorityFilter:s.priorityFilter,slaComplianceFilter:s.slaComplianceFilter,departmentFilter:s.departmentFilter,initiatorFilter:s.initiatorFilter,approverFilter:s.approverFilter,approverFilterType:s.approverFilterType,dateRange:s.dateRange,customStartDate:s.customStartDate,customEndDate:s.customEndDate}),L=x.useRef(!1);x.useEffect(()=>{const D=s.currentPage||1;_(D),L.current=!0},[]),x.useEffect(()=>{if(!L.current)return;const D=F.current;if(!(D.searchTerm!==s.searchTerm||D.statusFilter!==s.statusFilter||D.priorityFilter!==s.priorityFilter||D.slaComplianceFilter!==s.slaComplianceFilter||D.departmentFilter!==s.departmentFilter||D.initiatorFilter!==s.initiatorFilter||D.approverFilter!==s.approverFilter||D.approverFilterType!==s.approverFilterType||D.dateRange!==s.dateRange||D.customStartDate!==s.customStartDate||D.customEndDate!==s.customEndDate))return;const z=setTimeout(()=>{s.setCurrentPage(1),_(1),F.current={searchTerm:s.searchTerm,statusFilter:s.statusFilter,priorityFilter:s.priorityFilter,slaComplianceFilter:s.slaComplianceFilter,departmentFilter:s.departmentFilter,initiatorFilter:s.initiatorFilter,approverFilter:s.approverFilter,approverFilterType:s.approverFilterType,dateRange:s.dateRange,customStartDate:s.customStartDate,customEndDate:s.customEndDate}},s.searchTerm!==D.searchTerm?500:0);return()=>clearTimeout(z)},[s.searchTerm,s.statusFilter,s.priorityFilter,s.slaComplianceFilter,s.departmentFilter,s.initiatorFilter,s.approverFilter,s.approverFilterType,s.dateRange,s.customStartDate,s.customEndDate]);const A=x.useCallback(D=>{D>=1&&D<=v&&(s.setCurrentPage(D),_(D))},[v,_,s]),S=x.useMemo(()=>uh(a),[a]),T=x.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 D=S.filter(se=>{const te=(se.status||"").toString().toLowerCase();return te==="pending"||te==="in-progress"}).length,H=S.filter(se=>(se.status||"").toString().toLowerCase()==="paused").length,z=S.filter(se=>(se.status||"").toString().toLowerCase()==="approved").length,Z=S.filter(se=>(se.status||"").toString().toLowerCase()==="rejected").length,O=S.filter(se=>(se.status||"").toString().toLowerCase()==="closed").length;return{total:f>0?f:S.length,pending:D,paused:H,approved:z,rejected:Z,draft:0,closed:O}},[c,f,S]);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(oh,{isOrgLevel:!1,isAdmin:!1,loading:n,exporting:o,onExport:Y}),e.jsx(lh,{stats:T,onStatusFilter:D=>{s.setStatusFilter(D)}}),e.jsx(K,{className:"border-gray-200 shadow-md","data-testid":"requests-filters",children:e.jsx(G,{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(sr,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),s.hasActiveFilters&&e.jsx(ee,{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(Et,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(dt,{}),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(Xt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(fe,{placeholder:"Search requests...",value:s.searchTerm,onChange:D=>s.setSearchTerm(D.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(Te,{value:s.statusFilter,onValueChange:s.setStatusFilter,children:[e.jsx(Re,{className:"h-10","data-testid":"status-filter",children:e.jsx(ke,{placeholder:"All Status"})}),e.jsxs(De,{children:[e.jsx(U,{value:"all",children:"All Status"}),e.jsx(U,{value:"pending",children:"Pending"}),e.jsx(U,{value:"paused",children:"Paused"}),e.jsx(U,{value:"approved",children:"Approved"}),e.jsx(U,{value:"rejected",children:"Rejected"}),e.jsx(U,{value:"closed",children:"Closed"})]})]}),e.jsxs(Te,{value:s.priorityFilter,onValueChange:s.setPriorityFilter,children:[e.jsx(Re,{className:"h-10","data-testid":"priority-filter",children:e.jsx(ke,{placeholder:"All Priority"})}),e.jsxs(De,{children:[e.jsx(U,{value:"all",children:"All Priority"}),e.jsx(U,{value:"express",children:"Express"}),e.jsx(U,{value:"standard",children:"Standard"})]})]}),e.jsxs(Te,{value:s.departmentFilter,onValueChange:s.setDepartmentFilter,disabled:h||m.length===0,children:[e.jsx(Re,{className:"h-10","data-testid":"department-filter",children:e.jsx(ke,{placeholder:h?"Loading...":"All Departments"})}),e.jsxs(De,{children:[e.jsx(U,{value:"all",children:"All Departments"}),m.map(D=>e.jsx(U,{value:D,children:D},D))]})]}),e.jsxs(Te,{value:s.slaComplianceFilter,onValueChange:s.setSlaComplianceFilter,children:[e.jsx(Re,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(ke,{placeholder:"All SLA Status"})}),e.jsxs(De,{children:[e.jsx(U,{value:"all",children:"All SLA Status"}),e.jsx(U,{value:"compliant",children:"Compliant"}),e.jsx(U,{value:"on-track",children:"On Track"}),e.jsx(U,{value:"approaching",children:"Approaching"}),e.jsx(U,{value:"critical",children:"Critical"}),e.jsx(U,{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(J,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:N.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:N.selectedUser.displayName||N.selectedUser.email}),e.jsx(M,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:N.handleClear,children:e.jsx(lt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(fe,{placeholder:"Search initiator...",value:N.searchQuery,onChange:D=>N.handleSearch(D.target.value),onFocus:()=>{N.searchResults.length>0&&N.setShowResults(!0)},onBlur:()=>setTimeout(()=>N.setShowResults(!1),200),className:"h-10","data-testid":"initiator-search-input"}),N.showResults&&N.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:N.searchResults.map(D=>e.jsx("button",{type:"button",onClick:()=>N.handleSelect(D),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:D.displayName||D.email}),D.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:D.email})]})},D.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(J,{className:"text-sm font-medium text-gray-700",children:"Approver"}),s.approverFilter!=="all"&&e.jsxs(Te,{value:s.approverFilterType,onValueChange:D=>s.setApproverFilterType(D),children:[e.jsx(Re,{className:"h-7 w-32 text-xs",children:e.jsx(ke,{})}),e.jsxs(De,{children:[e.jsx(U,{value:"current",children:"Current Only"}),e.jsx(U,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:R.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:R.selectedUser.displayName||R.selectedUser.email}),e.jsx(M,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:R.handleClear,children:e.jsx(lt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(fe,{placeholder:"Search approver...",value:R.searchQuery,onChange:D=>R.handleSearch(D.target.value),onFocus:()=>{R.searchResults.length>0&&R.setShowResults(!0)},onBlur:()=>setTimeout(()=>R.setShowResults(!1),200),className:"h-10","data-testid":"approver-search-input"}),R.showResults&&R.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:R.searchResults.map(D=>e.jsx("button",{type:"button",onClick:()=>R.handleSelect(D),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:D.displayName||D.email}),D.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:D.email})]})},D.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(We,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Te,{value:s.dateRange,onValueChange:s.handleDateRangeChange,children:[e.jsx(Re,{className:"w-[160px] h-10",children:e.jsx(ke,{placeholder:"Date Range"})}),e.jsxs(De,{children:[e.jsx(U,{value:"all",children:"All Time"}),e.jsx(U,{value:"today",children:"Today"}),e.jsx(U,{value:"week",children:"This Week"}),e.jsx(U,{value:"month",children:"This Month"}),e.jsx(U,{value:"last7days",children:"Last 7 Days"}),e.jsx(U,{value:"last30days",children:"Last 30 Days"}),e.jsx(U,{value:"custom",children:"Custom Range"})]})]}),s.dateRange==="custom"&&e.jsxs(cs,{open:s.showCustomDatePicker,onOpenChange:s.setShowCustomDatePicker,children:[e.jsx(ds,{asChild:!0,children:e.jsxs(M,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(We,{className:"w-4 h-4"}),s.customStartDate&&s.customEndDate?`${xe(s.customStartDate,"MMM d, yyyy")} - ${xe(s.customEndDate,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(ms,{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(J,{htmlFor:"start-date",children:"Start Date"}),e.jsx(fe,{id:"start-date",type:"date",value:s.customStartDate?xe(s.customStartDate,"yyyy-MM-dd"):"",onChange:D=>{const H=D.target.value?new Date(D.target.value):void 0;H?(s.setCustomStartDate(H),s.customEndDate&&H>s.customEndDate&&s.setCustomEndDate(H)):s.setCustomStartDate(void 0)},max:xe(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"end-date",children:"End Date"}),e.jsx(fe,{id:"end-date",type:"date",value:s.customEndDate?xe(s.customEndDate,"yyyy-MM-dd"):"",onChange:D=>{const H=D.target.value?new Date(D.target.value):void 0;H?(s.setCustomEndDate(H),s.customStartDate&&H<s.customStartDate&&s.setCustomStartDate(H)):s.setCustomEndDate(void 0)},min:s.customStartDate?xe(s.customStartDate,"yyyy-MM-dd"):void 0,max:xe(new Date,"yyyy-MM-dd"),className:"w-full"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(M,{size:"sm",onClick:s.handleApplyCustomDate,disabled:!s.customStartDate||!s.customEndDate,className:"flex-1 bg-re-green hover:bg-re-green/90",children:"Apply"}),e.jsx(M,{size:"sm",variant:"outline",onClick:()=>{s.setShowCustomDatePicker(!1),s.setCustomStartDate(void 0),s.setCustomEndDate(void 0),s.setDateRange("month")},children:"Cancel"})]})]})})]})]})]})})}),e.jsx(ch,{requests:S,loading:n,hasActiveFilters:s.hasActiveFilters,onViewRequest:t}),e.jsx(da,{currentPage:s.currentPage||1,totalPages:v,totalRecords:f,itemsPerPage:b,onPageChange:A,loading:n,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}function aS(){const t=Hs();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(K,{children:e.jsxs(G,{className:"p-8 text-center",children:[e.jsx(Pe,{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(xs,{className:"w-4 h-4 mr-2"}),"Back"]})]})})})})}function rS({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(nt,{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(Et,{className:`w-4 h-4 ${s?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:"Refresh"})]})]})}function nS({approverStats:t}){const s=(t==null?void 0:t.tatCompliancePercent)??0;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(K,{children:[e.jsx(ae,{className:"pb-3",children:e.jsx(re,{className:"text-sm font-medium text-gray-600",children:"TAT Compliance"})}),e.jsxs(G,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-3xl font-bold text-gray-900",children:[s,"%"]}),e.jsx("div",{className:`p-2 rounded-lg ${s>=95?"bg-green-100":s>=90?"bg-blue-100":s>=85?"bg-orange-100":"bg-red-100"}`,children:e.jsx(ct,{className:`w-5 h-5 ${s>=95?"text-green-600":s>=90?"text-blue-600":s>=85?"text-orange-600":"text-red-600"}`})})]}),e.jsx(gs,{value:s,className:"mt-2 h-2"})]})]}),e.jsxs(K,{children:[e.jsx(ae,{className:"pb-3",children:e.jsx(re,{className:"text-sm font-medium text-gray-600",children:"Total Approved"})}),e.jsxs(G,{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(je,{className:"w-5 h-5 text-blue-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Requests handled"})]})]}),e.jsxs(K,{children:[e.jsx(ae,{className:"pb-3",children:e.jsx(re,{className:"text-sm font-medium text-gray-600",children:"Avg Response Time"})}),e.jsxs(G,{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(Bi,{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(K,{children:[e.jsx(ae,{className:"pb-3",children:e.jsx(re,{className:"text-sm font-medium text-gray-600",children:"Pending Actions"})}),e.jsxs(G,{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(Ie,{className:"w-5 h-5 text-orange-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Awaiting approval"})]})]})]})}function iS({approverName:t,approverStats:s,dateRange:a="all",customStartDate:r,customEndDate:n}){return e.jsxs(K,{"data-testid":"approver-actions-stats",children:[e.jsxs(ae,{children:[e.jsx(re,{children:"Approver's Actions"}),e.jsxs(ge,{children:["Statistics for all requests by ",t," ",a&&a!=="all"?o0(a,r,n,""):"(all time)"]})]}),e.jsxs(G,{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(nt,{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(je,{className:"w-5 h-5 text-green-600"}),e.jsx("span",{className:"text-xs text-green-600 font-medium",children:s&&s.approvedCount+s.rejectedCount>0?`${Math.round(s.approvedCount/(s.approvedCount+s.rejectedCount)*100)}%`:"0%"})]}),e.jsx("div",{className:"text-2xl font-bold text-green-700",children:(s==null?void 0:s.approvedCount)||0}),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(Je,{className:"w-5 h-5 text-red-600"}),e.jsx("span",{className:"text-xs text-red-600 font-medium",children:s&&s.approvedCount+s.rejectedCount>0?`${Math.round(s.rejectedCount/(s.approvedCount+s.rejectedCount)*100)}%`:"0%"})]}),e.jsx("div",{className:"text-2xl font-bold text-red-700",children:(s==null?void 0:s.rejectedCount)||0}),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(Ie,{className:"w-5 h-5 text-yellow-600"})}),e.jsx("div",{className:"text-2xl font-bold text-yellow-700",children:(s==null?void 0:s.pendingCount)||0}),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(Xr,{className:"w-5 h-5 text-gray-600"})}),e.jsx("div",{className:"text-2xl font-bold text-gray-700",children:(s==null?void 0:s.closedCount)||0}),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(Ae,{className:"w-5 h-5 text-blue-600"})}),e.jsx("div",{className:"text-2xl font-bold text-blue-700",children:(s==null?void 0:s.totalApproved)||0}),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(ct,{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(kx,{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}%`:"N/A"})]}),e.jsx("div",{className:"text-2xl font-bold text-green-700",children:(s==null?void 0:s.withinTatCount)||0}),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(Pe,{className:"w-5 h-5 text-red-600"})}),e.jsx("div",{className:"text-2xl font-bold text-red-700",children:(s==null?void 0:s.breachedCount)||0}),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(wd,{className:"w-5 h-5 text-purple-600"})}),e.jsx("div",{className:"text-2xl font-bold text-purple-700",children:s?s.approvedCount+s.rejectedCount:0}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"Completed Actions"})]})]})]})]})]})}function oS({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:p,onDateRangeChange:g,onShowCustomDatePickerChange:y,onTempStartDateChange:v,onTempEndDateChange:w,onApplyCustomDate:f,onClearFilters:C}){return e.jsxs(K,{"data-testid":"approver-performance-filters",children:[e.jsx(ae,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{children:"Filters"}),e.jsx(M,{variant:"ghost",size:"sm",onClick:C,className:"text-xs","data-testid":"clear-filters-button",children:"Clear All"})]})}),e.jsx(G,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-6 gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Xt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(fe,{placeholder:"Search requests...",value:t,onChange:b=>m(b.target.value),className:"pl-10","data-testid":"search-input"})]}),e.jsxs(Te,{value:s,onValueChange:u,children:[e.jsx(Re,{"data-testid":"status-filter",children:e.jsx(ke,{placeholder:"Status"})}),e.jsxs(De,{children:[e.jsx(U,{value:"all",children:"All Status"}),e.jsx(U,{value:"pending",children:"Pending"}),e.jsx(U,{value:"approved",children:"Approved"}),e.jsx(U,{value:"rejected",children:"Rejected"}),e.jsx(U,{value:"closed",children:"Closed"})]})]}),e.jsxs(Te,{value:a,onValueChange:h,children:[e.jsx(Re,{"data-testid":"priority-filter",children:e.jsx(ke,{placeholder:"Priority"})}),e.jsxs(De,{children:[e.jsx(U,{value:"all",children:"All Priority"}),e.jsx(U,{value:"express",children:"Express"}),e.jsx(U,{value:"standard",children:"Standard"})]})]}),e.jsxs(Te,{value:r,onValueChange:p,children:[e.jsx(Re,{"data-testid":"sla-compliance-filter",children:e.jsx(ke,{placeholder:"SLA Compliance"})}),e.jsxs(De,{children:[e.jsx(U,{value:"all",children:"All SLA"}),e.jsx(U,{value:"compliant",children:"Compliant"}),e.jsx(U,{value:"on-track",children:"On Track"}),e.jsx(U,{value:"approaching",children:"Approaching"}),e.jsx(U,{value:"critical",children:"Critical"}),e.jsx(U,{value:"breached",children:"Breached"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(We,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Te,{value:n,onValueChange:g,children:[e.jsx(Re,{className:"flex-1","data-testid":"date-range-filter",children:e.jsx(ke,{placeholder:"Date Range"})}),e.jsxs(De,{children:[e.jsx(U,{value:"all",children:"All Time"}),e.jsx(U,{value:"today",children:"Today"}),e.jsx(U,{value:"week",children:"This Week"}),e.jsx(U,{value:"month",children:"This Month"}),e.jsx(U,{value:"last7days",children:"Last 7 Days"}),e.jsx(U,{value:"last30days",children:"Last 30 Days"}),e.jsx(U,{value:"custom",children:"Custom Range"})]})]}),n==="custom"&&e.jsxs(cs,{open:l,onOpenChange:y,children:[e.jsx(ds,{asChild:!0,children:e.jsxs(M,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(We,{className:"w-4 h-4"}),c&&d?`${xe(c,"MMM d")} - ${xe(d,"MMM d")}`:"Select dates"]})}),e.jsx(ms,{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(J,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(fe,{id:"start-date",type:"date",value:c?xe(c,"yyyy-MM-dd"):"",onChange:b=>{const N=b.target.value?new Date(b.target.value):void 0;N?(v(N),d&&N>d&&w(N)):v(void 0)},max:xe(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(fe,{id:"end-date",type:"date",value:d?xe(d,"yyyy-MM-dd"):"",onChange:b=>{const N=b.target.value?new Date(b.target.value):void 0;N?(w(N),c&&N<c&&v(N)):w(void 0)},min:c?xe(c,"yyyy-MM-dd"):void 0,max:xe(new Date,"yyyy-MM-dd"),className:"w-full"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(M,{size:"sm",onClick:f,disabled:!c||!d,className:"flex-1 bg-re-green hover:bg-re-green/90","data-testid":"apply-date-button",children:"Apply"}),e.jsx(M,{size:"sm",variant:"outline",onClick:()=>{y(!1),v(i),w(o),(!i||!o)&&g("all")},"data-testid":"cancel-date-button",children:"Cancel"})]})]})})]})]})]})})]})}const lS=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Vs,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:ct,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:ct,iconColor:"text-gray-600"}}},cS=t=>{switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:je,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:Je,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:Ie,iconColor:"text-yellow-600"};case"in-progress":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Ie,iconColor:"text-blue-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:je,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ae,iconColor:"text-gray-600"}}},dS=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 mS(t){if(!t)return"N/A";try{return xe(new Date(t),"MMM d, yyyy")}catch{return"N/A"}}function uS(t){if(!t)return"N/A";try{return xe(new Date(t),"MMM d, yyyy HH:mm")}catch{return"N/A"}}function hS({requests:t,loading:s,approverName:a,currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:o,onPageChange:l}){const c=Hs();return e.jsxs(K,{"data-testid":"approver-performance-request-list",children:[e.jsxs(ae,{children:[e.jsx(re,{children:"Request Details"}),e.jsxs(ge,{children:["All requests handled by ",a," with applied filters"]})]}),e.jsxs(G,{children:[s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"loading-state",children:[e.jsx(Et,{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(Ae,{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=lS(d.priority),u=cS(d.status),h=dS(d.slaStatus||""),p=m.icon,g=u.icon;return e.jsx(K,{className:"hover:shadow-md transition-shadow cursor-pointer",onClick:()=>c(`/request/${d.requestId}`),"data-testid":`request-card-${d.requestId}`,children:e.jsx(G,{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(ee,{className:m.color,"data-testid":"priority-badge",children:[e.jsx(p,{className:`w-3 h-3 mr-1 ${m.iconColor}`}),d.priority]}),e.jsxs(ee,{className:u.color,"data-testid":"status-badge",children:[e.jsx(g,{className:`w-3 h-3 mr-1 ${u.iconColor}`}),d.status]}),d.approvalStatus&&e.jsx(ee,{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(je,{className:"w-3 h-3 mr-1"}),"Approved"]}):d.approvalStatus==="rejected"||d.approvalStatus==="REJECTED"?e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-3 h-3 mr-1"}),"Rejected"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ie,{className:"w-3 h-3 mr-1"}),"Pending"]})}),d.slaStatus&&e.jsx(ee,{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(it,{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(Ie,{className:"w-3 h-3"}),"Submitted: ",mS(d.submissionDate)]}),d.approvalActionDate&&e.jsxs("span",{className:"flex items-center gap-1","data-testid":"action-date",children:[e.jsx(je,{className:"w-3 h-3"}),"Action: ",uS(d.approvalActionDate)]}),e.jsxs("span",{className:"flex items-center gap-1","data-testid":"approval-level",children:[e.jsx(ct,{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(Bi,{className:"w-3 h-3"}),ot(d.levelElapsedHours)," / ",ot(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(Nt,{className:"w-4 h-4"})})]})})},d.requestId)})}),n>0&&e.jsx("div",{className:"mt-6","data-testid":"pagination-container",children:e.jsx(da,{currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:o,onPageChange:l,itemLabel:"requests",testIdPrefix:"approver-performance"})})]})]})}function pS(){const[t]=Ad(),[s,a]=x.useState(""),[r,n]=x.useState(t.get("status")||"all"),[i,o]=x.useState(t.get("priority")||"all"),[l,c]=x.useState(t.get("slaCompliance")||"all"),[d,m]=x.useState(t.get("dateRange")||"all"),[u,h]=x.useState(t.get("startDate")?new Date(t.get("startDate")):void 0),[p,g]=x.useState(t.get("endDate")?new Date(t.get("endDate")):void 0),[y,v]=x.useState(!1),[w,f]=x.useState(void 0),[C,b]=x.useState(void 0),N=x.useCallback(()=>{a(""),n("all"),o("all"),c("all"),m("all"),h(void 0),g(void 0),f(void 0),b(void 0),v(!1)},[]),R=x.useCallback(P=>{const I=P;m(I),I!=="custom"?(h(void 0),g(void 0),f(void 0),b(void 0),v(!1)):(f(u),b(p),v(!0))},[u,p]),E=x.useCallback(()=>{if(w&&C){if(w>C){const P=w;h(C),g(P),f(C),b(P)}else h(w),g(C);v(!1)}},[w,C]);return{searchTerm:s,statusFilter:r,priorityFilter:i,slaComplianceFilter:l,dateRange:d,customStartDate:u,customEndDate:p,showCustomDatePicker:y,tempCustomStartDate:w,tempCustomEndDate:C,setSearchTerm:a,setStatusFilter:n,setPriorityFilter:o,setSlaComplianceFilter:c,setDateRange:m,setCustomStartDate:h,setCustomEndDate:g,setShowCustomDatePicker:v,setTempCustomStartDate:f,setTempCustomEndDate:b,clearFilters:N,handleDateRangeChange:R,handleApplyCustomDate:E}}function xS({approverId:t,dateRange:s,customStartDate:a,customEndDate:r,statusFilter:n,priorityFilter:i,slaComplianceFilter:o,searchTerm:l,itemsPerPage:c}){const[d,m]=x.useState([]),[u,h]=x.useState(null),[p,g]=x.useState([]),[y,v]=x.useState(!0),[w,f]=x.useState(!1),[C,b]=x.useState(1),[N,R]=x.useState(1),[E,P]=x.useState(0),I=x.useRef(!0),j=x.useCallback(async()=>{if(t)try{const F=s==="all"?void 0:s,L=await He.getSingleApproverStats(t,F,a,r,i!=="all"?i:void 0,o!=="all"?o:void 0);h(L)}catch(F){console.error("[ApproverPerformance] Failed to fetch approver stats:",F),h(null)}},[t,s,a,r,i,o]),k=x.useCallback(async(F=1)=>{if(!t){v(!1);return}try{v(!0);const L=await He.getRequestsByApprover(t,F,c,s==="all"?void 0:s,a,r,n!=="all"?n:void 0,i!=="all"?i:void 0,o!=="all"?o:void 0,l||void 0);m(L.requests),P(L.pagination.totalRecords),R(L.pagination.totalPages),b(L.pagination.currentPage),g(L.requests)}catch(L){console.error("Failed to fetch requests:",L)}finally{v(!1),f(!1)}},[t,s,a,r,n,i,o,l,c]);x.useEffect(()=>{I.current&&(I.current=!1,j(),k(1))},[]),x.useEffect(()=>{I.current||j()},[s,a,r,i,o]),x.useEffect(()=>{I.current||k(1)},[s,a,r,n,i,o,l]);const _=x.useCallback(()=>{f(!0),j(),k(1)},[j,k]),Y=x.useCallback(F=>{k(F)},[k]);return{requests:d,approverStats:u,allFilteredRequests:p,loading:y,refreshing:w,currentPage:C,totalPages:N,totalRecords:E,handleRefresh:_,handlePageChange:Y}}const Hc=10;function gS(){const[t]=Ad(),s=t.get("approverId")||"",a=t.get("approverName")||"Unknown Approver",r=pS(),n=xS({approverId:s,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,slaComplianceFilter:r.slaComplianceFilter,searchTerm:r.searchTerm,itemsPerPage:Hc});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(rS,{approverName:a,refreshing:n.refreshing,onRefresh:n.handleRefresh}),n.approverStats&&e.jsx(nS,{approverStats:n.approverStats}),n.approverStats&&e.jsx(iS,{approverName:a,approverStats:n.approverStats,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate}),e.jsx(oS,{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(hS,{requests:n.requests,loading:n.loading,approverName:a,currentPage:n.currentPage,totalPages:n.totalPages,totalRecords:n.totalRecords,itemsPerPage:Hc,onPageChange:n.handlePageChange})]}):e.jsx(aS,{})}function fS(){const{user:t}=Mt(),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(K,{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(G,{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(bt,{className:"h-24 w-24 ring-4 ring-white/20 shadow-xl",children:[e.jsx(Qr,{src:(t==null?void 0:t.picture)||""}),e.jsx(jt,{className:"bg-yellow-400 text-slate-900 text-2xl font-bold",children:s()})]}),Zs(t)&&e.jsx("div",{className:"absolute -bottom-2 -right-2 bg-yellow-400 rounded-full p-1.5 shadow-lg",children:e.jsx(It,{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:[Zs(t)&&e.jsxs(ee,{className:"bg-yellow-400 text-slate-900 hover:bg-yellow-400 font-semibold",children:[e.jsx(It,{className:"w-3 h-3 mr-1"}),"Administrator"]}),Fa(t)&&e.jsxs(ee,{className:"bg-blue-400 text-slate-900 hover:bg-blue-400 font-semibold",children:[e.jsx(nt,{className:"w-3 h-3 mr-1"}),"Management"]}),(t==null?void 0:t.employeeId)&&e.jsxs(ee,{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(K,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(ae,{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(it,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(re,{className:"text-lg text-gray-900",children:"Personal Information"}),e.jsx(ge,{className:"text-gray-600",children:"Your personal details"})]})]})}),e.jsx(G,{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(Oi,{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(it,{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(it,{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(it,{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(yd,{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(K,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(ae,{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(Xo,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsx(re,{className:"text-lg text-gray-900",children:"Professional Information"}),e.jsx(ge,{className:"text-gray-600",children:"Work-related details"})]})]})}),e.jsx(G,{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(it,{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(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:"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(Xo,{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(It,{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(ee,{variant:Zs(t)||Fa(t)?"default":"secondary",className:Zs(t)?"bg-yellow-400 text-slate-900":Fa(t)?"bg-blue-400 text-slate-900":"",children:Zs(t)?"Administrator":Fa(t)?"Management":"User"}),(Zs(t)||Fa(t))&&e.jsx(je,{className:"w-4 h-4 text-green-600"})]})]})]})]})})]})]}),e.jsxs(K,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(ae,{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(We,{className:"h-5 w-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(re,{className:"text-lg text-gray-900",children:"Account Status"}),e.jsx(ge,{className:"text-gray-600",children:"Account information and activity"})]})]})}),e.jsx(G,{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(je,{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(ee,{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 Sr="BBb78N3tSTEw6mPbBmvEDX2bhYEDKPc_zffL-vxPV8FBSmR1qSpy9gdV8zt-WFF-q2NPpVmL4BhbUzLSHVAPjcI",yS="https://re-workflow-nt-dev.siplsolutions.com";function Zn(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<r.length;++i)n[i]=r.charCodeAt(i);return n}async function vS(){if(!("serviceWorker"in navigator))throw new Error("Service workers are not supported in this browser");let t;try{await navigator.serviceWorker.getRegistration("/service-worker.js")?t=await navigator.serviceWorker.ready:(t=await navigator.serviceWorker.register("/service-worker.js"),t=await navigator.serviceWorker.ready)}catch(s){throw new Error(`Failed to register service worker: ${(s==null?void 0:s.message)||"Unknown error"}`)}return t}async function bS(t){if(Sr.trim().length===0)throw new Error("VAPID public key is empty. Please configure VITE_PUBLIC_VAPID_KEY in your environment variables.");if(!t.pushManager)throw new Error("Push manager is not available. Please ensure your browser supports push notifications and the service worker is properly registered.");let s;try{const i=await t.pushManager.getSubscription();if(i)try{s=i}catch{console.warn("[Push] Existing subscription is invalid, creating new one..."),await i.unsubscribe().catch(()=>{}),s=await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Zn(Sr)})}else try{s=await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Zn(Sr)})}catch(o){console.warn("[Push] Initial subscription failed, attempting to clear and retry...");try{const l=await t.pushManager.getSubscription();l&&await l.unsubscribe().catch(()=>{}),s=await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Zn(Sr)})}catch(l){const c=(o==null?void 0:o.message)||(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. 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: ${c}`)}}}catch(i){const o=(i==null?void 0:i.message)||"Unknown error";throw o.includes("push service error")||o.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."):o.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: ${o}`)}const a=s.toJSON(),r=!0,n=null;try{const i={"Content-Type":"application/json"},o=await fetch(`${yS}/api/v1/workflows/notifications/subscribe`,{method:"POST",headers:i,credentials:"include",body:JSON.stringify(a)});if(!o.ok){const c=await o.json().catch(()=>({error:"Unknown error"}));throw new Error((c==null?void 0:c.error)||(c==null?void 0:c.message)||`Server error: ${o.status}`)}const l=await o.json();if(!l.success)throw new Error(l.error||"Failed to save subscription")}catch(i){throw i instanceof Error&&i.message.includes("Failed")?i:new Error(`Failed to save subscription to server: ${(i==null?void 0:i.message)||"Network error"}`)}return s}async function jS(){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 vS()}catch(a){throw new Error(`Service worker registration failed: ${(a==null?void 0:a.message)||"Unknown error"}`)}try{await bS(s)}catch(a){throw a}}function Di({className:t,defaultValue:s,value:a,min:r=0,max:n=100,...i}){const o=x.useMemo(()=>Array.isArray(a)?a:Array.isArray(s)?s:[r,n],[a,s,r,n]);return e.jsxs(Np,{"data-slot":"slider",defaultValue:s,value:a,min:r,max:n,className:ce("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(wp,{"data-slot":"slider-track",className:ce("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(Cp,{"data-slot":"slider-range",className:ce("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full")})}),Array.from({length:o.length},(l,c)=>e.jsx(Sp,{"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 NS({onConfigUpdate:t}){const[s,a]=x.useState([]),[r,n]=x.useState(!0),[i,o]=x.useState(null),[l,c]=x.useState(null),[d,m]=x.useState({}),[u,h]=x.useState(null);x.useEffect(()=>{p()},[]);const p=async()=>{var j,k;try{n(!0),c(null);const _=await tn();a(_)}catch(_){c(((k=(j=_.response)==null?void 0:j.data)==null?void 0:k.error)||"Failed to load configurations")}finally{n(!1)}},g=async j=>{var k,_;try{o(j.configKey),c(null);const Y=d[j.configKey]??j.configValue;if(j.validationRules){const F=parseFloat(Y);if(j.valueType==="NUMBER"){if(j.validationRules.min!==void 0&&F<j.validationRules.min)throw new Error(`Value must be at least ${j.validationRules.min}`);if(j.validationRules.max!==void 0&&F>j.validationRules.max)throw new Error(`Value must be at most ${j.validationRules.max}`)}}await vt(j.configKey,Y),a(F=>F.map(L=>L.configKey===j.configKey?{...L,configValue:Y}:L)),m(F=>{const L={...F};return delete L[j.configKey],L}),h(`${j.displayName} updated successfully`),setTimeout(()=>h(null),3e3),t&&t()}catch(Y){c(Y.message||((_=(k=Y.response)==null?void 0:k.data)==null?void 0:_.error)||"Failed to save configuration")}finally{o(null)}},y=async j=>{var k,_;if(confirm(`Reset "${j.displayName}" to default value?`))try{o(j.configKey),c(null),await gy(j.configKey),a(Y=>Y.map(F=>F.configKey===j.configKey?{...F,configValue:F.defaultValue||""}:F)),m(Y=>{const F={...Y};return delete F[j.configKey],F}),h(`${j.displayName} reset to default`),setTimeout(()=>h(null),3e3)}catch(Y){c(((_=(k=Y.response)==null?void 0:k.data)==null?void 0:_.error)||"Failed to reset configuration")}finally{o(null)}},v=(j,k)=>{m(_=>({..._,[j]:k}))},w=j=>d[j.configKey]??j.configValue,f=j=>d[j.configKey]!==void 0&&d[j.configKey]!==j.configValue,C=j=>{var Y,F,L,A;const k=w(j),_=i===j.configKey;if(!j.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:j.configValue}),e.jsxs("p",{className:"text-xs text-slate-500 mt-1.5 flex items-center gap-1",children:[e.jsx(Pe,{className:"w-3 h-3"}),"This setting cannot be modified"]})]});switch(j.uiComponent||j.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 ${k==="true"?"bg-green-500":"bg-slate-400"}`}),e.jsx("span",{className:`text-sm font-medium ${k==="true"?"text-green-700":"text-slate-600"}`,children:k==="true"?"Enabled":"Disabled"})]}),e.jsx(Lt,{checked:k==="true",onCheckedChange:H=>v(j.configKey,H?"true":"false"),disabled:_})]});case"slider":const S=parseInt(k)||0,T=((Y=j.validationRules)==null?void 0:Y.min)||0,D=((F=j.validationRules)==null?void 0:F.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:[S,"%"]}),e.jsxs("span",{className:"text-xs text-slate-500 bg-slate-100 px-2 py-1 rounded-sm border border-slate-200",children:["Range: ",T,"-",D]})]}),e.jsx(Di,{value:[S],min:T,max:D,step:1,onValueChange:([H])=>{H!==void 0&&v(j.configKey,H.toString())},disabled:_,className:"w-full"})]});case"number":return e.jsx(fe,{type:"number",value:k,onChange:H=>v(j.configKey,H.target.value),disabled:_,min:(L=j.validationRules)==null?void 0:L.min,max:(A=j.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(fe,{type:"text",value:k,onChange:H=>v(j.configKey,H.target.value),disabled:_,className:"font-mono border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 rounded-md transition-all shadow-sm"})}},b=j=>{switch(j){case"TAT_SETTINGS":return e.jsx(Ie,{className:"w-5 h-5"});case"DOCUMENT_POLICY":return e.jsx(Ae,{className:"w-5 h-5"});case"NOTIFICATION_RULES":return e.jsx(Ft,{className:"w-5 h-5"});case"AI_CONFIGURATION":return e.jsx(Gr,{className:"w-5 h-5"});case"WORKFLOW_SHARING":return e.jsx(Sa,{className:"w-5 h-5"});default:return e.jsx(Ls,{className:"w-5 h-5"})}},N=["DASHBOARD_LAYOUT"],R=["ALLOW_EXTERNAL_SHARING","NOTIFICATION_BATCH_DELAY_MS","AI_REMARK_MAX_CHARACTERS"],E=s.filter(j=>!N.includes(j.configCategory)&&!R.includes(j.configKey)),P=E.reduce((j,k)=>(j[k.configCategory]||(j[k.configCategory]=[]),j[k.configCategory].push(k),j),{});if(Object.keys(P).forEach(j=>{const k=P[j];k&&k.sort((_,Y)=>_.sortOrder-Y.sortOrder)}),r)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Ue,{className:"w-8 h-8 animate-spin text-gray-400"})});if(E.length===0)return e.jsx(K,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(G,{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(Ls,{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 I=Object.keys(P);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(je,{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(Pe,{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(Jr,{defaultValue:I[0],className:"w-full",children:[e.jsx(en,{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:I.map(j=>e.jsx(xt,{value:j,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:j.replace(/_/g," ")})},j))}),I.map(j=>{var k,_,Y;return e.jsx(gt,{value:j,className:"space-y-4 mt-6",children:e.jsxs(K,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ae,{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:b(j)})}),e.jsxs("div",{children:[e.jsx(re,{className:"text-lg font-semibold text-slate-900",children:j.replace(/_/g," ")}),e.jsxs(ge,{className:"text-sm",children:[((k=P[j])==null?void 0:k.length)||0," setting",(((_=P[j])==null?void 0:_.length)||0)!==1?"s":""," available"]})]})]})}),e.jsx(G,{className:"space-y-6",children:(Y=P[j])==null?void 0:Y.map(F=>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(J,{className:"text-sm font-semibold text-slate-900",children:F.displayName}),f(F)&&e.jsx(ee,{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"}),F.requiresRestart&&e.jsx(ee,{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"})]}),F.description&&e.jsx("p",{className:"text-xs text-slate-600 mt-1 leading-relaxed",children:F.description}),F.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:F.defaultValue})]})]})}),C(F),F.isEditable&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(M,{size:"sm",onClick:()=>g(F),disabled:!f(F)||i===F.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===F.configKey?e.jsxs(e.Fragment,{children:[e.jsx(Ue,{className:"w-4 h-4 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(zs,{className:"w-4 h-4"}),"Save Changes"]})}),F.defaultValue&&e.jsxs(M,{size:"sm",variant:"outline",onClick:()=>y(F),disabled:i===F.configKey,className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(Rx,{className:"w-4 h-4"}),"Reset to Default"]})]})]},F.configKey))})]})},j)})]})]})}function wS(){const[t,s]=x.useState([]),[a,r]=x.useState(!0),[n,i]=x.useState(new Date().getFullYear()),[o,l]=x.useState(!1),[c,d]=x.useState(null),[m,u]=x.useState(null),[h,p]=x.useState(null),[g,y]=x.useState({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1});x.useEffect(()=>{v()},[n]);const v=async()=>{var j,k;try{r(!0),u(null);const _=await fy(n);s(_)}catch(_){u(((k=(j=_.response)==null?void 0:j.data)==null?void 0:k.error)||"Failed to load holidays")}finally{r(!1)}},w=()=>{y({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1}),d(null),l(!0)},f=j=>{y({holidayDate:j.holidayDate,holidayName:j.holidayName,description:j.description||"",holidayType:j.holidayType,isRecurring:j.isRecurring}),d(j),l(!0)},C=()=>{if(c)return;const j=new Date;return j.setDate(j.getDate()+1),j.toISOString().split("T")[0]},b=async()=>{var j,k;try{if(u(null),!g.holidayDate||!g.holidayName){u("Holiday date and name are required");return}c?(await vy(c.holidayId,g),p("Holiday updated successfully")):(await yy(g),p("Holiday created successfully")),await v(),l(!1),setTimeout(()=>p(null),3e3)}catch(_){u(((k=(j=_.response)==null?void 0:j.data)==null?void 0:k.error)||"Failed to save holiday")}},N=async j=>{var k,_;if(confirm(`Delete "${j.holidayName}"?`))try{u(null),await by(j.holidayId),p("Holiday deleted successfully"),await v(),setTimeout(()=>p(null),3e3)}catch(Y){u(((_=(k=Y.response)==null?void 0:k.data)==null?void 0:_.error)||"Failed to delete holiday")}},R=j=>{switch(j){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"}},E=Array.from({length:5},(j,k)=>new Date().getFullYear()-1+k),P=t.reduce((j,k)=>{const _=new Date(k.holidayDate).toLocaleString("default",{month:"long"});return j[_]||(j[_]=[]),j[_].push(k),j},{}),I=Object.keys(P).sort((j,k)=>{const _=new Date(Date.parse(j+" 1, 2000")).getMonth(),Y=new Date(Date.parse(k+" 1, 2000")).getMonth();return _-Y});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(je,{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(Pe,{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(K,{className:"shadow-lg border-0 rounded-md",children:e.jsx(ae,{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(We,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(re,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Holiday Calendar"}),e.jsx(ge,{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(Te,{value:n.toString(),onValueChange:j=>i(parseInt(j)),children:[e.jsx(Re,{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(ke,{})}),e.jsx(De,{className:"rounded-md",children:E.map(j=>e.jsx(U,{value:j.toString(),children:j},j))})]}),e.jsxs(M,{onClick:w,className:"gap-2 bg-re-green hover:bg-re-green/90 text-white shadow-sm flex-1 sm:flex-initial",children:[e.jsx(_s,{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(Ue,{className:"w-8 h-8 animate-spin text-gray-400"})}):t.length===0?e.jsx(K,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(G,{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(We,{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:w,variant:"outline",className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(_s,{className:"w-4 h-4"}),"Add First Holiday"]})]})}):e.jsx("div",{className:"space-y-4 sm:space-y-6",children:I.map(j=>{var k,_,Y;return e.jsxs(K,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ae,{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(re,{className:"text-base sm:text-lg font-semibold text-slate-900",children:[j," ",n]}),e.jsxs(ge,{className:"text-xs sm:text-sm",children:[((k=P[j])==null?void 0:k.length)||0," holiday",(((_=P[j])==null?void 0:_.length)||0)!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-blue-50 rounded-md",children:e.jsx(We,{className:"w-4 h-4 text-blue-600"})})]})}),e.jsx(G,{className:"space-y-3 pt-4",children:(Y=P[j])==null?void 0:Y.map(F=>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:F.holidayName}),e.jsx(ee,{variant:"outline",className:`${R(F.holidayType)} text-[10px] sm:text-xs font-medium shadow-sm`,children:F.holidayType}),F.isRecurring&&e.jsx(ee,{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:Qd(F.holidayDate)}),F.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-1.5 line-clamp-2",children:F.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(F),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(Dx,{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:()=>N(F),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(Vi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Delete"})]})]})]},F.holidayId))})]},j)})}),e.jsx(et,{open:o,onOpenChange:l,children:e.jsxs(Xe,{className:"sm:max-w-[550px] max-h-[90vh] rounded-lg flex flex-col p-0",children:[e.jsx(tt,{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(We,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(Ze,{className:"text-xl font-semibold text-slate-900",children:c?"Edit Holiday":"Add New Holiday"}),e.jsx(qt,{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(J,{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(fe,{id:"date",type:"date",value:g.holidayDate,onChange:j=>y({...g,holidayDate:j.target.value}),min:C(),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(J,{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(fe,{id:"name",placeholder:"e.g., Diwali, Republic Day, Christmas",value:g.holidayName,onChange:j=>y({...g,holidayName:j.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(J,{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(fe,{id:"description",placeholder:"Add additional details about this holiday...",value:g.description,onChange:j=>y({...g,description:j.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(J,{htmlFor:"type",className:"text-sm font-semibold text-slate-900",children:"Holiday Type"}),e.jsxs(Te,{value:g.holidayType,onValueChange:j=>y({...g,holidayType:j}),children:[e.jsx(Re,{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(ke,{})}),e.jsxs(De,{className:"rounded-lg",children:[e.jsx(U,{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(U,{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(U,{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(U,{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({...g,isRecurring:!g.isRecurring}),children:[e.jsx("input",{type:"checkbox",id:"recurring",checked:g.isRecurring,onChange:j=>y({...g,isRecurring:j.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(J,{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(wt,{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:b,disabled:!g.holidayDate||!g.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(We,{className:"w-4 h-4 mr-2"}),c?"Update Holiday":"Add Holiday"]})]})]})})]})}function CS(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function SS(){const[t,s]=x.useState(""),[a,r]=x.useState([]),[n,i]=x.useState(!1),[o,l]=x.useState(null),[c,d]=x.useState("USER"),[m,u]=x.useState(!1),[h,p]=x.useState(null),[g,y]=x.useState([]),[v,w]=x.useState(!1),[f,C]=x.useState({admins:0,management:0,users:0}),[b,N]=x.useState("ELEVATED"),[R,E]=x.useState(1),[P,I]=x.useState(1),[j,k]=x.useState(0),_=10,Y=x.useRef(null),F=x.useRef(null),L=x.useCallback(CS(async $=>{var X,ne,q;if(!$||!$.startsWith("@")||$.length<2){r([]),i(!1);return}i(!0);try{const Q=$.slice(1),W=((X=(await Gt.searchUsers(Q,20)).data)==null?void 0:X.data)||[];r(W)}catch(Q){console.error("Search failed:",Q),p({type:"error",text:((q=(ne=Q.response)==null?void 0:ne.data)==null?void 0:q.message)||"Failed to search users"})}finally{i(!1)}},300),[]),A=$=>{const X=$.target.value;s(X),L(X)},S=async $=>{l($),s($.email),r([]);const X=g.find(ne=>ne.email.toLowerCase()===$.email.toLowerCase()||ne.userId===$.userId);if(X&&X.role)d(X.role);else try{const q=(await Gt.getAllUsers()).find(Q=>Q.email&&Q.email.toLowerCase()===$.email.toLowerCase()||Q.userId&&Q.userId===$.userId);q&&q.role?d(q.role):d("USER")}catch(ne){console.error("Failed to check user role:",ne),d("USER")}},T=async()=>{var $,X;if(!o||!c){p({type:"error",text:"Please select a user and role"});return}u(!0),p(null);try{await Gt.assignRole(o.email,c),p({type:"success",text:`Successfully assigned ${c} role to ${o.displayName||o.email}`}),l(null),s(""),d("USER"),await D(),await H()}catch(ne){console.error("Role assignment failed:",ne),p({type:"error",text:((X=($=ne.response)==null?void 0:$.data)==null?void 0:X.error)||"Failed to assign role"})}finally{u(!1)}},D=async($=R)=>{var X,ne,q,Q,oe,W;w(!0);try{const me=await Gt.getUsersByRole(b,$,_),we=((ne=(X=me.data)==null?void 0:X.data)==null?void 0:ne.users)||[],Ee=(Q=(q=me.data)==null?void 0:q.data)==null?void 0:Q.pagination,Fe=(W=(oe=me.data)==null?void 0:oe.data)==null?void 0:W.summary;y(we),Ee&&(E(Ee.currentPage),I(Ee.totalPages),k(Ee.totalUsers)),Fe&&C({admins:Fe.ADMIN||0,management:Fe.MANAGEMENT||0,users:Fe.USER||0})}catch(me){console.error("Failed to fetch users:",me)}finally{w(!1)}},H=async()=>{var $,X,ne,q,Q,oe;try{const W=await Gt.getRoleStatistics(),me=((X=($=W.data)==null?void 0:$.data)==null?void 0:X.statistics)||((ne=W.data)==null?void 0:ne.statistics)||[];C({admins:parseInt(((q=me.find(we=>we.role==="ADMIN"))==null?void 0:q.count)||"0"),management:parseInt(((Q=me.find(we=>we.role==="MANAGEMENT"))==null?void 0:Q.count)||"0"),users:parseInt(((oe=me.find(we=>we.role==="USER"))==null?void 0:oe.count)||"0")})}catch(W){console.error("Failed to fetch statistics:",W)}};x.useEffect(()=>{D(1),H()},[b]);const z=$=>{N($),E(1)},Z=$=>{D($)},O=$=>{N($),E(1),requestAnimationFrame(()=>{const X=F.current;X&&X.scrollIntoView({behavior:"smooth",block:"start"})})};x.useEffect(()=>{const $=X=>{Y.current&&!Y.current.contains(X.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",$),()=>{document.removeEventListener("mousedown",$)}},[a]);const se=$=>{switch($){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"}},te=$=>{switch($){case"ADMIN":return e.jsx(ha,{className:"w-5 h-5 text-slate-800"});case"MANAGEMENT":return e.jsx(nt,{className:"w-5 h-5 text-slate-800"});default:return e.jsx(it,{className:"w-5 h-5 text-slate-800"})}};return e.jsxs(K,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ae,{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(Px,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(re,{className:"text-lg font-semibold text-gray-900",children:"User Role Management"}),e.jsx(ge,{className:"text-sm text-gray-600",children:"Search for users, assign roles, and manage user permissions across the system"})]})]})}),e.jsxs(G,{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(K,{className:`border-2 bg-gradient-to-br from-yellow-50 to-yellow-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${b==="ADMIN"?"border-yellow-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"admin-count-card",onClick:()=>O("ADMIN"),children:e.jsx(G,{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:b==="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(ha,{className:"w-6 h-6 text-slate-800"})})]})})}),e.jsx(K,{className:`border-2 bg-gradient-to-br from-blue-50 to-blue-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${b==="MANAGEMENT"?"border-blue-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"management-count-card",onClick:()=>O("MANAGEMENT"),children:e.jsx(G,{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:b==="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(nt,{className:"w-6 h-6 text-slate-800"})})]})})}),e.jsx(K,{className:`border-2 bg-gradient-to-br from-gray-50 to-gray-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${b==="USER"?"border-gray-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"user-count-card",onClick:()=>O("USER"),children:e.jsx(G,{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:b==="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(it,{className:"w-6 h-6 text-slate-800"})})]})})})]}),e.jsx(dt,{}),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:Y,children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Search User"}),e.jsxs("div",{className:"relative",children:[e.jsx(Xt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none"}),e.jsx(fe,{type:"text",placeholder:"Type @ to search users...",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(Ue,{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 with @ to search users (e.g., @john)"}),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($=>e.jsxs("button",{onClick:()=>S($),className:"w-full text-left p-2 hover:bg-purple-50 rounded-lg transition-colors mb-1 last:mb-0","data-testid":`user-result-${$.email}`,children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:$.displayName||$.email}),e.jsx("p",{className:"text-xs text-gray-600",children:$.email}),$.department&&e.jsxs("p",{className:"text-xs text-gray-500",children:[$.department,$.designation?` • ${$.designation}`:""]})]},$.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(Te,{value:c,onValueChange:$=>d($),children:[e.jsx(Re,{className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20","data-testid":"role-select",children:e.jsx(ke,{placeholder:"Select role"})}),e.jsxs(De,{children:[e.jsx(U,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(it,{className:"w-4 h-4 text-gray-600"}),e.jsx("span",{children:"User - Regular access"})]})}),e.jsx(U,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nt,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Management - Read all data"})]})}),e.jsx(U,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ha,{className:"w-4 h-4 text-yellow-600"}),e.jsx("span",{children:"Administrator - Full access"})]})})]})]})]}),e.jsx(M,{onClick:T,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(Ue,{className:"w-4 h-4 mr-2 animate-spin"}),"Assigning Role..."]}):e.jsxs(e.Fragment,{children:[e.jsx(It,{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(je,{className:"w-5 h-5 text-green-600 shrink-0 mt-0.5"}):e.jsx(Pe,{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(dt,{}),e.jsxs("div",{ref:F,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 (",j," ",b!=="ALL"&&b!=="ELEVATED"?b.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(Te,{value:b,onValueChange:z,children:[e.jsx(Re,{className:"w-[200px] h-10 border rounded-lg border-gray-300",children:e.jsx(ke,{placeholder:"Filter by role"})}),e.jsxs(De,{children:[e.jsx(U,{value:"ELEVATED",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(It,{className:"w-4 h-4 text-purple-600"}),e.jsxs("span",{children:["Elevated (",f.admins+f.management,")"]})]})}),e.jsx(U,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ha,{className:"w-4 h-4 text-yellow-600"}),e.jsxs("span",{children:["Admins (",f.admins,")"]})]})}),e.jsx(U,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nt,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Management (",f.management,")"]})]})}),e.jsx(U,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(it,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["Users (",f.users,")"]})]})}),e.jsx(U,{value:"ALL",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nt,{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(Ue,{className:"w-6 h-6 animate-spin text-purple-500 mb-2"}),e.jsx("p",{className:"text-sm text-gray-500",children:"Loading users..."})]}):g.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(nt,{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:b==="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:g.map($=>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-${$.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 ${se($.role)} flex items-center justify-center shadow-sm`,children:te($.role)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-semibold text-gray-900 truncate",children:$.displayName}),e.jsx("p",{className:"text-sm text-gray-600 truncate",children:$.email}),$.department&&e.jsxs("p",{className:"text-xs text-gray-500 mt-1 truncate",children:[$.department,$.designation?` • ${$.designation}`:""]})]})]}),e.jsx(ee,{className:`${se($.role)} shrink-0`,"data-testid":`role-badge-${$.role}`,children:$.role})]})},$.userId))}),P>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)*_+1," to ",Math.min(R*_,j)," of ",j," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(M,{variant:"outline",size:"sm",onClick:()=>Z(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,P)},($,X)=>{let ne;return P<=5||R<=3?ne=X+1:R>=P-2?ne=P-4+X:ne=R-2+X,e.jsx(M,{variant:R===ne?"default":"outline",size:"sm",onClick:()=>Z(ne),className:`w-9 h-9 p-0 ${R===ne?"bg-re-green hover:bg-re-green/90 text-white":""}`,"data-testid":`page-${ne}-button`,children:ne},ne)})}),e.jsx(M,{variant:"outline",size:"sm",onClick:()=>Z(R+1),disabled:R===P,"data-testid":"next-page-button",children:"Next"})]})]})]})})]})]})]})}function AS({open:t,onClose:s,success:a,message:r}){return e.jsx(et,{open:t,onOpenChange:s,children:e.jsxs(Xe,{className:"sm:max-w-md",children:[e.jsxs(tt,{children:[e.jsxs(Ze,{className:"flex items-center gap-2",children:[e.jsx(Ft,{className:"w-5 h-5 text-blue-600"}),"Push Notifications"]}),e.jsx(qt,{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(je,{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(Je,{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(wt,{children:e.jsx(M,{onClick:s,className:"w-full",children:a?"Done":"Close"})})]})})}const TS=async()=>(await de.get("/user/preferences/notifications")).data.data,kS=async t=>(await de.put("/user/preferences/notifications",t)).data.data;function RS({open:t,onClose:s}){const[a,r]=x.useState({emailNotificationsEnabled:!0,pushNotificationsEnabled:!0,inAppNotificationsEnabled:!0}),[n,i]=x.useState(!0),[o,l]=x.useState(null),[c,d]=x.useState(null),[m,u]=x.useState(null);x.useEffect(()=>{t&&h()},[t]);const h=async()=>{var g,y;try{i(!0),u(null);const v=await TS();r(v)}catch(v){console.error("[NotificationPreferences] Failed to load preferences:",v),u(((y=(g=v.response)==null?void 0:g.data)==null?void 0:y.message)||"Failed to load notification preferences")}finally{i(!1)}},p=async(g,y)=>{var v,w;try{l(g),u(null),d(null);const f={[g]:y},C=await kS(f);r(C),d(`${g==="emailNotificationsEnabled"?"Email":g==="pushNotificationsEnabled"?"Push":"In-App"} notifications ${y?"enabled":"disabled"}`),setTimeout(()=>d(null),3e3)}catch(f){console.error("[NotificationPreferences] Failed to update preference:",f),u(((w=(v=f.response)==null?void 0:v.data)==null?void 0:w.message)||"Failed to update notification preference"),h()}finally{l(null)}};return e.jsx(et,{open:t,onOpenChange:s,children:e.jsxs(Xe,{className:"sm:max-w-[600px] max-h-[85vh] overflow-y-auto",children:[e.jsx(tt,{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",children:e.jsx(Ls,{className:"h-6 w-6 text-white"})}),e.jsxs("div",{children:[e.jsx(Ze,{className:"text-xl font-semibold",children:"Notification Preferences"}),e.jsx(qt,{className:"text-sm",children:"Customize how you receive notifications for workflow updates"})]})]})}),e.jsx(dt,{className:"my-4"}),n?e.jsx("div",{className:"p-12 flex items-center justify-center",children:e.jsx(Ue,{className:"w-8 h-8 animate-spin text-gray-400"})}):e.jsxs("div",{className:"space-y-6",children:[c&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-green-50 border border-green-200 rounded-md animate-in fade-in slide-in-from-top-2",children:[e.jsx(je,{className:"w-4 h-4 text-green-600 shrink-0"}),e.jsx("p",{className:"text-sm text-green-800 font-medium",children:c})]}),m&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-red-50 border border-red-200 rounded-md animate-in fade-in slide-in-from-top-2",children:[e.jsx(Pe,{className:"w-4 h-4 text-red-600 shrink-0"}),e.jsx("p",{className:"text-sm text-red-800 font-medium",children:m})]}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-lg border border-gray-200 hover:border-gray-300 transition-all",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 bg-white rounded-lg shadow-sm",children:e.jsx(Oi,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"email-notifications-modal",className:"text-base font-semibold text-gray-900 cursor-pointer",children:"Email Notifications"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"Receive important updates and alerts via email"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[o==="emailNotificationsEnabled"&&e.jsx(Ue,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(Lt,{id:"email-notifications-modal",checked:a.emailNotificationsEnabled,onCheckedChange:g=>p("emailNotificationsEnabled",g),disabled:o==="emailNotificationsEnabled"})]})]})}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-lg border border-gray-200 hover:border-gray-300 transition-all",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 bg-white rounded-lg shadow-sm",children:e.jsx(Ft,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"push-notifications-modal",className:"text-base font-semibold text-gray-900 cursor-pointer",children:"Push Notifications"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"Get instant browser notifications for real-time updates"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[o==="pushNotificationsEnabled"&&e.jsx(Ue,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(Lt,{id:"push-notifications-modal",checked:a.pushNotificationsEnabled,onCheckedChange:g=>p("pushNotificationsEnabled",g),disabled:o==="pushNotificationsEnabled"})]})]})}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-lg border border-gray-200 hover:border-gray-300 transition-all",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 bg-white rounded-lg shadow-sm",children:e.jsx(vs,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"inapp-notifications-modal",className:"text-base font-semibold text-gray-900 cursor-pointer",children:"In-App Notifications"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"View notifications in the notification center"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[o==="inAppNotificationsEnabled"&&e.jsx(Ue,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(Lt,{id:"inapp-notifications-modal",checked:a.inAppNotificationsEnabled,onCheckedChange:g=>p("inAppNotificationsEnabled",g),disabled:o==="inAppNotificationsEnabled"})]})]})}),e.jsx(dt,{}),e.jsx("div",{className:"p-4 bg-gray-50 border border-gray-200 rounded-lg",children:e.jsxs("p",{className:"text-sm text-gray-700 leading-relaxed",children:[e.jsx("span",{className:"font-semibold",children:"Note:"})," These settings control your notification preferences across all channels. Critical system alerts and urgent notifications may still be delivered regardless of these settings to ensure important information reaches you."]})})]})]})})}function DS(){const{user:t}=Mt(),s=Zs(t),[a,r]=x.useState(!1),[n,i]=x.useState(!1),[o,l]=x.useState(),[c,d]=x.useState(!1),[m,u]=x.useState(!1),[h,p]=x.useState(!1),[g,y]=x.useState(!0);x.useEffect(()=>{v()},[]);const v=async()=>{try{y(!0);const f=await yf();p(f.length>0)}catch(f){console.error("Failed to check subscription status:",f),p(!1)}finally{y(!1)}},w=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 f=Notification.permission;if(f==="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(f==="default"&&(f=await Notification.requestPermission(),f==="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(f!=="granted"){i(!1),l("Notification permission is required to enable push notifications. Please grant permission and try again."),r(!0),d(!1);return}await jS(),i(!0),l("Push notifications have been successfully enabled! You will now receive notifications for workflow updates, approvals, and TAT alerts."),r(!0),await v()}catch(f){console.error("[Settings] Error enabling notifications:",f),i(!1);const C=(f==null?void 0:f.message)||"Unknown error occurred";l(C.includes("permission")?"Notification permission was denied. Please enable notifications in your browser settings and try again.":C.includes("Service worker")?"Service worker registration failed. Please refresh the page and try again.":C.includes("token")?"Authentication required. Please log in again and try enabling notifications.":`Unable to enable push notifications: ${C}`),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(K,{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(G,{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(Ls,{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(Jr,{defaultValue:"user",className:"w-full",children:[e.jsxs(en,{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(xt,{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(Ls,{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(xt,{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(It,{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(xt,{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(Cd,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Configuration"}),e.jsx("span",{className:"sm:hidden",children:"Config"})]}),e.jsxs(xt,{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(We,{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(gt,{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(K,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ae,{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(Ft,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(re,{className:"text-lg font-semibold text-gray-900",children:"Browser Push Setup"}),e.jsx(ge,{className:"text-sm text-gray-600",children:"Register this browser for push notifications"})]})]})}),e.jsx(G,{children:e.jsxs("div",{className:"space-y-4",children:[g?e.jsx("div",{className:"p-4 bg-gray-50 border border-gray-200 rounded-md flex items-center justify-center",children:e.jsx("p",{className:"text-sm text-gray-600",children:"Checking registration status..."})}):h?e.jsx("div",{className:"p-3 bg-green-50 border border-green-200 rounded-md",children:e.jsx("p",{className:"text-xs text-green-800 font-medium",children:"✓ This browser is already registered for push notifications."})}):e.jsx("div",{className:"p-3 bg-blue-50 border border-blue-200 rounded-md",children:e.jsx("p",{className:"text-xs text-blue-800",children:"Click below to register this browser for receiving push notifications. This needs to be done once per browser/device."})}),e.jsxs(M,{onClick:w,disabled:c||h,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(Ft,{className:`w-4 h-4 mr-2 ${c?"animate-pulse":""}`}),c?"Registering...":h?"Already Registered":"Register Browser for Push"]})]})})]}),e.jsxs(K,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ae,{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(Ka,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(re,{className:"text-lg font-semibold text-gray-900",children:"Security"}),e.jsx(ge,{className:"text-sm text-gray-600",children:"Password and security settings"})]})]})}),e.jsx(G,{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(K,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ae,{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(Zo,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(re,{className:"text-lg font-semibold text-gray-900",children:"Appearance"}),e.jsx(ge,{className:"text-sm text-gray-600",children:"Theme and display preferences"})]})]})}),e.jsx(G,{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(K,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ae,{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(It,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(re,{className:"text-lg font-semibold text-gray-900",children:"Preferences"}),e.jsx(ge,{className:"text-sm text-gray-600",children:"Notification and application preferences"})]})]})}),e.jsx(G,{children:e.jsxs(M,{onClick:()=>u(!0),className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all",children:[e.jsx(It,{className:"w-4 h-4 mr-2"}),"Manage Preferences"]})})]})]})}),e.jsx(gt,{value:"roles",className:"mt-0",children:e.jsx(SS,{})}),e.jsx(gt,{value:"system",className:"mt-0",children:e.jsx(NS,{})}),e.jsx(gt,{value:"holidays",className:"mt-0",children:e.jsx(wS,{})})]})]}):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(K,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ae,{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(Ft,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(re,{className:"text-lg font-semibold text-gray-900",children:"Browser Push Setup"}),e.jsx(ge,{className:"text-sm text-gray-600",children:"Register this browser for push notifications"})]})]})}),e.jsx(G,{children:e.jsxs("div",{className:"space-y-4",children:[g?e.jsx("div",{className:"p-4 bg-gray-50 border border-gray-200 rounded-md flex items-center justify-center",children:e.jsx("p",{className:"text-sm text-gray-600",children:"Checking registration status..."})}):h?e.jsx("div",{className:"p-3 bg-green-50 border border-green-200 rounded-md",children:e.jsx("p",{className:"text-xs text-green-800 font-medium",children:"✓ This browser is already registered for push notifications."})}):e.jsx("div",{className:"p-3 bg-blue-50 border border-blue-200 rounded-md",children:e.jsx("p",{className:"text-xs text-blue-800",children:"Click below to register this browser for receiving push notifications. This needs to be done once per browser/device."})}),e.jsxs(M,{onClick:w,disabled:c||h,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(Ft,{className:`w-4 h-4 mr-2 ${c?"animate-pulse":""}`}),c?"Registering...":h?"Already Registered":"Register Browser for Push"]})]})})]}),e.jsxs(K,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ae,{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(Ka,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(re,{className:"text-lg font-semibold text-gray-900",children:"Security"}),e.jsx(ge,{className:"text-sm text-gray-600",children:"Password and security settings"})]})]})}),e.jsx(G,{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(K,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ae,{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(Zo,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(re,{className:"text-lg font-semibold text-gray-900",children:"Appearance"}),e.jsx(ge,{className:"text-sm text-gray-600",children:"Theme and display preferences"})]})]})}),e.jsx(G,{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(K,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ae,{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(It,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(re,{className:"text-lg font-semibold text-gray-900",children:"Preferences"}),e.jsx(ge,{className:"text-sm text-gray-600",children:"Notification and application preferences"})]})]})}),e.jsx(G,{children:e.jsxs(M,{onClick:()=>u(!0),className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all",children:[e.jsx(It,{className:"w-4 h-4 mr-2"}),"Manage Preferences"]})})]})]})})]}),e.jsx(AS,{open:a,onClose:()=>r(!1),success:n,message:o}),e.jsx(RS,{open:m,onClose:()=>u(!1)})]})}function PS({onNavigate:t}){const[s,a]=x.useState([]),[r,n]=x.useState(!0),[i,o]=x.useState(1),[l,c]=x.useState(1),[d,m]=x.useState(0),[u,h]=x.useState("all"),[p,g]=x.useState(!1),y=20,v=async(I=i,j=u==="unread")=>{var k,_;try{n(I===1);const Y=await Is.list({page:I,limit:y,unreadOnly:j}),F=((k=Y.data)==null?void 0:k.notifications)||[],L=((_=Y.data)==null?void 0:_.total)||0;a(F),m(L),c(Math.ceil(L/y))}catch(Y){console.error("[Notifications] Failed to fetch:",Y)}finally{n(!1),g(!1)}};x.useEffect(()=>{v(1,u==="unread")},[u]);const w=async I=>{var j;try{if(I.isRead||(await Is.markAsRead(I.notificationId),a(k=>k.map(_=>_.notificationId===I.notificationId?{..._,isRead:!0}:_))),I.actionUrl&&t){const k=(j=I.metadata)==null?void 0:j.requestNumber;if(k){let _=`request/${k}`;(I.notificationType==="mention"||I.notificationType==="comment"||I.notificationType==="worknote")&&(_+="?tab=worknotes"),t(_)}}}catch(k){console.error("[Notifications] Error handling notification click:",k)}},f=async()=>{try{g(!0),await Is.markAllAsRead(),await v(i,u==="unread")}catch(I){console.error("[Notifications] Error marking all as read:",I),g(!1)}},C=async I=>{try{await Is.delete(I),a(j=>j.filter(k=>k.notificationId!==I)),m(j=>j-1)}catch(j){console.error("[Notifications] Error deleting notification:",j)}},b=()=>{g(!0),v(i,u==="unread")},N=I=>{I<1||I>l||(o(I),v(I,u==="unread"))},R=I=>{const j="w-6 h-6";switch(I){case"mention":case"comment":return e.jsx(vs,{className:`${j} text-blue-600`});case"worknote":return e.jsx(Ae,{className:`${j} text-purple-600`});case"assignment":return e.jsx(Wr,{className:`${j} text-indigo-600`});case"approval":return e.jsx(je,{className:`${j} text-green-600`});case"rejection":return e.jsx(Je,{className:`${j} text-red-600`});case"tat_alert":return e.jsx(Ie,{className:`${j} text-orange-600`});case"tat_breach":return e.jsx(Pe,{className:`${j} text-red-600`});case"tat_breach_initiator":return e.jsx(is,{className:`${j} text-amber-600`});default:return e.jsx(Ft,{className:`${j} text-gray-600`})}},E=I=>{switch(I==null?void 0:I.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"}},P=s.filter(I=>!I.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(Ft,{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":"",P>0&&` • ${P} unread`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(M,{variant:"outline",size:"sm",onClick:b,disabled:p,className:"gap-2",children:[e.jsx(Et,{className:`w-4 h-4 ${p?"animate-spin":""}`}),"Refresh"]}),P>0&&e.jsxs(M,{variant:"outline",size:"sm",onClick:f,disabled:p,className:"gap-2",children:[e.jsx(Ex,{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",P>0&&e.jsx(ee,{className:"ml-2 bg-red-500 text-white",children:P})]})]}),e.jsxs(K,{children:[e.jsxs(ae,{children:[e.jsx(re,{children:"Recent Activity"}),e.jsx(ge,{children:"Stay updated with all your workflow activities and mentions"})]}),e.jsx(G,{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(Ft,{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(I=>{var j;return e.jsx("div",{className:`p-4 rounded-lg border transition-all cursor-pointer hover:shadow-md ${I.isRead?"bg-white border-gray-200 hover:bg-gray-50":"bg-blue-50 border-blue-200 hover:bg-blue-100"}`,onClick:()=>w(I),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"shrink-0 mt-0.5",children:R(I.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 ${I.isRead?"font-semibold":"font-bold"} text-gray-900`,children:I.title}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[I.priority&&I.priority!=="LOW"&&e.jsx(ee,{variant:"outline",className:`text-xs ${E(I.priority)}`,children:I.priority}),!I.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:I.message}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:[ld(new Date(I.createdAt),{addSuffix:!0}),((j=I.metadata)==null?void 0:j.requestNumber)&&e.jsxs("span",{className:"ml-2",children:["• ",I.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:k=>{k.stopPropagation(),C(I.notificationId)},children:e.jsx(Vi,{className:"w-3.5 h-3.5"})})]})]})]})},I.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:()=>N(i-1),disabled:i===1,children:[e.jsx(Nd,{className:"w-4 h-4"}),"Previous"]}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,l)},(I,j)=>{let k;return l<=5||i<=3?k=j+1:i>=l-2?k=l-4+j:k=i-2+j,e.jsx(M,{variant:i===k?"default":"outline",size:"sm",className:"w-9 h-9 p-0",onClick:()=>N(k),children:k},k)})}),e.jsxs(M,{variant:"outline",size:"sm",onClick:()=>N(i+1),disabled:i===l,children:["Next",e.jsx(Ui,{className:"w-4 h-4"})]})]})]})]})}function ES({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(xs,{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(Ae,{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 Oo({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 p=s&&a?`${xe(s,"MMM d, yyyy")} - ${xe(a,"MMM d, yyyy")}`:"Select dates";return e.jsxs("div",{className:"flex items-center gap-2","data-testid":`${h}-container`,children:[e.jsx(We,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Te,{value:t,onValueChange:o,"data-testid":`${h}-select`,children:[e.jsx(Re,{className:"w-[160px]",children:e.jsx(ke,{placeholder:"Date Range"})}),e.jsxs(De,{children:[e.jsx(U,{value:"today",children:"Today"}),e.jsx(U,{value:"week",children:"This Week"}),e.jsx(U,{value:"month",children:"This Month"}),e.jsx(U,{value:"custom",children:"Custom Range"})]})]}),t==="custom"&&e.jsxs(cs,{open:r,onOpenChange:l,children:[e.jsx(ds,{asChild:!0,children:e.jsxs(M,{variant:"outline",size:"sm",className:"gap-2","data-testid":`${h}-custom-trigger`,children:[e.jsx(We,{className:"w-4 h-4"}),p]})}),e.jsx(ms,{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(J,{htmlFor:`${h}-start-date`,className:"text-sm font-medium",children:"Start Date"}),e.jsx(fe,{id:`${h}-start-date`,type:"date",value:n?xe(n,"yyyy-MM-dd"):"",onChange:g=>{const y=g.target.value?new Date(g.target.value):void 0;c(y)},max:xe(new Date,"yyyy-MM-dd"),className:"w-full","data-testid":`${h}-start-input`})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:`${h}-end-date`,className:"text-sm font-medium",children:"End Date"}),e.jsx(fe,{id:`${h}-end-date`,type:"date",value:i?xe(i,"yyyy-MM-dd"):"",onChange:g=>{const y=g.target.value?new Date(g.target.value):void 0;d(y)},min:n?xe(n,"yyyy-MM-dd"):void 0,max:xe(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 MS(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 yh(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 vh(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 IS(t){return t>=20?"bg-red-600":t>=10?"bg-orange-500":"bg-amber-500"}function FS({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:p,onStartDateChange:g,onEndDateChange:y,onApplyCustomDate:v,onCancelCustomDate:w,onPageChange:f,onExport:C,onViewRequest:b}){return e.jsxs(K,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"request-lifecycle-report",children:[e.jsxs(ae,{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(re,{className:"text-lg text-gray-900",children:"Request Lifecycle Report"}),e.jsx(ge,{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:C,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(Oo,{dateRange:i,customStartDate:o,customEndDate:l,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,onDateRangeChange:h,onShowCustomDatePickerChange:p,onStartDateChange:g,onEndDateChange:y,onApply:v,onCancel:w,testIdPrefix:"lifecycle"})})]}),e.jsxs(G,{children:[s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"lifecycle-loading",children:[e.jsx(Ue,{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(Pe,{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(N=>e.jsx("div",{className:"border rounded-xl overflow-hidden","data-testid":`lifecycle-request-${N.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:()=>b(N.requestId||N.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(),b(N.requestId||N.id)},className:"font-semibold text-sm text-blue-600 hover:text-blue-800 hover:underline cursor-pointer transition-colors","data-testid":`lifecycle-request-link-${N.id}`,children:N.id}),e.jsx(ee,{className:yh(N.priority),"data-testid":`lifecycle-priority-${N.id}`,children:N.priority}),e.jsx(ee,{className:vh(N.status),"data-testid":`lifecycle-status-${N.id}`,children:N.status})]}),e.jsx("p",{className:"text-sm text-gray-700",children:N.title}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["Initiated by ",e.jsx("span",{className:"font-medium",children:N.initiator})," on ",N.initDate]}),N.currentStage&&!N.currentStage.includes("Level")&&e.jsxs("p",{className:"text-xs text-gray-400 mt-0.5",children:["Stage: ",N.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:N.currentStage}),e.jsxs("p",{className:"text-xs text-gray-400 mt-0.5",children:["(Level ",N.currentLevel,"/",N.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:N.overallTAT}),N.breachCount>0&&e.jsxs("p",{className:"text-xs text-red-500 mt-0.5",children:[N.breachCount," breach",N.breachCount>1?"es":""]})]}),e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>b(N.requestId||N.id),className:"gap-1.5","data-testid":`lifecycle-view-button-${N.id}`,children:e.jsx(Ui,{className:"w-4 h-4"})})]})]})})},N.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(Ue,{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:ce("w-full caption-bottom text-sm",t),...s})})}function Uo({className:t,...s}){return e.jsx("thead",{"data-slot":"table-header",className:ce("[&_tr]:border-b",t),...s})}function Bo({className:t,...s}){return e.jsx("tbody",{"data-slot":"table-body",className:ce("[&_tr:last-child]:border-0",t),...s})}function ca({className:t,...s}){return e.jsx("tr",{"data-slot":"table-row",className:ce("hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",t),...s})}function ft({className:t,...s}){return e.jsx("th",{"data-slot":"table-head",className:ce("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 ut({className:t,...s}){return e.jsx("td",{"data-slot":"table-cell",className:ce("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",t),...s})}function _S({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:p,onDateRangeChange:g,onShowCustomDatePickerChange:y,onStartDateChange:v,onEndDateChange:w,onApplyCustomDate:f,onCancelCustomDate:C,onCategoryChange:b,onSeverityChange:N,onClearFilters:R,onPageChange:E,onExport:P,onViewRequest:I}){const j=u!=="all"||h!=="all"||i!=="month"||o||l;return e.jsxs(K,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"user-activity-log-report",children:[e.jsxs(ae,{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(Mx,{className:"h-5 w-5 text-indigo-600"})}),e.jsxs("div",{children:[e.jsx(re,{className:"text-lg text-gray-900",children:"User Activity Log Report"}),e.jsx(ge,{className:"text-gray-600",children:"Consolidated user actions and activity history"})]})]}),e.jsxs(M,{variant:"outline",size:"sm",className:"gap-2",onClick:P,disabled:p,"data-testid":"export-activity-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(Oo,{dateRange:i,customStartDate:o,customEndDate:l,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,onDateRangeChange:g,onShowCustomDatePickerChange:y,onStartDateChange:v,onEndDateChange:w,onApply:f,onCancel:C,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(Te,{value:u,onValueChange:b,"data-testid":"activity-category-filter",children:[e.jsx(Re,{className:"w-40",children:e.jsx(ke,{placeholder:"All Categories"})}),e.jsxs(De,{children:[e.jsx(U,{value:"all",children:"All Categories"}),e.jsx(U,{value:"WORKFLOW",children:"Workflow"}),e.jsx(U,{value:"COLLABORATION",children:"Collaboration"}),e.jsx(U,{value:"DOCUMENT",children:"Document"}),e.jsx(U,{value:"AUTHENTICATION",children:"Authentication"}),e.jsx(U,{value:"SYSTEM",children:"System"}),e.jsx(U,{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(Te,{value:h,onValueChange:N,"data-testid":"activity-severity-filter",children:[e.jsx(Re,{className:"w-40",children:e.jsx(ke,{placeholder:"All Severities"})}),e.jsxs(De,{children:[e.jsx(U,{value:"all",children:"All Severities"}),e.jsx(U,{value:"INFO",children:"Info"}),e.jsx(U,{value:"WARNING",children:"Warning"}),e.jsx(U,{value:"ERROR",children:"Error"}),e.jsx(U,{value:"CRITICAL",children:"Critical"})]})]})]}),j&&e.jsx(M,{variant:"ghost",size:"sm",onClick:R,className:"text-xs","data-testid":"activity-clear-filters",children:"Clear Filters"})]})]}),e.jsx(G,{children:s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"activity-loading",children:[e.jsx(Ue,{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(Pe,{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(Uo,{children:e.jsxs(ca,{className:"bg-gray-50",children:[e.jsx(ft,{className:"font-semibold",children:"Timestamp"}),e.jsx(ft,{className:"font-semibold",children:"User"}),e.jsx(ft,{className:"font-semibold",children:"Action"}),e.jsx(ft,{className:"font-semibold",children:"Details"}),e.jsx(ft,{className:"font-semibold",children:"IP Address"}),e.jsx(ft,{className:"font-semibold",children:"Request ID"})]})}),e.jsx(Bo,{children:t.map((k,_)=>e.jsxs(ca,{className:"hover:bg-gray-50","data-testid":`activity-row-${_}`,children:[e.jsx(ut,{className:"text-xs font-medium",children:k.timestamp}),e.jsx(ut,{className:"text-sm",children:k.user}),e.jsx(ut,{children:e.jsx(ee,{className:MS(k.action),"data-testid":`activity-action-${_}`,children:k.action})}),e.jsx(ut,{className:"text-sm text-gray-600",children:k.details}),e.jsx(ut,{className:"text-xs font-mono text-gray-500",children:k.ip&&k.ip!=="N/A"?e.jsx("span",{title:k.userAgent||"",children:k.ip}):e.jsx("span",{className:"text-gray-400 italic",title:"IP address not yet captured",children:"N/A"})}),e.jsx(ut,{children:k.requestId!=="-"&&k.requestId!=="System Login"?e.jsx("button",{onClick:()=>{const Y=k.requestId;Y&&I(Y)},className:"hover:underline","data-testid":`activity-request-link-${_}`,children:e.jsx(ee,{variant:"outline",className:"text-xs cursor-pointer hover:bg-blue-50 hover:border-blue-300 transition-colors",children:k.requestId})}):e.jsx("span",{className:"text-xs text-gray-400",children:"-"})})]},_))})]}),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(Ue,{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:()=>E(n.page-1),disabled:n.page<=1||a,"data-testid":"activity-pagination-prev",children:"Previous"}),e.jsx(M,{variant:"outline",size:"sm",onClick:()=>E(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"activity-pagination-next",children:"Next"})]})]})]})})]})}function LS({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:p,exporting:g,onThresholdChange:y,onThresholdBlur:v,onDateRangeChange:w,onShowCustomDatePickerChange:f,onStartDateChange:C,onEndDateChange:b,onApplyCustomDate:N,onCancelCustomDate:R,onSearchChange:E,onPageChange:P,onExport:I,onViewRequest:j}){return e.jsxs(K,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"workflow-aging-report",children:[e.jsxs(ae,{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(Bi,{className:"h-5 w-5 text-amber-600"})}),e.jsxs("div",{children:[e.jsx(re,{className:"text-lg text-gray-900",children:"Workflow Aging Report"}),e.jsx(ge,{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(fe,{type:"number",min:"1",value:i,onChange:k=>y(k.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(ee,{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:I,disabled:g,"data-testid":"export-aging-button",children:[e.jsx(ns,{className:"w-4 h-4"}),g?"Exporting...":"Download CSV"]})]})]}),e.jsxs("div",{className:"mt-4 flex items-center gap-4 flex-wrap",children:[e.jsx(Oo,{dateRange:l,customStartDate:c,customEndDate:d,showCustomDatePicker:m,tempCustomStartDate:u,tempCustomEndDate:h,onDateRangeChange:w,onShowCustomDatePickerChange:f,onStartDateChange:C,onEndDateChange:b,onApply:N,onCancel:R,testIdPrefix:"aging"}),e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(Xt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(fe,{placeholder:"Search by Request ID, Title, or Initiator...",value:p,onChange:k=>E(k.target.value),className:"pl-10","data-testid":"aging-search-input"})]})]})]}),e.jsx(G,{children:s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"aging-loading",children:[e.jsx(Ue,{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(Pe,{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(Uo,{children:e.jsxs(ca,{className:"bg-gray-50",children:[e.jsx(ft,{className:"font-semibold",children:"Request ID"}),e.jsx(ft,{className:"font-semibold",children:"Title"}),e.jsx(ft,{className:"font-semibold",children:"Initiator"}),e.jsx(ft,{className:"font-semibold",children:"Start Date"}),e.jsx(ft,{className:"font-semibold",children:"Days Open"}),e.jsx(ft,{className:"font-semibold",children:"Current Stage"}),e.jsx(ft,{className:"font-semibold",children:"Assigned To"}),e.jsx(ft,{className:"font-semibold",children:"Priority"}),e.jsx(ft,{className:"font-semibold",children:"Status"})]})}),e.jsx(Bo,{children:t.map(k=>e.jsxs(ca,{className:"hover:bg-gray-50","data-testid":`aging-workflow-${k.id}`,children:[e.jsx(ut,{className:"font-medium text-sm",children:e.jsx("button",{onClick:()=>j(k.requestId||k.id),className:"text-blue-600 hover:text-blue-800 hover:underline cursor-pointer transition-colors","data-testid":`aging-request-link-${k.id}`,children:k.id})}),e.jsx(ut,{className:"text-sm",children:k.title}),e.jsx(ut,{className:"text-sm",children:k.initiator}),e.jsx(ut,{className:"text-sm text-gray-600",children:k.startDate}),e.jsx(ut,{children:e.jsxs(ee,{className:`${IS(k.daysOpen)} text-white border-transparent`,"data-testid":`aging-days-${k.id}`,children:[k.daysOpen," days",e.jsx("span",{className:"ml-1 text-xs opacity-75",children:"(business)"})]})}),e.jsx(ut,{className:"text-sm",children:k.currentStage}),e.jsx(ut,{className:"text-sm",children:k.assignedTo&&k.assignedTo!=="N/A"?k.assignedTo:e.jsx("span",{className:"text-gray-400 italic",title:"Assigned approver not available",children:"N/A"})}),e.jsx(ut,{children:e.jsx(ee,{className:yh(k.priority),"data-testid":`aging-priority-${k.id}`,children:k.priority})}),e.jsx(ut,{children:e.jsx(ee,{className:vh(k.status),"data-testid":`aging-status-${k.id}`,children:k.status})})]},k.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(Ue,{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:()=>P(n.page-1),disabled:n.page<=1||a,"data-testid":"aging-pagination-prev",children:"Previous"}),e.jsx(M,{variant:"outline",size:"sm",onClick:()=>P(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"aging-pagination-next",children:"Next"})]})]})]})})]})}function Qn(t="month"){const[s,a]=x.useState(t),[r,n]=x.useState(void 0),[i,o]=x.useState(void 0),[l,c]=x.useState(!1),[d,m]=x.useState(void 0),[u,h]=x.useState(void 0),p=x.useCallback(b=>{const N=b;a(N),N!=="custom"?(n(void 0),o(void 0),m(void 0),h(void 0),c(!1)):(m(r),h(i),c(!0))},[r,i]),g=x.useCallback(()=>{if(d&&u){if(d>u){const b=d;n(u),o(b),m(u),h(b)}else n(d),o(u);c(!1)}},[d,u]),y=x.useCallback(()=>{c(!1),m(r),h(i),(!r||!i)&&(n(void 0),o(void 0),a("month"))},[r,i]),v=x.useCallback(b=>{b?(m(b),u&&b>u&&h(b)):m(void 0)},[u]),w=x.useCallback(b=>{b?(h(b),d&&b<d&&m(b)):h(void 0)},[d]),f=x.useCallback(()=>r&&i?`${xe(r,"MMM d, yyyy")} - ${xe(i,"MMM d, yyyy")}`:"Select dates",[r,i]),C=x.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:p,handleApplyCustomDate:g,handleCancelCustomDate:y,handleStartDateChange:v,handleEndDateChange:w,getDisplayDateRange:f,reset:C}}function OS(t){if(!t&&t!==0)return"N/A";const s=8;if(t<s)return ot(t);const a=Math.floor(t/s),r=t%s;return r>0?`${a}d ${ot(r)}`:`${a}d`}function bh(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 ea(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 jh(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 $S=10;function US({dateRange:t,customStartDate:s,customEndDate:a}){const[r,n]=x.useState([]),[i,o]=x.useState(!0),[l,c]=x.useState(!1),[d,m]=x.useState(null),[u,h]=x.useState({page:1,totalPages:1,totalRecords:0}),p=x.useRef(!0),g=x.useCallback(async(y=1)=>{const v=y===1&&p.current;try{v?o(!0):c(!0),m(null);const w=await He.getLifecycleReport(y,$S,t,s,a),f=w.lifecycleData.map(C=>{const b=OS(C.overallTATHours);return{id:C.requestNumber,requestId:C.requestId,title:C.title,priority:C.priority||"medium",status:C.status,initiator:C.initiatorName||"Unknown",initDate:bh(C.submissionDate),currentStage:C.currentStageName||`Level ${C.currentLevel}`,overallTAT:b,currentLevel:C.currentLevel,totalLevels:C.totalLevels,breachCount:C.breachCount||0}});n(f),h({page:w.pagination.currentPage,totalPages:w.pagination.totalPages,totalRecords:w.pagination.totalRecords})}catch(w){console.error("Failed to fetch lifecycle data:",w),m((w==null?void 0:w.message)||"Failed to load lifecycle data")}finally{v?o(!1):c(!1)}v&&(p.current=!1)},[t,s,a]);return x.useEffect(()=>{t==="custom"&&(!s||!a)||g(1)},[t,s,a]),{lifecycleRequests:r,loading:i,loadingPage:l,error:d,pagination:u,fetchData:g}}const BS=20;function VS({dateRange:t,customStartDate:s,customEndDate:a,filterCategory:r,filterSeverity:n}){const[i,o]=x.useState([]),[l,c]=x.useState(!0),[d,m]=x.useState(!1),[u,h]=x.useState(null),[p,g]=x.useState({page:1,totalPages:1,totalRecords:0}),y=x.useRef(!0),v=x.useCallback(async(w=1)=>{const f=w===1&&y.current;try{f?c(!0):m(!0),h(null);const C=await He.getActivityLogReport(w,BS,t,void 0,void 0,r&&r!=="all"?r:void 0,n&&n!=="all"?n:void 0,s,a),b=C.activities.map(N=>{const R=jh(N.type||"",N.details),E=(N.type||"").toLowerCase()==="login"||N.requestId==="00000000-0000-0000-0000-000000000001"||N.requestId==="SYSTEM_LOGIN",P=E?N.details||"User login":N.requestTitle||N.requestNumber||N.details||"N/A";return{timestamp:N.timestamp?bh(N.timestamp):"N/A",user:N.userName||"Unknown",action:R,details:P,ip:N.ipAddress||"N/A",userAgent:N.userAgent||null,requestId:E?"System Login":N.requestNumber||N.requestId||"-",userId:N.userId}});o(b),g({page:C.pagination.currentPage,totalPages:C.pagination.totalPages,totalRecords:C.pagination.totalRecords})}catch(C){console.error("Failed to fetch activity data:",C),h((C==null?void 0:C.message)||"Failed to load activity data")}finally{f?c(!1):m(!1)}f&&(y.current=!1)},[r,n,t,s,a]);return x.useEffect(()=>{t==="custom"&&(!s||!a)||v(1)},[r,n,t,s,a]),{activityLog:i,loading:l,loadingPage:d,error:u,pagination:p,fetchData:v}}const zS=20;function HS({threshold:t,dateRange:s,customStartDate:a,customEndDate:r,searchQuery:n=""}){const[i,o]=x.useState([]),[l,c]=x.useState(!0),[d,m]=x.useState(!1),[u,h]=x.useState(null),[p,g]=x.useState({page:1,totalPages:1,totalRecords:0}),y=x.useRef(!0),v=x.useCallback(async(f=1)=>{const C=f===1&&y.current;try{C?c(!0):m(!0),h(null);const b=parseInt(t,10);if(isNaN(b)||b<1){h("Please enter a valid threshold (minimum 1 day)");return}const N=await He.getWorkflowAgingReport(b,f,zS,s,a,r),R=N.agingData.map(E=>({id:E.requestNumber||E.requestId,requestId:E.requestId,title:E.title,initiator:E.initiatorName||"Unknown",startDate:E.submissionDate?new Date(E.submissionDate).toLocaleDateString():"N/A",daysOpen:E.daysOpen,currentStage:E.currentStageName||`Level ${E.currentLevel}`,assignedTo:E.currentApproverName||"N/A",priority:E.priority||"medium",status:E.status||"pending"}));o(R),g({page:N.pagination.currentPage,totalPages:N.pagination.totalPages,totalRecords:N.pagination.totalRecords})}catch(b){console.error("Failed to fetch aging data:",b),h((b==null?void 0:b.message)||"Failed to load aging data")}finally{C?c(!1):m(!1)}C&&(y.current=!1)},[t,s,a,r]),w=x.useMemo(()=>i.filter(f=>{var b,N,R;if(!n)return!0;const C=n.toLowerCase();return((b=f.id)==null?void 0:b.toLowerCase().includes(C))||((N=f.title)==null?void 0:N.toLowerCase().includes(C))||((R=f.initiator)==null?void 0:R.toLowerCase().includes(C))}),[i,n]);return x.useEffect(()=>{s==="custom"&&(!a||!r)||v(1)},[t,s,a,r]),{agingWorkflows:w,loading:l,loadingPage:d,error:u,pagination:p,fetchData:v}}function qS(t="7"){const[s,a]=x.useState(t),[r,n]=x.useState(null),i=x.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=x.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 WS(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 aa(i.requestId||i.requestNumber),l=i.submissionDate?ea(i.submissionDate):"N/A",c=i.closureDate?ea(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),p=(o==null?void 0:o.approvals)||[];if(p.length===0){const g=[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(g.join(","))}else p.forEach(g=>{const y=g.levelStartTime?ea(g.levelStartTime):"N/A",v=g.levelEndTime||g.completedAt?ea(g.levelEndTime||g.completedAt):"N/A",w=g.tatHours||0,f=g.tatDays||(w>0?(w/8).toFixed(2):"0");let C="N/A",b="N/A",N="N/A",R="N/A";if(g.levelStartTime){const P=new Date(g.levelStartTime);if(b=(((g.levelEndTime||g.completedAt?new Date(g.levelEndTime||g.completedAt):new Date).getTime()-P.getTime())/(1e3*60*60)).toFixed(2),w>0){const k=parseFloat(b);N=Math.max(0,w-k).toFixed(2),R=(k/w*100).toFixed(2),g.status==="APPROVED"||g.status==="REJECTED"?C=k<=w?"Compliant":"Breached":g.status==="IN_PROGRESS"||g.status==="PENDING"?C=k<=w?"On Track":"At Risk":C="N/A"}}const E=[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(),(g.levelNumber||"").toString(),`"${(g.levelName||`Level ${g.levelNumber}`).replace(/"/g,'""')}"`,`"${(g.approverName||"N/A").replace(/"/g,'""')}"`,`"${(g.approverEmail||"N/A").replace(/"/g,'""')}"`,g.status||"PENDING",y,v,w.toString(),f.toString(),C,b,N,R];n.push(E.join(","))})}catch(o){console.error(`Failed to fetch details for request ${i.requestNumber}:`,o);const l=i.submissionDate?ea(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(","))}Vo(n,`lifecycle-report-end-to-end-${new Date().toISOString().split("T")[0]}.csv`)}async function KS(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=jh(l.type||"",l.details),m=[l.timestamp?ea(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(","))}),Vo(o,`activity-log-report-${new Date().toISOString().split("T")[0]}.csv`)}async function GS(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?ea(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(","))}),Vo(i,`workflow-aging-report-${new Date().toISOString().split("T")[0]}.csv`)}function Vo(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 YS(){const[t,s]=x.useState(!1),[a,r]=x.useState(!1),[n,i]=x.useState(!1),o=x.useCallback(async(d,m,u)=>{try{s(!0),await WS(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=x.useCallback(async(d,m,u,h,p)=>{try{r(!0),await KS(d,m,u,h,p)}catch(g){console.error("Failed to export activity data:",g),alert("Failed to export activity data. Please try again.")}finally{r(!1)}},[]),c=x.useCallback(async(d,m,u,h)=>{try{i(!0),await GS(d,m,u,h)}catch(p){console.error("Failed to export aging data:",p),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 XS({onBack:t}){const s=Hs(),[a,r]=x.useState(""),[n,i]=x.useState("all"),[o,l]=x.useState("all"),c=Qn("month"),d=Qn("month"),m=Qn("month"),u=qS("7"),h=US({dateRange:c.dateRange,customStartDate:c.customStartDate,customEndDate:c.customEndDate}),p=VS({dateRange:d.dateRange,customStartDate:d.customStartDate,customEndDate:d.customEndDate,filterCategory:n,filterSeverity:o}),g=HS({threshold:u.threshold,dateRange:m.dateRange,customStartDate:m.customStartDate,customEndDate:m.customEndDate,searchQuery:a}),y=YS(),v=x.useCallback(()=>{t?t():s("/dashboard")},[t,s]),w=x.useCallback(R=>{s(`/request/${R}`)},[s]),f=x.useCallback(()=>{y.handleExportLifecycle(c.dateRange,c.customStartDate,c.customEndDate)},[y,c]),C=x.useCallback(()=>{y.handleExportActivity(d.dateRange,d.customStartDate,d.customEndDate,n,o)},[y,d,n,o]),b=x.useCallback(()=>{const R=parseInt(u.threshold,10);!isNaN(R)&&R>=1&&y.handleExportAging(R,m.dateRange,m.customStartDate,m.customEndDate)},[y,u.threshold,m]),N=x.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(ES,{onBack:v}),e.jsx(FS,{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:w}),e.jsx(_S,{activityLog:p.activityLog,loading:p.loading,loadingPage:p.loadingPage,error:p.error,pagination:p.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:N,onPageChange:p.fetchData,onExport:C,onViewRequest:w}),e.jsx(LS,{agingWorkflows:g.agingWorkflows,loading:g.loading,loadingPage:g.loadingPage,error:g.error,pagination:g.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:g.fetchData,onExport:b,onViewRequest:w})]})})}function ZS({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(J,{htmlFor:"default-period",children:"Default Reporting Period"}),e.jsxs(Te,{value:t,onValueChange:a,children:[e.jsx(Re,{id:"default-period",children:e.jsx(ke,{})}),e.jsx(De,{children:n.map(i=>e.jsx(U,{value:i,children:i},i))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"refresh-interval",children:"Auto-Refresh Interval (minutes)"}),e.jsx(fe,{id:"refresh-interval",type:"number",min:"1",max:"60",value:s,onChange:i=>r(parseInt(i.target.value)||5)})]})]})}function QS({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(Lt,{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(Lt,{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(Lt,{checked:a,onCheckedChange:i})]})]})}const JS=["CSV","Excel","PDF","JSON"];function eA({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(J,{children:"Allowed Export Formats"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:JS.map(r=>e.jsxs("div",{className:"flex items-center space-x-2 p-2 bg-muted/50 rounded",children:[e.jsx(Gi,{id:`export-${r}`,checked:t.includes(r),onCheckedChange:n=>a(r,n)}),e.jsx(J,{htmlFor:`export-${r}`,className:"text-sm cursor-pointer",children:r})]},r))})]})}function tA({dataRetention:t,onDataRetentionChange:s}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"data-retention",children:"Historical Data Retention (months)"}),e.jsx(fe,{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 sA(){const[t,s]=x.useState({defaultPeriod:"This Month",refreshInterval:5,autoRefresh:!0,realTimeUpdates:!0,dataExport:!0,exportFormats:["CSV","Excel","PDF"],dataRetention:24}),a=()=>{be.success("Analytics configuration saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(K,{children:[e.jsxs(ae,{children:[e.jsx(re,{children:"Analytics & Reporting Configuration"}),e.jsx(ge,{children:"Configure default reporting periods, auto-refresh, export settings, and data retention"})]}),e.jsxs(G,{className:"space-y-6",children:[e.jsx(ZS,{defaultPeriod:t.defaultPeriod,refreshInterval:t.refreshInterval,onDefaultPeriodChange:n=>r({defaultPeriod:n}),onRefreshIntervalChange:n=>r({refreshInterval:n})}),e.jsx(dt,{}),e.jsx(QS,{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(dt,{}),e.jsx(eA,{exportFormats:t.exportFormats,onExportFormatsChange:n=>r({exportFormats:n})}),e.jsx(tA,{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(zs,{className:"w-4 h-4 mr-2"}),"Save Analytics Configuration"]})]})]})}const aA=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"}},rA=t=>t.split(" ").map(s=>s[0]).join("").toUpperCase().substring(0,2);function nA({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(Uo,{children:e.jsxs(ca,{children:[e.jsx(ft,{children:"User"}),e.jsx(ft,{children:"Role"}),e.jsx(ft,{children:"Department"}),e.jsx(ft,{children:"Status"}),e.jsx(ft,{className:"text-right",children:"Actions"})]})}),e.jsx(Bo,{children:t.length===0?e.jsx(ca,{children:e.jsx(ut,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No users found"})}):t.map(n=>e.jsxs(ca,{className:"hover:bg-muted/50",children:[e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(bt,{className:"size-10",children:e.jsx(jt,{className:"bg-re-green text-white",children:rA(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(ut,{children:e.jsx(ee,{className:aA(n.role),children:n.role})}),e.jsx(ut,{children:n.department}),e.jsx(ut,{children:e.jsxs(ee,{className:"bg-green-100 text-green-800 border-green-200",children:[e.jsx(ti,{className:"w-3 h-3 mr-1"}),n.status]})}),e.jsx(ut,{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(Yr,{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(Ix,{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(Vi,{className:"w-4 h-4"})})]})})]},n.id))})]})})}function iA({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 oA(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function lA(){const[t,s]=x.useState(""),[a,r]=x.useState([]),[n,i]=x.useState(!1),[o,l]=x.useState(null),[c,d]=x.useState("USER"),[m,u]=x.useState(!1),[h,p]=x.useState(!1),[g,y]=x.useState(null),[v,w]=x.useState([]),[f,C]=x.useState(!1),[b,N]=x.useState({admins:0,management:0,users:0,total:0,active:0,inactive:0}),[R,E]=x.useState("ELEVATED"),[P,I]=x.useState(1),[j,k]=x.useState(1),[_,Y]=x.useState(0),F=10,L=x.useRef(null),A=x.useCallback(oA(async q=>{var Q,oe,W;if(!q||!q.startsWith("@")||q.length<2){r([]),i(!1);return}i(!0);try{const me=q.slice(1),Ee=((Q=(await Gt.searchUsers(me,20)).data)==null?void 0:Q.data)||[];r(Ee)}catch(me){console.error("Search failed:",me),y({type:"error",text:((W=(oe=me.response)==null?void 0:oe.data)==null?void 0:W.message)||"Failed to search users"})}finally{i(!1)}},300),[]),S=q=>{const Q=q.target.value;s(Q),A(Q)},T=async q=>{var Q,oe;try{const W=v.find(Fe=>Fe.email.toLowerCase()===q.toLowerCase());if(W)return W.role;const Ee=(((oe=(Q=(await Gt.getUsersByRole("ALL",1,1e3)).data)==null?void 0:Q.data)==null?void 0:oe.users)||[]).find(Fe=>{var le;return((le=Fe.email)==null?void 0:le.toLowerCase())===q.toLowerCase()});return Ee&&Ee.role?Ee.role:null}catch(W){return console.error("Failed to fetch user role:",W),null}},D=async q=>{l(q),s(q.email),r([]),p(!0);try{const Q=await T(q.email);d(Q||"USER")}catch(Q){console.error("Failed to fetch user role:",Q),d("USER")}finally{p(!1)}},H=async()=>{var q,Q;if(!o||!c){y({type:"error",text:"Please select a user and role"});return}u(!0),y(null);try{await Gt.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 Z(),be.success("Role assigned successfully")}catch(oe){console.error("Role assignment failed:",oe);const W=((Q=(q=oe.response)==null?void 0:q.data)==null?void 0:Q.error)||"Failed to assign role";y({type:"error",text:W}),be.error(W)}finally{u(!1)}},z=async(q=P)=>{var Q,oe,W,me,we,Ee;C(!0);try{const Fe=await Gt.getUsersByRole(R,q,F),le=((oe=(Q=Fe.data)==null?void 0:Q.data)==null?void 0:oe.users)||[],ye=(me=(W=Fe.data)==null?void 0:W.data)==null?void 0:me.pagination,Ve=(Ee=(we=Fe.data)==null?void 0:we.data)==null?void 0:Ee.summary;w(le.map(Le=>({userId:Le.userId,email:Le.email,displayName:Le.displayName||Le.email,role:Le.role||"USER",department:Le.department,designation:Le.designation,isActive:Le.isActive!==!1}))),ye&&(I(ye.currentPage),k(ye.totalPages),Y(ye.totalUsers)),Ve&&N(Le=>({...Le,admins:Ve.ADMIN||0,management:Ve.MANAGEMENT||0,users:Ve.USER||0,total:(Ve.ADMIN||0)+(Ve.MANAGEMENT||0)+(Ve.USER||0)}))}catch(Fe){console.error("Failed to fetch users:",Fe),be.error("Failed to load users")}finally{C(!1)}},Z=async()=>{var q,Q,oe,W,me,we;try{const Ee=await Gt.getRoleStatistics(),Fe=((Q=(q=Ee.data)==null?void 0:q.data)==null?void 0:Q.statistics)||((oe=Ee.data)==null?void 0:oe.statistics)||[],le={admins:parseInt(((W=Fe.find(ye=>ye.role==="ADMIN"))==null?void 0:W.count)||"0"),management:parseInt(((me=Fe.find(ye=>ye.role==="MANAGEMENT"))==null?void 0:me.count)||"0"),users:parseInt(((we=Fe.find(ye=>ye.role==="USER"))==null?void 0:we.count)||"0")};N(ye=>({...ye,...le,total:le.admins+le.management+le.users,active:ye.active||le.admins+le.management+le.users,inactive:ye.inactive||0}))}catch(Ee){console.error("Failed to fetch statistics:",Ee)}};x.useEffect(()=>{z(1),Z()},[R]);const O=q=>{E(q),I(1)},se=q=>{z(q)},te=async(q,Q)=>{var oe,W;try{await Gt.updateUserRole(q,Q),be.success("User role updated successfully"),await z(),await Z()}catch(me){console.error("Failed to update user role:",me),be.error(((W=(oe=me.response)==null?void 0:oe.data)==null?void 0:W.error)||"Failed to update user role")}},$=async q=>{v.find(oe=>oe.userId===q)&&be.info("User status toggle functionality coming soon")},X=async q=>{const Q=v.find(oe=>oe.userId===q);if(Q){if(Q.role==="ADMIN"){be.error("Cannot delete admin user");return}be.info("User deletion functionality coming soon")}};x.useEffect(()=>{const q=Q=>{L.current&&!L.current.contains(Q.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",q),()=>{document.removeEventListener("mousedown",q)}},[a]);const ne={total:b.total,active:b.active,inactive:b.inactive,admins:b.admins};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(iA,{stats:ne}),e.jsxs(K,{children:[e.jsx(ae,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Assign User Role"}),e.jsx(ge,{children:"Search for a user in Okta and assign them a role"})]}),e.jsx(M,{onClick:H,disabled:!o||m,className:"bg-re-green hover:bg-re-green/90",children:m?e.jsxs(e.Fragment,{children:[e.jsx(Ue,{className:"w-4 h-4 mr-2 animate-spin"}),"Assigning..."]}):e.jsxs(e.Fragment,{children:[e.jsx(_s,{className:"w-4 h-4 mr-2"}),"Assign Role"]})})]})}),e.jsxs(G,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",ref:L,children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Xt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(fe,{type:"text",placeholder:"Type @ to search users...",value:t,onChange:S,className:"pl-10 border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),n&&e.jsx(Ue,{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 with @ to search users (e.g., @john)"}),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(q=>e.jsxs("button",{onClick:()=>D(q),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:q.displayName||q.email}),e.jsx("p",{className:"text-sm text-muted-foreground",children:q.email}),q.department&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[q.department,q.designation?` • ${q.designation}`:""]})]},q.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(Ue,{className:"w-3 h-3 animate-spin"}),"Checking current role..."]})]})]}),e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>{l(null),s(""),d("USER"),p(!1)},children:"Clear"})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Select Role"}),e.jsxs(Te,{value:c,onValueChange:q=>d(q),disabled:h,children:[e.jsx(Re,{className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(ke,{placeholder:h?"Loading current role...":"Select role"})}),e.jsxs(De,{className:"rounded-lg",children:[e.jsx(U,{value:"USER",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(it,{className:"w-4 h-4 text-gray-600"}),e.jsx("span",{children:"User - Regular access"})]})}),e.jsx(U,{value:"MANAGEMENT",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nt,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Management - Read all data"})]})}),e.jsx(U,{value:"ADMIN",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ha,{className:"w-4 h-4 text-yellow-600"}),e.jsx("span",{children:"Administrator - Full access"})]})})]})]})]}),g&&e.jsx("div",{className:`border-2 rounded-lg p-4 ${g.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:[g.type==="success"?e.jsx(je,{className:"w-5 h-5 text-green-600 shrink-0 mt-0.5"}):e.jsx(Pe,{className:"w-5 h-5 text-red-600 shrink-0 mt-0.5"}),e.jsx("p",{className:`text-sm ${g.type==="success"?"text-green-800":"text-red-800"}`,children:g.text})]})})]})]}),e.jsxs(K,{children:[e.jsx(ae,{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(re,{className:"flex items-center gap-2",children:[e.jsx(nt,{className:"w-5 h-5 text-re-green"}),"User Management"]}),e.jsxs(ge,{children:["View and manage user accounts and roles (",_," ",R!=="ALL"&&R!=="ELEVATED"?R.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(Te,{value:R,onValueChange:O,children:[e.jsx(Re,{className:"w-[200px] border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(ke,{placeholder:"Filter by role"})}),e.jsxs(De,{children:[e.jsx(U,{value:"ELEVATED",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(It,{className:"w-4 h-4 text-purple-600"}),e.jsxs("span",{children:["Elevated (",b.admins+b.management,")"]})]})}),e.jsx(U,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ha,{className:"w-4 h-4 text-yellow-600"}),e.jsxs("span",{children:["Admins (",b.admins,")"]})]})}),e.jsx(U,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nt,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Management (",b.management,")"]})]})}),e.jsx(U,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(it,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["Users (",b.users,")"]})]})}),e.jsx(U,{value:"ALL",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nt,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["All Users (",b.admins+b.management+b.users,")"]})]})})]})]})})]})}),e.jsx(G,{className:"pt-6",children:f?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsx(Ue,{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(nt,{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(nA,{users:v.map(q=>({id:q.userId,name:q.displayName,email:q.email,role:q.role,department:q.department||"N/A",status:q.isActive?"active":"inactive"})),onEdit:q=>{const Q=v.find(oe=>oe.userId===q);if(Q){const oe=Q.role==="USER"?"MANAGEMENT":Q.role==="MANAGEMENT"?"ADMIN":"USER";te(q,oe)}},onToggleStatus:$,onDelete:X}),j>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 ",(P-1)*F+1," to ",Math.min(P*F,_)," of ",_," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(M,{variant:"outline",size:"sm",onClick:()=>se(P-1),disabled:P===1,children:"Previous"}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,j)},(q,Q)=>{let oe;return j<=5||P<=3?oe=Q+1:P>=j-2?oe=j-4+Q:oe=P-2+Q,e.jsx(M,{variant:P===oe?"default":"outline",size:"sm",onClick:()=>se(oe),className:`w-9 h-9 p-0 ${P===oe?"bg-re-green hover:bg-re-green/90":""}`,children:oe},oe)})}),e.jsx(M,{variant:"outline",size:"sm",onClick:()=>se(P+1),disabled:P===j,children:"Next"})]})]})]})})]})]})}function cA({expressHours:t,standardHours:s,onExpressChange:a,onStandardChange:r}){return e.jsxs(K,{className:"border-0 shadow-sm",children:[e.jsxs(ae,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Li,{className:"w-5 h-5 text-re-green"}),e.jsx(re,{className:"text-base font-semibold",children:"Priority TAT Settings"})]}),e.jsx(ge,{className:"text-sm",children:"Set default turnaround time in hours for each priority level"})]}),e.jsx(G,{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(J,{htmlFor:"tat-express",className:"text-sm font-medium",children:"Express Priority (hours)"}),e.jsx(fe,{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(Ie,{className:"w-3 h-3"}),"Critical/Emergency requests (24/7, includes weekends)"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"tat-standard",className:"text-sm font-medium",children:"Standard Priority (hours)"}),e.jsx(fe,{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(Ie,{className:"w-3 h-3"}),"Regular priority requests (working hours only, excludes weekends & holidays)"]})]})]})})]})}function dA({reminderThreshold1:t,reminderThreshold2:s,onReminderThreshold1Change:a,onReminderThreshold2Change:r}){return e.jsxs(K,{className:"border-0 shadow-sm",children:[e.jsxs(ae,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ft,{className:"w-5 h-5 text-re-green"}),e.jsx(re,{className:"text-base font-semibold",children:"Auto-Reminder & Escalation"})]}),e.jsx(ge,{className:"text-sm",children:"Configure automatic reminder thresholds based on TAT percentage"})]}),e.jsx(G,{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(J,{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(Di,{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(Ft,{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(J,{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(Di,{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 $a=[{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 mA({workStartHour:t,workEndHour:s,workStartDay:a,workEndDay:r,onWorkStartHourChange:n,onWorkEndHourChange:i,onWorkStartDayChange:o,onWorkEndDayChange:l}){var c,d,m;return e.jsxs(K,{className:"border-0 shadow-sm",children:[e.jsxs(ae,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(We,{className:"w-5 h-5 text-re-green"}),e.jsx(re,{className:"text-base font-semibold",children:"Working Hours Configuration"})]}),e.jsx(ge,{className:"text-sm",children:"Define your organization's working hours and days for TAT calculations"})]}),e.jsxs(G,{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(J,{htmlFor:"work-start-hour",className:"text-sm font-medium",children:"Working Day Start Hour"}),e.jsx(fe,{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(Ie,{className:"w-3 h-3"}),"24-hour format (0-23). Default: 9 AM"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"work-end-hour",className:"text-sm font-medium",children:"Working Day End Hour"}),e.jsx(fe,{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(Ie,{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(J,{htmlFor:"work-start-day",className:"text-sm font-medium",children:"Working Week Start Day"}),e.jsxs(Te,{value:a.toString(),onValueChange:u=>o(parseInt(u)),children:[e.jsx(Re,{id:"work-start-day",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(ke,{placeholder:"Select start day"})}),e.jsx(De,{children:$a.map(u=>e.jsx(U,{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(J,{htmlFor:"work-end-day",className:"text-sm font-medium",children:"Working Week End Day"}),e.jsxs(Te,{value:r.toString(),onValueChange:u=>l(parseInt(u)),children:[e.jsx(Re,{id:"work-end-day",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(ke,{placeholder:"Select end day"})}),e.jsx(De,{children:$a.map(u=>e.jsx(U,{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=$a.find(u=>u.value===a))==null?void 0:c.label} only`:` ${(d=$a.find(u=>u.value===a))==null?void 0:d.label} to ${(m=$a.find(u=>u.value===r))==null?void 0:m.label}`]})})]})]})}function uA(){const[t,s]=x.useState(!0),[a,r]=x.useState(!1),[n,i]=x.useState({expressHours:24,standardHours:72,reminderThreshold1:50,reminderThreshold2:75,workStartHour:9,workEndHour:18,workStartDay:1,workEndDay:5});x.useEffect(()=>{o()},[]);const o=async()=>{try{s(!0);const d=await tn("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),be.error("Failed to load TAT configurations")}finally{s(!1)}},l=async()=>{var d,m;try{r(!0),await Promise.all([vt("DEFAULT_TAT_EXPRESS_HOURS",n.expressHours.toString()),vt("DEFAULT_TAT_STANDARD_HOURS",n.standardHours.toString()),vt("TAT_REMINDER_THRESHOLD_1",n.reminderThreshold1.toString()),vt("TAT_REMINDER_THRESHOLD_2",n.reminderThreshold2.toString()),vt("WORK_START_HOUR",n.workStartHour.toString()),vt("WORK_END_HOUR",n.workEndHour.toString()),vt("WORK_START_DAY",n.workStartDay.toString()),vt("WORK_END_DAY",n.workEndDay.toString())]),be.success("TAT configuration saved successfully"),await o()}catch(u){console.error("Failed to save TAT configuration:",u),be.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(K,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(G,{className:"p-12 text-center",children:[e.jsx(Ue,{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(K,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ae,{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(Ie,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(re,{className:"text-lg font-semibold text-gray-900",children:"Turn Around Time (TAT) Configuration"}),e.jsx(ge,{className:"text-sm text-gray-600",children:"Set default TAT hours per priority level, working hours, and configure auto-escalation thresholds"})]})]})}),e.jsxs(G,{className:"space-y-6",children:[e.jsx(cA,{expressHours:n.expressHours,standardHours:n.standardHours,onExpressChange:d=>c({expressHours:d}),onStandardChange:d=>c({standardHours:d})}),e.jsx(dt,{}),e.jsx(mA,{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(dt,{}),e.jsx(dA,{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(Ue,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(zs,{className:"w-4 h-4 mr-2"}),"Save TAT Settings"]})})})]})]})}function hA({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(Lt,{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(Lt,{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(Lt,{checked:a,onCheckedChange:i})]})]})}function pA({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(J,{htmlFor:"notification-frequency",children:"Notification Frequency"}),e.jsxs(Te,{value:t,onValueChange:a,children:[e.jsx(Re,{id:"notification-frequency",children:e.jsx(ke,{placeholder:"Select frequency"})}),e.jsxs(De,{children:[e.jsx(U,{value:"Immediate",children:"Immediate"}),e.jsx(U,{value:"Hourly",children:"Hourly"}),e.jsx(U,{value:"Daily",children:"Daily"}),e.jsx(U,{value:"Weekly",children:"Weekly"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"reminder-frequency",children:"Reminder Frequency (hours)"}),e.jsx(fe,{id:"reminder-frequency",type:"number",min:"1",max:"168",value:s,onChange:n=>r(parseInt(n.target.value)||12)})]})]})}function xA({emailTemplate:t,onEmailTemplateChange:s}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"email-template",children:"Email Template Message"}),e.jsx(bs,{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 gA(){const[t,s]=x.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=()=>{be.success("Notification configuration saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(K,{children:[e.jsxs(ae,{children:[e.jsx(re,{children:"Notification Configuration"}),e.jsx(ge,{children:"Configure notification channels, frequency, and message templates"})]}),e.jsxs(G,{className:"space-y-6",children:[e.jsx(hA,{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(dt,{}),e.jsx(pA,{notificationFrequency:t.notificationFrequency,reminderFrequency:t.reminderFrequency,onNotificationFrequencyChange:n=>r({notificationFrequency:n}),onReminderFrequencyChange:n=>r({reminderFrequency:n})}),e.jsx(xA,{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(zs,{className:"w-4 h-4 mr-2"}),"Save Notification Settings"]})]})]})}function fA({maxFileSizeMB:t,retentionDays:s,onMaxFileSizeChange:a,onRetentionDaysChange:r}){const n=Math.round(s/365*10)/10;return e.jsxs(K,{className:"border-0 shadow-sm",children:[e.jsxs(ae,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Na,{className:"w-5 h-5 text-re-green"}),e.jsx(re,{className:"text-base font-semibold",children:"Upload & Retention Settings"})]}),e.jsx(ge,{className:"text-sm",children:"Configure file size limits and document retention period"})]}),e.jsx(G,{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(J,{htmlFor:"max-upload",className:"text-sm font-medium",children:"Maximum Upload Size (MB)"}),e.jsx(fe,{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(Na,{className:"w-3 h-3"}),"Maximum allowed file size for document uploads"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"retention",className:"text-sm font-medium",children:"Retention Period (Days)"}),e.jsx(fe,{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(Xr,{className:"w-3 h-3"}),"Days to retain documents after workflow closure (",n," years)"]})]})]})})]})}const yA=[{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 vA({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(K,{className:"border-0 shadow-sm",children:[e.jsxs(ae,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bd,{className:"w-5 h-5 text-re-green"}),e.jsx(re,{className:"text-base font-semibold",children:"Allowed File Types"})]}),e.jsx(ge,{className:"text-sm",children:"Select which file types are allowed for upload"})]}),e.jsxs(G,{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:yA.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(J,{htmlFor:"file-types-manual",className:"text-sm font-medium",children:"File Extensions (comma-separated)"}),e.jsx(fe,{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 bA(){const[t,s]=x.useState(!0),[a,r]=x.useState(!1),[n,i]=x.useState({maxFileSizeMB:10,retentionDays:365,allowedFileTypes:"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif"});x.useEffect(()=>{o()},[]);const o=async()=>{try{s(!0);const d=await tn("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),be.error("Failed to load document configurations")}finally{s(!1)}},l=async()=>{var d,m;try{r(!0),await Promise.all([vt("MAX_FILE_SIZE_MB",n.maxFileSizeMB.toString()),vt("DOCUMENT_RETENTION_DAYS",n.retentionDays.toString()),vt("ALLOWED_FILE_TYPES",n.allowedFileTypes)]),be.success("Document policy saved successfully"),await o()}catch(u){console.error("Failed to save document configuration:",u),be.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(K,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(G,{className:"p-12 text-center",children:[e.jsx(Ue,{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(K,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ae,{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(Ae,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(re,{className:"text-lg font-semibold text-gray-900",children:"Document Upload Policy"}),e.jsx(ge,{className:"text-sm text-gray-600",children:"Configure file upload limits, allowed types, and retention policies"})]})]})}),e.jsxs(G,{className:"space-y-6",children:[e.jsx(fA,{maxFileSizeMB:n.maxFileSizeMB,retentionDays:n.retentionDays,onMaxFileSizeChange:d=>c({maxFileSizeMB:d}),onRetentionDaysChange:d=>c({retentionDays:d})}),e.jsx(dt,{}),e.jsx(vA,{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(Ue,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(zs,{className:"w-4 h-4 mr-2"}),"Save Document Policy"]})})})]})]})}function jA(){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 NA=["Total Requests","Open Requests","Approved Requests","Rejected Requests","My Pending Actions","TAT Compliance","Delayed Workflows","Average Cycle Time"],wA=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 CA({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(ee,{className:wA(t),children:[t," Dashboard"]})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-2 ml-4",children:NA.map(r=>e.jsxs("div",{className:"flex items-center space-x-2 p-2 bg-muted/50 rounded",children:[e.jsx(Gi,{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 SA(){const[t,s]=x.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=()=>{be.success("Dashboard layout saved successfully")},r=(i,o,l)=>{s(c=>({...c,[i]:{...c[i],[o]:l}}))},n=["Initiator","Approver","Spectator"];return e.jsxs(K,{children:[e.jsxs(ae,{children:[e.jsx(re,{children:"Dashboard Layout Configuration"}),e.jsx(ge,{children:"Control which KPI cards are visible for each user role"})]}),e.jsxs(G,{className:"space-y-4",children:[e.jsx(jA,{}),e.jsx("div",{className:"space-y-6",children:n.map(i=>e.jsx(CA,{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(zs,{className:"w-4 h-4 mr-2"}),"Save Dashboard Layout"]})]})]})}const AA=[{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 TA({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(K,{className:"border-0 shadow-sm",children:[e.jsxs(ae,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sd,{className:"w-5 h-5 text-re-green"}),e.jsx(re,{className:"text-base font-semibold",children:"AI Provider & API Keys"})]}),e.jsx(ge,{className:"text-sm",children:"Select your AI provider and configure API keys"})]}),e.jsxs(G,{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(Lt,{checked:t,onCheckedChange:o})]}),t&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"ai-provider",className:"text-sm font-medium",children:"AI Provider"}),e.jsxs(Te,{value:s,onValueChange:p=>l(p),children:[e.jsx(Re,{id:"ai-provider",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(ke,{placeholder:"Select AI provider"})}),e.jsx(De,{children:AA.map(p=>e.jsx(U,{value:p.value,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:p.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"-"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:p.description})]})},p.value))})]})]}),e.jsxs("div",{className:"space-y-4 pt-2",children:[e.jsxs(J,{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(J,{htmlFor:"claude-key",className:"text-xs text-muted-foreground",children:"Claude API Key"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(fe,{id:"claude-key",type:i.claude?"text":"password",value:a,onChange:p=>c(p.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(Ar,{className:"w-4 h-4"}):e.jsx(kt,{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(J,{htmlFor:"openai-key",className:"text-xs text-muted-foreground",children:"OpenAI API Key"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(fe,{id:"openai-key",type:i.openai?"text":"password",value:r,onChange:p=>d(p.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(Ar,{className:"w-4 h-4"}):e.jsx(kt,{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(J,{htmlFor:"gemini-key",className:"text-xs text-muted-foreground",children:"Gemini API Key"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(fe,{id:"gemini-key",type:i.gemini?"text":"password",value:n,onChange:p=>m(p.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(Ar,{className:"w-4 h-4"}):e.jsx(kt,{className:"w-4 h-4"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Get your API key from ai.google.dev"})]})]})]})]})]})}function kA({aiRemarkGeneration:t,onRemarkGenerationChange:s}){return e.jsxs(K,{className:"border-0 shadow-sm",children:[e.jsxs(ae,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gr,{className:"w-5 h-5 text-re-green"}),e.jsx(re,{className:"text-base font-semibold",children:"AI Features"})]}),e.jsx(ge,{className:"text-sm",children:"Enable/disable specific AI-powered features"})]}),e.jsx(G,{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(Lt,{checked:t,onCheckedChange:s})]})})})]})}function RA({maxRemarkChars:t,onMaxRemarkCharsChange:s}){return e.jsxs(K,{className:"border-0 shadow-sm",children:[e.jsxs(ae,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Cd,{className:"w-5 h-5 text-re-green"}),e.jsx(re,{className:"text-base font-semibold",children:"AI Parameters"})]}),e.jsx(ge,{className:"text-sm",children:"Configure AI generation parameters"})]}),e.jsx(G,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"max-remark-chars",className:"text-sm font-medium",children:"Maximum Remark Length"}),e.jsx(fe,{id:"max-remark-chars",type:"number",min:"500",max:"5000",value:t,onChange:a=>s(parseInt(a.target.value)||2e3),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 length for AI-generated conclusion remarks (500-5000 characters)"})]})})]})}function DA(){const[t,s]=x.useState(!0),[a,r]=x.useState(!1),[n,i]=x.useState({claude:!1,openai:!1,gemini:!1}),[o,l]=x.useState({aiEnabled:!0,aiProvider:"claude",claudeApiKey:"",openaiApiKey:"",geminiApiKey:"",aiRemarkGeneration:!0,maxRemarkChars:500});x.useEffect(()=>{c()},[]);const c=async()=>{try{s(!0);const p=await tn("AI_CONFIGURATION"),g={};p.forEach(y=>{g[y.configKey]=y.configValue}),l({aiEnabled:g.AI_ENABLED==="true",aiProvider:g.AI_PROVIDER||"claude",claudeApiKey:g.CLAUDE_API_KEY||"",openaiApiKey:g.OPENAI_API_KEY||"",geminiApiKey:g.GEMINI_API_KEY||"",aiRemarkGeneration:g.AI_REMARK_GENERATION_ENABLED==="true",maxRemarkChars:parseInt(g.AI_MAX_REMARK_LENGTH||"2000")})}catch(p){console.error("Failed to load AI configurations:",p),be.error("Failed to load AI configurations")}finally{s(!1)}},d=async()=>{var p,g;try{r(!0),await Promise.all([vt("AI_ENABLED",o.aiEnabled.toString()),vt("AI_PROVIDER",o.aiProvider),vt("CLAUDE_API_KEY",o.claudeApiKey),vt("OPENAI_API_KEY",o.openaiApiKey),vt("GEMINI_API_KEY",o.geminiApiKey),vt("AI_REMARK_GENERATION_ENABLED",o.aiRemarkGeneration.toString()),vt("AI_MAX_REMARK_LENGTH",o.maxRemarkChars.toString())]),be.success("AI configuration saved successfully"),await c()}catch(y){console.error("Failed to save AI configuration:",y),be.error(((g=(p=y.response)==null?void 0:p.data)==null?void 0:g.error)||"Failed to save AI configuration")}finally{r(!1)}},m=p=>{l(g=>({...g,...p}))},u=p=>{i(g=>({...g,[p]:!g[p]}))},h=p=>!p||p.length===0?"":p.length<=8?"••••••••":p.substring(0,4)+"••••••••"+p.substring(p.length-4);return t?e.jsx(K,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(G,{className:"p-12 text-center",children:[e.jsx(Ue,{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(K,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ae,{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(Gr,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(re,{className:"text-lg font-semibold text-gray-900",children:"AI Features Configuration"}),e.jsx(ge,{className:"text-sm text-gray-600",children:"Configure AI provider, API keys, and enable/disable AI-powered features"})]})]})}),e.jsxs(G,{className:"space-y-6",children:[e.jsx(TA,{aiEnabled:o.aiEnabled,aiProvider:o.aiProvider,claudeApiKey:o.claudeApiKey,openaiApiKey:o.openaiApiKey,geminiApiKey:o.geminiApiKey,showApiKeys:n,onAiEnabledChange:p=>m({aiEnabled:p}),onProviderChange:p=>m({aiProvider:p}),onClaudeApiKeyChange:p=>m({claudeApiKey:p}),onOpenaiApiKeyChange:p=>m({openaiApiKey:p}),onGeminiApiKeyChange:p=>m({geminiApiKey:p}),onToggleApiKeyVisibility:u,maskApiKey:h}),e.jsx(dt,{}),e.jsx(kA,{aiRemarkGeneration:o.aiRemarkGeneration,onRemarkGenerationChange:p=>m({aiRemarkGeneration:p})}),e.jsx(dt,{}),e.jsx(RA,{maxRemarkChars:o.maxRemarkChars,onMaxRemarkCharsChange:p=>m({maxRemarkChars:p})}),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(Ue,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(zs,{className:"w-4 h-4 mr-2"}),"Save AI Configuration"]})})})]})]})}const qc=["Admin Only","Initiator Only","Approver Only","Initiator & Approver","Admin & Initiator","Admin & Approver","All Roles"];function PA({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(J,{htmlFor:"spectator-permission",children:"Spectator Addition Permission"}),e.jsxs(Te,{value:t,onValueChange:a,children:[e.jsx(Re,{id:"spectator-permission",children:e.jsx(ke,{placeholder:"Select permission"})}),e.jsx(De,{children:qc.map(n=>e.jsx(U,{value:n,children:n},n))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{htmlFor:"link-sharing-permission",children:"Link Sharing Permission"}),e.jsxs(Te,{value:s,onValueChange:r,children:[e.jsx(Re,{id:"link-sharing-permission",children:e.jsx(ke,{placeholder:"Select permission"})}),e.jsx(De,{children:qc.map(n=>e.jsx(U,{value:n,children:n},n))})]})]})]})}function EA({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(Lt,{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(Lt,{checked:s,onCheckedChange:r})]})]})}function MA(){const[t,s]=x.useState({spectatorPermission:"Initiator & Approver",linkSharingPermission:"Admin & Initiator",requirePassword:!0,allowExternalSharing:!1}),a=()=>{be.success("Sharing policy saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(K,{children:[e.jsxs(ae,{children:[e.jsx(re,{children:"Workflow Sharing Policy"}),e.jsx(ge,{children:"Control who can add spectators and share workflow links"})]}),e.jsxs(G,{className:"space-y-6",children:[e.jsx(PA,{spectatorPermission:t.spectatorPermission,linkSharingPermission:t.linkSharingPermission,onSpectatorPermissionChange:n=>r({spectatorPermission:n}),onLinkSharingPermissionChange:n=>r({linkSharingPermission:n})}),e.jsx(dt,{}),e.jsx(EA,{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(zs,{className:"w-4 h-4 mr-2"}),"Save Sharing Policy"]})]})]})}function IA(){const{user:t}=Mt(),[s,a]=x.useState(""),[r,n]=x.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(It,{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(ee,{className:"bg-re-green/10 text-re-green border-re-green/20 px-4 py-2",children:[e.jsx(It,{className:"w-4 h-4 mr-2"}),"Administrator: ",(t==null?void 0:t.displayName)||"Admin User"]})]}),e.jsx(dt,{}),e.jsxs(Jr,{value:r,onValueChange:n,className:"flex flex-col gap-2 space-y-4",children:[e.jsxs(en,{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(xt,{value:"kpi",className:"flex items-center gap-2",children:[e.jsx(wd,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"KPI Config"})]}),e.jsxs(xt,{value:"analytics",className:"flex items-center gap-2",children:[e.jsx(Vs,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Analytics"})]}),e.jsxs(xt,{value:"users",className:"flex items-center gap-2",children:[e.jsx(nt,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Users"})]}),e.jsxs(xt,{value:"tat",className:"flex items-center gap-2",children:[e.jsx(Ie,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"TAT"})]}),e.jsxs(xt,{value:"notifications",className:"flex items-center gap-2",children:[e.jsx(Ft,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Notify"})]}),e.jsxs(xt,{value:"documents",className:"flex items-center gap-2",children:[e.jsx(Ae,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Docs"})]}),e.jsxs(xt,{value:"dashboard",className:"flex items-center gap-2",children:[e.jsx(_x,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Dashboard"})]}),e.jsxs(xt,{value:"ai",className:"flex items-center gap-2",children:[e.jsx(Sd,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"AI"})]}),e.jsxs(xt,{value:"sharing",className:"flex items-center gap-2",children:[e.jsx(Sa,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Sharing"})]})]}),e.jsx(gt,{value:"kpi",className:"flex-1 outline-none space-y-4",children:e.jsxs(K,{children:[e.jsx(ae,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(re,{children:"KPI Configuration"}),e.jsx(ge,{children:"Configure which KPIs are enabled, visible to specific roles, and set alert thresholds"})]}),e.jsxs(ee,{className:"bg-blue-50 text-blue-700",children:[l," / ",l," KPIs Active"]})]})}),e.jsxs(G,{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(Xt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(fe,{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(ee,{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(ee,{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(Lx,{className:"w-3 h-3"}):e.jsx(Ox,{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(ee,{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(Pe,{className:"w-3 h-3"}),e.jsx("span",{className:"font-medium",children:"Threshold Breached!"})]})]})]})]})})},m.id))})]},d.name))]})]})}),e.jsx(gt,{value:"analytics",className:"flex-1 outline-none space-y-4",children:e.jsx(sA,{})}),e.jsx(gt,{value:"users",className:"flex-1 outline-none space-y-4",children:e.jsx(lA,{})}),e.jsx(gt,{value:"tat",className:"flex-1 outline-none space-y-4",children:e.jsx(uA,{})}),e.jsx(gt,{value:"notifications",className:"flex-1 outline-none space-y-4",children:e.jsx(gA,{})}),e.jsx(gt,{value:"documents",className:"flex-1 outline-none space-y-4",children:e.jsx(bA,{})}),e.jsx(gt,{value:"dashboard",className:"flex-1 outline-none space-y-4",children:e.jsx(SA,{})}),e.jsx(gt,{value:"ai",className:"flex-1 outline-none space-y-4",children:e.jsx(DA,{})}),e.jsx(gt,{value:"sharing",className:"flex-1 outline-none space-y-4",children:e.jsx(MA,{})})]})]})}function FA({isOpen:t,onClose:s,action:a,requestId:r,requestTitle:n,onSubmit:i}){const[o,l]=x.useState(""),[c,d]=x.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()},p=a==="approve"?{title:"Approve Request",description:"Please provide your approval comments and remarks",icon:je,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:Je,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..."},g=p.icon;return e.jsx(et,{open:t,onOpenChange:u,children:e.jsxs(Xe,{className:"max-w-2xl bg-white",children:[e.jsxs(tt,{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(g,{className:`w-6 h-6 ${p.iconColor}`})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(Ze,{className:"text-xl",children:p.title}),e.jsx(qt,{className:"mt-1",children:p.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(ee,{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(ee,{className:p.badgeColor,variant:"outline",children:[e.jsx(g,{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(J,{htmlFor:"comment",className:"text-sm font-semibold text-gray-900",children:"Comments & Remarks *"}),e.jsx(bs,{id:"comment",placeholder:p.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(je,{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(wt,{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:p.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(g,{className:"w-4 h-4 mr-2"}),a==="approve"?"Approve Request":"Reject Request"]})})]})]})})}var _A=(t,s,a,r,n,i,o,l)=>{let c=document.documentElement,d=["light","dark"];function m(p){(Array.isArray(t)?t:[t]).forEach(g=>{let y=g==="class",v=y&&i?n.map(w=>i[w]||w):n;y?(c.classList.remove(...v),c.classList.add(i&&i[p]?i[p]:p)):c.setAttribute(g,p)}),u(p)}function u(p){l&&d.includes(p)&&(c.style.colorScheme=p)}function h(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}if(r)m(r);else try{let p=localStorage.getItem(s)||a,g=o&&p==="system"?h():p;m(g)}catch{}},LA=x.createContext(void 0),OA={setTheme:t=>{},themes:[]},$A=()=>{var t;return(t=x.useContext(LA))!=null?t:OA};x.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 x.createElement("script",{...d,suppressHydrationWarning:!0,nonce:typeof window>"u"?c:"",dangerouslySetInnerHTML:{__html:`(${_A.toString()})(${m})`}})});const UA=({...t})=>{const{theme:s="system"}=$A();return e.jsx($x,{theme:s,className:"toaster group",style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)"},...t})};function BA({onViewRequest:t}){const{user:s}=Mt();return Zr(s)?e.jsx(J2,{onViewRequest:t}):e.jsx(sS,{onViewRequest:t})}function VA({onLogout:t}){const s=Hs(),[a,r]=x.useState(null),[n,i]=x.useState([]),[o,l]=x.useState(""),[c,d]=x.useState("");x.useEffect(()=>{const f=localStorage.getItem("dynamicRequests");if(f)try{const C=JSON.parse(f);i(C)}catch(C){console.error("Error parsing dynamic requests:",C)}},[]),x.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,C,b)=>{l(f),d(C||"Unknown Request");const N=(b==null?void 0:b.toLowerCase())==="draft"||b==="DRAFT";s(N?`/edit-request/${f}`:`/request/${f}`)},h=()=>{s(-1)},p=()=>{s("/new-request")},g=f=>{var N,R,E,P,I,j,k,_,Y,F,L;if(f.templateType){f.templateType==="claim-management"&&s("/claim-management");return}const C=`RE-REQ-2024-${String(Object.keys(em).length+n.length+1).padStart(3,"0")}`,b={id:C,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:((N=f.approvers)==null?void 0:N.length)||1,currentApprover:((E=(R=f.approvers)==null?void 0:R[0])==null?void 0:E.name)||((j=(I=(P=f.approvers)==null?void 0:P[0])==null?void 0:I.email)==null?void 0:j.split("@")[0])||"Pending Assignment",approverLevel:`1 of ${((k=f.approvers)==null?void 0:k.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,S)=>{var H;const T=(A==null?void 0:A.name)||((H=A==null?void 0:A.email)==null?void 0:H.split("@")[0])||`Approver ${S+1}`,D=(A==null?void 0:A.email)||"";return{step:S+1,approver:`${T}${D?` (${D})`:""}`,role:(A==null?void 0:A.role)||`Level ${(A==null?void 0:A.level)||S+1} Approver`,status:S===0?"pending":"waiting",tatHours:A!=null&&A.tat?typeof A.tat=="string"?parseInt(A.tat):A.tat:48,elapsedHours:0,assignedAt:S===0?new Date().toISOString():null,comment:null,timestamp:null}}),documents:[],spectators:(f.spectators||[]).filter(A=>A&&(A.name||A.email)).map(A=>{var T;const S=(A==null?void 0:A.name)||((T=A==null?void 0:A.email)==null?void 0:T.split("@")[0])||"Observer";return{name:S,role:(A==null?void 0:A.role)||(A==null?void 0:A.department)||"Observer",avatar:S.split(" ").map(D=>D[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 ${((Y=(_=f.approvers)==null?void 0:_[0])==null?void 0:Y.name)||((L=(F=f.approvers)==null?void 0:F[0])==null?void 0:L.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,b]),s("/my-requests"),be.success("Request Submitted Successfully!",{description:`Your request "${f.title}" (${C}) has been created and sent for approval.`,duration:5e3})},y=(f,C)=>new Promise(b=>{setTimeout(()=>{f==="approve"?be.success("Request Approved",{description:"The request has been approved and forwarded to the next step.",duration:5e3}):be.error("Request Rejected",{description:"The request has been rejected and returned to the initiator.",duration:5e3}),r(null),b(!0)},1e3)}),v=()=>{r(null)},w=f=>{var N;const b={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",(N=f.activityType)==null?void 0:N.toLowerCase().replace(/\s+/g,"-")]};i(R=>[...R,b]),be.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(zx,{children:[e.jsx(ht,{path:"/login/callback",element:e.jsx($d,{})}),e.jsx(ht,{path:"/",element:e.jsx(Dt,{currentPage:"dashboard",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(dl,{onNavigate:m,onNewRequest:p})})}),e.jsx(ht,{path:"/dashboard",element:e.jsx(Dt,{currentPage:"dashboard",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(dl,{onNavigate:m,onNewRequest:p})})}),e.jsx(ht,{path:"/open-requests",element:e.jsx(Dt,{currentPage:"open-requests",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(z0,{onViewRequest:u})})}),e.jsx(ht,{path:"/closed-requests",element:e.jsx(Dt,{currentPage:"closed-requests",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(my,{onViewRequest:u})})}),e.jsx(ht,{path:"/shared-summaries",element:e.jsx(Dt,{currentPage:"shared-summaries",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(xv,{})})}),e.jsx(ht,{path:"/shared-summaries/:sharedSummaryId",element:e.jsx(Dt,{currentPage:"shared-summaries",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(gv,{})})}),e.jsx(ht,{path:"/my-requests",element:e.jsx(Dt,{currentPage:"my-requests",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(R2,{onViewRequest:u,dynamicRequests:n})})}),e.jsx(ht,{path:"/requests",element:e.jsx(Dt,{currentPage:"requests",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(BA,{onViewRequest:u})})}),e.jsx(ht,{path:"/approver-performance",element:e.jsx(Dt,{currentPage:"approver-performance",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(gS,{})})}),e.jsx(ht,{path:"/request/:requestId",element:e.jsx(Dt,{currentPage:"request-detail",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(pv,{requestId:"",onBack:h,dynamicRequests:n})})}),e.jsx(ht,{path:"/work-notes/:requestId",element:e.jsx(fv,{})}),e.jsx(ht,{path:"/new-request",element:e.jsx(Lc,{onBack:h,onSubmit:g})}),e.jsx(ht,{path:"/edit-request/:requestId",element:e.jsx(Lc,{onBack:h,onSubmit:g,requestId:void 0,isEditMode:!0})}),e.jsx(ht,{path:"/claim-management",element:e.jsx(u2,{onBack:h,onSubmit:w})}),e.jsx(ht,{path:"/profile",element:e.jsx(Dt,{currentPage:"profile",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(fS,{})})}),e.jsx(ht,{path:"/settings",element:e.jsx(Dt,{currentPage:"settings",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(DS,{})})}),e.jsx(ht,{path:"/notifications",element:e.jsx(Dt,{currentPage:"notifications",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(PS,{onNavigate:m})})}),e.jsx(ht,{path:"/detailed-reports",element:e.jsx(Dt,{currentPage:"detailed-reports",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(XS,{})})}),e.jsx(ht,{path:"/admin",element:e.jsx(Dt,{currentPage:"admin",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(IA,{})})})]}),e.jsx(UA,{position:"top-right",toastOptions:{style:{background:"var(--card)",color:"var(--card-foreground)",border:"1px solid var(--border)"}}}),a&&e.jsx(FA,{isOpen:!!a,onClose:v,action:a,requestId:o,requestTitle:c,onSubmit:y})]})}function zA(t){const{onLogout:s}=t||{};return e.jsx(Vx,{children:e.jsx(VA,{onLogout:s})})}function HA(){const{isAuthenticated:t,isLoading:s,error:a,user:r,logout:n}=Mt(),[i,o]=x.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 x.useEffect(()=>{},[t,s,a,r]),l?e.jsx($d,{}):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(zA,{onLogout:c}),i&&e.jsx(cf,{isOpen:i,onClose:()=>o(!1)})]}):e.jsx(of,{})}const Mr=()=>{try{return!0}catch{return!1}},qA=()=>{if(Mr())return null;try{return localStorage.getItem("token")}catch{return null}},WA={user:null,token:qA(),isAuthenticated:!1,isLoading:!1,error:null},Nh=Ta({name:"auth",initialState:WA,reducers:{loginStart:t=>{t.isLoading=!0,t.error=null},loginSuccess:(t,s)=>{if(t.isLoading=!1,t.isAuthenticated=!0,t.user=s.payload.user,t.token=s.payload.token,t.error=null,!Mr())try{localStorage.setItem("token",s.payload.token)}catch{}},loginFailure:(t,s)=>{if(t.isLoading=!1,t.isAuthenticated=!1,t.user=null,t.token=null,t.error=s.payload,!Mr())try{localStorage.removeItem("token")}catch{}},logout:t=>{if(t.isAuthenticated=!1,t.user=null,t.token=null,t.error=null,!Mr())try{localStorage.removeItem("token")}catch{}},clearError:t=>{t.error=null},updateUser:(t,s)=>{t.user=s.payload}}}),{loginStart:aT,loginSuccess:rT,loginFailure:nT,logout:iT,clearError:oT,updateUser:lT}=Nh.actions,KA=Bx({reducer:{auth:Nh.reducer,dashboard:zd.reducer,requests:dh.reducer,myRequests:ih.reducer,openRequests:qd.reducer,closedRequests:Jd.reducer},middleware:t=>t({serializableCheck:{ignoredActions:["persist/PERSIST"]}}),devTools:!1});ri.createRoot(document.getElementById("root")).render(e.jsx(Ep.StrictMode,{children:e.jsx(cg,{store:KA,children:e.jsx(Tg,{children:e.jsx(HA,{})})})}));export{de as a};
|
||
//# sourceMappingURL=index-Ctya9TRf.js.map
|