65 lines
994 KiB
JavaScript
65 lines
994 KiB
JavaScript
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/conclusionApi-nj0Kn1y4.js","assets/radix-vendor-C2EbRL2a.js","assets/charts-vendor-Cji9-Yri.js","assets/utils-vendor-DHm03ykU.js","assets/ui-vendor-IyYM8dvF.js","assets/socket-vendor-TjCxX7sJ.js","assets/redux-vendor-tbZCm13o.js","assets/router-vendor-CRr9x_Jp.js"])))=>i.map(i=>d[i]);
|
||
var Nh=Object.defineProperty;var wh=(t,s,a)=>s in t?Nh(t,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[s]=a;var dn=(t,s,a)=>wh(t,typeof s!="symbol"?s+"":s,a);import{j as e,S as qc,R as Wc,I as Kc,F as Gc,a as Ch,T as Sh,P as Ah,C as Th,b as kh,O as Yc,c as Zc,d as Rh,e as Ph,f as Dh,D as Eh,g as Mh,A as Ih,h as Fh,i as _h,k as Lh,l as Oh,m as $h,n as Uh,V as Bh,o as Vh,p as zh,q as Hh,r as qh,s as Wh,t as Kh,u as Gh,v as Yh,w as Zh,x as Xh,y as Qh,z as Jh,B as ep,E as tp,G as sp,H as ap,L as rp,J as np,K as ip,M as Xc,N as Qc,Q as op,U as Jc,W as ed,X as lp,Y as cp,Z as dp,_ as mp,$ as up,a0 as hp,a1 as pp,a2 as xp,a3 as gp,a4 as fp,a5 as yp,a6 as vp,a7 as bp,a8 as jp,a9 as Np,aa as wp,ab as Cp}from"./radix-vendor-C2EbRL2a.js";import{a as Sp,r as x,c as td,d as Pi,B as Ap,C as sd,X as ad,Y as rd,T as Di,L as nd,e as mn,P as Tp,f as kp,g as Rp,h as Pp,i as qo,j as Vr,k as zr,b as Dp}from"./charts-vendor-Cji9-Yri.js";import{a as id,f as od,b as he,d as Ep,c as Mp,e as Ip,s as Yt,g as Ei,h as Wo,i as Fp,j as ms,k as Wa,l as Mi,m as ld,n as zt,o as Wt,p as un,q as Cs,r as _p,t as Qn,u as Lp,v as Jn,w as Op,x as $p,y as Up,z as Bp,A as hn,B as Ko,C as Vp,D as cd,E as dd,F as Ii,G as Fi,H as zp,I as Hp,J as md}from"./utils-vendor-DHm03ykU.js";import{L as qp,C as Pe,a as ei,b as Ue,X as ft,H as Wp,c as ud,U as it,F as Se,d as je,S as Sa,P as _s,e as Kp,f as Gp,B as Ft,g as Ls,h as pn,i as hd,j as pd,k as Aa,l as Yp,m as sr,n as We,R as Et,I as ar,T as lt,o as Ee,p as ls,q as Zp,A as Nt,r as is,M as gs,s as Hr,t as as,u as Xp,D as ns,Z as _i,v as nt,w as Zt,x as xd,y as gd,z as Ka,E as Je,G as be,J as qr,O as ti,K as us,N as Qp,Q as Jp,V as ex,W as tx,Y as sx,_ as ax,$ as rx,a0 as nx,a1 as ix,a2 as ox,a3 as Li,a4 as fd,a5 as Os,a6 as Mr,a7 as Go,a8 as fr,a9 as yd,aa as lx,ab as Vs,ac as kt,ad as Na,ae as cx,af as dx,ag as mx,ah as Oi,ai as Wr,aj as It,ak as ux,al as hx,am as px,an as xx,ao as gx,ap as fx,aq as yx,ar as vd,as as Sr,at as Kr,au as si,av as vx,aw as bd,ax as bx,ay as jx,az as Nx,aA as $i,aB as jd,aC as wx,aD as Cx,aE as Gr,aF as Yr,aG as Ui,aH as Sx,aI as Nd,aJ as Yo,aK as zs,aL as Ax,aM as Tx,aN as Bi,aO as kx,aP as ha,aQ as wd,aR as Zo,aS as Rx,aT as Px,aU as Dx,aV as Cd,aW as Ex,aX as Mx,aY as Ix,aZ as Fx,a_ as _x}from"./ui-vendor-IyYM8dvF.js";import{l as Lx}from"./socket-vendor-TjCxX7sJ.js";import{c as Ta,a as Ox}from"./redux-vendor-tbZCm13o.js";import{u as rr,a as Hs,b as Sd,B as $x,R as Ux,c as ut}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 ai={},Xo=Sp;ai.createRoot=Xo.createRoot,ai.hydrateRoot=Xo.hydrateRoot;var Ad={exports:{}},Td={};/**
|
||
* @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 Bx(t,s){return t===s&&(t!==0||1/t===1/s)||t!==t&&s!==s}var Vx=typeof Object.is=="function"?Object.is:Bx,zx=nr.useSyncExternalStore,Hx=nr.useRef,qx=nr.useEffect,Wx=nr.useMemo,Kx=nr.useDebugValue;Td.useSyncExternalStoreWithSelector=function(t,s,a,r,n){var i=Hx(null);if(i.current===null){var o={hasValue:!1,value:null};i.current=o}else o=i.current;i=Wx(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,Vx(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=zx(t,i[0],i[1]);return qx(function(){o.hasValue=!0,o.value=l},[l]),Kx(l),l};Ad.exports=Td;var Gx=Ad.exports;function Yx(t){t()}function Zx(){let t=null,s=null;return{clear(){t=null,s=null},notify(){Yx(()=>{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 Qo={notify(){},get:()=>[]};function Xx(t,s){let a,r=Qo,n=0,i=!1;function o(y){m();const v=r.subscribe(y);let C=!1;return()=>{C||(C=!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=Zx())}function u(){n--,a&&n===0&&(a(),a=void 0,r.clear(),r=Qo)}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 Qx=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",Jx=Qx(),eg=()=>typeof navigator<"u"&&navigator.product==="ReactNative",tg=eg(),sg=()=>Jx||tg?x.useLayoutEffect:x.useEffect,ag=sg(),xn=Symbol.for("react-redux-context"),gn=typeof globalThis<"u"?globalThis:{};function rg(){if(!x.createContext)return{};const t=gn[xn]??(gn[xn]=new Map);let s=t.get(x.createContext);return s||(s=x.createContext(null),t.set(x.createContext,s)),s}var $s=rg();function ng(t){const{children:s,context:a,serverState:r,store:n}=t,i=x.useMemo(()=>{const c=Xx(n);return{store:n,subscription:c,getServerState:r?()=>r:void 0}},[n,r]),o=x.useMemo(()=>n.getState(),[n]);ag(()=>{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 ig=ng;function Vi(t=$s){return function(){return x.useContext(t)}}var kd=Vi();function Rd(t=$s){const s=t===$s?kd:Vi(t),a=()=>{const{store:r}=s();return r};return Object.assign(a,{withTypes:()=>a}),a}var og=Rd();function lg(t=$s){const s=t===$s?og:Rd(t),a=()=>s().dispatch;return Object.assign(a,{withTypes:()=>a}),a}var cg=lg(),dg=(t,s)=>t===s;function mg(t=$s){const s=t===$s?kd:Vi(t),a=(r,n={})=>{const{equalityFn:i=dg}=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=Gx.useSyncExternalStoreWithSelector(c.addNestedSub,l.getState,d||l.getState,m,i);return x.useDebugValue(u),u};return Object.assign(a,{withTypes:()=>a}),a}var ug=mg(),ri=function(t,s){return ri=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])},ri(t,s)};function hg(t,s){if(typeof s!="function"&&s!==null)throw new TypeError("Class extends value "+String(s)+" is not a constructor or null");ri(t,s);function a(){this.constructor=t}t.prototype=s===null?Object.create(s):(a.prototype=s.prototype,new a)}var Ir=function(){return Ir=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},Ir.apply(this,arguments)};var Js=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function zi(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function Hi(t,s){return t(s={exports:{}},s.exports),s.exports}var Zs=Hi(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()}});zi(Zs);var pg=zi(Hi(function(t,s){var a=Js&&Js.__awaiter||function(m,u,h,p){return new(h||(h=Promise))(function(g,y){function v(j){try{f(p.next(j))}catch(b){y(b)}}function C(j){try{f(p.throw(j))}catch(b){y(b)}}function f(j){j.done?g(j.value):new h(function(b){b(j.value)}).then(v,C)}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:C(0),throw:C(1),return:C(2)},typeof Symbol=="function"&&(y[Symbol.iterator]=function(){return this}),y;function C(f){return function(j){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(w){b=[6,w],p=0}finally{h=g=0}if(5&b[0])throw b[1];return{value:b[0]?b[1]:void 0,done:!0}}([f,j])}}},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,C,f,j;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]:(C=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:C,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,l(30)];case 4:return b.sent(),(f=v.getItemSync(y))!==null&&(j=JSON.parse(f)).id===this.id&&j.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,C;return r(this,function(f){switch(f.label){case 0:return[4,Zs.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?(Zs.default().unlock(h),[2]):((C=JSON.parse(v)).timeRefreshed=Date.now(),y.setItemSync(u,JSON.stringify(C)),Zs.default().unlock(h),this.refreshLockWhileAcquired(u,h),[2])):(Zs.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 C(){if(v||(window.removeEventListener("storage",C),m.removeFromWaiting(C),clearTimeout(f),v=!0),!g){g=!0;var j=50-(Date.now()-y);j>0?setTimeout(p,j):p(null)}}window.addEventListener("storage",C),m.addToWaiting(C);var f=setTimeout(C,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,Zs.default().lock(y.iat)];case 1:v.sent(),this.acquiredIatSet.delete(y.iat),h.removeItemSync(p),Zs.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 C=!1,f=0;f<g.length;f++){var j=g[f];if(j.includes(i)){var b=p.getItemSync(j);if(b!==null){var w=JSON.parse(b);(w.timeRefreshed===void 0&&w.timeAcquired<h||w.timeRefreshed!==void 0&&w.timeRefreshed<h)&&(p.removeItemSync(j),C=!0)}}}C&&m.notifyWaiters()},m.waiters=void 0,m}();s.default=d}));new TextEncoder;new TextDecoder;var ta=Hi(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}))}});zi(ta),ta.encode,ta.parse,ta.getAll;ta.get;ta.set;ta.remove;var Jo;(function(t){t.Code="code",t.ConnectCode="connect_code"})(Jo||(Jo={}));var el;(function(t){t.Bearer="Bearer",t.DPoP="DPoP"})(el||(el={}));new pg;var xg={isAuthenticated:!1,isLoading:!0,error:void 0,user:void 0},Bt=function(){throw new Error("You forgot to wrap your component in <Auth0Provider>.")},gg=Ir(Ir({},xg),{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}),fg=x.createContext(gg);(function(t){hg(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 yg=function(t){return t===void 0&&(t=fg),x.useContext(t)};const fn="idToken",yn="userData",vg=()=>!0;class ze{static setAccessToken(s){}static getAccessToken(){return null}static setRefreshToken(s){}static getRefreshToken(){return null}static setIdToken(s){sessionStorage.setItem(fn,s)}static getIdToken(){return sessionStorage.getItem(fn)}static setUserData(s){localStorage.setItem(yn,JSON.stringify(s))}static getUserData(){const s=localStorage.getItem(yn);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(yn),sessionStorage.removeItem(fn)}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 vg()}}function vn(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",ne=id.create({baseURL:Pd,headers:{"Content-Type":"application/json"},withCredentials:!0});ne.interceptors.request.use(t=>t,t=>Promise.reject(t));ne.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 id.post(`${Pd}/auth/refresh`,n?{}:{refreshToken:i},{withCredentials:!0}),c=(o.data.data||o.data).accessToken;return ne(s)}catch(i){return ze.clearAll(),window.location.href="/",Promise.reject(i)}}return Promise.reject(t)});async function bg(t,s){var a,r;try{const n=await ne.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 jg(){var r;const t={},a=(await ne.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 ne.get("/auth/me")).data;return s.data||s}async function Ng(){var t,s;try{await ne.post("/auth/logout",{},{withCredentials:!0})}catch(a){console.error("📡 Logout API error:",a),console.error("📡 Error details:",{message:a.message,status:(t=a.response)==null?void 0:t.status,data:(s=a.response)==null?void 0:s.data})}}const Dd=x.createContext(void 0);function wg({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__"),j=sessionStorage.getItem("__force_logout__");if(f==="true"||j==="true"){sessionStorage.removeItem("__logout_in_progress__"),sessionStorage.removeItem("__force_logout__"),ze.clearAll();try{localStorage.clear(),sessionStorage.clear()}catch(w){console.error("Error clearing storage:",w)}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 w=new URLSearchParams;b.has("okta_logged_out")&&w.set("okta_logged_out","true");const T=w.toString()?`/?${w.toString()}`:"/";window.history.replaceState({},document.title,T);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(w){console.error("Silent refresh failed:",w)}},j=10*60*1e3,b=setInterval(f,j);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 j=new URLSearchParams(window.location.search),b=j.get("code"),w=j.get("error");if(window.history.replaceState({},document.title,"/login/callback"),w){c(new Error(`Authentication error: ${w}`)),n(!1);return}if(!b){n(!1);return}try{n(!0),a(!1),c(null);const T=`${window.location.origin}/login/callback`,R=await bg(b,T);o(R.user),a(!0),c(null),window.history.replaceState({},document.title,"/")}catch(T){console.error("❌ Token exchange error in AuthContext:",T),c(T),a(!1),o(null),u.current=!1}finally{n(!1)}})()},[]);const h=async()=>{var j;if(d){n(!1);return}const f=!0;try{if(n(!0),f){const T=ze.getUserData();try{const R=await yr();o(R),ze.setUserData(R),a(!0)}catch(R){if(((j=R==null?void 0:R.response)==null?void 0:j.status)===401)try{await v();const k=await yr();o(k),ze.setUserData(k),a(!0)}catch{ze.clearAll(),a(!1),o(null)}else R!=null&&R.isConnectionError?T?(o(T),a(!0)):(a(!1),o(null)):(ze.clearAll(),a(!1),o(null))}return}const b=ze.getAccessToken(),w=ze.getUserData();if(!b){a(!1),o(null),n(!1);return}if(vn(b))try{await v();const T=ze.getAccessToken();if(T&&!vn(T)){const R=ze.getUserData();if(R)o(R),a(!0);else try{const k=await yr();o(k),ze.setUserData(k),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(w)o(w),a(!0);else try{const T=await yr();o(T),ze.setUserData(T),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",j="0oa2j8slwj5S4bG5k0h8",b=`${window.location.origin}/login/callback`,w="code",T="openid profile email",R=Math.random().toString(36).substring(7),k=new URLSearchParams(window.location.search),F=k.has("logout")||k.has("okta_logged_out");let N=`${f}/oauth2/default/v1/authorize?client_id=${j}&redirect_uri=${encodeURIComponent(b)}&response_type=${w}&scope=${encodeURIComponent(T)}&state=${R}`;F&&(N+="&prompt=login"),window.location.href=N}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 Ng()}catch(w){console.error("🚪 Logout API error:",w),console.warn("🚪 Backend logout failed - httpOnly cookies may not be cleared")}const f=sessionStorage.getItem("__logout_in_progress__"),j=sessionStorage.getItem("__force_logout__");ze.clearAll(),f&&sessionStorage.setItem("__logout_in_progress__",f),j&&sessionStorage.setItem("__force_logout__",j),await new Promise(w=>setTimeout(w,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 j=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(j)}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&&!vn(f))return f;try{return await v(),ze.getAccessToken()}catch{return null}},v=async()=>{try{const j=await jg();return}catch(j){throw ze.clearAll(),a(!1),o(null),j}},C={isAuthenticated:s,isLoading:r,user:i,error:l,login:p,logout:g,getAccessTokenSilently:y,refreshTokenSilently:v};return e.jsx(Dd.Provider,{value:C,children:t})}function Cg({children:t}){return e.jsx(wg,{children:t})}function Mt(){const t=x.useContext(Dd);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t}function Xs(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 tl=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,sl=td,Ed=(t,s)=>a=>{var r;if((s==null?void 0:s.variants)==null)return sl(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=tl(m)||tl(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 sl(t,o,c,a==null?void 0:a.class,a==null?void 0:a.className)},qi="-",Sg=t=>{const s=Tg(t),{conflictingClassGroups:a,conflictingClassGroupModifiers:r}=t;return{getClassGroupId:o=>{const l=o.split(qi);return l[0]===""&&l.length!==1&&l.shift(),Md(l,s)||Ag(o)},getConflictingClassGroupIds:(o,l)=>{const c=a[o]||[];return l&&r[o]?[...c,...r[o]]:c}}},Md=(t,s)=>{var o;if(t.length===0)return s.classGroupId;const a=t[0],r=s.nextPart.get(a),n=r?Md(t.slice(1),r):void 0;if(n)return n;if(s.validators.length===0)return;const i=t.join(qi);return(o=s.validators.find(({validator:l})=>l(i)))==null?void 0:o.classGroupId},al=/^\[(.+)\]$/,Ag=t=>{if(al.test(t)){const s=al.exec(t)[1],a=s==null?void 0:s.substring(0,s.indexOf(":"));if(a)return"arbitrary.."+a}},Tg=t=>{const{theme:s,prefix:a}=t,r={nextPart:new Map,validators:[]};return Rg(Object.entries(t.classGroups),a).forEach(([i,o])=>{ni(o,r,i,s)}),r},ni=(t,s,a,r)=>{t.forEach(n=>{if(typeof n=="string"){const i=n===""?s:rl(s,n);i.classGroupId=a;return}if(typeof n=="function"){if(kg(n)){ni(n(r),s,a,r);return}s.validators.push({validator:n,classGroupId:a});return}Object.entries(n).forEach(([i,o])=>{ni(o,rl(s,i),a,r)})})},rl=(t,s)=>{let a=t;return s.split(qi).forEach(r=>{a.nextPart.has(r)||a.nextPart.set(r,{nextPart:new Map,validators:[]}),a=a.nextPart.get(r)}),a},kg=t=>t.isThemeGetter,Rg=(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,Pg=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)}}},Id="!",Dg=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 C=l[v];if(d===0){if(C===n&&(r||l.slice(v,v+i)===s)){c.push(l.slice(m,v)),m=v+i;continue}if(C==="/"){u=v;continue}}C==="["?d++:C==="]"&&d--}const h=c.length===0?l:l.substring(m),p=h.startsWith(Id),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},Eg=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},Mg=t=>({cache:Pg(t.cacheSize),parseClassName:Dg(t),...Sg(t)}),Ig=/\s+/,Fg=(t,s)=>{const{parseClassName:a,getClassGroupId:r,getConflictingClassGroupIds:n}=s,i=[],o=t.trim().split(Ig);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=Eg(m).join(":"),C=u?v+Id:v,f=C+y;if(i.includes(f))continue;i.push(f);const j=n(y,g);for(let b=0;b<j.length;++b){const w=j[b];i.push(C+w)}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=Fd(s))&&(r&&(r+=" "),r+=a);return r}const Fd=t=>{if(typeof t=="string")return t;let s,a="";for(let r=0;r<t.length;r++)t[r]&&(s=Fd(t[r]))&&(a&&(a+=" "),a+=s);return a};function Lg(t,...s){let a,r,n,i=o;function o(c){const d=s.reduce((m,u)=>u(m),t());return a=Mg(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=Fg(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},_d=/^\[(?:([a-z-]+):)?(.+)\]$/i,Og=/^\d+\/\d+$/,$g=new Set(["px","full","screen"]),Ug=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Bg=/\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$/,Vg=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,zg=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Hg=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,js=t=>va(t)||$g.has(t)||Og.test(t),ks=t=>ka(t,"length",Qg),va=t=>!!t&&!Number.isNaN(Number(t)),bn=t=>ka(t,"number",va),_a=t=>!!t&&Number.isInteger(Number(t)),qg=t=>t.endsWith("%")&&va(t.slice(0,-1)),Oe=t=>_d.test(t),Rs=t=>Ug.test(t),Wg=new Set(["length","size","percentage"]),Kg=t=>ka(t,Wg,Ld),Gg=t=>ka(t,"position",Ld),Yg=new Set(["image","url"]),Zg=t=>ka(t,Yg,ef),Xg=t=>ka(t,"",Jg),La=()=>!0,ka=(t,s,a)=>{const r=_d.exec(t);return r?r[1]?typeof s=="string"?r[1]===s:s.has(r[1]):a(r[2]):!1},Qg=t=>Bg.test(t)&&!Vg.test(t),Ld=()=>!1,Jg=t=>zg.test(t),ef=t=>Hg.test(t),tf=()=>{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"),C=Ye("opacity"),f=Ye("padding"),j=Ye("saturate"),b=Ye("scale"),w=Ye("sepia"),T=Ye("skew"),R=Ye("space"),k=Ye("translate"),F=()=>["auto","contain","none"],N=()=>["auto","hidden","clip","visible","scroll"],A=()=>["auto",Oe,s],I=()=>[Oe,s],V=()=>["",js,ks],_=()=>["auto",va,Oe],L=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],S=()=>["solid","dashed","dotted","double","none"],M=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],P=()=>["start","end","center","between","around","evenly","stretch"],E=()=>["","0",Oe],H=()=>["auto","avoid","all","avoid-page","page","left","right","column"],q=()=>[va,Oe];return{cacheSize:500,separator:":",theme:{colors:[La],spacing:[js,ks],blur:["none","",Rs,Oe],brightness:q(),borderColor:[t],borderRadius:["none","","full",Rs,Oe],borderSpacing:I(),borderWidth:V(),contrast:q(),grayscale:E(),hueRotate:q(),invert:E(),gap:I(),gradientColorStops:[t],gradientColorStopPositions:[qg,ks],inset:A(),margin:A(),opacity:q(),padding:I(),saturate:q(),scale:q(),sepia:E(),skew:q(),space:I(),translate:I()},classGroups:{aspect:[{aspect:["auto","square","video",Oe]}],container:["container"],columns:[{columns:[Rs]}],"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(),Oe]}],overflow:[{overflow:N()}],"overflow-x":[{"overflow-x":N()}],"overflow-y":[{"overflow-y":N()}],overscroll:[{overscroll:F()}],"overscroll-x":[{"overscroll-x":F()}],"overscroll-y":[{"overscroll-y":F()}],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,Oe]}],basis:[{basis:A()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Oe]}],grow:[{grow:E()}],shrink:[{shrink:E()}],order:[{order:["first","last","none",_a,Oe]}],"grid-cols":[{"grid-cols":[La]}],"col-start-end":[{col:["auto",{span:["full",_a,Oe]},Oe]}],"col-start":[{"col-start":_()}],"col-end":[{"col-end":_()}],"grid-rows":[{"grid-rows":[La]}],"row-start-end":[{row:["auto",{span:[_a,Oe]},Oe]}],"row-start":[{"row-start":_()}],"row-end":[{"row-end":_()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Oe]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Oe]}],gap:[{gap:[h]}],"gap-x":[{"gap-x":[h]}],"gap-y":[{"gap-y":[h]}],"justify-content":[{justify:["normal",...P()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...P(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...P(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[f]}],px:[{px:[f]}],py:[{py:[f]}],ps:[{ps:[f]}],pe:[{pe:[f]}],pt:[{pt:[f]}],pr:[{pr:[f]}],pb:[{pb:[f]}],pl:[{pl:[f]}],m:[{m:[v]}],mx:[{mx:[v]}],my:[{my:[v]}],ms:[{ms:[v]}],me:[{me:[v]}],mt:[{mt:[v]}],mr:[{mr:[v]}],mb:[{mb:[v]}],ml:[{ml:[v]}],"space-x":[{"space-x":[R]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[R]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",Oe,s]}],"min-w":[{"min-w":[Oe,s,"min","max","fit"]}],"max-w":[{"max-w":[Oe,s,"none","full","min","max","fit","prose",{screen:[Rs]},Rs]}],h:[{h:[Oe,s,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[Oe,s,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[Oe,s,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[Oe,s,"auto","min","max","fit"]}],"font-size":[{text:["base",Rs,ks]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",bn]}],"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",Oe]}],"line-clamp":[{"line-clamp":["none",va,bn]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",js,Oe]}],"list-image":[{"list-image":["none",Oe]}],"list-style-type":[{list:["none","disc","decimal",Oe]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[t]}],"placeholder-opacity":[{"placeholder-opacity":[C]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[t]}],"text-opacity":[{"text-opacity":[C]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...S(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",js,ks]}],"underline-offset":[{"underline-offset":["auto",js,Oe]}],"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:I()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Oe]}],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",Oe]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[C]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...L(),Gg]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",Kg]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},Zg]}],"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":[C]}],"border-style":[{border:[...S(),"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":[C]}],"divide-style":[{divide:S()}],"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:["",...S()]}],"outline-offset":[{"outline-offset":[js,Oe]}],"outline-w":[{outline:[js,ks]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:V()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[C]}],"ring-offset-w":[{"ring-offset":[js,ks]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",Rs,Xg]}],"shadow-color":[{shadow:[La]}],opacity:[{opacity:[C]}],"mix-blend":[{"mix-blend":[...M(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":M()}],filter:[{filter:["","none"]}],blur:[{blur:[a]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",Rs,Oe]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[m]}],invert:[{invert:[u]}],saturate:[{saturate:[j]}],sepia:[{sepia:[w]}],"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":[C]}],"backdrop-saturate":[{"backdrop-saturate":[j]}],"backdrop-sepia":[{"backdrop-sepia":[w]}],"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",Oe]}],duration:[{duration:q()}],ease:[{ease:["linear","in","out","in-out",Oe]}],delay:[{delay:q()}],animate:[{animate:["none","spin","ping","pulse","bounce",Oe]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[b]}],"scale-x":[{"scale-x":[b]}],"scale-y":[{"scale-y":[b]}],rotate:[{rotate:[_a,Oe]}],"translate-x":[{"translate-x":[k]}],"translate-y":[{"translate-y":[k]}],"skew-x":[{"skew-x":[T]}],"skew-y":[{"skew-y":[T]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Oe]}],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",Oe]}],"caret-color":[{caret:[t]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":I()}],"scroll-mx":[{"scroll-mx":I()}],"scroll-my":[{"scroll-my":I()}],"scroll-ms":[{"scroll-ms":I()}],"scroll-me":[{"scroll-me":I()}],"scroll-mt":[{"scroll-mt":I()}],"scroll-mr":[{"scroll-mr":I()}],"scroll-mb":[{"scroll-mb":I()}],"scroll-ml":[{"scroll-ml":I()}],"scroll-p":[{"scroll-p":I()}],"scroll-px":[{"scroll-px":I()}],"scroll-py":[{"scroll-py":I()}],"scroll-ps":[{"scroll-ps":I()}],"scroll-pe":[{"scroll-pe":I()}],"scroll-pt":[{"scroll-pt":I()}],"scroll-pr":[{"scroll-pr":I()}],"scroll-pb":[{"scroll-pb":I()}],"scroll-pl":[{"scroll-pl":I()}],"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",Oe]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[js,ks,bn]}],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"]}}},sf=Lg(tf);function le(...t){return sf(td(t))}const Ga=Ed("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"}}),D=x.forwardRef(({className:t,variant:s,size:a,asChild:r=!1,...n},i)=>{const o=r?qc:"button";return e.jsx(o,{"data-slot":"button",className:le(Ga({variant:s,size:a,className:t})),ref:i,...n})});D.displayName="Button";function W({className:t,...s}){return e.jsx("div",{"data-slot":"card",className:le("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border",t),...s})}function ee({className:t,...s}){return e.jsx("div",{"data-slot":"card-header",className:le("@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 te({className:t,...s}){return e.jsx("h4",{"data-slot":"card-title",className:le("leading-none",t),...s})}function pe({className:t,...s}){return e.jsx("p",{"data-slot":"card-description",className:le("text-muted-foreground",t),...s})}function K({className:t,...s}){return e.jsx("div",{"data-slot":"card-content",className:le("px-6 [&:last-child]:pb-6",t),...s})}const Wi="/assets/Re_Logo-By51taPS.png";function af(){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(W,{className:"w-full max-w-md shadow-xl",children:[e.jsx(ee,{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:Wi,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(K,{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(D,{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(qp,{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 Od(){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:Wi,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(ei,{className:"w-16 h-16 text-green-500"})}),e.jsx(ei,{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 rf=Ed("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 X({className:t,variant:s,asChild:a=!1,...r}){const n=a?qc:"span";return e.jsx(n,{"data-slot":"badge",className:le(rf({variant:s}),t),...r})}function nf({isOpen:t,onClose:s}){const{user:a,isAuthenticated:r,isLoading:n,error:i}=yg();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(W,{className:"w-full max-w-2xl max-h-[90vh] overflow-auto",children:[e.jsx(ee,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(te,{children:"Authentication Debug Information"}),e.jsx(D,{variant:"ghost",size:"icon",onClick:s,children:e.jsx(ft,{className:"h-4 w-4"})})]})}),e.jsxs(K,{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(X,{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(Wc,{ref:a,"data-slot":"avatar",className:le("relative flex size-10 shrink-0 overflow-hidden rounded-full",t),...s}));bt.displayName=Wc.displayName;const Xr=x.forwardRef(({className:t,...s},a)=>e.jsx(Kc,{ref:a,"data-slot":"avatar-image",className:le("aspect-square size-full",t),...s}));Xr.displayName=Kc.displayName;const jt=x.forwardRef(({className:t,...s},a)=>e.jsx(Gc,{ref:a,"data-slot":"avatar-fallback",className:le("bg-muted flex size-full items-center justify-center rounded-full",t),...s}));jt.displayName=Gc.displayName;function nl({...t}){return e.jsx(Ch,{"data-slot":"dropdown-menu",...t})}function il({...t}){return e.jsx(Sh,{"data-slot":"dropdown-menu-trigger",...t})}function ol({className:t,sideOffset:s=4,...a}){return e.jsx(Ah,{children:e.jsx(Th,{"data-slot":"dropdown-menu-content",sideOffset:s,className:le("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 jn({className:t,inset:s,variant:a="default",...r}){return e.jsx(kh,{"data-slot":"dropdown-menu-item","data-inset":s,"data-variant":a,className:le("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 of({...t}){return e.jsx(Ph,{"data-slot":"alert-dialog",...t})}function lf({...t}){return e.jsx(Rh,{"data-slot":"alert-dialog-portal",...t})}const $d=x.forwardRef(({className:t,...s},a)=>e.jsx(Yc,{"data-slot":"alert-dialog-overlay",className:le("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}));$d.displayName=Yc.displayName;const Ud=x.forwardRef(({className:t,...s},a)=>e.jsxs(lf,{children:[e.jsx($d,{}),e.jsx(Zc,{"data-slot":"alert-dialog-content",ref:a,className:le("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})]}));Ud.displayName=Zc.displayName;function cf({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-header",className:le("flex flex-col gap-2 text-center sm:text-left",t),...s})}function df({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-footer",className:le("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s})}function mf({className:t,...s}){return e.jsx(Dh,{"data-slot":"alert-dialog-title",className:le("text-lg font-semibold",t),...s})}function uf({className:t,...s}){return e.jsx(Eh,{"data-slot":"alert-dialog-description",className:le("text-muted-foreground text-sm",t),...s})}function hf({className:t,...s}){return e.jsx(Ih,{className:le(Ga(),t),...s})}function pf({className:t,...s}){return e.jsx(Mh,{className:le(Ga({variant:"outline"}),t),...s})}const Ds={async list(t){return(await ne.get("/notifications",{params:t})).data},async getUnreadCount(){return(await ne.get("/notifications/unread-count")).data},async markAsRead(t){return(await ne.patch(`/notifications/${t}/read`)).data},async markAllAsRead(){return(await ne.post("/notifications/mark-all-read")).data},async delete(t){return(await ne.delete(`/notifications/${t}`)).data}},xf=async()=>(await ne.get("/notifications/subscriptions")).data.data.subscriptions;let Gs=null;function gf(){return"https://re-workflow-nt-dev.siplsolutions.com"}function Ya(t){const s=gf();return Gs||(Gs=Lx(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 ii(t,s,a){a?t.emit("join:request",{requestId:s,userId:a}):t.emit("join:request",s)}function Bd(t,s){t.emit("leave:request",s)}function ff(t,s){t.emit("join:user",{userId:s})}function Pt({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 w,T;try{if(y!=null&&y.displayName&&typeof y.displayName=="string"){const R=y.displayName.split(" ").filter(Boolean);return R.length>=2?`${((w=R[0])==null?void 0:w[0])||""}${((T=R[R.length-1])==null?void 0:T[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(R){return console.error("[PageLayout] Error getting user initials:",R),"U"}},C=x.useMemo(()=>{const w=[{id:"dashboard",label:"Dashboard",icon:Wp},{id:"requests",label:"All Requests",icon:ud}];return w.push({id:"my-requests",label:"My Requests",icon:it},{id:"open-requests",label:"Open Requests",icon:Se},{id:"closed-requests",label:"Closed Requests",icon:je},{id:"shared-summaries",label:"Shared Summary",icon:Sa}),w},[]),f=()=>{o(!i)},j=async w=>{var T;try{if(w.isRead||(await Ds.markAsRead(w.notificationId),m(R=>R.map(k=>k.notificationId===w.notificationId?{...k,isRead:!0}:k)),h(R=>Math.max(0,R-1))),w.actionUrl&&a){const R=(T=w.metadata)==null?void 0:T.requestNumber;if(R){let k=`request/${R}`;(w.notificationType==="mention"||w.notificationType==="comment"||w.notificationType==="worknote")&&(k+="?tab=worknotes"),a(k)}}g(!1)}catch(R){console.error("[PageLayout] Error handling notification click:",R)}},b=async()=>{try{await Ds.markAllAsRead(),m(w=>w.map(T=>({...T,isRead:!0}))),h(0)}catch(w){console.error("[PageLayout] Error marking all as read:",w)}};return x.useEffect(()=>{const w=y==null?void 0:y.userId;if(!w)return;let T=!0;(async()=>{var F,N;try{const A=await Ds.list({page:1,limit:4,unreadOnly:!1});if(!T)return;const I=((F=A.data)==null?void 0:F.notifications)||[];m(I),h(((N=A.data)==null?void 0:N.unreadCount)||0)}catch(A){console.error("[PageLayout] Failed to fetch notifications:",A)}})();const k=Ya();if(k){ff(k,w);const F=N=>{T&&(m(A=>[N.notification,...A].slice(0,4)),h(A=>A+1))};return k.on("notification:new",F),()=>{T=!1,k.off("notification:new",F)}}return()=>{T=!1}},[y]),x.useEffect(()=>{const w=()=>{window.innerWidth>=768?o(!0):o(!1)};return w(),window.addEventListener("resize",w),()=>window.removeEventListener("resize",w)},[]),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:Wi,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:C.map(w=>e.jsxs("button",{onClick:()=>{a==null||a(w.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===w.id?"bg-re-green text-white font-medium":"text-gray-300 hover:bg-gray-900 hover:text-white"}`,children:[e.jsx(w.icon,{className:"w-4 h-4 shrink-0"}),e.jsx("span",{className:"truncate",children:w.label})]},w.id))}),e.jsx("div",{className:"mt-6 pt-6 border-t border-gray-800 px-3",children:e.jsxs(D,{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(D,{variant:"ghost",size:"icon",onClick:f,className:"shrink-0 h-10 w-10 sidebar-toggle",children:i?e.jsx(Kp,{className:"w-5 h-5 text-gray-600"}):e.jsx(Gp,{className:"w-5 h-5 text-gray-600"})})}),e.jsxs("div",{className:"flex items-center gap-4 shrink-0",children:[e.jsxs(D,{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(nl,{open:p,onOpenChange:g,children:[e.jsx(il,{asChild:!0,children:e.jsxs(D,{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(X,{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(ol,{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(D,{variant:"ghost",size:"sm",className:"text-xs text-blue-600 hover:text-blue-700 h-auto p-1",onClick:w=>{w.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(w=>e.jsx("div",{className:`p-3 hover:bg-gray-50 cursor-pointer transition-colors ${w.isRead?"":"bg-blue-50"}`,onClick:()=>j(w),children:e.jsxs("div",{className:"flex gap-2",children:[!w.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 ${w.isRead?"font-medium":"font-semibold"}`,children:w.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-2",children:w.message}),e.jsx("p",{className:"text-xs text-gray-400 mt-1",children:od(new Date(w.createdAt),{addSuffix:!0})})]})]})},w.notificationId))})}),d.length>0&&e.jsx("div",{className:"p-2 border-t",children:e.jsx(D,{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(nl,{children:[e.jsx(il,{asChild:!0,children:e.jsxs(bt,{className:"cursor-pointer shrink-0 h-10 w-10",children:[e.jsx(Xr,{src:(y==null?void 0:y.picture)||""}),e.jsx(jt,{className:"bg-re-green text-white text-sm",children:v()})]})}),e.jsxs(ol,{align:"end",children:[e.jsxs(jn,{onClick:()=>a==null?void 0:a("profile"),children:[e.jsx(it,{className:"w-4 h-4 mr-2"}),"Profile"]}),e.jsxs(jn,{onClick:()=>a==null?void 0:a("settings"),children:[e.jsx(Ls,{className:"w-4 h-4 mr-2"}),"Settings"]}),e.jsxs(jn,{onClick:()=>c(!0),className:"text-red-600 focus:text-red-600",children:[e.jsx(pn,{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(of,{open:l,onOpenChange:c,children:e.jsxs(Ud,{children:[e.jsxs(cf,{children:[e.jsxs(mf,{className:"flex items-center gap-2",children:[e.jsx(pn,{className:"w-5 h-5 text-red-600"}),"Confirm Logout"]}),e.jsx(uf,{className:"pt-2",children:"Are you sure you want to logout? You will need to sign in again to access your account."})]}),e.jsxs(df,{children:[e.jsx(pf,{onClick:()=>c(!1),children:"Cancel"}),e.jsxs(hf,{onClick:async()=>{if(c(!1),n)try{await n()}catch(w){console.error("🔴 Error calling onLogout:",w)}else console.error("🔴 ERROR: onLogout is undefined!")},className:"bg-red-600 hover:bg-red-700 text-white focus:ring-red-600",children:[e.jsx(pn,{className:"w-4 h-4 mr-2"}),"Logout"]})]})]})})]})}const ir=()=>cg(),Ra=ug,yf=()=>{try{const t=localStorage.getItem("dashboard_viewAsUser");return t?JSON.parse(t):!1}catch{return!1}},vf={viewAsUser:yf()},Vd=Ta({name:"dashboard",initialState:vf,reducers:{setViewAsUser:(t,s)=>{t.viewAsUser=s.payload,localStorage.setItem("dashboard_viewAsUser",JSON.stringify(s.payload))}}}),{setViewAsUser:bf}=Vd.actions;function jf(){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 Nf(){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,C,f)=>{s({page:v,totalPages:C,totalRecords:f})},[]),d=x.useCallback((v,C,f)=>{r({page:v,totalPages:C,totalRecords:f})},[]),m=x.useCallback((v,C,f)=>{i({page:v,totalPages:C,totalRecords:f})},[]),u=x.useCallback((v,C,f)=>{l({page:v,totalPages:C,totalRecords:f})},[]),h=x.useCallback((v,C)=>{v>=1&&v<=t.totalPages&&(s(f=>({...f,page:v})),C(v))},[t.totalPages]),p=x.useCallback((v,C)=>{v>=1&&v<=a.totalPages&&(r(f=>({...f,page:v})),C(v))},[a.totalPages]),g=x.useCallback((v,C)=>{v>=1&&v<=n.totalPages&&(i(f=>({...f,page:v})),C(v))},[n.totalPages]),y=x.useCallback((v,C)=>{v>=1&&v<=o.totalPages&&(l(f=>({...f,page:v})),C(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 wf{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 ne.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 ne.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 ne.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 ne.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 ne.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 ne.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 ne.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 ne.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 ne.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 ne.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 ne.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 ne.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 ne.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 ne.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 ne.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 ne.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 ne.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 ne.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 ne.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 wf;function Cf({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([]),[C,f]=x.useState([]),[j,b]=x.useState(null),[w,T]=x.useState([]),[R,k]=x.useState(!0),[F,N]=x.useState(!1),A=x.useRef(o);A.current=o;const I=x.useCallback(async(M=!1)=>{try{M?N(!0):k(!0);const P=[He.getKPIs(r,n,i,s),He.getRecentActivity(1,10,s),He.getCriticalRequests(1,10,s),He.getUpcomingDeadlines(1,10,s)],E=!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)]:[],[q,J,B]=await Promise.all([Promise.all(P),E,Promise.all(H)]),oe=q[0],ge=q[1],z=q[2],re=q[3];if(!t&&J&&(oe.requestVolume=J),c(oe),m(ge.activities),A.current.activity(ge.pagination.currentPage,ge.pagination.totalPages,ge.pagination.totalRecords),h(z.criticalRequests),A.current.critical(z.pagination.currentPage,z.pagination.totalPages,z.pagination.totalRecords),f(re.deadlines),A.current.deadlines(re.pagination.currentPage,re.pagination.totalPages,re.pagination.totalRecords),t&&B.length>=4){const ye=B[0],G=B[1],Q=B[2],ie=B[3];g(ye),v(G),b(Q),T(ie.performance),A.current.approver(ie.pagination.currentPage,ie.pagination.totalPages,ie.pagination.totalRecords)}else t||(g([]),v([]),b(null),T([]))}catch(P){console.error("Failed to fetch dashboard data:",P)}finally{k(!1),N(!1)}},[t,s,a,r,n,i]),V=x.useCallback(async(M=1)=>{try{const P=await He.getRecentActivity(M,10,s);m(P.activities),A.current.activity(P.pagination.currentPage,P.pagination.totalPages,P.pagination.totalRecords)}catch(P){console.error("Failed to fetch recent activities:",P)}},[s]),_=x.useCallback(async(M=1)=>{try{const P=await He.getCriticalRequests(M,10,s);h(P.criticalRequests),A.current.critical(P.pagination.currentPage,P.pagination.totalPages,P.pagination.totalRecords)}catch(P){console.error("Failed to fetch critical requests:",P)}},[s]),L=x.useCallback(async(M=1)=>{try{const P=await He.getUpcomingDeadlines(M,10,s);f(P.deadlines),A.current.deadlines(P.pagination.currentPage,P.pagination.totalPages,P.pagination.totalRecords)}catch(P){console.error("Failed to fetch upcoming deadlines:",P)}},[s]),S=x.useCallback(async(M=1)=>{try{const P=await He.getApproverPerformance(r,M,10,n,i);T(P.performance),A.current.approver(P.pagination.currentPage,P.pagination.totalPages,P.pagination.totalRecords)}catch(P){console.error("Failed to fetch approver performance:",P)}},[r,n,i]);return{kpis:l,recentActivity:d,criticalRequests:u,departmentStats:p,priorityDistribution:y,upcomingDeadlines:C,aiRemarkUtilization:j,approverPerformance:w,loading:R,refreshing:F,fetchDashboardData:I,fetchRecentActivities:V,fetchCriticalRequests:_,fetchUpcomingDeadlines:L,fetchApproverPerformance:S}}const Ns={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 Sf{constructor(){dn(this,"config",null);dn(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 ne.get("/config"),r=((s=a.data)==null?void 0:s.data)||a.data;return{...Ns,...r,workingHours:{...Ns.workingHours,...r.workingHours},tat:{...Ns.tat,...r.tat},upload:{...Ns.upload,...r.upload},workflow:{...Ns.workflow,...r.workflow},workNotes:{...Ns.workNotes,...r.workNotes},features:{...Ns.features,...r.features},ui:{...Ns.ui,...r.ui}}}catch(a){return console.error("[ConfigService] ⚠️ Failed to fetch config from server, using defaults:",a),Ns}}async refreshConfig(){return this.config=null,this.loading=null,this.getConfig()}getCachedConfig(){return this.config}isLoaded(){return this.config!==null}}const Af=new Sf;let Tf=9,kf=18,Rf=1,Pf=5,ll=!1;async function Df(){if(!ll)try{const t=await Af.getConfig();Tf=t.workingHours.START_HOUR,kf=t.workingHours.END_HOUR,Rf=t.workingHours.START_DAY,Pf=t.workingHours.END_DAY,ll=!0}catch{console.warn("[SLA Tracker] ⚠️ Using default working hours (9 AM - 6 PM)")}}Df().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 Ef(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 Mf(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 If(){const[t,s]=x.useState(!1),[a,r]=x.useState(!1),n=x.useCallback(async(o,l,c)=>{try{s(!0),await Mf(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 Ef(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(Fh,{"data-slot":"switch",className:le("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(_h,{"data-slot":"switch-thumb",className:le("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 Z({className:t,...s}){return e.jsx(Lh,{"data-slot":"label",className:le("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 Ff({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(W,{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(K,{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(hd,{className:`w-3 h-3 sm:w-3.5 sm:h-3.5 ${a?"text-gray-300":"text-red-600"}`}),e.jsx(Z,{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(Z,{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(D,{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 Ae({...t}){return e.jsx(Oh,{"data-slot":"select",...t})}function Te({...t}){return e.jsx(Bh,{"data-slot":"select-value",...t})}function ke({className:t,size:s="default",children:a,...r}){return e.jsxs($h,{"data-slot":"select-trigger","data-size":s,className:le("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(Uh,{asChild:!0,children:e.jsx(pd,{className:"size-4 opacity-50"})})]})}function Re({className:t,children:s,position:a="popper",...r}){return e.jsx(Vh,{children:e.jsxs(zh,{"data-slot":"select-content",className:le("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(Hh,{className:le("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(Lf,{})]})})}function O({className:t,children:s,...a}){return e.jsxs(qh,{"data-slot":"select-item",className:le("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(Wh,{children:e.jsx(Aa,{className:"size-4"})})}),e.jsx(Kh,{children:s})]})}function _f({className:t,...s}){return e.jsx(Gh,{"data-slot":"select-scroll-up-button",className:le("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(Yp,{className:"size-4"})})}function Lf({className:t,...s}){return e.jsx(Yh,{"data-slot":"select-scroll-down-button",className:le("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(pd,{className:"size-4"})})}function ct({className:t,orientation:s="horizontal",decorative:a=!0,...r}){return e.jsx(Zh,{"data-slot":"separator-root",decorative:a,orientation:s,className:le("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 Es({...t}){return e.jsx(Xh,{"data-slot":"popover",...t})}function Ms({...t}){return e.jsx(Qh,{"data-slot":"popover-trigger",...t})}function Is({className:t,align:s="center",sideOffset:a=4,...r}){return e.jsx(Jh,{children:e.jsx(ep,{"data-slot":"popover-content",align:s,sideOffset:a,className:le("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",t),...r})})}function xe({className:t,type:s,...a}){return e.jsx("input",{type:s,"data-slot":"input",className:le("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 Of({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(W,{className:"shadow-md","data-testid":"dashboard-filters-bar",children:e.jsx(K,{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(X,{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(Ae,{value:s,onValueChange:o,"data-testid":"date-range-select",children:[e.jsx(ke,{className:"w-[140px]",children:e.jsx(Te,{placeholder:"Select period"})}),e.jsxs(Re,{children:[e.jsx(O,{value:"all",children:"All Time"}),e.jsx(O,{value:"today",children:"Today"}),e.jsx(O,{value:"week",children:"This Week"}),e.jsx(O,{value:"month",children:"This Month"}),e.jsx(O,{value:"last7days",children:"Last 7 Days"}),e.jsx(O,{value:"last30days",children:"Last 30 Days"}),e.jsx(O,{value:"custom",children:"Custom Range"})]})]}),s==="custom"&&e.jsxs(Es,{open:n,onOpenChange:d,children:[e.jsx(Ms,{asChild:!0,children:e.jsxs(D,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(We,{className:"w-4 h-4"}),a&&r?`${he(a,"MMM d, yyyy")} - ${he(r,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Is,{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(Z,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(xe,{id:"start-date",type:"date",value:a?he(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:he(new Date,"yyyy-MM-dd"),className:"w-full","data-testid":"start-date-input"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Z,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(xe,{id:"end-date",type:"date",value:r?he(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?he(a,"yyyy-MM-dd"):void 0,max:he(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(D,{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(D,{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(Ae,{value:s,onValueChange:p=>o(p),"data-testid":"date-range-select-user",children:[e.jsx(ke,{className:"w-[140px]",children:e.jsx(Te,{placeholder:"Select period"})}),e.jsxs(Re,{children:[e.jsx(O,{value:"all",children:"All Time"}),e.jsx(O,{value:"today",children:"Today"}),e.jsx(O,{value:"week",children:"This Week"}),e.jsx(O,{value:"month",children:"This Month"}),e.jsx(O,{value:"last7days",children:"Last 7 Days"}),e.jsx(O,{value:"last30days",children:"Last 30 Days"}),e.jsx(O,{value:"custom",children:"Custom Range"})]})]})]}),e.jsx(ct,{orientation:"vertical",className:"h-6 hidden sm:block"}),e.jsxs(D,{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(W,{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(ee,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(te,{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(K,{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 hs({className:t,value:s,indicatorClassName:a,...r}){return e.jsx(tp,{"data-slot":"progress",className:le("bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",t),...r,children:e.jsx(sp,{"data-slot":"progress-indicator",className:le("bg-primary h-full w-full flex-1 transition-all",a),style:{transform:`translateX(-${100-(s||0)}%)`}})})}function $f({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:Se,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:lt,iconBgColor:"bg-green-50",iconColor:"text-green-600",testId:"kpi-sla-compliance",onClick:()=>i(o()),children:e.jsxs("div",{className:"flex flex-col flex-1",children:[e.jsx(hs,{value:(t==null?void 0:t.tatEfficiency.avgTATCompliance)||0,className:"h-2 mb-2","data-testid":"sla-progress-bar"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-auto",children:[e.jsx(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:Ee,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 Uf({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:Se,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:Ee,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(hs,{value:u,className:"h-4 bg-gray-200 [&>div]:bg-green-600","data-testid":"success-rate-progress"}),e.jsxs("div",{className:"flex justify-between items-center text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Rejected"}),e.jsx("span",{className:"font-semibold text-red-600",children:(t==null?void 0:t.requestVolume.rejectedRequests)||0})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-auto",children:[e.jsxs("div",{className:"bg-green-50 rounded-lg p-2 text-center",children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Approved"}),e.jsx("div",{className:"text-lg font-semibold text-green-600",children:(t==null?void 0:t.requestVolume.approvedRequests)||0})]}),e.jsxs("div",{className:"bg-red-50 rounded-lg p-2 text-center",children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Rejected"}),e.jsx("div",{className:"text-lg font-semibold text-red-600",children:(t==null?void 0:t.requestVolume.rejectedRequests)||0})]})]})]})})]})}const Bf=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)))},Vf=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 zf({alert:t,onNavigate:s,testId:a="critical-alert-card"}){const r=Bf(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(X,{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(X,{variant:"outline",className:"text-xs bg-white border-red-200 text-red-700 font-medium whitespace-nowrap","data-testid":`${a}-remaining-time`,children:Vf(t)})]}),e.jsxs("div",{className:"space-y-1 sm:space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-xs text-gray-600",children:[e.jsx("span",{children:"TAT Used"}),e.jsxs("span",{className:"font-medium","data-testid":`${a}-progress-percentage`,children:[r,"%"]})]}),e.jsx(hs,{value:r,className:`h-1.5 sm:h-2 ${r>=80?"[&>div]:bg-red-600":r>=50?"[&>div]:bg-orange-500":"[&>div]:bg-green-600"}`,"data-testid":`${a}-progress-bar`})]})]})}function Hf(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 qf(t){return t.filter(s=>{const a=Number(s.tatPercentageUsed)||0;return(Number(s.remainingHours)||0)>0&&a<100})}function Wf(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 Kf(t){return t>=95?"bg-green-100 text-green-700":t>=90?"bg-blue-100 text-blue-700":t>=85?"bg-orange-100 text-orange-700":"bg-red-100 text-red-700"}function zd(t,s,a=3){const r=[];let n=Math.max(1,t-Math.floor(a/2)),i=Math.min(s,n+a-1);i-n<a-1&&(n=Math.max(1,i-a+1));for(let o=n;o<=i;o++)r.push(o);return r}function Gf({isAdmin:t,breachedRequests:s,pagination:a,onPageChange:r,onNavigate:n}){return e.jsxs(W,{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(ee,{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(te,{className:"text-base sm:text-lg text-gray-900",children:"Critical Alerts"}),e.jsx(pe,{className:"text-xs sm:text-sm text-gray-600",children:t?"Organization-wide":"My requests"})]})]}),e.jsx(X,{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(K,{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(zf,{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(D,{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"})}),zd(a.page,a.totalPages,3).map(i=>e.jsx(D,{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(D,{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 Yf=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"}},Zf=t=>{const s=new Date,a=new Date(t),r=Ep(s,a);if(r<1)return"just now";if(r<60)return`${r} minute${r>1?"s":""} ago`;const n=Mp(s,a);if(n<24)return`${n} hour${n>1?"s":""} ago`;const i=Ip(s,a);return`${i} day${i>1?"s":""} ago`},Xf=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()},Qf=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(gs,{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(Se,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-purple-600"}):s.includes("document")?e.jsx(Hr,{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 Jf({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(Xr,{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:Qf(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(X,{variant:"outline",className:`text-xs ${Yf(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:Xf(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:Zf(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 e0({isAdmin:t,recentActivity:s,pagination:a,refreshing:r,onPageChange:n,onRefresh:i,onNavigate:o,currentUserId:l,currentUserDisplayName:c,currentUserEmail:d}){return e.jsxs(W,{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(ee,{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(te,{className:"text-base sm:text-lg text-gray-900",children:"Recent Activity"}),e.jsx(pe,{className:"text-xs sm:text-sm text-gray-600 truncate",children:t?"All workflow updates":"My workflow updates"})]})]}),e.jsxs(D,{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(K,{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(Jf,{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(D,{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"})}),zd(a.page,a.totalPages,3).map(m=>e.jsx(D,{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(D,{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 t0({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(W,{className:"shadow-md hover:shadow-lg transition-shadow flex-1","data-testid":"active-levels-card",children:[e.jsx(ee,{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(te,{className:"text-sm",children:"Active Levels"})]})}),e.jsx(K,{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(ct,{}),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(W,{className:"shadow-md hover:shadow-lg transition-shadow flex-1","data-testid":"collaboration-card",children:[e.jsx(ee,{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(gs,{className:"h-4 w-4 text-indigo-600"})}),e.jsx(te,{className:"text-sm",children:"Collaboration"})]})}),e.jsx(K,{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(ct,{}),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(W,{className:"shadow-md hover:shadow-lg transition-shadow lg:col-span-2","data-testid":"department-stats-card",children:[e.jsx(ee,{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(Xp,{className:"h-5 w-5 sm:h-6 sm:w-6 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(te,{className:"text-base sm:text-lg lg:text-xl",children:"Department-wise Workflow Summary"}),e.jsx(pe,{className:"text-xs sm:text-sm",children:"Workflow distribution across departments"})]})]}),e.jsxs(D,{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(K,{children:e.jsx(Pi,{width:"100%",height:400,children:e.jsxs(Ap,{data:r,children:[e.jsx(sd,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(ad,{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(rd,{stroke:"#999",tick:{fontSize:11}}),e.jsx(Di,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(nd,{verticalAlign:"bottom",height:36,iconType:"square",wrapperStyle:{fontSize:"12px",paddingTop:"10px"}}),e.jsx(mn,{dataKey:"approved",fill:"#10b981",name:"Approved"}),e.jsx(mn,{dataKey:"inProgress",fill:"#f59e0b",name:"Pending"}),e.jsx(mn,{dataKey:"rejected",fill:"#ef4444",name:"Rejected"})]})})})]})]})}function s0({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(W,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"user-activity-card",children:[e.jsx(ee,{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(gs,{className:"h-4 w-4 text-indigo-600"})}),e.jsx(te,{className:"text-sm",children:"My Activity"})]})}),e.jsx(K,{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(W,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"user-response-time-card",children:[e.jsx(ee,{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(Ee,{className:"h-4 w-4 text-purple-600"})}),e.jsx(te,{className:"text-sm",children:"Avg Response Time"})]})}),e.jsx(K,{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(ct,{}),e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["≈ ",t.tatEfficiency.avgCycleTimeDays.toFixed(1)," working days"]})]})})]})]}):null}function a0({priorityDistribution:t,onNavigate:s}){return t.length===0?null:e.jsxs(W,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"priority-distribution-report",children:[e.jsx(ee,{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(lt,{className:"h-5 w-5 sm:h-6 sm:w-6 text-green-600"})}),e.jsxs("div",{children:[e.jsx(te,{className:"text-base sm:text-lg lg:text-xl",children:"Priority Distribution Report"}),e.jsx(pe,{className:"text-xs sm:text-sm",children:"Express vs Standard workflow analysis"})]})]})}),e.jsxs(K,{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(Tp,{children:[e.jsx(kp,{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(Rp,{fill:a.priority==="express"?"#ef4444":"#3b82f6",style:{cursor:"pointer"}},`cell-${r}`))}),e.jsx(Di,{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(W,{className:"shadow-md border-gray-200","data-testid":`${l}-container`,children:e.jsx(K,{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(W,{className:"shadow-md border-gray-200","data-testid":`${l}-container`,children:e.jsx(K,{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(D,{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(D,{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(D,{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(D,{variant:"outline",size:"sm",onClick:()=>n(s),className:"h-8 w-8 p-0","data-testid":`${l}-page-${s}`,children:s})]}),e.jsx(D,{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 r0(t,s,a,r="for"){return t==="custom"&&s&&a?`${r} ${he(s,"MMM d, yyyy")} - ${he(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 n0(t,s,a){return t==="all"?"All historical data":t==="custom"&&s&&a?`Data from ${he(s,"MMM d, yyyy")} to ${he(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 i0({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(W,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"tat-breach-report",children:[e.jsx(ee,{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(te,{className:"text-base sm:text-lg lg:text-xl",children:"TAT Breach Report"}),e.jsxs(pe,{className:"text-xs sm:text-sm",children:["Requests that breached TAT - ",n0(a,r,n)]})]})]}),e.jsxs(X,{variant:"destructive",className:"text-sm font-medium self-start sm:self-auto",children:[t.length," ",t.length===1?"Breach":"Breaches"]})]})}),e.jsxs(K,{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:Wf(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(X,{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 o0({isAdmin:t,upcomingDeadlines:s,pagination:a,onPageChange:r,onNavigate:n}){return s.length===0?null:e.jsxs(W,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"upcoming-deadlines-section",children:[e.jsx(ee,{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(te,{className:"text-base sm:text-lg",children:"Upcoming Deadlines"}),e.jsx(pe,{className:"text-xs sm:text-sm",children:t?"Current active levels organization-wide":"Requests awaiting your approval"})]})]})})}),e.jsxs(K,{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(X,{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(X,{variant:"outline",className:"text-xs bg-blue-50 text-blue-700 border-blue-200",children:["Level ",i.levelNumber||"?","/",i.totalLevels||"?"]}),e.jsx("span",{className:"truncate",children:i.approverName})]})]}),e.jsxs("div",{className:"text-right flex-shrink-0",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"TAT Used"}),e.jsxs("p",{className:`text-base sm:text-lg font-bold ${l>=80?"text-red-600":l>=50?"text-orange-600":"text-green-600"}`,children:[l.toFixed(0),"%"]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(hs,{value:l,className:`h-1.5 sm:h-2 ${l>=80?"bg-red-100":l>=50?"bg-orange-100":"bg-green-100"}`}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[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 l0({aiRemarkUtilization:t}){return t?e.jsxs(W,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"ai-remark-utilization-report",children:[e.jsx(ee,{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(_i,{className:"h-5 w-5 sm:h-6 sm:w-6 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(te,{className:"text-base sm:text-lg lg:text-xl",children:"AI Remark Utilization Report"}),e.jsx(pe,{className:"text-xs sm:text-sm",children:"AI-generated remarks usage and edits"})]})]})}),e.jsxs(K,{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(sd,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(ad,{dataKey:"month",stroke:"#999",tick:{fontSize:11}}),e.jsx(rd,{stroke:"#999",tick:{fontSize:11}}),e.jsx(Di,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(nd,{verticalAlign:"bottom",height:36,iconType:"circle",wrapperStyle:{fontSize:"12px",paddingTop:"10px"}}),e.jsx(qo,{type:"monotone",dataKey:"aiUsage",stroke:"#8b5cf6",strokeWidth:2,name:"AI Usage",dot:{fill:"#8b5cf6",r:4}}),e.jsx(qo,{type:"monotone",dataKey:"manualEdits",stroke:"#ec4899",strokeWidth:2,name:"Manual Edits",dot:{fill:"#ec4899",r:4}})]})})]})]}):null}function c0({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(W,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"approver-performance-report",children:[e.jsx(ee,{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(te,{className:"text-base sm:text-lg lg:text-xl",children:"Approver Performance Report"}),e.jsx(pe,{className:"text-xs sm:text-sm",children:"Response time & TAT compliance tracking"})]})]}),e.jsx(D,{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(K,{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 ${Kf(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 d0(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 m0(t,s,a){const r=[{label:"New Request",icon:Se,action:()=>s==null?void 0:s(),color:"bg-emerald-600 hover:bg-emerald-700"},{label:"View Pending",icon:Ee,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 cl({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(bf(Ct))},[r]),c=jf(),{dateRange:d,customStartDate:m,customEndDate:u,showCustomDatePicker:h,handleDateRangeChange:p,handleApplyCustomDate:g,resetCustomDates:y,setCustomStartDate:v,setCustomEndDate:C,setShowCustomDatePicker:f}=c,j=Nf(),{activity:b,critical:w,deadlines:T,approver:R,updateActivityPagination:k,updateCriticalPagination:F,updateDeadlinesPagination:N,updateApproverPagination:A,handleActivityPageChange:I,handleCriticalPageChange:V,handleDeadlinesPageChange:_,handleApproverPageChange:L}=j,S=Cf({isAdmin:o,viewAsUser:i&&n,userId:a==null?void 0:a.userId,dateRange:d,customStartDate:m,customEndDate:u,onPaginationUpdate:{activity:k,critical:F,deadlines:N,approver:A}}),{kpis:M,recentActivity:P,criticalRequests:E,departmentStats:H,priorityDistribution:q,upcomingDeadlines:J,aiRemarkUtilization:B,approverPerformance:oe,loading:ge,refreshing:z,fetchDashboardData:re,fetchRecentActivities:ye,fetchCriticalRequests:G,fetchUpcomingDeadlines:Q,fetchApproverPerformance:ie}=S,Y=If(),{exportingDeptStats:ue,exportingApproverPerformance:Me,handleExportDepartmentStats:$e,handleExportApproverPerformance:Ie}=Y,ae=x.useMemo(()=>Hf(E),[E]),fe=x.useMemo(()=>qf(J),[J]),Ve=x.useCallback(()=>{re(!0)},[d,m,u,re]),_e=x.useCallback(()=>{g(()=>{m&&u&&re(!1)})},[m,u,g,re]),Xt=x.useCallback(Ct=>{I(Ct,ye)},[I,ye]),ys=x.useCallback(Ct=>{V(Ct,G)},[V,G]),Ws=x.useCallback(Ct=>{_(Ct,Q)},[_,Q]),ma=x.useCallback(Ct=>{L(Ct,()=>ie(Ct))},[L,ie]);x.useEffect(()=>{d==="custom"?m&&u&&re(!1):re(!1)},[d,m,u,n]);const Ma=x.useMemo(()=>m0(i,s,t),[i,s,t]),vs=x.useCallback(Ct=>{const Ia=d0(Ct);t==null||t(Ia)},[t]);return ge?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(Ff,{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(Of,{isAdmin:o,dateRange:d,customStartDate:m,customEndDate:u,showCustomDatePicker:h,refreshing:z,onDateRangeChange:p,onCustomStartDateChange:v,onCustomEndDateChange:C,onShowCustomDatePickerChange:f,onApplyCustomDate:_e,onResetCustomDates:y,onRefresh:Ve}),o?e.jsx($f,{kpis:M,priorityDistribution:q,dateRange:d,customStartDate:m,customEndDate:u,onKPIClick:vs}):e.jsx(Uf,{kpis:M,criticalRequests:E,dateRange:d,customStartDate:m,customEndDate:u,onKPIClick:vs,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(Gf,{isAdmin:o,breachedRequests:ae,pagination:w,onPageChange:ys,onNavigate:t}),e.jsx(e0,{isAdmin:o,recentActivity:P,pagination:b,refreshing:z,onPageChange:Xt,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&&M&&e.jsx(t0,{kpis:M,upcomingDeadlines:J,criticalRequests:E,departmentStats:H,dateRange:d,customStartDate:m,customEndDate:u,exportingDeptStats:ue,onKPIClick:vs,onExportDepartmentStats:$e}),!o&&M&&e.jsx(s0,{kpis:M}),o&&q.length>0&&e.jsx(a0,{priorityDistribution:q,onNavigate:t}),o&&ae.length>0&&e.jsx(i0,{breachedRequests:ae,pagination:w,dateRange:d,customStartDate:m,customEndDate:u,onPageChange:ys,onKPIClick:vs,onNavigate:t}),fe.length>0&&e.jsx(o0,{isAdmin:o,upcomingDeadlines:fe,pagination:T,onPageChange:Ws,onNavigate:t}),o&&B&&e.jsx(l0,{aiRemarkUtilization:B}),o&&oe.length>0&&e.jsx(c0,{approverPerformance:oe,pagination:R,dateRange:d,customStartDate:m,customEndDate:u,loading:ge,exportingApproverPerformance:Me,onPageChange:ma,onExport:Ie,onNavigate:t})]})}const u0={searchTerm:"",statusFilter:"all",priorityFilter:"all",sortBy:"created",sortOrder:"desc",currentPage:1},Hd=Ta({name:"openRequests",initialState:u0,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:h0,setStatusFilter:p0,setPriorityFilter:x0,setSortBy:g0,setSortOrder:f0,setCurrentPage:y0,clearFilters:v0}=Hd.actions;function b0(){const t=ir(),{searchTerm:s,statusFilter:a,priorityFilter:r,sortBy:n,sortOrder:i,currentPage:o}=Ra(y=>y.openRequests),l=x.useCallback(y=>t(h0(y)),[t]),c=x.useCallback(y=>t(p0(y)),[t]),d=x.useCallback(y=>t(x0(y)),[t]),m=x.useCallback(y=>t(g0(y)),[t]),u=x.useCallback(y=>t(f0(y)),[t]),h=x.useCallback(y=>t(y0(y)),[t]),p=x.useCallback(()=>t(v0()),[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 Nn(){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 j0(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:Nn(),approverEmail:y,approverName:v,tatHours:g>0?g:24,isFinalApprover:h===(t.approverCount||1)}}),r=[...(t.spectators||[]).map(c=>({userId:Nn(),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:Nn(),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 ne.post("/workflows",n),o=((l=i.data)==null?void 0:l.data)||i.data;return{id:o.id||o.workflowId||""}}async function qd(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 ne.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 N0(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 ne.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 w0(t={}){var y,v,C,f,j;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 ne.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)||((C=g.data)==null?void 0:C.data)||[],pagination:((j=(f=g.data)==null?void 0:f.data)==null?void 0:j.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function C0(t={}){var g,y,v,C,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 ne.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=(C=p.data)==null?void 0:C.data)==null?void 0:f.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function S0(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 ne.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 A0(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 ne.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 T0(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 ne.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 ne.get(`/workflows/${t}/details`);return((a=s.data)==null?void 0:a.data)||s.data}async function ba(t){var a;const s=await ne.get(`/workflows/${t}/work-notes`);return((a=s.data)==null?void 0:a.data)||s.data}async function Wd(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 ne.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 Kd(t,s,a,r){var i;const n=await ne.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 k0(t,s,a){var n;const r=await ne.post(`/workflows/${t}/approvals/${s}/skip`,{reason:a});return((n=r.data)==null?void 0:n.data)||r.data}async function Gd(t,s){var r;const a=await ne.post(`/workflows/${t}/participants/spectator`,{email:s});return((r=a.data)==null?void 0:r.data)||a.data}async function R0(t,s,a,r){var i;const n=await ne.post(`/workflows/${t}/pause`,{levelId:s,reason:a,resumeDate:r.toISOString()});return((i=n.data)==null?void 0:i.data)||n.data}async function P0(t,s){var r;const a=await ne.post(`/workflows/${t}/resume`,{notes:s});return((r=a.data)==null?void 0:r.data)||a.data}async function D0(t){var a;const s=await ne.post(`/workflows/${t}/pause/retrigger`);return((a=s.data)==null?void 0:a.data)||s.data}async function dl(t){var a;const s=await ne.get(`/workflows/${t}/pause`);return((a=s.data)==null?void 0:a.data)||s.data}function E0(t){return`https://re-workflow-nt-dev.siplsolutions.com/api/v1/workflows/work-notes/attachments/${t}/preview`}function Yd(t){return`https://re-workflow-nt-dev.siplsolutions.com/api/v1/workflows/documents/${t}/preview`}async function oi(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 ml(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:j0,createWorkflowMultipart:qd,listWorkflows:N0,listParticipantRequests:w0,listMyWorkflows:C0,listMyInitiatedWorkflows:S0,listOpenForMe:A0,listClosedByMe:T0,submitWorkflow:Zd,getWorkflowDetails:aa,getWorkNotes:ba,createWorkNoteMultipart:Wd};async function Zd(t){var a;const s=await ne.patch(`/workflows/${t}/submit`);return((a=s.data)==null?void 0:a.data)||s.data}async function M0(t,s){var r;const a=await ne.put(`/workflows/${t}`,s);return((r=a.data)==null?void 0:r.data)||a.data}async function I0(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 ne.put(`/workflows/${t}/multipart`,i,{headers:{"Content-Type":"multipart/form-data"}});return((l=o.data)==null?void 0:l.data)||o.data}async function F0(t,s,a){var n;const r=await ne.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 ne.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 L0(t,s){const a=await ne.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 Xd(t){return Vt(t,{includeTime:!1,format:"short"})}function ps(t,s=!1){if(!t)return"N/A";try{const a=typeof t=="string"?new Date(t):t;if(isNaN(a.getTime()))return"Invalid Date";const r=String(a.getDate()).padStart(2,"0"),i=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][a.getMonth()],o=a.getFullYear();if(s){const l=a.getHours(),c=l%12||12,d=String(a.getMinutes()).padStart(2,"0"),m=String(a.getSeconds()).padStart(2,"0"),u=l>=12?"PM":"AM";return`${r} ${i} ${o}, ${c}:${d}:${m} ${u}`}return`${r} ${i} ${o}`}catch(a){return console.error("Error formatting date:",a),String(t)}}const O0=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:lt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:lt,iconColor:"text-gray-600"}}},$0=t=>{switch(t){case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:Ee,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 U0({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=b0(),g=x.useCallback(async(b=1,w)=>{try{b===1&&(n(!0),a([]));const T=await Ot.listOpenForMe({page:b,limit:u,search:w==null?void 0:w.search,status:w==null?void 0:w.status,priority:w==null?void 0:w.priority,sortBy:w==null?void 0:w.sortBy,sortOrder:w==null?void 0:w.sortOrder}),R=Array.isArray(T==null?void 0:T.data)?T.data:[],k=T==null?void 0:T.pagination;k&&(p.setCurrentPage(k.page||1),c(k.totalPages||1),m(k.total||0));const F=R.map(N=>{var I,V,_,L;const A=N.submittedAt||N.submitted_at||N.createdAt||N.created_at;return{id:N.requestNumber||N.request_number||N.requestId,requestId:N.requestId,displayId:N.requestNumber||N.request_number||N.requestId,title:N.title,description:N.description,status:(N.status||"").toString().toLowerCase().replace("_","-"),priority:(N.priority||"").toString().toLowerCase(),initiator:{name:((I=N.initiator)==null?void 0:I.displayName)||((V=N.initiator)==null?void 0:V.email)||"—",avatar:(((_=N.initiator)==null?void 0:_.displayName)||((L=N.initiator)==null?void 0:L.email)||"NA").split(" ").map(S=>S[0]).join("").slice(0,2).toUpperCase()},currentApprover:N.currentApprover?{name:N.currentApprover.name||N.currentApprover.email||"—",avatar:(N.currentApprover.name||N.currentApprover.email||"CA").split(" ").map(S=>S[0]).join("").slice(0,2).toUpperCase(),sla:N.currentApprover.sla}:void 0,createdAt:A||"—",approvalStep:N.currentLevel?`Step ${N.currentLevel} of ${N.totalLevels||"?"}`:void 0,department:N.department,currentLevelSLA:N.currentLevelSLA}});a(F)}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}))},C=()=>{const b=[];let T=Math.max(1,p.currentPage-Math.floor(2.5)),R=Math.min(l,T+5-1);R-T<4&&(T=Math.max(1,R-5+1));for(let k=T;k<=R;k++)b.push(k);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 j=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(Se,{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(X,{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(D,{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(W,{className:"shadow-lg border-0",children:[e.jsx(ee,{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(te,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(pe,{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(D,{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(ft,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Clear"})]})]})}),e.jsx(K,{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(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx(xe,{placeholder:"Search requests, IDs...",value: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(Ae,{value:p.priorityFilter,onValueChange:p.setPriorityFilter,children:[e.jsx(ke,{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(Te,{placeholder:"All Priorities"})}),e.jsxs(Re,{children:[e.jsx(O,{value:"all",children:"All Priorities"}),e.jsx(O,{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(O,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(lt,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(Ae,{value:p.statusFilter,onValueChange:p.setStatusFilter,children:[e.jsx(ke,{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(Te,{placeholder:"All Statuses"})}),e.jsxs(Re,{children:[e.jsx(O,{value:"all",children:"All Statuses"}),e.jsx(O,{value:"pending",children:"Pending (In Approval)"}),e.jsx(O,{value:"approved",children:"Approved (Needs Closure)"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ae,{value:p.sortBy,onValueChange:b=>p.setSortBy(b),children:[e.jsx(ke,{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(Te,{placeholder:"Sort by"})}),e.jsxs(Re,{children:[e.jsx(O,{value:"due",children:"Due Date"}),e.jsx(O,{value:"created",children:"Date Created"}),e.jsx(O,{value:"priority",children:"Priority"}),e.jsx(O,{value:"sla",children:"SLA Progress"})]})]}),e.jsx(D,{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(xd,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(gd,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]}),e.jsx("div",{className:"space-y-3",children:j.map(b=>{const w=O0(b.priority),T=$0(b.status);return e.jsx(W,{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(K,{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 ${w.color} border shadow-sm`,children:e.jsx(w.icon,{className:`w-5 h-5 ${w.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(X,{variant:"outline",className:`${T.color} text-xs px-2.5 py-0.5 font-semibold shrink-0`,children:[e.jsx(T.icon,{className:"w-3.5 h-3.5 mr-1"}),T.label||b.status]}),b.department&&e.jsx(X,{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(X,{variant:"outline",className:`${w.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 A;const R=!!(b.isPaused||(A=b.pauseInfo)!=null&&A.isPaused||b.status==="paused"),k=b.currentLevelSLA.percentageUsed||0,N=R?{bg:"bg-gray-100 border border-gray-300",progress:"bg-gray-500",text:"text-gray-600",icon:"text-gray-600"}:k>=100?{bg:"bg-red-50 border border-red-200",progress:"bg-red-600",text:"text-red-600",icon:"text-blue-600"}:k>=75?{bg:"bg-orange-50 border border-orange-200",progress:"bg-orange-500",text:"text-orange-600",icon:"text-blue-600"}:k>=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 ${N.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:[R?e.jsx(Ka,{className:`w-3.5 h-3.5 ${N.icon}`}):e.jsx(Ee,{className:`w-3.5 h-3.5 ${N.icon}`}),e.jsxs("span",{className:"text-xs font-medium text-gray-900",children:["TAT: ",k,"% ",R&&"(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 ${N.text}`,children:[b.currentLevelSLA.remainingText," left"]})]})]}),e.jsx(hs,{value:k,className:"h-1.5",indicatorClassName:N.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!=="—"?ps(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)})}),j.length===0&&e.jsx(W,{className:"shadow-lg border-0",children:e.jsxs(K,{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(Se,{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(D,{variant:"outline",className:"mt-4",onClick:p.clearFilters,children:"Clear all filters"})]})}),l>1&&!r&&e.jsx(W,{className:"shadow-md",children:e.jsx(K,{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(D,{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(D,{variant:"outline",size:"sm",onClick:()=>v(1),className:"h-8 w-8 p-0",children:"1"}),e.jsx("span",{className:"text-muted-foreground",children:"..."})]}),C().map(b=>e.jsx(D,{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(D,{variant:"outline",size:"sm",onClick:()=>v(l),className:"h-8 w-8 p-0",children:l})]}),e.jsx(D,{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 B0({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(Se,{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(X,{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(D,{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 V0({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(W,{className:"shadow-lg border-0","data-testid":"closed-requests-filters",children:[e.jsx(ee,{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(te,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(pe,{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(D,{variant:"ghost",size:"sm",onClick:u,className:"text-red-600 hover:bg-red-50 gap-1 h-8 sm:h-9 px-2 sm:px-3","data-testid":"closed-requests-clear-filters",children:[e.jsx(ft,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Clear"})]})]})}),e.jsx(K,{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(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx(xe,{placeholder:"Search requests, IDs...",value:t,onChange:h=>o(h.target.value),className:"pl-9 sm:pl-10 h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white transition-colors","data-testid":"closed-requests-search"})]}),e.jsxs(Ae,{value:s,onValueChange:l,children:[e.jsx(ke,{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(Te,{placeholder:"All Priorities"})}),e.jsxs(Re,{children:[e.jsx(O,{value:"all",children:"All Priorities"}),e.jsx(O,{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(O,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(lt,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(Ae,{value:a,onValueChange:c,children:[e.jsx(ke,{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(Te,{placeholder:"Closure Type"})}),e.jsxs(Re,{children:[e.jsx(O,{value:"all",children:"All Closures"}),e.jsx(O,{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(O,{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(Ae,{value:r,onValueChange:h=>d(h),children:[e.jsx(ke,{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(Te,{placeholder:"Sort by"})}),e.jsxs(Re,{children:[e.jsx(O,{value:"due",children:"Due Date"}),e.jsx(O,{value:"created",children:"Date Created"}),e.jsx(O,{value:"priority",children:"Priority"})]})]}),e.jsx(D,{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(xd,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(gd,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function z0(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:lt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:lt,iconColor:"text-gray-600"}}}function H0(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 q0({request:t,onViewRequest:s}){const a=z0(t.priority),r=H0(t.status),n=a.icon,i=r.icon;return e.jsx(W,{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(K,{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(X,{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(X,{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(X,{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!=="—"?ps(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: ",ps(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 W0({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(q0,{request:r,onViewRequest:a},r.id))})}function K0({searchTerm:t,activeFiltersCount:s,onClearFilters:a}){return e.jsx(W,{className:"shadow-lg border-0","data-testid":"closed-requests-empty",children:e.jsxs(K,{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(Se,{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(D,{variant:"outline",className:"mt-4",onClick:a,"data-testid":"closed-requests-empty-clear-filters",children:"Clear all filters"})]})})}function G0(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 Y0({pagination:t,onPageChange:s}){const{currentPage:a,totalPages:r,totalRecords:n,itemsPerPage:i}=t;if(r<=1)return null;const o=G0(a,r);return e.jsx(W,{className:"shadow-md","data-testid":"closed-requests-pagination",children:e.jsx(K,{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(D,{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(D,{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(D,{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(D,{variant:"outline",size:"sm",onClick:()=>s(r),className:"h-8 w-8 p-0","data-testid":"closed-requests-pagination-last",children:r})]}),e.jsx(D,{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 Z0(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 X0(t){return t.map(Z0)}function Q0({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([]));let p=h==null?void 0:h.status;if(p==="approved"){a([]),c({currentPage:1,totalPages:1,totalRecords:0,itemsPerPage:t}),n(!1),o(!1);return}const g=await Ot.listClosedByMe({page:u,limit:t,search:h==null?void 0:h.search,status:p&&p!=="all"?p:void 0,priority:h==null?void 0:h.priority,sortBy:h==null?void 0:h.sortBy,sortOrder:h==null?void 0:h.sortOrder}),y=Array.isArray(g==null?void 0:g.data)?g.data:[],v=X0(y);a(v);const C=g==null?void 0:g.pagination;C&&c({currentPage:C.page||1,totalPages:C.totalPages||1,totalRecords:C.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 J0={searchTerm:"",statusFilter:"all",priorityFilter:"all",sortBy:"created",sortOrder:"desc",currentPage:1},Qd=Ta({name:"closedRequests",initialState:J0,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:ey,setStatusFilter:ty,setPriorityFilter:sy,setSortBy:ay,setSortOrder:ry,setCurrentPage:ny,clearFilters:iy}=Qd.actions;function oy({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(ey(b)),[a]),h=x.useCallback(b=>a(ty(b)),[a]),p=x.useCallback(b=>a(sy(b)),[a]),g=x.useCallback(b=>a(ay(b)),[a]),y=x.useCallback(b=>a(ry(b)),[a]),v=x.useCallback(b=>a(ny(b)),[a]),C=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(C())},i?s:0);return r.current=b,()=>{r.current&&clearTimeout(r.current)}},[i,o,l,c,d,t,C,s]);const f=x.useCallback(()=>{a(iy())},[a]),j=[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:j,getFilters:C}}function ly({onViewRequest:t}){const s=Q0({itemsPerPage:10}),a=x.useRef(s.fetchRequests);a.current=s.fetchRequests;const r=oy(),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(B0,{totalRecords:s.pagination.totalRecords,loading:s.loading,refreshing:s.refreshing,onRefresh:l}),e.jsx(V0,{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(W0,{requests:s.requests,loading:s.loading,onViewRequest:t}),s.requests.length===0&&!s.loading&&e.jsx(K0,{searchTerm:r.searchTerm,activeFiltersCount:r.activeFiltersCount,onClearFilters:r.clearFilters}),!s.loading&&e.jsx(Y0,{pagination:s.pagination,onPageChange:o})]})}function Qr({className:t,...s}){return e.jsx(ap,{"data-slot":"tabs",className:le("flex flex-col gap-2",t),...s})}function Jr({className:t,...s}){return e.jsx(rp,{"data-slot":"tabs-list",className:le("bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-xl p-[3px] flex",t),...s})}function pt({className:t,...s}){return e.jsx(np,{"data-slot":"tabs-trigger",className:le("data-[state=active]:bg-card dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-xl border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...s})}function xt({className:t,...s}){return e.jsx(ip,{"data-slot":"tabs-content",className:le("flex-1 outline-none",t),...s})}const Jd={"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"]}},cy={"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 dy(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=(w,T)=>(w||T||"NA").toString().split(" ").map(k=>k[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),v=w=>{const T=(w||"").toUpperCase();return T==="IN_PROGRESS"?"in-review":T==="PENDING"?"pending":T==="APPROVED"?"approved":T==="REJECTED"?"rejected":T==="CLOSED"?"closed":T==="SKIPPED"?"skipped":(w||"").toLowerCase()},C=x.useCallback(async()=>{var w,T,R,k,F,N,A,I,V;o(!0);try{const _=await Ot.getWorkflowDetails(t);if(!_){console.warn("[useRequestDetails] No details returned from API");return}const L=_.workflow||{},S=Array.isArray(_.approvals)?_.approvals:[],M=Array.isArray(_.participants)?_.participants:[],P=Array.isArray(_.documents)?_.documents:[],E=_.summary||{},H=Array.isArray(_.tatAlerts)?_.tatAlerts:[];H.length>0;const q=(E==null?void 0:E.currentLevel)||L.currentLevel||1,J=S.map(Y=>{const ue=Y.levelNumber||0,Me=(Y.status||"").toString().toUpperCase(),$e=Y.levelId||Y.level_id;let Ie=v(Y.status);ue>q&&Me!=="APPROVED"&&Me!=="REJECTED"?Ie="waiting":ue===q&&Me==="PENDING"&&(Ie="pending");const ae=H.filter(fe=>fe.levelId===$e);return{step:ue,levelId:$e,role:Y.levelName||Y.approverName||"Approver",status:Ie,approver:Y.approverName||Y.approverEmail,approverId:Y.approverId||Y.approver_id,approverEmail:Y.approverEmail,tatHours:Number(Y.tatHours||0),elapsedHours:Number(Y.elapsedHours||0),remainingHours:Number(Y.remainingHours||0),tatPercentageUsed:Number(Y.tatPercentageUsed||0),actualHours:Y.levelEndTime&&Y.levelStartTime?Math.max(0,(new Date(Y.levelEndTime).getTime()-new Date(Y.levelStartTime).getTime())/(1e3*60*60)):void 0,comment:Y.comments||void 0,timestamp:Y.actionDate||void 0,levelStartTime:Y.levelStartTime||Y.tatStartTime,tatAlerts:ae,skipReason:Y.skipReason||void 0,isSkipped:Me==="SKIPPED"||Y.isSkipped||!1}}),B=M.filter(Y=>(Y.participantType||Y.participant_type||"").toUpperCase()==="SPECTATOR").map(Y=>({name:Y.userName||Y.user_name||Y.userEmail||Y.user_email,role:"Spectator",email:Y.userEmail||Y.user_email,avatar:y(Y.userName||Y.user_name,Y.userEmail||Y.user_email)})),oe=Y=>{var Me,$e;if(!Y)return;const ue=M.find(Ie=>Ie.userId===Y||Ie.user_id===Y);return ue!=null&&ue.userName||ue!=null&&ue.user_name?ue.userName||ue.user_name:L.initiatorId===Y?((Me=L.initiator)==null?void 0:Me.displayName)||(($e=L.initiator)==null?void 0:$e.email):Y},ge=P.map(Y=>{const ue=Number(Y.fileSize||Y.file_size||0),Me=(ue/(1024*1024)).toFixed(2)+" MB";return{documentId:Y.documentId||Y.document_id,name:Y.originalFileName||Y.fileName||Y.file_name,fileType:Y.fileType||Y.file_type||"",size:Me,sizeBytes:ue,uploadedBy:oe(Y.uploadedBy||Y.uploaded_by),uploadedAt:Y.uploadedAt||Y.uploaded_at}}),z=Array.isArray(_.activities)?_.activities.filter(Y=>(Y.type||"").toLowerCase()!=="sla_warning"):[];let re=null;try{re=await dl(L.requestId)}catch(Y){console.debug("Pause details not available:",Y)}const ye={...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:J,approvals:S,participants:M,documents:ge,spectators:B,summary:E,initiator:{name:((w=L.initiator)==null?void 0:w.displayName)||((T=L.initiator)==null?void 0:T.email),role:((R=L.initiator)==null?void 0:R.designation)||void 0,department:((k=L.initiator)==null?void 0:k.department)||void 0,email:((F=L.initiator)==null?void 0:F.email)||void 0,phone:((N=L.initiator)==null?void 0:N.phone)||void 0,avatar:y((A=L.initiator)==null?void 0:A.displayName,(I=L.initiator)==null?void 0:I.email)},createdAt:L.createdAt,updatedAt:L.updatedAt,totalSteps:L.totalLevels||1,currentStepRaw:(E==null?void 0:E.currentLevel)||L.currentLevel||1,currentStep:Math.min(Math.max(1,(E==null?void 0:E.currentLevel)||L.currentLevel||1),L.totalLevels||1),auditTrail:z,conclusionRemark:L.conclusionRemark||null,closureDate:L.closureDate||null,pauseInfo:re||null};n(ye);const G=(V=a==null?void 0:a.email)==null?void 0:V.toLowerCase(),Q=S.find(Y=>{const ue=(Y.status||"").toString().toUpperCase(),Me=(Y.approverEmail||"").toLowerCase(),$e=Y.levelNumber||0;return(ue==="PENDING"||ue==="IN_PROGRESS"||ue==="PAUSED")&&Me===G&&$e===q});h(Q||null);const ie=a==null?void 0:a.userId;if(ie){const Y=M.some(ue=>(ue.participantType||ue.participant_type||"").toUpperCase()==="SPECTATOR"&&(ue.userId||ue.user_id)===ie);g(Y)}else g(!1)}catch(_){console.error("[useRequestDetails] Error refreshing details:",_),alert("Failed to refresh request details. Please try again.")}finally{o(!1)}},[t,a]);x.useEffect(()=>{if(!t){c(!1);return}let w=!0;return c(!0),m(null),(async()=>{var T,R,k,F,N,A,I,V,_,L,S,M;try{const P=await Ot.getWorkflowDetails(t);if(!w||!P){w&&c(!1);return}const E=P.workflow||{},H=Array.isArray(P.approvals)?P.approvals:[],q=Array.isArray(P.participants)?P.participants:[],J=Array.isArray(P.documents)?P.documents:[],B=P.summary||{},oe=Array.isArray(P.tatAlerts)?P.tatAlerts:[],ge=(E.priority||"").toString().toLowerCase(),z=(B==null?void 0:B.currentLevel)||E.currentLevel||1,re=H.map(ae=>{const fe=ae.levelNumber||0,Ve=(ae.status||"").toString().toUpperCase(),_e=ae.levelId||ae.level_id;let Xt=v(ae.status);Ve==="PAUSED"?Xt="paused":fe>z&&Ve!=="APPROVED"&&Ve!=="REJECTED"?Xt="waiting":fe===z&&(Ve==="PENDING"||Ve==="IN_PROGRESS")&&(Xt=Ve==="IN_PROGRESS"?"in-review":"pending");const ys=oe.filter(Ws=>Ws.levelId===_e);return{step:fe,levelId:_e,role:ae.levelName||ae.approverName||"Approver",status:Xt,approver:ae.approverName||ae.approverEmail,approverId:ae.approverId||ae.approver_id,approverEmail:ae.approverEmail,tatHours:Number(ae.tatHours||0),elapsedHours:Number(ae.elapsedHours||0),remainingHours:Number(ae.remainingHours||0),tatPercentageUsed:Number(ae.tatPercentageUsed||0),actualHours:ae.elapsedHours!==void 0&&ae.elapsedHours!==null?Number(ae.elapsedHours):void 0,comment:ae.comments||void 0,timestamp:ae.actionDate||void 0,levelStartTime:ae.levelStartTime||ae.tatStartTime,tatAlerts:ys}}),ye=q.filter(ae=>(ae.participantType||"").toUpperCase()==="SPECTATOR").map(ae=>({name:ae.userName||ae.userEmail,role:"Spectator",avatar:y(ae.userName,ae.userEmail)})),G=ae=>{var Ve,_e;if(!ae)return;const fe=q.find(Xt=>Xt.userId===ae);return fe!=null&&fe.userName?fe.userName:E.initiatorId===ae?((Ve=E.initiator)==null?void 0:Ve.displayName)||((_e=E.initiator)==null?void 0:_e.email):ae},Q=J.map(ae=>{const fe=Number(ae.fileSize||0),Ve=(fe/(1024*1024)).toFixed(2)+" MB";return{documentId:ae.documentId||ae.document_id,name:ae.originalFileName||ae.fileName,fileType:ae.fileType||ae.file_type||"",size:Ve,sizeBytes:fe,uploadedBy:G(ae.uploadedBy),uploadedAt:ae.uploadedAt}}),ie=Array.isArray(P.activities)?P.activities.filter(ae=>(ae.type||"").toLowerCase()!=="sla_warning"):[];let Y=null;try{Y=await dl(E.requestId)}catch(ae){console.debug("Pause details not available:",ae)}const ue={id:E.requestNumber||E.requestId,requestId:E.requestId,title:E.title,description:E.description,priority:ge,status:v(E.status),summary:B,initiator:{name:((T=E.initiator)==null?void 0:T.displayName)||((R=E.initiator)==null?void 0:R.email),role:((k=E.initiator)==null?void 0:k.designation)||void 0,department:((F=E.initiator)==null?void 0:F.department)||void 0,email:((N=E.initiator)==null?void 0:N.email)||void 0,phone:((A=E.initiator)==null?void 0:A.phone)||void 0,avatar:y((I=E.initiator)==null?void 0:I.displayName,(V=E.initiator)==null?void 0:V.email)},createdAt:E.createdAt,updatedAt:E.updatedAt,totalSteps:E.totalLevels||1,currentStepRaw:(B==null?void 0:B.currentLevel)||E.currentLevel||1,currentStep:Math.min(Math.max(1,(B==null?void 0:B.currentLevel)||E.currentLevel||1),E.totalLevels||1),approvalFlow:re,approvals:H,documents:Q,spectators:ye,auditTrail:ie,conclusionRemark:E.conclusionRemark||null,closureDate:E.closureDate||null,pauseInfo:Y||null};n(ue);const Me=(_=a==null?void 0:a.email)==null?void 0:_.toLowerCase(),$e=H.find(ae=>{const fe=(ae.status||"").toString().toUpperCase(),Ve=(ae.approverEmail||"").toLowerCase(),_e=ae.levelNumber||0;return(fe==="PENDING"||fe==="IN_PROGRESS"||fe==="PAUSED")&&Ve===Me&&_e===z});h($e||null);const Ie=a==null?void 0:a.userId;if(Ie){const ae=q.some(fe=>(fe.participantType||"").toUpperCase()==="SPECTATOR"&&fe.userId===Ie);g(ae)}else g(!1)}catch(P){if(console.error("[useRequestDetails] Error loading request details:",P),w){if(((L=P==null?void 0:P.response)==null?void 0:L.status)===403){const E=((M=(S=P==null?void 0:P.response)==null?void 0:S.data)==null?void 0:M.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:E})}n(null)}}finally{w&&c(!1)}})(),()=>{w=!1}},[t,a]);const f=x.useMemo(()=>{if(r)return r;const w=Jd[t];if(w)return w;const T=cy[t];if(T)return T;const R=s.find(k=>k.id===t||k.requestNumber===t||k.request_number===t);return R||null},[t,s,r]),j=x.useMemo(()=>{var R,k,F;if(!f||!a)return!1;const w=(R=a==null?void 0:a.email)==null?void 0:R.toLowerCase(),T=(F=(k=f.initiator)==null?void 0:k.email)==null?void 0:F.toLowerCase();return w===T},[f,a]),b=x.useMemo(()=>{var T;if(!f)return[];const w=[];return(T=f.initiator)!=null&&T.email&&w.push({email:f.initiator.email.toLowerCase(),participantType:"INITIATOR",name:f.initiator.name}),f.approvalFlow&&Array.isArray(f.approvalFlow)&&f.approvalFlow.forEach(R=>{R.approverEmail&&w.push({email:R.approverEmail.toLowerCase(),participantType:"APPROVER",name:R.approver})}),f.spectators&&Array.isArray(f.spectators)&&f.spectators.forEach(R=>{R.email&&w.push({email:R.email.toLowerCase(),participantType:"SPECTATOR",name:R.name})}),f.participants&&Array.isArray(f.participants)&&f.participants.forEach(R=>{const k=(R.userEmail||R.email||"").toLowerCase(),F=(R.participantType||R.participant_type||"").toUpperCase(),N=R.userName||R.user_name||R.name;k&&F&&!w.find(A=>A.email===k)&&w.push({email:k,participantType:F,name:N})}),w},[f]);return x.useEffect(()=>{if(!t||!r)return;const w=Ya();if(!w){console.warn("[useRequestDetails] Socket not available");return}console.log("[useRequestDetails] Setting up socket listener for request:",r.requestId);const T=R=>{console.log("[useRequestDetails] 📡 Received request:updated event:",R),(R==null?void 0:R.requestId)===r.requestId||(R==null?void 0:R.requestNumber)===t?(console.log("[useRequestDetails] 🔄 Request updated remotely, refreshing silently..."),C()):console.log("[useRequestDetails] ⚠️ Event for different request, ignoring")};return w.on("request:updated",T),console.log("[useRequestDetails] ✅ Registered listener for request:updated"),()=>{console.log("[useRequestDetails] 🧹 Cleaning up socket listener"),w.off("request:updated",T)}},[t,r,C]),{request:f,apiRequest:r,loading:l,refreshing:i,refreshDetails:C,currentApprovalLevel:u,isSpectator:p,isInitiator:j,existingParticipants:b,accessDenied:d}}function my(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=()=>{ii(h,u,p)};return h.connected?g():h.on("connect",g),()=>{m&&(h.off("connect",g),Bd(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((C,f)=>{const j=new Date(C.createdAt||C.created_at||C.timestamp||0).getTime(),b=new Date(f.createdAt||f.created_at||f.timestamp||0).getTime();return j-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 uy(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 ne.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 ne.get("/users/configurations",{params:s})).data.data},en=async t=>{const s=t?{category:t}:{};return(await ne.get("/admin/configurations",{params:s})).data.data},vt=async(t,s)=>{await ne.put(`/admin/configurations/${t}`,{configValue:s})},hy=async t=>{await ne.post(`/admin/configurations/${t}/reset`)},py=async t=>{const s=t?{year:t}:{};return(await ne.get("/admin/holidays",{params:s})).data.data},xy=async t=>(await ne.post("/admin/holidays",t)).data.data,gy=async(t,s)=>(await ne.put(`/admin/holidays/${t}`,s)).data.data,fy=async t=>{await ne.delete(`/admin/holidays/${t}`)};function yy(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(j=>{y[j.configKey]=j.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(j=>j.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,j;const g=p.target.files;if(!g||g.length===0)return;const y=Array.from(g),v=[],C=[];if(y.forEach(b=>{const w=m(b);w.valid?C.push(b):v.push({fileName:b.name,reason:w.reason||"Unknown validation error"})}),v.length>0&&d({show:!0,errors:v}),C.length===0){p.target&&(p.target.value="");return}r(!0);try{const b=C[0],w=t==null?void 0:t.requestId;if(!w){be.error("Request ID not found");return}b&&await uy(b,w,"SUPPORTING"),await s(),C.length<y.length?be.warning(`${C.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(((j=(f=b==null?void 0:b.response)==null?void 0:f.data)==null?void 0:j.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 vy="modulepreload",by=function(t){return"/"+t},ul={},wn=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=by(c),c in ul)return;ul[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":vy,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 jy(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 wn(async()=>{const{getConclusion:b}=await import("./conclusionApi-nj0Kn1y4.js");return{getConclusion:b}},__vite__mapDeps([0,1,2,3,4,5,6,7])),j=await f(t.requestId||s);j&&j.aiGeneratedRemark&&(c(j.finalRemark||j.aiGeneratedRemark),g(!!j.aiGeneratedRemark))}catch{}},v=async()=>{try{m(!0);const{generateConclusion:f}=await wn(async()=>{const{generateConclusion:b}=await import("./conclusionApi-nj0Kn1y4.js");return{generateConclusion:b}},__vite__mapDeps([0,1,2,3,4,5,6,7])),j=await f(t.requestId||s);c(j.aiGeneratedRemark),g(!0)}catch(f){console.error("[useConclusionRemark] AI generation failed:",f),c(""),g(!1)}finally{m(!1)}},C=async()=>{var j,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:w}=await wn(async()=>{const{finalizeConclusion:T}=await import("./conclusionApi-nj0Kn1y4.js");return{finalizeConclusion:T}},__vite__mapDeps([0,1,2,3,4,5,6,7]));await w(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(w){i==null||i({success:!1,title:"Error",message:((b=(j=w.response)==null?void 0:j.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:C}}function Ny(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),[C,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:C,setActionStatus:f,handleApproveConfirm:async k=>{var N,A;const F=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!F){alert("Approval level not found");return}await F0(t,F,k||""),await a(),(N=window==null?void 0:window.closeModal)==null||N.call(window),(A=window==null?void 0:window.toast)==null||A.call(window,"Approved successfully")},handleRejectConfirm:async k=>{var N,A;if(!(k!=null&&k.trim())){alert("Comments & remarks are required");return}const F=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!F){alert("Approval level not found");return}await _0(t,F,k.trim(),k.trim()),await a(),(N=window==null?void 0:window.closeModal)==null||N.call(window),(A=window==null?void 0:window.toast)==null||A.call(window,"Rejected successfully")},handleAddApprover:async(k,F,N)=>{var A,I;try{await Kd(t,k,F,N),await a(),c(!1),f==null||f({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${N} with ${F}h TAT`}),g==null||g(!0)}catch(V){throw f==null||f({success:!1,title:"Failed to Add Approver",message:((I=(A=V==null?void 0:V.response)==null?void 0:A.data)==null?void 0:I.error)||"Failed to add approver. Please try again."}),g==null||g(!0),V}},handleSkipApprover:async k=>{var F,N;if(y)try{await k0(t,y.levelId,k),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(A){throw f==null||f({success:!1,title:"Failed to Skip Approver",message:((N=(F=A==null?void 0:A.response)==null?void 0:F.data)==null?void 0:N.error)||"Failed to skip approver. Please try again."}),g==null||g(!0),A}},handleAddSpectator:async k=>{var F,N;try{await Gd(t,k),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(A){throw f==null||f({success:!1,title:"Failed to Add Spectator",message:((N=(F=A==null?void 0:A.response)==null?void 0:F.data)==null?void 0:N.error)||"Failed to add spectator. Please try again."}),g==null||g(!0),A}}}}const wy=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"}}},Cy=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}}},Sy=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(gs,{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(qr,{className:"w-5 h-5 text-purple-600"});case"created":return e.jsx(Se,{className:"w-5 h-5 text-blue-600"});case"reminder":return e.jsx(Ee,{className:"w-5 h-5 text-yellow-600"});case"document_added":return e.jsx(Hr,{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 Ay({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(Ee,{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(Ee,{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(X,{className:`text-xs ${l.badge}`,"data-testid":`${r}-badge`,children:[t.percentageUsed||0,"% elapsed ",a&&"(frozen)"]})]}),e.jsx(hs,{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: ",ps(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(ti,{className:"h-3.5 w-3.5"}),"URGENT - Deadline Passed"]})]})}function Ty({request:t,refreshing:s,onBack:a,onRefresh:r,onShareSummary:n,isInitiator:i}){var d,m,u;const o=wy((t==null?void 0:t.priority)||"standard"),l=Cy((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(D,{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(us,{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(Se,{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(X,{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(X,{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(D,{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(D,{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(Ay,{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(cp,{"data-slot":"dialog",...t})}function ky({...t}){return e.jsx(lp,{"data-slot":"dialog-portal",...t})}const em=x.forwardRef(({className:t,...s},a)=>e.jsx(Xc,{ref:a,"data-slot":"dialog-overlay",className:le("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}));em.displayName=Xc.displayName;const Ze=x.forwardRef(({className:t,children:s,...a},r)=>e.jsxs(ky,{"data-slot":"dialog-portal",children:[e.jsx(em,{}),e.jsxs(Qc,{ref:r,"data-slot":"dialog-content",className:le("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(op,{className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[e.jsx(ft,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Ze.displayName=Qc.displayName;const tt=x.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,"data-slot":"dialog-header",className:le("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:le("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s}));wt.displayName="DialogFooter";const Xe=x.forwardRef(({className:t,...s},a)=>e.jsx(Jc,{ref:a,"data-slot":"dialog-title",className:le("text-lg leading-none font-semibold",t),...s}));Xe.displayName=Jc.displayName;const qt=x.forwardRef(({className:t,...s},a)=>e.jsx(ed,{ref:a,"data-slot":"dialog-description",className:le("text-muted-foreground text-sm",t),...s}));qt.displayName=ed.displayName;function Ki({className:t,...s}){return e.jsx(dp,{"data-slot":"checkbox",className:le("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(mp,{"data-slot":"checkbox-indicator",className:"flex items-center justify-center text-current transition-none",children:e.jsx(Aa,{className:"size-3.5"})})})}async function tm(t){return(await ne.get(`/summaries/${t}`)).data.data}async function Ry(t,s){return(await ne.post(`/summaries/${t}/share`,{userIds:s})).data.data}async function Py(t={}){var n,i;const{page:s=1,limit:a=20}=t,r=await ne.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 sm(t){await ne.patch(`/summaries/shared/${t}/view`)}async function Dy(t){var s;try{return(await ne.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 Ey(t){return(await ne.get(`/summaries/${t}/recipients`)).data.data||[]}async function xs(t,s=10){return await ne.get("/users/search",{params:{q:t,limit:s}})}async function Ss(t){var a;const s=await ne.post("/users/ensure",t);return((a=s.data)==null?void 0:a.data)||s.data}async function My(t,s,a){return await ne.post("/admin/users/assign-role",{email:t,role:s,userData:a?{userId:a.userId,email:a.email,displayName:a.displayName,firstName:a.firstName,lastName:a.lastName,department:a.department,phone:a.phone,mobilePhone:a.mobilePhone,designation:a.designation,jobTitle:a.jobTitle,manager:a.manager,employeeId:a.employeeId,employeeNumber:a.employeeNumber,secondEmail:a.secondEmail,location:a.location}:void 0})}async function Iy(t,s){return await ne.put(`/admin/users/${t}/role`,{role:s})}async function Fy(t,s=1,a=10){return await ne.get("/admin/users/by-role",{params:{role:t||"ELEVATED",page:s,limit:a}})}async function _y(){return await ne.get("/admin/users/role-statistics")}async function Ly(){var s,a;return((a=(s=(await ne.get("/users")).data)==null?void 0:s.data)==null?void 0:a.users)||[]}const Gt={searchUsers:xs,ensureUserExists:Ss,assignRole:My,updateUserRole:Iy,getUsersByRole:Fy,getRoleStatistics:_y,getAllUsers:Ly};function Oy({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||!i.trim()){c([]);return}const f=setTimeout(async()=>{var j;try{h(!0);const b=await xs(i),w=((j=b==null?void 0:b.data)==null?void 0:j.data)||(b==null?void 0:b.data)||[];c(Array.isArray(w)?w:[])}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(j=>{const b=new Set(j);return b.has(f)?b.delete(f):b.add(f),b})},v=async()=>{var f,j;if(d.size===0){be.error("Please select at least one user to share with");return}try{g(!0),await Ry(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(((j=(f=b==null?void 0:b.response)==null?void 0:f.data)==null?void 0:j.message)||"Failed to share summary")}finally{g(!1)}},C=()=>{m(new Set),o(""),c([]),s()};return e.jsx(et,{open:t,onOpenChange:C,children:e.jsxs(Ze,{className:"sm:max-w-[500px]",children:[e.jsx(tt,{children:e.jsx(Xe,{children:"Share Summary"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{children:[e.jsx(Z,{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(Z,{htmlFor:"user-search",className:"text-sm font-medium text-gray-700",children:"Search Users"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(xe,{id:"user-search",placeholder:"Search by name or email...",value:i,onChange:f=>o(f.target.value),className:"pl-10"})]})]}),u&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(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 j=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(Ki,{checked:j,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&&l.length===0&&e.jsx("div",{className:"text-center py-8 text-gray-500 text-sm",children:"No users found"}),d.size>0&&e.jsxs("div",{className:"border rounded-lg p-3 bg-blue-50",children:[e.jsxs("p",{className:"text-sm font-medium text-gray-700 mb-2",children:["Selected (",d.size,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(d).map(f=>{const j=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:(j==null?void 0:j.displayName)||(j==null?void 0:j.email)||f}),e.jsx("button",{onClick:()=>y(f),className:"ml-1 hover:text-red-600",children:e.jsx(ft,{className:"h-3 w-3"})})]},f)})})]})]}),e.jsxs(wt,{children:[e.jsx(D,{variant:"outline",onClick:C,disabled:p,children:"Cancel"}),e.jsx(D,{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)`})]})]})})}function am({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);x.useEffect(()=>{o.current&&o.current.innerHTML!==t&&o.current.innerHTML!==t&&(o.current.innerHTML=t||"")},[t]);const u=x.useCallback(j=>(j=j.replace(/<!--[\s\S]*?-->/g,""),j=j.replace(/<style[^>]*>[\s\S]*?<\/style>/gi,""),j=j.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,""),j=j.replace(/<meta[^>]*>/gi,""),j=j.replace(/\s*class="Mso[^"]*"/gi,""),j=j.replace(/\s*class="mso[^"]*"/gi,""),j=j.replace(/\s*style="[^"]*mso-[^"]*"/gi,""),j=j.replace(/\s*style="[^"]*font-family:[^"]*"/gi,""),j=j.replace(/\s*xmlns[^=]*="[^"]*"/gi,""),j=j.replace(/<\/?o:p[^>]*>/gi,""),j=j.replace(/<v:[^>]*>[\s\S]*?<\/v:[^>]*>/gi,""),j=j.replace(/<v:[^>]*\/>/gi,""),j=j.replace(/<p[^>]*>\s*<\/p>/gi,""),j=j.replace(/<div[^>]*>\s*<\/div>/gi,""),j=j.replace(/\s+/g," "),j=j.trim(),j),[]),h=x.useCallback(j=>{j.preventDefault();const b=j.clipboardData;let w=b.getData("text/html")||b.getData("text/plain");if((w.includes("<!--")||w.includes("<style")||w.includes("MsoNormal"))&&(w=u(w)),!o.current)return;const T=window.getSelection();if(!T||T.rangeCount===0)return;const R=T.getRangeAt(0);R.deleteContents();const k=document.createElement("div");k.innerHTML=w;const F=document.createDocumentFragment();Array.from(k.childNodes).forEach(N=>{if(N.nodeType===Node.ELEMENT_NODE){const A=N;if(A.tagName==="UL"||A.tagName==="OL"){const I=A.cloneNode(!0);I.removeAttribute("style"),I.removeAttribute("class"),I.querySelectorAll("li").forEach(V=>{V.removeAttribute("style"),V.removeAttribute("class");const _=V.textContent||"";_.trim()&&(V.textContent=_.trim())}),F.appendChild(I)}else if(A.tagName==="TABLE"){const I=A.cloneNode(!0);I.removeAttribute("style"),I.removeAttribute("class"),I.querySelectorAll("td, th").forEach(_=>{_.removeAttribute("style"),_.removeAttribute("class")});const V=document.createElement("div");V.className="table-wrapper",V.style.overflowX="auto",V.style.maxWidth="100%",V.style.margin="8px 0",V.appendChild(I),F.appendChild(V)}else if(A.tagName==="P"||A.tagName==="DIV"){const I=document.createElement("p"),_=A.innerHTML.replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<!--[\s\S]*?-->/g,"");I.innerHTML=_,I.removeAttribute("style"),I.removeAttribute("class"),F.appendChild(I)}else if(A.tagName==="BR")F.appendChild(A.cloneNode(!0));else{const I=A.textContent||"";if(I.trim()){const V=document.createElement("p");V.textContent=I.trim(),F.appendChild(V)}}}else if(N.nodeType===Node.TEXT_NODE){const A=N.textContent||"";if(A.trim()){const I=document.createElement("p");I.textContent=A.trim(),F.appendChild(I)}}}),F.childNodes.length===0&&b.getData("text/plain").split(`
|
||
`).forEach(I=>{if(I.trim()){const V=document.createElement("p");V.textContent=I.trim(),F.appendChild(V)}else F.appendChild(document.createElement("br"))}),R.insertNode(F),R.collapse(!1),T.removeAllRanges(),T.addRange(R),o.current&&s(o.current.innerHTML)},[s,u]),p=x.useCallback(()=>{if(!o.current||!l)return;const j=new Set,b=window.getSelection();if(b&&b.rangeCount>0){const T=b.getRangeAt(0).commonAncestorContainer;let R=null;for(T.nodeType===Node.TEXT_NODE?R=T.parentElement:R=T;R&&R!==o.current;){const k=R.tagName.toLowerCase();(k==="strong"||k==="b")&&j.add("bold"),(k==="em"||k==="i")&&j.add("italic"),k==="u"&&j.add("underline"),k==="h1"&&j.add("h1"),k==="h2"&&j.add("h2"),k==="h3"&&j.add("h3"),k==="ul"&&j.add("ul"),k==="ol"&&j.add("ol");const F=window.getComputedStyle(R);F.textAlign==="center"&&j.add("center"),F.textAlign==="right"&&j.add("right"),F.textAlign==="left"&&j.add("left"),R=R.parentElement}}m(j)},[l]),g=x.useCallback((j,b)=>{if(!o.current)return;l||o.current.focus();const w=window.getSelection();if(!w||w.rangeCount===0){o.current.focus();return}document.execCommand(j,!1,b),o.current&&s(o.current.innerHTML),setTimeout(p,10)},[l,s,p]),y=x.useCallback(()=>{o.current&&s(o.current.innerHTML),p()},[s,p]),v=x.useCallback(j=>{if(j.ctrlKey&&j.key==="b"){j.preventDefault(),g("bold");return}if(j.ctrlKey&&j.key==="i"){j.preventDefault(),g("italic");return}if(j.ctrlKey&&j.key==="u"){j.preventDefault(),g("underline");return}},[g]),C=x.useCallback(()=>{c(!0)},[]),f=x.useCallback(()=>{c(!1),o.current&&s(o.current.innerHTML)},[s]);return x.useEffect(()=>{if(!l)return;const j=()=>{p()};return document.addEventListener("selectionchange",j),()=>{document.removeEventListener("selectionchange",j)}},[l,p]),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(D,{type:"button",variant:"ghost",size:"sm",className:le("h-7 w-7 p-0",d.has("bold")&&"bg-blue-100 text-blue-700"),onClick:()=>g("bold"),title:"Bold (Ctrl+B)",children:e.jsx(Qp,{className:"h-4 w-4"})}),e.jsx(D,{type:"button",variant:"ghost",size:"sm",className:le("h-7 w-7 p-0",d.has("italic")&&"bg-blue-100 text-blue-700"),onClick:()=>g("italic"),title:"Italic (Ctrl+I)",children:e.jsx(Jp,{className:"h-4 w-4"})}),e.jsx(D,{type:"button",variant:"ghost",size:"sm",className:le("h-7 w-7 p-0",d.has("underline")&&"bg-blue-100 text-blue-700"),onClick:()=>g("underline"),title:"Underline (Ctrl+U)",children:e.jsx(ex,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-1 border-r border-gray-300 pr-2",children:[e.jsx(D,{type:"button",variant:"ghost",size:"sm",className:le("h-7 w-7 p-0",d.has("h1")&&"bg-blue-100 text-blue-700"),onClick:()=>g("formatBlock","<h1>"),title:"Heading 1",children:e.jsx(tx,{className:"h-4 w-4"})}),e.jsx(D,{type:"button",variant:"ghost",size:"sm",className:le("h-7 w-7 p-0",d.has("h2")&&"bg-blue-100 text-blue-700"),onClick:()=>g("formatBlock","<h2>"),title:"Heading 2",children:e.jsx(sx,{className:"h-4 w-4"})}),e.jsx(D,{type:"button",variant:"ghost",size:"sm",className:le("h-7 w-7 p-0",d.has("h3")&&"bg-blue-100 text-blue-700"),onClick:()=>g("formatBlock","<h3>"),title:"Heading 3",children:e.jsx(ax,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-1 border-r border-gray-300 pr-2",children:[e.jsx(D,{type:"button",variant:"ghost",size:"sm",className:le("h-7 w-7 p-0",d.has("ul")&&"bg-blue-100 text-blue-700"),onClick:()=>g("insertUnorderedList"),title:"Bullet List",children:e.jsx(ud,{className:"h-4 w-4"})}),e.jsx(D,{type:"button",variant:"ghost",size:"sm",className:le("h-7 w-7 p-0",d.has("ol")&&"bg-blue-100 text-blue-700"),onClick:()=>g("insertOrderedList"),title:"Numbered List",children:e.jsx(rx,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(D,{type:"button",variant:"ghost",size:"sm",className:le("h-7 w-7 p-0",d.has("left")&&"bg-blue-100 text-blue-700"),onClick:()=>g("justifyLeft"),title:"Align Left",children:e.jsx(nx,{className:"h-4 w-4"})}),e.jsx(D,{type:"button",variant:"ghost",size:"sm",className:le("h-7 w-7 p-0",d.has("center")&&"bg-blue-100 text-blue-700"),onClick:()=>g("justifyCenter"),title:"Align Center",children:e.jsx(ix,{className:"h-4 w-4"})}),e.jsx(D,{type:"button",variant:"ghost",size:"sm",className:le("h-7 w-7 p-0",d.has("right")&&"bg-blue-100 text-blue-700"),onClick:()=>g("justifyRight"),title:"Align Right",children:e.jsx(ox,{className:"h-4 w-4"})})]})]}),e.jsx("div",{ref:o,contentEditable:!0,onPaste:h,onInput:y,onFocus:C,onBlur:f,onKeyDown:v,onMouseUp:p,onKeyUp:p,"data-placeholder":a,className:le("w-full rounded-b-md border-0 px-3 py-2 text-base transition-all outline-none","bg-white text-gray-900","min-h-[120px]","overflow-y-auto","overflow-x-auto","md:overflow-x-visible","md:text-sm","empty:before:content-[attr(data-placeholder)] empty:before:text-muted-foreground empty:before:pointer-events-none","focus-visible:outline-none","[&_ul]:list-disc [&_ul]:ml-6 [&_ul]:my-2 [&_ul]:list-outside","[&_ol]:list-decimal [&_ol]:ml-6 [&_ol]:my-2 [&_ol]:list-outside","[&_li]:my-1 [&_li]:pl-2","[&_.table-wrapper]:overflow-x-auto [&_.table-wrapper]:max-w-full [&_.table-wrapper]:my-2","[&_.table-wrapper_table]:border-collapse [&_.table-wrapper_table]:border [&_.table-wrapper_table]:border-gray-300 [&_.table-wrapper_table]:min-w-full","[&_.table-wrapper_table_td]:border [&_.table-wrapper_table_td]:border-gray-300 [&_.table-wrapper_table_td]:px-3 [&_.table-wrapper_table_td]:py-2 [&_.table-wrapper_table_td]:text-sm [&_.table-wrapper_table_td]:whitespace-nowrap","[&_.table-wrapper_table_th]:border [&_.table-wrapper_table_th]:border-gray-300 [&_.table-wrapper_table_th]:px-3 [&_.table-wrapper_table_th]:py-2 [&_.table-wrapper_table_th]:bg-gray-50 [&_.table-wrapper_table_th]:font-semibold [&_.table-wrapper_table_th]:text-sm [&_.table-wrapper_table_th]:text-left [&_.table-wrapper_table_th]:whitespace-nowrap","[&_.table-wrapper_table_tr:nth-child(even)]:bg-gray-50","[&_table]:border-collapse [&_table]:my-2 [&_table]:border [&_table]:border-gray-300 [&_table]:w-full","[&_table_td]:border [&_table_td]:border-gray-300 [&_table_td]:px-3 [&_table_td]:py-2 [&_table_td]:text-sm","[&_table_th]:border [&_table_th]:border-gray-300 [&_table_th]:px-3 [&_table_th]:py-2 [&_table_th]:bg-gray-50 [&_table_th]:font-semibold [&_table_th]:text-sm [&_table_th]:text-left","[&_table_tr:nth-child(even)]:bg-gray-50","[&_p]:my-1 [&_p]:leading-relaxed","[&_strong]:font-bold","[&_em]:italic","[&_u]:underline","[&_h1]:text-xl [&_h1]:font-bold [&_h1]:my-2","[&_h2]:text-lg [&_h2]:font-semibold [&_h2]:my-2","[&_h3]:text-base [&_h3]:font-semibold [&_h3]:my-1",r),style:{minHeight:n},...i})]})}function 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:le("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 rm={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(Vr,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+)?$/,C=/\[([^\]]+)]|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(_){var L=["th","st","nd","rd"],S=_%100;return"["+_+(L[(S-20)%10]||L[S]||L[0])+"]"}},j=function(_,L,S){var M=String(_);return!M||M.length>=L?_:""+Array(L+1-M.length).join(S)+_},b={s:j,z:function(_){var L=-_.utcOffset(),S=Math.abs(L),M=Math.floor(S/60),P=S%60;return(L<=0?"+":"-")+j(M,2,"0")+":"+j(P,2,"0")},m:function _(L,S){if(L.date()<S.date())return-_(S,L);var M=12*(S.year()-L.year())+(S.month()-L.month()),P=L.clone().add(M,u),E=S-P<0,H=L.clone().add(M+(E?-1:1),u);return+(-(M+(S-P)/(E?P-H:H-P))||0)},a:function(_){return _<0?Math.ceil(_)||0:Math.floor(_)},p:function(_){return{M:u,y:p,w:m,d,D:g,h:c,m:l,s:o,ms:i,Q:h}[_]||String(_||"").toLowerCase().replace(/s$/,"")},u:function(_){return _===void 0}},w="en",T={};T[w]=f;var R="$isDayjsObject",k=function(_){return _ instanceof I||!(!_||!_[R])},F=function _(L,S,M){var P;if(!L)return w;if(typeof L=="string"){var E=L.toLowerCase();T[E]&&(P=E),S&&(T[E]=S,P=E);var H=L.split("-");if(!P&&H.length>1)return _(H[0])}else{var q=L.name;T[q]=L,P=q}return!M&&P&&(w=P),P||!M&&w},N=function(_,L){if(k(_))return _.clone();var S=typeof L=="object"?L:{};return S.date=_,S.args=arguments,new I(S)},A=b;A.l=F,A.i=k,A.w=function(_,L){return N(_,{locale:L.$L,utc:L.$u,x:L.$x,$offset:L.$offset})};var I=function(){function _(S){this.$L=F(S.locale,null,!0),this.parse(S),this.$x=this.$x||S.x||{},this[R]=!0}var L=_.prototype;return L.parse=function(S){this.$d=function(M){var P=M.date,E=M.utc;if(P===null)return new Date(NaN);if(A.u(P))return new Date;if(P instanceof Date)return new Date(P);if(typeof P=="string"&&!/Z$/i.test(P)){var H=P.match(v);if(H){var q=H[2]-1||0,J=(H[7]||"0").substring(0,3);return E?new Date(Date.UTC(H[1],q,H[3]||1,H[4]||0,H[5]||0,H[6]||0,J)):new Date(H[1],q,H[3]||1,H[4]||0,H[5]||0,H[6]||0,J)}}return new Date(P)}(S),this.init()},L.init=function(){var S=this.$d;this.$y=S.getFullYear(),this.$M=S.getMonth(),this.$D=S.getDate(),this.$W=S.getDay(),this.$H=S.getHours(),this.$m=S.getMinutes(),this.$s=S.getSeconds(),this.$ms=S.getMilliseconds()},L.$utils=function(){return A},L.isValid=function(){return this.$d.toString()!==y},L.isSame=function(S,M){var P=N(S);return this.startOf(M)<=P&&P<=this.endOf(M)},L.isAfter=function(S,M){return N(S)<this.startOf(M)},L.isBefore=function(S,M){return this.endOf(M)<N(S)},L.$g=function(S,M,P){return A.u(S)?this[M]:this.set(P,S)},L.unix=function(){return Math.floor(this.valueOf()/1e3)},L.valueOf=function(){return this.$d.getTime()},L.startOf=function(S,M){var P=this,E=!!A.u(M)||M,H=A.p(S),q=function(G,Q){var ie=A.w(P.$u?Date.UTC(P.$y,Q,G):new Date(P.$y,Q,G),P);return E?ie:ie.endOf(d)},J=function(G,Q){return A.w(P.toDate()[G].apply(P.toDate("s"),(E?[0,0,0,0]:[23,59,59,999]).slice(Q)),P)},B=this.$W,oe=this.$M,ge=this.$D,z="set"+(this.$u?"UTC":"");switch(H){case p:return E?q(1,0):q(31,11);case u:return E?q(1,oe):q(0,oe+1);case m:var re=this.$locale().weekStart||0,ye=(B<re?B+7:B)-re;return q(E?ge-ye:ge+(6-ye),oe);case d:case g:return J(z+"Hours",0);case c:return J(z+"Minutes",1);case l:return J(z+"Seconds",2);case o:return J(z+"Milliseconds",3);default:return this.clone()}},L.endOf=function(S){return this.startOf(S,!1)},L.$set=function(S,M){var P,E=A.p(S),H="set"+(this.$u?"UTC":""),q=(P={},P[d]=H+"Date",P[g]=H+"Date",P[u]=H+"Month",P[p]=H+"FullYear",P[c]=H+"Hours",P[l]=H+"Minutes",P[o]=H+"Seconds",P[i]=H+"Milliseconds",P)[E],J=E===d?this.$D+(M-this.$W):M;if(E===u||E===p){var B=this.clone().set(g,1);B.$d[q](J),B.init(),this.$d=B.set(g,Math.min(this.$D,B.daysInMonth())).$d}else q&&this.$d[q](J);return this.init(),this},L.set=function(S,M){return this.clone().$set(S,M)},L.get=function(S){return this[A.p(S)]()},L.add=function(S,M){var P,E=this;S=Number(S);var H=A.p(M),q=function(oe){var ge=N(E);return A.w(ge.date(ge.date()+Math.round(oe*S)),E)};if(H===u)return this.set(u,this.$M+S);if(H===p)return this.set(p,this.$y+S);if(H===d)return q(1);if(H===m)return q(7);var J=(P={},P[l]=r,P[c]=n,P[o]=a,P)[H]||1,B=this.$d.getTime()+S*J;return A.w(B,this)},L.subtract=function(S,M){return this.add(-1*S,M)},L.format=function(S){var M=this,P=this.$locale();if(!this.isValid())return P.invalidDate||y;var E=S||"YYYY-MM-DDTHH:mm:ssZ",H=A.z(this),q=this.$H,J=this.$m,B=this.$M,oe=P.weekdays,ge=P.months,z=P.meridiem,re=function(Q,ie,Y,ue){return Q&&(Q[ie]||Q(M,E))||Y[ie].slice(0,ue)},ye=function(Q){return A.s(q%12||12,Q,"0")},G=z||function(Q,ie,Y){var ue=Q<12?"AM":"PM";return Y?ue.toLowerCase():ue};return E.replace(C,function(Q,ie){return ie||function(Y){switch(Y){case"YY":return String(M.$y).slice(-2);case"YYYY":return A.s(M.$y,4,"0");case"M":return B+1;case"MM":return A.s(B+1,2,"0");case"MMM":return re(P.monthsShort,B,ge,3);case"MMMM":return re(ge,B);case"D":return M.$D;case"DD":return A.s(M.$D,2,"0");case"d":return String(M.$W);case"dd":return re(P.weekdaysMin,M.$W,oe,2);case"ddd":return re(P.weekdaysShort,M.$W,oe,3);case"dddd":return oe[M.$W];case"H":return String(q);case"HH":return A.s(q,2,"0");case"h":return ye(1);case"hh":return ye(2);case"a":return G(q,J,!0);case"A":return G(q,J,!1);case"m":return String(J);case"mm":return A.s(J,2,"0");case"s":return String(M.$s);case"ss":return A.s(M.$s,2,"0");case"SSS":return A.s(M.$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(S,M,P){var E,H=this,q=A.p(M),J=N(S),B=(J.utcOffset()-this.utcOffset())*r,oe=this-J,ge=function(){return A.m(H,J)};switch(q){case p:E=ge()/12;break;case u:E=ge();break;case h:E=ge()/3;break;case m:E=(oe-B)/6048e5;break;case d:E=(oe-B)/864e5;break;case c:E=oe/n;break;case l:E=oe/r;break;case o:E=oe/a;break;default:E=oe}return P?E:A.a(E)},L.daysInMonth=function(){return this.endOf(u).$D},L.$locale=function(){return T[this.$L]},L.locale=function(S,M){if(!S)return this.$L;var P=this.clone(),E=F(S,M,!0);return E&&(P.$L=E),P},L.clone=function(){return A.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()},_}(),V=I.prototype;return N.prototype=V,[["$ms",i],["$s",o],["$m",l],["$H",c],["$W",d],["$M",u],["$y",p],["$D",g]].forEach(function(_){V[_[1]]=function(L){return this.$g(L,_[0],_[1])}}),N.extend=function(_,L){return _.$i||(_(L,I,N),_.$i=!0),N},N.locale=F,N.isDayjs=k,N.unix=function(_){return N(1e3*_)},N.en=T[w],N.Ls=T,N.p={},N})})(rm);var $y=rm.exports;const st=zr($y);var nm={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(Vr,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,C=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"}],j=f.length,b=0;b<j;b+=1){var w=f[b];w.d&&(g=h?n(d).diff(u,w.d,!0):u.diff(d,w.d,!0));var T=(a.rounding||Math.round)(Math.abs(g));if(v=g>0,T<=w.r||!w.r){T<=1&&b>0&&(w=f[b-1]);var R=C[w.l];p&&(T=p(""+T)),y=typeof R=="string"?R.replace("%d",T):R(T,m,w.l,v);break}}if(m)return y;var k=v?C.future:C.past;return typeof k=="function"?k(y):k.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)}}})})(nm);var Uy=nm.exports;const By=zr(Uy);st.extend(By);function Vy({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 R,k,F,N,A,I,V,_;const{user:v}=Mt(),C=t==null?void 0:t.pauseInfo,f=(C==null?void 0:C.isPaused)||!1,j=(R=C==null?void 0:C.pausedBy)==null?void 0:R.userId,b=(v==null?void 0:v.userId)||"",w=f&&u&&(p||s),T=f&&s&&j&&j!==b&&h;return e.jsxs("div",{className:"space-y-4 sm:space-y-6","data-testid":"overview-tab-content",children:[e.jsxs(W,{"data-testid":"initiator-card",children:[e.jsx(ee,{className:"pb-3 sm:pb-4",children:e.jsxs(te,{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(K,{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:((k=t.initiator)==null?void 0:k.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:((F=t.initiator)==null?void 0:F.name)||"N/A"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 truncate",children:((N=t.initiator)==null?void 0:N.role)||"N/A"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-500 truncate",children:((A=t.initiator)==null?void 0:A.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(Li,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:((I=t.initiator)==null?void 0:I.email)||"N/A"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs sm:text-sm text-gray-600",children:[e.jsx(fd,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{children:((V=t.initiator)==null?void 0:V.phone)||"N/A"})]})]})]})]})})]}),e.jsxs(W,{"data-testid":"request-details-card",children:[e.jsx(ee,{className:"pb-3 sm:pb-4",children:e.jsxs(te,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Se,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Details"]})}),e.jsxs(K,{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&&C&&e.jsxs(W,{className:"border-orange-300 bg-orange-50/50","data-testid":"pause-status-card",children:[e.jsx(ee,{className:"pb-3 sm:pb-4",children:e.jsxs(te,{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(K,{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:[C.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:C.pauseReason})]}),C.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:C.pausedBy.name||C.pausedBy.email})]}),C.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(C.pauseResumeDate),st(C.pauseResumeDate).isAfter(st())&&e.jsxs("span",{className:"ml-2 text-xs text-gray-500",children:["(",st(C.pauseResumeDate).fromNow(),")"]})]})]}),C.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(C.pausedAt)})]})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-2 border-t border-orange-200",children:[w&&u&&e.jsxs(D,{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(Mr,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-1.5"}),"Resume Now"]}),T&&h&&e.jsxs(D,{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(W,{children:[e.jsx(ee,{className:"pb-4",children:e.jsxs(te,{className:"flex items-center gap-2 text-base",children:[e.jsx(Se,{className:"w-5 h-5 text-purple-600"}),"Claim Management Details"]})}),e.jsxs(K,{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?Xd(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(W,{children:[e.jsxs(ee,{className:"bg-gradient-to-r from-gray-50 to-slate-50 border-b border-gray-200",children:[e.jsxs(te,{className:"flex items-center gap-2 text-base",children:[e.jsx(je,{className:"w-5 h-5 text-gray-600"}),"Conclusion Remark"]}),e.jsx(pe,{className:"mt-1 text-xs sm:text-sm",children:"Final summary of this closed request"})]}),e.jsxs(K,{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 ",((_=t.initiator)==null?void 0:_.name)||"Initiator"]})]})]})]}),a&&e.jsxs(W,{"data-testid":"conclusion-remark-card",children:[e.jsx(ee,{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(te,{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(pe,{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(D,{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(K,{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(am,{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."}),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(D,{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 Ar({delayDuration:t=0,...s}){return e.jsx(up,{"data-slot":"tooltip-provider",delayDuration:t,...s})}function Cn({...t}){return e.jsx(Ar,{children:e.jsx(hp,{"data-slot":"tooltip",...t})})}function Sn({...t}){return e.jsx(pp,{"data-slot":"tooltip-trigger",...t})}function An({className:t,sideOffset:s=0,children:a,...r}){return e.jsx(xp,{children:e.jsxs(gp,{"data-slot":"tooltip-content",sideOffset:s,className:le("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(fp,{className:"bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function fs({className:t,...s}){return e.jsx("textarea",{"data-slot":"textarea",className:le("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 hl=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`},zy=(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(yd,{className:"w-4 h-4 sm:w-5 sm:h-5 text-yellow-600"});case"pending":case"in-review":return e.jsx(Ee,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"});case"waiting":return e.jsx(Ee,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400"});default:return e.jsx(Ee,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400"})}};function Hy({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 C=t.status==="pending"||t.status==="in-review",f=t.status==="approved",j=t.status==="rejected",b=t.status==="waiting",w=t.status==="paused",T=Number(t.tatHours||0),R=t.actualHours??0,k=f&&R?Math.max(0,T-R):0,F=T>0?R/T*100:0,N=F>=100,A=(d==null?void 0:d.role)==="ADMIN",I=Zr(d),V=t.approverId===(d==null?void 0:d.userId),_=A||I||V,L=async()=>{var S,M;if(!h.trim()){be.error("Breach Reason Required",{description:"Please enter a reason for the breach."});return}y(!0);try{await L0(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(P){console.error("Error updating breach reason:",P);const E=((M=(S=P==null?void 0:P.response)==null?void 0:S.data)==null?void 0:M.error)||(P==null?void 0:P.message)||"Failed to update breach reason. Please try again.";be.error("Failed to Update Breach Reason",{description:E,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":C?"border-blue-500 bg-blue-50 shadow-md":f?"border-green-500 bg-green-50":j?"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":w?"bg-yellow-100":C?"bg-blue-100":f?"bg-green-100":j?"bg-red-100":b?"bg-gray-200":"bg-gray-100"}`,children:zy(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(X,{variant:"outline",className:`text-xs shrink-0 capitalize ${t.isSkipped?"bg-orange-100 text-orange-800 border-orange-200":C?"bg-yellow-100 text-yellow-800 border-yellow-200":f?"bg-green-100 text-green-800 border-green-200":j?"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(Ar,{delayDuration:200,children:e.jsxs(Cn,{children:[e.jsx(Sn,{asChild:!0,children:e.jsx("button",{type:"button",className:"inline-flex items-center justify-center cursor-pointer hover:opacity-80 transition-opacity",onClick:S=>S.stopPropagation(),children:e.jsx(Pe,{className:"w-4 h-4 text-orange-600"})})}),e.jsxs(An,{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(Go,{className:"w-3 h-3"}),"Skip Reason:"]}),e.jsx("p",{className:"text-xs text-gray-700",children:t.skipReason})]})]})}),f&&R&&e.jsx(X,{className:"bg-green-600 text-white text-xs","data-testid":`${c}-completion-time`,children:hl(R)})]}),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:[T," hours"]})]})]}),f&&R!==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:hl(R)})]}),e.jsx("div",{className:"space-y-2",children:(()=>{const S=Math.min(100,F),M=()=>N?"bg-red-600":F>=75?"bg-orange-500":F>=50?"bg-amber-500":"bg-green-600",P=()=>N?"text-red-600":F>=75?"text-orange-600":F>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(hs,{value:S,className:"h-2 bg-gray-200",indicatorClassName:M(),"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 ${P()}`,children:[Math.round(S),"% of TAT used"]}),N&&_&&e.jsx(Ar,{children:e.jsxs(Cn,{children:[e.jsx(Sn,{asChild:!0,children:e.jsx(D,{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(An,{children:e.jsx("p",{children:v?"Edit breach reason":"Add breach reason"})})]})})]}),k>0&&e.jsxs("span",{className:"text-green-600 font-semibold",children:["Saved ",ot(k)]})]})]})})()}),N&&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(gs,{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&&(C||w)&&(a==null?void 0:a.sla)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Due by:"}),e.jsx("span",{className:"font-medium text-gray-900",children:a.sla.deadline?ps(a.sla.deadline,!0):"Not set"})]}),e.jsxs("div",{className:`border rounded-lg p-3 ${w?"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(Ee,{className:"w-4 h-4"}),"Current Approver - Time Tracking ",w&&"(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(T)," allocated"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[(()=>{const S=a.sla.percentageUsed||0,M=()=>w?"bg-gray-500":S>=100?"bg-red-600":S>=75?"bg-orange-500":S>=50?"bg-amber-500":"bg-green-600",P=()=>w?"text-gray-600":S>=100?"text-red-600":S>=75?"text-orange-600":S>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(hs,{value:a.sla.percentageUsed,className:"h-3",indicatorClassName:M(),"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 ${P()}`,children:["Progress: ",Math.min(100,a.sla.percentageUsed),"% of TAT used"]}),a.sla.status==="breached"&&_&&e.jsx(Ar,{children:e.jsxs(Cn,{children:[e.jsx(Sn,{asChild:!0,children:e.jsx(D,{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(An,{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(ti,{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(yd,{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 ",T," hours for approval"]})]})}),j&&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(Go,{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((S,M)=>{var P,E,H,q,J,B;return e.jsx("div",{className:`p-2 sm:p-3 rounded-lg border ${S.isBreached?"bg-red-50 border-red-200":(S.thresholdPercentage||0)===75?"bg-orange-50 border-orange-200":"bg-yellow-50 border-yellow-200"}`,"data-testid":`${c}-tat-alert-${M}`,children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("div",{className:"flex-shrink-0 mt-0.5",children:[(S.thresholdPercentage||0)===50&&e.jsx(lx,{className:"w-5 h-5 text-yellow-600"}),(S.thresholdPercentage||0)===75&&e.jsx(is,{className:"w-5 h-5 text-orange-600"}),(S.thresholdPercentage||0)===100&&e.jsx(ti,{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 ",M+1," - ",S.thresholdPercentage||0,"% TAT"]}),e.jsx(X,{variant:"outline",className:`text-[10px] sm:text-xs shrink-0 ${S.isBreached?"bg-red-100 text-red-800 border-red-300":"bg-amber-100 text-amber-800 border-amber-300"}`,children:S.isBreached?"BREACHED":"WARNING"})]}),e.jsxs("p",{className:"text-[10px] sm:text-xs md:text-sm text-gray-700 mt-1",children:[S.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(S.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(S.tatHoursElapsed||0)),((P=S.metadata)==null?void 0:P.tatTestMode)&&e.jsxs("span",{className:"text-purple-600 ml-1",children:["(",(Number(S.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 ${(S.tatHoursRemaining||0)<2?"text-red-600":"text-gray-900"}`,children:[ot(Number(S.tatHoursRemaining||0)),((E=S.metadata)==null?void 0:E.tatTestMode)&&e.jsxs("span",{className:"text-purple-600 ml-1",children:["(",(Number(S.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:S.expectedCompletionTime?ps(S.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=S.metadata)==null?void 0:H.testMode)||((q=S.metadata)==null?void 0:q.tatTestMode))&&e.jsx(X,{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: ",S.alertSentAt?Vt(S.alertSentAt):"N/A"]}),(((J=S.metadata)==null?void 0:J.testMode)||((B=S.metadata)==null?void 0:B.tatTestMode))&&e.jsx("p",{className:"text-[10px] text-purple-600 mt-1 italic",children:"Note: Test mode active (1 hour = 1 minute)"})]})]})]})},M)})}),t.timestamp&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:[f?"Approved":j?"Rejected":"Actioned"," on ",Vt(t.timestamp)]}),n&&!w&&(C||t.status==="pending")&&!f&&!j&&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(D,{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:w?"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(Ze,{className:"sm:max-w-[500px]",children:[e.jsxs(tt,{children:[e.jsx(Xe,{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(fs,{placeholder:"Enter the reason for the breach...",value:h,onChange:S=>p(S.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(D,{variant:"outline",onClick:()=>{u(!1),p("")},disabled:g,children:"Cancel"}),e.jsx(D,{onClick:L,disabled:!h.trim()||g,className:"bg-red-600 hover:bg-red-700",children:g?"Saving...":"Save Reason"})]})]})})]})}function qy({request:t,user:s,isInitiator:a,onSkipApprover:r,onRefresh:n}){return e.jsxs(W,{children:[e.jsx(ee,{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(te,{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(pe,{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(X,{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(X,{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(X,{variant:"outline",className:"font-medium text-xs sm:text-sm shrink-0",children:["Step ",h," of ",i," - ",l," completed"]})})()]})}),e.jsx(K,{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(Hy,{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 Wy=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 pl({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(Se,{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&&Wy(t.fileType)&&s&&e.jsx(D,{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(D,{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 Ky({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(W,{children:[e.jsx(ee,{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(te,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Se,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Documents"]}),e.jsx(pe,{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(D,{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(K,{children:t.documents&&t.documents.length>0?e.jsx("div",{className:"space-y-3",children:t.documents.map((l,c)=>e.jsx(pl,{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(W,{children:[e.jsxs(ee,{children:[e.jsxs(te,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(gs,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"Work Note Attachments"]}),e.jsx(pe,{className:"text-xs sm:text-sm",children:"Files shared in work notes discussions"})]}),e.jsx(K,{children:s&&s.length>0?e.jsx("div",{className:"space-y-3",children:s.map((l,c)=>e.jsx(pl,{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 Gy({request:t}){return e.jsxs(W,{children:[e.jsxs(ee,{children:[e.jsxs(te,{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(pe,{className:"text-xs sm:text-sm",children:"Complete audit trail of all request activities"})]}),e.jsx(K,{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:Sy(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 Gi({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,C]=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"),j=s.toLowerCase().includes("pdf"),b=f||j;x.useEffect(()=>{if(!o||!b||!a){p(null);return}return(async()=>{y(!0),C(null);try{let I=a;a.startsWith("/")&&!a.startsWith("//")&&(I=`${window.location.origin}${a}`);const _=await fetch(I,{headers:{Accept:j?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!_.ok){const M=await _.text().catch(()=>"");throw new Error(`Failed to load file: ${_.status} ${_.statusText}. ${M}`)}const L=await _.blob();if(L.size===0)throw new Error("File is empty or could not be loaded");j&&!L.type.includes("pdf")&&L.type!=="application/octet-stream"&&console.warn(`Expected PDF but got ${L.type}`);const S=window.URL.createObjectURL(L);p(S)}catch(N){console.error("Failed to load file for preview:",N),C(N instanceof Error?N.message:"Failed to load file for preview")}finally{y(!1)}})(),()=>{h&&(window.URL.revokeObjectURL(h),p(null))}},[o,a,b,j]);const w=async()=>{if(i&&n)try{await i(n)}catch{alert("Failed to download file")}},T=()=>d(F=>Math.min(F+25,200)),R=()=>d(F=>Math.max(F-25,50)),k=()=>u(F=>(F+90)%360);return e.jsx(et,{open:o,onOpenChange:l,children:e.jsx(Ze,{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(Xe,{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(D,{variant:"ghost",size:"sm",onClick:R,disabled:c<=50,title:"Zoom out",className:"h-8 w-8 p-0",children:e.jsx(cx,{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(D,{variant:"ghost",size:"sm",onClick:T,disabled:c>=200,title:"Zoom in",className:"h-8 w-8 p-0",children:e.jsx(dx,{className:"h-4 w-4"})}),e.jsx(D,{variant:"ghost",size:"sm",onClick:k,title:"Rotate",className:"h-8 w-8 p-0",children:e.jsx(mx,{className:"h-4 w-4"})})]}),i&&n&&e.jsxs(D,{variant:"outline",size:"sm",onClick:w,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(ft,{className:"w-10 h-10 text-red-600"})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Preview Failed"}),e.jsx("p",{className:"text-sm text-gray-600 mb-6",children:v}),i&&n&&e.jsxs(D,{onClick:w,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"})}),j&&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:()=>{C("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(D,{onClick:w,className:"gap-2",children:[e.jsx(ns,{className:"h-4 w-4"}),"Download ",t]})]})})]})})})}function im({open:t,onClose:s,success:a,title:r,message:n}){return e.jsx(et,{open:t,onOpenChange:s,children:e.jsxs(Ze,{className:"sm:max-w-md",children:[e.jsx(tt,{children:e.jsxs(Xe,{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(D,{onClick:s,className:`w-full ${a?"bg-green-600 hover:bg-green-700":"bg-gray-600 hover:bg-gray-700"}`,children:"OK"})})]})})}function om({open:t,onClose:s,violations:a,policyDetails:r}){return e.jsx(et,{open:t,onOpenChange:s,children:e.jsxs(Ze,{className:"sm:max-w-lg",children:[e.jsxs(tt,{children:[e.jsxs(Xe,{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(D,{onClick:s,className:"w-full sm:w-auto",children:"OK"})})]})})}function lm({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,C]=x.useState({open:!1,type:"error",email:"",message:""}),[f,j]=x.useState({open:!1,violations:[]}),[b,w]=x.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20});x.useEffect(()=>{t&&(async()=>{var A;try{const I=await ia("WORKFLOW_SHARING"),V=await ia("TAT_SETTINGS"),_=[...I,...V],L={};_.forEach(S=>{L[S.configKey]=S.configValue}),w({maxApprovalLevels:parseInt(L.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(L.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((A=L.ALLOW_ADD_SPECTATOR)==null?void 0:A.toLowerCase())==="true",maxSpectators:parseInt(L.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(I){console.error("Failed to load system policy:",I)}})()},[t]);const T=async()=>{var M,P;const N=n.trim().toLowerCase();if(!N){C({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(N)){C({open:!0,type:"error",email:N,message:"Please enter a valid email address"});return}const I=r.find(E=>(E.email||"").toLowerCase()===N);if(I){const E=((M=I.participantType)==null?void 0:M.toUpperCase())||"PARTICIPANT",H=I.name||N;if(E==="INITIATOR"){C({open:!0,type:"error",email:N,message:`${H} is the request initiator and cannot be added as a spectator.`});return}else if(E==="APPROVER"){C({open:!0,type:"error",email:N,message:`${H} is already an approver on this request and cannot be added as a spectator.`});return}else if(E==="SPECTATOR"){C({open:!0,type:"error",email:N,message:`${H} is already a spectator on this request.`});return}else{C({open:!0,type:"error",email:N,message:`${H} is already a participant on this request.`});return}}const V=[];b.allowSpectators||V.push({type:"Spectators Not Allowed",message:"Adding spectators is not allowed by system policy."});const L=r.filter(E=>(E.participantType||"").toUpperCase()==="SPECTATOR").length;L>=b.maxSpectators&&V.push({type:"Maximum Spectators Exceeded",message:"This request has reached the maximum number of spectators allowed.",currentValue:L,maxValue:b.maxSpectators});const S=r.length+1;if(S>b.maxParticipants&&V.push({type:"Maximum Participants Exceeded",message:"Adding this spectator would exceed the maximum participants limit.",currentValue:S,maxValue:b.maxParticipants}),V.length>0){j({open:!0,violations:V});return}if(!h||h.email.toLowerCase()!==N)try{const H=((P=(await xs(N,1)).data)==null?void 0:P.data)||[];if(H.length===0){C({open:!0,type:"not-found",email:N,message:""});return}const q=H[0];await Ss({userId:q.userId,email:q.email,displayName:q.displayName,firstName:q.firstName,lastName:q.lastName,department:q.department,phone:q.phone,mobilePhone:q.mobilePhone,designation:q.designation,jobTitle:q.jobTitle,manager:q.manager,employeeId:q.employeeId,employeeNumber:q.employeeNumber,secondEmail:q.secondEmail,location:q.location})}catch(E){console.error("Failed to validate spectator:",E),C({open:!0,type:"error",email:N,message:"Failed to validate user. Please try again."});return}try{l(!0),await a(N),i(""),p(null),s()}catch(E){console.error("Failed to add spectator:",E)}finally{l(!1)}},R=()=>{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 k=N=>{if(i(N),h&&h.email.toLowerCase()!==N.toLowerCase()&&p(null),g.current&&clearTimeout(g.current),!N||!N.startsWith("@")||N.length<2){d([]),u(!1);return}u(!0),g.current=setTimeout(async()=>{var A;try{const I=N.slice(1),_=((A=(await xs(I,10)).data)==null?void 0:A.data)||[];d(_)}catch(I){console.error("Search failed:",I),d([])}finally{u(!1)}},300)},F=async N=>{try{await Ss({userId:N.userId,email:N.email,displayName:N.displayName,firstName:N.firstName,lastName:N.lastName,department:N.department,phone:N.phone,mobilePhone:N.mobilePhone,designation:N.designation,jobTitle:N.jobTitle,manager:N.manager,employeeId:N.employeeId,employeeNumber:N.employeeNumber,secondEmail:N.secondEmail,location:N.location}),i(N.email),p(N),d([]),u(!1)}catch(A){console.error("Failed to ensure user exists:",A),C({open:!0,type:"error",email:N.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(et,{open:t,onOpenChange:R,children:[e.jsxs(Ze,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:R,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:o,children:[e.jsx(ft,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(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(Xe,{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(Oi,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(xe,{type:"text",placeholder:"@username or user@example.com",value:n,onChange:N=>k(N.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(N=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>F(N),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:(N.displayName||N.email).split(" ").map(A=>A[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:N.displayName||[N.firstName,N.lastName].filter(Boolean).join(" ")||N.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:N.email}),N.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:N.designation})]})]})},N.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(D,{type:"button",variant:"outline",onClick:R,className:"flex-1 h-11 border-gray-300",disabled:o,children:"Cancel"}),e.jsxs(D,{type:"button",onClick:T,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:N=>C(A=>({...A,open:N})),children:e.jsxs(Ze,{className:"sm:max-w-md",children:[e.jsxs(tt,{children:[e.jsx(Xe,{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(Wr,{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(D,{onClick:()=>C(N=>({...N,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(om,{open:f.open,onClose:()=>j({open:!1,violations:[]}),violations:f.violations,policyDetails:{maxApprovalLevels:b.maxApprovalLevels,maxParticipants:b.maxParticipants,allowSpectators:b.allowSpectators,maxSpectators:b.maxSpectators}})]})}function cm({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),[C,f]=x.useState(null),j=x.useRef(null),b=x.useRef(null),[w,T]=x.useState({open:!1,type:"error",email:"",message:""}),R=n.filter(S=>S&&(S.status==="approved"||S.status==="rejected"||S.status==="skipped")),k=Math.max(1,R.length+1),F=Math.max(1,n.length+1),N=F>=k?Array.from({length:F-k+1},(S,M)=>k+M):[k];x.useEffect(()=>{N.length>0&&d===null&&m(N[0]||null)},[N.length,d]);const A=async()=>{var E,H;const S=i.trim().toLowerCase();if(!S){T({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(S)){T({open:!0,type:"error",email:S,message:"Please enter a valid email address"});return}if(!l||l<=0){T({open:!0,type:"error",email:"",message:"Please enter valid TAT hours (minimum 1 hour)"});return}if(l>720){T({open:!0,type:"error",email:"",message:"TAT hours cannot exceed 720 hours (30 days)"});return}if(!d){T({open:!0,type:"error",email:"",message:"Please select an approval level"});return}if(d<k){T({open:!0,type:"error",email:"",message:`Cannot add approver at level ${d}. Minimum allowed level is ${k} (after completed levels)`});return}const P=r.find(q=>(q.email||"").toLowerCase()===S);if(P){const q=((E=P.participantType)==null?void 0:E.toUpperCase())||"PARTICIPANT",J=P.name||S;if(q==="INITIATOR"){T({open:!0,type:"error",email:S,message:`${J} is the request initiator and cannot be added as an approver.`});return}else if(q==="APPROVER"){T({open:!0,type:"error",email:S,message:`${J} is already an approver on this request.`});return}else if(q==="SPECTATOR"){T({open:!0,type:"error",email:S,message:`${J} is currently a spectator on this request and cannot be added as an approver. Please remove them as spectator first.`});return}else{T({open:!0,type:"error",email:S,message:`${J} is already a participant on this request.`});return}}if(!C||C.email.toLowerCase()!==S)try{const J=((H=(await xs(S,1)).data)==null?void 0:H.data)||[];if(J.length===0){T({open:!0,type:"not-found",email:S,message:""});return}const B=J[0];await Ss({userId:B.userId,email:B.email,displayName:B.displayName,firstName:B.firstName,lastName:B.lastName,department:B.department,phone:B.phone,mobilePhone:B.mobilePhone,designation:B.designation,jobTitle:B.jobTitle,manager:B.manager,employeeId:B.employeeId,employeeNumber:B.employeeNumber,secondEmail:B.secondEmail,location:B.location})}catch(q){console.error("Failed to validate approver:",q),T({open:!0,type:"error",email:S,message:"Failed to validate user. Please try again."});return}try{h(!0),await a(S,l,d),o(""),c(24),m(null),f(null),s()}catch(q){console.error("Failed to add approver:",q)}finally{h(!1)}},I=()=>{u||(o(""),c(24),m(null),f(null),g([]),v(!1),s())},V=S=>{const M=S.toLowerCase();return M==="approved"?e.jsx(je,{className:"w-4 h-4 text-green-600"}):M==="rejected"?e.jsx(Je,{className:"w-4 h-4 text-red-600"}):M==="skipped"?e.jsx(Pe,{className:"w-4 h-4 text-orange-600"}):M==="in-review"||M==="pending"?e.jsx(Ee,{className:"w-4 h-4 text-blue-600"}):e.jsx(Ee,{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(()=>()=>{j.current&&clearTimeout(j.current)},[]);const _=S=>{if(o(S),C&&C.email.toLowerCase()!==S.toLowerCase()&&f(null),j.current&&clearTimeout(j.current),!S||!S.startsWith("@")||S.length<2){g([]),v(!1);return}v(!0),j.current=setTimeout(async()=>{var M;try{const P=S.slice(1),H=((M=(await xs(P,10)).data)==null?void 0:M.data)||[];g(H)}catch(P){console.error("Search failed:",P),g([])}finally{v(!1)}},300)},L=async S=>{try{await Ss({userId:S.userId,email:S.email,displayName:S.displayName,firstName:S.firstName,lastName:S.lastName,department:S.department,phone:S.phone,mobilePhone:S.mobilePhone,designation:S.designation,jobTitle:S.jobTitle,manager:S.manager,employeeId:S.employeeId,employeeNumber:S.employeeNumber,secondEmail:S.secondEmail,location:S.location}),o(S.email),f(S),g([]),v(!1)}catch(M){console.error("Failed to ensure user exists:",M),T({open:!0,type:"error",email:S.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(et,{open:t,onOpenChange:I,children:[e.jsxs(Ze,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:I,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:u,children:[e.jsx(ft,{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(Xe,{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(Z,{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(S=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-md ${S.status==="approved"?"bg-green-100 border border-green-200":S.status==="rejected"?"bg-red-100 border border-red-200":S.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:S.levelNumber}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:S.approverName}),e.jsxs("p",{className:"text-xs text-gray-500",children:[S.tatHours,"h TAT"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[V(S.status),e.jsx(X,{variant:"outline",className:`text-xs ${S.status==="approved"?"bg-green-50 text-green-700 border-green-300":S.status==="rejected"?"bg-red-50 text-red-700 border-red-300":S.status==="skipped"?"bg-orange-50 text-orange-700 border-orange-300":"bg-blue-50 text-blue-700 border-blue-300"}`,children:S.status})]})]},S.levelNumber))}),e.jsxs("p",{className:"text-xs text-gray-500",children:["ℹ️ New approver can only be added at level ",k," or higher (after completed levels)"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Z,{className:"text-sm font-medium text-gray-700",children:"Approval Level *"}),e.jsxs(Ae,{value:(d==null?void 0:d.toString())||"",onValueChange:S=>m(Number(S)),disabled:u,children:[e.jsx(ke,{className:"h-11 border-gray-300",children:e.jsx(Te,{placeholder:"Select level"})}),e.jsx(Re,{children:N.map(S=>e.jsx(O,{value:S.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 ",S]}),S<=n.length&&e.jsxs("span",{className:"text-xs text-gray-500",children:["(will shift existing Level ",S,")"]})]})},S))})]}),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(Z,{className:"text-sm font-medium text-gray-700",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{type:"number",min:"1",max:"720",value:l,onChange:S=>c(Number(S.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(Ee,{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(Oi,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(xe,{type:"text",placeholder:"@username or user@example.com",value:i,onChange:S=>_(S.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(S=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>L(S),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:(S.displayName||S.email).split(" ").map(M=>M[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:S.displayName||[S.firstName,S.lastName].filter(Boolean).join(" ")||S.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:S.email}),S.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:S.designation})]})]})},S.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(D,{type:"button",variant:"outline",onClick:I,className:"flex-1 h-11 border-gray-300",disabled:u,children:"Cancel"}),e.jsxs(D,{type:"button",onClick:A,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:w.open,onOpenChange:S=>T(M=>({...M,open:S})),children:e.jsxs(Ze,{className:"sm:max-w-md",children:[e.jsxs(tt,{children:[e.jsx(Xe,{className:"flex items-center gap-2",children:w.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:[w.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:w.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(Wr,{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."]})})]}),w.type==="error"&&e.jsxs(e.Fragment,{children:[w.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:w.email}),"."]}),w.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:w.message})})]})]})})]}),e.jsx(wt,{children:e.jsx(D,{onClick:()=>T(S=>({...S,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const Yy=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"}},Zy=t=>{switch(t){case"online":return"Online";case"away":return"Away";case"offline":return"Offline";default:return"Unknown"}},Xy=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 />"),Qy=t=>t<1024?t+" B":t<1024*1024?(t/1024).toFixed(1)+" KB":(t/(1024*1024)).toFixed(1)+" MB",xl=({type:t})=>{const s="w-4 h-4",a=t.toLowerCase();return a.includes("pdf")?e.jsx(Se,{className:`${s} text-red-600`}):a.includes("excel")||a.includes("spreadsheet")||a.includes("xlsx")?e.jsx(xx,{className:`${s} text-green-600`}):a.includes("powerpoint")||a.includes("presentation")||a.includes("pptx")?e.jsx(Se,{className:`${s} text-orange-600`}):a.includes("word")||a.includes("document")||a.includes("docx")?e.jsx(Se,{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(gx,{className:`${s} text-purple-600`}):e.jsx(Hr,{className:`${s} text-gray-600`})};function dm({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,C]=x.useState(!1),[f,j]=x.useState([]),[b,w]=x.useState(!1),[T,R]=x.useState([]),[k,F]=x.useState(null),[N,A]=x.useState(null),[I,V]=x.useState(!1),[_,L]=x.useState(!1),[S,M]=x.useState(!1),[P,E]=x.useState({success:!0,title:"",message:""}),H=x.useRef(null),q=x.useRef(null),J=x.useRef(null),B=x.useRef(!1),[oe,ge]=x.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[z,re]=x.useState({open:!1,errors:[]}),ye=x.useMemo(()=>({id:u,title:n||"Request Details"}),[u,n]),[G,Q]=x.useState([]),ie=G.filter(U=>U.status==="online"),Y=f.filter(U=>U.content.toLowerCase().includes(g.toLowerCase())||U.user.name.toLowerCase().includes(g.toLowerCase())),ue=x.useMemo(()=>l!==void 0?l:!k||G.length===0?!1:G.some(U=>{const se=U.userId||U.user_id,$=(U.role||"").toString().toUpperCase(),de=(U.participantType||U.participant_type||"").toString().toUpperCase();return se===k&&($==="SPECTATOR"||de==="SPECTATOR")}),[l,k,G]);x.useEffect(()=>{},[G]),x.useEffect(()=>{!u||!k||s||(async()=>{try{const U=await ba(u),se=Array.isArray(U)?U.map($=>{const de=$.userId||$.user_id;return{id:$.noteId||$.id||String(Math.random()),user:{name:$.userName||"User",avatar:($.userName||"U").slice(0,2).toUpperCase(),role:$.userRole||"Participant"},content:$.message||"",timestamp:$.createdAt||new Date().toISOString(),isCurrentUser:de===k,attachments:Array.isArray($.attachments)?$.attachments.map(ce=>({attachmentId:ce.attachmentId||ce.attachment_id,name:ce.fileName||ce.file_name||ce.name,fileName:ce.fileName||ce.file_name||ce.name,url:ce.storageUrl||ce.storage_url||ce.url||"#",type:ce.fileType||ce.file_type||ce.type||"file",fileType:ce.fileType||ce.file_type||ce.type||"file",fileSize:ce.fileSize||ce.file_size})):void 0}}):[];j(se)}catch(U){console.error("[WorkNoteChat] Failed to load messages:",U)}})()},[u,k,s]);const Me=x.useMemo(()=>{const U=[];return f.forEach(se=>{se.attachments&&se.attachments.length>0&&se.attachments.forEach($=>{U.push({attachmentId:$.attachmentId||$.attachment_id,name:$.fileName||$.file_name||$.name||"Untitled",fileName:$.fileName||$.file_name||$.name||"Untitled",size:$.fileSize||$.file_size,type:$.fileType||$.file_type||$.type||"file",uploadedBy:se.user.name,uploadedAt:se.timestamp,url:$.storageUrl||$.storage_url||$.url||"#"})})}),U},[f]);x.useEffect(()=>{i&&Me.length>=0&&i(Me)},[Me,i]);const $e=x.useMemo(()=>G.map(U=>({email:(U.email||"").toLowerCase(),participantType:U.role==="Initiator"?"INITIATOR":U.role==="Approver"?"APPROVER":U.role==="Spectator"?"SPECTATOR":"PARTICIPANT",name:U.name})),[G]),Ie=U=>{if(!U)return"Participant";switch(U.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return U.charAt(0).toUpperCase()+U.slice(1).toLowerCase()}},ae=()=>{var U;(U=H.current)==null||U.scrollIntoView({behavior:"smooth"})};x.useEffect(()=>{ae()},[f]);const fe=U=>{switch(U.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return U.charAt(0).toUpperCase()+U.slice(1).toLowerCase()}};x.useEffect(()=>{B.current||u&&(async()=>{try{const U=await aa(u),se=Array.isArray(U==null?void 0:U.participants)?U.participants:[];if(se.length===0)return;const $=se.map(me=>{const De=me.participantType||me.participant_type||"participant",ve=me.userId||me.user_id||"";return{name:me.userName||me.user_name||me.user_email||me.userEmail||"User",avatar:(me.userName||me.user_name||me.user_email||"U").toString().split(" ").map(Fe=>Fe[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:fe(De.toString()),status:"offline",email:me.userEmail||me.user_email||"",permissions:["read","write","mention"],userId:ve}});B.current=!0,Q($);let de=0;const ce=3,Ne=()=>{J.current&&J.current.connected?(J.current.emit("request:online-users",{requestId:u}),de++,de<ce&&setTimeout(Ne,500)):(de++,de<ce&&setTimeout(Ne,200))};setTimeout(Ne,100)}catch(U){console.error("[WorkNoteChat] ❌ Failed to load participants:",U)}})()},[u]),x.useEffect(()=>()=>{u&&(B.current=!1)},[u]),x.useEffect(()=>{const U=localStorage.getItem("userData");if(U)try{const se=JSON.parse(U),$=(se==null?void 0:se.id)||(se==null?void 0:se.userId)||(se==null?void 0:se.user_id)||null;F($)}catch(se){console.error("[WorkNoteChat] Failed to parse userData:",se)}},[]),x.useEffect(()=>{(async()=>{try{const se=await ia("DOCUMENT_POLICY"),$={};se.forEach(me=>{$[me.configKey]=me.configValue});const de=parseInt($.MAX_FILE_SIZE_MB||"10"),Ne=($.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(me=>me.trim().toLowerCase());ge({maxFileSizeMB:de,allowedFileTypes:Ne})}catch(se){console.error("Failed to load document policy:",se)}})()},[]),x.useEffect(()=>{if(!k)return;let U=u;return(async()=>{var se;try{const $=await aa(u);(se=$==null?void 0:$.workflow)!=null&&se.requestId&&(U=$.workflow.requestId)}catch{}try{const $=Ya();r?Q(Be=>Be.map(qe=>qe.userId===k?{...qe,status:"online"}:qe)):(ii($,U,k),Q(Be=>Be.map(qe=>qe.userId===k?{...qe,status:"online"}:qe)));const de=Be=>{const Le=(Be==null?void 0:Be.note)||Be;if(!Le)return;const qe=Le.noteId||Le.id;j($t=>{if($t.some(Ke=>Ke.id===qe))return $t;const yt=Le.userName||Le.user_name||"User",Ks=Le.userRole||Le.user_role,ua=Ie(Ks),xr=Le.userId||Le.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:Le.message||"",timestamp:Le.createdAt||new Date().toISOString(),isCurrentUser:xr===k,attachments:Array.isArray(Le.attachments)?Le.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]})},ce=Be=>{Q(Le=>Le.length===0||!Le.find(yt=>yt.userId===Be.userId)?Le:Le.map(yt=>yt.userId===Be.userId?{...yt,status:"online"}:yt))},Ne=Be=>{Be.userId!==k&&Q(Le=>Le.length===0||!Le.find(yt=>yt.userId===Be.userId)?Le:Le.map(yt=>yt.userId===Be.userId?{...yt,status:"offline"}:yt))},me=Be=>{Q(Le=>Le.length===0?Le:Le.map($t=>{const yt=$t.userId||"";if(yt===k)return{...$t,status:"online"};const ua=Be.userIds.includes(yt);return{...$t,status:ua?"online":"offline"}}))},De=()=>{Q(Be=>Be.map(qe=>qe.userId===k?{...qe,status:"online"}:qe)),r||ii($,U,k),B.current&&($.emit("request:online-users",{requestId:U}),setTimeout(()=>$.emit("request:online-users",{requestId:U}),300),setTimeout(()=>$.emit("request:online-users",{requestId:U}),800))},ve=Be=>{console.error("[WorkNoteChat] ❌ Socket error:",Be)},Fe=Be=>{console.warn("[WorkNoteChat] ⚠️ Socket disconnected:",Be),Q(Le=>Le.map(qe=>qe.userId===k?qe:{...qe,status:"offline"}))},Qt=Be=>{Be.includes("presence")||Be.includes("worknote")||Be.includes("request")};$.on("connect",De),$.on("disconnect",Fe),$.on("error",ve),$.on("worknote:new",de),$.on("presence:join",ce),$.on("presence:leave",Ne),$.on("presence:online",me),$.onAny(Qt),J.current=$,$.connected&&B.current&&($.emit("request:online-users",{requestId:U}),setTimeout(()=>{$.emit("request:online-users",{requestId:U})},300),setTimeout(()=>{$.emit("request:online-users",{requestId:U})},800),setTimeout(()=>{$.emit("request:online-users",{requestId:U})},1500));const St=()=>{$.off("connect",De),$.off("disconnect",Fe),$.off("error",ve),$.off("worknote:new",de),$.off("presence:join",ce),$.off("presence:leave",Ne),$.off("presence:online",me),$.offAny(Qt),r||Bd($,U),J.current=null};window.__wn_cleanup=St}catch{}})(),()=>{var se;try{(se=window.__wn_cleanup)==null||se.call(window)}catch{}}},[u,k,r]);const Ve=async()=>{if(h.trim()||T.length>0){const U=Ia(h),se=U.map(ce=>{const Ne=G.find(me=>me.name.toLowerCase().includes(ce.toLowerCase()));return Ne==null?void 0:Ne.userId}).filter(Boolean),$=T.map(ce=>({name:ce.name,url:URL.createObjectURL(ce),type:ce.type.split("/")[1]||"file"})),de={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:U,isHighPriority:h.includes("!important")||h.includes("urgent"),attachments:$.length>0?$:void 0,isCurrentUser:!0};if(a)try{await a(h,T)}catch{}else try{await Wd(u,{message:h,mentions:se},T);const ce=await ba(u),Ne=Array.isArray(ce)?ce.map(me=>{const De=me.userId||me.user_id;return{id:me.noteId||me.id||String(Math.random()),user:{name:me.userName||"User",avatar:(me.userName||"U").slice(0,2).toUpperCase(),role:me.userRole||"Participant"},content:me.message||"",timestamp:me.createdAt||new Date().toISOString(),isCurrentUser:De===k,attachments:Array.isArray(me.attachments)?me.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}}):[];j(Ne)}catch{j(ce=>[...ce,de])}p(""),R([])}};x.useEffect(()=>{if(s&&Array.isArray(s))try{const se=s.filter($=>($.type||"").toLowerCase()!=="sla_warning").map($=>{var ce;if($.type||$.activityType||$.isSystem)return{id:$.id||`activity-${$.timestamp||Date.now()}-${Math.random()}`,user:{name:"System",avatar:"SY",role:"System"},content:$.details||$.action||$.content||"",timestamp:$.timestamp||$.createdAt||$.created_at||new Date().toISOString(),isSystem:!0,isCurrentUser:!1};{const Ne=$.userName||$.user_name||((ce=$.user)==null?void 0:ce.name)||"User",me=$.userRole||$.user_role,De=Ie(me),ve=$.userId||$.user_id;return{id:$.noteId||$.note_id||$.id||String(Math.random()),user:{name:Ne,avatar:Ne.split(" ").map(Fe=>Fe[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:De},content:$.message||$.content||"",timestamp:$.createdAt||$.created_at||$.timestamp||new Date().toISOString(),isSystem:!1,attachments:Array.isArray($.attachments)?$.attachments.map(Fe=>({attachmentId:Fe.attachmentId||Fe.attachment_id,name:Fe.fileName||Fe.file_name||Fe.name,fileName:Fe.fileName||Fe.file_name||Fe.name,url:Fe.storageUrl||Fe.storage_url||Fe.url||"#",type:Fe.fileType||Fe.file_type||Fe.type||"file",fileType:Fe.fileType||Fe.file_type||Fe.type||"file",fileSize:Fe.fileSize||Fe.file_size})):void 0,isCurrentUser:ve===k}}}).sort(($,de)=>new Date($.timestamp).getTime()-new Date(de.timestamp).getTime());j(se)}catch(U){console.error("[WorkNoteChat] Error mapping messages:",U)}else(async()=>{try{const U=await ba(u),se=Array.isArray(U)?U.map($=>{const de=$.userName||$.user_name||"User",ce=$.userRole||$.user_role,Ne=Ie(ce),me=$.userId||$.user_id;return{id:$.noteId||$.note_id||$.id||String(Math.random()),user:{name:de,avatar:de.split(" ").map(De=>De[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ne},content:$.message||"",timestamp:$.createdAt||$.created_at||new Date().toISOString(),attachments:Array.isArray($.attachments)?$.attachments.map(De=>({attachmentId:De.attachmentId||De.attachment_id,name:De.fileName||De.file_name||De.name,fileName:De.fileName||De.file_name||De.name,url:De.storageUrl||De.storage_url||De.url||"#",type:De.fileType||De.file_type||De.type||"file",fileType:De.fileType||De.file_type||De.type||"file",fileSize:De.fileSize||De.file_size})):void 0,isCurrentUser:me===k}}):[];j(se)}catch(U){console.error("[WorkNoteChat] Error loading work notes:",U)}})()},[s,u,G]);const _e=U=>{const se=oe.maxFileSizeMB*1024*1024;if(U.size>se)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${oe.maxFileSizeMB}MB. Current size: ${(U.size/(1024*1024)).toFixed(2)}MB`};const $=U.name.toLowerCase(),de=$.substring($.lastIndexOf(".")+1);return oe.allowedFileTypes.includes(de)?{valid:!0}:{valid:!1,reason:`File type "${de}" is not allowed. Allowed types: ${oe.allowedFileTypes.join(", ")}`}},Xt=U=>{if(!U.target.files||U.target.files.length===0)return;const se=Array.from(U.target.files),$=[],de=[];se.forEach(ce=>{const Ne=_e(ce);Ne.valid?de.push(ce):$.push({fileName:ce.name,reason:Ne.reason||"Unknown validation error"})}),$.length>0&&re({open:!0,errors:$}),de.length>0&&(R(ce=>[...ce,...de]),de.length<se.length?be.warning(`${de.length} of ${se.length} file(s) were added. ${$.length} file(s) were rejected.`):be.success(`${de.length} file(s) added successfully`)),U.target&&(U.target.value="")},ys=U=>{R(se=>se.filter(($,de)=>de!==U)),q.current&&(q.current.value="")},Ws=U=>{p(se=>se+U),C(!1)},ma=()=>{var U;(U=q.current)==null||U.click()},Ma=async U=>{var se,$;try{await Gd(u,U);const de=await aa(u),ce=Array.isArray(de==null?void 0:de.participants)?de.participants:[];if(ce.length){const Ne=ce.map(me=>{const De=me.participantType||me.participant_type||"participant",ve=me.userId||me.user_id||"",Fe=me.userName||me.user_name||me.userEmail||me.user_email||"User",Qt=me.userEmail||me.user_email||"",St=Fe.split(" ").map(Be=>Be[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:Fe,avatar:St,role:fe(De),status:"offline",email:Qt,lastSeen:void 0,permissions:["read"],userId:ve}});Q(Ne),J.current&&J.current.connected&&J.current.emit("request:online-users",{requestId:u})}V(!1),E({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),M(!0)}catch(de){throw console.error("Failed to add spectator:",de),E({success:!1,title:"Failed to Add Spectator",message:(($=(se=de==null?void 0:de.response)==null?void 0:se.data)==null?void 0:$.error)||"Failed to add spectator. Please try again."}),M(!0),de}},vs=async(U,se,$)=>{var de,ce;if(d)await d(U,se,$),L(!1);else try{await Kd(u,U,se,$);const Ne=await aa(u),me=Array.isArray(Ne==null?void 0:Ne.participants)?Ne.participants:[];if(me.length){const De=me.map(ve=>{const Fe=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||"",Le=St.split(" ").map(qe=>qe[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:St,avatar:Le,role:fe(Fe),status:"offline",email:Be,lastSeen:void 0,permissions:["read"],userId:Qt}});Q(De),J.current&&J.current.connected&&J.current.emit("request:online-users",{requestId:u})}L(!1),E({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${$} with ${se}h TAT`}),M(!0)}catch(Ne){throw console.error("Failed to add approver:",Ne),E({success:!1,title:"Failed to Add Approver",message:((ce=(de=Ne==null?void 0:Ne.response)==null?void 0:de.data)==null?void 0:ce.error)||"Failed to add approver. Please try again."}),M(!0),Ne}},Ct=["😊","😂","🤣","😁","😃","😄","😅","😆","😉","😌","😍","🥰","😘","😗","😙","😚","🙂","🤗","🤩","🤔","🤨","😐","😑","😶","🙄","😏","😒","🙃","😬","🤐","😴","😪","😵","🤯","🤪","😜","😝","😛","🤤","😋","😎","🤓","🧐","😕","😟","🙁","☹️","😮","😯","😲","😳","🥺","😦","😧","😨","😰","😥","😢","😭","😱","😖","😣","😞","😓","😩","😫","🥱","😤","😡","😠","🤬","😈","👿","💀","☠️","💩","🤡","👹","👺","👻","👋","🤚","🖐️","✋","🖖","👌","🤌","🤏","✌️","🤞","🤟","🤘","🤙","👈","👉","👆","🖕","👇","☝️","👍","👎","✊","👊","🤛","🤜","👏","🙌","👐","🤲","🤝","🙏","💪","🦾","🦿","🦵","🦶","👂","🦻","👃","🧠","❤️","🧡","💛","💚","💙","💜","🖤","🤍","🤎","💔","❣️","💕","💞","💓","💗","💖","💘","💝","💟","❤️🔥","💼","📊","📈","📉","💻","⌨️","🖥️","🖨️","🖱️","💾","💿","📱","☎️","📞","📟","📠","📧","✉️","📨","📩","📮","📪","📫","📬","📭","📄","📃","📑","📝","✏️","✒️","🖊️","🖋️","📏","📐","📌","📍","🗂️","📁","📂","✅","✔️","☑️","🎯","🎖️","🏆","🥇","🥈","🥉","⭐","🌟","✨","💫","🔥","💥","⚡","💯","🎉","🎊","🎈","⚠️","🚫","❌","⛔","🚷","🚯","🚱","🚳","🔞","📵","❗","❓","❕","❔","‼️","⁉️","💢","💬","💭","🗯️","⏰","⏱️","⏲️","⏳","⌛","📅","📆","🗓️","📇","🕐","🕑","🕒","🕓","🕔","🕕","🕖","🕗","🕘","🕙","🕚","🚀","🎯","🎲","🎰","🧩","🔍","🔎","🔑","🗝️","🔒","🔓","🔐","🔏","🔔","🔕","📣","📢","💡","🔦","🏮","➕","➖","✖️","➗","♾️","‼️","⁉️","❓","❔","❕","🔄","🔃","🔂","▶️","⏸️","⏯️","⏹️","⏺️","⏭️","⏮️","⏩","⏪","⏫","⏬","◀️","🔼","🔽","➡️","⬅️","⬆️","⬇️","↗️","↘️","↙️","↖️","↕️","↔️","↪️","↩️","⤴️"],Ia=U=>{const se=/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,$=[];let de;for(;(de=se.exec(U))!==null;)if(de[1]){const ce=de.index+de[0].length,Ne=U.slice(ce),me=U[ce];(Ne.startsWith("@")||!me||/\s|[.,!?;:]|@/.test(me))&&$.push(de[1].trim())}return $},pr=U=>{U.key==="Enter"&&!U.shiftKey&&(U.preventDefault(),Ve())},ln=(U,se)=>{j($=>$.map(de=>{if(de.id===U){const ce=de.reactions||[],Ne=ce.find(me=>me.emoji===se);if(Ne)if(Ne.users.includes("You")){if(Ne.users=Ne.users.filter(me=>me!=="You"),Ne.users.length===0)return{...de,reactions:ce.filter(me=>me.emoji!==se)}}else Ne.users.push("You");else ce.push({emoji:se,users:["You"]});return{...de,reactions:ce}}return de}))};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(gs,{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:ye.title}),e.jsx(X,{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:[ie.slice(0,3).map((U,se)=>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:U.avatar})},se)),ie.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:["+",ie.length-3]})]})}),e.jsx(D,{variant:"outline",size:"sm",onClick:()=>w(!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(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(xe,{placeholder:"Search messages...",value:g,onChange:U=>y(U.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:[Y.map(U=>{const se=U.isCurrentUser||!1;return e.jsxs("div",{className:`flex gap-2 sm:gap-3 lg:gap-4 ${U.isSystem?"justify-center":se?"justify-end":""}`,children:[!U.isSystem&&!se&&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 ${U.user.role==="Initiator"?"bg-green-600":U.user.role==="Current User"?"bg-blue-500":U.user.role==="System"?"bg-gray-500":"bg-slate-600"}`,children:U.user.avatar})}),e.jsx("div",{className:`${se?"max-w-[70%]":"flex-1"} min-w-0 ${U.isSystem?"text-center max-w-xs sm:max-w-md mx-auto":""}`,children:U.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:U.content}),e.jsx("span",{className:"text-xs text-gray-500 hidden sm:inline",children:Vt(U.timestamp)})]}):e.jsxs("div",{children:[e.jsxs("div",{className:`flex items-center gap-2 sm:gap-3 mb-1 sm:mb-2 flex-wrap ${se?"justify-end":""}`,children:[e.jsxs("span",{className:"font-semibold text-gray-900 text-sm sm:text-base truncate",children:[U.user.name," ",se&&e.jsx("span",{className:"text-xs text-gray-500 font-normal",children:"(you)"})]}),e.jsx(X,{variant:"outline",className:"text-xs flex-shrink-0",children:U.user.role}),e.jsxs("span",{className:"text-xs text-gray-500 flex items-center gap-1 flex-shrink-0",children:[e.jsx(Ee,{className:"w-3 h-3"}),Vt(U.timestamp)]}),U.isHighPriority&&e.jsxs(X,{variant:"destructive",className:"text-xs flex-shrink-0",children:[e.jsx(ux,{className:"w-3 h-3 mr-1"}),"Priority"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 sm:p-4 shadow-sm ${se?"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:Xy(U.content)}}),U.attachments&&U.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:U.attachments.map(($,de)=>{const ce=$.fileSize||$.file_size,Ne=$.fileName||$.file_name||$.name,me=$.fileType||$.file_type||$.type||"",De=$.attachmentId||$.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(xl,{type:me})}),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}),ce&&e.jsx("p",{className:"text-xs text-gray-500",children:Qy(ce)})]}),De&&(()=>{const ve=(me||"").toLowerCase();return ve.includes("image")||ve.includes("pdf")||ve.includes("jpg")||ve.includes("jpeg")||ve.includes("png")||ve.includes("gif")})()&&e.jsx(D,{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 Fe=E0(De);A({fileName:Ne,fileType:me,fileUrl:Fe,fileSize:ce,attachmentId:De})},title:"Preview file",children:e.jsx(kt,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),e.jsx(D,{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(),!De){be.error("Cannot download: Attachment ID missing");return}try{await ml(De)}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"})})]},de)})})}),U.reactions&&U.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:[U.reactions.map(($,de)=>e.jsxs("button",{onClick:()=>ln(U.id,$.emoji),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs sm:text-sm transition-colors flex-shrink-0 ${$.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:$.emoji}),e.jsx("span",{className:"text-xs font-medium",children:$.users.length})]},de)),e.jsx(D,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-7 sm:w-7 p-0 flex-shrink-0",onClick:()=>C(!v),children:e.jsx(_s,{className:"w-2 h-2 sm:w-3 sm:h-3"})})]})]})]})}),!U.isSystem&&se&&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:U.user.avatar})})]},U.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:q,onChange:Xt,className:"hidden",multiple:!0,accept:oe.allowedFileTypes.map(U=>`.${U}`).join(",")}),T.length>0&&e.jsx("div",{className:"mb-3 space-y-2 max-h-32 overflow-y-auto pr-2",children:T.map((U,se)=>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(xl,{type:U.type.split("/")[1]||"file"})}),e.jsx("span",{className:"text-sm text-gray-700 flex-1 truncate min-w-0",children:U.name}),e.jsxs("span",{className:"text-xs text-gray-500 flex-shrink-0",children:[(U.size/1024).toFixed(1)," KB"]}),e.jsx(D,{variant:"ghost",size:"sm",onClick:()=>ys(se),className:"h-6 w-6 p-0 hover:bg-red-100 flex-shrink-0",children:e.jsx(ft,{className:"h-3 w-3 text-red-600"})})]},se))}),e.jsxs("div",{className:"relative mb-2",children:[(()=>{const U=h.lastIndexOf("@"),se=U>=0;if(!se)return null;const $=h.slice(U+1),de=$.trim(),ce=$.endsWith(" "),Ne=de.length>0,me=de.includes(" ")&&!ce,De=ce&&Ne;if(!(se&&$.length<=20&&!me&&!De))return null;const Fe=de.toLowerCase(),Qt=G.filter(St=>St.userId===k?!1:Fe?St.name.toLowerCase().includes(Fe):!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:Le=>{Le.preventDefault(),Le.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:Fe?`No participants found matching "${Fe}"`:"No other participants available"})})]})})(),e.jsx(fs,{placeholder:"Type your message... Use @username to mention someone",value:h,onChange:U=>p(U.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(D,{variant:"ghost",size:"sm",onClick:()=>C(!1),className:"h-6 w-6 p-0",children:e.jsx(ft,{className:"h-3 w-3"})})]}),e.jsx("div",{className:"grid grid-cols-8 sm:grid-cols-10 gap-1",children:Ct.map((U,se)=>e.jsx("button",{onClick:()=>Ws(U),className:"text-xl sm:text-2xl hover:bg-gray-100 rounded p-1 transition-colors flex items-center justify-center",title:U,children:U},se))})]})]}),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(D,{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(Hr,{className:"h-4 w-4"})}),e.jsx(D,{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:()=>C(!v),title:"Add emoji",children:e.jsx(hx,{className:"h-4 w-4"})}),e.jsx(D,{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(U=>U+"@"),title:"Mention someone",children:e.jsx(Oi,{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(D,{onClick:Ve,disabled:!h.trim()&&T.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(px,{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:()=>w(!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(D,{variant:"ghost",size:"sm",onClick:()=>w(!1),className:"lg:hidden h-8 w-8 p-0",children:e.jsx(ft,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-3 sm:space-y-4 overflow-y-auto flex-1 pr-2",children:G.map((U,se)=>{const $=U.userId===k;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 ${U.role==="Initiator"?"bg-green-600":$?"bg-blue-500":"bg-slate-600"}`,children:U.avatar})}),e.jsx("div",{className:`absolute -bottom-1 -right-1 w-3 h-3 rounded-full border-2 border-white ${Yy(U.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:[U.name," ",$&&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:U.role}),e.jsx("span",{className:"text-xs text-gray-400",children:"•"}),e.jsx("p",{className:"text-xs text-gray-500",children:Zy(U.status)})]}),U.lastSeen&&U.status==="offline"&&e.jsx("p",{className:"text-xs text-gray-400",children:U.lastSeen})]})]},se)})})]}),!ue&&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(D,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>L(!0),children:[e.jsx(qr,{className:"h-4 w-4"}),"Add Approver"]}),e.jsxs(D,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>V(!0),children:[e.jsx(kt,{className:"h-4 w-4"}),"Add Spectator"]})]})]})]})]}),N&&e.jsx(Gi,{fileName:N.fileName,fileType:N.fileType,fileUrl:N.fileUrl,fileSize:N.fileSize,attachmentId:N.attachmentId,onDownload:ml,open:!!N,onClose:()=>A(null)}),!ue&&e.jsx(lm,{open:I,onClose:()=>V(!1),onConfirm:Ma,requestIdDisplay:u,requestTitle:ye.title,existingParticipants:$e}),!ue&&o&&e.jsx(cm,{open:_,onClose:()=>L(!1),onConfirm:vs,requestIdDisplay:u,requestTitle:ye.title,existingParticipants:$e,currentLevels:c}),e.jsx(et,{open:z.open,onOpenChange:U=>re(se=>({...se,open:U})),children:e.jsxs(Ze,{className:"sm:max-w-lg",children:[e.jsxs(tt,{children:[e.jsxs(Xe,{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:z.errors.map((U,se)=>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:U.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:U.reason})]},se))}),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: ",oe.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",oe.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(wt,{children:e.jsx(D,{onClick:()=>re({open:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(im,{open:S,onClose:()=>M(!1),success:P.success,title:P.title,message:P.message})]})}function Jy({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(dm,{requestId:t,requestTitle:s,skipSocketJoin:!0,messages:a,onAttachmentsExtracted:r,isInitiator:n,isSpectator:i,currentLevels:o,onAddApprover:l})})}function ev({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(Ee,{className:"h-4 w-4 text-orange-600"}):e.jsx(Se,{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(D,{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(X,{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:he(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:he(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(X,{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(Se,{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 tv({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 A,I,V;const{user:p}=Mt(),[g,y]=x.useState([]),[v,C]=x.useState(!1),[f,j]=x.useState(!1),b=(t==null?void 0:t.status)==="closed",w=((A=t==null?void 0:t.pauseInfo)==null?void 0:A.isPaused)||!1,T=(V=(I=t==null?void 0:t.pauseInfo)==null?void 0:I.pausedBy)==null?void 0:V.userId,R=(p==null?void 0:p.userId)||"",k=!w&&!b&&(r||s),F=w&&d&&(r||s),N=w&&s&&T&&T!==R&&m;return x.useEffect(()=>{if(!w||!r||!(t!=null&&t.requestId)){j(!1);return}(async()=>{var L;try{const P=(((L=(await Ds.list({page:1,limit:50,unreadOnly:!0})).data)==null?void 0:L.notifications)||[]).some(E=>E.requestId===t.requestId&&E.notificationType==="pause_retrigger_request");j(P)}catch(S){console.error("Failed to check retrigger notifications:",S),j(!1)}})()},[w,r,t==null?void 0:t.requestId,h]),x.useEffect(()=>{(async()=>{if(!b||!u||!s){y([]);return}try{C(!0);const L=await Ey(u);y(L)}catch(L){console.error("Failed to fetch shared recipients:",L),y([])}finally{C(!1)}})()},[b,u,s,h]),e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[!a&&t.status!=="closed"&&e.jsxs(W,{"data-testid":"quick-actions-card",children:[e.jsx(ee,{className:"pb-2",children:e.jsx(te,{className:"text-sm sm:text-base",children:"Quick Actions"})}),e.jsxs(K,{className:"space-y-2",children:[s&&t.status!=="closed"&&e.jsxs(D,{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(qr,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Add Approver"]}),t.status!=="closed"&&e.jsxs(D,{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"]}),k&&c&&e.jsxs(D,{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"]}),F&&e.jsxs(D,{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(Mr,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Resume Workflow"]}),N&&e.jsxs(D,{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&&!w&&e.jsxs(e.Fragment,{children:[e.jsxs(D,{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(D,{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"]})]}),w&&e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-3 text-center",children:T===R?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&&T!==R&&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&&T!==R?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&&T&&T!==R?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:N?'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(W,{"data-testid":"spectators-card",children:[e.jsx(ee,{className:"pb-2",children:e.jsx(te,{className:"text-sm sm:text-base",children:"Spectators"})}),e.jsx(K,{className:"space-y-3",children:t.spectators&&t.spectators.length>0?t.spectators.map((_,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:_.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:_.name}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:_.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(W,{"data-testid":"shared-recipients-card",children:[e.jsx(ee,{className:"pb-2",children:e.jsxs(te,{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(K,{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((_,L)=>{const S=(_.displayName||"NA").split(" ").map(M=>M[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:S})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:_.displayName}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:_.email}),_.isRead&&e.jsx("p",{className:"text-xs text-green-600 mt-0.5",children:"Viewed"})]})]},_.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 sv({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(Ze,{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(Xe,{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(X,{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(fs,{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(D,{variant:"outline",onClick:s,disabled:d,children:"Cancel"}),e.jsxs(D,{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 av({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(Ze,{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(Xe,{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(X,{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(fs,{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(D,{variant:"outline",onClick:s,disabled:d,children:"Cancel"}),e.jsxs(D,{variant:"destructive",onClick:p,disabled:d,children:[e.jsx(Je,{className:"w-4 h-4 mr-2"}),d?"Rejecting...":"Reject Request"]})]})]})})}function rv({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(Ze,{className:"sm:max-w-md max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:h,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:d,children:[e.jsx(ft,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(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(Xe,{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(Z,{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(Z,{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(Z,{htmlFor:"skip-reason",className:"text-sm font-semibold text-gray-700",children:"Reason for Skipping *"}),e.jsx(fs,{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(D,{type:"button",variant:"outline",onClick:h,className:"flex-1 h-11 border-gray-300",disabled:d,children:"Cancel"}),e.jsxs(D,{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 nv({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:C,setShowActionStatusModal:f,setPreviewDocument:j,setDocumentError:b,setSkipApproverData:w,setActionStatus:T,handleApproveConfirm:R,handleRejectConfirm:k,handleAddApprover:F,handleAddSpectator:N,handleSkipApprover:A,downloadDocument:I,documentPolicy:V}){return e.jsxs(e.Fragment,{children:[e.jsx(sv,{open:t,onClose:()=>p(!1),onConfirm:R,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(av,{open:s,onClose:()=>g(!1),onConfirm:k,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(cm,{open:a,onClose:()=>y(!1),onConfirm:F,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:u,currentLevels:h}),e.jsx(lm,{open:r,onClose:()=>v(!1),onConfirm:N,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:u}),e.jsx(rv,{open:n,onClose:()=>{C(!1),w(null)},onConfirm:A,approverName:d==null?void 0:d.approverName,levelNumber:d==null?void 0:d.levelNumber,requestIdDisplay:c.id,requestTitle:c.title}),o&&e.jsx(Gi,{fileName:o.fileName,fileType:o.fileType,fileUrl:Yd(o.documentId),fileSize:o.fileSize,attachmentId:o.documentId,onDownload:I,open:!!o,onClose:()=>j(null)}),m&&e.jsx(im,{open:i,onClose:()=>{f(!1),T(null)},success:m.success,title:m.title,message:m.message}),e.jsx(et,{open:l.show,onOpenChange:_=>b(L=>({...L,show:_})),children:e.jsxs(Ze,{className:"sm:max-w-lg",children:[e.jsxs(tt,{children:[e.jsxs(Xe,{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((_,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:_.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:_.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: ",V.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",V.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(wt,{children:e.jsx(D,{onClick:()=>b({show:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})})]})}function iv({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 j,b,w,T;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),C=st().add(1,"month"),f=st().add(1,"day");if(v.isAfter(C)){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 R0(a,r,i.trim(),v.toDate()),be.success("Workflow paused successfully"),n&&await n(),o(""),c(u()),s()}catch(R){console.error("Failed to pause workflow:",R),be.error(((b=(j=R==null?void 0:R.response)==null?void 0:j.data)==null?void 0:b.error)||((T=(w=R==null?void 0:R.response)==null?void 0:w.data)==null?void 0:T.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(Ze,{className:"sm:max-w-[500px]",children:[e.jsx(tt,{children:e.jsxs(Xe,{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(Z,{htmlFor:"pause-reason",className:"text-sm font-medium",children:["Reason for Pausing ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(fs,{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(Z,{htmlFor:"resume-date",className:"text-sm font-medium",children:["Resume Date ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(xe,{id:"resume-date",type:"date",value:l,onChange:v=>c(v.target.value),min: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(D,{variant:"outline",onClick:y,disabled:d,children:"Cancel"}),e.jsx(D,{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 ov({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 P0(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(Ze,{className:"sm:max-w-[500px]",children:[e.jsx(tt,{children:e.jsxs(Xe,{className:"flex items-center gap-2",children:[e.jsx(Mr,{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(Z,{htmlFor:"resume-notes",className:"text-sm font-medium",children:"Notes (Optional)"}),e.jsx(fs,{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(D,{variant:"outline",onClick:d,disabled:o,children:"Cancel"}),e.jsx(D,{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(Mr,{className:"w-4 h-4 mr-2"}),"Resume Workflow"]})})]})]})})}function lv({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 D0(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(Ze,{className:"sm:max-w-[450px]",children:[e.jsx(tt,{children:e.jsxs(Xe,{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(D,{variant:"outline",onClick:s,disabled:i,children:"Cancel"}),e.jsx(D,{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 cv 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(D,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(D,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}}function dv({requestId:t,onBack:s,dynamicRequests:a=[]}){var xr,gr,Ke,Vo,zo,Ho;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),[C,f]=x.useState(0),[j,b]=x.useState(!1),[w,T]=x.useState(!1),[R,k]=x.useState(!1),{user:F}=Mt(),{request:N,apiRequest:A,loading:I,refreshing:V,refreshDetails:_,currentApprovalLevel:L,isSpectator:S,isInitiator:M,existingParticipants:P,accessDenied:E}=dy(n,a,F),{mergedMessages:H,unreadWorkNotes:q,workNoteAttachments:J,setWorkNoteAttachments:B}=my(n,A,l,F),{uploadingDocument:oe,triggerFileInput:ge,previewDocument:z,setPreviewDocument:re,documentPolicy:ye,documentError:G,setDocumentError:Q}=yy(A,_),{showApproveModal:ie,setShowApproveModal:Y,showRejectModal:ue,setShowRejectModal:Me,showAddApproverModal:$e,setShowAddApproverModal:Ie,showAddSpectatorModal:ae,setShowAddSpectatorModal:fe,showSkipApproverModal:Ve,setShowSkipApproverModal:_e,showActionStatusModal:Xt,setShowActionStatusModal:ys,skipApproverData:Ws,setSkipApproverData:ma,actionStatus:Ma,setActionStatus:vs,handleApproveConfirm:Ct,handleRejectConfirm:Ia,handleAddApprover:pr,handleSkipApprover:ln,handleAddSpectator:U}=Ny(n,L,_),{conclusionRemark:se,setConclusionRemark:$,conclusionLoading:de,conclusionSubmitting:ce,aiGenerated:Ne,handleGenerateConclusion:me,handleFinalizeConclusion:De}=jy(N,n,M,_,s,vs,ys);x.useEffect(()=>{const bs=new URLSearchParams(window.location.search).get("tab");bs&&c(bs)},[n]);const ve=()=>{_()},Fe=()=>{b(!0)},Qt=()=>{T(!0)},St=async()=>{await _()},Be=()=>{k(!0)},Le=async()=>{await _()},qe=async()=>{await _()},$t=async()=>{if(!(A!=null&&A.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=((N==null?void 0:N.status)==="approved"||(N==null?void 0:N.status)==="rejected")&&M,Ks=(N==null?void 0:N.status)==="closed"||(N==null?void 0:N.status)==="approved"&&!M||(N==null?void 0:N.status)==="rejected"&&!M;x.useEffect(()=>{(async()=>{if(!Ks||!(A!=null&&A.requestId)){g(null),h(null);return}try{v(!0);const bs=await Dy(A.requestId);if(bs!=null&&bs.summaryId){h(bs.summaryId);try{const cn=await tm(bs.summaryId);g(cn)}catch(cn){console.error("Failed to fetch summary details:",cn),g(null),h(null)}}else g(null),h(null)}catch{g(null),h(null)}finally{v(!1)}})()},[Ks,A==null?void 0:A.requestId]);const ua=((N==null?void 0:N.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 I&&!N&&!A?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..."})]})}):E!=null&&E.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(fx,{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:E.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(D,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(us,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(D,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})}):N?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(Ty,{request:N,refreshing:V,onBack:s||(()=>window.history.back()),onRefresh:ve,onShareSummary:$t,isInitiator:M}),e.jsxs(Qr,{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(Jr,{className:"grid grid-cols-3 sm:grid-cols-6 lg:flex lg:flex-row h-auto bg-gray-100 p-1.5 sm:p-1 rounded-lg gap-1.5 sm:gap-1",children:[e.jsxs(pt,{value:"overview",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900","data-testid":"tab-overview",children:[e.jsx(yx,{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(pt,{value:"summary",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900","data-testid":"tab-summary",children:[e.jsx(vd,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Summary"})]}),e.jsxs(pt,{value:"workflow",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900","data-testid":"tab-workflow",children:[e.jsx(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(pt,{value:"documents",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900","data-testid":"tab-documents",children:[e.jsx(Se,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Docs"})]}),e.jsxs(pt,{value:"activity",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900 col-span-1 sm:col-span-1","data-testid":"tab-activity",children:[e.jsx(as,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Activity"})]}),e.jsxs(pt,{value:"worknotes",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900 relative col-span-2 sm:col-span-1","data-testid":"tab-worknotes",children:[e.jsx(gs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Work Notes"}),q>0&&e.jsx(X,{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:q>9?"9+":q})]})]})}),e.jsxs("div",{className:l==="worknotes"?"":"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs("div",{className:l==="worknotes"?"":"lg:col-span-2",children:[e.jsx(xt,{value:"overview",className:"mt-0","data-testid":"overview-tab-content",children:e.jsx(Vy,{request:N,isInitiator:M,needsClosure:yt,conclusionRemark:se,setConclusionRemark:$,conclusionLoading:de,conclusionSubmitting:ce,aiGenerated:Ne,handleGenerateConclusion:me,handleFinalizeConclusion:De,onPause:Fe,onResume:Qt,onRetrigger:Be,currentUserIsApprover:!!L,pausedByUserId:(gr=(xr=N==null?void 0:N.pauseInfo)==null?void 0:xr.pausedBy)==null?void 0:gr.userId,currentUserId:F==null?void 0:F.userId})}),Ks&&e.jsx(xt,{value:"summary",className:"mt-0","data-testid":"summary-tab-content",children:e.jsx(ev,{summary:p,loading:y,onShare:$t,isInitiator:M})}),e.jsx(xt,{value:"workflow",className:"mt-0",children:e.jsx(qy,{request:N,user:F,isInitiator:M,onSkipApprover:Ut=>{if(!Ut.levelId){alert("Level ID not available");return}ma(Ut),_e(!0)},onRefresh:_})}),e.jsx(xt,{value:"documents",className:"mt-0",children:e.jsx(Ky,{request:N,workNoteAttachments:J,uploadingDocument:oe,documentPolicy:ye,triggerFileInput:ge,setPreviewDocument:re,downloadDocument:oi})}),e.jsx(xt,{value:"activity",className:"mt-0",children:e.jsx(Gy,{request:N})}),e.jsx(xt,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:l!=="worknotes",children:e.jsx(Jy,{requestId:n,requestTitle:N.title,mergedMessages:H,setWorkNoteAttachments:B,isInitiator:M,isSpectator:S,currentLevels:ua,onAddApprover:pr})})]}),l!=="worknotes"&&e.jsx(tv,{request:N,isInitiator:M,isSpectator:S,currentApprovalLevel:L,onAddApprover:()=>Ie(!0),onAddSpectator:()=>fe(!0),onApprove:()=>Y(!0),onReject:()=>Me(!0),onPause:Fe,onResume:Qt,onRetrigger:Be,summaryId:u,refreshTrigger:C,pausedByUserId:(Vo=(Ke=N==null?void 0:N.pauseInfo)==null?void 0:Ke.pausedBy)==null?void 0:Vo.userId,currentUserId:F==null?void 0:F.userId})]})]})]})}),d&&u&&e.jsx(Oy,{isOpen:d,onClose:()=>m(!1),summaryId:u,requestTitle:(N==null?void 0:N.title)||"N/A",onSuccess:()=>{_(),f(Ut=>Ut+1)}}),j&&(A==null?void 0:A.requestId)&&e.jsx(iv,{isOpen:j,onClose:()=>b(!1),requestId:A.requestId,levelId:(L==null?void 0:L.levelId)||null,onSuccess:Le}),w&&(A==null?void 0:A.requestId)&&e.jsx(ov,{isOpen:w,onClose:()=>T(!1),requestId:A.requestId,onSuccess:St}),R&&(A==null?void 0:A.requestId)&&e.jsx(lv,{isOpen:R,onClose:()=>k(!1),requestId:A.requestId,approverName:(Ho=(zo=N==null?void 0:N.pauseInfo)==null?void 0:zo.pausedBy)==null?void 0:Ho.name,onSuccess:qe}),e.jsx(nv,{showApproveModal:ie,showRejectModal:ue,showAddApproverModal:$e,showAddSpectatorModal:ae,showSkipApproverModal:Ve,showActionStatusModal:Xt,previewDocument:z,documentError:G,request:N,skipApproverData:Ws,actionStatus:Ma,existingParticipants:P,currentLevels:ua,setShowApproveModal:Y,setShowRejectModal:Me,setShowAddApproverModal:Ie,setShowAddSpectatorModal:fe,setShowSkipApproverModal:_e,setShowActionStatusModal:ys,setPreviewDocument:re,setDocumentError:Q,setSkipApproverData:ma,setActionStatus:vs,handleApproveConfirm:Ct,handleRejectConfirm:Ia,handleAddApprover:pr,handleAddSpectator:U,handleSkipApprover:ln,downloadDocument:oi,documentPolicy:ye})]}):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(Se,{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(D,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(us,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(D,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})})}function mv(t){return e.jsx(cv,{children:e.jsx(dv,{...t})})}function uv({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(j=1)=>{try{i(!0);const b=await Py({page:j,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 j=>{try{await sm(j),r(b=>b.map(w=>w.sharedSummaryId===j?{...w,isRead:!0,viewedAt:new Date().toISOString()}:w)),t?t(j):s(`/shared-summaries/${j}`)}catch(b){console.error("Failed to mark as viewed:",b),t?t(j):s(`/shared-summaries/${j}`)}},C=j=>{j>=1&&j<=m&&y(j)},f=a.filter(j=>{var w,T,R,k;if(!o)return!0;const b=o.toLowerCase();return((w=j.title)==null?void 0:w.toLowerCase().includes(b))||((T=j.requestNumber)==null?void 0:T.toLowerCase().includes(b))||((R=j.initiatorName)==null?void 0:R.toLowerCase().includes(b))||((k=j.sharedByName)==null?void 0:k.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(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(xe,{placeholder:"Search by title, request number, or user...",value:o,onChange:j=>l(j.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(Se,{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(j=>e.jsx("div",{className:`bg-white rounded-lg shadow-sm border-2 transition-all cursor-pointer hover:shadow-md ${j.isRead?"border-gray-200":"border-blue-300 bg-blue-50"}`,onClick:()=>v(j.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:[j.isRead?e.jsx(Sr,{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:j.title}),!j.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:j.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:j.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:j.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: ",he(new Date(j.sharedAt),"MMM dd, yyyy HH:mm")]})]}),j.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: ",he(new Date(j.viewedAt),"MMM dd, yyyy HH:mm")]})]})]})]}),e.jsx(D,{variant:"outline",size:"sm",className:"w-full sm:w-auto flex-shrink-0",onClick:b=>{b.stopPropagation(),v(j.sharedSummaryId)},children:"View"})]})})},j.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(D,{variant:"outline",size:"sm",onClick:()=>C(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(D,{variant:"outline",size:"sm",onClick:()=>C(c+1),disabled:c===m,className:"text-xs sm:text-sm",children:"Next"})]})]})]})]})})}function hv(){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 sm(t)}catch(p){console.warn("Failed to mark as viewed:",p)}const h=await tm(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(Ee,{className:"h-4 w-4 text-orange-600"}):e.jsx(Se,{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(D,{variant:"ghost",size:"sm",onClick:()=>s("/shared-summaries"),className:"mb-4",children:[e.jsx(us,{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(X,{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:he(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:he(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(X,{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(Se,{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(D,{onClick:()=>s("/shared-summaries"),children:"Go Back"})]})})}function pv(){const{requestId:t}=rr(),s=Hs(),a=i=>{s(`/${i}`)},r=()=>{s("/new-request")},n=()=>{s("/login")};return e.jsx(Pt,{currentPage:"work-notes",onNavigate:a,onNewRequest:r,onLogout:n,children:e.jsx("div",{className:"h-full w-full overflow-hidden",children:e.jsx(dm,{requestId:t||""})})})}const Yi=x.createContext({});function Zi(t){const s=x.useRef(null);return s.current===null&&(s.current=t()),s.current}const Xi=typeof window<"u",mm=Xi?x.useLayoutEffect:x.useEffect,tn=x.createContext(null);function Qi(t,s){t.indexOf(s)===-1&&t.push(s)}function Ji(t,s){const a=t.indexOf(s);a>-1&&t.splice(a,1)}const As=(t,s,a)=>a>s?s:a<t?t:a;let eo=()=>{};const Ts={},um=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function hm(t){return typeof t=="object"&&t!==null}const pm=t=>/^0[^.\s]+$/u.test(t);function to(t){let s;return()=>(s===void 0&&(s=t()),s)}const ss=t=>t,xv=(t,s)=>a=>s(t(a)),or=(...t)=>t.reduce(xv),Za=(t,s,a)=>{const r=s-t;return r===0?1:(a-t)/r};class so{constructor(){this.subscriptions=[]}add(s){return Qi(this.subscriptions,s),()=>Ji(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 cs=t=>t*1e3,ts=t=>t/1e3;function xm(t,s){return s?t*(1e3/s):0}const gm=(t,s,a)=>(((1-3*a+3*s)*t+(3*a-6*s))*t+3*s)*t,gv=1e-7,fv=12;function yv(t,s,a,r,n){let i,o,l=0;do o=s+(a-s)/2,i=gm(o,r,n)-t,i>0?a=o:s=o;while(Math.abs(i)>gv&&++l<fv);return o}function lr(t,s,a,r){if(t===s&&a===r)return ss;const n=i=>yv(i,0,1,t,a);return i=>i===0||i===1?i:gm(n(i),s,r)}const fm=t=>s=>s<=.5?t(2*s)/2:(2-t(2*(1-s)))/2,ym=t=>s=>1-t(1-s),vm=lr(.33,1.53,.69,.99),ao=ym(vm),bm=fm(ao),jm=t=>(t*=2)<1?.5*ao(t):.5*(2-Math.pow(2,-10*(t-1))),ro=t=>1-Math.sin(Math.acos(t)),Nm=ym(ro),wm=fm(ro),vv=lr(.42,0,1,1),bv=lr(0,0,.58,1),Cm=lr(.42,0,.58,1),jv=t=>Array.isArray(t)&&typeof t[0]!="number",Sm=t=>Array.isArray(t)&&typeof t[0]=="number",Nv={linear:ss,easeIn:vv,easeInOut:Cm,easeOut:bv,circIn:ro,circInOut:wm,circOut:Nm,backIn:ao,backInOut:bm,backOut:vm,anticipate:jm},wv=t=>typeof t=="string",gl=t=>{if(Sm(t)){eo(t.length===4);const[s,a,r,n]=t;return lr(s,a,r,n)}else if(wv(t))return Nv[t];return t},vr=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function Cv(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 Sv=40;function Am(t,s){let a=!1,r=!0;const n={delta:0,timestamp:0,isProcessing:!1},i=()=>a=!0,o=vr.reduce((j,b)=>(j[b]=Cv(i),j),{}),{setup:l,read:c,resolveKeyframes:d,preUpdate:m,update:u,preRender:h,render:p,postRender:g}=o,y=()=>{const j=Ts.useManualTiming?n.timestamp:performance.now();a=!1,Ts.useManualTiming||(n.delta=r?1e3/60:Math.max(Math.min(j-n.timestamp,Sv),1)),n.timestamp=j,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:vr.reduce((j,b)=>{const w=o[b];return j[b]=(T,R=!1,k=!1)=>(a||v(),w.schedule(T,R,k)),j},{}),cancel:j=>{for(let b=0;b<vr.length;b++)o[vr[b]].cancel(j)},state:n,steps:o}}const{schedule:Qe,cancel:Us,state:Rt,steps:Tn}=Am(typeof requestAnimationFrame<"u"?requestAnimationFrame:ss,!0);let Tr;function Av(){Tr=void 0}const Ht={now:()=>(Tr===void 0&&Ht.set(Rt.isProcessing||Ts.useManualTiming?Rt.timestamp:performance.now()),Tr),set:t=>{Tr=t,queueMicrotask(Av)}},Tm=t=>s=>typeof s=="string"&&s.startsWith(t),no=Tm("--"),Tv=Tm("var(--"),io=t=>Tv(t)?kv.test(t.split("/*")[0].trim()):!1,kv=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,Pa={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},Xa={...Pa,transform:t=>As(0,1,t)},br={...Pa,default:1},Ba=t=>Math.round(t*1e5)/1e5,oo=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Rv(t){return t==null}const Pv=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,lo=(t,s)=>a=>!!(typeof a=="string"&&Pv.test(a)&&a.startsWith(t)||s&&!Rv(a)&&Object.prototype.hasOwnProperty.call(a,s)),km=(t,s,a)=>r=>{if(typeof r!="string")return r;const[n,i,o,l]=r.match(oo);return{[t]:parseFloat(n),[s]:parseFloat(i),[a]:parseFloat(o),alpha:l!==void 0?parseFloat(l):1}},Dv=t=>As(0,255,t),kn={...Pa,transform:t=>Math.round(Dv(t))},ra={test:lo("rgb","red"),parse:km("red","green","blue"),transform:({red:t,green:s,blue:a,alpha:r=1})=>"rgba("+kn.transform(t)+", "+kn.transform(s)+", "+kn.transform(a)+", "+Ba(Xa.transform(r))+")"};function Ev(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 li={test:lo("#"),parse:Ev,transform:ra.transform},cr=t=>({test:s=>typeof s=="string"&&s.endsWith(t)&&s.split(" ").length===1,parse:parseFloat,transform:s=>`${s}${t}`}),Ps=cr("deg"),ds=cr("%"),we=cr("px"),Mv=cr("vh"),Iv=cr("vw"),fl={...ds,parse:t=>ds.parse(t)/100,transform:t=>ds.transform(t*100)},pa={test:lo("hsl","hue"),parse:km("hue","saturation","lightness"),transform:({hue:t,saturation:s,lightness:a,alpha:r=1})=>"hsla("+Math.round(t)+", "+ds.transform(Ba(s))+", "+ds.transform(Ba(a))+", "+Ba(Xa.transform(r))+")"},ht={test:t=>ra.test(t)||li.test(t)||pa.test(t),parse:t=>ra.test(t)?ra.parse(t):pa.test(t)?pa.parse(t):li.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?ra.transform(t):pa.transform(t),getAnimatableNone:t=>{const s=ht.parse(t);return s.alpha=0,ht.transform(s)}},Fv=/(?:#[\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(oo))==null?void 0:s.length)||0)+(((a=t.match(Fv))==null?void 0:a.length)||0)>0}const Rm="number",Pm="color",Lv="var",Ov="var(",yl="${}",$v=/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($v,c=>(ht.test(c)?(r.color.push(i),n.push(Pm),a.push(ht.parse(c))):c.startsWith(Ov)?(r.var.push(i),n.push(Lv),a.push(c)):(r.number.push(i),n.push(Rm),a.push(parseFloat(c))),++i,yl)).split(yl);return{values:a,split:l,indexes:r,types:n}}function Dm(t){return Qa(t).values}function Em(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===Rm?i+=Ba(n[o]):l===Pm?i+=ht.transform(n[o]):i+=n[o]}return i}}const Uv=t=>typeof t=="number"?0:ht.test(t)?ht.getAnimatableNone(t):t;function Bv(t){const s=Dm(t);return Em(t)(s.map(Uv))}const Bs={test:_v,parse:Dm,createTransformer:Em,getAnimatableNone:Bv};function Rn(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 Vv({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=Rn(c,l,t+1/3),i=Rn(c,l,t),o=Rn(c,l,t-1/3)}return{red:Math.round(n*255),green:Math.round(i*255),blue:Math.round(o*255),alpha:r}}function Fr(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)},zv=[li,ra,pa],Hv=t=>zv.find(s=>s.test(t));function vl(t){const s=Hv(t);if(!s)return!1;let a=s.parse(t);return s===pa&&(a=Vv(a)),a}const bl=(t,s)=>{const a=vl(t),r=vl(s);if(!a||!r)return Fr(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))},ci=new Set(["none","hidden"]);function qv(t,s){return ci.has(t)?a=>a<=0?t:s:a=>a>=1?s:t}function Wv(t,s){return a=>at(t,s,a)}function co(t){return typeof t=="number"?Wv:typeof t=="string"?io(t)?Fr:ht.test(t)?bl:Yv:Array.isArray(t)?Mm:typeof t=="object"?ht.test(t)?bl:Kv:Fr}function Mm(t,s){const a=[...t],r=a.length,n=t.map((i,o)=>co(i)(i,s[o]));return i=>{for(let o=0;o<r;o++)a[o]=n[o](i);return a}}function Kv(t,s){const a={...t,...s},r={};for(const n in a)t[n]!==void 0&&s[n]!==void 0&&(r[n]=co(t[n])(t[n],s[n]));return n=>{for(const i in r)a[i]=r[i](n);return a}}function Gv(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 Yv=(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?ci.has(t)&&!n.values.length||ci.has(s)&&!r.values.length?qv(t,s):or(Mm(Gv(r,n),n.values),a):Fr(t,s)};function Im(t,s,a){return typeof t=="number"&&typeof s=="number"&&typeof a=="number"?at(t,s,a):co(t)(t,s)}const Zv=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()}},Fm=(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)})`},_r=2e4;function mo(t){let s=0;const a=50;let r=t.next(s);for(;!r.done&&s<_r;)s+=a,r=t.next(s);return s>=_r?1/0:s}function Xv(t,s=100,a){const r=a({...t,keyframes:[0,s]}),n=Math.min(mo(r),_r);return{type:"keyframes",ease:i=>r.next(n*i).value/s,duration:ts(n)}}const Qv=5;function _m(t,s,a){const r=Math.max(s-Qv,0);return xm(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},Dn=.001;function Jv({duration:t=rt.duration,bounce:s=rt.bounce,velocity:a=rt.velocity,mass:r=rt.mass}){let n,i,o=1-s;o=As(rt.minDamping,rt.maxDamping,o),t=As(rt.minDuration,rt.maxDuration,ts(t)),o<1?(n=d=>{const m=d*o,u=m*t,h=m-a,p=di(d,o),g=Math.exp(-u);return Dn-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=di(Math.pow(d,2),o);return(-n(d)+Dn>0?-1:1)*((h-p)*g)/y}):(n=d=>{const m=Math.exp(-d*t),u=(d-a)*t+1;return-Dn+m*u},i=d=>{const m=Math.exp(-d*t),u=(a-d)*(t*t);return m*u});const l=5/t,c=tb(n,i,l);if(t=cs(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 eb=12;function tb(t,s,a){let r=a;for(let n=1;n<eb;n++)r=r-t(r)/s(r);return r}function di(t,s){return t*Math.sqrt(1-s*s)}const sb=["duration","bounce"],ab=["stiffness","damping","mass"];function jl(t,s){return s.some(a=>t[a]!==void 0)}function rb(t){let s={velocity:rt.velocity,stiffness:rt.stiffness,damping:rt.damping,mass:rt.mass,isResolvedFromDuration:!1,...t};if(!jl(t,ab)&&jl(t,sb))if(t.visualDuration){const a=t.visualDuration,r=2*Math.PI/(a*1.2),n=r*r,i=2*As(.05,1,1-(t.bounce||0))*Math.sqrt(n);s={...s,mass:rt.mass,stiffness:n,damping:i}}else{const a=Jv(t);s={...s,...a,mass:rt.mass},s.isResolvedFromDuration=!0}return s}function Lr(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}=rb({...a,velocity:-ts(a.velocity||0)}),g=h||0,y=d/(2*Math.sqrt(c*m)),v=o-i,C=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 j;if(y<1){const w=di(C,y);j=T=>{const R=Math.exp(-y*C*T);return o-R*((g+y*C*v)/w*Math.sin(w*T)+v*Math.cos(w*T))}}else if(y===1)j=w=>o-Math.exp(-C*w)*(v+(g+C*v)*w);else{const w=C*Math.sqrt(y*y-1);j=T=>{const R=Math.exp(-y*C*T),k=Math.min(w*T,300);return o-R*((g+y*C*v)*Math.sinh(k)+w*v*Math.cosh(k))/w}}const b={calculatedDuration:p&&u||null,next:w=>{const T=j(w);if(p)l.done=w>=u;else{let R=w===0?g:0;y<1&&(R=w===0?cs(g):_m(j,w,T));const k=Math.abs(R)<=r,F=Math.abs(o-T)<=n;l.done=k&&F}return l.value=l.done?o:T,l},toString:()=>{const w=Math.min(mo(b),_r),T=Fm(R=>b.next(w*R).value,w,30);return w+"ms "+T},toTransition:()=>{}};return b}Lr.applyToOptions=t=>{const s=Xv(t,100,Lr);return t.ease=s.ease,t.duration=cs(s.duration),t.type="keyframes",t};function mi({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=k=>l!==void 0&&k<l||c!==void 0&&k>c,g=k=>l===void 0?c:c===void 0||Math.abs(l-k)<Math.abs(c-k)?l:c;let y=a*s;const v=u+y,C=o===void 0?v:o(v);C!==v&&(y=C-u);const f=k=>-y*Math.exp(-k/r),j=k=>C+f(k),b=k=>{const F=f(k),N=j(k);h.done=Math.abs(F)<=d,h.value=h.done?C:N};let w,T;const R=k=>{p(h.value)&&(w=k,T=Lr({keyframes:[h.value,g(h.value)],velocity:_m(j,k,h.value),damping:n,stiffness:i,restDelta:d,restSpeed:m}))};return R(0),{calculatedDuration:null,next:k=>{let F=!1;return!T&&w===void 0&&(F=!0,b(k),R(k)),w!==void 0&&k>=w?T.next(k-w):(!F&&b(k),h)}}}function nb(t,s,a){const r=[],n=a||Ts.mix||Im,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 ib(t,s,{clamp:a=!0,ease:r,mixer:n}={}){const i=t.length;if(eo(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=nb(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=Za(t[u],t[u+1],m);return l[u](h)};return a?m=>d(As(t[0],t[i-1],m)):d}function ob(t,s){const a=t[t.length-1];for(let r=1;r<=s;r++){const n=Za(0,s,r);t.push(at(a,1,n))}}function lb(t){const s=[0];return ob(s,t.length-1),s}function cb(t,s){return t.map(a=>a*s)}function db(t,s){return t.map(()=>s||Cm).splice(0,t.length-1)}function Va({duration:t=300,keyframes:s,times:a,ease:r="easeInOut"}){const n=jv(r)?r.map(gl):gl(r),i={done:!1,value:s[0]},o=cb(a&&a.length===s.length?a:lb(s),t),l=ib(o,s,{ease:Array.isArray(n)?n:db(s,n)});return{calculatedDuration:t,next:c=>(i.value=l(c),i.done=c>=t,i)}}const mb=t=>t!==null;function uo(t,{repeat:s,repeatType:a="loop"},r,n=1){const i=t.filter(mb),l=n<0||s&&a!=="loop"&&s%2===1?0:i.length-1;return!l||r===void 0?i[l]:r}const ub={decay:mi,inertia:mi,tween:Va,keyframes:Va,spring:Lr};function Lm(t){typeof t.type=="string"&&(t.type=ub[t.type])}class ho{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 hb=t=>t/100;class po extends ho{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;Lm(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(hb,Im(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=mo(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 C=this.currentTime-d*(this.playbackSpeed>=0?1:-1),f=this.playbackSpeed>=0?C<0:C>n;this.currentTime=Math.max(C,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=n);let j=this.currentTime,b=r;if(u){const k=Math.min(this.currentTime,n)/l;let F=Math.floor(k),N=k%1;!N&&k>=1&&(N=1),N===1&&F--,F=Math.min(F,u+1),!!(F%2)&&(h==="reverse"?(N=1-N,p&&(N-=p/l)):h==="mirror"&&(b=o)),j=As(0,1,N)*l}const w=f?{done:!1,value:m[0]}:b.next(j);i&&(w.value=i(w.value));let{done:T}=w;!f&&c!==null&&(T=this.playbackSpeed>=0?this.currentTime>=n:this.currentTime<=0);const R=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&T);return R&&g!==mi&&(w.value=uo(m,this.options,v,this.speed)),y&&y(w.value),R&&this.finish(),w}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=cs(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=Zv,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 pb(t){for(let s=1;s<t.length;s++)t[s]??(t[s]=t[s-1])}const na=t=>t*180/Math.PI,ui=t=>{const s=na(Math.atan2(t[1],t[0]));return hi(s)},xb={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:ui,rotateZ:ui,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},hi=t=>(t=t%360,t<0&&(t+=360),t),Nl=ui,wl=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),Cl=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),gb={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:wl,scaleY:Cl,scale:t=>(wl(t)+Cl(t))/2,rotateX:t=>hi(na(Math.atan2(t[6],t[5]))),rotateY:t=>hi(na(Math.atan2(-t[2],t[0]))),rotateZ:Nl,rotate:Nl,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 pi(t){return t.includes("scale")?1:0}function xi(t,s){if(!t||t==="none")return pi(s);const a=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,n;if(a)r=gb,n=a;else{const l=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=xb,n=l}if(!n)return pi(s);const i=r[s],o=n[1].split(",").map(yb);return typeof i=="function"?i(o):o[i]}const fb=(t,s)=>{const{transform:a="none"}=getComputedStyle(t);return xi(a,s)};function yb(t){return parseFloat(t.trim())}const Da=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Ea=new Set(Da),Sl=t=>t===Pa||t===we,vb=new Set(["x","y","z"]),bb=Da.filter(t=>!vb.has(t));function jb(t){const s=[];return bb.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})=>xi(s,"x"),y:(t,{transform:s})=>xi(s,"y")};oa.translateX=oa.x;oa.translateY=oa.y;const la=new Set;let gi=!1,fi=!1,yi=!1;function Om(){if(fi){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=jb(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)})}fi=!1,gi=!1,la.forEach(t=>t.complete(yi)),la.clear()}function $m(){la.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(fi=!0)})}function Nb(){yi=!0,$m(),Om(),yi=!1}class xo{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),gi||(gi=!0,Qe.read($m),Qe.resolveKeyframes(Om))):(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])}pb(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 wb=t=>t.startsWith("--");function Cb(t,s,a){wb(s)?t.style.setProperty(s,a):t.style[s]=a}const Sb=to(()=>window.ScrollTimeline!==void 0),Ab={};function Tb(t,s){const a=to(t);return()=>Ab[s]??a()}const Um=Tb(()=>{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})`,Al={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 Bm(t,s){if(t)return typeof t=="function"?Um()?Fm(t,s):"ease-out":Sm(t)?Ua(t):Array.isArray(t)?t.map(a=>Bm(a,s)||Al.easeOut):Al[t]}function kb(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=Bm(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 Vm(t){return typeof t=="function"&&"applyToOptions"in t}function Rb({type:t,...s}){return Vm(t)&&Um()?t.applyToOptions(s):(s.duration??(s.duration=300),s.ease??(s.ease="easeOut"),s)}class Pb extends ho{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,eo(typeof s.type!="string");const d=Rb(s);this.animation=kb(a,r,n,d,i),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const m=uo(n,this.options,l,this.speed);this.updateMotionValue?this.updateMotionValue(m):Cb(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=cs(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&&Sb()?(this.animation.timeline=s,ss):a(this)}}const zm={anticipate:jm,backInOut:bm,circInOut:wm};function Db(t){return t in zm}function Eb(t){typeof t.ease=="string"&&Db(t.ease)&&(t.ease=zm[t.ease])}const Tl=10;class Mb extends Pb{constructor(s){Eb(s),Lm(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 po({...o,autoplay:!1}),c=cs(this.finishedTime??this.time);a.setWithVelocity(l.sample(c-Tl).value,l.sample(c).value,Tl),l.stop()}}const kl=(t,s)=>s==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(Bs.test(t)||t==="0")&&!t.startsWith("url("));function Ib(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 Fb(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=kl(n,s),l=kl(i,s);return!o||!l?!1:Ib(t)||(a==="spring"||Vm(a))&&r}function vi(t){t.duration=0,t.type="keyframes"}const _b=new Set(["opacity","clipPath","filter","transform"]),Lb=to(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function Ob(t){var m;const{motionValue:s,name:a,repeatDelay:r,repeatType:n,damping:i,type:o}=t;if(!(((m=s==null?void 0:s.owner)==null?void 0:m.current)instanceof HTMLElement))return!1;const{onUpdate:c,transformTemplate:d}=s.owner.getProps();return Lb()&&a&&_b.has(a)&&(a!=="transform"||!d)&&!c&&!r&&n!=="mirror"&&i!==0&&o!=="inertia"}const $b=40;class Ub extends ho{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)||xo;this.keyframeResolver=new p(l,(y,v,C)=>this.onKeyframesResolved(y,v,h,!C),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(),Fb(s,i,o,l)||((Ts.instantAnimations||!c)&&(m==null||m(uo(s,r,a))),s[0]=s[s.length-1],vi(r),r.repeat=0);const h={startTime:n?this.resolvedAt?this.resolvedAt-this.createdAt>$b?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:a,...r,keyframes:s},p=!d&&Ob(h)?new Mb({...h,element:h.motionValue.owner.current}):new po(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(),Nb()),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 Bb=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function Vb(t){const s=Bb.exec(t);if(!s)return[,];const[,a,r,n]=s;return[`--${a??r}`,n]}function Hm(t,s,a=1){const[r,n]=Vb(t);if(!r)return;const i=window.getComputedStyle(s).getPropertyValue(r);if(i){const o=i.trim();return um(o)?parseFloat(o):o}return io(n)?Hm(n,s,a+1):n}function go(t,s){return(t==null?void 0:t[s])??(t==null?void 0:t.default)??t}const qm=new Set(["width","height","top","left","right","bottom",...Da]),zb={test:t=>t==="auto",parse:t=>t},Wm=t=>s=>s.test(t),Km=[Pa,we,ds,Ps,Iv,Mv,zb],Rl=t=>Km.find(Wm(t));function Hb(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||pm(t):!0}const qb=new Set(["brightness","contrast","saturate","opacity"]);function Wb(t){const[s,a]=t.slice(0,-1).split("(");if(s==="drop-shadow")return t;const[r]=a.match(oo)||[];if(!r)return t;const n=a.replace(r,"");let i=qb.has(s)?1:0;return r!==a&&(i*=100),s+"("+i+n+")"}const Kb=/\b([a-z-]*)\(.*?\)/gu,bi={...Bs,getAnimatableNone:t=>{const s=t.match(Kb);return s?s.map(Wb).join(" "):t}},Pl={...Pa,transform:Math.round},Gb={rotate:Ps,rotateX:Ps,rotateY:Ps,rotateZ:Ps,scale:br,scaleX:br,scaleY:br,scaleZ:br,skew:Ps,skewX:Ps,skewY:Ps,distance:we,translateX:we,translateY:we,translateZ:we,x:we,y:we,z:we,perspective:we,transformPerspective:we,opacity:Xa,originX:fl,originY:fl,originZ:we},fo={borderWidth:we,borderTopWidth:we,borderRightWidth:we,borderBottomWidth:we,borderLeftWidth:we,borderRadius:we,radius:we,borderTopLeftRadius:we,borderTopRightRadius:we,borderBottomRightRadius:we,borderBottomLeftRadius:we,width:we,maxWidth:we,height:we,maxHeight:we,top:we,right:we,bottom:we,left:we,padding:we,paddingTop:we,paddingRight:we,paddingBottom:we,paddingLeft:we,margin:we,marginTop:we,marginRight:we,marginBottom:we,marginLeft:we,backgroundPositionX:we,backgroundPositionY:we,...Gb,zIndex:Pl,fillOpacity:Xa,strokeOpacity:Xa,numOctaves:Pl},Yb={...fo,color:ht,backgroundColor:ht,outlineColor:ht,fill:ht,stroke:ht,borderColor:ht,borderTopColor:ht,borderRightColor:ht,borderBottomColor:ht,borderLeftColor:ht,filter:bi,WebkitFilter:bi},Gm=t=>Yb[t];function Ym(t,s){let a=Gm(t);return a!==bi&&(a=Bs),a.getAnimatableNone?a.getAnimatableNone(s):void 0}const Zb=new Set(["auto","none","0"]);function Xb(t,s,a){let r=0,n;for(;r<t.length&&!n;){const i=t[r];typeof i=="string"&&!Zb.has(i)&&Qa(i).values.length&&(n=t[r]),r++}if(n&&a)for(const i of s)t[i]=Ym(a,n)}class Qb extends xo{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(),io(d))){const m=Hm(d,a.current);m!==void 0&&(s[c]=m),c===s.length-1&&(this.finalKeyframe=d)}}if(this.resolveNoneKeyframes(),!qm.has(r)||s.length!==2)return;const[n,i]=s,o=Rl(n),l=Rl(i);if(o!==l)if(Sl(o)&&Sl(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||Hb(s[n]))&&r.push(n);r.length&&Xb(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 Jb(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 Xm(t){return hm(t)&&"offsetHeight"in t}const Dl=30,ej=t=>!isNaN(parseFloat(t));class tj{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=ej(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 so);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>Dl)return 0;const a=Math.min(this.updatedAt-this.prevUpdatedAt,Dl);return xm(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 tj(t,s)}const{schedule:yo}=Am(queueMicrotask,!1),rs={x:!1,y:!1};function Qm(){return rs.x||rs.y}function sj(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 Jm(t,s){const a=Jb(t),r=new AbortController,n={passive:!0,...s,signal:r.signal};return[a,n,()=>r.abort()]}function El(t){return!(t.pointerType==="touch"||Qm())}function aj(t,s,a={}){const[r,n,i]=Jm(t,a),o=l=>{if(!El(l))return;const{target:c}=l,d=s(c,l);if(typeof d!="function"||!c)return;const m=u=>{El(u)&&(d(u),c.removeEventListener("pointerleave",m))};c.addEventListener("pointerleave",m,n)};return r.forEach(l=>{l.addEventListener("pointerenter",o,n)}),i}const eu=(t,s)=>s?t===s?!0:eu(t,s.parentElement):!1,vo=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,rj=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function nj(t){return rj.has(t.tagName)||t.tabIndex!==-1}const kr=new WeakSet;function Ml(t){return s=>{s.key==="Enter"&&t(s)}}function En(t,s){t.dispatchEvent(new PointerEvent("pointer"+s,{isPrimary:!0,bubbles:!0}))}const ij=(t,s)=>{const a=t.currentTarget;if(!a)return;const r=Ml(()=>{if(kr.has(a))return;En(a,"down");const n=Ml(()=>{En(a,"up")}),i=()=>En(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 Il(t){return vo(t)&&!Qm()}function oj(t,s,a={}){const[r,n,i]=Jm(t,a),o=l=>{const c=l.currentTarget;if(!Il(l))return;kr.add(c);const d=s(c,l),m=(p,g)=>{window.removeEventListener("pointerup",u),window.removeEventListener("pointercancel",h),kr.has(c)&&kr.delete(c),Il(p)&&typeof d=="function"&&d(p,{success:g})},u=p=>{m(p,c===window||c===document||a.useGlobalTarget||eu(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),Xm(l)&&(l.addEventListener("focus",d=>ij(d,n)),!nj(l)&&!l.hasAttribute("tabindex")&&(l.tabIndex=0))}),i}function tu(t){return hm(t)&&"ownerSVGElement"in t}function lj(t){return tu(t)&&t.tagName==="svg"}const Dt=t=>!!(t&&t.getVelocity),cj=[...Km,ht,Bs],dj=t=>cj.find(Wm(t)),bo=x.createContext({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});function Fl(t,s){if(typeof t=="function")return t(s);t!=null&&(t.current=s)}function mj(...t){return s=>{let a=!1;const r=t.map(n=>{const i=Fl(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():Fl(t[n],null)}}}}function uj(...t){return x.useCallback(mj(...t),t)}class hj extends x.Component{getSnapshotBeforeUpdate(s){const a=this.props.childRef.current;if(a&&s.isPresent&&!this.props.isPresent){const r=a.offsetParent,n=Xm(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 pj({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(bo),c=uj(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(hj,{isPresent:s,childRef:i,sizeRef:o,children:x.cloneElement(t,{ref:c})})}const xj=({children:t,initial:s,isPresent:a,onExitComplete:r,custom:n,presenceAffectsLayout:i,mode:o,anchorX:l,root:c})=>{const d=Zi(gj),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(pj,{isPresent:a,anchorX:l,root:c,children:t})),e.jsx(tn.Provider,{value:h,children:t})};function gj(){return new Map}function su(t=!0){const s=x.useContext(tn);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 jr=t=>t.key||"";function _l(t){const s=[];return x.Children.forEach(t,a=>{x.isValidElement(a)&&s.push(a)}),s}const sn=({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]=su(o),u=x.useMemo(()=>_l(t),[t]),h=o&&!d?[]:u.map(jr),p=x.useRef(!0),g=x.useRef(u),y=Zi(()=>new Map),[v,C]=x.useState(u),[f,j]=x.useState(u);mm(()=>{p.current=!1,g.current=u;for(let T=0;T<f.length;T++){const R=jr(f[T]);h.includes(R)?y.delete(R):y.get(R)!==!0&&y.set(R,!1)}},[f,h.length,h.join("-")]);const b=[];if(u!==v){let T=[...u];for(let R=0;R<f.length;R++){const k=f[R],F=jr(k);h.includes(F)||(T.splice(R,0,k),b.push(k))}return i==="wait"&&b.length&&(T=b),j(_l(T)),C(u),null}const{forceRender:w}=x.useContext(Yi);return e.jsx(e.Fragment,{children:f.map(T=>{const R=jr(T),k=o&&!d?!1:u===f||h.includes(R),F=()=>{if(y.has(R))y.set(R,!0);else return;let N=!0;y.forEach(A=>{A||(N=!1)}),N&&(w==null||w(),j(g.current),o&&(m==null||m()),r&&r())};return e.jsx(xj,{isPresent:k,initial:!p.current||a?void 0:!1,custom:s,presenceAffectsLayout:n,mode:i,root:c,onExitComplete:k?void 0:F,anchorX:l,children:T},R)})})},au=x.createContext({strict:!1}),Ll={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 Ll)Ca[t]={isEnabled:s=>Ll[t].some(a=>!!s[a])};function fj(t){for(const s in t)Ca[s]={...Ca[s],...t[s]}}const yj=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 Or(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||yj.has(t)}let ru=t=>!Or(t);function vj(t){typeof t=="function"&&(ru=s=>s.startsWith("on")?!Or(s):t(s))}try{vj(require("@emotion/is-prop-valid").default)}catch{}function bj(t,s,a){const r={};for(const n in t)n==="values"&&typeof t.values=="object"||(ru(n)||a===!0&&Or(n)||!s&&!Or(n)||t.draggable&&n.startsWith("onDrag"))&&(r[n]=t[n]);return r}const an=x.createContext({});function rn(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function Ja(t){return typeof t=="string"||Array.isArray(t)}const jo=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],No=["initial",...jo];function nn(t){return rn(t.animate)||No.some(s=>Ja(t[s]))}function nu(t){return!!(nn(t)||t.variants)}function jj(t,s){if(nn(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 Nj(t){const{initial:s,animate:a}=jj(t,x.useContext(an));return x.useMemo(()=>({initial:s,animate:a}),[Ol(s),Ol(a)])}function Ol(t){return Array.isArray(t)?t.join(" "):t}const er={};function wj(t){for(const s in t)er[s]=t[s],no(s)&&(er[s].isCSSVariable=!0)}function iu(t,{layout:s,layoutId:a}){return Ea.has(t)||t.startsWith("origin")||(s||a!==void 0)&&(!!er[t]||t==="opacity")}const Cj={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Sj=Da.length;function Aj(t,s,a){let r="",n=!0;for(let i=0;i<Sj;i++){const o=Da[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,fo[o]);if(!c){n=!1;const m=Cj[o]||o;r+=`${m}(${d}) `}a&&(s[o]=d)}}return r=r.trim(),a?r=a(s,n?"":r):n&&(r="none"),r}function wo(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(no(c)){n[c]=d;continue}else{const m=Zm(d,fo[c]);c.startsWith("origin")?(l=!0,i[c]=m):r[c]=m}}if(s.transform||(o||a?r.transform=Aj(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 Co=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function ou(t,s,a){for(const r in s)!Dt(s[r])&&!iu(r,a)&&(t[r]=s[r])}function Tj({transformTemplate:t},s){return x.useMemo(()=>{const a=Co();return wo(a,s,t),Object.assign({},a.vars,a.style)},[s])}function kj(t,s){const a=t.style||{},r={};return ou(r,a,t),Object.assign(r,Tj(t,s)),r}function Rj(t,s){const a={},r=kj(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 Pj={offset:"stroke-dashoffset",array:"stroke-dasharray"},Dj={offset:"strokeDashoffset",array:"strokeDasharray"};function Ej(t,s,a=1,r=0,n=!0){t.pathLength=1;const i=n?Pj:Dj;t[i.offset]=we.transform(-r);const o=we.transform(s),l=we.transform(a);t[i.array]=`${o} ${l}`}function lu(t,{attrX:s,attrY:a,attrScale:r,pathLength:n,pathSpacing:i=1,pathOffset:o=0,...l},c,d,m){if(wo(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&&Ej(u,n,i,o,!1)}const cu=()=>({...Co(),attrs:{}}),du=t=>typeof t=="string"&&t.toLowerCase()==="svg";function Mj(t,s,a,r){const n=x.useMemo(()=>{const i=cu();return lu(i,s,du(r),t.transformTemplate,t.style),{...i.attrs,style:{...i.style}}},[s]);if(t.style){const i={};ou(i,t.style,t),n.style={...i,...n.style}}return n}const Ij=["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 So(t){return typeof t!="string"||t.includes("-")?!1:!!(Ij.indexOf(t)>-1||/[A-Z]/u.test(t))}function Fj(t,s,a,{latestValues:r},n,i=!1){const l=(So(t)?Mj:Rj)(s,r,n,t),c=bj(s,typeof t=="string",i),d=t!==x.Fragment?{...c,...l,ref:a}:{},{children:m}=s,u=x.useMemo(()=>Dt(m)?m.get():m,[m]);return x.createElement(t,{...d,children:u})}function $l(t){const s=[{},{}];return t==null||t.values.forEach((a,r)=>{s[0][r]=a.get(),s[1][r]=a.getVelocity()}),s}function Ao(t,s,a,r){if(typeof s=="function"){const[n,i]=$l(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]=$l(r);s=s(a!==void 0?a:t.custom,n,i)}return s}function Rr(t){return Dt(t)?t.get():t}function _j({scrapeMotionValuesFromProps:t,createRenderState:s},a,r,n){return{latestValues:Lj(a,r,n,t),renderState:s()}}function Lj(t,s,a,r){const n={},i=r(t,{});for(const h in i)n[h]=Rr(i[h]);let{initial:o,animate:l}=t;const c=nn(t),d=nu(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"&&!rn(u)){const h=Array.isArray(u)?u:[u];for(let p=0;p<h.length;p++){const g=Ao(t,h[p]);if(g){const{transitionEnd:y,transition:v,...C}=g;for(const f in C){let j=C[f];if(Array.isArray(j)){const b=m?j.length-1:0;j=j[b]}j!==null&&(n[f]=j)}for(const f in y)n[f]=y[f]}}}return n}const mu=t=>(s,a)=>{const r=x.useContext(an),n=x.useContext(tn),i=()=>_j(t,s,r,n);return a?i():Zi(i)};function To(t,s,a){var i;const{style:r}=t,n={};for(const o in r)(Dt(r[o])||s.style&&Dt(s.style[o])||iu(o,t)||((i=a==null?void 0:a.getValue(o))==null?void 0:i.liveStyle)!==void 0)&&(n[o]=r[o]);return n}const Oj=mu({scrapeMotionValuesFromProps:To,createRenderState:Co});function uu(t,s,a){const r=To(t,s,a);for(const n in t)if(Dt(t[n])||Dt(s[n])){const i=Da.indexOf(n)!==-1?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n;r[i]=t[n]}return r}const $j=mu({scrapeMotionValuesFromProps:uu,createRenderState:cu}),Uj=Symbol.for("motionComponentSymbol");function xa(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function Bj(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 ko=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),Vj="framerAppearId",hu="data-"+ko(Vj),pu=x.createContext({});function zj(t,s,a,r,n){var y,v;const{visualElement:i}=x.useContext(an),o=x.useContext(au),l=x.useContext(tn),c=x.useContext(bo).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(pu);m&&!m.projection&&n&&(m.type==="html"||m.type==="svg")&&Hj(d.current,a,n,u);const h=x.useRef(!1);x.useInsertionEffect(()=>{m&&h.current&&m.update(a,l)});const p=a[hu],g=x.useRef(!!p&&!((y=window.MotionHandoffIsComplete)!=null&&y.call(window,p))&&((v=window.MotionHasOptimisedAnimation)==null?void 0:v.call(window,p)));return mm(()=>{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 C;(C=window.MotionHandoffMarkAsComplete)==null||C.call(window,p)}),g.current=!1),m.enteringChildren=void 0)}),m}function Hj(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:xu(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 xu(t){if(t)return t.options.allowProjection!==!1?t.projection:xu(t.parent)}function Mn(t,{forwardMotionProps:s=!1}={},a,r){a&&fj(a);const n=So(t)?$j:Oj;function i(l,c){let d;const m={...x.useContext(bo),...l,layoutId:qj(l)},{isStatic:u}=m,h=Nj(l),p=n(l,u);if(!u&&Xi){Wj();const g=Kj(m);d=g.MeasureLayout,h.visualElement=zj(t,p,m,r,g.ProjectionNode)}return e.jsxs(an.Provider,{value:h,children:[d&&h.visualElement?e.jsx(d,{visualElement:h.visualElement,...m}):null,Fj(t,l,Bj(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[Uj]=t,o}function qj({layoutId:t}){const s=x.useContext(Yi).id;return s&&t!==void 0?s+"-"+t:t}function Wj(t,s){x.useContext(au).strict}function Kj(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 Gj(t,s){if(typeof Proxy>"u")return Mn;const a=new Map,r=(i,o)=>Mn(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,Mn(o,void 0,t,s)),a.get(o))})}function gu({top:t,left:s,right:a,bottom:r}){return{x:{min:s,max:a},y:{min:t,max:r}}}function Yj({x:t,y:s}){return{top:s.min,right:t.max,bottom:s.max,left:t.min}}function Zj(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 In(t){return t===void 0||t===1}function ji({scale:t,scaleX:s,scaleY:a}){return!In(t)||!In(s)||!In(a)}function Qs(t){return ji(t)||fu(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function fu(t){return Ul(t.x)||Ul(t.y)}function Ul(t){return t&&t!=="0%"}function $r(t,s,a){const r=t-a,n=s*r;return a+n}function Bl(t,s,a,r,n){return n!==void 0&&(t=$r(t,n,r)),$r(t,a,r)+s}function Ni(t,s=0,a=1,r,n){t.min=Bl(t.min,s,a,r,n),t.max=Bl(t.max,s,a,r,n)}function yu(t,{x:s,y:a}){Ni(t.x,s.translate,s.scale,s.originPoint),Ni(t.y,a.translate,a.scale,a.originPoint)}const Vl=.999999999999,zl=1.0000000000001;function Xj(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,yu(t,o)),r&&Qs(i.latestValues)&&fa(t,i.latestValues))}s.x<zl&&s.x>Vl&&(s.x=1),s.y<zl&&s.y>Vl&&(s.y=1)}function ga(t,s){t.min=t.min+s,t.max=t.max+s}function Hl(t,s,a,r,n=.5){const i=at(t.min,t.max,n);Ni(t,s,a,i,r)}function fa(t,s){Hl(t.x,s.x,s.scaleX,s.scale,s.originX),Hl(t.y,s.y,s.scaleY,s.scale,s.originY)}function vu(t,s){return gu(Zj(t.getBoundingClientRect(),s))}function Qj(t,s,a){const r=vu(t,a),{scroll:n}=s;return n&&(ga(r.x,n.offset.x),ga(r.y,n.offset.y)),r}const ql=()=>({translate:0,scale:1,origin:0,originPoint:0}),ya=()=>({x:ql(),y:ql()}),Wl=()=>({min:0,max:0}),dt=()=>({x:Wl(),y:Wl()}),wi={current:null},bu={current:!1};function Jj(){if(bu.current=!0,!!Xi)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),s=()=>wi.current=t.matches;t.addEventListener("change",s),s()}else wi.current=!1}const eN=new WeakMap;function tN(t,s,a){for(const r in s){const n=s[r],i=a[r];if(Dt(n))t.addValue(r,n);else if(Dt(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 Kl=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class sN{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=xo,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=nn(a),this.isVariantNode=nu(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&&Dt(p)&&p.set(c[h])}}mount(s){var a;this.current=s,eN.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)),bu.current||Jj(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:wi.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):dt()}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<Kl.length;r++){const n=Kl[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=tN(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"&&(um(r)||pm(r))?r=parseFloat(r):!dj(r)&&Bs.test(a)&&(r=Ym(s,a)),this.setBaseTarget(s,Dt(r)?r.get():r)),Dt(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=Ao(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&&!Dt(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 so),this.events[s].add(a)}notify(s,...a){this.events[s]&&this.events[s].notify(...a)}scheduleRenderMicrotask(){yo.render(this.render)}}class ju extends sN{constructor(){super(...arguments),this.KeyframeResolver=Qb}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;Dt(s)&&(this.childSubscription=s.on("change",a=>{this.current&&(this.current.textContent=`${a}`)}))}}function Nu(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 aN(t){return window.getComputedStyle(t)}class rN extends ju{constructor(){super(...arguments),this.type="html",this.renderInstance=Nu}readValueFromInstance(s,a){var r;if(Ea.has(a))return(r=this.projection)!=null&&r.isProjecting?pi(a):fb(s,a);{const n=aN(s),i=(no(a)?n.getPropertyValue(a):n[a])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(s,{transformPagePoint:a}){return vu(s,a)}build(s,a,r){wo(s,a,r.transformTemplate)}scrapeMotionValuesFromProps(s,a,r){return To(s,a,r)}}const wu=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 nN(t,s,a,r){Nu(t,s,void 0,r);for(const n in s.attrs)t.setAttribute(wu.has(n)?n:ko(n),s.attrs[n])}class iN extends ju{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=dt}getBaseTargetFromProps(s,a){return s[a]}readValueFromInstance(s,a){if(Ea.has(a)){const r=Gm(a);return r&&r.default||0}return a=wu.has(a)?a:ko(a),s.getAttribute(a)}scrapeMotionValuesFromProps(s,a,r){return uu(s,a,r)}build(s,a,r){lu(s,a,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(s,a,r,n){nN(s,a,r,n)}mount(s){this.isSVGTag=du(s.tagName),super.mount(s)}}const oN=(t,s)=>So(t)?new iN(s):new rN(s,{allowProjection:t!==x.Fragment});function ja(t,s,a){const r=t.getProps();return Ao(r,s,a!==void 0?a:r.custom,t)}const Ci=t=>Array.isArray(t);function lN(t,s,a){t.hasValue(s)?t.getValue(s).set(a):t.addValue(s,wa(a))}function cN(t){return Ci(t)?t[t.length-1]||0:t}function dN(t,s){const a=ja(t,s);let{transitionEnd:r={},transition:n={},...i}=a||{};i={...i,...r};for(const o in i){const l=cN(i[o]);lN(t,o,l)}}function mN(t){return!!(Dt(t)&&t.add)}function Si(t,s){const a=t.getValue("willChange");if(mN(a))return a.add(s);if(!a&&Ts.WillChange){const r=new Ts.WillChange("auto");t.addValue("willChange",r),r.add(s)}}function Cu(t){return t.props[hu]}const uN=t=>t!==null;function hN(t,{repeat:s,repeatType:a="loop"},r){const n=t.filter(uN),i=s&&a!=="loop"&&s%2===1?0:n.length-1;return n[i]}const pN={type:"spring",stiffness:500,damping:25,restSpeed:10},xN=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),gN={type:"keyframes",duration:.8},fN={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},yN=(t,{keyframes:s})=>s.length>2?gN:Ea.has(t)?t.startsWith("scale")?xN(s[1]):pN:fN;function vN({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 Ro=(t,s,a,r={},n,i)=>o=>{const l=go(r,t)||{},c=l.delay||r.delay||0;let{elapsed:d=0}=r;d=d-cs(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};vN(l)||Object.assign(m,yN(t,m)),m.duration&&(m.duration=cs(m.duration)),m.repeatDelay&&(m.repeatDelay=cs(m.repeatDelay)),m.from!==void 0&&(m.keyframes[0]=m.from);let u=!1;if((m.type===!1||m.duration===0&&!m.repeatDelay)&&(vi(m),m.delay===0&&(u=!0)),(Ts.instantAnimations||Ts.skipAnimations)&&(u=!0,vi(m),m.delay=0),m.allowFlatten=!l.type&&!l.ease,u&&!i&&s.get()!==void 0){const h=hN(m.keyframes,l);if(h!==void 0){Qe.update(()=>{m.onUpdate(h),m.onComplete()});return}}return l.isSync?new po(m):new Ub(m)};function bN({protectedKeys:t,needsAnimating:s},a){const r=t.hasOwnProperty(a)&&s[a]!==!0;return s[a]=!1,r}function Su(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&&bN(d,m))continue;const p={delay:a,...go(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 C=Cu(t);if(C){const f=window.MotionHandoffAnimation(C,m,Qe);f!==null&&(p.startTime=f,y=!0)}}Si(t,m),u.start(Ro(m,u,h,t.shouldReduceMotion&&qm.has(m)?{type:!1}:p,t,y));const v=u.animation;v&&c.push(v)}return o&&Promise.all(c).then(()=>{Qe.update(()=>{o&&dN(t,o)})}),c}function Au(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 Ai(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(Su(t,r,a)):()=>Promise.resolve(),o=t.variantChildren&&t.variantChildren.size?(d=0)=>{const{delayChildren:m=0,staggerChildren:u,staggerDirection:h}=n;return jN(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 jN(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(Ai(c,s,{...o,delay:a+(typeof r=="function"?0:r)+Au(t.variantChildren,c,r,n,i)}).then(()=>c.notify("AnimationComplete",s)));return Promise.all(l)}function NN(t,s,a={}){t.notify("AnimationStart",s);let r;if(Array.isArray(s)){const n=s.map(i=>Ai(t,i,a));r=Promise.all(n)}else if(typeof s=="string")r=Ai(t,s,a);else{const n=typeof s=="function"?ja(t,s,a.custom):s;r=Promise.all(Su(t,n,a))}return r.then(()=>{t.notify("AnimationComplete",s)})}function Tu(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 wN=No.length;function ku(t){if(!t)return;if(!t.isControllingVariants){const a=t.parent?ku(t.parent)||{}:{};return t.props.initial!==void 0&&(a.initial=t.props.initial),a}const s={};for(let a=0;a<wN;a++){const r=No[a],n=t.props[r];(Ja(n)||n===!1)&&(s[r]=n)}return s}const CN=[...jo].reverse(),SN=jo.length;function AN(t){return s=>Promise.all(s.map(({animation:a,options:r})=>NN(t,a,r)))}function TN(t){let s=AN(t),a=Gl(),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=ku(t.parent)||{},u=[],h=new Set;let p={},g=1/0;for(let v=0;v<SN;v++){const C=CN[v],f=a[C],j=d[C]!==void 0?d[C]:m[C],b=Ja(j),w=C===c?f.isActive:null;w===!1&&(g=v);let T=j===m[C]&&j!==d[C]&&b;if(T&&r&&t.manuallyAnimateOnMount&&(T=!1),f.protectedKeys={...p},!f.isActive&&w===null||!j&&!f.prevProp||rn(j)||typeof j=="boolean")continue;const R=kN(f.prevProp,j);let k=R||C===c&&f.isActive&&!T&&b||v>g&&b,F=!1;const N=Array.isArray(j)?j:[j];let A=N.reduce(n(C),{});w===!1&&(A={});const{prevResolvedValues:I={}}=f,V={...I,...A},_=M=>{k=!0,h.has(M)&&(F=!0,h.delete(M)),f.needsAnimating[M]=!0;const P=t.getValue(M);P&&(P.liveStyle=!1)};for(const M in V){const P=A[M],E=I[M];if(p.hasOwnProperty(M))continue;let H=!1;Ci(P)&&Ci(E)?H=!Tu(P,E):H=P!==E,H?P!=null?_(M):h.add(M):P!==void 0&&h.has(M)?_(M):f.protectedKeys[M]=!0}f.prevProp=j,f.prevResolvedValues=A,f.isActive&&(p={...p,...A}),r&&t.blockInitialAnimation&&(k=!1);const L=T&&R;k&&(!L||F)&&u.push(...N.map(M=>{const P={type:C};if(typeof M=="string"&&r&&!L&&t.manuallyAnimateOnMount&&t.parent){const{parent:E}=t,H=ja(E,M);if(E.enteringChildren&&H){const{delayChildren:q}=H.transition||{};P.delay=Au(E.enteringChildren,t,q)}}return{animation:M,options:P}}))}if(h.size){const v={};if(typeof d.initial!="boolean"){const C=ja(t,Array.isArray(d.initial)?d.initial[0]:d.initial);C&&C.transition&&(v.transition=C.transition)}h.forEach(C=>{const f=t.getBaseTarget(C),j=t.getValue(C);j&&(j.liveStyle=!0),v[C]=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=Gl()}}}function kN(t,s){return typeof s=="string"?s!==t:Array.isArray(s)?!Tu(s,t):!1}function Ys(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Gl(){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 RN extends qs{constructor(s){super(s),s.animationState||(s.animationState=TN(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();rn(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 PN=0;class DN extends qs{constructor(){super(...arguments),this.id=PN++}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 EN={animation:{Feature:RN},exit:{Feature:DN}};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 MN=t=>s=>vo(s)&&t(s,dr(s));function za(t,s,a,r){return tr(t,s,MN(a),r)}const Ru=1e-4,IN=1-Ru,FN=1+Ru,Pu=.01,_N=0-Pu,LN=0+Pu;function _t(t){return t.max-t.min}function ON(t,s,a){return Math.abs(t-s)<=a}function Yl(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>=IN&&t.scale<=FN||isNaN(t.scale))&&(t.scale=1),(t.translate>=_N&&t.translate<=LN||isNaN(t.translate))&&(t.translate=0)}function Ha(t,s,a,r){Yl(t.x,s.x,a.x,r?r.originX:void 0),Yl(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 $N(t,s,a){Zl(t.x,s.x,a.x),Zl(t.y,s.y,a.y)}function Xl(t,s,a){t.min=s.min-a.min,t.max=t.min+_t(s)}function qa(t,s,a){Xl(t.x,s.x,a.x),Xl(t.y,s.y,a.y)}function es(t){return[t("x"),t("y")]}const Du=({current:t})=>t?t.ownerDocument.defaultView:null,Ql=(t,s)=>Math.abs(t-s);function UN(t,s){const a=Ql(t.x,s.x),r=Ql(t.y,s.y);return Math.sqrt(a**2+r**2)}class Eu{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=_n(this.lastMoveEventInfo,this.history),p=this.startEvent!==null,g=UN(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:C,onMove:f}=this.handlers;p||(C&&C(this.lastMoveEvent,h),this.startEvent=this.lastMoveEvent),f&&f(this.lastMoveEvent,h)},this.handlePointerMove=(h,p)=>{this.lastMoveEvent=h,this.lastMoveEventInfo=Fn(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 C=_n(h.type==="pointercancel"?this.lastMoveEventInfo:Fn(p,this.transformPagePoint),this.history);this.startEvent&&g&&g(h,C),y&&y(h,C)},!vo(s))return;this.dragSnapToOrigin=i,this.handlers=a,this.transformPagePoint=r,this.distanceThreshold=o,this.contextWindow=n||window;const l=dr(s),c=Fn(l,this.transformPagePoint),{point:d}=c,{timestamp:m}=Rt;this.history=[{...d,timestamp:m}];const{onSessionStart:u}=a;u&&u(s,_n(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 Fn(t,s){return s?{point:s(t.point)}:t}function Jl(t,s){return{x:t.x-s.x,y:t.y-s.y}}function _n({point:t},s){return{point:t,delta:Jl(t,Mu(s)),offset:Jl(t,BN(s)),velocity:VN(s,.1)}}function BN(t){return t[0]}function Mu(t){return t[t.length-1]}function VN(t,s){if(t.length<2)return{x:0,y:0};let a=t.length-1,r=null;const n=Mu(t);for(;a>=0&&(r=t[a],!(n.timestamp-r.timestamp>cs(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 zN(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 ec(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 HN(t,{top:s,left:a,bottom:r,right:n}){return{x:ec(t.x,a,n),y:ec(t.y,s,r)}}function tc(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 qN(t,s){return{x:tc(t.x,s.x),y:tc(t.y,s.y)}}function WN(t,s){let a=.5;const r=_t(t),n=_t(s);return n>r?a=Za(s.min,s.max-r,t.min):r>n&&(a=Za(t.min,t.max-n,s.min)),As(0,1,a)}function KN(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 Ti=.35;function GN(t=Ti){return t===!1?t=0:t===!0&&(t=Ti),{x:sc(t,"left","right"),y:sc(t,"top","bottom")}}function sc(t,s,a){return{min:ac(t,s),max:ac(t,a)}}function ac(t,s){return typeof t=="number"?t:t[s]||0}const YN=new WeakMap;class ZN{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=dt(),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=sj(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(C=>{let f=this.getAxisMotionValue(C).get()||0;if(ds.test(f)){const{projection:j}=this.visualElement;if(j&&j.layout){const b=j.layout.layoutBox[C];b&&(f=_t(b)*(parseFloat(f)/100))}}this.originPoint[C]=f}),y&&Qe.postRender(()=>y(u,h)),Si(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:C}=h;if(g&&this.currentDirection===null){this.currentDirection=XN(C),this.currentDirection!==null&&y&&y(this.currentDirection);return}this.updateAxis("x",h.point,C),this.updateAxis("y",h.point,C),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 Eu(s,{onSessionStart:i,onStart:o,onMove:l,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:m,distanceThreshold:r,contextWindow:Du(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||!Nr(s,n,this.currentDirection))return;const i=this.getAxisMotionValue(s);let o=this.originPoint[s]+r[s];this.constraints&&this.constraints[s]&&(o=zN(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=HN(r.layoutBox,s):this.constraints=!1,this.elastic=GN(a),n!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&es(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=KN(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=Qj(r,n.root,this.visualElement.getTransformPagePoint());let o=qN(n.layout.layoutBox,i);if(a){const l=a(Yj(o));this.hasMutatedConstraints=!!l,l&&(o=gu(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(!Nr(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 Si(this.visualElement,s),r.start(Ro(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(!Nr(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]=WN({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(!Nr(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;YN.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=Ti,dragMomentum:l=!0}=s;return{...s,drag:a,dragDirectionLock:r,dragPropagation:n,dragConstraints:i,dragElastic:o,dragMomentum:l}}}function Nr(t,s,a){return(s===!0||s===t)&&(a===null||a===t)}function XN(t,s=10){let a=null;return Math.abs(t.y)>s?a="y":Math.abs(t.x)>s&&(a="x"),a}class QN extends qs{constructor(s){super(s),this.removeGroupControls=ss,this.removeListeners=ss,this.controls=new ZN(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 rc=t=>(s,a)=>{t&&Qe.postRender(()=>t(s,a))};class JN extends qs{constructor(){super(...arguments),this.removePointerDownListener=ss}onPointerDown(s){this.session=new Eu(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Du(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:a,onPan:r,onPanEnd:n}=this.node.getProps();return{onSessionStart:rc(s),onStart:rc(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 nc(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(we.test(t))t=parseFloat(t);else return t;const a=nc(t,s.target.x),r=nc(t,s.target.y);return`${a}% ${r}%`}},ew={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 Ln=!1;class tw extends x.Component{componentDidMount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r,layoutId:n}=this.props,{projection:i}=s;wj(sw),i&&(a.group&&a.group.add(i),r&&r.register&&n&&r.register(i),Ln&&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,Ln=!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(),yo.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r}=this.props,{projection:n}=s;Ln=!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 Iu(t){const[s,a]=su(),r=x.useContext(Yi);return e.jsx(tw,{...t,layoutGroup:r,switchLayoutGroup:x.useContext(pu),isPresent:s,safeToRemove:a})}const sw={borderRadius:{...Oa,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Oa,borderTopRightRadius:Oa,borderBottomLeftRadius:Oa,borderBottomRightRadius:Oa,boxShadow:ew};function aw(t,s,a){const r=Dt(t)?t:wa(t);return r.start(Ro("",r,s,a)),r.animation}const rw=(t,s)=>t.depth-s.depth;class nw{constructor(){this.children=[],this.isDirty=!1}add(s){Qi(this.children,s),this.isDirty=!0}remove(s){Ji(this.children,s),this.isDirty=!0}forEach(s){this.isDirty&&this.children.sort(rw),this.isDirty=!1,this.children.forEach(s)}}function iw(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 Fu=["TopLeft","TopRight","BottomLeft","BottomRight"],ow=Fu.length,ic=t=>typeof t=="string"?parseFloat(t):t,oc=t=>typeof t=="number"||we.test(t);function lw(t,s,a,r,n,i){n?(t.opacity=at(0,a.opacity??1,cw(r)),t.opacityExit=at(s.opacity??1,0,dw(r))):i&&(t.opacity=at(s.opacity??1,a.opacity??1,r));for(let o=0;o<ow;o++){const l=`border${Fu[o]}Radius`;let c=lc(s,l),d=lc(a,l);if(c===void 0&&d===void 0)continue;c||(c=0),d||(d=0),c===0||d===0||oc(c)===oc(d)?(t[l]=Math.max(at(ic(c),ic(d),r),0),(ds.test(d)||ds.test(c))&&(t[l]+="%")):t[l]=d}(s.rotate||a.rotate)&&(t.rotate=at(s.rotate||0,a.rotate||0,r))}function lc(t,s){return t[s]!==void 0?t[s]:t.borderRadius}const cw=_u(0,.5,Nm),dw=_u(.5,.95,ss);function _u(t,s,a){return r=>r<t?0:r>s?1:a(Za(t,s,r))}function cc(t,s){t.min=s.min,t.max=s.max}function Jt(t,s){cc(t.x,s.x),cc(t.y,s.y)}function dc(t,s){t.translate=s.translate,t.scale=s.scale,t.originPoint=s.originPoint,t.origin=s.origin}function mc(t,s,a,r,n){return t-=s,t=$r(t,1/a,r),n!==void 0&&(t=$r(t,1/n,r)),t}function mw(t,s=0,a=1,r=.5,n,i=t,o=t){if(ds.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=mc(t.min,s,a,l,n),t.max=mc(t.max,s,a,l,n)}function uc(t,s,[a,r,n],i,o){mw(t,s[a],s[r],s[n],s.scale,i,o)}const uw=["x","scaleX","originX"],hw=["y","scaleY","originY"];function hc(t,s,a,r){uc(t.x,s,uw,a?a.x:void 0,r?r.x:void 0),uc(t.y,s,hw,a?a.y:void 0,r?r.y:void 0)}function pc(t){return t.translate===0&&t.scale===1}function Lu(t){return pc(t.x)&&pc(t.y)}function xc(t,s){return t.min===s.min&&t.max===s.max}function pw(t,s){return xc(t.x,s.x)&&xc(t.y,s.y)}function gc(t,s){return Math.round(t.min)===Math.round(s.min)&&Math.round(t.max)===Math.round(s.max)}function Ou(t,s){return gc(t.x,s.x)&&gc(t.y,s.y)}function fc(t){return _t(t.x)/_t(t.y)}function yc(t,s){return t.translate===s.translate&&t.scale===s.scale&&t.originPoint===s.originPoint}class xw{constructor(){this.members=[]}add(s){Qi(this.members,s),s.scheduleRender()}remove(s){if(Ji(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 gw(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 On=["","X","Y","Z"],fw=1e3;let yw=0;function $n(t,s,a,r){const{latestValues:n}=s;n[t]&&(a[t]=n[t],s.setStaticValue(t,0),r&&(r[t]=0))}function $u(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:s}=t.options;if(!s)return;const a=Cu(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&&$u(r)}function Uu({attachResizeListener:t,defaultParent:s,measureScroll:a,checkIsScrollRoot:r,resetTransform:n}){return class{constructor(o={},l=s==null?void 0:s()){this.id=yw++,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(jw),this.nodes.forEach(Sw),this.nodes.forEach(Aw),this.nodes.forEach(Nw)},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 nw)}addEventListener(o,l){return this.eventHandlers.has(o)||this.eventHandlers.set(o,new so),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=tu(o)&&!lj(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=iw(h,250),Pr.hasAnimatedSinceResize&&(Pr.hasAnimatedSinceResize=!1,this.nodes.forEach(jc)))})}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()||Dw,{onLayoutAnimationStart:y,onLayoutAnimationComplete:v}=d.getProps(),C=!this.targetLayout||!Ou(this.targetLayout,p),f=!u&&h;if(this.options.layoutRoot||this.resumeFrom||f||u&&(C||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const j={...go(g,"layout"),onPlay:y,onComplete:v};(d.shouldReduceMotion||this.options.layoutRoot)&&(j.delay=0,j.type=!1),this.startAnimation(j),this.setAnimationOrigin(m,f)}else u||jc(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(Tw),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&&$u(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(vc);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(bc);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(Cw),this.nodes.forEach(vw),this.nodes.forEach(bw)):this.nodes.forEach(bc),this.clearAllSnapshots();const l=Ht.now();Rt.delta=As(0,1e3/60,l-Rt.timestamp),Rt.timestamp=l,Rt.isProcessing=!0,Tn.update.process(Rt),Tn.preRender.process(Rt),Tn.render.process(Rt),Rt.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,yo.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(ww),this.sharedNodes.forEach(kw)}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=dt(),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&&!Lu(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)),Ew(c),{animationId:this.root.animationId,measuredBox:l,layoutBox:c,latestValues:{},source:this.id}}measurePageBox(){var d;const{visualElement:o}=this.options;if(!o)return dt();const l=o.measureViewportBox();if(!(((d=this.scroll)==null?void 0:d.wasRoot)||this.path.some(Mw))){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=dt();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=dt();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=dt();Jt(l,o);for(let c=0;c<this.path.length;c++){const d=this.path[c];if(!d.instance||!Qs(d.latestValues))continue;ji(d.latestValues)&&d.updateSnapshot();const m=dt(),u=d.measurePageBox();Jt(m,u),hc(l,d.latestValues,d.snapshot?d.snapshot.layoutBox:void 0,m)}return Qs(this.latestValues)&&hc(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=dt(),this.relativeTargetOrigin=dt(),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=dt(),this.targetWithTransforms=dt()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),$N(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):Jt(this.target,this.layout.layoutBox),yu(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=dt(),this.relativeTargetOrigin=dt(),qa(this.relativeTargetOrigin,this.target,p.target),Jt(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||ji(this.parent.latestValues)||fu(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;Xj(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=dt());const{target:p}=o;if(!p){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(dc(this.prevProjectionDelta.x,this.projectionDelta.x),dc(this.prevProjectionDelta.y,this.projectionDelta.y)),Ha(this.projectionDelta,this.layoutCorrected,p,this.latestValues),(this.treeScale.x!==u||this.treeScale.y!==h||!yc(this.projectionDelta.x,this.prevProjectionDelta.x)||!yc(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=dt(),p=c?c.source:void 0,g=this.layout?this.layout.source:void 0,y=p!==g,v=this.getStack(),C=!v||v.members.length<=1,f=!!(y&&!C&&this.options.crossfade===!0&&!this.path.some(Pw));this.animationProgress=0;let j;this.mixTargetDelta=b=>{const w=b/1e3;Nc(u.x,o.x,w),Nc(u.y,o.y,w),this.setTargetDelta(u),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(qa(h,this.layout.layoutBox,this.relativeParent.layout.layoutBox),Rw(this.relativeTarget,this.relativeTargetOrigin,h,w),j&&pw(this.relativeTarget,j)&&(this.isProjectionDirty=!1),j||(j=dt()),Jt(j,this.relativeTarget)),y&&(this.animationValues=m,lw(m,d,this.latestValues,w,f,C)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=w},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=aw(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(fw),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&&Bu(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||dt();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 xw),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&&$n("z",o,d,this.animationValues);for(let m=0;m<On.length;m++)$n(`rotate${On[m]}`,o,d,this.animationValues),$n(`skew${On[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=Rr(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=Rr(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=gw(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:C}=er[g],f=u==="none"?m[g]:y(m[g],d);if(v){const j=v.length;for(let b=0;b<j;b++)o[v[b]]=f}else C?this.options.visualElement.renderState.vars[g]=f:o[g]=f}this.options.layoutId&&(o.pointerEvents=d===this?Rr(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(vc),this.root.sharedNodes.clear()}}}function vw(t){t.updateLayout()}function bw(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}):Bu(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=!Lu(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=dt();qa(g,s.layoutBox,h.layoutBox);const y=dt();qa(y,r,p.layoutBox),Ou(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 jw(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 Nw(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function ww(t){t.clearSnapshot()}function vc(t){t.clearMeasurements()}function bc(t){t.isLayoutDirty=!1}function Cw(t){const{visualElement:s}=t.options;s&&s.getProps().onBeforeLayoutMeasure&&s.notify("BeforeLayoutMeasure"),t.resetTransform()}function jc(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function Sw(t){t.resolveTargetDelta()}function Aw(t){t.calcProjection()}function Tw(t){t.resetSkewAndRotation()}function kw(t){t.removeLeadSnapshot()}function Nc(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 wc(t,s,a,r){t.min=at(s.min,a.min,r),t.max=at(s.max,a.max,r)}function Rw(t,s,a,r){wc(t.x,s.x,a.x,r),wc(t.y,s.y,a.y,r)}function Pw(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const Dw={duration:.45,ease:[.4,0,.1,1]},Cc=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),Sc=Cc("applewebkit/")&&!Cc("chrome/")?Math.round:ss;function Ac(t){t.min=Sc(t.min),t.max=Sc(t.max)}function Ew(t){Ac(t.x),Ac(t.y)}function Bu(t,s,a){return t==="position"||t==="preserve-aspect"&&!ON(fc(s),fc(a),.2)}function Mw(t){var s;return t!==t.root&&((s=t.scroll)==null?void 0:s.wasRoot)}const Iw=Uu({attachResizeListener:(t,s)=>tr(t,"resize",s),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Un={current:void 0},Vu=Uu({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!Un.current){const t=new Iw({});t.mount(window),t.setOptions({layoutScroll:!0}),Un.current=t}return Un.current},resetTransform:(t,s)=>{t.style.transform=s!==void 0?s:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),Fw={pan:{Feature:JN},drag:{Feature:QN,ProjectionNode:Vu,MeasureLayout:Iu}};function Tc(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=aj(s,(a,r)=>(Tc(this.node,r,"Start"),n=>Tc(this.node,n,"End"))))}unmount(){}}class Lw 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 kc(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 Ow extends qs{mount(){const{current:s}=this.node;s&&(this.unmount=oj(s,(a,r)=>(kc(this.node,r,"Start"),(n,{success:i})=>kc(this.node,n,i?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const ki=new WeakMap,Bn=new WeakMap,$w=t=>{const s=ki.get(t.target);s&&s(t)},Uw=t=>{t.forEach($w)};function Bw({root:t,...s}){const a=t||document;Bn.has(a)||Bn.set(a,{});const r=Bn.get(a),n=JSON.stringify(s);return r[n]||(r[n]=new IntersectionObserver(Uw,{root:t,...s})),r[n]}function Vw(t,s,a){const r=Bw(s);return ki.set(t,a),r.observe(t),()=>{ki.delete(t),r.unobserve(t)}}const zw={some:0,all:1};class Hw 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:zw[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 Vw(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(qw(s,a))&&this.startObserver()}unmount(){}}function qw({viewport:t={}},{viewport:s={}}={}){return a=>t[a]!==s[a]}const Ww={inView:{Feature:Hw},tap:{Feature:Ow},focus:{Feature:Lw},hover:{Feature:_w}},Kw={layout:{ProjectionNode:Vu,MeasureLayout:Iu}},Gw={...EN,...Ww,...Fw,...Kw},Tt=Gj(Gw,oN),Rc=[{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:si,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:vx,color:"from-green-500 to-emerald-600",estimatedTime:"3-5 days",steps:5,features:["PO matching","Invoice verification","Multi-level approvals","Payment scheduling"]}];function Yw({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(Ze,{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(Xe,{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(ft,{className:"w-5 h-5 text-gray-600"})}),e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsxs("div",{className:"min-h-full flex flex-col items-center justify-center px-6 py-12",children:[e.jsxs(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(Kr,{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:Rc.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(W,{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(ee,{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(te,{className:"text-xl mb-2",children:c.name}),e.jsx(pe,{className:"text-sm leading-relaxed",children:c.description})]})]}),e.jsxs(K,{className:"pt-0 space-y-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(X,{variant:"secondary",className:"text-xs",children:c.category})}),e.jsx(ct,{}),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(Ee,{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(lt,{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(D,{variant:"outline",onClick:s,size:"lg",className:"px-8",children:"Cancel"}),e.jsxs(D,{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(sn,{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=Rc.find(c=>c.id===r))==null?void 0:l.name})]})})})]})})]})})}const Zw={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 Xw(t,s,a){const[r,n]=x.useState(Zw),[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 C;try{const f=await ia("DOCUMENT_POLICY"),j={};f.forEach(A=>{j[A.configKey]=A.configValue});const b=parseInt(j.MAX_FILE_SIZE_MB||"10"),T=(j.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(A=>A.trim().toLowerCase());h({maxFileSizeMB:b,allowedFileTypes:T});const R=await ia("WORKFLOW_SHARING"),k=await ia("TAT_SETTINGS"),F=[...R,...k],N={};F.forEach(A=>{N[A.configKey]=A.configValue}),m({maxApprovalLevels:parseInt(N.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(N.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((C=N.ALLOW_ADD_SPECTATOR)==null?void 0:C.toLowerCase())==="true",maxSpectators:parseInt(N.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 C=await aa(s);if(!v||!C)return;const f=C.workflow||{},j=Array.isArray(C.approvals)?C.approvals:[],b=Array.isArray(C.participants)?C.participants:[],w=Array.isArray(C.documents)?C.documents.filter(I=>!I.isDeleted):[];g(w);const T=(f.priority||"").toString().toLowerCase(),R={standard:"standard",express:"express"},k=f.templateType==="TEMPLATE"?"existing-template":"custom",F=a.find(I=>I.id===k)||a[0]||null;o(F);const N=j.sort((I,V)=>(I.levelNumber||0)-(V.levelNumber||0)).map(I=>{const V=Number(I.tatHours||24),_=Math.floor(V/24),L=V%24;return{id:I.approverId||`temp-${I.levelNumber}`,name:I.approverName||I.approverEmail||"",email:I.approverEmail||"",role:I.levelName||`Level ${I.levelNumber}`,department:"",avatar:(I.approverName||I.approverEmail||"XX").substring(0,2).toUpperCase(),level:I.levelNumber||1,canClose:!1,tat:_>0?_:L,tatType:_>0?"days":"hours",userId:I.approverId}}),A=b.filter(I=>(I.participantType||I.participant_type||"").toString().toUpperCase().trim()==="SPECTATOR"?!!(I.userEmail||I.user_email||I.email):!1).map((I,V)=>{const _=I.userId||I.user_id||I.id,L=I.userName||I.user_name||I.name||"",S=I.userEmail||I.user_email||I.email||"",P=(L||S||"XX").split(" ").map(E=>E[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{id:_||`spectator-${s}-${V}-${Date.now()}`,userId:_,name:L||S||"Spectator",email:S,role:"Spectator",department:I.department||"",avatar:P,level:1,canClose:!1}});n(I=>({...I,template:k,title:f.title||"",description:f.description||"",priority:R[T]||"standard",approvers:N,approverCount:N.length||1,spectators:A,maxLevel:Math.max(...N.map(V=>V.level||1),1)}))}catch(C){console.error("Failed to load draft:",C)}finally{v&&c(!1)}})(),()=>{v=!1}},[t,s,a]),{formData:r,setFormData:n,updateFormData:(v,C)=>{n(f=>({...f,[v]:C}))},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 Qw(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 Jw(){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 e1(t,s){const a=typeof t=="number"?t:parseInt(String(t))||0;return s==="days"?a*24:a||24}function t1(t,s,a){var n;const r=e1(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 s1(t,s){return t.slice(0,s).map((a,r)=>{const n=r+1;return t1(a,n,n===s)})}function Dc(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 Ec(t,s,a){const r=s1(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 a1(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 zu(t,s){return{id:(await qd(t,s||[],"SUPPORTING")).id}}async function Hu(t,s,a,r){const n=a&&a.length>0,i=r.length>0;n||i?await I0(t,s,a||[],r):await M0(t,s)}async function qu(t){await Zd(t)}async function r1(t,s){const a=await zu(t,s);return await qu(a.id),a}async function n1(t,s,a,r){await Hu(t,s,a,r),await qu(t)}function i1({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=a1(t.approvers||[],t.approverCount||1);if(!g.valid){alert(g.message);return}d(!0);try{if(i&&o){const y=Ec(t,n,r);await n1(o,y,a,r),l==null||l({...t,backendId:o,template:s})}else{const y=Dc(t,s,n),v=await r1(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=Ec(t,n,r);await Hu(o,g,a,r),l==null||l({...t,backendId:o,template:s})}else{const g=Dc(t,s,n),y=await zu(g,a);l==null||l({...t,backendId:y.id,template:s})}}catch(g){console.error("Failed to save draft:",g),u(!1)}}}}}async function o1(t,s){var a;if(t.email.toLowerCase()===s.toLowerCase())return{success:!1,error:{type:"self-assign",email:t.email,message:""}};try{const n=((a=(await xs(t.email,1)).data)==null?void 0:a.data)||[];if(n.length===0)return{success:!1,error:{type:"not-found",email:t.email,message:""}};const i=n[0];return i?(await Ss({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 l1(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 o1(o,s);if(!l.success)return{success:!1,error:l.error};try{const m=(((n=(await xs(o.email,1)).data)==null?void 0:n.data)||[])[0];if(m){const u=await Ss({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 c1({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:w=>{s(w),a("template",w.id),a("category",w.category),a("priority",w.priority);const T=new Date;T.setDate(T.getDate()+w.suggestedSLA),a("slaEndDate",T),w.id==="existing-template"&&h(!0)},handleTemplateSelection:w=>{m&&m({templateType:w})},nextStep:async()=>{var w;if(i()){if(window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}),n===3){const T=((w=c==null?void 0:c.email)==null?void 0:w.toLowerCase())||"",R=await l1(r.approvers,T);if(!R.success&&R.error){d(R.error.type,R.error.email,R.error.message);return}R.validatedApprovers&&a("approvers",R.validatedApprovers)}o()}},prevStep:()=>{l(),window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"})},handlePreviewDocument:(w,T)=>{if(T){const R=w.documentId||w.document_id||"";g({fileName:w.originalFileName||w.fileName||"Document",fileType:w.fileType||w.file_type||"application/octet-stream",fileUrl:Yd(R),fileSize:Number(w.fileSize||w.file_size||0),documentId:R})}else{const R=URL.createObjectURL(w);g({fileName:w.name,fileType:w.type||"application/octet-stream",fileUrl:R,fileSize:w.size,file:w})}},closePreview:()=>{p!=null&&p.fileUrl&&(p!=null&&p.file)&&URL.revokeObjectURL(p.fileUrl),g(null)}}}const Mc=[{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:Wr,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:Se,estimatedTime:"1-2 days",commonApprovers:["Department Head","Manager"],suggestedSLA:2,priority:"medium",fields:{timeline:!0}}];function d1({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 m1({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(D,{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(us,{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(D,{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(D,{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(bd,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),"Submit"]})}):e.jsxs(D,{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 Ic=t=>{switch(t){case"high":return e.jsx(ls,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(lt,{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(lt,{className:"w-4 h-4 text-gray-600"})}};function u1({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(W,{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(ee,{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(te,{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(X,{variant:"secondary",className:"text-xs","data-testid":`template-card-${r.id}-category`,children:r.category}),Ic(r.priority)]})]})]}),e.jsxs(K,{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(ct,{}),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(Ee,{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(sn,{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(W,{className:"bg-gradient-to-br from-blue-50 to-indigo-50 border-2 border-blue-200",children:[e.jsx(ee,{children:e.jsxs(te,{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(K,{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(Z,{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(Z,{className:"text-blue-900 font-semibold",children:"Priority Level"}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[Ic(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(Z,{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(Z,{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(X,{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 h1({className:t,...s}){return e.jsx(yp,{"data-slot":"radio-group",className:le("grid gap-3",t),...s})}function Fc({className:t,...s}){return e.jsx(vp,{"data-slot":"radio-group-item",className:le("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(bp,{"data-slot":"radio-group-indicator",className:"relative flex items-center justify-center",children:e.jsx(bx,{className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}function p1({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(Se,{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(Z,{htmlFor:"title",className:"text-base font-semibold",children:"Request Title *"}),e.jsx("p",{className:"text-sm text-gray-600 mb-3",children:"Be specific and descriptive. This will be visible to all participants."}),e.jsx(xe,{id:"title",placeholder:"e.g., Approval on new office location",value:t.title,onChange:r=>a("title",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-title-input"})]}),e.jsxs("div",{"data-testid":"basic-information-description-field",children:[e.jsx(Z,{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(am,{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(Z,{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(h1,{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(Fc,{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(_i,{className:"w-4 h-4 text-red-600"}),e.jsx(Z,{htmlFor:"express",className:"font-medium text-red-900 cursor-pointer",children:"Express"}),e.jsx(X,{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(Fc,{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(Ee,{className:"w-4 h-4 text-blue-600"}),e.jsx(Z,{htmlFor:"standard",className:"font-medium text-blue-900 cursor-pointer",children:"Standard"}),e.jsx(X,{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(Z,{htmlFor:"amount",className:"text-base font-semibold",children:"Budget Amount"}),e.jsx(xe,{id:"amount",placeholder:"Enter amount",value:t.amount,onChange:r=>a("amount",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-amount-input"})]}),e.jsxs("div",{children:[e.jsx(Z,{className:"text-base font-semibold",children:"Currency"}),e.jsxs(Ae,{value:t.currency,onValueChange:r=>a("currency",r),"data-testid":"basic-information-currency-select",children:[e.jsx(ke,{className:"h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm",children:e.jsx(Te,{})}),e.jsxs(Re,{children:[e.jsx(O,{value:"USD",children:"USD ($)"}),e.jsx(O,{value:"EUR",children:"EUR (€)"}),e.jsx(O,{value:"GBP",children:"GBP (£)"}),e.jsx(O,{value:"INR",children:"INR (₹)"})]})]})]})]}),(s==null?void 0:s.fields.vendor)&&e.jsxs("div",{"data-testid":"basic-information-vendor-field",children:[e.jsx(Z,{htmlFor:"vendor",className:"text-base font-semibold",children:"Vendor/Supplier"}),e.jsx(xe,{id:"vendor",placeholder:"Enter vendor or supplier name",value:t.vendor,onChange:r=>a("vendor",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-vendor-input"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{"data-testid":"basic-information-cost-center-field",children:[e.jsx(Z,{htmlFor:"costCenter",className:"text-base font-semibold",children:"Cost Center"}),e.jsx(xe,{id:"costCenter",placeholder:"e.g., Marketing, IT, Operations",value:t.costCenter,onChange:r=>a("costCenter",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-cost-center-input"})]}),e.jsxs("div",{"data-testid":"basic-information-project-field",children:[e.jsx(Z,{htmlFor:"project",className:"text-base font-semibold",children:"Related Project"}),e.jsx(xe,{id:"project",placeholder:"Associated project name or code",value:t.project,onChange:r=>a("project",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-project-input"})]})]})]})]})]})]})}function x1(){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 xs(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 Ss({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 g1(){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 xs(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 f1({formData:t,updateFormData:s,onValidationError:a}){var d;const{userSearchResults:r,userSearchLoading:n,searchUsersForIndex:i,clearSearchForIndex:o}=g1();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,C,f,j;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||(C=h[m])==null?void 0:C.name,department:g||(f=h[m])==null?void 0:f.department,avatar:g||(j=h[m])==null?void 0:j.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,j)=>{var b,w;return j!==m&&(f.userId===u.userId||((b=f.email)==null?void 0:b.toLowerCase())===((w=u.email)==null?void 0:w.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 j,b;return f.userId===u.userId||((j=f.email)==null?void 0:j.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 Ss({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}),C=[...t.approvers];C[m]={...C[m],email:u.email,name:u.displayName||[u.firstName,u.lastName].filter(Boolean).join(" "),userId:v.userId,level:m+1},s("approvers",C),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(W,{"data-testid":"approval-workflow-config-card",children:[e.jsxs(ee,{children:[e.jsxs(te,{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(pe,{children:"Configure how many approvers you need and define the approval sequence."})]}),e.jsx(K,{className:"space-y-6",children:e.jsxs("div",{"data-testid":"approval-workflow-count-field",children:[e.jsx(Z,{className:"text-base font-semibold mb-4 block",children:"Number of Approvers *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(D,{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(jx,{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(D,{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(W,{"data-testid":"approval-workflow-hierarchy-card",children:[e.jsxs(ee,{children:[e.jsxs(te,{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(pe,{children:["Define the approval sequence. Each approver will review the request in order from Level 1 to Level ",t.approverCount||1,"."]})]}),e.jsxs(K,{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(X,{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(X,{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(Z,{htmlFor:`approver-${h}`,className:"text-sm font-medium",children:"Email Address *"}),g.email&&g.userId&&e.jsxs(X,{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(xe,{id:`approver-${h}`,type:"email",placeholder:"approver@royalenfield.com",value:g.email||"",onChange:C=>l(u,C.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(C=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>c(u,C),"data-testid":`approval-workflow-approver-${h}-search-result-${C.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:C.displayName||C.email}),e.jsx("div",{className:"text-xs text-gray-600",children:C.email})]},C.userId))})})]})]}),e.jsxs("div",{"data-testid":`approval-workflow-approver-${h}-tat-field`,children:[e.jsx(Z,{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(xe,{id:`tat-${h}`,type:"number",placeholder:g.tatType==="days"?"7":"24",min:"1",max:g.tatType==="days"?"30":"720",value:g.tat||"",onChange:C=>{const f=[...t.approvers];f[u]={...f[u],tat:parseInt(C.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(Ae,{value:g.tatType||"hours",onValueChange:C=>{const f=[...t.approvers];f[u]={...f[u],tatType:C,level:h,tat:""},s("approvers",f)},"data-testid":`approval-workflow-approver-${h}-tat-type-select`,children:[e.jsx(ke,{className:"w-20 h-10 border-2 border-gray-300",children:e.jsx(Te,{})}),e.jsxs(Re,{children:[e.jsx(O,{value:"hours",children:"Hours"}),e.jsx(O,{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(Ee,{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 y1({formData:t,updateFormData:s,onValidationError:a,initiatorEmail:r}){const[n,i]=x.useState(""),{searchResults:o,searchLoading:l,searchUsersDebounced:c,clearSearch:d,ensureUser:m}=x1(),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 C=t.spectators.some(j=>{var b,w;return j.userId===g.userId||((b=j.email)==null?void 0:b.toLowerCase())===((w=g.email)==null?void 0:w.toLowerCase())}),f=(y=t.approvers)==null?void 0:y.some(j=>{var b,w;return j.userId===g.userId||((b=j.email)==null?void 0:b.toLowerCase())===((w=g.email)==null?void 0:w.toLowerCase())});if(C){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 j=await m(g),b={id:j.userId,userId:j.userId,name:j.displayName||g.email.split("@")[0],email:j.email,avatar:(j.displayName||j.email).substring(0,2).toUpperCase(),role:"Spectator",department:j.department||"",level:1,canClose:!1},w=[...t.spectators,b];s("spectators",w),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 C=t.spectators.some(j=>{var b;return((b=j.email)==null?void 0:b.toLowerCase())===n.toLowerCase()}),f=(v=t.approvers)==null?void 0:v.some(j=>{var b;return((b=j.email)==null?void 0:b.toLowerCase())===n.toLowerCase()});if(C){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(W,{"data-testid":"participants-spectators-card",children:[e.jsxs(ee,{children:[e.jsxs(te,{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(X,{variant:"outline",className:"text-xs","data-testid":"participants-spectators-count",children:t.spectators.length})]}),e.jsx(pe,{children:"Users who can view and comment but cannot approve"})]}),e.jsxs(K,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2","data-testid":"participants-spectators-add-section",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative w-full",children:[e.jsx(xe,{placeholder:"Use @ sign to add a user",value:n,onChange: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(D,{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(D,{variant:"ghost",size:"sm",onClick:()=>p(g.id),"data-testid":`participants-spectator-${g.id}-remove`,children:e.jsx(ft,{className:"h-3 w-3"})})]},g.id))})]})]})})})]})}function v1({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 C=t.maxFileSizeMB*1024*1024,f=[],j=[];v.forEach(b=>{if(b.size>C){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 w=b.name.toLowerCase(),T=w.substring(w.lastIndexOf(".")+1);if(!t.allowedFileTypes.includes(T)){f.push({fileName:b.name,reason:`File type "${T}" is not allowed. Allowed types: ${t.allowedFileTypes.join(", ")}`});return}j.push(b)}),j.length>0&&i([...a,...j]),f.length>0&&d&&d(f),y.target&&(y.target.value="")},h=y=>{const v=a.filter((C,f)=>f!==y);i(v)},p=y=>{l([...n,y])},g=(y,v=!1)=>{if(v){const C=(y.fileType||y.file_type||"").toLowerCase(),f=(y.originalFileName||y.fileName||"").toLowerCase();return C.includes("image")||C.includes("pdf")||f.endsWith(".jpg")||f.endsWith(".jpeg")||f.endsWith(".png")||f.endsWith(".gif")||f.endsWith(".pdf")}else{const C=(y.type||"").toLowerCase(),f=(y.name||"").toLowerCase();return C.includes("image")||C.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(W,{"data-testid":"documents-upload-card",children:[e.jsxs(ee,{children:[e.jsxs(te,{className:"flex items-center gap-2","data-testid":"documents-upload-title",children:[e.jsx(Se,{className:"w-5 h-5"}),"File Upload"]}),e.jsxs(pe,{children:["Attach supporting documents. Max ",t.maxFileSizeMB,"MB per file. Allowed types: ",t.allowedFileTypes.join(", ")]})]}),e.jsx(K,{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(D,{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(W,{"data-testid":"documents-existing-card",children:[e.jsx(ee,{children:e.jsxs(te,{className:"flex items-center justify-between","data-testid":"documents-existing-title",children:[e.jsx("span",{children:"Existing Documents"}),e.jsxs(X,{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(K,{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(Se,{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(D,{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(D,{variant:"ghost",size:"sm",onClick:()=>p(v),"data-testid":`documents-existing-${v}-delete`,children:e.jsx(ft,{className:"h-4 w-4 text-red-600"})})]})]},v)})})})]}),a.length>0&&e.jsxs(W,{"data-testid":"documents-new-card",children:[e.jsx(ee,{children:e.jsxs(te,{className:"flex items-center justify-between","data-testid":"documents-new-title",children:[e.jsx("span",{children:"New Files to Upload"}),e.jsxs(X,{variant:"secondary","data-testid":"documents-new-count",children:[a.length," file",a.length!==1?"s":""]})]})}),e.jsx(K,{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(Se,{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(D,{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(D,{variant:"ghost",size:"sm",onClick:()=>h(v),"data-testid":`documents-new-${v}-remove`,children:e.jsx(ft,{className:"h-4 w-4"})})]})]},v))})})]})]})]})}const b1=t=>{switch(t){case"high":return e.jsx(ls,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(lt,{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(lt,{className:"w-4 h-4 text-gray-600"})}};function j1({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(W,{className:"border-2 border-green-200 bg-green-50/50","data-testid":"review-submit-overview-card",children:[e.jsx(ee,{children:e.jsxs(te,{className:"flex items-center gap-2 text-green-900","data-testid":"review-submit-overview-title",children:[e.jsx(bd,{className:"w-5 h-5"}),"Request Overview"]})}),e.jsxs(K,{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(Z,{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(X,{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(Z,{className:"text-green-900 font-semibold",children:"Priority"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[b1(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(Z,{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(Z,{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(W,{"data-testid":"review-submit-basic-info-card",children:[e.jsx(ee,{children:e.jsxs(te,{className:"flex items-center gap-2","data-testid":"review-submit-basic-info-title",children:[e.jsx(Se,{className:"w-5 h-5"}),"Basic Information"]})}),e.jsxs(K,{className:"space-y-4",children:[e.jsxs("div",{"data-testid":"review-submit-basic-info-description",children:[e.jsx(Z,{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(Nx,{className:"w-4 h-4 text-blue-600"}),e.jsx(Z,{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(W,{className:"border-2 border-orange-200 bg-orange-50/50","data-testid":"review-submit-approval-card",children:[e.jsxs(ee,{children:[e.jsxs(te,{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(pe,{className:"text-orange-700",children:"Sequential approval hierarchy with TAT (Turn Around Time) for each level"})]}),e.jsx(K,{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(X,{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(W,{"data-testid":"review-submit-participants-card",children:[e.jsx(ee,{children:e.jsxs(te,{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(K,{className:"space-y-4",children:t.spectators.length>0&&e.jsxs("div",{"data-testid":"review-submit-participants-spectators",children:[e.jsxs(Z,{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(X,{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(W,{"data-testid":"review-submit-documents-card",children:[e.jsxs(ee,{children:[e.jsxs(te,{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(pe,{children:[t.documents.length," document",t.documents.length!==1?"s":""," attached to this request"]})]}),e.jsx(K,{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(Se,{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(W,{className:"border-2 border-blue-200 bg-blue-50/50","data-testid":"review-submit-confirmation-card",children:e.jsx(K,{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 N1({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(D,{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(us,{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 w1({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(sn,{mode:"wait",children:t})})})}function C1({modal:t,onClose:s}){return e.jsx(et,{open:t.open,onOpenChange:a=>!a&&s(),"data-testid":"create-request-validation-modal",children:e.jsxs(Ze,{className:"sm:max-w-md",children:[e.jsxs(tt,{children:[e.jsxs(Xe,{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(Wr,{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(D,{onClick:s,className:"w-full sm:w-auto","data-testid":"validation-modal-ok-button",children:t.type==="not-found"?"Fix Email":"OK"})})]})})}function S1({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(Ze,{className:"sm:max-w-lg",children:[e.jsxs(tt,{children:[e.jsxs(Xe,{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(D,{onClick:a,className:"w-full sm:w-auto","data-testid":"document-error-modal-ok-button",children:"OK"})})]})})}function _c({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:C}=Xw(l,o,Mc),{currentStep:f,totalSteps:j,stepNames:b,isStepValid:w,nextStep:T,prevStep:R}=Qw(l,u,d),[k,F]=x.useState([]),[N,A]=x.useState([]),I=x.useRef(null),{validationModal:V,policyViolationModal:_,documentErrorModal:L,openValidationModal:S,closeValidationModal:M,closePolicyViolationModal:P,openDocumentErrorModal:E,closeDocumentErrorModal:H}=Jw(),{submitting:q,savingDraft:J,handleSubmit:B,handleSaveDraft:oe}=i1({formData:d,selectedTemplate:u,documents:k,documentsToDelete:N,user:c,isEditing:l,editRequestId:o,onSubmit:s}),{showTemplateModal:ge,setShowTemplateModal:z,previewDocument:re,selectTemplate:ye,handleTemplateSelection:G,nextStep:Q,prevStep:ie,handlePreviewDocument:Y,closePreview:ue}=c1({selectedTemplate:u,setSelectedTemplate:h,updateFormData:m,formData:d,currentStep:f,isStepValid:w,wizardNextStep:T,wizardPrevStep:R,user:c,openValidationModal:S,onSubmit:s}),Me=x.useCallback(()=>{f===1||f===3||f===4?t?t():window.history.length>1?window.history.back():i("/dashboard",{replace:!0}):ie()},[f,t,i,ie]),$e=x.useRef(!0),Ie=x.useRef(!1);x.useEffect(()=>{$e.current&&d.documents&&d.documents.length>0&&!Ie.current&&(F(d.documents),Ie.current=!0),$e.current=!1},[d.documents]);const ae=x.useRef(!1),fe=x.useRef(k);x.useEffect(()=>{if(ae.current){ae.current=!1,fe.current=k;return}fe.current!==k&&(m("documents",k),fe.current=k)},[k]);const Ve=()=>{switch(f){case 1:return e.jsx(u1,{templates:Mc,selectedTemplate:u,onSelectTemplate:ye});case 2:return e.jsx(p1,{formData:d,selectedTemplate:u,updateFormData:m});case 3:return e.jsx(f1,{formData:d,updateFormData:m,onValidationError:_e=>S(_e.type,_e.email,_e.message)});case 4:return e.jsx(y1,{formData:d,updateFormData:m,onValidationError:_e=>S(_e.type,_e.email,_e.message),initiatorEmail:(c==null?void 0:c.email)||""});case 5:return e.jsx(v1,{documentPolicy:y,isEditing:l,documents:k,existingDocuments:v,documentsToDelete:N,onDocumentsChange:F,onExistingDocumentsChange:C,onDocumentsToDeleteChange:A,onPreviewDocument:Y,onDocumentErrors:_e=>E(_e),fileInputRef:I});case 6:return e.jsx(j1,{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(N1,{isEditing:l,currentStep:f,totalSteps:j,stepNames:b,onBack:Me}),e.jsx(d1,{currentStep:f,totalSteps:j,stepNames:b}),e.jsx(w1,{children:Ve()}),e.jsx(m1,{currentStep:f,totalSteps:j,isStepValid:w(),onPrev:ie,onNext:Q,onSubmit:B,onSaveDraft:oe,submitting:q,savingDraft:J,loadingDraft:p,isEditing:l}),e.jsx(Yw,{open:ge,onClose:()=>z(!1),onSelectTemplate:G}),re&&e.jsx(Gi,{fileName:re.fileName,fileType:re.fileType,fileUrl:re.fileUrl,fileSize:re.fileSize,open:!!re,onClose:ue,onDownload:async()=>{if(re.file){const _e=document.createElement("a");_e.href=re.fileUrl,_e.download=re.fileName,document.body.appendChild(_e),_e.click(),document.body.removeChild(_e)}else re.documentId&&await oi(re.documentId)},attachmentId:re.documentId}),e.jsx(C1,{modal:V,onClose:M}),e.jsx(S1,{modal:L,documentPolicy:y,onClose:H}),e.jsx(om,{open:_.open,onClose:P,violations:_.violations,policyDetails:{maxApprovalLevels:g.maxApprovalLevels,maxParticipants:g.maxParticipants,allowSpectators:g.allowSpectators,maxSpectators:g.maxSpectators}})]})}var Ce=function(){return Ce=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},Ce.apply(this,arguments)};function A1(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 Wu(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 on(t){return t.mode==="single"}var T1={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 k1(t,s){return he(t,"LLLL y",s)}function R1(t,s){return he(t,"d",s)}function P1(t,s){return he(t,"LLLL",s)}function D1(t){return"".concat(t)}function E1(t,s){return he(t,"cccccc",s)}function M1(t,s){return he(t,"yyyy",s)}var I1=Object.freeze({__proto__:null,formatCaption:k1,formatDay:R1,formatMonthCaption:P1,formatWeekNumber:D1,formatWeekdayName:E1,formatYearCaption:M1}),F1=function(t,s,a){return he(t,"do MMMM (EEEE)",a)},_1=function(){return"Month: "},L1=function(){return"Go to next month"},O1=function(){return"Go to previous month"},$1=function(t,s){return he(t,"cccc",s)},U1=function(t){return"Week n. ".concat(t)},B1=function(){return"Year: "},V1=Object.freeze({__proto__:null,labelDay:F1,labelMonthDropdown:_1,labelNext:L1,labelPrevious:O1,labelWeekNumber:U1,labelWeekday:$1,labelYearDropdown:B1});function z1(){var t="buttons",s=T1,a=Fp,r={},n={},i=1,o={},l=new Date;return{captionLayout:t,classNames:s,formatters:I1,labels:V1,locale:a,modifiersClassNames:r,modifiers:n,numberOfMonths:i,styles:o,today:l,mode:"default"}}function H1(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=Ei(n):a&&(o=new Date(a,11,31)),{fromDate:i?Wo(i):void 0,toDate:o?Wo(o):void 0}}var Ku=x.createContext(void 0);function q1(t){var s,a=t.initialProps,r=z1(),n=H1(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;(on(a)||mr(a)||ur(a))&&(c=a.onSelect);var d=Ce(Ce(Ce({},r),a),{captionLayout:l,classNames:Ce(Ce({},r.classNames),a.classNames),components:Ce({},a.components),formatters:Ce(Ce({},r.formatters),a.formatters),fromDate:i,labels:Ce(Ce({},r.labels),a.labels),mode:a.mode||r.mode,modifiers:Ce(Ce({},r.modifiers),a.modifiers),modifiersClassNames:Ce(Ce({},r.modifiersClassNames),a.modifiersClassNames),onSelect:c,styles:Ce(Ce({},r.styles),a.styles),toDate:o});return e.jsx(Ku.Provider,{value:d,children:t.children})}function Ge(){var t=x.useContext(Ku);if(!t)throw new Error("useDayPicker must be used within a DayPickerProvider.");return t}function Gu(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 W1(t){return e.jsx("svg",Ce({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 Yu(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:W1;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 K1(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(Bp(r,n))for(var h=Yt(r),p=r.getMonth();p<=n.getMonth();p++)u.push(hn(h,p));else for(var h=Yt(new Date),p=0;p<=11;p++)u.push(hn(h,p));var g=function(v){var C=Number(v.target.value),f=hn(Yt(t.displayMonth),C);t.onChange(f)},y=(s=d==null?void 0:d.Dropdown)!==null&&s!==void 0?s:Yu;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 G1(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(Ko(Vp(new Date),y));var v=function(f){var j=Ko(Yt(a),Number(f.target.value));t.onChange(j)},C=(s=d==null?void 0:d.Dropdown)!==null&&s!==void 0?s:Yu;return e.jsx(C,{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 Y1(t,s){var a=x.useState(t),r=a[0],n=a[1],i=s===void 0?r:s;return[i,n]}function Z1(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=ms(i,d)}return o&&Wa(n,o)<0&&(n=o),Yt(n)}function X1(){var t=Ge(),s=Z1(t),a=Y1(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 Q1(t,s){for(var a=s.reverseMonths,r=s.numberOfMonths,n=Yt(t),i=Yt(ms(n,r)),o=Wa(i,n),l=[],c=0;c<o;c++){var d=ms(n,c);l.push(d)}return a&&(l=l.reverse()),l}function J1(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 ms(l,o);var c=Wa(a,t);if(!(c<i))return ms(l,o)}}function eC(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 ms(l,-o);var c=Wa(l,a);if(!(c<=0))return ms(l,-o)}}var Zu=x.createContext(void 0);function tC(t){var s=Ge(),a=X1(),r=a[0],n=a[1],i=Q1(r,s),o=J1(r,s),l=eC(r,s),c=function(u){return i.some(function(h){return Mi(u,h)})},d=function(u,h){c(u)||(h&&ld(u,h)?n(ms(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 Lc(t){var s,a=Ge(),r=a.classNames,n=a.styles,i=a.components,o=hr().goToMonth,l=function(m){o(ms(m,t.displayIndex?-t.displayIndex:0))},c=(s=i==null?void 0:i.CaptionLabel)!==null&&s!==void 0?s:Gu,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(K1,{onChange:l,displayMonth:t.displayMonth}),e.jsx(G1,{onChange:l,displayMonth:t.displayMonth})]})}function sC(t){return e.jsx("svg",Ce({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 aC(t){return e.jsx("svg",Ce({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 Ur=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=Ce(Ce({},n.button_reset),n.button);return t.style&&Object.assign(l,t.style),e.jsx("button",Ce({},t,{ref:s,type:"button",className:o,style:l}))});function rC(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:aC,C=(a=u==null?void 0:u.IconLeft)!==null&&a!==void 0?a:sC;return e.jsxs("div",{className:o.nav,style:l.nav,children:[!t.hidePrevious&&e.jsx(Ur,{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(C,{className:o.nav_icon,style:l.nav_icon})}),!t.hideNext&&e.jsx(Ur,{name:"next-month","aria-label":g,className:y,style:l.nav_button_next,disabled:!t.nextMonth,onClick:t.onNextClick,children:n==="rtl"?e.jsx(C,{className:o.nav_icon,style:l.nav_icon}):e.jsx(v,{className:o.nav_icon,style:l.nav_icon})})]})}function Oc(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 Mi(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(rC,{displayMonth:t.displayMonth,hideNext:m,hidePrevious:u,nextMonth:n,previousMonth:r,onPreviousClick:h,onNextClick:p})}function nC(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:Gu,d;return n?d=e.jsx(c,{id:t.id,displayMonth:t.displayMonth}):o==="dropdown"?d=e.jsx(Lc,{displayMonth:t.displayMonth,id:t.id}):o==="dropdown-buttons"?d=e.jsxs(e.Fragment,{children:[e.jsx(Lc,{displayMonth:t.displayMonth,displayIndex:t.displayIndex,id:t.id}),e.jsx(Oc,{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(Oc,{displayMonth:t.displayMonth,id:t.id})]}),e.jsx("div",{className:r.caption,style:i.caption,children:d})}function iC(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 oC(t,s,a){for(var r=a?Ii(new Date):Fi(new Date,{locale:t,weekStartsOn:s}),n=[],i=0;i<7;i++){var o=Wt(r,i);n.push(o)}return n}function lC(){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=oC(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 cC(){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:lC;return e.jsx("thead",{style:r.head,className:a.head,children:e.jsx(i,{})})}function dC(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 mC(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(uC,{initialProps:t.initialProps,children:t.children})}function uC(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?Wu([],r):[];if(m.selected){var C=v.findIndex(function(f){return zt(d,f)});v.splice(C,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 Do(){var t=x.useContext(Po);if(!t)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return t}function hC(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:Jn(r,t)?{from:t,to:n}:{from:r,to:t}:n?Jn(t,n)?{from:n,to:t}:{from:t,to:n}:r?ld(t,r)?{from:t,to:r}:{from:r,to:t}:{from:t,to:void 0}}var Eo=x.createContext(void 0);function pC(t){if(!ur(t.initialProps)){var s={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(Eo.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=r||{},i=n.from,o=n.to,l=s.min,c=s.max,d=function(p,g,y){var v,C;(v=s.onDayClick)===null||v===void 0||v.call(s,p,g,y);var f=hC(p,r);(C=s.onSelect)===null||C===void 0||C.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:un(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:un(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=Cs(o,i)+1,h=c-u;m.disabled.push({before:un(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(Eo.Provider,{value:{selected:r,onDayClick:d,modifiers:m},children:a})}function Mo(){var t=x.useContext(Eo);if(!t)throw new Error("useSelectRange must be used within a SelectRangeProvider");return t}function Dr(t){return Array.isArray(t)?Wu([],t):t!==void 0?[t]:[]}function gC(t){var s={};return Object.entries(t).forEach(function(a){var r=a[0],n=a[1];s[r]=Dr(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 fC=os.Selected,ws=os.Disabled,yC=os.Hidden,vC=os.Today,Vn=os.RangeEnd,zn=os.RangeMiddle,Hn=os.RangeStart,bC=os.Outside;function jC(t,s,a){var r,n=(r={},r[fC]=Dr(t.selected),r[ws]=Dr(t.disabled),r[yC]=Dr(t.hidden),r[vC]=[t.today],r[Vn]=[],r[zn]=[],r[Hn]=[],r[bC]=[],r);return t.fromDate&&n[ws].push({before:t.fromDate}),t.toDate&&n[ws].push({after:t.toDate}),mr(t)?n[ws]=n[ws].concat(s.modifiers[ws]):ur(t)&&(n[ws]=n[ws].concat(a.modifiers[ws]),n[Hn]=a.modifiers[Hn],n[zn]=a.modifiers[zn],n[Vn]=a.modifiers[Vn]),n}var Xu=x.createContext(void 0);function NC(t){var s=Ge(),a=Do(),r=Mo(),n=jC(s,a,r),i=gC(s.modifiers),o=Ce(Ce({},n),i);return e.jsx(Xu.Provider,{value:o,children:t.children})}function Qu(){var t=x.useContext(Xu);if(!t)throw new Error("useModifiers must be used within a ModifiersProvider");return t}function wC(t){return!!(t&&typeof t=="object"&&"before"in t&&"after"in t)}function CC(t){return!!(t&&typeof t=="object"&&"from"in t)}function SC(t){return!!(t&&typeof t=="object"&&"after"in t)}function AC(t){return!!(t&&typeof t=="object"&&"before"in t)}function TC(t){return!!(t&&typeof t=="object"&&"dayOfWeek"in t)}function kC(t,s){var a,r=s.from,n=s.to;if(r&&n){var i=Cs(n,r)<0;i&&(a=[n,r],r=a[0],n=a[1]);var o=Cs(t,r)>=0&&Cs(n,t)>=0;return o}return n?zt(n,t):r?zt(r,t):!1}function RC(t){return md(t)}function PC(t){return Array.isArray(t)&&t.every(md)}function DC(t,s){return s.some(function(a){if(typeof a=="boolean")return a;if(RC(a))return zt(t,a);if(PC(a))return a.includes(t);if(CC(a))return kC(t,a);if(TC(a))return a.dayOfWeek.includes(t.getDay());if(wC(a)){var r=Cs(a.before,t),n=Cs(a.after,t),i=r>0,o=n<0,l=Jn(a.before,a.after);return l?o&&i:i||o}return SC(a)?Cs(t,a.after)>0:AC(a)?Cs(a.before,t)>0:typeof a=="function"?a(t):!1})}function Io(t,s,a){var r=Object.keys(s).reduce(function(i,o){var l=s[o];return DC(t,l)&&i.push(o),i},[]),n={};return r.forEach(function(i){return n[i]=!0}),a&&!Mi(t,a)&&(n.outside=!0),n}function EC(t,s){for(var a=Yt(t[0]),r=Ei(t[t.length-1]),n,i,o=a;o<=r;){var l=Io(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 MC=365;function Ju(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:Qn,month:ms,year:Op,startOfWeek:function(v){return n.ISOWeek?Ii(v):Fi(v,{locale:u,weekStartsOn:c})},endOfWeek:function(v){return n.ISOWeek?cd(v):dd(v,{locale:u,weekStartsOn:c})}},p=h[a](t,r==="after"?1:-1);r==="before"&&d?p=$p([d,p]):r==="after"&&m&&(p=Up([m,p]));var g=!0;if(i){var y=Io(p,i);g=!y.disabled&&!y.hidden}return g?p:l.count>MC?l.lastFocused:Ju(p,{moveBy:a,direction:r,context:n,modifiers:i,retry:Ce(Ce({},l),{count:l.count+1})})}var eh=x.createContext(void 0);function IC(t){var s=hr(),a=Qu(),r=x.useState(),n=r[0],i=r[1],o=x.useState(),l=o[0],c=o[1],d=EC(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,C){if(n){var f=Ju(n,{moveBy:v,direction:C,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(eh.Provider,{value:y,children:t.children})}function Fo(){var t=x.useContext(eh);if(!t)throw new Error("useFocusContext must be used within a FocusProvider");return t}function FC(t,s){var a=Qu(),r=Io(t,a,s);return r}var _o=x.createContext(void 0);function _C(t){if(!on(t.initialProps)){var s={selected:void 0};return e.jsx(_o.Provider,{value:s,children:t.children})}return e.jsx(LC,{initialProps:t.initialProps,children:t.children})}function LC(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(_o.Provider,{value:n,children:a})}function th(){var t=x.useContext(_o);if(!t)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return t}function OC(t,s){var a=Ge(),r=th(),n=Do(),i=Mo(),o=Fo(),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,C=o.focusStartOfWeek,f=o.focusEndOfWeek,j=function(M){var P,E,H,q;on(a)?(P=r.onDayClick)===null||P===void 0||P.call(r,t,s,M):mr(a)?(E=n.onDayClick)===null||E===void 0||E.call(n,t,s,M):ur(a)?(H=i.onDayClick)===null||H===void 0||H.call(i,t,s,M):(q=a.onDayClick)===null||q===void 0||q.call(a,t,s,M)},b=function(M){var P;h(t),(P=a.onDayFocus)===null||P===void 0||P.call(a,t,s,M)},w=function(M){var P;u(),(P=a.onDayBlur)===null||P===void 0||P.call(a,t,s,M)},T=function(M){var P;(P=a.onDayMouseEnter)===null||P===void 0||P.call(a,t,s,M)},R=function(M){var P;(P=a.onDayMouseLeave)===null||P===void 0||P.call(a,t,s,M)},k=function(M){var P;(P=a.onDayPointerEnter)===null||P===void 0||P.call(a,t,s,M)},F=function(M){var P;(P=a.onDayPointerLeave)===null||P===void 0||P.call(a,t,s,M)},N=function(M){var P;(P=a.onDayTouchCancel)===null||P===void 0||P.call(a,t,s,M)},A=function(M){var P;(P=a.onDayTouchEnd)===null||P===void 0||P.call(a,t,s,M)},I=function(M){var P;(P=a.onDayTouchMove)===null||P===void 0||P.call(a,t,s,M)},V=function(M){var P;(P=a.onDayTouchStart)===null||P===void 0||P.call(a,t,s,M)},_=function(M){var P;(P=a.onDayKeyUp)===null||P===void 0||P.call(a,t,s,M)},L=function(M){var P;switch(M.key){case"ArrowLeft":M.preventDefault(),M.stopPropagation(),a.dir==="rtl"?l():c();break;case"ArrowRight":M.preventDefault(),M.stopPropagation(),a.dir==="rtl"?c():l();break;case"ArrowDown":M.preventDefault(),M.stopPropagation(),d();break;case"ArrowUp":M.preventDefault(),M.stopPropagation(),m();break;case"PageUp":M.preventDefault(),M.stopPropagation(),M.shiftKey?y():p();break;case"PageDown":M.preventDefault(),M.stopPropagation(),M.shiftKey?v():g();break;case"Home":M.preventDefault(),M.stopPropagation(),C();break;case"End":M.preventDefault(),M.stopPropagation(),f();break}(P=a.onDayKeyDown)===null||P===void 0||P.call(a,t,s,M)},S={onClick:j,onFocus:b,onBlur:w,onKeyDown:L,onKeyUp:_,onMouseEnter:T,onMouseLeave:R,onPointerEnter:k,onPointerLeave:F,onTouchCancel:N,onTouchEnd:A,onTouchMove:I,onTouchStart:V};return S}function $C(){var t=Ge(),s=th(),a=Do(),r=Mo(),n=on(t)?s.selected:mr(t)?a.selected:ur(t)?r.selected:void 0;return n}function UC(t){return Object.values(os).includes(t)}function BC(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(UC(r)){var i=t.classNames["day_".concat(r)];i&&a.push(i)}}),a}function VC(t,s){var a=Ce({},t.styles.day);return Object.keys(s).forEach(function(r){var n;a=Ce(Ce({},a),(n=t.modifiersStyles)===null||n===void 0?void 0:n[r])}),a}function zC(t,s,a){var r,n,i,o=Ge(),l=Fo(),c=FC(t,s),d=OC(t,c),m=$C(),u=!!(o.onDayClick||o.mode!=="default");x.useEffect(function(){var T;c.outside||l.focusedDay&&u&&zt(l.focusedDay,t)&&((T=a.current)===null||T===void 0||T.focus())},[l.focusedDay,t,a,u,c.outside]);var h=BC(o,c).join(" "),p=VC(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:dC,v=e.jsx(y,{date:t,displayMonth:s,activeModifiers:c}),C={style:p,className:h,children:v,role:"gridcell"},f=l.focusTarget&&zt(l.focusTarget,t)&&!c.outside,j=l.focusedDay&&zt(l.focusedDay,t),b=Ce(Ce(Ce({},C),(r={disabled:c.disabled,role:"gridcell"},r["aria-selected"]=c.selected,r.tabIndex=j||f?0:-1,r)),d),w={isButton:u,isHidden:g,activeModifiers:c,selectedDays:m,buttonProps:b,divProps:C};return w}function HC(t){var s=x.useRef(null),a=zC(t.date,t.displayMonth,s);return a.isHidden?e.jsx("div",{role:"gridcell"}):a.isButton?e.jsx(Ur,Ce({name:"day",ref:s},a.buttonProps)):e.jsx("div",Ce({},a.divProps))}function qC(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(Ur,{name:"week-number","aria-label":u,className:o.weeknumber,style:i.weeknumber,onClick:h,children:m})}function WC(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:HC,d=(a=l==null?void 0:l.WeekNumber)!==null&&a!==void 0?a:qC,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})},Lp(u))})]})}function $c(t,s,a){for(var r=a!=null&&a.ISOWeek?cd(s):dd(s,a),n=a!=null&&a.ISOWeek?Ii(t):Fi(t,a),i=Cs(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?zp(m):Hp(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 KC(t,s){var a=$c(Yt(t),Ei(t),s);if(s!=null&&s.useFixedWeeks){var r=_p(t,s);if(r<6){var n=a[a.length-1],i=n.dates[n.dates.length-1],o=Qn(i,6-r),l=$c(Qn(i,1),o,s);a.push.apply(a,l)}}return a}function GC(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=KC(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:cC,v=(a=m==null?void 0:m.Row)!==null&&a!==void 0?a:WC,C=(r=m==null?void 0:m.Footer)!==null&&r!==void 0?r:iC;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(C,{displayMonth:t.displayMonth})]})}function YC(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var ZC=YC()?x.useLayoutEffect:x.useEffect,qn=!1,XC=0;function Uc(){return"react-day-picker-".concat(++XC)}function QC(t){var s,a=t??(qn?Uc():null),r=x.useState(a),n=r[0],i=r[1];return ZC(function(){n===null&&i(Uc())},[]),x.useEffect(function(){qn===!1&&(qn=!0)},[]),(s=t??n)!==null&&s!==void 0?s:void 0}function JC(t){var s,a,r=Ge(),n=r.dir,i=r.classNames,o=r.styles,l=r.components,c=hr().displayMonths,d=QC(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=Ce(Ce({},h),o.caption_start)),g&&(u.push(i.caption_end),h=Ce(Ce({},h),o.caption_end)),y&&(u.push(i.caption_between),h=Ce(Ce({},h),o.caption_between));var v=(a=l==null?void 0:l.Caption)!==null&&a!==void 0?a:nC;return e.jsxs("div",{className:u.join(" "),style:h,children:[e.jsx(v,{id:d,displayMonth:t.displayMonth,displayIndex:t.displayIndex}),e.jsx(GC,{id:m,"aria-labelledby":d,displayMonth:t.displayMonth})]},t.displayIndex)}function e2(t){var s=Ge(),a=s.classNames,r=s.styles;return e.jsx("div",{className:a.months,style:r.months,children:t.children})}function t2(t){var s,a,r=t.initialProps,n=Ge(),i=Fo(),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=Ce(Ce({},n.styles.root),n.style),h=Object.keys(r).filter(function(g){return g.startsWith("data-")}).reduce(function(g,y){var v;return Ce(Ce({},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:e2;return e.jsx("div",Ce({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(JC,{displayIndex:y,displayMonth:g},y)})})}))}function s2(t){var s=t.children,a=A1(t,["children"]);return e.jsx(q1,{initialProps:a,children:e.jsx(tC,{children:e.jsx(_C,{initialProps:a,children:e.jsx(mC,{initialProps:a,children:e.jsx(pC,{initialProps:a,children:e.jsx(NC,{children:e.jsx(IC,{children:s})})})})})})})}function a2(t){return e.jsx(s2,Ce({},t,{children:e.jsx(t2,{initialProps:t})}))}function Wn({className:t,classNames:s,showOutsideDays:a=!0,...r}){return e.jsx(a2,{showOutsideDays:a,className:le("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:le(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:le("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:le(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(jd,{className:le("size-4",n),...i}),IconRight:({className:n,...i})=>e.jsx($i,{className:le("size-4",n),...i})},...r})}const sh={"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 r2(t){return sh[t]||null}function n2(){return Object.values(sh)}function i2(t){return`${t.address}, ${t.city}, ${t.state}`}const o2=["Marketing Activity","Promotional Event","Dealer Training","Infrastructure Development","Customer Experience Initiative","Service Campaign"],l2=n2(),Kn=["Claim Details","Review & Submit"];function c2({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=Kn.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=r2(g);y&&(l("dealerCode",y.code),l("dealerName",y.name),l("dealerEmail",y.email),l("dealerPhone",y.phone),l("dealerAddress",i2(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(si,{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(Z,{htmlFor:"activityName",className:"text-base font-semibold",children:"Activity Name *"}),e.jsx(xe,{id:"activityName",placeholder:"e.g., Himalayan Adventure Fest 2024",value:n.activityName,onChange:g=>l("activityName",g.target.value),className:"mt-2 h-12"})]}),e.jsxs("div",{children:[e.jsx(Z,{htmlFor:"activityType",className:"text-base font-semibold",children:"Activity Type *"}),e.jsxs(Ae,{value:n.activityType,onValueChange:g=>l("activityType",g),children:[e.jsx(ke,{className:"mt-2 h-12",children:e.jsx(Te,{placeholder:"Select activity type"})}),e.jsx(Re,{children:o2.map(g=>e.jsx(O,{value:g,children:g},g))})]})]})]}),e.jsxs("div",{children:[e.jsx(Z,{htmlFor:"dealer",className:"text-base font-semibold",children:"Dealer Code / Dealer Name *"}),e.jsxs(Ae,{value:n.dealerCode,onValueChange:u,children:[e.jsx(ke,{className:"mt-2 h-12",children:e.jsx(Te,{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(Re,{children:l2.map(g=>e.jsx(O,{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(Z,{className:"text-base font-semibold",children:"Date *"}),e.jsxs(Es,{children:[e.jsx(Ms,{asChild:!0,children:e.jsxs(D,{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?he(n.activityDate,"PPP"):"Select date"]})}),e.jsx(Is,{className:"w-auto p-0",align:"start",children:e.jsx(Wn,{mode:"single",selected:n.activityDate,onSelect:g=>l("activityDate",g),initialFocus:!0})})]})]}),e.jsxs("div",{children:[e.jsx(Z,{htmlFor:"location",className:"text-base font-semibold",children:"Location *"}),e.jsx(xe,{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(Z,{htmlFor:"requestDescription",className:"text-base font-semibold",children:"Request in Detail - Brief Requirement *"}),e.jsx(fs,{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(Z,{className:"text-base font-semibold",children:"Period (If Any)"}),e.jsx(X,{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(Z,{className:"text-sm text-gray-600",children:"Start Date"}),e.jsxs(Es,{children:[e.jsx(Ms,{asChild:!0,children:e.jsxs(D,{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?he(n.periodStartDate,"PPP"):"Start date"]})}),e.jsx(Is,{className:"w-auto p-0",align:"start",children:e.jsx(Wn,{mode:"single",selected:n.periodStartDate,onSelect:g=>l("periodStartDate",g),initialFocus:!0})})]})]}),e.jsxs("div",{children:[e.jsx(Z,{className:"text-sm text-gray-600",children:"End Date"}),e.jsxs(Es,{children:[e.jsx(Ms,{asChild:!0,children:e.jsxs(D,{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?he(n.periodEndDate,"PPP"):"End date"]})}),e.jsx(Is,{className:"w-auto p-0",align:"start",children:e.jsx(Wn,{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: ${he(n.periodStartDate,"MMM dd, yyyy")} - ${he(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(W,{className:"border-2",children:[e.jsx(ee,{className:"bg-gradient-to-br from-blue-50 to-indigo-50",children:e.jsxs(te,{className:"flex items-center gap-2",children:[e.jsx(si,{className:"w-5 h-5 text-blue-600"}),"Activity Information"]})}),e.jsx(K,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(Z,{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(Z,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Type"}),e.jsx(X,{variant:"secondary",className:"mt-1",children:n.activityType})]})]})})]}),e.jsxs(W,{className:"border-2",children:[e.jsx(ee,{className:"bg-gradient-to-br from-green-50 to-emerald-50",children:e.jsxs(te,{className:"flex items-center gap-2",children:[e.jsx(wx,{className:"w-5 h-5 text-green-600"}),"Dealer Information"]})}),e.jsx(K,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(Z,{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(Z,{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(Z,{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(Z,{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(Z,{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(W,{className:"border-2",children:[e.jsx(ee,{className:"bg-gradient-to-br from-purple-50 to-pink-50",children:e.jsxs(te,{className:"flex items-center gap-2",children:[e.jsx(We,{className:"w-5 h-5 text-purple-600"}),"Date & Location"]})}),e.jsx(K,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(Z,{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?he(n.activityDate,"PPP"):"N/A"})]}),e.jsxs("div",{children:[e.jsx(Z,{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(Cx,{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(Z,{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(W,{className:"border-2",children:[e.jsx(ee,{className:"bg-gradient-to-br from-orange-50 to-amber-50",children:e.jsxs(te,{className:"flex items-center gap-2",children:[e.jsx(Se,{className:"w-5 h-5 text-orange-600"}),"Request Details"]})}),e.jsx(K,{className:"pt-6 space-y-4",children:e.jsxs("div",{children:[e.jsx(Z,{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(W,{className:"border-2",children:[e.jsx(ee,{className:"bg-gradient-to-br from-cyan-50 to-blue-50",children:e.jsxs(te,{className:"flex items-center gap-2",children:[e.jsx(Ee,{className:"w-5 h-5 text-cyan-600"}),"Period"]})}),e.jsx(K,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(Z,{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?he(n.periodStartDate,"PPP"):"Not specified"})]}),e.jsxs("div",{children:[e.jsx(Z,{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?he(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(D,{variant:"ghost",onClick:t,className:"mb-3 sm:mb-4 gap-2 text-sm sm:text-base",children:[e.jsx(us,{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(X,{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:Kn[a-1]})]})]})}),e.jsxs("div",{className:"mt-4 sm:mt-6",children:[e.jsx(hs,{value:a/o*100,className:"h-2"}),e.jsx("div",{className:"flex justify-between mt-2 px-1",children:Kn.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(W,{className:"mb-6 sm:mb-8",children:e.jsx(K,{className:"p-4 sm:p-6 lg:p-8",children:e.jsx(sn,{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(D,{variant:"outline",onClick:m,disabled:a===1,className:"gap-2 w-full sm:w-auto order-2 sm:order-1",children:[e.jsx(us,{className:"w-4 h-4"}),"Previous"]}),a<o?e.jsxs(D,{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(D,{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 ah({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(X,{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(W,{className:`${n} border transition-shadow ${c?"cursor-pointer hover:shadow-lg":"hover:shadow-md"}`,"data-testid":l,onClick:c,children:e.jsx(K,{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 d2({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:Se,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:Ee,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:Gr,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:Yr,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 m2({searchTerm:t,statusFilter:s,priorityFilter:a,onSearchChange:r,onStatusChange:n,onPriorityChange:i}){return e.jsx(W,{className:"border-gray-200","data-testid":"my-requests-filters",children:e.jsx(K,{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(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx(xe,{placeholder:"Search requests by title, description, or ID...",value:t,onChange:o=>r(o.target.value),className:"pl-9 text-sm sm:text-base bg-white border-gray-300 hover:border-gray-400 focus:border-blue-400 focus:ring-1 focus:ring-blue-200 h-9 sm:h-10","data-testid":"search-input"})]}),e.jsxs("div",{className:"flex gap-2 sm:gap-3 w-full md:w-auto",children:[e.jsxs(Ae,{value:s,onValueChange:n,children:[e.jsx(ke,{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(Te,{placeholder:"Status"})}),e.jsxs(Re,{children:[e.jsx(O,{value:"all",children:"All Status"}),e.jsx(O,{value:"draft",children:"Draft"}),e.jsx(O,{value:"pending",children:"Pending"}),e.jsx(O,{value:"paused",children:"Paused"}),e.jsx(O,{value:"approved",children:"Approved"}),e.jsx(O,{value:"rejected",children:"Rejected"}),e.jsx(O,{value:"closed",children:"Closed"})]})]}),e.jsxs(Ae,{value:a,onValueChange:i,children:[e.jsx(ke,{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(Te,{placeholder:"Priority"})}),e.jsxs(Re,{children:[e.jsx(O,{value:"all",children:"All Priority"}),e.jsx(O,{value:"express",children:"Express"}),e.jsx(O,{value:"standard",children:"Standard"})]})]})]})]})})})}function u2(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:lt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:lt,iconColor:"text-gray-600"}}}function h2(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:Ee,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:Gr,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Pe,iconColor:"text-gray-600"}}}const p2=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 x2({request:t,index:s,onViewRequest:a}){var l;const r=h2(t.status),n=u2(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(W,{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(K,{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(X,{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(X,{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(X,{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(X,{variant:"secondary",className:"bg-purple-100 text-purple-700 text-xs shrink-0 hidden sm:inline-flex","data-testid":"template-badge",children:[e.jsx(Se,{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:p2(t.description||"")||"No description provided"}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-1 sm:gap-4 text-xs sm:text-sm text-gray-500",children:[e.jsxs("span",{className:"truncate","data-testid":"request-id-display",children:[e.jsx("span",{className:"font-medium",children:"ID:"})," ",t.displayId||t.id]}),e.jsxs("span",{className:"truncate","data-testid":"submitted-date",children:[e.jsx("span",{className:"font-medium",children:"Submitted:"})," ",ps(t.submittedDate)]})]})]}),e.jsx(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(Ee,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{"data-testid":"submitted-timestamp",children:["Submitted: ",ps(t.submittedDate)]})]})]})]})})})})}function g2({requests:t,loading:s,searchTerm:a,statusFilter:r,priorityFilter:n,onViewRequest:i}){if(s)return e.jsx(W,{"data-testid":"loading-state",children:e.jsx(K,{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(W,{"data-testid":"empty-state",children:e.jsxs(K,{className:"p-12 text-center",children:[e.jsx(Se,{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(x2,{request:o,index:l,onViewRequest:i},o.id))})}function f2(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 rh(t){return Array.isArray(t)?t.map(f2):[]}function y2({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=rh(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 v2={searchTerm:"",statusFilter:"all",priorityFilter:"all",currentPage:1},nh=Ta({name:"myRequests",initialState:v2,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:b2,setStatusFilter:j2,setPriorityFilter:N2,setCurrentPage:w2,clearFilters:C2}=nh.actions;function S2({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(b2(y)),[a]),m=x.useCallback(y=>a(j2(y)),[a]),u=x.useCallback(y=>a(N2(y)),[a]),h=x.useCallback(y=>a(w2(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(C2())},[a]);return{searchTerm:i,statusFilter:o,priorityFilter:l,currentPage:c,setSearchTerm:d,setStatusFilter:m,setPriorityFilter:u,setCurrentPage:h,getFilters:p,resetFilters:g}}function A2({onViewRequest:t,dynamicRequests:s=[]}){const{user:a}=Mt(),r=y2({itemsPerPage:10}),n=x.useRef(r.fetchMyRequests);n.current=r.fetchMyRequests;const i=S2(),o=x.useRef({searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter}),l=x.useRef(!1);x.useEffect(()=>{const C=i.currentPage||1;n.current(C,{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 C=o.current;if(!(C.searchTerm!==i.searchTerm||C.statusFilter!==i.statusFilter||C.priorityFilter!==i.priorityFilter))return;const j=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!==C.searchTerm?500:0);return()=>clearTimeout(j)},[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 C=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:C.totalRequests||0,pending:C.openRequests||0,paused:C.pausedRequests||0,approved:C.approvedRequests||0,rejected:C.rejectedRequests||0,draft:C.draftRequests||0,closed:C.closedRequests||0})}catch(C){console.error("Failed to fetch backend stats:",C),d(null)}finally{u(!1)}},[a==null?void 0:a.userId,i.searchTerm,i.priorityFilter]);x.useEffect(()=>{const C=setTimeout(()=>{h()},i.searchTerm?500:0);return()=>clearTimeout(C)},[i.searchTerm,i.priorityFilter,h]);const p=rh(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(C=>{C>=1&&C<=r.pagination.totalPages&&(i.setCurrentPage(C),r.fetchMyRequests(C,{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(ah,{icon:Se,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(d2,{stats:y,onStatusFilter:C=>{i.setStatusFilter(C)}}),e.jsx(m2,{searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,onSearchChange:i.setSearchTerm,onStatusChange:i.setStatusFilter,onPriorityChange:i.setPriorityFilter}),e.jsx(g2,{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 ih({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(ah,{icon:Se,title:i(),description:o(),testId:"requests-header"}),e.jsx(X,{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(D,{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 oh({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:Se,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:Ee,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:Yr,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 T2=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:lt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:lt,iconColor:"text-gray-600"}}},k2=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:Ee,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:Gr,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Pe,iconColor:"text-gray-600"}}},R2=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 P2({request:t,index:s,onViewRequest:a}){var l;const r=k2(t.status),n=T2(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(W,{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(K,{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(X,{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(X,{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(X,{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(X,{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:R2(t.description||"")||"No description provided"}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-1 sm:gap-4 text-xs sm:text-sm text-gray-500",children:[e.jsxs("span",{className:"truncate","data-testid":"request-id-display",children:[e.jsx("span",{className:"font-medium",children:"ID:"})," ",t.displayId||t.id]}),e.jsxs("span",{className:"truncate","data-testid":"submitted-date",children:[e.jsx("span",{className:"font-medium",children:"Submitted:"})," ",ps(t.submittedDate)]})]})]}),e.jsx(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(Ee,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{"data-testid":"submitted-timestamp",children:["Submitted: ",ps(t.submittedDate)]})]})]})]})})})})}function lh({requests:t,loading:s,hasActiveFilters:a,onViewRequest:r}){return s?e.jsx(W,{"data-testid":"loading-state",children:e.jsx(K,{className:"p-6 text-sm text-gray-600",children:"Loading requests…"})}):t.length===0?e.jsx(W,{"data-testid":"empty-state",children:e.jsxs(K,{className:"p-12 text-center",children:[e.jsx(Se,{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(P2,{request:n,index:i,onViewRequest:r},n.id))})}const D2={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},ch=Ta({name:"requests",initialState:D2,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:E2,setStatusFilter:M2,setPriorityFilter:I2,setSlaComplianceFilter:F2,setDepartmentFilter:_2,setInitiatorFilter:L2,setApproverFilter:O2,setApproverFilterType:$2,setDateRange:Bc,setCustomStartDate:Gn,setCustomEndDate:Yn,setShowCustomDatePicker:wr,setCurrentPage:U2,clearFilters:B2}=ch.actions;function dh(){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(S=>S.requests),g=x.useCallback(S=>t(E2(S)),[t]),y=x.useCallback(S=>t(M2(S)),[t]),v=x.useCallback(S=>t(I2(S)),[t]),C=x.useCallback(S=>t(F2(S)),[t]),f=x.useCallback(S=>t(_2(S)),[t]),j=x.useCallback(S=>t(L2(S)),[t]),b=x.useCallback(S=>t(O2(S)),[t]),w=x.useCallback(S=>t($2(S)),[t]),T=x.useCallback(S=>t(Bc(S)),[t]),R=x.useCallback(S=>t(Gn(S)),[t]),k=x.useCallback(S=>t(Yn(S)),[t]),F=x.useCallback(S=>t(wr(S)),[t]),N=x.useCallback(S=>t(U2(S)),[t]),A=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]),I=x.useCallback(()=>{t(B2())},[t]),V=x.useCallback(S=>{const M=S;t(Bc(M)),M!=="custom"?(t(Gn(void 0)),t(Yn(void 0)),t(wr(!1))):t(wr(!0))},[t]),_=x.useCallback(()=>{m&&u&&(m>u&&(t(Gn(u)),t(Yn(m))),t(wr(!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:C,setDepartmentFilter:f,setInitiatorFilter:j,setApproverFilter:b,setApproverFilterType:w,setDateRange:T,setCustomStartDate:R,setCustomEndDate:k,setShowCustomDatePicker:F,setCurrentPage:N,getFilters:A,clearFilters:I,handleDateRangeChange:V,handleApplyCustomDate:_}}function Br({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(),C=t.filter(f=>{const j=(f.email||"").toLowerCase(),b=(f.displayName||"").toLowerCase();return j.includes(v)||b.includes(v)});o(C.slice(0,10)),c(C.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 V2(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(C=>{const f=(C.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((j,b)=>{const w=j.levelNumber||j.level_number||0;return(b.levelNumber||b.level_number||0)-w})[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(C=>{const f=(C.status||"").toString().toUpperCase();return f==="PENDING"||f==="IN_PROGRESS"});if(v){const C=v.levelNumber||v.level_number||0,f=c||t.approvals.length;i=`${C} 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 mh(t){return Array.isArray(t)?t.map(V2):[]}function z2(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 uh={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(Vr,function(){return function(a,r){r.prototype.isSameOrBefore=function(n,i){return this.isSame(n,i)||this.isBefore(n,i)}}})})(uh);var H2=uh.exports;const hh=zr(H2);var ph={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(Vr,function(){return function(a,r){r.prototype.isSameOrAfter=function(n,i){return this.isSame(n,i)||this.isAfter(n,i)}}})})(ph);var q2=ph.exports;const xh=zr(q2);st.extend(xh);st.extend(hh);function W2(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,C,f,j;const n=s.slaCompliance||"";if(n.toLowerCase()==="compliant"){const b=(r.status||"").toString().toUpperCase();if(!(b==="APPROVED"||b==="REJECTED"||b==="CLOSED"))return!1;const T=((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 T?T!=="breached"&&T.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)||((C=r.sla)==null?void 0:C.status)||((j=(f=r.summary)==null?void 0:f.sla)==null?void 0:j.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(hh);st.extend(xh);function K2(t){if(!t)return"N/A";try{const s=typeof t=="string"?new Date(t):t;return he(s,"yyyy-MM-dd HH:mm:ss")}catch{return"N/A"}}async function gh(t,s){const a=W2(t,s),r=[["Request Number","Title","Status","Priority","Initiator","Department","Current Approver","Approval Level","Submitted Date","Description"].join(",")];a.forEach(c=>{var f,j,b,w,T;const d=(c.status||"").toString().toLowerCase().replace("_","-"),m=(c.priority||"").toString().toLowerCase(),u=((f=c.initiator)==null?void 0:f.displayName)||((j=c.initiator)==null?void 0:j.email)||c.initiatorName||"N/A",h=c.department||((b=c.initiator)==null?void 0:b.department)||"N/A",p=((w=c.currentApprover)==null?void 0:w.displayName)||((T=c.currentApprover)==null?void 0:T.email)||c.currentApproverName||"N/A",g=c.currentApproverLevel||c.approvalLevel||c.currentLevel||"N/A",y=K2(c.submittedAt||c.createdAt||c.submitted_at||c.created_at),v=(c.description||"").replace(/"/g,'""').replace(/\n/g," ").replace(/\r/g,""),C=[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(C.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 G2({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 Y2(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 Z2({onViewRequest:t}){const{user:s}=Mt(),a=Ra(B=>B.dashboard.viewAsUser),r=x.useMemo(()=>Zr(s),[s]),n=x.useMemo(()=>r&&!a,[r,a]),i=dh(),[o,l]=x.useState([]),[c,d]=x.useState(!1),[m,u]=x.useState(!1),[h,p]=x.useState(null),[g,y]=x.useState([]),[v,C]=x.useState(!1),[f,j]=x.useState([]),[b,w]=x.useState(1),[T,R]=x.useState(0),[k]=x.useState(10),F=Br({allUsers:f,filterValue:i.initiatorFilter,onFilterChange:i.setInitiatorFilter}),N=Br({allUsers:f,filterValue:i.approverFilter,onFilterChange:i.setApproverFilter}),A=x.useCallback(async(B,oe,ge,z)=>{try{const re=z==null?void 0:z.slaCompliance;if(re&&re!=="all"&&re!=="breached"&&re!=="compliant"){const G={};z!=null&&z.search&&(G.search=z.search),z!=null&&z.priority&&z.priority!=="all"&&(G.priority=z.priority),z!=null&&z.department&&z.department!=="all"&&(G.department=z.department),z!=null&&z.initiator&&z.initiator!=="all"&&(G.initiator=z.initiator),z!=null&&z.approver&&z.approver!=="all"&&(G.approver=z.approver,G.approverType=z.approverType||"current"),G.slaCompliance=re,B&&(G.dateRange=B),oe&&(G.startDate=oe.toISOString()),ge&&(G.endDate=ge.toISOString());const Q=n?await Ot.listWorkflows({page:1,limit:1e3,...G}):await Ot.listParticipantRequests({page:1,limit:1e3,...G}),ie=Array.isArray(Q==null?void 0:Q.data)?Q.data:[],Y=ie.length,ue=ie.filter(ae=>{const fe=(ae.status||"").toString().toUpperCase();return fe==="PENDING"||fe==="IN_PROGRESS"}).length,Me=ie.filter(ae=>(ae.status||"").toString().toUpperCase()==="APPROVED").length,$e=ie.filter(ae=>(ae.status||"").toString().toUpperCase()==="REJECTED").length,Ie=ie.filter(ae=>(ae.status||"").toString().toUpperCase()==="CLOSED").length;p({total:Y,pending:ue,paused:0,approved:Me,rejected:$e,draft:0,closed:Ie})}else{const G=await He.getRequestStats(B,oe?oe.toISOString():void 0,ge?ge.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,!n);p({total:G.totalRequests||0,pending:G.openRequests||0,paused:G.pausedRequests||0,approved:G.approvedRequests||0,rejected:G.rejectedRequests||0,draft:G.draftRequests||0,closed:G.closedRequests||0})}}catch(re){console.error("Failed to fetch backend stats:",re)}finally{}},[n]),I=x.useCallback(async()=>{try{C(!0);const B=await He.getDepartments();y(B)}catch{}finally{C(!1)}},[]),V=x.useCallback(async()=>{try{const oe=(await Gt.getAllUsers()).map(ge=>({userId:ge.userId,email:ge.email,displayName:ge.displayName||ge.email}));j(oe)}catch(B){console.error("Failed to fetch users:",B)}},[]),_=x.useRef(i),L=x.useRef(A);x.useEffect(()=>{_.current=i,L.current=A},[i,A]);const S=x.useCallback(async(B=1)=>{try{B===1&&(d(!0),l([]));const oe=_.current.getFilters(),ge=await G2({page:B,itemsPerPage:k,filters:oe,isOrgLevel:n});l(ge.data),i.setCurrentPage(ge.pagination.page),w(ge.pagination.totalPages),R(ge.pagination.total)}catch{l([])}finally{d(!1)}},[k,n]),M=x.useCallback(async()=>{try{u(!0);const B=await Y2(n);await gh(B,i.getFilters())}catch(B){console.error("Failed to export requests:",B),alert("Failed to export requests. Please try again.")}finally{u(!1)}},[n,i]);x.useEffect(()=>{I(),V()},[I,V]),x.useEffect(()=>{const B=setTimeout(()=>{const oe={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},ge=i.dateRange||"all";L.current(ge,i.customStartDate,i.customEndDate,oe)},i.searchTerm?500:0);return()=>clearTimeout(B)},[n,i.dateRange,i.customStartDate,i.customEndDate,i.priorityFilter,i.departmentFilter,i.initiatorFilter,i.approverFilter,i.approverFilterType,i.searchTerm,i.slaComplianceFilter]);const P=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}),E=x.useRef(!1);x.useEffect(()=>{const B=i.currentPage||1;S(B),E.current=!0},[]),x.useEffect(()=>{if(!E.current)return;const B=P.current;if(!(B.searchTerm!==i.searchTerm||B.statusFilter!==i.statusFilter||B.priorityFilter!==i.priorityFilter||B.slaComplianceFilter!==i.slaComplianceFilter||B.departmentFilter!==i.departmentFilter||B.initiatorFilter!==i.initiatorFilter||B.approverFilter!==i.approverFilter||B.approverFilterType!==i.approverFilterType||B.dateRange!==i.dateRange||B.customStartDate!==i.customStartDate||B.customEndDate!==i.customEndDate||B.isOrgLevel!==n))return;const ge=setTimeout(()=>{i.setCurrentPage(1),S(1),P.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!==B.searchTerm?500:0);return()=>clearTimeout(ge)},[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(B=>{B>=1&&B<=b&&(i.setCurrentPage(B),S(B))},[b,S,i]),q=x.useMemo(()=>mh(o),[o]),J=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}:z2([],n,h,!1,T,q),[n,h,T,q]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"requests-page",children:[e.jsx(ih,{isOrgLevel:n,isAdmin:r,loading:c,exporting:m,onExport:M}),e.jsx(oh,{stats:J,onStatusFilter:B=>{i.setStatusFilter(B)}}),e.jsx(W,{className:"border-gray-200 shadow-md","data-testid":"requests-filters",children:e.jsx(K,{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(X,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),i.hasActiveFilters&&e.jsxs(D,{variant:"ghost",size:"sm",onClick:i.clearFilters,className:"gap-2",children:[e.jsx(Et,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(ct,{}),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(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(xe,{placeholder:"Search requests...",value:i.searchTerm,onChange:B=>i.setSearchTerm(B.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(Ae,{value:i.statusFilter,onValueChange:i.setStatusFilter,children:[e.jsx(ke,{className:"h-10","data-testid":"status-filter",children:e.jsx(Te,{placeholder:"All Status"})}),e.jsxs(Re,{children:[e.jsx(O,{value:"all",children:"All Status"}),e.jsx(O,{value:"pending",children:"Pending"}),e.jsx(O,{value:"paused",children:"Paused"}),e.jsx(O,{value:"approved",children:"Approved"}),e.jsx(O,{value:"rejected",children:"Rejected"}),e.jsx(O,{value:"closed",children:"Closed"})]})]}),e.jsxs(Ae,{value:i.priorityFilter,onValueChange:i.setPriorityFilter,children:[e.jsx(ke,{className:"h-10","data-testid":"priority-filter",children:e.jsx(Te,{placeholder:"All Priority"})}),e.jsxs(Re,{children:[e.jsx(O,{value:"all",children:"All Priority"}),e.jsx(O,{value:"express",children:"Express"}),e.jsx(O,{value:"standard",children:"Standard"})]})]}),e.jsxs(Ae,{value:i.departmentFilter,onValueChange:i.setDepartmentFilter,disabled:v||g.length===0,children:[e.jsx(ke,{className:"h-10","data-testid":"department-filter",children:e.jsx(Te,{placeholder:v?"Loading...":"All Departments"})}),e.jsxs(Re,{children:[e.jsx(O,{value:"all",children:"All Departments"}),g.map(B=>e.jsx(O,{value:B,children:B},B))]})]}),e.jsxs(Ae,{value:i.slaComplianceFilter,onValueChange:i.setSlaComplianceFilter,children:[e.jsx(ke,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(Te,{placeholder:"All SLA Status"})}),e.jsxs(Re,{children:[e.jsx(O,{value:"all",children:"All SLA Status"}),e.jsx(O,{value:"compliant",children:"Compliant"}),e.jsx(O,{value:"on-track",children:"On Track"}),e.jsx(O,{value:"approaching",children:"Approaching"}),e.jsx(O,{value:"critical",children:"Critical"}),e.jsx(O,{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(Z,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:F.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:F.selectedUser.displayName||F.selectedUser.email}),e.jsx(D,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:F.handleClear,children:e.jsx(ft,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(xe,{placeholder:"Search initiator...",value:F.searchQuery,onChange:B=>F.handleSearch(B.target.value),onFocus:()=>{F.searchResults.length>0&&F.setShowResults(!0)},onBlur:()=>setTimeout(()=>F.setShowResults(!1),200),className:"h-10","data-testid":"initiator-search-input"}),F.showResults&&F.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:F.searchResults.map(B=>e.jsx("button",{type:"button",onClick:()=>F.handleSelect(B),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:B.displayName||B.email}),B.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:B.email})]})},B.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(Z,{className:"text-sm font-medium text-gray-700",children:"Approver"}),i.approverFilter!=="all"&&e.jsxs(Ae,{value:i.approverFilterType,onValueChange:B=>i.setApproverFilterType(B),children:[e.jsx(ke,{className:"h-7 w-32 text-xs",children:e.jsx(Te,{})}),e.jsxs(Re,{children:[e.jsx(O,{value:"current",children:"Current Only"}),e.jsx(O,{value:"any",children:"Any Approver"})]})]})]}),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(D,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:N.handleClear,children:e.jsx(ft,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(xe,{placeholder:"Search approver...",value:N.searchQuery,onChange:B=>N.handleSearch(B.target.value),onFocus:()=>{N.searchResults.length>0&&N.setShowResults(!0)},onBlur:()=>setTimeout(()=>N.setShowResults(!1),200),className:"h-10","data-testid":"approver-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(B=>e.jsx("button",{type:"button",onClick:()=>N.handleSelect(B),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:B.displayName||B.email}),B.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:B.email})]})},B.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(Ae,{value:i.dateRange,onValueChange:i.handleDateRangeChange,children:[e.jsx(ke,{className:"w-[160px] h-10",children:e.jsx(Te,{placeholder:"Date Range"})}),e.jsxs(Re,{children:[e.jsx(O,{value:"all",children:"All Time"}),e.jsx(O,{value:"today",children:"Today"}),e.jsx(O,{value:"week",children:"This Week"}),e.jsx(O,{value:"month",children:"This Month"}),e.jsx(O,{value:"last7days",children:"Last 7 Days"}),e.jsx(O,{value:"last30days",children:"Last 30 Days"}),e.jsx(O,{value:"custom",children:"Custom Range"})]})]}),i.dateRange==="custom"&&e.jsxs(Es,{open:i.showCustomDatePicker,onOpenChange:i.setShowCustomDatePicker,children:[e.jsx(Ms,{asChild:!0,children:e.jsxs(D,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(We,{className:"w-4 h-4"}),i.customStartDate&&i.customEndDate?`${he(i.customStartDate,"MMM d, yyyy")} - ${he(i.customEndDate,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Is,{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(Z,{htmlFor:"start-date",children:"Start Date"}),e.jsx(xe,{id:"start-date",type:"date",value:i.customStartDate?he(i.customStartDate,"yyyy-MM-dd"):"",onChange:B=>{const oe=B.target.value?new Date(B.target.value):void 0;oe?(i.setCustomStartDate(oe),i.customEndDate&&oe>i.customEndDate&&i.setCustomEndDate(oe)):i.setCustomStartDate(void 0)},max:he(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Z,{htmlFor:"end-date",children:"End Date"}),e.jsx(xe,{id:"end-date",type:"date",value:i.customEndDate?he(i.customEndDate,"yyyy-MM-dd"):"",onChange:B=>{const oe=B.target.value?new Date(B.target.value):void 0;oe?(i.setCustomEndDate(oe),i.customStartDate&&oe<i.customStartDate&&i.setCustomStartDate(oe)):i.setCustomEndDate(void 0)},min:i.customStartDate?he(i.customStartDate,"yyyy-MM-dd"):void 0,max:he(new Date,"yyyy-MM-dd"),className:"w-full"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(D,{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(D,{size:"sm",variant:"outline",onClick:()=>{i.setShowCustomDatePicker(!1),i.setCustomStartDate(void 0),i.setCustomEndDate(void 0),i.setDateRange("month")},children:"Cancel"})]})]})})]})]})]})})}),e.jsx(lh,{requests:q,loading:c,hasActiveFilters:i.hasActiveFilters,onViewRequest:t}),e.jsx(da,{currentPage:i.currentPage||1,totalPages:b,totalRecords:T,itemsPerPage:k,onPageChange:H,loading:c,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}async function X2({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 Vc=100;async function Q2(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:Vc,...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===Vc}}return s}function J2({onViewRequest:t}){const s=dh(),[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,C]=x.useState(1),[f,j]=x.useState(0),[b]=x.useState(10),w=Br({allUsers:g,filterValue:s.initiatorFilter,onFilterChange:s.setInitiatorFilter}),T=Br({allUsers:g,filterValue:s.approverFilter,onFilterChange:s.setApproverFilter}),R=x.useCallback(async(E,H,q,J)=>{try{const B=await He.getRequestStats(E,H?H.toISOString():void 0,q?q.toISOString():void 0,void 0,J==null?void 0:J.priority,J==null?void 0:J.department,J==null?void 0:J.initiator,J==null?void 0:J.approver,J==null?void 0:J.approverType,J==null?void 0:J.search,J==null?void 0:J.slaCompliance,!0);d({total:B.totalRequests||0,pending:B.openRequests||0,paused:B.pausedRequests||0,approved:B.approvedRequests||0,rejected:B.rejectedRequests||0,draft:B.draftRequests||0,closed:B.closedRequests||0})}catch(B){console.error("Failed to fetch backend stats:",B)}},[]),k=x.useCallback(async()=>{try{p(!0);const E=await He.getDepartments();u(E)}catch{}finally{p(!1)}},[]),F=x.useCallback(async()=>{try{const H=(await Gt.getAllUsers()).map(q=>({userId:q.userId,email:q.email,displayName:q.displayName||q.email}));y(H)}catch(E){console.error("Failed to fetch users:",E)}},[]),N=x.useRef(s),A=x.useRef(R);x.useEffect(()=>{N.current=s,A.current=R},[s,R]);const I=x.useCallback(async(E=1)=>{try{E===1&&(i(!0),r([]));const H=N.current.getFilters(),q=await X2({page:E,itemsPerPage:b,filters:H});r(q.data),s.setCurrentPage(q.pagination.page),C(q.pagination.totalPages),j(q.pagination.total)}catch{r([])}finally{i(!1)}},[b]),V=x.useCallback(async()=>{try{l(!0);const E=await Q2(s.getFilters());await gh(E,s.getFilters())}catch(E){console.error("Failed to export requests:",E),alert("Failed to export requests. Please try again.")}finally{l(!1)}},[s]);x.useEffect(()=>{k(),F()},[k,F]),x.useEffect(()=>{const E=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},q=s.dateRange||"month";A.current(q,s.customStartDate,s.customEndDate,H)},s.searchTerm?500:0);return()=>clearTimeout(E)},[s.searchTerm,s.priorityFilter,s.slaComplianceFilter,s.departmentFilter,s.initiatorFilter,s.approverFilter,s.approverFilterType,s.dateRange,s.customStartDate,s.customEndDate]);const _=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 E=s.currentPage||1;I(E),L.current=!0},[]),x.useEffect(()=>{if(!L.current)return;const E=_.current;if(!(E.searchTerm!==s.searchTerm||E.statusFilter!==s.statusFilter||E.priorityFilter!==s.priorityFilter||E.slaComplianceFilter!==s.slaComplianceFilter||E.departmentFilter!==s.departmentFilter||E.initiatorFilter!==s.initiatorFilter||E.approverFilter!==s.approverFilter||E.approverFilterType!==s.approverFilterType||E.dateRange!==s.dateRange||E.customStartDate!==s.customStartDate||E.customEndDate!==s.customEndDate))return;const q=setTimeout(()=>{s.setCurrentPage(1),I(1),_.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!==E.searchTerm?500:0);return()=>clearTimeout(q)},[s.searchTerm,s.statusFilter,s.priorityFilter,s.slaComplianceFilter,s.departmentFilter,s.initiatorFilter,s.approverFilter,s.approverFilterType,s.dateRange,s.customStartDate,s.customEndDate]);const S=x.useCallback(E=>{E>=1&&E<=v&&(s.setCurrentPage(E),I(E))},[v,I,s]),M=x.useMemo(()=>mh(a),[a]),P=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 E=M.filter(oe=>{const ge=(oe.status||"").toString().toLowerCase();return ge==="pending"||ge==="in-progress"}).length,H=M.filter(oe=>(oe.status||"").toString().toLowerCase()==="paused").length,q=M.filter(oe=>(oe.status||"").toString().toLowerCase()==="approved").length,J=M.filter(oe=>(oe.status||"").toString().toLowerCase()==="rejected").length,B=M.filter(oe=>(oe.status||"").toString().toLowerCase()==="closed").length;return{total:f>0?f:M.length,pending:E,paused:H,approved:q,rejected:J,draft:0,closed:B}},[c,f,M]);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(ih,{isOrgLevel:!1,isAdmin:!1,loading:n,exporting:o,onExport:V}),e.jsx(oh,{stats:P,onStatusFilter:E=>{s.setStatusFilter(E)}}),e.jsx(W,{className:"border-gray-200 shadow-md","data-testid":"requests-filters",children:e.jsx(K,{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(X,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),s.hasActiveFilters&&e.jsxs(D,{variant:"ghost",size:"sm",onClick:s.clearFilters,className:"gap-2",children:[e.jsx(Et,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(ct,{}),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(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(xe,{placeholder:"Search requests...",value:s.searchTerm,onChange:E=>s.setSearchTerm(E.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(Ae,{value:s.statusFilter,onValueChange:s.setStatusFilter,children:[e.jsx(ke,{className:"h-10","data-testid":"status-filter",children:e.jsx(Te,{placeholder:"All Status"})}),e.jsxs(Re,{children:[e.jsx(O,{value:"all",children:"All Status"}),e.jsx(O,{value:"pending",children:"Pending"}),e.jsx(O,{value:"paused",children:"Paused"}),e.jsx(O,{value:"approved",children:"Approved"}),e.jsx(O,{value:"rejected",children:"Rejected"}),e.jsx(O,{value:"closed",children:"Closed"})]})]}),e.jsxs(Ae,{value:s.priorityFilter,onValueChange:s.setPriorityFilter,children:[e.jsx(ke,{className:"h-10","data-testid":"priority-filter",children:e.jsx(Te,{placeholder:"All Priority"})}),e.jsxs(Re,{children:[e.jsx(O,{value:"all",children:"All Priority"}),e.jsx(O,{value:"express",children:"Express"}),e.jsx(O,{value:"standard",children:"Standard"})]})]}),e.jsxs(Ae,{value:s.departmentFilter,onValueChange:s.setDepartmentFilter,disabled:h||m.length===0,children:[e.jsx(ke,{className:"h-10","data-testid":"department-filter",children:e.jsx(Te,{placeholder:h?"Loading...":"All Departments"})}),e.jsxs(Re,{children:[e.jsx(O,{value:"all",children:"All Departments"}),m.map(E=>e.jsx(O,{value:E,children:E},E))]})]}),e.jsxs(Ae,{value:s.slaComplianceFilter,onValueChange:s.setSlaComplianceFilter,children:[e.jsx(ke,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(Te,{placeholder:"All SLA Status"})}),e.jsxs(Re,{children:[e.jsx(O,{value:"all",children:"All SLA Status"}),e.jsx(O,{value:"compliant",children:"Compliant"}),e.jsx(O,{value:"on-track",children:"On Track"}),e.jsx(O,{value:"approaching",children:"Approaching"}),e.jsx(O,{value:"critical",children:"Critical"}),e.jsx(O,{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(Z,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:w.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:w.selectedUser.displayName||w.selectedUser.email}),e.jsx(D,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:w.handleClear,children:e.jsx(ft,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(xe,{placeholder:"Search initiator...",value:w.searchQuery,onChange:E=>w.handleSearch(E.target.value),onFocus:()=>{w.searchResults.length>0&&w.setShowResults(!0)},onBlur:()=>setTimeout(()=>w.setShowResults(!1),200),className:"h-10","data-testid":"initiator-search-input"}),w.showResults&&w.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:w.searchResults.map(E=>e.jsx("button",{type:"button",onClick:()=>w.handleSelect(E),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:E.displayName||E.email}),E.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:E.email})]})},E.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(Z,{className:"text-sm font-medium text-gray-700",children:"Approver"}),s.approverFilter!=="all"&&e.jsxs(Ae,{value:s.approverFilterType,onValueChange:E=>s.setApproverFilterType(E),children:[e.jsx(ke,{className:"h-7 w-32 text-xs",children:e.jsx(Te,{})}),e.jsxs(Re,{children:[e.jsx(O,{value:"current",children:"Current Only"}),e.jsx(O,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:T.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:T.selectedUser.displayName||T.selectedUser.email}),e.jsx(D,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:T.handleClear,children:e.jsx(ft,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(xe,{placeholder:"Search approver...",value:T.searchQuery,onChange:E=>T.handleSearch(E.target.value),onFocus:()=>{T.searchResults.length>0&&T.setShowResults(!0)},onBlur:()=>setTimeout(()=>T.setShowResults(!1),200),className:"h-10","data-testid":"approver-search-input"}),T.showResults&&T.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:T.searchResults.map(E=>e.jsx("button",{type:"button",onClick:()=>T.handleSelect(E),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:E.displayName||E.email}),E.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:E.email})]})},E.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(Ae,{value:s.dateRange,onValueChange:s.handleDateRangeChange,children:[e.jsx(ke,{className:"w-[160px] h-10",children:e.jsx(Te,{placeholder:"Date Range"})}),e.jsxs(Re,{children:[e.jsx(O,{value:"all",children:"All Time"}),e.jsx(O,{value:"today",children:"Today"}),e.jsx(O,{value:"week",children:"This Week"}),e.jsx(O,{value:"month",children:"This Month"}),e.jsx(O,{value:"last7days",children:"Last 7 Days"}),e.jsx(O,{value:"last30days",children:"Last 30 Days"}),e.jsx(O,{value:"custom",children:"Custom Range"})]})]}),s.dateRange==="custom"&&e.jsxs(Es,{open:s.showCustomDatePicker,onOpenChange:s.setShowCustomDatePicker,children:[e.jsx(Ms,{asChild:!0,children:e.jsxs(D,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(We,{className:"w-4 h-4"}),s.customStartDate&&s.customEndDate?`${he(s.customStartDate,"MMM d, yyyy")} - ${he(s.customEndDate,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Is,{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(Z,{htmlFor:"start-date",children:"Start Date"}),e.jsx(xe,{id:"start-date",type:"date",value:s.customStartDate?he(s.customStartDate,"yyyy-MM-dd"):"",onChange:E=>{const H=E.target.value?new Date(E.target.value):void 0;H?(s.setCustomStartDate(H),s.customEndDate&&H>s.customEndDate&&s.setCustomEndDate(H)):s.setCustomStartDate(void 0)},max:he(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Z,{htmlFor:"end-date",children:"End Date"}),e.jsx(xe,{id:"end-date",type:"date",value:s.customEndDate?he(s.customEndDate,"yyyy-MM-dd"):"",onChange:E=>{const H=E.target.value?new Date(E.target.value):void 0;H?(s.setCustomEndDate(H),s.customStartDate&&H<s.customStartDate&&s.setCustomStartDate(H)):s.setCustomEndDate(void 0)},min:s.customStartDate?he(s.customStartDate,"yyyy-MM-dd"):void 0,max:he(new Date,"yyyy-MM-dd"),className:"w-full"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(D,{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(D,{size:"sm",variant:"outline",onClick:()=>{s.setShowCustomDatePicker(!1),s.setCustomStartDate(void 0),s.setCustomEndDate(void 0),s.setDateRange("month")},children:"Cancel"})]})]})})]})]})]})})}),e.jsx(lh,{requests:M,loading:n,hasActiveFilters:s.hasActiveFilters,onViewRequest:t}),e.jsx(da,{currentPage:s.currentPage||1,totalPages:v,totalRecords:f,itemsPerPage:b,onPageChange:S,loading:n,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}function eS(){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(W,{children:e.jsxs(K,{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(D,{onClick:()=>t(-1),className:"mt-4","data-testid":"back-button",children:[e.jsx(us,{className:"w-4 h-4 mr-2"}),"Back"]})]})})})})}function tS({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(D,{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 sS({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(W,{children:[e.jsx(ee,{className:"pb-3",children:e.jsx(te,{className:"text-sm font-medium text-gray-600",children:"TAT Compliance"})}),e.jsxs(K,{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(lt,{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(hs,{value:s,className:"mt-2 h-2"})]})]}),e.jsxs(W,{children:[e.jsx(ee,{className:"pb-3",children:e.jsx(te,{className:"text-sm font-medium text-gray-600",children:"Total Approved"})}),e.jsxs(K,{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(W,{children:[e.jsx(ee,{className:"pb-3",children:e.jsx(te,{className:"text-sm font-medium text-gray-600",children:"Avg Response Time"})}),e.jsxs(K,{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(Ui,{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(W,{children:[e.jsx(ee,{className:"pb-3",children:e.jsx(te,{className:"text-sm font-medium text-gray-600",children:"Pending Actions"})}),e.jsxs(K,{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(Ee,{className:"w-5 h-5 text-orange-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Awaiting approval"})]})]})]})}function aS({approverName:t,approverStats:s,dateRange:a="all",customStartDate:r,customEndDate:n}){return e.jsxs(W,{"data-testid":"approver-actions-stats",children:[e.jsxs(ee,{children:[e.jsx(te,{children:"Approver's Actions"}),e.jsxs(pe,{children:["Statistics for all requests by ",t," ",a&&a!=="all"?r0(a,r,n,""):"(all time)"]})]}),e.jsxs(K,{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(Ee,{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(Yr,{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(Se,{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(lt,{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(Sx,{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(Nd,{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 rS({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:C,onApplyCustomDate:f,onClearFilters:j}){return e.jsxs(W,{"data-testid":"approver-performance-filters",children:[e.jsx(ee,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(te,{children:"Filters"}),e.jsx(D,{variant:"ghost",size:"sm",onClick:j,className:"text-xs","data-testid":"clear-filters-button",children:"Clear All"})]})}),e.jsx(K,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-6 gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(xe,{placeholder:"Search requests...",value:t,onChange:b=>m(b.target.value),className:"pl-10","data-testid":"search-input"})]}),e.jsxs(Ae,{value:s,onValueChange:u,children:[e.jsx(ke,{"data-testid":"status-filter",children:e.jsx(Te,{placeholder:"Status"})}),e.jsxs(Re,{children:[e.jsx(O,{value:"all",children:"All Status"}),e.jsx(O,{value:"pending",children:"Pending"}),e.jsx(O,{value:"approved",children:"Approved"}),e.jsx(O,{value:"rejected",children:"Rejected"}),e.jsx(O,{value:"closed",children:"Closed"})]})]}),e.jsxs(Ae,{value:a,onValueChange:h,children:[e.jsx(ke,{"data-testid":"priority-filter",children:e.jsx(Te,{placeholder:"Priority"})}),e.jsxs(Re,{children:[e.jsx(O,{value:"all",children:"All Priority"}),e.jsx(O,{value:"express",children:"Express"}),e.jsx(O,{value:"standard",children:"Standard"})]})]}),e.jsxs(Ae,{value:r,onValueChange:p,children:[e.jsx(ke,{"data-testid":"sla-compliance-filter",children:e.jsx(Te,{placeholder:"SLA Compliance"})}),e.jsxs(Re,{children:[e.jsx(O,{value:"all",children:"All SLA"}),e.jsx(O,{value:"compliant",children:"Compliant"}),e.jsx(O,{value:"on-track",children:"On Track"}),e.jsx(O,{value:"approaching",children:"Approaching"}),e.jsx(O,{value:"critical",children:"Critical"}),e.jsx(O,{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(Ae,{value:n,onValueChange:g,children:[e.jsx(ke,{className:"flex-1","data-testid":"date-range-filter",children:e.jsx(Te,{placeholder:"Date Range"})}),e.jsxs(Re,{children:[e.jsx(O,{value:"all",children:"All Time"}),e.jsx(O,{value:"today",children:"Today"}),e.jsx(O,{value:"week",children:"This Week"}),e.jsx(O,{value:"month",children:"This Month"}),e.jsx(O,{value:"last7days",children:"Last 7 Days"}),e.jsx(O,{value:"last30days",children:"Last 30 Days"}),e.jsx(O,{value:"custom",children:"Custom Range"})]})]}),n==="custom"&&e.jsxs(Es,{open:l,onOpenChange:y,children:[e.jsx(Ms,{asChild:!0,children:e.jsxs(D,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(We,{className:"w-4 h-4"}),c&&d?`${he(c,"MMM d")} - ${he(d,"MMM d")}`:"Select dates"]})}),e.jsx(Is,{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(Z,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(xe,{id:"start-date",type:"date",value:c?he(c,"yyyy-MM-dd"):"",onChange:b=>{const w=b.target.value?new Date(b.target.value):void 0;w?(v(w),d&&w>d&&C(w)):v(void 0)},max:he(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Z,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(xe,{id:"end-date",type:"date",value:d?he(d,"yyyy-MM-dd"):"",onChange:b=>{const w=b.target.value?new Date(b.target.value):void 0;w?(C(w),c&&w<c&&v(w)):C(void 0)},min:c?he(c,"yyyy-MM-dd"):void 0,max:he(new Date,"yyyy-MM-dd"),className:"w-full"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(D,{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(D,{size:"sm",variant:"outline",onClick:()=>{y(!1),v(i),C(o),(!i||!o)&&g("all")},"data-testid":"cancel-date-button",children:"Cancel"})]})]})})]})]})]})})]})}const nS=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:lt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:lt,iconColor:"text-gray-600"}}},iS=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:Ee,iconColor:"text-yellow-600"};case"in-progress":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Ee,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:Se,iconColor:"text-gray-600"}}},oS=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 lS(t){if(!t)return"N/A";try{return he(new Date(t),"MMM d, yyyy")}catch{return"N/A"}}function cS(t){if(!t)return"N/A";try{return he(new Date(t),"MMM d, yyyy HH:mm")}catch{return"N/A"}}function dS({requests:t,loading:s,approverName:a,currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:o,onPageChange:l}){const c=Hs();return e.jsxs(W,{"data-testid":"approver-performance-request-list",children:[e.jsxs(ee,{children:[e.jsx(te,{children:"Request Details"}),e.jsxs(pe,{children:["All requests handled by ",a," with applied filters"]})]}),e.jsxs(K,{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(Se,{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=nS(d.priority),u=iS(d.status),h=oS(d.slaStatus||""),p=m.icon,g=u.icon;return e.jsx(W,{className:"hover:shadow-md transition-shadow cursor-pointer",onClick:()=>c(`/request/${d.requestId}`),"data-testid":`request-card-${d.requestId}`,children:e.jsx(K,{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(X,{className:m.color,"data-testid":"priority-badge",children:[e.jsx(p,{className:`w-3 h-3 mr-1 ${m.iconColor}`}),d.priority]}),e.jsxs(X,{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(X,{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(Ee,{className:"w-3 h-3 mr-1"}),"Pending"]})}),d.slaStatus&&e.jsx(X,{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(Ee,{className:"w-3 h-3"}),"Submitted: ",lS(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: ",cS(d.approvalActionDate)]}),e.jsxs("span",{className:"flex items-center gap-1","data-testid":"approval-level",children:[e.jsx(lt,{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(Ui,{className:"w-3 h-3"}),ot(d.levelElapsedHours)," / ",ot(d.levelTatHours||0)," TAT"]})]})]}),e.jsx(D,{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 mS(){const[t]=Sd(),[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),[C,f]=x.useState(void 0),[j,b]=x.useState(void 0),w=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)},[]),T=x.useCallback(k=>{const F=k;m(F),F!=="custom"?(h(void 0),g(void 0),f(void 0),b(void 0),v(!1)):(f(u),b(p),v(!0))},[u,p]),R=x.useCallback(()=>{if(C&&j){if(C>j){const k=C;h(j),g(k),f(j),b(k)}else h(C),g(j);v(!1)}},[C,j]);return{searchTerm:s,statusFilter:r,priorityFilter:i,slaComplianceFilter:l,dateRange:d,customStartDate:u,customEndDate:p,showCustomDatePicker:y,tempCustomStartDate:C,tempCustomEndDate:j,setSearchTerm:a,setStatusFilter:n,setPriorityFilter:o,setSlaComplianceFilter:c,setDateRange:m,setCustomStartDate:h,setCustomEndDate:g,setShowCustomDatePicker:v,setTempCustomStartDate:f,setTempCustomEndDate:b,clearFilters:w,handleDateRangeChange:T,handleApplyCustomDate:R}}function uS({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),[C,f]=x.useState(!1),[j,b]=x.useState(1),[w,T]=x.useState(1),[R,k]=x.useState(0),F=x.useRef(!0),N=x.useCallback(async()=>{if(t)try{const _=s==="all"?void 0:s,L=await He.getSingleApproverStats(t,_,a,r,i!=="all"?i:void 0,o!=="all"?o:void 0);h(L)}catch(_){console.error("[ApproverPerformance] Failed to fetch approver stats:",_),h(null)}},[t,s,a,r,i,o]),A=x.useCallback(async(_=1)=>{if(!t){v(!1);return}try{v(!0);const L=await He.getRequestsByApprover(t,_,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),k(L.pagination.totalRecords),T(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(()=>{F.current&&(F.current=!1,N(),A(1))},[]),x.useEffect(()=>{F.current||N()},[s,a,r,i,o]),x.useEffect(()=>{F.current||A(1)},[s,a,r,n,i,o,l]);const I=x.useCallback(()=>{f(!0),N(),A(1)},[N,A]),V=x.useCallback(_=>{A(_)},[A]);return{requests:d,approverStats:u,allFilteredRequests:p,loading:y,refreshing:C,currentPage:j,totalPages:w,totalRecords:R,handleRefresh:I,handlePageChange:V}}const zc=10;function hS(){const[t]=Sd(),s=t.get("approverId")||"",a=t.get("approverName")||"Unknown Approver",r=mS(),n=uS({approverId:s,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,slaComplianceFilter:r.slaComplianceFilter,searchTerm:r.searchTerm,itemsPerPage:zc});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(tS,{approverName:a,refreshing:n.refreshing,onRefresh:n.handleRefresh}),n.approverStats&&e.jsx(sS,{approverStats:n.approverStats}),n.approverStats&&e.jsx(aS,{approverName:a,approverStats:n.approverStats,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate}),e.jsx(rS,{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(dS,{requests:n.requests,loading:n.loading,approverName:a,currentPage:n.currentPage,totalPages:n.totalPages,totalRecords:n.totalRecords,itemsPerPage:zc,onPageChange:n.handlePageChange})]}):e.jsx(eS,{})}function pS(){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(W,{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(K,{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(Xr,{src:(t==null?void 0:t.picture)||""}),e.jsx(jt,{className:"bg-yellow-400 text-slate-900 text-2xl font-bold",children:s()})]}),Xs(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:[Xs(t)&&e.jsxs(X,{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(X,{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(X,{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(W,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(ee,{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(te,{className:"text-lg text-gray-900",children:"Personal Information"}),e.jsx(pe,{className:"text-gray-600",children:"Your personal details"})]})]})}),e.jsx(K,{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(Li,{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(fd,{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(W,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(ee,{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(Yo,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsx(te,{className:"text-lg text-gray-900",children:"Professional Information"}),e.jsx(pe,{className:"text-gray-600",children:"Work-related details"})]})]})}),e.jsx(K,{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(hd,{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(Yo,{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(X,{variant:Xs(t)||Fa(t)?"default":"secondary",className:Xs(t)?"bg-yellow-400 text-slate-900":Fa(t)?"bg-blue-400 text-slate-900":"",children:Xs(t)?"Administrator":Fa(t)?"Management":"User"}),(Xs(t)||Fa(t))&&e.jsx(je,{className:"w-4 h-4 text-green-600"})]})]})]})]})})]})]}),e.jsxs(W,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(ee,{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(te,{className:"text-lg text-gray-900",children:"Account Status"}),e.jsx(pe,{className:"text-gray-600",children:"Account information and activity"})]})]})}),e.jsx(K,{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(X,{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 Cr="BBb78N3tSTEw6mPbBmvEDX2bhYEDKPc_zffL-vxPV8FBSmR1qSpy9gdV8zt-WFF-q2NPpVmL4BhbUzLSHVAPjcI",xS="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 gS(){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 fS(t){if(Cr.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(Cr)})}else try{s=await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Zn(Cr)})}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(Cr)})}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(`${xS}/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 yS(){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 gS()}catch(a){throw new Error(`Service worker registration failed: ${(a==null?void 0:a.message)||"Unknown error"}`)}try{await fS(s)}catch(a){throw a}}function Ri({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(jp,{"data-slot":"slider",defaultValue:s,value:a,min:r,max:n,className:le("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(Np,{"data-slot":"slider-track",className:le("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(wp,{"data-slot":"slider-range",className:le("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full")})}),Array.from({length:o.length},(l,c)=>e.jsx(Cp,{"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 vS({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 N,A;try{n(!0),c(null);const I=await en();a(I)}catch(I){c(((A=(N=I.response)==null?void 0:N.data)==null?void 0:A.error)||"Failed to load configurations")}finally{n(!1)}},g=async N=>{var A,I;try{o(N.configKey),c(null);const V=d[N.configKey]??N.configValue;if(N.validationRules){const _=parseFloat(V);if(N.valueType==="NUMBER"){if(N.validationRules.min!==void 0&&_<N.validationRules.min)throw new Error(`Value must be at least ${N.validationRules.min}`);if(N.validationRules.max!==void 0&&_>N.validationRules.max)throw new Error(`Value must be at most ${N.validationRules.max}`)}}await vt(N.configKey,V),a(_=>_.map(L=>L.configKey===N.configKey?{...L,configValue:V}:L)),m(_=>{const L={..._};return delete L[N.configKey],L}),h(`${N.displayName} updated successfully`),setTimeout(()=>h(null),3e3),t&&t()}catch(V){c(V.message||((I=(A=V.response)==null?void 0:A.data)==null?void 0:I.error)||"Failed to save configuration")}finally{o(null)}},y=async N=>{var A,I;if(confirm(`Reset "${N.displayName}" to default value?`))try{o(N.configKey),c(null),await hy(N.configKey),a(V=>V.map(_=>_.configKey===N.configKey?{..._,configValue:_.defaultValue||""}:_)),m(V=>{const _={...V};return delete _[N.configKey],_}),h(`${N.displayName} reset to default`),setTimeout(()=>h(null),3e3)}catch(V){c(((I=(A=V.response)==null?void 0:A.data)==null?void 0:I.error)||"Failed to reset configuration")}finally{o(null)}},v=(N,A)=>{m(I=>({...I,[N]:A}))},C=N=>d[N.configKey]??N.configValue,f=N=>d[N.configKey]!==void 0&&d[N.configKey]!==N.configValue,j=N=>{var V,_,L,S;const A=C(N),I=i===N.configKey;if(!N.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:N.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(N.uiComponent||N.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 ${A==="true"?"bg-green-500":"bg-slate-400"}`}),e.jsx("span",{className:`text-sm font-medium ${A==="true"?"text-green-700":"text-slate-600"}`,children:A==="true"?"Enabled":"Disabled"})]}),e.jsx(Lt,{checked:A==="true",onCheckedChange:H=>v(N.configKey,H?"true":"false"),disabled:I})]});case"slider":const M=parseInt(A)||0,P=((V=N.validationRules)==null?void 0:V.min)||0,E=((_=N.validationRules)==null?void 0:_.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:[M,"%"]}),e.jsxs("span",{className:"text-xs text-slate-500 bg-slate-100 px-2 py-1 rounded-sm border border-slate-200",children:["Range: ",P,"-",E]})]}),e.jsx(Ri,{value:[M],min:P,max:E,step:1,onValueChange:([H])=>{H!==void 0&&v(N.configKey,H.toString())},disabled:I,className:"w-full"})]});case"number":return e.jsx(xe,{type:"number",value:A,onChange:H=>v(N.configKey,H.target.value),disabled:I,min:(L=N.validationRules)==null?void 0:L.min,max:(S=N.validationRules)==null?void 0:S.max,className:"font-mono border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 rounded-md transition-all shadow-sm"});case"text":case"input":default:return e.jsx(xe,{type:"text",value:A,onChange:H=>v(N.configKey,H.target.value),disabled:I,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=N=>{switch(N){case"TAT_SETTINGS":return e.jsx(Ee,{className:"w-5 h-5"});case"DOCUMENT_POLICY":return e.jsx(Se,{className:"w-5 h-5"});case"NOTIFICATION_RULES":return e.jsx(Ft,{className:"w-5 h-5"});case"AI_CONFIGURATION":return e.jsx(Kr,{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"})}},w=["DASHBOARD_LAYOUT"],T=["ALLOW_EXTERNAL_SHARING","NOTIFICATION_BATCH_DELAY_MS","AI_REMARK_MAX_CHARACTERS"],R=s.filter(N=>!w.includes(N.configCategory)&&!T.includes(N.configKey)),k=R.reduce((N,A)=>(N[A.configCategory]||(N[A.configCategory]=[]),N[A.configCategory].push(A),N),{});if(Object.keys(k).forEach(N=>{const A=k[N];A&&A.sort((I,V)=>I.sortOrder-V.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(R.length===0)return e.jsx(W,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(K,{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 F=Object.keys(k);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(D,{size:"sm",variant:"ghost",onClick:()=>c(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsxs(Qr,{defaultValue:F[0],className:"w-full",children:[e.jsx(Jr,{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:F.map(N=>e.jsx(pt,{value:N,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:N.replace(/_/g," ")})},N))}),F.map(N=>{var A,I,V;return e.jsx(xt,{value:N,className:"space-y-4 mt-6",children:e.jsxs(W,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ee,{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(N)})}),e.jsxs("div",{children:[e.jsx(te,{className:"text-lg font-semibold text-slate-900",children:N.replace(/_/g," ")}),e.jsxs(pe,{className:"text-sm",children:[((A=k[N])==null?void 0:A.length)||0," setting",(((I=k[N])==null?void 0:I.length)||0)!==1?"s":""," available"]})]})]})}),e.jsx(K,{className:"space-y-6",children:(V=k[N])==null?void 0:V.map(_=>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(Z,{className:"text-sm font-semibold text-slate-900",children:_.displayName}),f(_)&&e.jsx(X,{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"}),_.requiresRestart&&e.jsx(X,{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"})]}),_.description&&e.jsx("p",{className:"text-xs text-slate-600 mt-1 leading-relaxed",children:_.description}),_.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:_.defaultValue})]})]})}),j(_),_.isEditable&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(D,{size:"sm",onClick:()=>g(_),disabled:!f(_)||i===_.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===_.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"]})}),_.defaultValue&&e.jsxs(D,{size:"sm",variant:"outline",onClick:()=>y(_),disabled:i===_.configKey,className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(Ax,{className:"w-4 h-4"}),"Reset to Default"]})]})]},_.configKey))})]})},N)})]})]})}function bS(){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 N,A;try{r(!0),u(null);const I=await py(n);s(I)}catch(I){u(((A=(N=I.response)==null?void 0:N.data)==null?void 0:A.error)||"Failed to load holidays")}finally{r(!1)}},C=()=>{y({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1}),d(null),l(!0)},f=N=>{y({holidayDate:N.holidayDate,holidayName:N.holidayName,description:N.description||"",holidayType:N.holidayType,isRecurring:N.isRecurring}),d(N),l(!0)},j=()=>{if(c)return;const N=new Date;return N.setDate(N.getDate()+1),N.toISOString().split("T")[0]},b=async()=>{var N,A;try{if(u(null),!g.holidayDate||!g.holidayName){u("Holiday date and name are required");return}c?(await gy(c.holidayId,g),p("Holiday updated successfully")):(await xy(g),p("Holiday created successfully")),await v(),l(!1),setTimeout(()=>p(null),3e3)}catch(I){u(((A=(N=I.response)==null?void 0:N.data)==null?void 0:A.error)||"Failed to save holiday")}},w=async N=>{var A,I;if(confirm(`Delete "${N.holidayName}"?`))try{u(null),await fy(N.holidayId),p("Holiday deleted successfully"),await v(),setTimeout(()=>p(null),3e3)}catch(V){u(((I=(A=V.response)==null?void 0:A.data)==null?void 0:I.error)||"Failed to delete holiday")}},T=N=>{switch(N){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"}},R=Array.from({length:5},(N,A)=>new Date().getFullYear()-1+A),k=t.reduce((N,A)=>{const I=new Date(A.holidayDate).toLocaleString("default",{month:"long"});return N[I]||(N[I]=[]),N[I].push(A),N},{}),F=Object.keys(k).sort((N,A)=>{const I=new Date(Date.parse(N+" 1, 2000")).getMonth(),V=new Date(Date.parse(A+" 1, 2000")).getMonth();return I-V});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(D,{size:"sm",variant:"ghost",onClick:()=>u(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsx(W,{className:"shadow-lg border-0 rounded-md",children:e.jsx(ee,{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(te,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Holiday Calendar"}),e.jsx(pe,{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(Ae,{value:n.toString(),onValueChange:N=>i(parseInt(N)),children:[e.jsx(ke,{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(Te,{})}),e.jsx(Re,{className:"rounded-md",children:R.map(N=>e.jsx(O,{value:N.toString(),children:N},N))})]}),e.jsxs(D,{onClick:C,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(W,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(K,{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(D,{onClick:C,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:F.map(N=>{var A,I,V;return e.jsxs(W,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ee,{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(te,{className:"text-base sm:text-lg font-semibold text-slate-900",children:[N," ",n]}),e.jsxs(pe,{className:"text-xs sm:text-sm",children:[((A=k[N])==null?void 0:A.length)||0," holiday",(((I=k[N])==null?void 0:I.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(K,{className:"space-y-3 pt-4",children:(V=k[N])==null?void 0:V.map(_=>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:_.holidayName}),e.jsx(X,{variant:"outline",className:`${T(_.holidayType)} text-[10px] sm:text-xs font-medium shadow-sm`,children:_.holidayType}),_.isRecurring&&e.jsx(X,{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:Xd(_.holidayDate)}),_.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-1.5 line-clamp-2",children:_.description})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-2 self-end sm:self-auto",children:[e.jsxs(D,{size:"sm",variant:"ghost",onClick:()=>f(_),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(Tx,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]}),e.jsxs(D,{size:"sm",variant:"ghost",onClick:()=>w(_),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(Bi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Delete"})]})]})]},_.holidayId))})]},N)})}),e.jsx(et,{open:o,onOpenChange:l,children:e.jsxs(Ze,{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(Xe,{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(Z,{htmlFor:"date",className:"text-sm font-semibold text-slate-900 flex items-center gap-1",children:["Date ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(xe,{id:"date",type:"date",value:g.holidayDate,onChange:N=>y({...g,holidayDate:N.target.value}),min:j(),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(Z,{htmlFor:"name",className:"text-sm font-semibold text-slate-900 flex items-center gap-1",children:["Holiday Name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(xe,{id:"name",placeholder:"e.g., Diwali, Republic Day, Christmas",value:g.holidayName,onChange:N=>y({...g,holidayName:N.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(Z,{htmlFor:"description",className:"text-sm font-semibold text-slate-900",children:["Description ",e.jsx("span",{className:"text-slate-400 font-normal text-xs",children:"(Optional)"})]}),e.jsx(xe,{id:"description",placeholder:"Add additional details about this holiday...",value:g.description,onChange:N=>y({...g,description:N.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(Z,{htmlFor:"type",className:"text-sm font-semibold text-slate-900",children:"Holiday Type"}),e.jsxs(Ae,{value:g.holidayType,onValueChange:N=>y({...g,holidayType:N}),children:[e.jsx(ke,{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(Te,{})}),e.jsxs(Re,{className:"rounded-lg",children:[e.jsx(O,{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(O,{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(O,{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(O,{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:N=>y({...g,isRecurring:N.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(Z,{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(D,{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(D,{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 jS(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function NS(){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,C]=x.useState(!1),[f,j]=x.useState({admins:0,management:0,users:0}),[b,w]=x.useState("ELEVATED"),[T,R]=x.useState(1),[k,F]=x.useState(1),[N,A]=x.useState(0),I=10,V=x.useRef(null),_=x.useRef(null),L=x.useCallback(jS(async z=>{var re,ye,G;if(!z||!z.startsWith("@")||z.length<2){r([]),i(!1);return}i(!0);try{const Q=z.slice(1),Y=((re=(await Gt.searchUsers(Q,20)).data)==null?void 0:re.data)||[];r(Y)}catch(Q){console.error("Search failed:",Q),p({type:"error",text:((G=(ye=Q.response)==null?void 0:ye.data)==null?void 0:G.message)||"Failed to search users"})}finally{i(!1)}},300),[]),S=z=>{const re=z.target.value;s(re),L(re)},M=async z=>{l(z),s(z.email),r([]);const re=g.find(ye=>ye.email.toLowerCase()===z.email.toLowerCase()||ye.userId===z.userId);if(re&&re.role)d(re.role);else try{const G=(await Gt.getAllUsers()).find(Q=>Q.email&&Q.email.toLowerCase()===z.email.toLowerCase()||Q.userId&&Q.userId===z.userId);G&&G.role?d(G.role):d("USER")}catch(ye){console.error("Failed to check user role:",ye),d("USER")}},P=async()=>{var z,re;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,o),p({type:"success",text:`Successfully assigned ${c} role to ${o.displayName||o.email}`}),l(null),s(""),d("USER"),await E(),await H()}catch(ye){console.error("Role assignment failed:",ye),p({type:"error",text:((re=(z=ye.response)==null?void 0:z.data)==null?void 0:re.error)||"Failed to assign role"})}finally{u(!1)}},E=async(z=T)=>{var re,ye,G,Q,ie,Y;C(!0);try{const ue=await Gt.getUsersByRole(b,z,I),Me=((ye=(re=ue.data)==null?void 0:re.data)==null?void 0:ye.users)||[],$e=(Q=(G=ue.data)==null?void 0:G.data)==null?void 0:Q.pagination,Ie=(Y=(ie=ue.data)==null?void 0:ie.data)==null?void 0:Y.summary;y(Me),$e&&(R($e.currentPage),F($e.totalPages),A($e.totalUsers)),Ie&&j({admins:Ie.ADMIN||0,management:Ie.MANAGEMENT||0,users:Ie.USER||0})}catch(ue){console.error("Failed to fetch users:",ue)}finally{C(!1)}},H=async()=>{var z,re,ye,G,Q,ie;try{const Y=await Gt.getRoleStatistics(),ue=((re=(z=Y.data)==null?void 0:z.data)==null?void 0:re.statistics)||((ye=Y.data)==null?void 0:ye.statistics)||[];j({admins:parseInt(((G=ue.find(Me=>Me.role==="ADMIN"))==null?void 0:G.count)||"0"),management:parseInt(((Q=ue.find(Me=>Me.role==="MANAGEMENT"))==null?void 0:Q.count)||"0"),users:parseInt(((ie=ue.find(Me=>Me.role==="USER"))==null?void 0:ie.count)||"0")})}catch(Y){console.error("Failed to fetch statistics:",Y)}};x.useEffect(()=>{E(1),H()},[b]);const q=z=>{w(z),R(1)},J=z=>{E(z)},B=z=>{w(z),R(1),requestAnimationFrame(()=>{const re=_.current;re&&re.scrollIntoView({behavior:"smooth",block:"start"})})};x.useEffect(()=>{const z=re=>{V.current&&!V.current.contains(re.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",z),()=>{document.removeEventListener("mousedown",z)}},[a]);const oe=z=>{switch(z){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"}},ge=z=>{switch(z){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(W,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ee,{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(kx,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(te,{className:"text-lg font-semibold text-gray-900",children:"User Role Management"}),e.jsx(pe,{className:"text-sm text-gray-600",children:"Search for users, assign roles, and manage user permissions across the system"})]})]})}),e.jsxs(K,{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(W,{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:()=>B("ADMIN"),children:e.jsx(K,{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(W,{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:()=>B("MANAGEMENT"),children:e.jsx(K,{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(W,{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:()=>B("USER"),children:e.jsx(K,{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(ct,{}),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:V,children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Search User"}),e.jsxs("div",{className:"relative",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none"}),e.jsx(xe,{type:"text",placeholder:"Type @ to search users...",value:t,onChange:S,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(z=>e.jsxs("button",{onClick:()=>M(z),className:"w-full text-left p-2 hover:bg-purple-50 rounded-lg transition-colors mb-1 last:mb-0","data-testid":`user-result-${z.email}`,children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:z.displayName||z.email}),e.jsx("p",{className:"text-xs text-gray-600",children:z.email}),z.department&&e.jsxs("p",{className:"text-xs text-gray-500",children:[z.department,z.designation?` • ${z.designation}`:""]})]},z.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(D,{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(Ae,{value:c,onValueChange:z=>d(z),children:[e.jsx(ke,{className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20","data-testid":"role-select",children:e.jsx(Te,{placeholder:"Select role"})}),e.jsxs(Re,{children:[e.jsx(O,{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(O,{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(O,{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(D,{onClick:P,disabled:!o||m,className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"assign-role-button",children:m?e.jsxs(e.Fragment,{children:[e.jsx(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(ct,{}),e.jsxs("div",{ref:_,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 (",N," ",b!=="ALL"&&b!=="ELEVATED"?b.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(Ae,{value:b,onValueChange:q,children:[e.jsx(ke,{className:"w-[200px] h-10 border rounded-lg border-gray-300",children:e.jsx(Te,{placeholder:"Filter by role"})}),e.jsxs(Re,{children:[e.jsx(O,{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(O,{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(O,{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(O,{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(O,{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(z=>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-${z.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 ${oe(z.role)} flex items-center justify-center shadow-sm`,children:ge(z.role)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-semibold text-gray-900 truncate",children:z.displayName}),e.jsx("p",{className:"text-sm text-gray-600 truncate",children:z.email}),z.department&&e.jsxs("p",{className:"text-xs text-gray-500 mt-1 truncate",children:[z.department,z.designation?` • ${z.designation}`:""]})]})]}),e.jsx(X,{className:`${oe(z.role)} shrink-0`,"data-testid":`role-badge-${z.role}`,children:z.role})]})},z.userId))}),k>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 ",(T-1)*I+1," to ",Math.min(T*I,N)," of ",N," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(D,{variant:"outline",size:"sm",onClick:()=>J(T-1),disabled:T===1,"data-testid":"prev-page-button",children:"Previous"}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,k)},(z,re)=>{let ye;return k<=5||T<=3?ye=re+1:T>=k-2?ye=k-4+re:ye=T-2+re,e.jsx(D,{variant:T===ye?"default":"outline",size:"sm",onClick:()=>J(ye),className:`w-9 h-9 p-0 ${T===ye?"bg-re-green hover:bg-re-green/90 text-white":""}`,"data-testid":`page-${ye}-button`,children:ye},ye)})}),e.jsx(D,{variant:"outline",size:"sm",onClick:()=>J(T+1),disabled:T===k,"data-testid":"next-page-button",children:"Next"})]})]})]})})]})]})]})}function wS({open:t,onClose:s,success:a,message:r}){return e.jsx(et,{open:t,onOpenChange:s,children:e.jsxs(Ze,{className:"sm:max-w-md",children:[e.jsxs(tt,{children:[e.jsxs(Xe,{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(D,{onClick:s,className:"w-full",children:a?"Done":"Close"})})]})})}const CS=async()=>(await ne.get("/user/preferences/notifications")).data.data,SS=async t=>(await ne.put("/user/preferences/notifications",t)).data.data;function AS({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 CS();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,C;try{l(g),u(null),d(null);const f={[g]:y},j=await SS(f);r(j),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(((C=(v=f.response)==null?void 0:v.data)==null?void 0:C.message)||"Failed to update notification preference"),h()}finally{l(null)}};return e.jsx(et,{open:t,onOpenChange:s,children:e.jsxs(Ze,{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(Xe,{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(ct,{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(Li,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(Z,{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(Z,{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(gs,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(Z,{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(ct,{}),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 TS(){const{user:t}=Mt(),s=Xs(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 xf();p(f.length>0)}catch(f){console.error("Failed to check subscription status:",f),p(!1)}finally{y(!1)}},C=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 yS(),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 j=(f==null?void 0:f.message)||"Unknown error occurred";l(j.includes("permission")?"Notification permission was denied. Please enable notifications in your browser settings and try again.":j.includes("Service worker")?"Service worker registration failed. Please refresh the page and try again.":j.includes("token")?"Authentication required. Please log in again and try enabling notifications.":`Unable to enable push notifications: ${j}`),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(W,{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(K,{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(Qr,{defaultValue:"user",className:"w-full",children:[e.jsxs(Jr,{className:"grid w-full grid-cols-2 lg:grid-cols-4 mb-8 bg-slate-100 p-1 rounded-xl h-auto gap-1",children:[e.jsxs(pt,{value:"user",className:"flex items-center justify-center gap-2 py-3 rounded-lg data-[state=active]:bg-white data-[state=active]:shadow-md transition-all",children:[e.jsx(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(pt,{value:"roles",className:"flex items-center justify-center gap-2 py-3 rounded-lg data-[state=active]:bg-white data-[state=active]:shadow-md transition-all",children:[e.jsx(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(pt,{value:"system",className:"flex items-center justify-center gap-2 py-3 rounded-lg data-[state=active]:bg-white data-[state=active]:shadow-md transition-all",children:[e.jsx(wd,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Configuration"}),e.jsx("span",{className:"sm:hidden",children:"Config"})]}),e.jsxs(pt,{value:"holidays",className:"flex items-center justify-center gap-2 py-3 rounded-lg data-[state=active]:bg-white data-[state=active]:shadow-md transition-all",children:[e.jsx(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(xt,{value:"user",className:"mt-0 space-y-0",children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6",children:[e.jsxs(W,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ee,{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(te,{className:"text-lg font-semibold text-gray-900",children:"Browser Push Setup"}),e.jsx(pe,{className:"text-sm text-gray-600",children:"Register this browser for push notifications"})]})]})}),e.jsx(K,{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(D,{onClick:C,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(W,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ee,{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(te,{className:"text-lg font-semibold text-gray-900",children:"Security"}),e.jsx(pe,{className:"text-sm text-gray-600",children:"Password and security settings"})]})]})}),e.jsx(K,{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(W,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ee,{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(te,{className:"text-lg font-semibold text-gray-900",children:"Appearance"}),e.jsx(pe,{className:"text-sm text-gray-600",children:"Theme and display preferences"})]})]})}),e.jsx(K,{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(W,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ee,{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(te,{className:"text-lg font-semibold text-gray-900",children:"Preferences"}),e.jsx(pe,{className:"text-sm text-gray-600",children:"Notification and application preferences"})]})]})}),e.jsx(K,{children:e.jsxs(D,{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(xt,{value:"roles",className:"mt-0",children:e.jsx(NS,{})}),e.jsx(xt,{value:"system",className:"mt-0",children:e.jsx(vS,{})}),e.jsx(xt,{value:"holidays",className:"mt-0",children:e.jsx(bS,{})})]})]}):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(W,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ee,{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(te,{className:"text-lg font-semibold text-gray-900",children:"Browser Push Setup"}),e.jsx(pe,{className:"text-sm text-gray-600",children:"Register this browser for push notifications"})]})]})}),e.jsx(K,{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(D,{onClick:C,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(W,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ee,{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(te,{className:"text-lg font-semibold text-gray-900",children:"Security"}),e.jsx(pe,{className:"text-sm text-gray-600",children:"Password and security settings"})]})]})}),e.jsx(K,{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(W,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ee,{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(te,{className:"text-lg font-semibold text-gray-900",children:"Appearance"}),e.jsx(pe,{className:"text-sm text-gray-600",children:"Theme and display preferences"})]})]})}),e.jsx(K,{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(W,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ee,{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(te,{className:"text-lg font-semibold text-gray-900",children:"Preferences"}),e.jsx(pe,{className:"text-sm text-gray-600",children:"Notification and application preferences"})]})]})}),e.jsx(K,{children:e.jsxs(D,{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(wS,{open:a,onClose:()=>r(!1),success:n,message:o}),e.jsx(AS,{open:m,onClose:()=>u(!1)})]})}function kS({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(F=i,N=u==="unread")=>{var A,I;try{n(F===1);const V=await Ds.list({page:F,limit:y,unreadOnly:N}),_=((A=V.data)==null?void 0:A.notifications)||[],L=((I=V.data)==null?void 0:I.total)||0;a(_),m(L),c(Math.ceil(L/y))}catch(V){console.error("[Notifications] Failed to fetch:",V)}finally{n(!1),g(!1)}};x.useEffect(()=>{v(1,u==="unread")},[u]);const C=async F=>{var N;try{if(F.isRead||(await Ds.markAsRead(F.notificationId),a(A=>A.map(I=>I.notificationId===F.notificationId?{...I,isRead:!0}:I))),F.actionUrl&&t){const A=(N=F.metadata)==null?void 0:N.requestNumber;if(A){let I=`request/${A}`;(F.notificationType==="mention"||F.notificationType==="comment"||F.notificationType==="worknote")&&(I+="?tab=worknotes"),t(I)}}}catch(A){console.error("[Notifications] Error handling notification click:",A)}},f=async()=>{try{g(!0),await Ds.markAllAsRead(),await v(i,u==="unread")}catch(F){console.error("[Notifications] Error marking all as read:",F),g(!1)}},j=async F=>{try{await Ds.delete(F),a(N=>N.filter(A=>A.notificationId!==F)),m(N=>N-1)}catch(N){console.error("[Notifications] Error deleting notification:",N)}},b=()=>{g(!0),v(i,u==="unread")},w=F=>{F<1||F>l||(o(F),v(F,u==="unread"))},T=F=>{const N="w-6 h-6";switch(F){case"mention":case"comment":return e.jsx(gs,{className:`${N} text-blue-600`});case"worknote":return e.jsx(Se,{className:`${N} text-purple-600`});case"assignment":return e.jsx(qr,{className:`${N} text-indigo-600`});case"approval":return e.jsx(je,{className:`${N} text-green-600`});case"rejection":return e.jsx(Je,{className:`${N} text-red-600`});case"tat_alert":return e.jsx(Ee,{className:`${N} text-orange-600`});case"tat_breach":return e.jsx(Pe,{className:`${N} text-red-600`});case"tat_breach_initiator":return e.jsx(is,{className:`${N} text-amber-600`});default:return e.jsx(Ft,{className:`${N} text-gray-600`})}},R=F=>{switch(F==null?void 0:F.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"}},k=s.filter(F=>!F.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":"",k>0&&` • ${k} unread`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(D,{variant:"outline",size:"sm",onClick:b,disabled:p,className:"gap-2",children:[e.jsx(Et,{className:`w-4 h-4 ${p?"animate-spin":""}`}),"Refresh"]}),k>0&&e.jsxs(D,{variant:"outline",size:"sm",onClick:f,disabled:p,className:"gap-2",children:[e.jsx(Rx,{className:"w-4 h-4"}),"Mark All Read"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(D,{variant:u==="all"?"default":"outline",size:"sm",onClick:()=>{h("all"),o(1)},children:"All Notifications"}),e.jsxs(D,{variant:u==="unread"?"default":"outline",size:"sm",onClick:()=>{h("unread"),o(1)},children:["Unread",k>0&&e.jsx(X,{className:"ml-2 bg-red-500 text-white",children:k})]})]}),e.jsxs(W,{children:[e.jsxs(ee,{children:[e.jsx(te,{children:"Recent Activity"}),e.jsx(pe,{children:"Stay updated with all your workflow activities and mentions"})]}),e.jsx(K,{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(F=>{var N;return e.jsx("div",{className:`p-4 rounded-lg border transition-all cursor-pointer hover:shadow-md ${F.isRead?"bg-white border-gray-200 hover:bg-gray-50":"bg-blue-50 border-blue-200 hover:bg-blue-100"}`,onClick:()=>C(F),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"shrink-0 mt-0.5",children:T(F.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 ${F.isRead?"font-semibold":"font-bold"} text-gray-900`,children:F.title}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[F.priority&&F.priority!=="LOW"&&e.jsx(X,{variant:"outline",className:`text-xs ${R(F.priority)}`,children:F.priority}),!F.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:F.message}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:[od(new Date(F.createdAt),{addSuffix:!0}),((N=F.metadata)==null?void 0:N.requestNumber)&&e.jsxs("span",{className:"ml-2",children:["• ",F.metadata.requestNumber]})]}),e.jsx(D,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-600",onClick:A=>{A.stopPropagation(),j(F.notificationId)},children:e.jsx(Bi,{className:"w-3.5 h-3.5"})})]})]})]})},F.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(D,{variant:"outline",size:"sm",onClick:()=>w(i-1),disabled:i===1,children:[e.jsx(jd,{className:"w-4 h-4"}),"Previous"]}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,l)},(F,N)=>{let A;return l<=5||i<=3?A=N+1:i>=l-2?A=l-4+N:A=i-2+N,e.jsx(D,{variant:i===A?"default":"outline",size:"sm",className:"w-9 h-9 p-0",onClick:()=>w(A),children:A},A)})}),e.jsxs(D,{variant:"outline",size:"sm",onClick:()=>w(i+1),disabled:i===l,children:["Next",e.jsx($i,{className:"w-4 h-4"})]})]})]})]})}function RS({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(D,{variant:"outline",onClick:t,className:"inline-flex items-center gap-2","data-testid":"back-button",children:[e.jsx(us,{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(Se,{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 Lo({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?`${he(s,"MMM d, yyyy")} - ${he(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(Ae,{value:t,onValueChange:o,"data-testid":`${h}-select`,children:[e.jsx(ke,{className:"w-[160px]",children:e.jsx(Te,{placeholder:"Date Range"})}),e.jsxs(Re,{children:[e.jsx(O,{value:"today",children:"Today"}),e.jsx(O,{value:"week",children:"This Week"}),e.jsx(O,{value:"month",children:"This Month"}),e.jsx(O,{value:"custom",children:"Custom Range"})]})]}),t==="custom"&&e.jsxs(Es,{open:r,onOpenChange:l,children:[e.jsx(Ms,{asChild:!0,children:e.jsxs(D,{variant:"outline",size:"sm",className:"gap-2","data-testid":`${h}-custom-trigger`,children:[e.jsx(We,{className:"w-4 h-4"}),p]})}),e.jsx(Is,{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(Z,{htmlFor:`${h}-start-date`,className:"text-sm font-medium",children:"Start Date"}),e.jsx(xe,{id:`${h}-start-date`,type:"date",value:n?he(n,"yyyy-MM-dd"):"",onChange:g=>{const y=g.target.value?new Date(g.target.value):void 0;c(y)},max:he(new Date,"yyyy-MM-dd"),className:"w-full","data-testid":`${h}-start-input`})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Z,{htmlFor:`${h}-end-date`,className:"text-sm font-medium",children:"End Date"}),e.jsx(xe,{id:`${h}-end-date`,type:"date",value:i?he(i,"yyyy-MM-dd"):"",onChange:g=>{const y=g.target.value?new Date(g.target.value):void 0;d(y)},min:n?he(n,"yyyy-MM-dd"):void 0,max:he(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(D,{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(D,{size:"sm",variant:"outline",onClick:u,"data-testid":`${h}-cancel-button`,children:"Cancel"})]})]})})]})]})}function PS(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 fh(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 yh(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 DS(t){return t>=20?"bg-red-600":t>=10?"bg-orange-500":"bg-amber-500"}function ES({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:C,onPageChange:f,onExport:j,onViewRequest:b}){return e.jsxs(W,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"request-lifecycle-report",children:[e.jsxs(ee,{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(te,{className:"text-lg text-gray-900",children:"Request Lifecycle Report"}),e.jsx(pe,{className:"text-gray-600",children:"End-to-end workflow status including all approval levels, approvers, dates, and TAT compliance"})]})]}),e.jsxs(D,{variant:"outline",size:"sm",className:"gap-2",onClick:j,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(Lo,{dateRange:i,customStartDate:o,customEndDate:l,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,onDateRangeChange:h,onShowCustomDatePickerChange:p,onStartDateChange:g,onEndDateChange:y,onApply:v,onCancel:C,testIdPrefix:"lifecycle"})})]}),e.jsxs(K,{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(w=>e.jsx("div",{className:"border rounded-xl overflow-hidden","data-testid":`lifecycle-request-${w.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(w.requestId||w.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:T=>{T.stopPropagation(),b(w.requestId||w.id)},className:"font-semibold text-sm text-blue-600 hover:text-blue-800 hover:underline cursor-pointer transition-colors","data-testid":`lifecycle-request-link-${w.id}`,children:w.id}),e.jsx(X,{className:fh(w.priority),"data-testid":`lifecycle-priority-${w.id}`,children:w.priority}),e.jsx(X,{className:yh(w.status),"data-testid":`lifecycle-status-${w.id}`,children:w.status})]}),e.jsx("p",{className:"text-sm text-gray-700",children:w.title}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["Initiated by ",e.jsx("span",{className:"font-medium",children:w.initiator})," on ",w.initDate]}),w.currentStage&&!w.currentStage.includes("Level")&&e.jsxs("p",{className:"text-xs text-gray-400 mt-0.5",children:["Stage: ",w.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:w.currentStage}),e.jsxs("p",{className:"text-xs text-gray-400 mt-0.5",children:["(Level ",w.currentLevel,"/",w.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:w.overallTAT}),w.breachCount>0&&e.jsxs("p",{className:"text-xs text-red-500 mt-0.5",children:[w.breachCount," breach",w.breachCount>1?"es":""]})]}),e.jsx(D,{variant:"ghost",size:"sm",onClick:()=>b(w.requestId||w.id),className:"gap-1.5","data-testid":`lifecycle-view-button-${w.id}`,children:e.jsx($i,{className:"w-4 h-4"})})]})]})})},w.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(D,{variant:"outline",size:"sm",onClick:()=>f(n.page-1),disabled:n.page<=1||a,"data-testid":"lifecycle-pagination-prev",children:"Previous"}),e.jsx(D,{variant:"outline",size:"sm",onClick:()=>f(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"lifecycle-pagination-next",children:"Next"})]})]})]})]})}function Oo({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:le("w-full caption-bottom text-sm",t),...s})})}function $o({className:t,...s}){return e.jsx("thead",{"data-slot":"table-header",className:le("[&_tr]:border-b",t),...s})}function Uo({className:t,...s}){return e.jsx("tbody",{"data-slot":"table-body",className:le("[&_tr:last-child]:border-0",t),...s})}function ca({className:t,...s}){return e.jsx("tr",{"data-slot":"table-row",className:le("hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",t),...s})}function gt({className:t,...s}){return e.jsx("th",{"data-slot":"table-head",className:le("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 mt({className:t,...s}){return e.jsx("td",{"data-slot":"table-cell",className:le("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",t),...s})}function MS({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:C,onApplyCustomDate:f,onCancelCustomDate:j,onCategoryChange:b,onSeverityChange:w,onClearFilters:T,onPageChange:R,onExport:k,onViewRequest:F}){const N=u!=="all"||h!=="all"||i!=="month"||o||l;return e.jsxs(W,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"user-activity-log-report",children:[e.jsxs(ee,{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(Px,{className:"h-5 w-5 text-indigo-600"})}),e.jsxs("div",{children:[e.jsx(te,{className:"text-lg text-gray-900",children:"User Activity Log Report"}),e.jsx(pe,{className:"text-gray-600",children:"Consolidated user actions and activity history"})]})]}),e.jsxs(D,{variant:"outline",size:"sm",className:"gap-2",onClick:k,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(Lo,{dateRange:i,customStartDate:o,customEndDate:l,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,onDateRangeChange:g,onShowCustomDatePickerChange:y,onStartDateChange:v,onEndDateChange:C,onApply:f,onCancel:j,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(Ae,{value:u,onValueChange:b,"data-testid":"activity-category-filter",children:[e.jsx(ke,{className:"w-40",children:e.jsx(Te,{placeholder:"All Categories"})}),e.jsxs(Re,{children:[e.jsx(O,{value:"all",children:"All Categories"}),e.jsx(O,{value:"WORKFLOW",children:"Workflow"}),e.jsx(O,{value:"COLLABORATION",children:"Collaboration"}),e.jsx(O,{value:"DOCUMENT",children:"Document"}),e.jsx(O,{value:"AUTHENTICATION",children:"Authentication"}),e.jsx(O,{value:"SYSTEM",children:"System"}),e.jsx(O,{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(Ae,{value:h,onValueChange:w,"data-testid":"activity-severity-filter",children:[e.jsx(ke,{className:"w-40",children:e.jsx(Te,{placeholder:"All Severities"})}),e.jsxs(Re,{children:[e.jsx(O,{value:"all",children:"All Severities"}),e.jsx(O,{value:"INFO",children:"Info"}),e.jsx(O,{value:"WARNING",children:"Warning"}),e.jsx(O,{value:"ERROR",children:"Error"}),e.jsx(O,{value:"CRITICAL",children:"Critical"})]})]})]}),N&&e.jsx(D,{variant:"ghost",size:"sm",onClick:T,className:"text-xs","data-testid":"activity-clear-filters",children:"Clear Filters"})]})]}),e.jsx(K,{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(Oo,{children:[e.jsx($o,{children:e.jsxs(ca,{className:"bg-gray-50",children:[e.jsx(gt,{className:"font-semibold",children:"Timestamp"}),e.jsx(gt,{className:"font-semibold",children:"User"}),e.jsx(gt,{className:"font-semibold",children:"Action"}),e.jsx(gt,{className:"font-semibold",children:"Details"}),e.jsx(gt,{className:"font-semibold",children:"IP Address"}),e.jsx(gt,{className:"font-semibold",children:"Request ID"})]})}),e.jsx(Uo,{children:t.map((A,I)=>e.jsxs(ca,{className:"hover:bg-gray-50","data-testid":`activity-row-${I}`,children:[e.jsx(mt,{className:"text-xs font-medium",children:A.timestamp}),e.jsx(mt,{className:"text-sm",children:A.user}),e.jsx(mt,{children:e.jsx(X,{className:PS(A.action),"data-testid":`activity-action-${I}`,children:A.action})}),e.jsx(mt,{className:"text-sm text-gray-600",children:A.details}),e.jsx(mt,{className:"text-xs font-mono text-gray-500",children:A.ip&&A.ip!=="N/A"?e.jsx("span",{title:A.userAgent||"",children:A.ip}):e.jsx("span",{className:"text-gray-400 italic",title:"IP address not yet captured",children:"N/A"})}),e.jsx(mt,{children:A.requestId!=="-"&&A.requestId!=="System Login"?e.jsx("button",{onClick:()=>{const V=A.requestId;V&&F(V)},className:"hover:underline","data-testid":`activity-request-link-${I}`,children:e.jsx(X,{variant:"outline",className:"text-xs cursor-pointer hover:bg-blue-50 hover:border-blue-300 transition-colors",children:A.requestId})}):e.jsx("span",{className:"text-xs text-gray-400",children:"-"})})]},I))})]}),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(D,{variant:"outline",size:"sm",onClick:()=>R(n.page-1),disabled:n.page<=1||a,"data-testid":"activity-pagination-prev",children:"Previous"}),e.jsx(D,{variant:"outline",size:"sm",onClick:()=>R(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"activity-pagination-next",children:"Next"})]})]})]})})]})}function IS({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:C,onShowCustomDatePickerChange:f,onStartDateChange:j,onEndDateChange:b,onApplyCustomDate:w,onCancelCustomDate:T,onSearchChange:R,onPageChange:k,onExport:F,onViewRequest:N}){return e.jsxs(W,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"workflow-aging-report",children:[e.jsxs(ee,{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(Ui,{className:"h-5 w-5 text-amber-600"})}),e.jsxs("div",{children:[e.jsx(te,{className:"text-lg text-gray-900",children:"Workflow Aging Report"}),e.jsx(pe,{className:"text-gray-600",children:"Workflows exceeding aging threshold"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-sm text-gray-600 whitespace-nowrap",children:"Threshold:"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{type:"number",min:"1",value:i,onChange:A=>y(A.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(X,{variant:"outline",className:"font-semibold","data-testid":"aging-total-badge",children:[n.totalRecords," workflows"]}),e.jsxs(D,{variant:"outline",size:"sm",className:"gap-2",onClick:F,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(Lo,{dateRange:l,customStartDate:c,customEndDate:d,showCustomDatePicker:m,tempCustomStartDate:u,tempCustomEndDate:h,onDateRangeChange:C,onShowCustomDatePickerChange:f,onStartDateChange:j,onEndDateChange:b,onApply:w,onCancel:T,testIdPrefix:"aging"}),e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(xe,{placeholder:"Search by Request ID, Title, or Initiator...",value:p,onChange:A=>R(A.target.value),className:"pl-10","data-testid":"aging-search-input"})]})]})]}),e.jsx(K,{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(Oo,{children:[e.jsx($o,{children:e.jsxs(ca,{className:"bg-gray-50",children:[e.jsx(gt,{className:"font-semibold",children:"Request ID"}),e.jsx(gt,{className:"font-semibold",children:"Title"}),e.jsx(gt,{className:"font-semibold",children:"Initiator"}),e.jsx(gt,{className:"font-semibold",children:"Start Date"}),e.jsx(gt,{className:"font-semibold",children:"Days Open"}),e.jsx(gt,{className:"font-semibold",children:"Current Stage"}),e.jsx(gt,{className:"font-semibold",children:"Assigned To"}),e.jsx(gt,{className:"font-semibold",children:"Priority"}),e.jsx(gt,{className:"font-semibold",children:"Status"})]})}),e.jsx(Uo,{children:t.map(A=>e.jsxs(ca,{className:"hover:bg-gray-50","data-testid":`aging-workflow-${A.id}`,children:[e.jsx(mt,{className:"font-medium text-sm",children:e.jsx("button",{onClick:()=>N(A.requestId||A.id),className:"text-blue-600 hover:text-blue-800 hover:underline cursor-pointer transition-colors","data-testid":`aging-request-link-${A.id}`,children:A.id})}),e.jsx(mt,{className:"text-sm",children:A.title}),e.jsx(mt,{className:"text-sm",children:A.initiator}),e.jsx(mt,{className:"text-sm text-gray-600",children:A.startDate}),e.jsx(mt,{children:e.jsxs(X,{className:`${DS(A.daysOpen)} text-white border-transparent`,"data-testid":`aging-days-${A.id}`,children:[A.daysOpen," days",e.jsx("span",{className:"ml-1 text-xs opacity-75",children:"(business)"})]})}),e.jsx(mt,{className:"text-sm",children:A.currentStage}),e.jsx(mt,{className:"text-sm",children:A.assignedTo&&A.assignedTo!=="N/A"?A.assignedTo:e.jsx("span",{className:"text-gray-400 italic",title:"Assigned approver not available",children:"N/A"})}),e.jsx(mt,{children:e.jsx(X,{className:fh(A.priority),"data-testid":`aging-priority-${A.id}`,children:A.priority})}),e.jsx(mt,{children:e.jsx(X,{className:yh(A.status),"data-testid":`aging-status-${A.id}`,children:A.status})})]},A.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(D,{variant:"outline",size:"sm",onClick:()=>k(n.page-1),disabled:n.page<=1||a,"data-testid":"aging-pagination-prev",children:"Previous"}),e.jsx(D,{variant:"outline",size:"sm",onClick:()=>k(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"aging-pagination-next",children:"Next"})]})]})]})})]})}function Xn(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 w=b;a(w),w!=="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]),C=x.useCallback(b=>{b?(h(b),d&&b<d&&m(b)):h(void 0)},[d]),f=x.useCallback(()=>r&&i?`${he(r,"MMM d, yyyy")} - ${he(i,"MMM d, yyyy")}`:"Select dates",[r,i]),j=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:C,getDisplayDateRange:f,reset:j}}function FS(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 vh(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 bh(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 LS({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 C=await He.getLifecycleReport(y,_S,t,s,a),f=C.lifecycleData.map(j=>{const b=FS(j.overallTATHours);return{id:j.requestNumber,requestId:j.requestId,title:j.title,priority:j.priority||"medium",status:j.status,initiator:j.initiatorName||"Unknown",initDate:vh(j.submissionDate),currentStage:j.currentStageName||`Level ${j.currentLevel}`,overallTAT:b,currentLevel:j.currentLevel,totalLevels:j.totalLevels,breachCount:j.breachCount||0}});n(f),h({page:C.pagination.currentPage,totalPages:C.pagination.totalPages,totalRecords:C.pagination.totalRecords})}catch(C){console.error("Failed to fetch lifecycle data:",C),m((C==null?void 0:C.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 OS=20;function $S({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(C=1)=>{const f=C===1&&y.current;try{f?c(!0):m(!0),h(null);const j=await He.getActivityLogReport(C,OS,t,void 0,void 0,r&&r!=="all"?r:void 0,n&&n!=="all"?n:void 0,s,a),b=j.activities.map(w=>{const T=bh(w.type||"",w.details),R=(w.type||"").toLowerCase()==="login"||w.requestId==="00000000-0000-0000-0000-000000000001"||w.requestId==="SYSTEM_LOGIN",k=R?w.details||"User login":w.requestTitle||w.requestNumber||w.details||"N/A";return{timestamp:w.timestamp?vh(w.timestamp):"N/A",user:w.userName||"Unknown",action:T,details:k,ip:w.ipAddress||"N/A",userAgent:w.userAgent||null,requestId:R?"System Login":w.requestNumber||w.requestId||"-",userId:w.userId}});o(b),g({page:j.pagination.currentPage,totalPages:j.pagination.totalPages,totalRecords:j.pagination.totalRecords})}catch(j){console.error("Failed to fetch activity data:",j),h((j==null?void 0:j.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 US=20;function BS({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 j=f===1&&y.current;try{j?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 w=await He.getWorkflowAgingReport(b,f,US,s,a,r),T=w.agingData.map(R=>({id:R.requestNumber||R.requestId,requestId:R.requestId,title:R.title,initiator:R.initiatorName||"Unknown",startDate:R.submissionDate?new Date(R.submissionDate).toLocaleDateString():"N/A",daysOpen:R.daysOpen,currentStage:R.currentStageName||`Level ${R.currentLevel}`,assignedTo:R.currentApproverName||"N/A",priority:R.priority||"medium",status:R.status||"pending"}));o(T),g({page:w.pagination.currentPage,totalPages:w.pagination.totalPages,totalRecords:w.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{j?c(!1):m(!1)}j&&(y.current=!1)},[t,s,a,r]),C=x.useMemo(()=>i.filter(f=>{var b,w,T;if(!n)return!0;const j=n.toLowerCase();return((b=f.id)==null?void 0:b.toLowerCase().includes(j))||((w=f.title)==null?void 0:w.toLowerCase().includes(j))||((T=f.initiator)==null?void 0:T.toLowerCase().includes(j))}),[i,n]);return x.useEffect(()=>{s==="custom"&&(!a||!r)||v(1)},[t,s,a,r]),{agingWorkflows:C,loading:l,loadingPage:d,error:u,pagination:p,fetchData:v}}function VS(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 zS(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",C=g.tatHours||0,f=g.tatDays||(C>0?(C/8).toFixed(2):"0");let j="N/A",b="N/A",w="N/A",T="N/A";if(g.levelStartTime){const k=new Date(g.levelStartTime);if(b=(((g.levelEndTime||g.completedAt?new Date(g.levelEndTime||g.completedAt):new Date).getTime()-k.getTime())/(1e3*60*60)).toFixed(2),C>0){const A=parseFloat(b);w=Math.max(0,C-A).toFixed(2),T=(A/C*100).toFixed(2),g.status==="APPROVED"||g.status==="REJECTED"?j=A<=C?"Compliant":"Breached":g.status==="IN_PROGRESS"||g.status==="PENDING"?j=A<=C?"On Track":"At Risk":j="N/A"}}const R=[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,C.toString(),f.toString(),j,b,w,T];n.push(R.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(","))}Bo(n,`lifecycle-report-end-to-end-${new Date().toISOString().split("T")[0]}.csv`)}async function HS(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=bh(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(","))}),Bo(o,`activity-log-report-${new Date().toISOString().split("T")[0]}.csv`)}async function qS(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(","))}),Bo(i,`workflow-aging-report-${new Date().toISOString().split("T")[0]}.csv`)}function Bo(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 WS(){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 zS(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 HS(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 qS(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 KS({onBack:t}){const s=Hs(),[a,r]=x.useState(""),[n,i]=x.useState("all"),[o,l]=x.useState("all"),c=Xn("month"),d=Xn("month"),m=Xn("month"),u=VS("7"),h=LS({dateRange:c.dateRange,customStartDate:c.customStartDate,customEndDate:c.customEndDate}),p=$S({dateRange:d.dateRange,customStartDate:d.customStartDate,customEndDate:d.customEndDate,filterCategory:n,filterSeverity:o}),g=BS({threshold:u.threshold,dateRange:m.dateRange,customStartDate:m.customStartDate,customEndDate:m.customEndDate,searchQuery:a}),y=WS(),v=x.useCallback(()=>{t?t():s("/dashboard")},[t,s]),C=x.useCallback(T=>{s(`/request/${T}`)},[s]),f=x.useCallback(()=>{y.handleExportLifecycle(c.dateRange,c.customStartDate,c.customEndDate)},[y,c]),j=x.useCallback(()=>{y.handleExportActivity(d.dateRange,d.customStartDate,d.customEndDate,n,o)},[y,d,n,o]),b=x.useCallback(()=>{const T=parseInt(u.threshold,10);!isNaN(T)&&T>=1&&y.handleExportAging(T,m.dateRange,m.customStartDate,m.customEndDate)},[y,u.threshold,m]),w=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(RS,{onBack:v}),e.jsx(ES,{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:C}),e.jsx(MS,{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:w,onPageChange:p.fetchData,onExport:j,onViewRequest:C}),e.jsx(IS,{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:C})]})})}function GS({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(Z,{htmlFor:"default-period",children:"Default Reporting Period"}),e.jsxs(Ae,{value:t,onValueChange:a,children:[e.jsx(ke,{id:"default-period",children:e.jsx(Te,{})}),e.jsx(Re,{children:n.map(i=>e.jsx(O,{value:i,children:i},i))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Z,{htmlFor:"refresh-interval",children:"Auto-Refresh Interval (minutes)"}),e.jsx(xe,{id:"refresh-interval",type:"number",min:"1",max:"60",value:s,onChange:i=>r(parseInt(i.target.value)||5)})]})]})}function YS({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 ZS=["CSV","Excel","PDF","JSON"];function XS({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(Z,{children:"Allowed Export Formats"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:ZS.map(r=>e.jsxs("div",{className:"flex items-center space-x-2 p-2 bg-muted/50 rounded",children:[e.jsx(Ki,{id:`export-${r}`,checked:t.includes(r),onCheckedChange:n=>a(r,n)}),e.jsx(Z,{htmlFor:`export-${r}`,className:"text-sm cursor-pointer",children:r})]},r))})]})}function QS({dataRetention:t,onDataRetentionChange:s}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(Z,{htmlFor:"data-retention",children:"Historical Data Retention (months)"}),e.jsx(xe,{id:"data-retention",type:"number",min:"1",max:"120",value:t,onChange:a=>s(parseInt(a.target.value)||24)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Analytics data older than this will be archived or deleted"})]})}function JS(){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(W,{children:[e.jsxs(ee,{children:[e.jsx(te,{children:"Analytics & Reporting Configuration"}),e.jsx(pe,{children:"Configure default reporting periods, auto-refresh, export settings, and data retention"})]}),e.jsxs(K,{className:"space-y-6",children:[e.jsx(GS,{defaultPeriod:t.defaultPeriod,refreshInterval:t.refreshInterval,onDefaultPeriodChange:n=>r({defaultPeriod:n}),onRefreshIntervalChange:n=>r({refreshInterval:n})}),e.jsx(ct,{}),e.jsx(YS,{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(ct,{}),e.jsx(XS,{exportFormats:t.exportFormats,onExportFormatsChange:n=>r({exportFormats:n})}),e.jsx(QS,{dataRetention:t.dataRetention,onDataRetentionChange:n=>r({dataRetention:n})}),e.jsxs(D,{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 eA=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"}},tA=t=>t.split(" ").map(s=>s[0]).join("").toUpperCase().substring(0,2);function sA({users:t,onEdit:s,onToggleStatus:a,onDelete:r}){return e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(Oo,{children:[e.jsx($o,{children:e.jsxs(ca,{children:[e.jsx(gt,{children:"User"}),e.jsx(gt,{children:"Role"}),e.jsx(gt,{children:"Department"}),e.jsx(gt,{children:"Status"}),e.jsx(gt,{className:"text-right",children:"Actions"})]})}),e.jsx(Uo,{children:t.length===0?e.jsx(ca,{children:e.jsx(mt,{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(mt,{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:tA(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(mt,{children:e.jsx(X,{className:eA(n.role),children:n.role})}),e.jsx(mt,{children:n.department}),e.jsx(mt,{children:e.jsxs(X,{className:"bg-green-100 text-green-800 border-green-200",children:[e.jsx(ei,{className:"w-3 h-3 mr-1"}),n.status]})}),e.jsx(mt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(D,{variant:"ghost",size:"sm",onClick:()=>s(n.id),className:"h-8",children:e.jsx(Gr,{className:"w-4 h-4"})}),e.jsx(D,{variant:"ghost",size:"sm",onClick:()=>a(n.id),disabled:n.role.toUpperCase()==="ADMIN",className:"h-8",children:e.jsx(Dx,{className:"w-4 h-4"})}),e.jsx(D,{variant:"ghost",size:"sm",onClick:()=>r(n.id),disabled:n.role.toUpperCase()==="ADMIN",className:"h-8 text-destructive hover:text-destructive",children:e.jsx(Bi,{className:"w-4 h-4"})})]})})]},n.id))})]})})}function aA({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 rA(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function nA(){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,C]=x.useState([]),[f,j]=x.useState(!1),[b,w]=x.useState({admins:0,management:0,users:0,total:0,active:0,inactive:0}),[T,R]=x.useState("ELEVATED"),[k,F]=x.useState(1),[N,A]=x.useState(1),[I,V]=x.useState(0),_=10,L=x.useRef(null),S=x.useCallback(rA(async G=>{var Q,ie,Y;if(!G||!G.startsWith("@")||G.length<2){r([]),i(!1);return}i(!0);try{const ue=G.slice(1),$e=((Q=(await Gt.searchUsers(ue,20)).data)==null?void 0:Q.data)||[];r($e)}catch(ue){console.error("Search failed:",ue),y({type:"error",text:((Y=(ie=ue.response)==null?void 0:ie.data)==null?void 0:Y.message)||"Failed to search users"})}finally{i(!1)}},300),[]),M=G=>{const Q=G.target.value;s(Q),S(Q)},P=async G=>{var Q,ie;try{const Y=v.find(Ie=>Ie.email.toLowerCase()===G.toLowerCase());if(Y)return Y.role;const $e=(((ie=(Q=(await Gt.getUsersByRole("ALL",1,1e3)).data)==null?void 0:Q.data)==null?void 0:ie.users)||[]).find(Ie=>{var ae;return((ae=Ie.email)==null?void 0:ae.toLowerCase())===G.toLowerCase()});return $e&&$e.role?$e.role:null}catch(Y){return console.error("Failed to fetch user role:",Y),null}},E=async G=>{l(G),s(G.email),r([]),p(!0);try{const Q=await P(G.email);d(Q||"USER")}catch(Q){console.error("Failed to fetch user role:",Q),d("USER")}finally{p(!1)}},H=async()=>{var G,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 q(),await J(),be.success("Role assigned successfully")}catch(ie){console.error("Role assignment failed:",ie);const Y=((Q=(G=ie.response)==null?void 0:G.data)==null?void 0:Q.error)||"Failed to assign role";y({type:"error",text:Y}),be.error(Y)}finally{u(!1)}},q=async(G=k)=>{var Q,ie,Y,ue,Me,$e;j(!0);try{const Ie=await Gt.getUsersByRole(T,G,_),ae=((ie=(Q=Ie.data)==null?void 0:Q.data)==null?void 0:ie.users)||[],fe=(ue=(Y=Ie.data)==null?void 0:Y.data)==null?void 0:ue.pagination,Ve=($e=(Me=Ie.data)==null?void 0:Me.data)==null?void 0:$e.summary;C(ae.map(_e=>({userId:_e.userId,email:_e.email,displayName:_e.displayName||_e.email,role:_e.role||"USER",department:_e.department,designation:_e.designation,isActive:_e.isActive!==!1}))),fe&&(F(fe.currentPage),A(fe.totalPages),V(fe.totalUsers)),Ve&&w(_e=>({..._e,admins:Ve.ADMIN||0,management:Ve.MANAGEMENT||0,users:Ve.USER||0,total:(Ve.ADMIN||0)+(Ve.MANAGEMENT||0)+(Ve.USER||0)}))}catch(Ie){console.error("Failed to fetch users:",Ie),be.error("Failed to load users")}finally{j(!1)}},J=async()=>{var G,Q,ie,Y,ue,Me;try{const $e=await Gt.getRoleStatistics(),Ie=((Q=(G=$e.data)==null?void 0:G.data)==null?void 0:Q.statistics)||((ie=$e.data)==null?void 0:ie.statistics)||[],ae={admins:parseInt(((Y=Ie.find(fe=>fe.role==="ADMIN"))==null?void 0:Y.count)||"0"),management:parseInt(((ue=Ie.find(fe=>fe.role==="MANAGEMENT"))==null?void 0:ue.count)||"0"),users:parseInt(((Me=Ie.find(fe=>fe.role==="USER"))==null?void 0:Me.count)||"0")};w(fe=>({...fe,...ae,total:ae.admins+ae.management+ae.users,active:fe.active||ae.admins+ae.management+ae.users,inactive:fe.inactive||0}))}catch($e){console.error("Failed to fetch statistics:",$e)}};x.useEffect(()=>{q(1),J()},[T]);const B=G=>{R(G),F(1)},oe=G=>{q(G)},ge=async(G,Q)=>{var ie,Y;try{await Gt.updateUserRole(G,Q),be.success("User role updated successfully"),await q(),await J()}catch(ue){console.error("Failed to update user role:",ue),be.error(((Y=(ie=ue.response)==null?void 0:ie.data)==null?void 0:Y.error)||"Failed to update user role")}},z=async G=>{v.find(ie=>ie.userId===G)&&be.info("User status toggle functionality coming soon")},re=async G=>{const Q=v.find(ie=>ie.userId===G);if(Q){if(Q.role==="ADMIN"){be.error("Cannot delete admin user");return}be.info("User deletion functionality coming soon")}};x.useEffect(()=>{const G=Q=>{L.current&&!L.current.contains(Q.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",G),()=>{document.removeEventListener("mousedown",G)}},[a]);const ye={total:b.total,active:b.active,inactive:b.inactive,admins:b.admins};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(aA,{stats:ye}),e.jsxs(W,{children:[e.jsx(ee,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Assign User Role"}),e.jsx(pe,{children:"Search for a user in Okta and assign them a role"})]}),e.jsx(D,{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(K,{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(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(xe,{type:"text",placeholder:"Type @ to search users...",value:t,onChange:M,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(G=>e.jsxs("button",{onClick:()=>E(G),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:G.displayName||G.email}),e.jsx("p",{className:"text-sm text-muted-foreground",children:G.email}),G.department&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[G.department,G.designation?` • ${G.designation}`:""]})]},G.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(D,{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(Ae,{value:c,onValueChange:G=>d(G),disabled:h,children:[e.jsx(ke,{className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Te,{placeholder:h?"Loading current role...":"Select role"})}),e.jsxs(Re,{className:"rounded-lg",children:[e.jsx(O,{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(O,{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(O,{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(W,{children:[e.jsx(ee,{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(te,{className:"flex items-center gap-2",children:[e.jsx(nt,{className:"w-5 h-5 text-re-green"}),"User Management"]}),e.jsxs(pe,{children:["View and manage user accounts and roles (",I," ",T!=="ALL"&&T!=="ELEVATED"?T.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(Ae,{value:T,onValueChange:B,children:[e.jsx(ke,{className:"w-[200px] border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Te,{placeholder:"Filter by role"})}),e.jsxs(Re,{children:[e.jsx(O,{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(O,{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(O,{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(O,{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(O,{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(K,{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:T==="ELEVATED"?"Assign ADMIN or MANAGEMENT roles to see users here":"No users match the selected filter"})]}):e.jsxs(e.Fragment,{children:[e.jsx(sA,{users:v.map(G=>({id:G.userId,name:G.displayName,email:G.email,role:G.role,department:G.department||"N/A",status:G.isActive?"active":"inactive"})),onEdit:G=>{const Q=v.find(ie=>ie.userId===G);if(Q){const ie=Q.role==="USER"?"MANAGEMENT":Q.role==="MANAGEMENT"?"ADMIN":"USER";ge(G,ie)}},onToggleStatus:z,onDelete:re}),N>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 ",(k-1)*_+1," to ",Math.min(k*_,I)," of ",I," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(D,{variant:"outline",size:"sm",onClick:()=>oe(k-1),disabled:k===1,children:"Previous"}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,N)},(G,Q)=>{let ie;return N<=5||k<=3?ie=Q+1:k>=N-2?ie=N-4+Q:ie=k-2+Q,e.jsx(D,{variant:k===ie?"default":"outline",size:"sm",onClick:()=>oe(ie),className:`w-9 h-9 p-0 ${k===ie?"bg-re-green hover:bg-re-green/90":""}`,children:ie},ie)})}),e.jsx(D,{variant:"outline",size:"sm",onClick:()=>oe(k+1),disabled:k===N,children:"Next"})]})]})]})})]})]})}function iA({expressHours:t,standardHours:s,onExpressChange:a,onStandardChange:r}){return e.jsxs(W,{className:"border-0 shadow-sm",children:[e.jsxs(ee,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_i,{className:"w-5 h-5 text-re-green"}),e.jsx(te,{className:"text-base font-semibold",children:"Priority TAT Settings"})]}),e.jsx(pe,{className:"text-sm",children:"Set default turnaround time in hours for each priority level"})]}),e.jsx(K,{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(Z,{htmlFor:"tat-express",className:"text-sm font-medium",children:"Express Priority (hours)"}),e.jsx(xe,{id:"tat-express",type:"number",min:"1",max:"168",value:t,onChange:n=>a(parseInt(n.target.value)||24),className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ee,{className:"w-3 h-3"}),"Critical/Emergency requests (24/7, includes weekends)"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Z,{htmlFor:"tat-standard",className:"text-sm font-medium",children:"Standard Priority (hours)"}),e.jsx(xe,{id:"tat-standard",type:"number",min:"1",max:"720",value:s,onChange:n=>r(parseInt(n.target.value)||72),className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ee,{className:"w-3 h-3"}),"Regular priority requests (working hours only, excludes weekends & holidays)"]})]})]})})]})}function oA({reminderThreshold1:t,reminderThreshold2:s,onReminderThreshold1Change:a,onReminderThreshold2Change:r}){return e.jsxs(W,{className:"border-0 shadow-sm",children:[e.jsxs(ee,{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(te,{className:"text-base font-semibold",children:"Auto-Reminder & Escalation"})]}),e.jsx(pe,{className:"text-sm",children:"Configure automatic reminder thresholds based on TAT percentage"})]}),e.jsx(K,{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(Z,{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(Ri,{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(Z,{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(Ri,{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 lA({workStartHour:t,workEndHour:s,workStartDay:a,workEndDay:r,onWorkStartHourChange:n,onWorkEndHourChange:i,onWorkStartDayChange:o,onWorkEndDayChange:l}){var c,d,m;return e.jsxs(W,{className:"border-0 shadow-sm",children:[e.jsxs(ee,{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(te,{className:"text-base font-semibold",children:"Working Hours Configuration"})]}),e.jsx(pe,{className:"text-sm",children:"Define your organization's working hours and days for TAT calculations"})]}),e.jsxs(K,{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(Z,{htmlFor:"work-start-hour",className:"text-sm font-medium",children:"Working Day Start Hour"}),e.jsx(xe,{id:"work-start-hour",type:"number",min:"0",max:"23",value:t,onChange:u=>n(parseInt(u.target.value)||9),className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ee,{className:"w-3 h-3"}),"24-hour format (0-23). Default: 9 AM"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Z,{htmlFor:"work-end-hour",className:"text-sm font-medium",children:"Working Day End Hour"}),e.jsx(xe,{id:"work-end-hour",type:"number",min:"0",max:"23",value:s,onChange:u=>i(parseInt(u.target.value)||18),className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ee,{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(Z,{htmlFor:"work-start-day",className:"text-sm font-medium",children:"Working Week Start Day"}),e.jsxs(Ae,{value:a.toString(),onValueChange:u=>o(parseInt(u)),children:[e.jsx(ke,{id:"work-start-day",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Te,{placeholder:"Select start day"})}),e.jsx(Re,{children:$a.map(u=>e.jsx(O,{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(Z,{htmlFor:"work-end-day",className:"text-sm font-medium",children:"Working Week End Day"}),e.jsxs(Ae,{value:r.toString(),onValueChange:u=>l(parseInt(u)),children:[e.jsx(ke,{id:"work-end-day",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Te,{placeholder:"Select end day"})}),e.jsx(Re,{children:$a.map(u=>e.jsx(O,{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 cA(){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 en("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(W,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(K,{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(W,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ee,{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(Ee,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(te,{className:"text-lg font-semibold text-gray-900",children:"Turn Around Time (TAT) Configuration"}),e.jsx(pe,{className:"text-sm text-gray-600",children:"Set default TAT hours per priority level, working hours, and configure auto-escalation thresholds"})]})]})}),e.jsxs(K,{className:"space-y-6",children:[e.jsx(iA,{expressHours:n.expressHours,standardHours:n.standardHours,onExpressChange:d=>c({expressHours:d}),onStandardChange:d=>c({standardHours:d})}),e.jsx(ct,{}),e.jsx(lA,{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(ct,{}),e.jsx(oA,{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(D,{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 dA({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 mA({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(Z,{htmlFor:"notification-frequency",children:"Notification Frequency"}),e.jsxs(Ae,{value:t,onValueChange:a,children:[e.jsx(ke,{id:"notification-frequency",children:e.jsx(Te,{placeholder:"Select frequency"})}),e.jsxs(Re,{children:[e.jsx(O,{value:"Immediate",children:"Immediate"}),e.jsx(O,{value:"Hourly",children:"Hourly"}),e.jsx(O,{value:"Daily",children:"Daily"}),e.jsx(O,{value:"Weekly",children:"Weekly"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Z,{htmlFor:"reminder-frequency",children:"Reminder Frequency (hours)"}),e.jsx(xe,{id:"reminder-frequency",type:"number",min:"1",max:"168",value:s,onChange:n=>r(parseInt(n.target.value)||12)})]})]})}function uA({emailTemplate:t,onEmailTemplateChange:s}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(Z,{htmlFor:"email-template",children:"Email Template Message"}),e.jsx(fs,{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 hA(){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(W,{children:[e.jsxs(ee,{children:[e.jsx(te,{children:"Notification Configuration"}),e.jsx(pe,{children:"Configure notification channels, frequency, and message templates"})]}),e.jsxs(K,{className:"space-y-6",children:[e.jsx(dA,{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(ct,{}),e.jsx(mA,{notificationFrequency:t.notificationFrequency,reminderFrequency:t.reminderFrequency,onNotificationFrequencyChange:n=>r({notificationFrequency:n}),onReminderFrequencyChange:n=>r({reminderFrequency:n})}),e.jsx(uA,{emailTemplate:t.emailTemplate,onEmailTemplateChange:n=>r({emailTemplate:n})}),e.jsxs(D,{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 pA({maxFileSizeMB:t,retentionDays:s,onMaxFileSizeChange:a,onRetentionDaysChange:r}){const n=Math.round(s/365*10)/10;return e.jsxs(W,{className:"border-0 shadow-sm",children:[e.jsxs(ee,{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(te,{className:"text-base font-semibold",children:"Upload & Retention Settings"})]}),e.jsx(pe,{className:"text-sm",children:"Configure file size limits and document retention period"})]}),e.jsx(K,{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(Z,{htmlFor:"max-upload",className:"text-sm font-medium",children:"Maximum Upload Size (MB)"}),e.jsx(xe,{id:"max-upload",type:"number",min:"1",max:"100",value:t,onChange:i=>a(parseInt(i.target.value)||10),className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Na,{className:"w-3 h-3"}),"Maximum allowed file size for document uploads"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Z,{htmlFor:"retention",className:"text-sm font-medium",children:"Retention Period (Days)"}),e.jsx(xe,{id:"retention",type:"number",min:"30",max:"3650",value:s,onChange:i=>r(parseInt(i.target.value)||365),className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Yr,{className:"w-3 h-3"}),"Days to retain documents after workflow closure (",n," years)"]})]})]})})]})}const xA=[{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 gA({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(W,{className:"border-0 shadow-sm",children:[e.jsxs(ee,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vd,{className:"w-5 h-5 text-re-green"}),e.jsx(te,{className:"text-base font-semibold",children:"Allowed File Types"})]}),e.jsx(pe,{className:"text-sm",children:"Select which file types are allowed for upload"})]}),e.jsxs(K,{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:xA.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(Z,{htmlFor:"file-types-manual",className:"text-sm font-medium",children:"File Extensions (comma-separated)"}),e.jsx(xe,{id:"file-types-manual",type:"text",value:t,onChange:o=>i(o.target.value),placeholder:"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20 font-mono text-sm"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Edit directly or use the checkboxes above. Separate extensions with commas."})]})]})]})}function fA(){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 en("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(W,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(K,{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(W,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ee,{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(Se,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(te,{className:"text-lg font-semibold text-gray-900",children:"Document Upload Policy"}),e.jsx(pe,{className:"text-sm text-gray-600",children:"Configure file upload limits, allowed types, and retention policies"})]})]})}),e.jsxs(K,{className:"space-y-6",children:[e.jsx(pA,{maxFileSizeMB:n.maxFileSizeMB,retentionDays:n.retentionDays,onMaxFileSizeChange:d=>c({maxFileSizeMB:d}),onRetentionDaysChange:d=>c({retentionDays:d})}),e.jsx(ct,{}),e.jsx(gA,{allowedFileTypes:n.allowedFileTypes,onAllowedFileTypesChange:d=>c({allowedFileTypes:d})}),e.jsx("div",{className:"flex justify-end pt-4",children:e.jsx(D,{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 yA(){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 vA=["Total Requests","Open Requests","Approved Requests","Rejected Requests","My Pending Actions","TAT Compliance","Delayed Workflows","Average Cycle Time"],bA=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 jA({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(X,{className:bA(t),children:[t," Dashboard"]})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-2 ml-4",children:vA.map(r=>e.jsxs("div",{className:"flex items-center space-x-2 p-2 bg-muted/50 rounded",children:[e.jsx(Ki,{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 NA(){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(W,{children:[e.jsxs(ee,{children:[e.jsx(te,{children:"Dashboard Layout Configuration"}),e.jsx(pe,{children:"Control which KPI cards are visible for each user role"})]}),e.jsxs(K,{className:"space-y-4",children:[e.jsx(yA,{}),e.jsx("div",{className:"space-y-6",children:n.map(i=>e.jsx(jA,{role:i,kpis:t[i]||{},onKPIToggle:(o,l)=>r(i,o,l)},i))}),e.jsxs(D,{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 wA=[{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 CA({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(W,{className:"border-0 shadow-sm",children:[e.jsxs(ee,{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(te,{className:"text-base font-semibold",children:"AI Provider & API Keys"})]}),e.jsx(pe,{className:"text-sm",children:"Select your AI provider and configure API keys"})]}),e.jsxs(K,{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(Z,{htmlFor:"ai-provider",className:"text-sm font-medium",children:"AI Provider"}),e.jsxs(Ae,{value:s,onValueChange:p=>l(p),children:[e.jsx(ke,{id:"ai-provider",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Te,{placeholder:"Select AI provider"})}),e.jsx(Re,{children:wA.map(p=>e.jsx(O,{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(Z,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Ex,{className:"w-4 h-4"}),"API Keys"]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Z,{htmlFor:"claude-key",className:"text-xs text-muted-foreground",children:"Claude API Key"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{id:"claude-key",type:i.claude?"text":"password",value:a,onChange: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(D,{type:"button",variant:"outline",size:"icon",onClick:()=>u("claude"),className:"border-gray-200",children:i.claude?e.jsx(Sr,{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(Z,{htmlFor:"openai-key",className:"text-xs text-muted-foreground",children:"OpenAI API Key"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{id:"openai-key",type:i.openai?"text":"password",value:r,onChange: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(D,{type:"button",variant:"outline",size:"icon",onClick:()=>u("openai"),className:"border-gray-200",children:i.openai?e.jsx(Sr,{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(Z,{htmlFor:"gemini-key",className:"text-xs text-muted-foreground",children:"Gemini API Key"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{id:"gemini-key",type:i.gemini?"text":"password",value:n,onChange: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(D,{type:"button",variant:"outline",size:"icon",onClick:()=>u("gemini"),className:"border-gray-200",children:i.gemini?e.jsx(Sr,{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 SA({aiRemarkGeneration:t,onRemarkGenerationChange:s}){return e.jsxs(W,{className:"border-0 shadow-sm",children:[e.jsxs(ee,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Kr,{className:"w-5 h-5 text-re-green"}),e.jsx(te,{className:"text-base font-semibold",children:"AI Features"})]}),e.jsx(pe,{className:"text-sm",children:"Enable/disable specific AI-powered features"})]}),e.jsx(K,{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 AA({maxRemarkChars:t,onMaxRemarkCharsChange:s}){return e.jsxs(W,{className:"border-0 shadow-sm",children:[e.jsxs(ee,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wd,{className:"w-5 h-5 text-re-green"}),e.jsx(te,{className:"text-base font-semibold",children:"AI Parameters"})]}),e.jsx(pe,{className:"text-sm",children:"Configure AI generation parameters"})]}),e.jsx(K,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(Z,{htmlFor:"max-remark-chars",className:"text-sm font-medium",children:"Maximum Remark Length"}),e.jsx(xe,{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 TA(){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 en("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(W,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(K,{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(W,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ee,{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(Kr,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(te,{className:"text-lg font-semibold text-gray-900",children:"AI Features Configuration"}),e.jsx(pe,{className:"text-sm text-gray-600",children:"Configure AI provider, API keys, and enable/disable AI-powered features"})]})]})}),e.jsxs(K,{className:"space-y-6",children:[e.jsx(CA,{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(ct,{}),e.jsx(SA,{aiRemarkGeneration:o.aiRemarkGeneration,onRemarkGenerationChange:p=>m({aiRemarkGeneration:p})}),e.jsx(ct,{}),e.jsx(AA,{maxRemarkChars:o.maxRemarkChars,onMaxRemarkCharsChange:p=>m({maxRemarkChars:p})}),e.jsx("div",{className:"flex justify-end pt-4",children:e.jsx(D,{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 Hc=["Admin Only","Initiator Only","Approver Only","Initiator & Approver","Admin & Initiator","Admin & Approver","All Roles"];function kA({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(Z,{htmlFor:"spectator-permission",children:"Spectator Addition Permission"}),e.jsxs(Ae,{value:t,onValueChange:a,children:[e.jsx(ke,{id:"spectator-permission",children:e.jsx(Te,{placeholder:"Select permission"})}),e.jsx(Re,{children:Hc.map(n=>e.jsx(O,{value:n,children:n},n))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Z,{htmlFor:"link-sharing-permission",children:"Link Sharing Permission"}),e.jsxs(Ae,{value:s,onValueChange:r,children:[e.jsx(ke,{id:"link-sharing-permission",children:e.jsx(Te,{placeholder:"Select permission"})}),e.jsx(Re,{children:Hc.map(n=>e.jsx(O,{value:n,children:n},n))})]})]})]})}function RA({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 PA(){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(W,{children:[e.jsxs(ee,{children:[e.jsx(te,{children:"Workflow Sharing Policy"}),e.jsx(pe,{children:"Control who can add spectators and share workflow links"})]}),e.jsxs(K,{className:"space-y-6",children:[e.jsx(kA,{spectatorPermission:t.spectatorPermission,linkSharingPermission:t.linkSharingPermission,onSpectatorPermissionChange:n=>r({spectatorPermission:n}),onLinkSharingPermissionChange:n=>r({linkSharingPermission:n})}),e.jsx(ct,{}),e.jsx(RA,{requirePassword:t.requirePassword,allowExternalSharing:t.allowExternalSharing,onRequirePasswordChange:n=>r({requirePassword:n}),onAllowExternalSharingChange:n=>r({allowExternalSharing:n})}),e.jsxs(D,{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 DA(){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(X,{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(ct,{}),e.jsxs(Qr,{value:r,onValueChange:n,className:"flex flex-col gap-2 space-y-4",children:[e.jsxs(Jr,{className:"text-muted-foreground items-center justify-center rounded-xl p-[3px] bg-muted grid w-full grid-cols-9 h-auto",children:[e.jsxs(pt,{value:"kpi",className:"flex items-center gap-2",children:[e.jsx(Nd,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"KPI Config"})]}),e.jsxs(pt,{value:"analytics",className:"flex items-center gap-2",children:[e.jsx(Vs,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Analytics"})]}),e.jsxs(pt,{value:"users",className:"flex items-center gap-2",children:[e.jsx(nt,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Users"})]}),e.jsxs(pt,{value:"tat",className:"flex items-center gap-2",children:[e.jsx(Ee,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"TAT"})]}),e.jsxs(pt,{value:"notifications",className:"flex items-center gap-2",children:[e.jsx(Ft,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Notify"})]}),e.jsxs(pt,{value:"documents",className:"flex items-center gap-2",children:[e.jsx(Se,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Docs"})]}),e.jsxs(pt,{value:"dashboard",className:"flex items-center gap-2",children:[e.jsx(Mx,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Dashboard"})]}),e.jsxs(pt,{value:"ai",className:"flex items-center gap-2",children:[e.jsx(Cd,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"AI"})]}),e.jsxs(pt,{value:"sharing",className:"flex items-center gap-2",children:[e.jsx(Sa,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Sharing"})]})]}),e.jsx(xt,{value:"kpi",className:"flex-1 outline-none space-y-4",children:e.jsxs(W,{children:[e.jsx(ee,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(te,{children:"KPI Configuration"}),e.jsx(pe,{children:"Configure which KPIs are enabled, visible to specific roles, and set alert thresholds"})]}),e.jsxs(X,{className:"bg-blue-50 text-blue-700",children:[l," / ",l," KPIs Active"]})]})}),e.jsxs(K,{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(Zt,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search KPIs by name, description, or category...",value:s,onChange:d=>a(d.target.value),className:"pl-10"})]})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:i.map(d=>e.jsxs("div",{className:"p-4 bg-muted/50 rounded-lg",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:d.name}),e.jsx("p",{className:"text-2xl font-semibold",children:d.count})]},d.name))}),o.map(d=>e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(as,{className:"w-5 h-5 text-re-green"}),e.jsx("h3",{className:"font-semibold",children:d.name}),e.jsxs(X,{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(X,{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(Ix,{className:"w-3 h-3"}):e.jsx(Fx,{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(X,{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(xt,{value:"analytics",className:"flex-1 outline-none space-y-4",children:e.jsx(JS,{})}),e.jsx(xt,{value:"users",className:"flex-1 outline-none space-y-4",children:e.jsx(nA,{})}),e.jsx(xt,{value:"tat",className:"flex-1 outline-none space-y-4",children:e.jsx(cA,{})}),e.jsx(xt,{value:"notifications",className:"flex-1 outline-none space-y-4",children:e.jsx(hA,{})}),e.jsx(xt,{value:"documents",className:"flex-1 outline-none space-y-4",children:e.jsx(fA,{})}),e.jsx(xt,{value:"dashboard",className:"flex-1 outline-none space-y-4",children:e.jsx(NA,{})}),e.jsx(xt,{value:"ai",className:"flex-1 outline-none space-y-4",children:e.jsx(TA,{})}),e.jsx(xt,{value:"sharing",className:"flex-1 outline-none space-y-4",children:e.jsx(PA,{})})]})]})}function EA({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(Ze,{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(Xe,{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(X,{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(X,{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(Z,{htmlFor:"comment",className:"text-sm font-semibold text-gray-900",children:"Comments & Remarks *"}),e.jsx(fs,{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(D,{variant:"outline",onClick:u,disabled:c,children:"Cancel"}),e.jsx(D,{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 MA=(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(C=>i[C]||C):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{}},IA=x.createContext(void 0),FA={setTheme:t=>{},themes:[]},_A=()=>{var t;return(t=x.useContext(IA))!=null?t:FA};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:`(${MA.toString()})(${m})`}})});const LA=({...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 OA({onViewRequest:t}){const{user:s}=Mt();return Zr(s)?e.jsx(Z2,{onViewRequest:t}):e.jsx(J2,{onViewRequest:t})}function $A({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 j=JSON.parse(f);i(j)}catch(j){console.error("Error parsing dynamic requests:",j)}},[]),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,j,b)=>{l(f),d(j||"Unknown Request");const w=(b==null?void 0:b.toLowerCase())==="draft"||b==="DRAFT";s(w?`/edit-request/${f}`:`/request/${f}`)},h=()=>{s(-1)},p=()=>{s("/new-request")},g=f=>{var w,T,R,k,F,N,A,I,V,_,L;if(f.templateType){f.templateType==="claim-management"&&s("/claim-management");return}const j=`RE-REQ-2024-${String(Object.keys(Jd).length+n.length+1).padStart(3,"0")}`,b={id:j,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:((w=f.approvers)==null?void 0:w.length)||1,currentApprover:((R=(T=f.approvers)==null?void 0:T[0])==null?void 0:R.name)||((N=(F=(k=f.approvers)==null?void 0:k[0])==null?void 0:F.email)==null?void 0:N.split("@")[0])||"Pending Assignment",approverLevel:`1 of ${((A=f.approvers)==null?void 0:A.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(S=>S).map((S,M)=>{var H;const P=(S==null?void 0:S.name)||((H=S==null?void 0:S.email)==null?void 0:H.split("@")[0])||`Approver ${M+1}`,E=(S==null?void 0:S.email)||"";return{step:M+1,approver:`${P}${E?` (${E})`:""}`,role:(S==null?void 0:S.role)||`Level ${(S==null?void 0:S.level)||M+1} Approver`,status:M===0?"pending":"waiting",tatHours:S!=null&&S.tat?typeof S.tat=="string"?parseInt(S.tat):S.tat:48,elapsedHours:0,assignedAt:M===0?new Date().toISOString():null,comment:null,timestamp:null}}),documents:[],spectators:(f.spectators||[]).filter(S=>S&&(S.name||S.email)).map(S=>{var P;const M=(S==null?void 0:S.name)||((P=S==null?void 0:S.email)==null?void 0:P.split("@")[0])||"Observer";return{name:M,role:(S==null?void 0:S.role)||(S==null?void 0:S.department)||"Observer",avatar:M.split(" ").map(E=>E[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 ${((V=(I=f.approvers)==null?void 0:I[0])==null?void 0:V.name)||((L=(_=f.approvers)==null?void 0:_[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}" (${j}) has been created and sent for approval.`,duration:5e3})},y=(f,j)=>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)},C=f=>{var w;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",(w=f.activityType)==null?void 0:w.toLowerCase().replace(/\s+/g,"-")]};i(T=>[...T,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(Ux,{children:[e.jsx(ut,{path:"/login/callback",element:e.jsx(Od,{})}),e.jsx(ut,{path:"/",element:e.jsx(Pt,{currentPage:"dashboard",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(cl,{onNavigate:m,onNewRequest:p})})}),e.jsx(ut,{path:"/dashboard",element:e.jsx(Pt,{currentPage:"dashboard",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(cl,{onNavigate:m,onNewRequest:p})})}),e.jsx(ut,{path:"/open-requests",element:e.jsx(Pt,{currentPage:"open-requests",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(U0,{onViewRequest:u})})}),e.jsx(ut,{path:"/closed-requests",element:e.jsx(Pt,{currentPage:"closed-requests",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(ly,{onViewRequest:u})})}),e.jsx(ut,{path:"/shared-summaries",element:e.jsx(Pt,{currentPage:"shared-summaries",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(uv,{})})}),e.jsx(ut,{path:"/shared-summaries/:sharedSummaryId",element:e.jsx(Pt,{currentPage:"shared-summaries",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(hv,{})})}),e.jsx(ut,{path:"/my-requests",element:e.jsx(Pt,{currentPage:"my-requests",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(A2,{onViewRequest:u,dynamicRequests:n})})}),e.jsx(ut,{path:"/requests",element:e.jsx(Pt,{currentPage:"requests",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(OA,{onViewRequest:u})})}),e.jsx(ut,{path:"/approver-performance",element:e.jsx(Pt,{currentPage:"approver-performance",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(hS,{})})}),e.jsx(ut,{path:"/request/:requestId",element:e.jsx(Pt,{currentPage:"request-detail",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(mv,{requestId:"",onBack:h,dynamicRequests:n})})}),e.jsx(ut,{path:"/work-notes/:requestId",element:e.jsx(pv,{})}),e.jsx(ut,{path:"/new-request",element:e.jsx(_c,{onBack:h,onSubmit:g})}),e.jsx(ut,{path:"/edit-request/:requestId",element:e.jsx(_c,{onBack:h,onSubmit:g,requestId:void 0,isEditMode:!0})}),e.jsx(ut,{path:"/claim-management",element:e.jsx(c2,{onBack:h,onSubmit:C})}),e.jsx(ut,{path:"/profile",element:e.jsx(Pt,{currentPage:"profile",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(pS,{})})}),e.jsx(ut,{path:"/settings",element:e.jsx(Pt,{currentPage:"settings",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(TS,{})})}),e.jsx(ut,{path:"/notifications",element:e.jsx(Pt,{currentPage:"notifications",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(kS,{onNavigate:m})})}),e.jsx(ut,{path:"/detailed-reports",element:e.jsx(Pt,{currentPage:"detailed-reports",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(KS,{})})}),e.jsx(ut,{path:"/admin",element:e.jsx(Pt,{currentPage:"admin",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(DA,{})})})]}),e.jsx(LA,{position:"top-right",toastOptions:{style:{background:"var(--card)",color:"var(--card-foreground)",border:"1px solid var(--border)"}}}),a&&e.jsx(EA,{isOpen:!!a,onClose:v,action:a,requestId:o,requestTitle:c,onSubmit:y})]})}function UA(t){const{onLogout:s}=t||{};return e.jsx($x,{children:e.jsx($A,{onLogout:s})})}function BA(){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(Od,{}):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(UA,{onLogout:c}),i&&e.jsx(nf,{isOpen:i,onClose:()=>o(!1)})]}):e.jsx(af,{})}const Er=()=>{try{return!0}catch{return!1}},VA=()=>{if(Er())return null;try{return localStorage.getItem("token")}catch{return null}},zA={user:null,token:VA(),isAuthenticated:!1,isLoading:!1,error:null},jh=Ta({name:"auth",initialState:zA,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,!Er())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,!Er())try{localStorage.removeItem("token")}catch{}},logout:t=>{if(t.isAuthenticated=!1,t.user=null,t.token=null,t.error=null,!Er())try{localStorage.removeItem("token")}catch{}},clearError:t=>{t.error=null},updateUser:(t,s)=>{t.user=s.payload}}}),{loginStart:eT,loginSuccess:tT,loginFailure:sT,logout:aT,clearError:rT,updateUser:nT}=jh.actions,HA=Ox({reducer:{auth:jh.reducer,dashboard:Vd.reducer,requests:ch.reducer,myRequests:nh.reducer,openRequests:Hd.reducer,closedRequests:Qd.reducer},middleware:t=>t({serializableCheck:{ignoredActions:["persist/PERSIST"]}}),devTools:!1});ai.createRoot(document.getElementById("root")).render(e.jsx(Dp.StrictMode,{children:e.jsx(ig,{store:HA,children:e.jsx(Cg,{children:e.jsx(BA,{})})})}));export{ne as a};
|
||
//# sourceMappingURL=index-onQ3Ui-x.js.map
|