65 lines
1.1 MiB
65 lines
1.1 MiB
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/conclusionApi-CGl-93sb.js","assets/radix-vendor-C2EbRL2a.js","assets/charts-vendor-Cji9-Yri.js","assets/utils-vendor-DHm03ykU.js","assets/ui-vendor-BpFwwBOf.js","assets/socket-vendor-TjCxX7sJ.js","assets/redux-vendor-tbZCm13o.js","assets/router-vendor-CRr9x_Jp.js"])))=>i.map(i=>d[i]);
|
||
var qh=Object.defineProperty;var ep=(t,s,a)=>s in t?qh(t,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[s]=a;var _n=(t,s,a)=>ep(t,typeof s!="symbol"?s+"":s,a);import{j as e,S as vd,R as jd,I as Nd,F as wd,a as tp,T as sp,P as ap,C as rp,b as np,O as Cd,c as Sd,d as ip,e as op,f as lp,D as cp,g as dp,A as mp,h as up,i as hp,k as pp,l as xp,m as gp,n as fp,V as yp,o as bp,p as vp,q as jp,r as Np,s as wp,t as Cp,u as Sp,v as Ap,w as kp,x as Tp,y as Dp,z as Rp,B as Pp,E as Ep,G as Ip,H as Mp,L as Fp,J as _p,K as Lp,M as Ad,N as kd,Q as Op,U as Td,W as Dd,X as $p,Y as Up,Z as Bp,_ as Vp,$ as zp,a0 as Hp,a1 as Wp,a2 as Kp,a3 as Gp,a4 as Yp,a5 as Zp,a6 as Xp,a7 as Jp,a8 as Qp,a9 as qp,aa as ex,ab as tx}from"./radix-vendor-C2EbRL2a.js";import{a as sx,r as x,c as Rd,d as ro,B as ax,C as Pd,X as Ed,Y as Id,T as no,L as Md,e as Ln,P as rx,f as nx,g as ix,h as ox,i as bl,j as xn,k as gn,b as lx}from"./charts-vendor-Cji9-Yri.js";import{a as Fd,f as _d,b as Ne,d as cx,c as dx,e as mx,s as ys,g as io,h as vl,i as ux,j as Es,k as fr,l as oo,m as Ld,n as ms,o as xs,p as On,q as Hs,r as hx,t as Ci,u as px,v as Si,w as xx,x as gx,y as fx,z as yx,A as $n,B as jl,C as bx,D as Od,E as $d,F as lo,G as co,H as vx,I as jx,J as Ud}from"./utils-vendor-DHm03ykU.js";import{L as Nx,C as Pe,a as Ai,b as Xe,X as ut,H as wx,c as Bd,U as St,F as Re,d as Ce,S as Ya,P as Is,e as Cx,f as Sx,B as as,g as la,h as Un,i as Vd,j as zd,k as Za,l as Ax,m as kr,n as et,R as es,I as Tr,T as kt,o as Ue,p as Ts,q as kx,A as Vt,r as Cs,M as Ds,s as fn,t as qt,u as Tx,D as Qt,Z as mo,v as Ct,w as bs,x as Hd,y as Wd,z as yr,E as ht,G as te,J as yn,O as ki,K as Ms,N as Dx,Q as Rx,V as Px,W as Ex,Y as Ix,_ as Mx,$ as Fx,a0 as _x,a1 as Lx,a2 as Ox,a3 as Xa,a4 as bn,a5 as ca,a6 as nn,a7 as uo,a8 as Fs,a9 as hs,aa as ho,ab as Kd,ac as Nl,ad as Br,ae as Gd,af as $x,ag as Ys,ah as ps,ai as zt,aj as Ti,ak as Ux,al as Yd,am as Bx,an as Vx,ao as zx,ap as po,aq as vn,ar as ss,as as Hx,at as Wx,au as Kx,av as Gx,aw as Yx,ax as Zd,ay as Xr,az as jn,aA as Zx,aB as Xd,aC as Xx,aD as Jx,aE as xo,aF as Jd,aG as Nn,aH as wn,aI as go,aJ as Qx,aK as Qd,aL as wl,aM as ha,aN as qx,aO as fo,aP as eg,aQ as La,aR as qd,aS as Cl,aT as tg,aU as sg,aV as ag,aW as em,aX as rg,aY as ng,aZ as ig,a_ as og,a$ as lg}from"./ui-vendor-BpFwwBOf.js";import{l as cg}from"./socket-vendor-TjCxX7sJ.js";import{c as Ja,a as dg}from"./redux-vendor-tbZCm13o.js";import{u as Dr,a as pa,b as tm,B as mg,R as ug,c as _t}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 Di={},Sl=sx;Di.createRoot=Sl.createRoot,Di.hydrateRoot=Sl.hydrateRoot;var sm={exports:{}},am={};/**
|
||
* @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 Rr=x;function hg(t,s){return t===s&&(t!==0||1/t===1/s)||t!==t&&s!==s}var pg=typeof Object.is=="function"?Object.is:hg,xg=Rr.useSyncExternalStore,gg=Rr.useRef,fg=Rr.useEffect,yg=Rr.useMemo,bg=Rr.useDebugValue;am.useSyncExternalStoreWithSelector=function(t,s,a,r,n){var i=gg(null);if(i.current===null){var o={hasValue:!1,value:null};i.current=o}else o=i.current;i=yg(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,pg(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=xg(t,i[0],i[1]);return fg(function(){o.hasValue=!0,o.value=l},[l]),bg(l),l};sm.exports=am;var vg=sm.exports;function jg(t){t()}function Ng(){let t=null,s=null;return{clear(){t=null,s=null},notify(){jg(()=>{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 Al={notify(){},get:()=>[]};function wg(t,s){let a,r=Al,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=Ng())}function u(){n--,a&&n===0&&(a(),a=void 0,r.clear(),r=Al)}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 Cg=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",Sg=Cg(),Ag=()=>typeof navigator<"u"&&navigator.product==="ReactNative",kg=Ag(),Tg=()=>Sg||kg?x.useLayoutEffect:x.useEffect,Dg=Tg(),Bn=Symbol.for("react-redux-context"),Vn=typeof globalThis<"u"?globalThis:{};function Rg(){if(!x.createContext)return{};const t=Vn[Bn]??(Vn[Bn]=new Map);let s=t.get(x.createContext);return s||(s=x.createContext(null),t.set(x.createContext,s)),s}var da=Rg();function Pg(t){const{children:s,context:a,serverState:r,store:n}=t,i=x.useMemo(()=>{const c=wg(n);return{store:n,subscription:c,getServerState:r?()=>r:void 0}},[n,r]),o=x.useMemo(()=>n.getState(),[n]);Dg(()=>{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||da;return x.createElement(l.Provider,{value:i},s)}var Eg=Pg;function yo(t=da){return function(){return x.useContext(t)}}var rm=yo();function nm(t=da){const s=t===da?rm:yo(t),a=()=>{const{store:r}=s();return r};return Object.assign(a,{withTypes:()=>a}),a}var Ig=nm();function Mg(t=da){const s=t===da?Ig:nm(t),a=()=>s().dispatch;return Object.assign(a,{withTypes:()=>a}),a}var Fg=Mg(),_g=(t,s)=>t===s;function Lg(t=da){const s=t===da?rm:yo(t),a=(r,n={})=>{const{equalityFn:i=_g}=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=vg.useSyncExternalStoreWithSelector(c.addNestedSub,l.getState,d||l.getState,m,i);return x.useDebugValue(u),u};return Object.assign(a,{withTypes:()=>a}),a}var Og=Lg(),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 $g(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 on=function(){return on=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},on.apply(this,arguments)};var Ca=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function bo(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function vo(t,s){return t(s={exports:{}},s.exports),s.exports}var ja=vo(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()}});bo(ja);var Ug=bo(vo(function(t,s){var a=Ca&&Ca.__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=Ca&&Ca.__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(N){b=[6,N],p=0}finally{h=g=0}if(5&b[0])throw b[1];return{value:b[0]?b[1]:void 0,done:!0}}([f,j])}}},n=Ca;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,ja.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?(ja.default().unlock(h),[2]):((C=JSON.parse(v)).timeRefreshed=Date.now(),y.setItemSync(u,JSON.stringify(C)),ja.default().unlock(h),this.refreshLockWhileAcquired(u,h),[2])):(ja.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,ja.default().lock(y.iat)];case 1:v.sent(),this.acquiredIatSet.delete(y.iat),h.removeItemSync(p),ja.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 N=JSON.parse(b);(N.timeRefreshed===void 0&&N.timeAcquired<h||N.timeRefreshed!==void 0&&N.timeRefreshed<h)&&(p.removeItemSync(j),C=!0)}}}C&&m.notifyWaiters()},m.waiters=void 0,m}();s.default=d}));new TextEncoder;new TextDecoder;var Aa=vo(function(t,s){var a=Ca&&Ca.__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}))}});bo(Aa),Aa.encode,Aa.parse,Aa.getAll;Aa.get;Aa.set;Aa.remove;var kl;(function(t){t.Code="code",t.ConnectCode="connect_code"})(kl||(kl={}));var Tl;(function(t){t.Bearer="Bearer",t.DPoP="DPoP"})(Tl||(Tl={}));new Ug;var Bg={isAuthenticated:!1,isLoading:!0,error:void 0,user:void 0},cs=function(){throw new Error("You forgot to wrap your component in <Auth0Provider>.")},Vg=on(on({},Bg),{buildAuthorizeUrl:cs,buildLogoutUrl:cs,getAccessTokenSilently:cs,getAccessTokenWithPopup:cs,getIdTokenClaims:cs,loginWithRedirect:cs,loginWithPopup:cs,connectAccountWithRedirect:cs,logout:cs,handleRedirectCallback:cs,getDpopNonce:cs,setDpopNonce:cs,generateDpopProof:cs,createFetcher:cs}),zg=x.createContext(Vg);(function(t){$g(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 Hg=function(t){return t===void 0&&(t=zg),x.useContext(t)};const zn="idToken",Hn="userData",Wg=()=>!0;class st{static setAccessToken(s){}static getAccessToken(){return null}static setRefreshToken(s){}static getRefreshToken(){return null}static setIdToken(s){sessionStorage.setItem(zn,s)}static getIdToken(){return sessionStorage.getItem(zn)}static setUserData(s){localStorage.setItem(Hn,JSON.stringify(s))}static getUserData(){const s=localStorage.getItem(Hn);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(Hn),sessionStorage.removeItem(zn)}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 Wg()}}function Wn(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 im="https://re-workflow-nt-dev.siplsolutions.com/api/v1",ce=Fd.create({baseURL:im,headers:{"Content-Type":"application/json"},withCredentials:!0});ce.interceptors.request.use(t=>t,t=>Promise.reject(t));ce.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=st.getRefreshToken(),o=await Fd.post(`${im}/auth/refresh`,n?{}:{refreshToken:i},{withCredentials:!0}),c=(o.data.data||o.data).accessToken;return ce(s)}catch(i){return st.clearAll(),window.location.href="/",Promise.reject(i)}}return Promise.reject(t)});async function Kg(t,s){var a,r;try{const n=await ce.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&&st.setUserData(o.user),o.idToken&&st.setIdToken(o.idToken),o.accessToken&&o.refreshToken&&(st.setAccessToken(o.accessToken),st.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 Gg(){var r;const t={},a=(await ce.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 Vr(){const s=(await ce.get("/auth/me")).data;return s.data||s}async function Yg(){var t,s;try{await ce.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 om=x.createContext(void 0);function Zg({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__"),st.clearAll();try{localStorage.clear(),sessionStorage.clear()}catch(N){console.error("Error clearing storage:",N)}a(!1),o(null),n(!1),c(null);return}const b=new URLSearchParams(window.location.search);if(b.has("logout")||b.has("okta_logged_out")){st.clearAll(),localStorage.clear(),sessionStorage.clear(),a(!1),o(null),n(!1);const N=new URLSearchParams;b.has("okta_logged_out")&&N.set("okta_logged_out","true");const A=N.toString()?`/?${N.toString()}`:"/";window.history.replaceState({},document.title,A);return}window.location.pathname!=="/login/callback"&&(st.getUserData(),d?n(!1):h())},[d]),x.useEffect(()=>{if(!s)return;const f=async()=>{try{await v()}catch(N){console.error("Silent refresh failed:",N)}},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"),N=j.get("error");if(window.history.replaceState({},document.title,"/login/callback"),N){c(new Error(`Authentication error: ${N}`)),n(!1);return}if(!b){n(!1);return}try{n(!0),a(!1),c(null);const A=`${window.location.origin}/login/callback`,D=await Kg(b,A);o(D.user),a(!0),c(null),window.history.replaceState({},document.title,"/")}catch(A){console.error("❌ Token exchange error in AuthContext:",A),c(A),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 A=st.getUserData();try{const D=await Vr();o(D),st.setUserData(D),a(!0)}catch(D){if(((j=D==null?void 0:D.response)==null?void 0:j.status)===401)try{await v();const T=await Vr();o(T),st.setUserData(T),a(!0)}catch{st.clearAll(),a(!1),o(null)}else D!=null&&D.isConnectionError?A?(o(A),a(!0)):(a(!1),o(null)):(st.clearAll(),a(!1),o(null))}return}const b=st.getAccessToken(),N=st.getUserData();if(!b){a(!1),o(null),n(!1);return}if(Wn(b))try{await v();const A=st.getAccessToken();if(A&&!Wn(A)){const D=st.getUserData();if(D)o(D),a(!0);else try{const T=await Vr();o(T),st.setUserData(T),a(!0)}catch{st.clearAll(),a(!1),o(null)}}else st.clearAll(),a(!1),o(null)}catch{st.clearAll(),a(!1),o(null)}else if(N)o(N),a(!0);else try{const A=await Vr();o(A),st.setUserData(A),a(!0)}catch{st.clearAll(),a(!1),o(null)}}catch(b){console.error("Error checking auth status:",b),c(b),st.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`,N="code",A="openid profile email",D=Math.random().toString(36).substring(7),T=new URLSearchParams(window.location.search),P=T.has("logout")||T.has("okta_logged_out");let w=`${f}/oauth2/default/v1/authorize?client_id=${j}&redirect_uri=${encodeURIComponent(b)}&response_type=${N}&scope=${encodeURIComponent(A)}&state=${D}`;P&&(w+="&prompt=login"),window.location.href=w}catch(f){throw c(f),f}},g=async()=>{try{st.getIdToken(),sessionStorage.setItem("__logout_in_progress__","true"),sessionStorage.setItem("__force_logout__","true"),m(!0),a(!1),o(null),c(null),n(!0);try{await Yg()}catch(N){console.error("🚪 Logout API error:",N),console.warn("🚪 Backend logout failed - httpOnly cookies may not be cleared")}const f=sessionStorage.getItem("__logout_in_progress__"),j=sessionStorage.getItem("__force_logout__");st.clearAll(),f&&sessionStorage.setItem("__logout_in_progress__",f),j&&sessionStorage.setItem("__force_logout__",j),await new Promise(N=>setTimeout(N,100));const b=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(b)}catch(f){console.error("🚪 Logout error:",f);try{localStorage.clear(),sessionStorage.clear(),sessionStorage.setItem("__logout_in_progress__","true");const 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=st.getAccessToken();if(f&&!Wn(f))return f;try{return await v(),st.getAccessToken()}catch{return null}},v=async()=>{try{const j=await Gg();return}catch(j){throw st.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(om.Provider,{value:C,children:t})}function Xg({children:t}){return e.jsx(Zg,{children:t})}function ts(){const t=x.useContext(om);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t}function Na(t){return(t==null?void 0:t.role)==="ADMIN"}function nr(t){return(t==null?void 0:t.role)==="MANAGEMENT"}function Cn(t){return(t==null?void 0:t.role)==="MANAGEMENT"||(t==null?void 0:t.role)==="ADMIN"}const Dl=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,Rl=Rd,lm=(t,s)=>a=>{var r;if((s==null?void 0:s.variants)==null)return Rl(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=Dl(m)||Dl(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 Rl(t,o,c,a==null?void 0:a.class,a==null?void 0:a.className)},jo="-",Jg=t=>{const s=qg(t),{conflictingClassGroups:a,conflictingClassGroupModifiers:r}=t;return{getClassGroupId:o=>{const l=o.split(jo);return l[0]===""&&l.length!==1&&l.shift(),cm(l,s)||Qg(o)},getConflictingClassGroupIds:(o,l)=>{const c=a[o]||[];return l&&r[o]?[...c,...r[o]]:c}}},cm=(t,s)=>{var o;if(t.length===0)return s.classGroupId;const a=t[0],r=s.nextPart.get(a),n=r?cm(t.slice(1),r):void 0;if(n)return n;if(s.validators.length===0)return;const i=t.join(jo);return(o=s.validators.find(({validator:l})=>l(i)))==null?void 0:o.classGroupId},Pl=/^\[(.+)\]$/,Qg=t=>{if(Pl.test(t)){const s=Pl.exec(t)[1],a=s==null?void 0:s.substring(0,s.indexOf(":"));if(a)return"arbitrary.."+a}},qg=t=>{const{theme:s,prefix:a}=t,r={nextPart:new Map,validators:[]};return tf(Object.entries(t.classGroups),a).forEach(([i,o])=>{Pi(o,r,i,s)}),r},Pi=(t,s,a,r)=>{t.forEach(n=>{if(typeof n=="string"){const i=n===""?s:El(s,n);i.classGroupId=a;return}if(typeof n=="function"){if(ef(n)){Pi(n(r),s,a,r);return}s.validators.push({validator:n,classGroupId:a});return}Object.entries(n).forEach(([i,o])=>{Pi(o,El(s,i),a,r)})})},El=(t,s)=>{let a=t;return s.split(jo).forEach(r=>{a.nextPart.has(r)||a.nextPart.set(r,{nextPart:new Map,validators:[]}),a=a.nextPart.get(r)}),a},ef=t=>t.isThemeGetter,tf=(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,sf=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)}}},dm="!",af=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(dm),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},rf=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},nf=t=>({cache:sf(t.cacheSize),parseClassName:af(t),...Jg(t)}),of=/\s+/,lf=(t,s)=>{const{parseClassName:a,getClassGroupId:r,getConflictingClassGroupIds:n}=s,i=[],o=t.trim().split(of);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=rf(m).join(":"),C=u?v+dm: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 N=j[b];i.push(C+N)}l=d+(l.length>0?" "+l:l)}return l};function cf(){let t=0,s,a,r="";for(;t<arguments.length;)(s=arguments[t++])&&(a=mm(s))&&(r&&(r+=" "),r+=a);return r}const mm=t=>{if(typeof t=="string")return t;let s,a="";for(let r=0;r<t.length;r++)t[r]&&(s=mm(t[r]))&&(a&&(a+=" "),a+=s);return a};function df(t,...s){let a,r,n,i=o;function o(c){const d=s.reduce((m,u)=>u(m),t());return a=nf(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=lf(c,a);return n(c,m),m}return function(){return i(cf.apply(null,arguments))}}const gt=t=>{const s=a=>a[t]||[];return s.isThemeGetter=!0,s},um=/^\[(?:([a-z-]+):)?(.+)\]$/i,mf=/^\d+\/\d+$/,uf=new Set(["px","full","screen"]),hf=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,pf=/\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$/,xf=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,gf=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,ff=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Bs=t=>za(t)||uf.has(t)||mf.test(t),qs=t=>Qa(t,"length",Sf),za=t=>!!t&&!Number.isNaN(Number(t)),Kn=t=>Qa(t,"number",za),ir=t=>!!t&&Number.isInteger(Number(t)),yf=t=>t.endsWith("%")&&za(t.slice(0,-1)),Ye=t=>um.test(t),ea=t=>hf.test(t),bf=new Set(["length","size","percentage"]),vf=t=>Qa(t,bf,hm),jf=t=>Qa(t,"position",hm),Nf=new Set(["image","url"]),wf=t=>Qa(t,Nf,kf),Cf=t=>Qa(t,"",Af),or=()=>!0,Qa=(t,s,a)=>{const r=um.exec(t);return r?r[1]?typeof s=="string"?r[1]===s:s.has(r[1]):a(r[2]):!1},Sf=t=>pf.test(t)&&!xf.test(t),hm=()=>!1,Af=t=>gf.test(t),kf=t=>ff.test(t),Tf=()=>{const t=gt("colors"),s=gt("spacing"),a=gt("blur"),r=gt("brightness"),n=gt("borderColor"),i=gt("borderRadius"),o=gt("borderSpacing"),l=gt("borderWidth"),c=gt("contrast"),d=gt("grayscale"),m=gt("hueRotate"),u=gt("invert"),h=gt("gap"),p=gt("gradientColorStops"),g=gt("gradientColorStopPositions"),y=gt("inset"),v=gt("margin"),C=gt("opacity"),f=gt("padding"),j=gt("saturate"),b=gt("scale"),N=gt("sepia"),A=gt("skew"),D=gt("space"),T=gt("translate"),P=()=>["auto","contain","none"],w=()=>["auto","hidden","clip","visible","scroll"],S=()=>["auto",Ye,s],M=()=>[Ye,s],B=()=>["",Bs,qs],_=()=>["auto",za,Ye],$=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],k=()=>["solid","dashed","dotted","double","none"],I=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],E=()=>["start","end","center","between","around","evenly","stretch"],F=()=>["","0",Ye],O=()=>["auto","avoid","all","avoid-page","page","left","right","column"],L=()=>[za,Ye];return{cacheSize:500,separator:":",theme:{colors:[or],spacing:[Bs,qs],blur:["none","",ea,Ye],brightness:L(),borderColor:[t],borderRadius:["none","","full",ea,Ye],borderSpacing:M(),borderWidth:B(),contrast:L(),grayscale:F(),hueRotate:L(),invert:F(),gap:M(),gradientColorStops:[t],gradientColorStopPositions:[yf,qs],inset:S(),margin:S(),opacity:L(),padding:M(),saturate:L(),scale:L(),sepia:F(),skew:L(),space:M(),translate:M()},classGroups:{aspect:[{aspect:["auto","square","video",Ye]}],container:["container"],columns:[{columns:[ea]}],"break-after":[{"break-after":O()}],"break-before":[{"break-before":O()}],"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:[...$(),Ye]}],overflow:[{overflow:w()}],"overflow-x":[{"overflow-x":w()}],"overflow-y":[{"overflow-y":w()}],overscroll:[{overscroll:P()}],"overscroll-x":[{"overscroll-x":P()}],"overscroll-y":[{"overscroll-y":P()}],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",ir,Ye]}],basis:[{basis:S()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Ye]}],grow:[{grow:F()}],shrink:[{shrink:F()}],order:[{order:["first","last","none",ir,Ye]}],"grid-cols":[{"grid-cols":[or]}],"col-start-end":[{col:["auto",{span:["full",ir,Ye]},Ye]}],"col-start":[{"col-start":_()}],"col-end":[{"col-end":_()}],"grid-rows":[{"grid-rows":[or]}],"row-start-end":[{row:["auto",{span:[ir,Ye]},Ye]}],"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",Ye]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Ye]}],gap:[{gap:[h]}],"gap-x":[{"gap-x":[h]}],"gap-y":[{"gap-y":[h]}],"justify-content":[{justify:["normal",...E()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...E(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...E(),"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":[D]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[D]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",Ye,s]}],"min-w":[{"min-w":[Ye,s,"min","max","fit"]}],"max-w":[{"max-w":[Ye,s,"none","full","min","max","fit","prose",{screen:[ea]},ea]}],h:[{h:[Ye,s,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[Ye,s,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[Ye,s,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[Ye,s,"auto","min","max","fit"]}],"font-size":[{text:["base",ea,qs]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Kn]}],"font-family":[{font:[or]}],"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",Ye]}],"line-clamp":[{"line-clamp":["none",za,Kn]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Bs,Ye]}],"list-image":[{"list-image":["none",Ye]}],"list-style-type":[{list:["none","disc","decimal",Ye]}],"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:[...k(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Bs,qs]}],"underline-offset":[{"underline-offset":["auto",Bs,Ye]}],"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:M()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Ye]}],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",Ye]}],"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:[...$(),jf]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",vf]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},wf]}],"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:[...k(),"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:k()}],"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:["",...k()]}],"outline-offset":[{"outline-offset":[Bs,Ye]}],"outline-w":[{outline:[Bs,qs]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:B()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[C]}],"ring-offset-w":[{"ring-offset":[Bs,qs]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",ea,Cf]}],"shadow-color":[{shadow:[or]}],opacity:[{opacity:[C]}],"mix-blend":[{"mix-blend":[...I(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":I()}],filter:[{filter:["","none"]}],blur:[{blur:[a]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",ea,Ye]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[m]}],invert:[{invert:[u]}],saturate:[{saturate:[j]}],sepia:[{sepia:[N]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[a]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[m]}],"backdrop-invert":[{"backdrop-invert":[u]}],"backdrop-opacity":[{"backdrop-opacity":[C]}],"backdrop-saturate":[{"backdrop-saturate":[j]}],"backdrop-sepia":[{"backdrop-sepia":[N]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[o]}],"border-spacing-x":[{"border-spacing-x":[o]}],"border-spacing-y":[{"border-spacing-y":[o]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",Ye]}],duration:[{duration:L()}],ease:[{ease:["linear","in","out","in-out",Ye]}],delay:[{delay:L()}],animate:[{animate:["none","spin","ping","pulse","bounce",Ye]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[b]}],"scale-x":[{"scale-x":[b]}],"scale-y":[{"scale-y":[b]}],rotate:[{rotate:[ir,Ye]}],"translate-x":[{"translate-x":[T]}],"translate-y":[{"translate-y":[T]}],"skew-x":[{"skew-x":[A]}],"skew-y":[{"skew-y":[A]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Ye]}],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",Ye]}],"caret-color":[{caret:[t]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":M()}],"scroll-mx":[{"scroll-mx":M()}],"scroll-my":[{"scroll-my":M()}],"scroll-ms":[{"scroll-ms":M()}],"scroll-me":[{"scroll-me":M()}],"scroll-mt":[{"scroll-mt":M()}],"scroll-mr":[{"scroll-mr":M()}],"scroll-mb":[{"scroll-mb":M()}],"scroll-ml":[{"scroll-ml":M()}],"scroll-p":[{"scroll-p":M()}],"scroll-px":[{"scroll-px":M()}],"scroll-py":[{"scroll-py":M()}],"scroll-ps":[{"scroll-ps":M()}],"scroll-pe":[{"scroll-pe":M()}],"scroll-pt":[{"scroll-pt":M()}],"scroll-pr":[{"scroll-pr":M()}],"scroll-pb":[{"scroll-pb":M()}],"scroll-pl":[{"scroll-pl":M()}],"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",Ye]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[Bs,qs,Kn]}],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"]}}},Df=df(Tf);function fe(...t){return Df(Rd(t))}const br=lm("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"}}),R=x.forwardRef(({className:t,variant:s,size:a,asChild:r=!1,...n},i)=>{const o=r?vd:"button";return e.jsx(o,{"data-slot":"button",className:fe(br({variant:s,size:a,className:t})),ref:i,...n})});R.displayName="Button";function Z({className:t,...s}){return e.jsx("div",{"data-slot":"card",className:fe("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border",t),...s})}function ae({className:t,...s}){return e.jsx("div",{"data-slot":"card-header",className:fe("@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 ne({className:t,...s}){return e.jsx("h4",{"data-slot":"card-title",className:fe("leading-none",t),...s})}function we({className:t,...s}){return e.jsx("p",{"data-slot":"card-description",className:fe("text-muted-foreground",t),...s})}function X({className:t,...s}){return e.jsx("div",{"data-slot":"card-content",className:fe("px-6 [&:last-child]:pb-6",t),...s})}const No="/assets/Re_Logo-By51taPS.png";function Rf(){const{login:t,isLoading:s,error:a}=ts(),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(Z,{className:"w-full max-w-md shadow-xl",children:[e.jsx(ae,{className:"space-y-1 text-center pb-6",children:e.jsxs("div",{className:"flex flex-col items-center justify-center mb-4",children:[e.jsx("img",{src:No,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(X,{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(R,{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(Nx,{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 pm(){const{isAuthenticated:t,isLoading:s,error:a,user:r}=ts(),[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:No,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(Ai,{className:"w-16 h-16 text-green-500"})}),e.jsx(Ai,{className:"w-16 h-16 text-green-500 relative"})]}):e.jsxs("div",{className:"relative",children:[e.jsx(Xe,{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 Pf=lm("inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",secondary:"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",destructive:"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"}},defaultVariants:{variant:"default"}});function ee({className:t,variant:s,asChild:a=!1,...r}){const n=a?vd:"span";return e.jsx(n,{"data-slot":"badge",className:fe(Pf({variant:s}),t),...r})}function Ef({isOpen:t,onClose:s}){const{user:a,isAuthenticated:r,isLoading:n,error:i}=Hg();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(Z,{className:"w-full max-w-2xl max-h-[90vh] overflow-auto",children:[e.jsx(ae,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{children:"Authentication Debug Information"}),e.jsx(R,{variant:"ghost",size:"icon",onClick:s,children:e.jsx(ut,{className:"h-4 w-4"})})]})}),e.jsxs(X,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold",children:"Status:"}),e.jsx(ee,{variant:r?"default":"destructive",children:n?"Loading...":r?"Authenticated":"Not Authenticated"})]}),i&&e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded p-3",children:[e.jsx("p",{className:"text-sm text-red-700 font-semibold",children:"Error:"}),e.jsx("p",{className:"text-sm text-red-600",children:i.message})]}),a&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-semibold",children:"User Information:"}),e.jsx("pre",{className:"bg-gray-50 p-3 rounded text-xs overflow-auto",children:JSON.stringify(a,null,2)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-semibold",children:"All Auth Claims:"}),e.jsx("pre",{className:"bg-gray-50 p-3 rounded text-xs overflow-auto",children:JSON.stringify({isAuthenticated:r,isLoading:n,error:(i==null?void 0:i.message)||null,hasUser:!!a},null,2)})]})]})]})}):null}const $t=x.forwardRef(({className:t,...s},a)=>e.jsx(jd,{ref:a,"data-slot":"avatar",className:fe("relative flex size-10 shrink-0 overflow-hidden rounded-full",t),...s}));$t.displayName=jd.displayName;const Sn=x.forwardRef(({className:t,...s},a)=>e.jsx(Nd,{ref:a,"data-slot":"avatar-image",className:fe("aspect-square size-full",t),...s}));Sn.displayName=Nd.displayName;const Ut=x.forwardRef(({className:t,...s},a)=>e.jsx(wd,{ref:a,"data-slot":"avatar-fallback",className:fe("bg-muted flex size-full items-center justify-center rounded-full",t),...s}));Ut.displayName=wd.displayName;function Il({...t}){return e.jsx(tp,{"data-slot":"dropdown-menu",...t})}function Ml({...t}){return e.jsx(sp,{"data-slot":"dropdown-menu-trigger",...t})}function Fl({className:t,sideOffset:s=4,...a}){return e.jsx(ap,{children:e.jsx(rp,{"data-slot":"dropdown-menu-content",sideOffset:s,className:fe("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 Gn({className:t,inset:s,variant:a="default",...r}){return e.jsx(np,{"data-slot":"dropdown-menu-item","data-inset":s,"data-variant":a,className:fe("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 If({...t}){return e.jsx(op,{"data-slot":"alert-dialog",...t})}function Mf({...t}){return e.jsx(ip,{"data-slot":"alert-dialog-portal",...t})}const xm=x.forwardRef(({className:t,...s},a)=>e.jsx(Cd,{"data-slot":"alert-dialog-overlay",className:fe("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}));xm.displayName=Cd.displayName;const gm=x.forwardRef(({className:t,...s},a)=>e.jsxs(Mf,{children:[e.jsx(xm,{}),e.jsx(Sd,{"data-slot":"alert-dialog-content",ref:a,className:fe("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})]}));gm.displayName=Sd.displayName;function Ff({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-header",className:fe("flex flex-col gap-2 text-center sm:text-left",t),...s})}function _f({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-footer",className:fe("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s})}function Lf({className:t,...s}){return e.jsx(lp,{"data-slot":"alert-dialog-title",className:fe("text-lg font-semibold",t),...s})}function Of({className:t,...s}){return e.jsx(cp,{"data-slot":"alert-dialog-description",className:fe("text-muted-foreground text-sm",t),...s})}function $f({className:t,...s}){return e.jsx(mp,{className:fe(br(),t),...s})}function Uf({className:t,...s}){return e.jsx(dp,{className:fe(br({variant:"outline"}),t),...s})}const aa={async list(t){return(await ce.get("/notifications",{params:t})).data},async getUnreadCount(){return(await ce.get("/notifications/unread-count")).data},async markAsRead(t){return(await ce.patch(`/notifications/${t}/read`)).data},async markAllAsRead(){return(await ce.post("/notifications/mark-all-read")).data},async delete(t){return(await ce.delete(`/notifications/${t}`)).data}},Bf=async()=>(await ce.get("/notifications/subscriptions")).data.data.subscriptions;let ba=null;function Vf(){return"https://re-workflow-nt-dev.siplsolutions.com"}function vr(t){const s=Vf();return ba||(ba=cg(s,{withCredentials:!0,transports:["websocket","polling"],path:"/socket.io",reconnection:!0,reconnectionDelay:1e3,reconnectionAttempts:5}),ba.on("connect",()=>{}),ba.on("connect_error",a=>{console.error("[Socket] Connection error:",a.message)}),ba.on("disconnect",a=>{}),ba)}function Ei(t,s,a){a?t.emit("join:request",{requestId:s,userId:a}):t.emit("join:request",s)}function fm(t,s){t.emit("leave:request",s)}function zf(t,s){t.emit("join:user",{userId:s})}function Xt({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}=ts(),v=()=>{var N,A;try{if(y!=null&&y.displayName&&typeof y.displayName=="string"){const D=y.displayName.split(" ").filter(Boolean);return D.length>=2?`${((N=D[0])==null?void 0:N[0])||""}${((A=D[D.length-1])==null?void 0:A[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(D){return console.error("[PageLayout] Error getting user initials:",D),"U"}},C=x.useMemo(()=>{const N=[{id:"dashboard",label:"Dashboard",icon:wx},{id:"requests",label:"All Requests",icon:Bd}];return N.push({id:"my-requests",label:"My Requests",icon:St},{id:"open-requests",label:"Open Requests",icon:Re},{id:"closed-requests",label:"Closed Requests",icon:Ce},{id:"shared-summaries",label:"Shared Summary",icon:Ya}),N},[]),f=()=>{o(!i)},j=async N=>{var A;try{if(N.isRead||(await aa.markAsRead(N.notificationId),m(D=>D.map(T=>T.notificationId===N.notificationId?{...T,isRead:!0}:T)),h(D=>Math.max(0,D-1))),N.actionUrl&&a){const D=(A=N.metadata)==null?void 0:A.requestNumber;if(D){let T=`request/${D}`;(N.notificationType==="mention"||N.notificationType==="comment"||N.notificationType==="worknote")&&(T+="?tab=worknotes"),a(T)}}g(!1)}catch(D){console.error("[PageLayout] Error handling notification click:",D)}},b=async()=>{try{await aa.markAllAsRead(),m(N=>N.map(A=>({...A,isRead:!0}))),h(0)}catch(N){console.error("[PageLayout] Error marking all as read:",N)}};return x.useEffect(()=>{const N=y==null?void 0:y.userId;if(!N)return;let A=!0;(async()=>{var P,w;try{const S=await aa.list({page:1,limit:4,unreadOnly:!1});if(!A)return;const M=((P=S.data)==null?void 0:P.notifications)||[];m(M),h(((w=S.data)==null?void 0:w.unreadCount)||0)}catch(S){console.error("[PageLayout] Failed to fetch notifications:",S)}})();const T=vr();if(T){zf(T,N);const P=w=>{A&&(m(S=>[w.notification,...S].slice(0,4)),h(S=>S+1))};return T.on("notification:new",P),()=>{A=!1,T.off("notification:new",P)}}return()=>{A=!1}},[y]),x.useEffect(()=>{const N=()=>{window.innerWidth>=768?o(!0):o(!1)};return N(),window.addEventListener("resize",N),()=>window.removeEventListener("resize",N)},[]),e.jsxs("div",{className:"min-h-screen flex w-full bg-background",children:[i&&e.jsx("div",{className:"fixed inset-0 bg-black/50 z-40 md:hidden",onClick:()=>o(!1)}),e.jsx("aside",{className:`
|
||
fixed md:relative
|
||
inset-y-0 left-0
|
||
w-64
|
||
transform transition-transform duration-300 ease-in-out
|
||
${i?"translate-x-0":"-translate-x-full"}
|
||
md:translate-x-0
|
||
${i?"md:w-64":"md:w-0"}
|
||
z-50 md:z-auto
|
||
flex-shrink-0
|
||
border-r border-gray-800 bg-black
|
||
flex flex-col
|
||
overflow-hidden
|
||
`,children:e.jsxs("div",{className:`w-64 h-full flex flex-col overflow-hidden ${i?"":"md:hidden"}`,children:[e.jsx("div",{className:"p-4 border-b border-gray-800 flex-shrink-0",children:e.jsxs("div",{className:"flex flex-col items-center justify-center",children:[e.jsx("img",{src:No,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(N=>e.jsxs("button",{onClick:()=>{a==null||a(N.id),window.innerWidth<768&&o(!1)},className:`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-colors ${s===N.id?"bg-re-green text-white font-medium":"text-gray-300 hover:bg-gray-900 hover:text-white"}`,children:[e.jsx(N.icon,{className:"w-4 h-4 shrink-0"}),e.jsx("span",{className:"truncate",children:N.label})]},N.id))}),e.jsx("div",{className:"mt-6 pt-6 border-t border-gray-800 px-3",children:e.jsxs(R,{onClick:r,className:"w-full bg-re-green hover:bg-re-green/90 text-white text-sm font-medium",size:"sm",children:[e.jsx(Is,{className:"w-4 h-4 mr-2"}),"Raise New Request"]})})]})]})}),e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsxs("header",{className:"h-16 border-b border-gray-200 bg-white flex items-center justify-between px-6 shrink-0",children:[e.jsx("div",{className:"flex items-center gap-4 min-w-0 flex-1",children:e.jsx(R,{variant:"ghost",size:"icon",onClick:f,className:"shrink-0 h-10 w-10 sidebar-toggle",children:i?e.jsx(Cx,{className:"w-5 h-5 text-gray-600"}):e.jsx(Sx,{className:"w-5 h-5 text-gray-600"})})}),e.jsxs("div",{className:"flex items-center gap-4 shrink-0",children:[e.jsxs(R,{onClick:r,className:"bg-re-green hover:bg-re-green/90 text-white gap-2 hidden md:flex text-sm",size:"sm",children:[e.jsx(Is,{className:"w-4 h-4"}),"New Request"]}),e.jsxs(Il,{open:p,onOpenChange:g,children:[e.jsx(Ml,{asChild:!0,children:e.jsxs(R,{variant:"ghost",size:"icon",className:"relative shrink-0 h-10 w-10",children:[e.jsx(as,{className:"w-5 h-5"}),u>0&&e.jsx(ee,{className:"absolute -top-1 -right-1 w-5 h-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center p-0",children:u>9?"9+":u})]})}),e.jsxs(Fl,{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(R,{variant:"ghost",size:"sm",className:"text-xs text-blue-600 hover:text-blue-700 h-auto p-1",onClick:N=>{N.stopPropagation(),b()},children:"Mark all as read"})]}),e.jsx("div",{className:"max-h-[400px] overflow-y-auto",children:d.length===0?e.jsxs("div",{className:"p-6 text-center",children:[e.jsx(as,{className:"w-12 h-12 text-gray-300 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-gray-500",children:"No notifications yet"})]}):e.jsx("div",{className:"divide-y",children:d.map(N=>e.jsx("div",{className:`p-3 hover:bg-gray-50 cursor-pointer transition-colors ${N.isRead?"":"bg-blue-50"}`,onClick:()=>j(N),children:e.jsxs("div",{className:"flex gap-2",children:[!N.isRead&&e.jsx("div",{className:"w-2 h-2 rounded-full bg-blue-600 mt-1.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`text-sm ${N.isRead?"font-medium":"font-semibold"}`,children:N.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-2",children:N.message}),e.jsx("p",{className:"text-xs text-gray-400 mt-1",children:_d(new Date(N.createdAt),{addSuffix:!0})})]})]})},N.notificationId))})}),d.length>0&&e.jsx("div",{className:"p-2 border-t",children:e.jsx(R,{variant:"ghost",className:"w-full text-sm text-blue-600 hover:text-blue-700",onClick:()=>{g(!1),a==null||a("notifications")},children:"View all notifications"})})]})]}),e.jsxs(Il,{children:[e.jsx(Ml,{asChild:!0,children:e.jsxs($t,{className:"cursor-pointer shrink-0 h-10 w-10",children:[e.jsx(Sn,{src:(y==null?void 0:y.picture)||""}),e.jsx(Ut,{className:"bg-re-green text-white text-sm",children:v()})]})}),e.jsxs(Fl,{align:"end",children:[e.jsxs(Gn,{onClick:()=>a==null?void 0:a("profile"),children:[e.jsx(St,{className:"w-4 h-4 mr-2"}),"Profile"]}),e.jsxs(Gn,{onClick:()=>a==null?void 0:a("settings"),children:[e.jsx(la,{className:"w-4 h-4 mr-2"}),"Settings"]}),e.jsxs(Gn,{onClick:()=>c(!0),className:"text-red-600 focus:text-red-600",children:[e.jsx(Un,{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(If,{open:l,onOpenChange:c,children:e.jsxs(gm,{children:[e.jsxs(Ff,{children:[e.jsxs(Lf,{className:"flex items-center gap-2",children:[e.jsx(Un,{className:"w-5 h-5 text-red-600"}),"Confirm Logout"]}),e.jsx(Of,{className:"pt-2",children:"Are you sure you want to logout? You will need to sign in again to access your account."})]}),e.jsxs(_f,{children:[e.jsx(Uf,{onClick:()=>c(!1),children:"Cancel"}),e.jsxs($f,{onClick:async()=>{if(c(!1),n)try{await n()}catch(N){console.error("🔴 Error calling onLogout:",N)}else console.error("🔴 ERROR: onLogout is undefined!")},className:"bg-red-600 hover:bg-red-700 text-white focus:ring-red-600",children:[e.jsx(Un,{className:"w-4 h-4 mr-2"}),"Logout"]})]})]})})]})}const Pr=()=>Fg(),qa=Og,Hf=()=>{try{const t=localStorage.getItem("dashboard_viewAsUser");return t?JSON.parse(t):!1}catch{return!1}},Wf={viewAsUser:Hf()},ym=Ja({name:"dashboard",initialState:Wf,reducers:{setViewAsUser:(t,s)=>{t.viewAsUser=s.payload,localStorage.setItem("dashboard_viewAsUser",JSON.stringify(s.payload))}}}),{setViewAsUser:Kf}=ym.actions;function Gf(){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 Yf(){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 Zf{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 ce.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 ce.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 ce.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 ce.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 ce.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 ce.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 ce.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 ce.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 ce.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 ce.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 ce.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 ce.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 ce.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 ce.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 ce.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 ce.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 ce.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 ce.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 ce.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 mt=new Zf;function Xf({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),[N,A]=x.useState([]),[D,T]=x.useState(!0),[P,w]=x.useState(!1),S=x.useRef(o);S.current=o;const M=x.useCallback(async(I=!1)=>{try{I?w(!0):T(!0);const E=[mt.getKPIs(r,n,i,s),mt.getRecentActivity(1,10,s),mt.getCriticalRequests(1,10,s),mt.getUpcomingDeadlines(1,10,s)],F=!t&&a?mt.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,O=t?[mt.getDepartmentStats(r,n,i),mt.getPriorityDistribution(r,n,i),mt.getAIRemarkUtilization(r,n,i),mt.getApproverPerformance(r,1,10,n,i)]:[],[L,J,U]=await Promise.all([Promise.all(E),F,Promise.all(O)]),oe=L[0],ge=L[1],G=L[2],me=L[3];if(!t&&J&&(oe.requestVolume=J),c(oe),m(ge.activities),S.current.activity(ge.pagination.currentPage,ge.pagination.totalPages,ge.pagination.totalRecords),h(G.criticalRequests),S.current.critical(G.pagination.currentPage,G.pagination.totalPages,G.pagination.totalRecords),f(me.deadlines),S.current.deadlines(me.pagination.currentPage,me.pagination.totalPages,me.pagination.totalRecords),t&&U.length>=4){const re=U[0],V=U[1],q=U[2],ie=U[3];g(re),v(V),b(q),A(ie.performance),S.current.approver(ie.pagination.currentPage,ie.pagination.totalPages,ie.pagination.totalRecords)}else t||(g([]),v([]),b(null),A([]))}catch(E){console.error("Failed to fetch dashboard data:",E)}finally{T(!1),w(!1)}},[t,s,a,r,n,i]),B=x.useCallback(async(I=1)=>{try{const E=await mt.getRecentActivity(I,10,s);m(E.activities),S.current.activity(E.pagination.currentPage,E.pagination.totalPages,E.pagination.totalRecords)}catch(E){console.error("Failed to fetch recent activities:",E)}},[s]),_=x.useCallback(async(I=1)=>{try{const E=await mt.getCriticalRequests(I,10,s);h(E.criticalRequests),S.current.critical(E.pagination.currentPage,E.pagination.totalPages,E.pagination.totalRecords)}catch(E){console.error("Failed to fetch critical requests:",E)}},[s]),$=x.useCallback(async(I=1)=>{try{const E=await mt.getUpcomingDeadlines(I,10,s);f(E.deadlines),S.current.deadlines(E.pagination.currentPage,E.pagination.totalPages,E.pagination.totalRecords)}catch(E){console.error("Failed to fetch upcoming deadlines:",E)}},[s]),k=x.useCallback(async(I=1)=>{try{const E=await mt.getApproverPerformance(r,I,10,n,i);A(E.performance),S.current.approver(E.pagination.currentPage,E.pagination.totalPages,E.pagination.totalRecords)}catch(E){console.error("Failed to fetch approver performance:",E)}},[r,n,i]);return{kpis:l,recentActivity:d,criticalRequests:u,departmentStats:p,priorityDistribution:y,upcomingDeadlines:C,aiRemarkUtilization:j,approverPerformance:N,loading:D,refreshing:P,fetchDashboardData:M,fetchRecentActivities:B,fetchCriticalRequests:_,fetchUpcomingDeadlines:$,fetchApproverPerformance:k}}const Vs={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 Jf{constructor(){_n(this,"config",null);_n(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 ce.get("/config"),r=((s=a.data)==null?void 0:s.data)||a.data;return{...Vs,...r,workingHours:{...Vs.workingHours,...r.workingHours},tat:{...Vs.tat,...r.tat},upload:{...Vs.upload,...r.upload},workflow:{...Vs.workflow,...r.workflow},workNotes:{...Vs.workNotes,...r.workNotes},features:{...Vs.features,...r.features},ui:{...Vs.ui,...r.ui}}}catch(a){return console.error("[ConfigService] ⚠️ Failed to fetch config from server, using defaults:",a),Vs}}async refreshConfig(){return this.config=null,this.loading=null,this.getConfig()}getCachedConfig(){return this.config}isLoaded(){return this.config!==null}}const Qf=new Jf;let qf=9,e0=18,t0=1,s0=5,_l=!1;async function a0(){if(!_l)try{const t=await Qf.getConfig();qf=t.workingHours.START_HOUR,e0=t.workingHours.END_HOUR,t0=t.workingHours.START_DAY,s0=t.workingHours.END_DAY,_l=!0}catch{console.warn("[SLA Tracker] ⚠️ Using default working hours (9 AM - 6 PM)")}}a0().catch(()=>{});function At(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 r0(t,s,a){const r=[];let n=1,i=!0;const o=100;for(;i&&n<=o;){const h=await mt.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,At(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 n0(t,s,a){const r=await mt.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 i0(){const[t,s]=x.useState(!1),[a,r]=x.useState(!1),n=x.useCallback(async(o,l,c)=>{try{s(!0),await n0(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 r0(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 ns({className:t,...s}){return e.jsx(up,{"data-slot":"switch",className:fe("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(hp,{"data-slot":"switch-thumb",className:fe("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 Y({className:t,...s}){return e.jsx(pp,{"data-slot":"label",className:fe("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 o0({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(Z,{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(X,{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(Vd,{className:`w-3 h-3 sm:w-3.5 sm:h-3.5 ${a?"text-gray-300":"text-red-600"}`}),e.jsx(Y,{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(ns,{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(St,{className:`w-3 h-3 sm:w-3.5 sm:h-3.5 ${a?"text-red-600":"text-gray-300"}`}),e.jsx(Y,{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(R,{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 _e({...t}){return e.jsx(xp,{"data-slot":"select",...t})}function Le({...t}){return e.jsx(yp,{"data-slot":"select-value",...t})}function Oe({className:t,size:s="default",children:a,...r}){return e.jsxs(gp,{"data-slot":"select-trigger","data-size":s,className:fe("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(fp,{asChild:!0,children:e.jsx(zd,{className:"size-4 opacity-50"})})]})}function $e({className:t,children:s,position:a="popper",...r}){return e.jsx(bp,{children:e.jsxs(vp,{"data-slot":"select-content",className:fe("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(l0,{}),e.jsx(jp,{className:fe("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(c0,{})]})})}function H({className:t,children:s,...a}){return e.jsxs(Np,{"data-slot":"select-item",className:fe("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(wp,{children:e.jsx(Za,{className:"size-4"})})}),e.jsx(Cp,{children:s})]})}function l0({className:t,...s}){return e.jsx(Sp,{"data-slot":"select-scroll-up-button",className:fe("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(Ax,{className:"size-4"})})}function c0({className:t,...s}){return e.jsx(Ap,{"data-slot":"select-scroll-down-button",className:fe("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(zd,{className:"size-4"})})}function Tt({className:t,orientation:s="horizontal",decorative:a=!0,...r}){return e.jsx(kp,{"data-slot":"separator-root",decorative:a,orientation:s,className:fe("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 ra({...t}){return e.jsx(Tp,{"data-slot":"popover",...t})}function na({...t}){return e.jsx(Dp,{"data-slot":"popover-trigger",...t})}function ia({className:t,align:s="center",sideOffset:a=4,...r}){return e.jsx(Rp,{children:e.jsx(Pp,{"data-slot":"popover-content",align:s,sideOffset:a,className:fe("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 je({className:t,type:s,...a}){return e.jsx("input",{type:s,"data-slot":"input",className:fe("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 d0({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(Z,{className:"shadow-md","data-testid":"dashboard-filters-bar",children:e.jsx(X,{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(kr,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Filters"}),t&&e.jsx(ee,{variant:"outline",className:"bg-purple-50 text-purple-700 border-purple-200","data-testid":"management-badge",children:"Management View"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 w-full sm:w-auto",children:[t?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(et,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(_e,{value:s,onValueChange:o,"data-testid":"date-range-select",children:[e.jsx(Oe,{className:"w-[140px]",children:e.jsx(Le,{placeholder:"Select period"})}),e.jsxs($e,{children:[e.jsx(H,{value:"all",children:"All Time"}),e.jsx(H,{value:"today",children:"Today"}),e.jsx(H,{value:"week",children:"This Week"}),e.jsx(H,{value:"month",children:"This Month"}),e.jsx(H,{value:"last7days",children:"Last 7 Days"}),e.jsx(H,{value:"last30days",children:"Last 30 Days"}),e.jsx(H,{value:"custom",children:"Custom Range"})]})]}),s==="custom"&&e.jsxs(ra,{open:n,onOpenChange:d,children:[e.jsx(na,{asChild:!0,children:e.jsxs(R,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(et,{className:"w-4 h-4"}),a&&r?`${Ne(a,"MMM d, yyyy")} - ${Ne(r,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(ia,{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(Y,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(je,{id:"start-date",type:"date",value:a?Ne(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:Ne(new Date,"yyyy-MM-dd"),className:"w-full","data-testid":"start-date-input"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Y,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(je,{id:"end-date",type:"date",value:r?Ne(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?Ne(a,"yyyy-MM-dd"):void 0,max:Ne(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(R,{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(R,{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(et,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(_e,{value:s,onValueChange:p=>o(p),"data-testid":"date-range-select-user",children:[e.jsx(Oe,{className:"w-[140px]",children:e.jsx(Le,{placeholder:"Select period"})}),e.jsxs($e,{children:[e.jsx(H,{value:"all",children:"All Time"}),e.jsx(H,{value:"today",children:"Today"}),e.jsx(H,{value:"week",children:"This Week"}),e.jsx(H,{value:"month",children:"This Month"}),e.jsx(H,{value:"last7days",children:"Last 7 Days"}),e.jsx(H,{value:"last30days",children:"Last 30 Days"}),e.jsx(H,{value:"custom",children:"Custom Range"})]})]})]}),e.jsx(Tt,{orientation:"vertical",className:"h-6 hidden sm:block"}),e.jsxs(R,{variant:"outline",size:"sm",onClick:h,disabled:i,className:"gap-2 min-w-[110px]","data-testid":"refresh-button",children:[e.jsx(es,{className:`w-4 h-4 ${i?"animate-spin":""}`}),e.jsx("span",{className:"inline-block w-[60px] text-center",children:i?"Refreshing...":"Refresh"})]})]})]})})})}function ka({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(Z,{className:"hover:shadow-lg transition-all duration-200 shadow-md cursor-pointer h-full flex flex-col",onClick:c,"data-testid":l,children:[e.jsxs(ae,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(ne,{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(Tr,{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(X,{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 Wt({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 _s({className:t,value:s,indicatorClassName:a,...r}){return e.jsx(Ep,{"data-slot":"progress",className:fe("bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",t),...r,children:e.jsx(Ip,{"data-slot":"progress-indicator",className:fe("bg-primary h-full w-full flex-1 transition-all",a),style:{transform:`translateX(-${100-(s||0)}%)`}})})}function m0({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(ka,{title:"Total Requests",value:(t==null?void 0:t.requestVolume.totalRequests)||0,icon:Re,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(Wt,{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(Wt,{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(Wt,{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(Wt,{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(Wt,{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(ka,{title:"SLA Compliance",value:`${(t==null?void 0:t.tatEfficiency.avgTATCompliance)||0}%`,icon:kt,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(_s,{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(Wt,{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(Wt,{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(ka,{title:"Avg Cycle Time",value:t!=null&&t.tatEfficiency.avgCycleTimeHours?At(t.tatEfficiency.avgCycleTimeHours):"0 hours",icon:Ue,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(Wt,{label:"Express",value:(()=>{const l=s.find(d=>d.priority==="express"),c=l?Number(l.avgCycleTimeHours):0;return c>0?At(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(Wt,{label:"Standard",value:(()=>{const l=s.find(d=>d.priority==="standard"),c=l?Number(l.avgCycleTimeHours):0;return c>0?At(c):"N/A"})(),bgColor:"bg-blue-50",textColor:"text-blue-600",testId:"stat-standard-time",onClick:l=>{l.stopPropagation(),i({...o(),priority:"standard"})}})]})})})]})}function u0({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(ka,{title:"My Requests (Submitted)",value:(t==null?void 0:t.requestVolume.totalRequests)||0,icon:Re,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(Wt,{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(Wt,{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(Wt,{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(Wt,{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(Wt,{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(ka,{title:"Awaiting My Approval",value:(t==null?void 0:t.approverLoad.pendingActions)||0,icon:Ue,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(Wt,{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(Wt,{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(ka,{title:"Critical Alerts",value:s.length,icon:Ts,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(Wt,{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(Wt,{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(ka,{title:"Success Rate",value:`${u.toFixed(0)}%`,icon:Ce,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(_s,{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 h0=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)))},p0=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 x0({alert:t,onNavigate:s,testId:a="critical-alert-card"}){const r=h0(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(kx,{className:"h-3 w-3 text-red-500 flex-shrink-0","data-testid":`${a}-priority-icon`}),t.breachCount>0&&e.jsx(ee,{variant:"destructive",className:"text-xs","data-testid":`${a}-breach-count`,children:t.breachCount})]}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-700 line-clamp-2","data-testid":`${a}-title`,children:t.title})]}),e.jsx(ee,{variant:"outline",className:"text-xs bg-white border-red-200 text-red-700 font-medium whitespace-nowrap","data-testid":`${a}-remaining-time`,children:p0(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(_s,{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 g0(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 f0(t){return t.filter(s=>{const a=Number(s.tatPercentageUsed)||0;return(Number(s.remainingHours)||0)>0&&a<100})}function y0(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 b0(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 bm(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 v0({isAdmin:t,breachedRequests:s,pagination:a,onPageChange:r,onNavigate:n}){return e.jsxs(Z,{className:"lg:col-span-2 shadow-md hover:shadow-lg transition-shadow flex flex-col overflow-hidden",style:{height:"100%"},"data-testid":"critical-alerts-section",children:[e.jsx(ae,{className:"pb-3 sm:pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("div",{className:"p-2 sm:p-3 bg-red-100 rounded-lg",children:e.jsx(Ts,{className:"h-4 w-4 sm:h-5 sm:w-5 text-red-600"})}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-base sm:text-lg text-gray-900",children:"Critical Alerts"}),e.jsx(we,{className:"text-xs sm:text-sm text-gray-600",children:t?"Organization-wide":"My requests"})]})]}),e.jsx(ee,{variant:"destructive",className:`font-semibold text-xs sm:text-sm ${a.totalRecords>0?"animate-pulse":""}`,"data-testid":"critical-count-badge",children:a.totalRecords})]})}),e.jsx(X,{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(Ce,{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(x0,{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(R,{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(Vt,{className:"h-3 w-3 rotate-180"})}),bm(a.page,a.totalPages,3).map(i=>e.jsx(R,{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(R,{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(Vt,{className:"h-3 w-3"})})]})]})})]})}const j0=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"}},N0=t=>{const s=new Date,a=new Date(t),r=cx(s,a);if(r<1)return"just now";if(r<60)return`${r} minute${r>1?"s":""} ago`;const n=dx(s,a);if(n<24)return`${n} hour${n>1?"s":""} ago`;const i=mx(s,a);return`${i} day${i>1?"s":""} ago`},w0=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()},C0=t=>{const s=t.toLowerCase();return s.includes("approv")?e.jsx(Ce,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-green-600"}):s.includes("reject")?e.jsx(Cs,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-red-600"}):s.includes("comment")?e.jsx(Ds,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-blue-600"}):s.includes("escalat")?e.jsx(Ts,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-orange-600"}):s.includes("submit")?e.jsx(Re,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-purple-600"}):s.includes("document")?e.jsx(fn,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-indigo-600"}):e.jsx(qt,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-gray-600"})};function S0({activity:t,currentUserId:s,currentUserDisplayName:a,currentUserEmail:r,onNavigate:n,testId:i="activity-feed-item"}){const o=t.userId===s,l=o?"You":t.userName||"System",c=o?(a||r||"ME").split(" ").map(d=>d[0]).join("").toUpperCase().substring(0,2):t.userName?t.userName.split(" ").map(d=>d[0]).join("").toUpperCase().substring(0,2):"SY";return e.jsxs("div",{className:"flex items-start gap-2 sm:gap-3 p-3 sm:p-4 rounded-lg hover:bg-gray-50 transition-all duration-200 cursor-pointer border border-gray-100 hover:border-gray-300",onClick:()=>n==null?void 0:n(t.requestNumber),"data-testid":`${i}-${t.activityId}`,children:[e.jsxs("div",{className:"relative flex-shrink-0 mt-0.5",children:[e.jsxs($t,{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(Sn,{src:""}),e.jsx(Ut,{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:C0(t.action)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"flex items-center justify-between gap-2 mb-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold text-xs sm:text-sm text-gray-900","data-testid":`${i}-request-number`,children:t.requestNumber}),e.jsx(ee,{variant:"outline",className:`text-xs ${j0(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:w0(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:N0(t.timestamp)})]})]}),e.jsx(Vt,{className:"h-4 w-4 text-gray-400 hover:text-blue-600 transition-colors flex-shrink-0 hidden sm:block mt-1","data-testid":`${i}-arrow`})]})}function A0({isAdmin:t,recentActivity:s,pagination:a,refreshing:r,onPageChange:n,onRefresh:i,onNavigate:o,currentUserId:l,currentUserDisplayName:c,currentUserEmail:d}){return e.jsxs(Z,{className:"lg:col-span-1 shadow-md hover:shadow-lg transition-shadow flex flex-col overflow-hidden",style:{height:"100%"},"data-testid":"recent-activity-section",children:[e.jsx(ae,{className:"pb-3 sm:pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-1 min-w-0",children:[e.jsx("div",{className:"p-2 sm:p-3 bg-blue-100 rounded-lg",children:e.jsx(qt,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx(ne,{className:"text-base sm:text-lg text-gray-900",children:"Recent Activity"}),e.jsx(we,{className:"text-xs sm:text-sm text-gray-600 truncate",children:t?"All workflow updates":"My workflow updates"})]})]}),e.jsxs(R,{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(es,{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(X,{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(qt,{className:"w-10 h-10 sm:w-12 sm:h-12 mx-auto mb-2 text-gray-400"}),e.jsx("p",{className:"text-sm",children:"No recent activity"}),e.jsx("p",{className:"text-xs",children:"Activity will appear here once requests are processed"})]}):s.map(m=>e.jsx(S0,{activity:m,currentUserId:l,currentUserDisplayName:c,currentUserEmail:d,onNavigate:u=>o==null?void 0:o(`request/${u}`),testId:"dashboard-activity"},m.activityId))})}),a.totalPages>1&&s.length>0&&e.jsx("div",{className:"border-t bg-gray-50 px-4 py-2 flex-shrink-0",children:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["Page ",a.page," of ",a.totalPages," (",a.totalRecords," total)"]}),e.jsxs("div",{className:"flex items-center justify-center gap-1 flex-wrap",children:[e.jsx(R,{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(Vt,{className:"h-3 w-3 rotate-180"})}),bm(a.page,a.totalPages,3).map(m=>e.jsx(R,{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(R,{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(Vt,{className:"h-3 w-3"})})]})]})})]})}function k0({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(Z,{className:"shadow-md hover:shadow-lg transition-shadow flex-1","data-testid":"active-levels-card",children:[e.jsx(ae,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-2 bg-blue-100 rounded-lg",children:e.jsx(qt,{className:"h-4 w-4 text-blue-600"})}),e.jsx(ne,{className:"text-sm",children:"Active Levels"})]})}),e.jsx(X,{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(Tt,{}),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(Z,{className:"shadow-md hover:shadow-lg transition-shadow flex-1","data-testid":"collaboration-card",children:[e.jsx(ae,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-2 bg-indigo-100 rounded-lg",children:e.jsx(Ds,{className:"h-4 w-4 text-indigo-600"})}),e.jsx(ne,{className:"text-sm",children:"Collaboration"})]})}),e.jsx(X,{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(Tt,{}),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(Z,{className:"shadow-md hover:shadow-lg transition-shadow lg:col-span-2","data-testid":"department-stats-card",children:[e.jsx(ae,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"bg-blue-50 p-2 sm:p-3 rounded-lg",children:e.jsx(Tx,{className:"h-5 w-5 sm:h-6 sm:w-6 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-base sm:text-lg lg:text-xl",children:"Department-wise Workflow Summary"}),e.jsx(we,{className:"text-xs sm:text-sm",children:"Workflow distribution across departments"})]})]}),e.jsxs(R,{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(Qt,{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(X,{children:e.jsx(ro,{width:"100%",height:400,children:e.jsxs(ax,{data:r,children:[e.jsx(Pd,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(Ed,{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(Id,{stroke:"#999",tick:{fontSize:11}}),e.jsx(no,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(Md,{verticalAlign:"bottom",height:36,iconType:"square",wrapperStyle:{fontSize:"12px",paddingTop:"10px"}}),e.jsx(Ln,{dataKey:"approved",fill:"#10b981",name:"Approved"}),e.jsx(Ln,{dataKey:"inProgress",fill:"#f59e0b",name:"Pending"}),e.jsx(Ln,{dataKey:"rejected",fill:"#ef4444",name:"Rejected"})]})})})]})]})}function T0({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(Z,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"user-activity-card",children:[e.jsx(ae,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-2 bg-indigo-100 rounded-lg",children:e.jsx(Ds,{className:"h-4 w-4 text-indigo-600"})}),e.jsx(ne,{className:"text-sm",children:"My Activity"})]})}),e.jsx(X,{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(Z,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"user-response-time-card",children:[e.jsx(ae,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-2 bg-purple-100 rounded-lg",children:e.jsx(Ue,{className:"h-4 w-4 text-purple-600"})}),e.jsx(ne,{className:"text-sm",children:"Avg Response Time"})]})}),e.jsx(X,{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:At(t.tatEfficiency.avgCycleTimeHours)})}),e.jsx(Tt,{}),e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["≈ ",t.tatEfficiency.avgCycleTimeDays.toFixed(1)," working days"]})]})})]})]}):null}function D0({priorityDistribution:t,onNavigate:s}){return t.length===0?null:e.jsxs(Z,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"priority-distribution-report",children:[e.jsx(ae,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"bg-green-50 p-2 sm:p-3 rounded-lg",children:e.jsx(kt,{className:"h-5 w-5 sm:h-6 sm:w-6 text-green-600"})}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-base sm:text-lg lg:text-xl",children:"Priority Distribution Report"}),e.jsx(we,{className:"text-xs sm:text-sm",children:"Express vs Standard workflow analysis"})]})]})}),e.jsxs(X,{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: ",At(n)," cycle"]})]},r)})}),e.jsx("div",{className:"flex justify-center",children:e.jsx(ro,{width:"100%",height:300,children:e.jsxs(rx,{children:[e.jsx(nx,{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(ix,{fill:a.priority==="express"?"#ef4444":"#3b82f6",style:{cursor:"pointer"}},`cell-${r}`))}),e.jsx(no,{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 Fa({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(Z,{className:"shadow-md border-gray-200","data-testid":`${l}-container`,children:e.jsx(X,{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(Z,{className:"shadow-md border-gray-200","data-testid":`${l}-container`,children:e.jsx(X,{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(R,{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(Vt,{className:"h-4 w-4 rotate-180"})}),t>3&&s>5&&e.jsxs(e.Fragment,{children:[e.jsx(R,{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(R,{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(R,{variant:"outline",size:"sm",onClick:()=>n(s),className:"h-8 w-8 p-0","data-testid":`${l}-page-${s}`,children:s})]}),e.jsx(R,{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(Vt,{className:"h-4 w-4"})})]})]})})})}function R0(t,s,a,r="for"){return t==="custom"&&s&&a?`${r} ${Ne(s,"MMM d, yyyy")} - ${Ne(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 P0(t,s,a){return t==="all"?"All historical data":t==="custom"&&s&&a?`Data from ${Ne(s,"MMM d, yyyy")} to ${Ne(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 E0({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(Z,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"tat-breach-report",children:[e.jsx(ae,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"bg-red-50 p-2 sm:p-3 rounded-lg",children:e.jsx(Cs,{className:"h-5 w-5 sm:h-6 sm:w-6 text-red-600"})}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-base sm:text-lg lg:text-xl",children:"TAT Breach Report"}),e.jsxs(we,{className:"text-xs sm:text-sm",children:["Requests that breached TAT - ",P0(a,r,n)]})]})]}),e.jsxs(ee,{variant:"destructive",className:"text-sm font-medium self-start sm:self-auto",children:[t.length," ",t.length===1?"Breach":"Breaches"]})]})}),e.jsxs(X,{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:y0(u)})}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-700 w-[300px]",children:e.jsx("div",{className:"max-h-32 overflow-y-auto",children:e.jsx("p",{className:"whitespace-pre-line break-words leading-relaxed",children:d.breachReason||"TAT Exceeded"})})}),e.jsx("td",{className:"py-3 px-4",children:e.jsx(ee,{variant:"outline",className:`text-xs font-medium ${d.priority==="express"?"bg-orange-100 text-orange-800 border-orange-200":"bg-blue-100 text-blue-800 border-blue-200"}`,children:d.priority})})]},m)})})]})}),e.jsx("div",{className:"mt-4",children:e.jsx(Fa,{currentPage:s.page,totalPages:s.totalPages,totalRecords:s.totalRecords,itemsPerPage:10,onPageChange:i,itemLabel:"critical requests",testIdPrefix:"dashboard-critical-pagination"})})]})]})}function I0({isAdmin:t,upcomingDeadlines:s,pagination:a,onPageChange:r,onNavigate:n}){return s.length===0?null:e.jsxs(Z,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"upcoming-deadlines-section",children:[e.jsx(ae,{children:e.jsx("div",{className:"flex items-center justify-between gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(et,{className:"h-4 w-4 sm:h-5 sm:w-5 text-orange-600"}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-base sm:text-lg",children:"Upcoming Deadlines"}),e.jsx(we,{className:"text-xs sm:text-sm",children:t?"Current active levels organization-wide":"Requests awaiting your approval"})]})]})})}),e.jsxs(X,{children:[e.jsx("div",{className:"space-y-2 sm:space-y-3",children:s.map((i,o)=>{const l=Number(i.tatPercentageUsed)||0,c=Number(i.elapsedHours)||0,d=Number(i.remainingHours)||0;return e.jsxs("div",{className:"p-3 sm:p-4 border rounded-lg hover:shadow-md transition-all cursor-pointer",onClick:()=>n==null?void 0:n(`request/${i.requestNumber}`),"data-testid":`deadline-item-${i.requestNumber}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 mb-1 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-xs sm:text-sm",children:i.requestNumber}),e.jsx(ee,{variant:"outline",className:`text-xs ${i.priority==="express"?"bg-orange-50 text-orange-700":"bg-blue-50 text-blue-700"}`,children:i.priority})]}),e.jsx("p",{className:"text-xs sm:text-sm text-muted-foreground truncate",children:i.requestTitle}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 text-xs text-muted-foreground flex-wrap",children:[e.jsxs(ee,{variant:"outline",className:"text-xs bg-blue-50 text-blue-700 border-blue-200",children:["Level ",i.levelNumber||"?","/",i.totalLevels||"?"]}),e.jsx("span",{className:"truncate",children:i.approverName})]})]}),e.jsxs("div",{className:"text-right flex-shrink-0",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"TAT Used"}),e.jsxs("p",{className:`text-base sm:text-lg font-bold ${l>=80?"text-red-600":l>=50?"text-orange-600":"text-green-600"}`,children:[l.toFixed(0),"%"]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(_s,{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:[At(c)," elapsed"]}),e.jsxs("span",{children:[At(d)," left"]})]})]})]},o)})}),e.jsx("div",{className:"mt-4",children:e.jsx(Fa,{currentPage:a.page,totalPages:a.totalPages,totalRecords:a.totalRecords,itemsPerPage:10,onPageChange:r,itemLabel:"deadlines",testIdPrefix:"dashboard-deadlines-pagination"})})]})]})}function M0({aiRemarkUtilization:t}){return t?e.jsxs(Z,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"ai-remark-utilization-report",children:[e.jsx(ae,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"bg-purple-50 p-2 sm:p-3 rounded-lg",children:e.jsx(mo,{className:"h-5 w-5 sm:h-6 sm:w-6 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-base sm:text-lg lg:text-xl",children:"AI Remark Utilization Report"}),e.jsx(we,{className:"text-xs sm:text-sm",children:"AI-generated remarks usage and edits"})]})]})}),e.jsxs(X,{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(ro,{width:"100%",height:250,children:e.jsxs(ox,{data:t.monthlyTrends,children:[e.jsx(Pd,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(Ed,{dataKey:"month",stroke:"#999",tick:{fontSize:11}}),e.jsx(Id,{stroke:"#999",tick:{fontSize:11}}),e.jsx(no,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(Md,{verticalAlign:"bottom",height:36,iconType:"circle",wrapperStyle:{fontSize:"12px",paddingTop:"10px"}}),e.jsx(bl,{type:"monotone",dataKey:"aiUsage",stroke:"#8b5cf6",strokeWidth:2,name:"AI Usage",dot:{fill:"#8b5cf6",r:4}}),e.jsx(bl,{type:"monotone",dataKey:"manualEdits",stroke:"#ec4899",strokeWidth:2,name:"Manual Edits",dot:{fill:"#ec4899",r:4}})]})})]})]}):null}function F0({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(Z,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"approver-performance-report",children:[e.jsx(ae,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"bg-yellow-50 p-2 sm:p-3 rounded-lg",children:e.jsx(Ct,{className:"h-5 w-5 sm:h-6 sm:w-6 text-yellow-600"})}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-base sm:text-lg lg:text-xl",children:"Approver Performance Report"}),e.jsx(we,{className:"text-xs sm:text-sm",children:"Response time & TAT compliance tracking"})]})]}),e.jsx(R,{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(es,{className:"w-4 h-4 mr-2 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Qt,{className:"w-4 h-4 mr-2"}),"Export"]})})]})}),e.jsxs(X,{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 ${b0(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:At(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(Fa,{currentPage:s.page,totalPages:s.totalPages,totalRecords:s.totalRecords,itemsPerPage:10,onPageChange:l,itemLabel:"approvers",testIdPrefix:"dashboard-approver-pagination"})})]})]})}function _0(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 L0(t,s,a){const r=[{label:"New Request",icon:Re,action:()=>s==null?void 0:s(),color:"bg-emerald-600 hover:bg-emerald-700"},{label:"View Pending",icon:Ue,action:()=>a==null?void 0:a("open-requests"),color:"bg-blue-600 hover:bg-blue-700"},{label:"Settings",icon:la,action:()=>a==null?void 0:a("settings"),color:"bg-slate-600 hover:bg-slate-700"}];return t&&r.splice(2,0,{label:"Reports",icon:qt,action:()=>a==null?void 0:a("detailed-reports"),color:"bg-purple-600 hover:bg-purple-700"}),r}function Ll({onNavigate:t,onNewRequest:s}){const{user:a}=ts(),r=Pr(),n=qa(ct=>ct.dashboard.viewAsUser),i=x.useMemo(()=>Cn(a),[a]),o=i&&!n,l=x.useCallback(ct=>{r(Kf(ct))},[r]),c=Gf(),{dateRange:d,customStartDate:m,customEndDate:u,showCustomDatePicker:h,handleDateRangeChange:p,handleApplyCustomDate:g,resetCustomDates:y,setCustomStartDate:v,setCustomEndDate:C,setShowCustomDatePicker:f}=c,j=Yf(),{activity:b,critical:N,deadlines:A,approver:D,updateActivityPagination:T,updateCriticalPagination:P,updateDeadlinesPagination:w,updateApproverPagination:S,handleActivityPageChange:M,handleCriticalPageChange:B,handleDeadlinesPageChange:_,handleApproverPageChange:$}=j,k=Xf({isAdmin:o,viewAsUser:i&&n,userId:a==null?void 0:a.userId,dateRange:d,customStartDate:m,customEndDate:u,onPaginationUpdate:{activity:T,critical:P,deadlines:w,approver:S}}),{kpis:I,recentActivity:E,criticalRequests:F,departmentStats:O,priorityDistribution:L,upcomingDeadlines:J,aiRemarkUtilization:U,approverPerformance:oe,loading:ge,refreshing:G,fetchDashboardData:me,fetchRecentActivities:re,fetchCriticalRequests:V,fetchUpcomingDeadlines:q,fetchApproverPerformance:ie}=k,ue=i0(),{exportingDeptStats:Te,exportingApproverPerformance:qe,handleExportDepartmentStats:ze,handleExportApproverPerformance:Ze}=ue,Ge=x.useMemo(()=>g0(F),[F]),He=x.useMemo(()=>f0(J),[J]),xt=x.useCallback(()=>{me(!0)},[d,m,u,me]),Q=x.useCallback(()=>{g(()=>{m&&u&&me(!1)})},[m,u,g,me]),xe=x.useCallback(ct=>{M(ct,re)},[M,re]),ot=x.useCallback(ct=>{B(ct,V)},[B,V]),de=x.useCallback(ct=>{_(ct,q)},[_,q]),Ee=x.useCallback(ct=>{$(ct,()=>ie(ct))},[$,ie]);x.useEffect(()=>{d==="custom"?m&&u&&me(!1):me(!1)},[d,m,u,n]);const lt=x.useMemo(()=>L0(i,s,t),[i,s,t]),jt=x.useCallback(ct=>{const Ss=_0(ct);t==null||t(Ss)},[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(es,{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(o0,{isAdmin:i,effectiveIsAdmin:o,viewAsUser:n,onToggleView:l,quickActions:lt,userDisplayName:a==null?void 0:a.displayName,userEmail:a==null?void 0:a.email}),e.jsx(d0,{isAdmin:o,dateRange:d,customStartDate:m,customEndDate:u,showCustomDatePicker:h,refreshing:G,onDateRangeChange:p,onCustomStartDateChange:v,onCustomEndDateChange:C,onShowCustomDatePickerChange:f,onApplyCustomDate:Q,onResetCustomDates:y,onRefresh:xt}),o?e.jsx(m0,{kpis:I,priorityDistribution:L,dateRange:d,customStartDate:m,customEndDate:u,onKPIClick:jt}):e.jsx(u0,{kpis:I,criticalRequests:F,dateRange:d,customStartDate:m,customEndDate:u,onKPIClick:jt,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(v0,{isAdmin:o,breachedRequests:Ge,pagination:N,onPageChange:ot,onNavigate:t}),e.jsx(A0,{isAdmin:o,recentActivity:E,pagination:b,refreshing:G,onPageChange:xe,onRefresh:xt,onNavigate:t,currentUserId:a==null?void 0:a.userId,currentUserDisplayName:a==null?void 0:a.displayName,currentUserEmail:a==null?void 0:a.email})]}),o&&I&&e.jsx(k0,{kpis:I,upcomingDeadlines:J,criticalRequests:F,departmentStats:O,dateRange:d,customStartDate:m,customEndDate:u,exportingDeptStats:Te,onKPIClick:jt,onExportDepartmentStats:ze}),!o&&I&&e.jsx(T0,{kpis:I}),o&&L.length>0&&e.jsx(D0,{priorityDistribution:L,onNavigate:t}),o&&Ge.length>0&&e.jsx(E0,{breachedRequests:Ge,pagination:N,dateRange:d,customStartDate:m,customEndDate:u,onPageChange:ot,onKPIClick:jt,onNavigate:t}),He.length>0&&e.jsx(I0,{isAdmin:o,upcomingDeadlines:He,pagination:A,onPageChange:de,onNavigate:t}),o&&U&&e.jsx(M0,{aiRemarkUtilization:U}),o&&oe.length>0&&e.jsx(F0,{approverPerformance:oe,pagination:D,dateRange:d,customStartDate:m,customEndDate:u,loading:ge,exportingApproverPerformance:qe,onPageChange:Ee,onExport:Ze,onNavigate:t})]})}const O0={searchTerm:"",statusFilter:"all",priorityFilter:"all",sortBy:"created",sortOrder:"desc",currentPage:1},vm=Ja({name:"openRequests",initialState:O0,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:$0,setStatusFilter:U0,setPriorityFilter:B0,setSortBy:V0,setSortOrder:z0,setCurrentPage:H0,clearFilters:W0}=vm.actions;function K0(){const t=Pr(),{searchTerm:s,statusFilter:a,priorityFilter:r,sortBy:n,sortOrder:i,currentPage:o}=qa(y=>y.openRequests),l=x.useCallback(y=>t($0(y)),[t]),c=x.useCallback(y=>t(U0(y)),[t]),d=x.useCallback(y=>t(B0(y)),[t]),m=x.useCallback(y=>t(V0(y)),[t]),u=x.useCallback(y=>t(z0(y)),[t]),h=x.useCallback(y=>t(H0(y)),[t]),p=x.useCallback(()=>t(W0()),[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 Yn(){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 G0(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:Yn(),approverEmail:y,approverName:v,tatHours:g>0?g:24,isFinalApprover:h===(t.approverCount||1)}}),r=[...(t.spectators||[]).map(c=>({userId:Yn(),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:Yn(),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 ce.post("/workflows",n),o=((l=i.data)==null?void 0:l.data)||i.data;return{id:o.id||o.workflowId||""}}async function jm(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 ce.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 Y0(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 ce.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 Z0(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 ce.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 X0(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 ce.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 J0(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 ce.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 Q0(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 ce.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 q0(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 ce.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 ds(t,s){var r;const a=await ce.get(`/workflows/${t}/details`);return((r=a.data)==null?void 0:r.data)||a.data}async function Ha(t){var a;const s=await ce.get(`/workflows/${t}/work-notes`);return((a=s.data)==null?void 0:a.data)||s.data}async function sa(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 ce.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 Nm(t,s,a,r){var i;const n=await ce.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 ey(t,s,a){var n;const r=await ce.post(`/workflows/${t}/approvals/${s}/skip`,{reason:a});return((n=r.data)==null?void 0:n.data)||r.data}async function wm(t,s){var r;const a=await ce.post(`/workflows/${t}/participants/spectator`,{email:s});return((r=a.data)==null?void 0:r.data)||a.data}async function ty(t,s,a,r){var i;const n=await ce.post(`/workflows/${t}/pause`,{levelId:s,reason:a,resumeDate:r.toISOString()});return((i=n.data)==null?void 0:i.data)||n.data}async function sy(t,s){var r;const a=await ce.post(`/workflows/${t}/resume`,{notes:s});return((r=a.data)==null?void 0:r.data)||a.data}async function ay(t){var a;const s=await ce.post(`/workflows/${t}/pause/retrigger`);return((a=s.data)==null?void 0:a.data)||s.data}async function Ol(t){var a;const s=await ce.get(`/workflows/${t}/pause`);return((a=s.data)==null?void 0:a.data)||s.data}function ry(t){return`https://re-workflow-nt-dev.siplsolutions.com/api/v1/workflows/work-notes/attachments/${t}/preview`}function Cm(t){return`https://re-workflow-nt-dev.siplsolutions.com/api/v1/workflows/documents/${t}/preview`}async function Ii(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 $l(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 is={createWorkflowFromForm:G0,createWorkflowMultipart:jm,listWorkflows:Y0,listParticipantRequests:Z0,listMyWorkflows:X0,listMyInitiatedWorkflows:J0,listOpenForMe:Q0,listClosedByMe:q0,submitWorkflow:Sm,getWorkflowDetails:ds,getWorkNotes:Ha,createWorkNoteMultipart:sa};async function Sm(t){var a;const s=await ce.patch(`/workflows/${t}/submit`);return((a=s.data)==null?void 0:a.data)||s.data}async function ny(t,s){var r;const a=await ce.put(`/workflows/${t}`,s);return((r=a.data)==null?void 0:r.data)||a.data}async function iy(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 ce.put(`/workflows/${t}/multipart`,i,{headers:{"Content-Type":"multipart/form-data"}});return((l=o.data)==null?void 0:l.data)||o.data}async function Mi(t,s,a){var n;const r=await ce.patch(`/workflows/${t}/approvals/${s}/approve`,{action:"APPROVE",comments:a||""});return((n=r.data)==null?void 0:n.data)||r.data}async function Fi(t,s,a,r){var i;const n=await ce.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 oy(t,s){const a=await ce.put(`/tat/breach-reason/${t}`,{breachReason:s});if(!a.data.success)throw new Error(a.data.error||"Failed to update breach reason")}function Yt(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 Am(t){return Yt(t,{includeTime:!1,format:"short"})}function Ls(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 ly=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ts,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:kt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:kt,iconColor:"text-gray-600"}}},cy=t=>{switch(t){case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:Ue,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:ht,iconColor:"text-red-600",label:"Rejected"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ce,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 dy({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=K0(),g=x.useCallback(async(b=1,N)=>{try{b===1&&(n(!0),a([]));const A=await is.listOpenForMe({page:b,limit:u,search:N==null?void 0:N.search,status:N==null?void 0:N.status,priority:N==null?void 0:N.priority,sortBy:N==null?void 0:N.sortBy,sortOrder:N==null?void 0:N.sortOrder}),D=Array.isArray(A==null?void 0:A.data)?A.data:[],T=A==null?void 0:A.pagination;T&&(p.setCurrentPage(T.page||1),c(T.totalPages||1),m(T.total||0));const P=D.map(w=>{var M,B,_,$;const S=w.submittedAt||w.submitted_at||w.createdAt||w.created_at;return{id:w.requestNumber||w.request_number||w.requestId,requestId:w.requestId,displayId:w.requestNumber||w.request_number||w.requestId,title:w.title,description:w.description,status:(w.status||"").toString().toLowerCase().replace("_","-"),priority:(w.priority||"").toString().toLowerCase(),initiator:{name:((M=w.initiator)==null?void 0:M.displayName)||((B=w.initiator)==null?void 0:B.email)||"—",avatar:(((_=w.initiator)==null?void 0:_.displayName)||(($=w.initiator)==null?void 0:$.email)||"NA").split(" ").map(k=>k[0]).join("").slice(0,2).toUpperCase()},currentApprover:w.currentApprover?{name:w.currentApprover.name||w.currentApprover.email||"—",avatar:(w.currentApprover.name||w.currentApprover.email||"CA").split(" ").map(k=>k[0]).join("").slice(0,2).toUpperCase(),sla:w.currentApprover.sla}:void 0,createdAt:S||"—",approvalStep:w.currentLevel?`Step ${w.currentLevel} of ${w.totalLevels||"?"}`:void 0,department:w.department,currentLevelSLA:w.currentLevelSLA}});a(P)}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 A=Math.max(1,p.currentPage-Math.floor(2.5)),D=Math.min(l,A+5-1);D-A<4&&(A=Math.max(1,D-5+1));for(let T=A;T<=D;T++)b.push(T);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(Re,{className:"w-5 h-5 sm:w-6 sm:h-6 text-white"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl sm:text-2xl md:text-3xl font-bold text-gray-900",children:"My Open Requests"}),e.jsx("p",{className:"text-sm sm:text-base text-gray-600",children:"Manage and track your active approval requests"})]})]})}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsxs(ee,{variant:"secondary",className:"text-xs sm:text-sm md:text-base px-2 sm:px-3 md:px-4 py-1 sm:py-1.5 md:py-2 bg-slate-100 text-slate-800 font-semibold",children:[r?"Loading…":`${d||s.length} open`,e.jsx("span",{className:"hidden sm:inline ml-1",children:"requests"})]}),e.jsxs(R,{variant:"outline",size:"sm",className:"gap-1 sm:gap-2 h-8 sm:h-9",onClick:y,disabled:i,children:[e.jsx(es,{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(Z,{className:"shadow-lg border-0",children:[e.jsx(ae,{className:"pb-3 sm:pb-4 px-3 sm:px-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("div",{className:"p-1.5 sm:p-2 bg-blue-100 rounded-lg",children:e.jsx(kr,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(we,{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(R,{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(ut,{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(X,{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(bs,{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(je,{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(_e,{value:p.priorityFilter,onValueChange:p.setPriorityFilter,children:[e.jsx(Oe,{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(Le,{placeholder:"All Priorities"})}),e.jsxs($e,{children:[e.jsx(H,{value:"all",children:"All Priorities"}),e.jsx(H,{value:"express",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ts,{className:"w-4 h-4 text-orange-600"}),e.jsx("span",{children:"Express"})]})}),e.jsx(H,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kt,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(_e,{value:p.statusFilter,onValueChange:p.setStatusFilter,children:[e.jsx(Oe,{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(Le,{placeholder:"All Statuses"})}),e.jsxs($e,{children:[e.jsx(H,{value:"all",children:"All Statuses"}),e.jsx(H,{value:"pending",children:"Pending (In Approval)"}),e.jsx(H,{value:"approved",children:"Approved (Needs Closure)"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(_e,{value:p.sortBy,onValueChange:b=>p.setSortBy(b),children:[e.jsx(Oe,{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(Le,{placeholder:"Sort by"})}),e.jsxs($e,{children:[e.jsx(H,{value:"due",children:"Due Date"}),e.jsx(H,{value:"created",children:"Date Created"}),e.jsx(H,{value:"priority",children:"Priority"}),e.jsx(H,{value:"sla",children:"SLA Progress"})]})]}),e.jsx(R,{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(Hd,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(Wd,{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 N=ly(b.priority),A=cy(b.status);return e.jsx(Z,{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(X,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex-shrink-0 pt-1",children:e.jsx("div",{className:`p-2.5 rounded-lg ${N.color} border shadow-sm`,children:e.jsx(N.icon,{className:`w-5 h-5 ${N.iconColor}`})})}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-2.5",children:[e.jsxs("div",{className:"flex items-center gap-2.5 flex-wrap",children:[e.jsx("h3",{className:"text-base font-bold text-gray-900 group-hover:text-blue-600 transition-colors",children:b.displayId||b.id}),e.jsxs(ee,{variant:"outline",className:`${A.color} text-xs px-2.5 py-0.5 font-semibold shrink-0`,children:[e.jsx(A.icon,{className:"w-3.5 h-3.5 mr-1"}),A.label||b.status]}),b.department&&e.jsx(ee,{variant:"secondary",className:"bg-blue-50 text-blue-700 text-xs px-2.5 py-0.5 hidden sm:inline-flex",children:b.department}),e.jsx(ee,{variant:"outline",className:`${N.color} text-xs px-2.5 py-0.5 capitalize hidden md:inline-flex`,children:b.priority})]}),e.jsx("h4",{className:"text-sm font-semibold text-gray-800 line-clamp-1 leading-relaxed",children:b.title}),b.currentLevelSLA&&(()=>{var S;const D=!!(b.isPaused||(S=b.pauseInfo)!=null&&S.isPaused||b.status==="paused"),T=b.currentLevelSLA.percentageUsed||0,w=D?{bg:"bg-gray-100 border border-gray-300",progress:"bg-gray-500",text:"text-gray-600",icon:"text-gray-600"}:T>=100?{bg:"bg-red-50 border border-red-200",progress:"bg-red-600",text:"text-red-600",icon:"text-blue-600"}:T>=75?{bg:"bg-orange-50 border border-orange-200",progress:"bg-orange-500",text:"text-orange-600",icon:"text-blue-600"}:T>=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 ${w.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:[D?e.jsx(yr,{className:`w-3.5 h-3.5 ${w.icon}`}):e.jsx(Ue,{className:`w-3.5 h-3.5 ${w.icon}`}),e.jsxs("span",{className:"text-xs font-medium text-gray-900",children:["TAT: ",T,"% ",D&&"(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 ${w.text}`,children:[b.currentLevelSLA.remainingText," left"]})]})]}),e.jsx(_s,{value:T,className:"h-1.5",indicatorClassName:w.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($t,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(Ut,{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($t,{className:"h-6 w-6 ring-2 ring-yellow-200 shadow-sm",children:e.jsx(Ut,{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(et,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",b.createdAt!=="—"?Ls(b.createdAt):"—"]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(Vt,{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(Z,{className:"shadow-lg border-0",children:e.jsxs(X,{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(Re,{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(R,{variant:"outline",className:"mt-4",onClick:p.clearFilters,children:"Clear all filters"})]})}),l>1&&!r&&e.jsx(Z,{className:"shadow-md",children:e.jsx(X,{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(R,{variant:"outline",size:"sm",onClick:()=>v(p.currentPage-1),disabled:p.currentPage===1,className:"h-8 w-8 p-0",children:e.jsx(Vt,{className:"h-4 w-4 rotate-180"})}),p.currentPage>3&&l>5&&e.jsxs(e.Fragment,{children:[e.jsx(R,{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(R,{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(R,{variant:"outline",size:"sm",onClick:()=>v(l),className:"h-8 w-8 p-0",children:l})]}),e.jsx(R,{variant:"outline",size:"sm",onClick:()=>v(p.currentPage+1),disabled:p.currentPage===l,className:"h-8 w-8 p-0",children:e.jsx(Vt,{className:"h-4 w-4"})})]})]})})})]})}function my({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(Re,{className:"w-5 h-5 sm:w-6 sm:h-6 text-white"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl sm:text-2xl md:text-3xl font-bold text-gray-900",children:"My Closed Requests"}),e.jsx("p",{className:"text-sm sm:text-base text-gray-600",children:"Review your completed and archived requests"})]})]})}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsxs(ee,{variant:"secondary",className:"text-xs sm:text-sm md:text-base px-2 sm:px-3 md:px-4 py-1 sm:py-1.5 md:py-2 bg-slate-100 text-slate-800 font-semibold","data-testid":"closed-requests-count",children:[s?"Loading…":`${t} closed`,e.jsx("span",{className:"hidden sm:inline ml-1",children:"requests"})]}),e.jsxs(R,{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(es,{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 uy({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(Z,{className:"shadow-lg border-0","data-testid":"closed-requests-filters",children:[e.jsx(ae,{className:"pb-3 sm:pb-4 px-3 sm:px-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("div",{className:"p-1.5 sm:p-2 bg-blue-100 rounded-lg",children:e.jsx(kr,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(we,{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(R,{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(ut,{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(X,{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(bs,{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(je,{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(_e,{value:s,onValueChange:l,children:[e.jsx(Oe,{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(Le,{placeholder:"All Priorities"})}),e.jsxs($e,{children:[e.jsx(H,{value:"all",children:"All Priorities"}),e.jsx(H,{value:"express",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ts,{className:"w-4 h-4 text-orange-600"}),e.jsx("span",{children:"Express"})]})}),e.jsx(H,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kt,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(_e,{value:a,onValueChange:c,children:[e.jsx(Oe,{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(Le,{placeholder:"Closure Type"})}),e.jsxs($e,{children:[e.jsx(H,{value:"all",children:"All Closures"}),e.jsx(H,{value:"approved",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ce,{className:"w-4 h-4 text-green-600"}),e.jsx("span",{children:"Closed After Approval"})]})}),e.jsx(H,{value:"rejected",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ht,{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(_e,{value:r,onValueChange:h=>d(h),children:[e.jsx(Oe,{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(Le,{placeholder:"Sort by"})}),e.jsxs($e,{children:[e.jsx(H,{value:"due",children:"Due Date"}),e.jsx(H,{value:"created",children:"Date Created"}),e.jsx(H,{value:"priority",children:"Priority"})]})]}),e.jsx(R,{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(Hd,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(Wd,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function hy(t){switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ts,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:kt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:kt,iconColor:"text-gray-600"}}}function py(t){switch(t){case"closed":return{color:"bg-slate-100 text-slate-800 border-slate-300",icon:Ce,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:ht,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 xy({request:t,onViewRequest:s}){const a=hy(t.priority),r=py(t.status),n=a.icon,i=r.icon;return e.jsx(Z,{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(X,{className:"p-5",children:e.jsxs("div",{className:"flex items-start gap-5",children:[e.jsx("div",{className:"flex-shrink-0 pt-1",children:e.jsx("div",{className:`p-2.5 rounded-lg ${a.color} border shadow-sm`,children:e.jsx(n,{className:`w-5 h-5 ${a.iconColor}`})})}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2.5 flex-wrap",children:[e.jsx("h3",{className:"text-base font-bold text-gray-900 group-hover:text-blue-600 transition-colors",children:t.displayId||t.id}),e.jsxs(ee,{variant:"outline",className:`${r.color} text-xs px-2.5 py-0.5 font-semibold shrink-0`,children:[e.jsx(i,{className:"w-3.5 h-3.5 mr-1"}),r.label]}),t.department&&e.jsx(ee,{variant:"secondary",className:"bg-blue-50 text-blue-700 text-xs px-2.5 py-0.5 hidden sm:inline-flex",children:t.department}),e.jsx(ee,{variant:"outline",className:`${a.color} text-xs px-2.5 py-0.5 capitalize hidden md:inline-flex`,children:t.priority})]}),e.jsx("h4",{className:"text-sm font-semibold text-gray-800 line-clamp-1 leading-relaxed",children:t.title}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-xs text-gray-600",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx($t,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(Ut,{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(Ce,{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(et,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",t.createdAt!=="—"?Ls(t.createdAt,!0):"—"]})]}),t.dueDate&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ce,{className:"w-3.5 h-3.5 text-slate-600"}),e.jsxs("span",{className:"font-medium",children:["Closed: ",Ls(t.dueDate,!0)]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(Vt,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})})}function gy({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(xy,{request:r,onViewRequest:a},r.id))})}function fy({searchTerm:t,activeFiltersCount:s,onClearFilters:a}){return e.jsx(Z,{className:"shadow-lg border-0","data-testid":"closed-requests-empty",children:e.jsxs(X,{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(Re,{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(R,{variant:"outline",className:"mt-4",onClick:a,"data-testid":"closed-requests-empty-clear-filters",children:"Clear all filters"})]})})}function yy(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 by({pagination:t,onPageChange:s}){const{currentPage:a,totalPages:r,totalRecords:n,itemsPerPage:i}=t;if(r<=1)return null;const o=yy(a,r);return e.jsx(Z,{className:"shadow-md","data-testid":"closed-requests-pagination",children:e.jsx(X,{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(R,{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(Vt,{className:"h-4 w-4 rotate-180"})}),a>3&&r>5&&e.jsxs(e.Fragment,{children:[e.jsx(R,{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(R,{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(R,{variant:"outline",size:"sm",onClick:()=>s(r),className:"h-8 w-8 p-0","data-testid":"closed-requests-pagination-last",children:r})]}),e.jsx(R,{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(Vt,{className:"h-4 w-4"})})]})]})})})}function vy(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 jy(t){return t.map(vy)}function Ny({itemsPerPage:t=10}={}){const[s,a]=x.useState([]),[r,n]=x.useState(!1),[i,o]=x.useState(!1),[l,c]=x.useState({currentPage:1,totalPages:1,totalRecords:0,itemsPerPage:t}),d=x.useCallback(async(u=1,h)=>{try{u===1&&(n(!0),a([]));const p=await is.listClosedByMe({page:u,limit:t,search:h==null?void 0:h.search,status:h!=null&&h.status&&h.status!=="all"?h.status:void 0,priority:h==null?void 0:h.priority,sortBy:h==null?void 0:h.sortBy,sortOrder:h==null?void 0:h.sortOrder}),g=Array.isArray(p==null?void 0:p.data)?p.data:[],y=jy(g);a(y);const v=p==null?void 0:p.pagination;v&&c({currentPage:v.page||1,totalPages:v.totalPages||1,totalRecords:v.total||0,itemsPerPage:t})}catch(p){console.error("[ClosedRequests] Error fetching requests:",p),a([])}finally{n(!1),o(!1)}},[t]),m=x.useCallback(u=>{o(!0),d(l.currentPage,u)},[d,l.currentPage]);return{requests:s,loading:r,refreshing:i,pagination:l,fetchRequests:d,handleRefresh:m}}const wy={searchTerm:"",statusFilter:"all",priorityFilter:"all",sortBy:"created",sortOrder:"desc",currentPage:1},km=Ja({name:"closedRequests",initialState:wy,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:Cy,setStatusFilter:Sy,setPriorityFilter:Ay,setSortBy:ky,setSortOrder:Ty,setCurrentPage:Dy,clearFilters:Ry}=km.actions;function Py({onFiltersChange:t,debounceMs:s=500}={}){const a=Pr(),r=x.useRef(null),n=x.useRef(!0),{searchTerm:i,statusFilter:o,priorityFilter:l,sortBy:c,sortOrder:d,currentPage:m}=qa(b=>b.closedRequests),u=x.useCallback(b=>a(Cy(b)),[a]),h=x.useCallback(b=>a(Sy(b)),[a]),p=x.useCallback(b=>a(Ay(b)),[a]),g=x.useCallback(b=>a(ky(b)),[a]),y=x.useCallback(b=>a(Ty(b)),[a]),v=x.useCallback(b=>a(Dy(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(Ry())},[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 Ey({onViewRequest:t}){const s=Ny({itemsPerPage:10}),a=x.useRef(s.fetchRequests);a.current=s.fetchRequests;const r=Py(),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(my,{totalRecords:s.pagination.totalRecords,loading:s.loading,refreshing:s.refreshing,onRefresh:l}),e.jsx(uy,{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(gy,{requests:s.requests,loading:s.loading,onViewRequest:t}),s.requests.length===0&&!s.loading&&e.jsx(fy,{searchTerm:r.searchTerm,activeFiltersCount:r.activeFiltersCount,onClearFilters:r.clearFilters}),!s.loading&&e.jsx(by,{pagination:s.pagination,onPageChange:o})]})}function An({className:t,...s}){return e.jsx(Mp,{"data-slot":"tabs",className:fe("flex flex-col gap-2",t),...s})}function kn({className:t,...s}){return e.jsx(Fp,{"data-slot":"tabs-list",className:fe("bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-xl p-[3px] flex",t),...s})}function Et({className:t,...s}){return e.jsx(_p,{"data-slot":"tabs-trigger",className:fe("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 It({className:t,...s}){return e.jsx(Lp,{"data-slot":"tabs-content",className:fe("flex-1 outline-none",t),...s})}const Tm={"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"]}},Iy={"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 My(t,s=[],a){const[r,n]=x.useState(null),[i,o]=x.useState(!1),[l,c]=x.useState(!0),[d,m]=x.useState(null),[u,h]=x.useState(null),[p,g]=x.useState(!1),y=(N,A)=>(N||A||"NA").toString().split(" ").map(T=>T[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),v=N=>{const A=(N||"").toUpperCase();return A==="IN_PROGRESS"?"in-review":A==="PENDING"?"pending":A==="APPROVED"?"approved":A==="REJECTED"?"rejected":A==="CLOSED"?"closed":A==="SKIPPED"?"skipped":(N||"").toLowerCase()},C=x.useCallback(async()=>{var N,A,D,T,P,w,S,M,B,_,$,k,I;o(!0);try{const E=await is.getWorkflowDetails(t);if(!E){console.warn("[useRequestDetails] No details returned from API");return}const F=E.workflow||{},O=Array.isArray(E.approvals)?E.approvals:[],L=Array.isArray(E.participants)?E.participants:[],J=Array.isArray(E.documents)?E.documents:[],U=E.summary||{},oe=Array.isArray(E.tatAlerts)?E.tatAlerts:[];oe.length>0;const ge=(U==null?void 0:U.currentLevel)||F.currentLevel||1,G=O.map(Q=>{const xe=Q.levelNumber||0,ot=(Q.status||"").toString().toUpperCase(),de=Q.levelId||Q.level_id;let Ee=v(Q.status);xe>ge&&ot!=="APPROVED"&&ot!=="REJECTED"?Ee="waiting":xe===ge&&ot==="PENDING"&&(Ee="pending");const lt=oe.filter(jt=>jt.levelId===de);return{step:xe,levelId:de,role:Q.levelName||Q.approverName||"Approver",status:Ee,approver:Q.approverName||Q.approverEmail,approverId:Q.approverId||Q.approver_id,approverEmail:Q.approverEmail,tatHours:Number(Q.tatHours||0),elapsedHours:Number(Q.elapsedHours||0),remainingHours:Number(Q.remainingHours||0),tatPercentageUsed:Number(Q.tatPercentageUsed||0),actualHours:Q.levelEndTime&&Q.levelStartTime?Math.max(0,(new Date(Q.levelEndTime).getTime()-new Date(Q.levelStartTime).getTime())/(1e3*60*60)):void 0,comment:Q.comments||void 0,timestamp:Q.actionDate||void 0,levelStartTime:Q.levelStartTime||Q.tatStartTime,tatAlerts:lt,skipReason:Q.skipReason||void 0,isSkipped:ot==="SKIPPED"||Q.isSkipped||!1}}),me=L.filter(Q=>(Q.participantType||Q.participant_type||"").toUpperCase()==="SPECTATOR").map(Q=>({name:Q.userName||Q.user_name||Q.userEmail||Q.user_email,role:"Spectator",email:Q.userEmail||Q.user_email,avatar:y(Q.userName||Q.user_name,Q.userEmail||Q.user_email)})),re=Q=>{var ot,de;if(!Q)return;const xe=L.find(Ee=>Ee.userId===Q||Ee.user_id===Q);return xe!=null&&xe.userName||xe!=null&&xe.user_name?xe.userName||xe.user_name:F.initiatorId===Q?((ot=F.initiator)==null?void 0:ot.displayName)||((de=F.initiator)==null?void 0:de.email):Q},V=J.map(Q=>{const xe=Number(Q.fileSize||Q.file_size||0),ot=(xe/(1024*1024)).toFixed(2)+" MB";return{documentId:Q.documentId||Q.document_id,name:Q.originalFileName||Q.fileName||Q.file_name,fileType:Q.fileType||Q.file_type||"",size:ot,sizeBytes:xe,uploadedBy:re(Q.uploadedBy||Q.uploaded_by),uploadedAt:Q.uploadedAt||Q.uploaded_at}}),q=Array.isArray(E.activities)?E.activities.filter(Q=>(Q.type||"").toLowerCase()!=="sla_warning"):[];let ie=null;try{ie=await Ol(F.requestId)}catch(Q){console.debug("Pause details not available:",Q)}let ue=null,Te=null,qe=null,ze=null;if(F.workflowType==="CLAIM_MANAGEMENT"||F.templateType==="claim-management")try{console.debug("[useRequestDetails] Fetching claim details for requestId:",F.requestId);const Q=await ce.get(`/dealer-claims/${F.requestId}`);console.debug("[useRequestDetails] Claim API response:",{status:Q.status,hasData:!!Q.data,dataKeys:Q.data?Object.keys(Q.data):[],fullResponse:Q.data});const xe=((N=Q.data)==null?void 0:N.data)||Q.data;if(console.debug("[useRequestDetails] Extracted claimData:",{hasClaimData:!!xe,claimDataKeys:xe?Object.keys(xe):[],hasClaimDetails:!!(xe!=null&&xe.claimDetails||xe!=null&&xe.claim_details),hasProposalDetails:!!(xe!=null&&xe.proposalDetails||xe!=null&&xe.proposal_details),hasCompletionDetails:!!(xe!=null&&xe.completionDetails||xe!=null&&xe.completion_details),hasInternalOrder:!!(xe!=null&&xe.internalOrder||xe!=null&&xe.internal_order)}),xe){ue=xe.claimDetails||xe.claim_details,Te=xe.proposalDetails||xe.proposal_details,qe=xe.completionDetails||xe.completion_details,ze=xe.internalOrder||xe.internal_order||null;const ot=xe.budgetTracking||xe.budget_tracking||null,de=xe.invoice||null,Ee=xe.creditNote||xe.credit_note||null,lt=xe.completionExpenses||xe.completion_expenses||null;ue&&(ue.budgetTracking=ot,ue.invoice=de,ue.creditNote=Ee,ue.completionExpenses=lt),console.debug("[useRequestDetails] Extracted details:",{claimDetails:ue?{hasActivityName:!!(ue.activityName||ue.activity_name),hasActivityType:!!(ue.activityType||ue.activity_type),hasLocation:!!ue.location,activityName:ue.activityName||ue.activity_name,activityType:ue.activityType||ue.activity_type,location:ue.location,allKeys:Object.keys(ue)}:null,hasProposalDetails:!!Te,hasCompletionDetails:!!qe,hasInternalOrder:!!ze,hasBudgetTracking:!!ot,hasInvoice:!!de,hasCreditNote:!!Ee,hasCompletionExpenses:Array.isArray(lt)&<.length>0})}else console.warn("[useRequestDetails] No claimData found in response")}catch(Q){console.error("[useRequestDetails] Error fetching claim details:",{error:(Q==null?void 0:Q.message)||Q,status:(A=Q==null?void 0:Q.response)==null?void 0:A.status,statusText:(D=Q==null?void 0:Q.response)==null?void 0:D.statusText,responseData:(T=Q==null?void 0:Q.response)==null?void 0:T.data,requestId:F.requestId})}const Ze={...F,id:F.requestNumber||F.requestId,requestId:F.requestId,requestNumber:F.requestNumber,title:F.title,description:F.description,status:v(F.status),priority:(F.priority||"").toString().toLowerCase(),workflowType:F.workflowType||(F.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),approvalFlow:G,approvals:O,participants:L,documents:V,spectators:me,summary:U,initiator:{name:((P=F.initiator)==null?void 0:P.displayName)||((w=F.initiator)==null?void 0:w.email),role:((S=F.initiator)==null?void 0:S.designation)||void 0,department:((M=F.initiator)==null?void 0:M.department)||void 0,email:((B=F.initiator)==null?void 0:B.email)||void 0,phone:((_=F.initiator)==null?void 0:_.phone)||void 0,avatar:y(($=F.initiator)==null?void 0:$.displayName,(k=F.initiator)==null?void 0:k.email)},createdAt:F.createdAt,updatedAt:F.updatedAt,totalSteps:F.totalLevels||1,currentStepRaw:(U==null?void 0:U.currentLevel)||F.currentLevel||1,currentStep:Math.min(Math.max(1,(U==null?void 0:U.currentLevel)||F.currentLevel||1),F.totalLevels||1),auditTrail:q,conclusionRemark:F.conclusionRemark||null,closureDate:F.closureDate||null,pauseInfo:ie||null,claimDetails:ue||null,proposalDetails:Te||null,completionDetails:qe||null,internalOrder:ze||null,budgetTracking:(ue==null?void 0:ue.budgetTracking)||null,invoice:(ue==null?void 0:ue.invoice)||null,creditNote:(ue==null?void 0:ue.creditNote)||null,completionExpenses:(ue==null?void 0:ue.completionExpenses)||null};n(Ze);const Ge=(I=a==null?void 0:a.email)==null?void 0:I.toLowerCase(),He=O.find(Q=>{const xe=(Q.status||"").toString().toUpperCase(),ot=(Q.approverEmail||"").toLowerCase(),de=Q.levelNumber||0;return(xe==="PENDING"||xe==="IN_PROGRESS"||xe==="PAUSED")&&ot===Ge&&de===ge});h(He||null);const xt=a==null?void 0:a.userId;if(xt){const Q=L.some(xe=>(xe.participantType||xe.participant_type||"").toUpperCase()==="SPECTATOR"&&(xe.userId||xe.user_id)===xt);g(Q)}else g(!1)}catch(E){console.error("[useRequestDetails] Error refreshing details:",E),alert("Failed to refresh request details. Please try again.")}finally{o(!1)}},[t,a]);x.useEffect(()=>{if(!t){c(!1);return}let N=!0;return c(!0),m(null),(async()=>{var A,D,T,P,w,S,M,B,_,$,k,I,E,F;try{const O=await is.getWorkflowDetails(t);if(!N||!O){N&&c(!1);return}const L=O.workflow||{},J=Array.isArray(O.approvals)?O.approvals:[],U=Array.isArray(O.participants)?O.participants:[],oe=Array.isArray(O.documents)?O.documents:[],ge=O.summary||{},G=Array.isArray(O.tatAlerts)?O.tatAlerts:[],me=(L.priority||"").toString().toLowerCase(),re=(ge==null?void 0:ge.currentLevel)||L.currentLevel||1,V=J.map(de=>{const Ee=de.levelNumber||0,lt=(de.status||"").toString().toUpperCase(),jt=de.levelId||de.level_id;let ct=v(de.status);lt==="PAUSED"?ct="paused":Ee>re&<!=="APPROVED"&<!=="REJECTED"?ct="waiting":Ee===re&&(lt==="PENDING"||lt==="IN_PROGRESS")&&(ct=lt==="IN_PROGRESS"?"in-review":"pending");const Ss=G.filter(Zs=>Zs.levelId===jt);return{step:Ee,levelId:jt,role:de.levelName||de.approverName||"Approver",status:ct,approver:de.approverName||de.approverEmail,approverId:de.approverId||de.approver_id,approverEmail:de.approverEmail,tatHours:Number(de.tatHours||0),elapsedHours:Number(de.elapsedHours||0),remainingHours:Number(de.remainingHours||0),tatPercentageUsed:Number(de.tatPercentageUsed||0),actualHours:de.elapsedHours!==void 0&&de.elapsedHours!==null?Number(de.elapsedHours):void 0,comment:de.comments||void 0,timestamp:de.actionDate||void 0,levelStartTime:de.levelStartTime||de.tatStartTime,tatAlerts:Ss}}),q=U.filter(de=>(de.participantType||"").toUpperCase()==="SPECTATOR").map(de=>({name:de.userName||de.userEmail,role:"Spectator",avatar:y(de.userName,de.userEmail)})),ie=de=>{var lt,jt;if(!de)return;const Ee=U.find(ct=>ct.userId===de);return Ee!=null&&Ee.userName?Ee.userName:L.initiatorId===de?((lt=L.initiator)==null?void 0:lt.displayName)||((jt=L.initiator)==null?void 0:jt.email):de},ue=oe.map(de=>{const Ee=Number(de.fileSize||0),lt=(Ee/(1024*1024)).toFixed(2)+" MB";return{documentId:de.documentId||de.document_id,name:de.originalFileName||de.fileName,fileType:de.fileType||de.file_type||"",size:lt,sizeBytes:Ee,uploadedBy:ie(de.uploadedBy),uploadedAt:de.uploadedAt}}),Te=Array.isArray(O.activities)?O.activities.filter(de=>(de.type||"").toLowerCase()!=="sla_warning"):[];let qe=null;try{qe=await Ol(L.requestId)}catch(de){console.debug("Pause details not available:",de)}let ze=null,Ze=null,Ge=null,He=null;if(L.workflowType==="CLAIM_MANAGEMENT"||L.templateType==="claim-management")try{console.debug("[useRequestDetails] Initial load - Fetching claim details for requestId:",L.requestId);const de=await ce.get(`/dealer-claims/${L.requestId}`);console.debug("[useRequestDetails] Initial load - Claim API response:",{status:de.status,hasData:!!de.data,dataKeys:de.data?Object.keys(de.data):[]});const Ee=((A=de.data)==null?void 0:A.data)||de.data;Ee&&(ze=Ee.claimDetails||Ee.claim_details,Ze=Ee.proposalDetails||Ee.proposal_details,Ge=Ee.completionDetails||Ee.completion_details,He=Ee.internalOrder||Ee.internal_order||null,console.debug("[useRequestDetails] Initial load - Extracted details:",{hasClaimDetails:!!ze,claimDetailsKeys:ze?Object.keys(ze):[],hasProposalDetails:!!Ze,hasCompletionDetails:!!Ge,hasInternalOrder:!!He}))}catch(de){console.error("[useRequestDetails] Initial load - Error fetching claim details:",{error:(de==null?void 0:de.message)||de,status:(D=de==null?void 0:de.response)==null?void 0:D.status,requestId:L.requestId})}const xt={id:L.requestNumber||L.requestId,requestId:L.requestId,title:L.title,description:L.description,priority:me,status:v(L.status),workflowType:L.workflowType||(L.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),summary:ge,initiator:{name:((T=L.initiator)==null?void 0:T.displayName)||((P=L.initiator)==null?void 0:P.email),role:((w=L.initiator)==null?void 0:w.designation)||void 0,department:((S=L.initiator)==null?void 0:S.department)||void 0,email:((M=L.initiator)==null?void 0:M.email)||void 0,phone:((B=L.initiator)==null?void 0:B.phone)||void 0,avatar:y((_=L.initiator)==null?void 0:_.displayName,($=L.initiator)==null?void 0:$.email)},createdAt:L.createdAt,updatedAt:L.updatedAt,totalSteps:L.totalLevels||1,currentStepRaw:(ge==null?void 0:ge.currentLevel)||L.currentLevel||1,currentStep:Math.min(Math.max(1,(ge==null?void 0:ge.currentLevel)||L.currentLevel||1),L.totalLevels||1),approvalFlow:V,approvals:J,documents:ue,spectators:q,auditTrail:Te,conclusionRemark:L.conclusionRemark||null,closureDate:L.closureDate||null,pauseInfo:qe||null,claimDetails:ze||null,proposalDetails:Ze||null,completionDetails:Ge||null,internalOrder:He||null};n(xt);const Q=(k=a==null?void 0:a.email)==null?void 0:k.toLowerCase(),xe=J.find(de=>{const Ee=(de.status||"").toString().toUpperCase(),lt=(de.approverEmail||"").toLowerCase(),jt=de.levelNumber||0;return(Ee==="PENDING"||Ee==="IN_PROGRESS"||Ee==="PAUSED")&<===Q&&jt===re});h(xe||null);const ot=a==null?void 0:a.userId;if(ot){const de=U.some(Ee=>(Ee.participantType||"").toUpperCase()==="SPECTATOR"&&Ee.userId===ot);g(de)}else g(!1)}catch(O){if(console.error("[useRequestDetails] Error loading request details:",O),N){if(((I=O==null?void 0:O.response)==null?void 0:I.status)===403){const L=((F=(E=O==null?void 0:O.response)==null?void 0:E.data)==null?void 0:F.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:L})}n(null)}}finally{N&&c(!1)}})(),()=>{N=!1}},[t,a]);const f=x.useMemo(()=>{if(r)return r;const N=Tm[t];if(N)return N;const A=Iy[t];if(A)return A;const D=s.find(T=>T.id===t||T.requestNumber===t||T.request_number===t);return D||null},[t,s,r]),j=x.useMemo(()=>{var D,T,P;if(!f||!a)return!1;const N=(D=a==null?void 0:a.email)==null?void 0:D.toLowerCase(),A=(P=(T=f.initiator)==null?void 0:T.email)==null?void 0:P.toLowerCase();return N===A},[f,a]),b=x.useMemo(()=>{var A;if(!f)return[];const N=[];return(A=f.initiator)!=null&&A.email&&N.push({email:f.initiator.email.toLowerCase(),participantType:"INITIATOR",name:f.initiator.name}),f.approvalFlow&&Array.isArray(f.approvalFlow)&&f.approvalFlow.forEach(D=>{D.approverEmail&&N.push({email:D.approverEmail.toLowerCase(),participantType:"APPROVER",name:D.approver})}),f.spectators&&Array.isArray(f.spectators)&&f.spectators.forEach(D=>{D.email&&N.push({email:D.email.toLowerCase(),participantType:"SPECTATOR",name:D.name})}),f.participants&&Array.isArray(f.participants)&&f.participants.forEach(D=>{const T=(D.userEmail||D.email||"").toLowerCase(),P=(D.participantType||D.participant_type||"").toUpperCase(),w=D.userName||D.user_name||D.name;T&&P&&!N.find(S=>S.email===T)&&N.push({email:T,participantType:P,name:w})}),N},[f]);return x.useEffect(()=>{if(!t||!r)return;const N=vr();if(!N){console.warn("[useRequestDetails] Socket not available");return}console.log("[useRequestDetails] Setting up socket listener for request:",r.requestId);const A=D=>{console.log("[useRequestDetails] 📡 Received request:updated event:",D),(D==null?void 0:D.requestId)===r.requestId||(D==null?void 0:D.requestNumber)===t?(console.log("[useRequestDetails] 🔄 Request updated remotely, refreshing silently..."),C()):console.log("[useRequestDetails] ⚠️ Event for different request, ignoring")};return N.on("request:updated",A),console.log("[useRequestDetails] ✅ Registered listener for request:updated"),()=>{console.log("[useRequestDetails] 🧹 Cleaning up socket listener"),N.off("request:updated",A)}},[t,r,C]),{request:f,apiRequest:r,loading:l,refreshing:i,refreshDetails:C,currentApprovalLevel:u,isSpectator:p,isInitiator:j,existingParticipants:b,accessDenied:d}}function Fy(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 is.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=vr();if(!h){console.error("[useRequestSocket] Socket not available");return}const p=r==null?void 0:r.userId,g=()=>{Ei(h,u,p)};return h.connected?g():h.on("connect",g),()=>{m&&(h.off("connect",g),fm(h,u))}})(),()=>{m=!1}},[t,r]),x.useEffect(()=>{!t||!s||(async()=>{try{const m=await Ha(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=vr();if(!m)return;const u=p=>{a!=="worknotes"&&l(g=>g+1),(async()=>{try{const g=await Ha(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 is.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 dr(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 ce.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 Pa=async t=>{const s=t?{category:t}:{};return(await ce.get("/users/configurations",{params:s})).data.data},Tn=async t=>{const s=t?{category:t}:{};return(await ce.get("/admin/configurations",{params:s})).data.data},Bt=async(t,s)=>{await ce.put(`/admin/configurations/${t}`,{configValue:s})},_y=async t=>{await ce.post(`/admin/configurations/${t}/reset`)},Ly=async t=>{const s=t?{year:t}:{};return(await ce.get("/admin/holidays",{params:s})).data.data},Oy=async t=>(await ce.post("/admin/holidays",t)).data.data,$y=async(t,s)=>(await ce.put(`/admin/holidays/${t}`,s)).data.data,Uy=async t=>{await ce.delete(`/admin/holidays/${t}`)};function By(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 Pa("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 N=m(b);N.valid?C.push(b):v.push({fileName:b.name,reason:N.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],N=t==null?void 0:t.requestId;if(!N){te.error("Request ID not found");return}b&&await dr(b,N,"SUPPORTING"),await s(),C.length<y.length?te.warning(`${C.length} of ${y.length} file(s) were uploaded. ${v.length} file(s) were rejected.`):te.success("Document uploaded successfully")}catch(b){console.error("[useDocumentUpload] Upload error:",b),te.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",zy=function(t){return"/"+t},Ul={},Zn=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=zy(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 Hy(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 Zn(async()=>{const{getConclusion:b}=await import("./conclusionApi-CGl-93sb.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 Zn(async()=>{const{generateConclusion:b}=await import("./conclusionApi-CGl-93sb.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:N}=await Zn(async()=>{const{finalizeConclusion:A}=await import("./conclusionApi-CGl-93sb.js");return{finalizeConclusion:A}},__vite__mapDeps([0,1,2,3,4,5,6,7]));await N(t.requestId||s,l),i==null||i({success:!0,title:"Request Closed with Successful Completion",message:"The request has been finalized and moved to Closed Requests."}),o==null||o(!0),await r(),setTimeout(()=>{n?(n(),setTimeout(()=>{window.location.hash="#/closed-requests"},100)):window.location.hash="#/closed-requests"},2e3)}catch(N){i==null||i({success:!1,title:"Error",message:((b=(j=N.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 Wy(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 T=>{var w,S;const P=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!P){alert("Approval level not found");return}await Mi(t,P,T||""),await a(),(w=window==null?void 0:window.closeModal)==null||w.call(window),(S=window==null?void 0:window.toast)==null||S.call(window,"Approved successfully")},handleRejectConfirm:async T=>{var w,S;if(!(T!=null&&T.trim())){alert("Comments & remarks are required");return}const P=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!P){alert("Approval level not found");return}await Fi(t,P,T.trim(),T.trim()),await a(),(w=window==null?void 0:window.closeModal)==null||w.call(window),(S=window==null?void 0:window.toast)==null||S.call(window,"Rejected successfully")},handleAddApprover:async(T,P,w)=>{var S,M;try{await Nm(t,T,P,w),await a(),c(!1),f==null||f({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${w} with ${P}h TAT`}),g==null||g(!0)}catch(B){throw f==null||f({success:!1,title:"Failed to Add Approver",message:((M=(S=B==null?void 0:B.response)==null?void 0:S.data)==null?void 0:M.error)||"Failed to add approver. Please try again."}),g==null||g(!0),B}},handleSkipApprover:async T=>{var P,w;if(y)try{await ey(t,y.levelId,T),await a(),h(!1),v(null),f==null||f({success:!0,title:"Approver Skipped",message:"Approver skipped successfully. The workflow has moved to the next level."}),g==null||g(!0)}catch(S){throw f==null||f({success:!1,title:"Failed to Skip Approver",message:((w=(P=S==null?void 0:S.response)==null?void 0:P.data)==null?void 0:w.error)||"Failed to skip approver. Please try again."}),g==null||g(!0),S}},handleAddSpectator:async T=>{var P,w;try{await wm(t,T),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(S){throw f==null||f({success:!1,title:"Failed to Add Spectator",message:((w=(P=S==null?void 0:S.response)==null?void 0:P.data)==null?void 0:w.error)||"Failed to add spectator. Please try again."}),g==null||g(!0),S}}}}const Ky=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"}}},Gy=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}}},Yy=t=>{switch(t){case"approval":case"approved":return e.jsx(Ce,{className:"w-5 h-5 text-green-600"});case"rejection":case"rejected":return e.jsx(ht,{className:"w-5 h-5 text-red-600"});case"comment":return e.jsx(Ds,{className:"w-5 h-5 text-blue-600"});case"status_change":case"updated":return e.jsx(es,{className:"w-5 h-5 text-orange-600"});case"assignment":return e.jsx(yn,{className:"w-5 h-5 text-purple-600"});case"created":return e.jsx(Re,{className:"w-5 h-5 text-blue-600"});case"reminder":return e.jsx(Ue,{className:"w-5 h-5 text-yellow-600"});case"document_added":return e.jsx(fn,{className:"w-5 h-5 text-indigo-600"});case"sla_warning":return e.jsx(Cs,{className:"w-5 h-5 text-amber-600"});default:return e.jsx(qt,{className:"w-5 h-5 text-gray-600"})}};function Zy({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(yr,{className:"h-4 w-4 text-gray-600"}):s==="approved"?e.jsx(Ce,{className:"h-4 w-4 text-green-600"}):s==="rejected"?e.jsx(ht,{className:"h-4 w-4 text-red-600"}):e.jsx(Ue,{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(yr,{className:`h-4 w-4 ${l.icon}`}):e.jsx(Ue,{className:`h-4 w-4 ${l.icon}`}),e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:a?"SLA Progress (Paused)":"SLA Progress"})]}),e.jsxs(ee,{className:`text-xs ${l.badge}`,"data-testid":`${r}-badge`,children:[t.percentageUsed||0,"% elapsed ",a&&"(frozen)"]})]}),e.jsx(_s,{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||At(t.elapsedHours||0)," elapsed"]}),e.jsxs("span",{className:`font-semibold ${c==="breached"||c==="critical"?l.text:"text-gray-700"}`,"data-testid":`${r}-remaining`,children:[At(t.remainingHours||0)," remaining"]})]}),t.deadline&&e.jsxs("p",{className:"text-xs text-gray-500","data-testid":`${r}-deadline`,children:["Due: ",Ls(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(Cs,{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(ki,{className:"h-3.5 w-3.5"}),"URGENT - Deadline Passed"]})]})}function Xy({request:t,refreshing:s,onBack:a,onRefresh:r,onShareSummary:n,isInitiator:i}){var d,m,u;const o=Ky((t==null?void 0:t.priority)||"standard"),l=Gy((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(R,{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(Ms,{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(Re,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"})}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-2 min-w-0 flex-1",children:[e.jsx("h1",{className:"text-sm sm:text-base md:text-lg font-bold text-gray-900 truncate","data-testid":"request-id",children:t.id||"N/A"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2",children:[e.jsx(ee,{className:`${o.color} rounded-full px-2 sm:px-3 text-xs capitalize shrink-0`,variant:"outline","data-testid":"priority-badge",children:o.label}),e.jsx(ee,{className:`${l.color} rounded-full px-2 sm:px-3 text-xs capitalize shrink-0`,variant:"outline","data-testid":"status-badge",children:l.label})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[n&&i&&((m=t==null?void 0:t.status)==null?void 0:m.toLowerCase())==="closed"&&e.jsxs(R,{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(Ya,{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(R,{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(es,{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(Zy,{sla:((u=t.summary)==null?void 0:u.sla)||t.sla,requestStatus:t.status,isPaused:c,testId:"request-sla"})})]})}function nt({...t}){return e.jsx(Up,{"data-slot":"dialog",...t})}function Jy({...t}){return e.jsx($p,{"data-slot":"dialog-portal",...t})}const Dm=x.forwardRef(({className:t,...s},a)=>e.jsx(Ad,{ref:a,"data-slot":"dialog-overlay",className:fe("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}));Dm.displayName=Ad.displayName;const at=x.forwardRef(({className:t,children:s,...a},r)=>e.jsxs(Jy,{"data-slot":"dialog-portal",children:[e.jsx(Dm,{}),e.jsxs(kd,{ref:r,"data-slot":"dialog-content",className:fe("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(ut,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));at.displayName=kd.displayName;const it=x.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,"data-slot":"dialog-header",className:fe("flex flex-col gap-2 text-center sm:text-left",t),...s}));it.displayName="DialogHeader";const yt=x.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,"data-slot":"dialog-footer",className:fe("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s}));yt.displayName="DialogFooter";const rt=x.forwardRef(({className:t,...s},a)=>e.jsx(Td,{ref:a,"data-slot":"dialog-title",className:fe("text-lg leading-none font-semibold",t),...s}));rt.displayName=Td.displayName;const Ht=x.forwardRef(({className:t,...s},a)=>e.jsx(Dd,{ref:a,"data-slot":"dialog-description",className:fe("text-muted-foreground text-sm",t),...s}));Ht.displayName=Dd.displayName;function wo({className:t,...s}){return e.jsx(Bp,{"data-slot":"checkbox",className:fe("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(Vp,{"data-slot":"checkbox-indicator",className:"flex items-center justify-center text-current transition-none",children:e.jsx(Za,{className:"size-3.5"})})})}async function Rm(t){return(await ce.get(`/summaries/${t}`)).data.data}async function Qy(t,s){return(await ce.post(`/summaries/${t}/share`,{userIds:s})).data.data}async function qy(t={}){var n,i;const{page:s=1,limit:a=20}=t,r=await ce.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 Pm(t){await ce.patch(`/summaries/shared/${t}/view`)}async function eb(t){var s;try{return(await ce.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 tb(t){return(await ce.get(`/summaries/${t}/recipients`)).data.data||[]}async function Os(t,s=10){return await ce.get("/users/search",{params:{q:t,limit:s}})}async function Ws(t){var a;const s=await ce.post("/users/ensure",t);return((a=s.data)==null?void 0:a.data)||s.data}async function sb(t,s){return await ce.post("/admin/users/assign-role",{email:t,role:s})}async function ab(t,s){return await ce.put(`/admin/users/${t}/role`,{role:s})}async function rb(t,s=1,a=10){return await ce.get("/admin/users/by-role",{params:{role:t||"ELEVATED",page:s,limit:a}})}async function nb(){return await ce.get("/admin/users/role-statistics")}async function ib(){var s,a;return((a=(s=(await ce.get("/users")).data)==null?void 0:s.data)==null?void 0:a.users)||[]}const fs={searchUsers:Os,ensureUserExists:Ws,assignRole:sb,updateUserRole:ab,getUsersByRole:rb,getRoleStatistics:nb,getAllUsers:ib};function ob({isOpen:t,onClose:s,summaryId:a,requestTitle:r,onSuccess:n}){const[i,o]=x.useState(""),[l,c]=x.useState([]),[d,m]=x.useState(new Set),[u,h]=x.useState(!1),[p,g]=x.useState(!1);x.useEffect(()=>{if(!t){c([]);return}if(!i||!i.startsWith("@")||i.length<2){c([]),h(!1);return}const f=setTimeout(async()=>{var j;try{h(!0);const b=i.slice(1),N=await Os(b,10),A=((j=N==null?void 0:N.data)==null?void 0:j.data)||(N==null?void 0:N.data)||[];c(Array.isArray(A)?A:[])}catch(b){console.error("Failed to search users:",b),te.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){te.error("Please select at least one user to share with");return}try{g(!0),await Qy(a,Array.from(d)),te.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),te.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(nt,{open:t,onOpenChange:C,children:e.jsxs(at,{className:"sm:max-w-[500px]",children:[e.jsx(it,{children:e.jsx(rt,{children:"Share Summary"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{children:[e.jsx(Y,{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(Y,{htmlFor:"user-search",className:"text-sm font-medium text-gray-700",children:"Search Users"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(bs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(je,{id:"user-search",placeholder:"Type @ to search users...",value:i,onChange:f=>o(f.target.value),className:"pl-10"})]}),i&&!i.startsWith("@")&&e.jsx("p",{className:"text-xs text-gray-500 mt-1 ml-1",children:"Start with @ to search users (e.g., @john)"})]}),u&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Xe,{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(wo,{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(St,{className:"h-4 w-4 text-gray-400 flex-shrink-0"}),e.jsx("p",{className:"text-sm font-medium text-gray-900 truncate",children:f.displayName||f.email})]}),(f.designation||f.department)&&e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:f.designation||f.department}),e.jsx("p",{className:"text-xs text-gray-400 truncate",children:f.email})]})]},f.userId)})}),!u&&i&&i.startsWith("@")&&l.length===0&&e.jsx("div",{className:"text-center py-8 text-gray-500 text-sm",children:"No users found"}),!u&&i&&!i.startsWith("@")&&e.jsx("div",{className:"text-center py-8 text-gray-500 text-sm",children:"Start typing with @ to search users"}),d.size>0&&e.jsxs("div",{className:"border rounded-lg p-3 bg-blue-50",children:[e.jsxs("p",{className:"text-sm font-medium text-gray-700 mb-2",children:["Selected (",d.size,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(d).map(f=>{const 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(ut,{className:"h-3 w-3"})})]},f)})})]})]}),e.jsxs(yt,{children:[e.jsx(R,{variant:"outline",onClick:C,disabled:p,children:"Cancel"}),e.jsx(R,{onClick:v,disabled:p||d.size===0,children:p?e.jsxs(e.Fragment,{children:[e.jsx(Xe,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):`Share with ${d.size} user(s)`})]})]})})}function Em({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 N=b.getData("text/html")||b.getData("text/plain");if((N.includes("<!--")||N.includes("<style")||N.includes("MsoNormal"))&&(N=u(N)),!o.current)return;const A=window.getSelection();if(!A||A.rangeCount===0)return;const D=A.getRangeAt(0);D.deleteContents();const T=document.createElement("div");T.innerHTML=N;const P=document.createDocumentFragment();Array.from(T.childNodes).forEach(w=>{if(w.nodeType===Node.ELEMENT_NODE){const S=w;if(S.tagName==="UL"||S.tagName==="OL"){const M=S.cloneNode(!0);M.removeAttribute("style"),M.removeAttribute("class"),M.querySelectorAll("li").forEach(B=>{B.removeAttribute("style"),B.removeAttribute("class");const _=B.textContent||"";_.trim()&&(B.textContent=_.trim())}),P.appendChild(M)}else if(S.tagName==="TABLE"){const M=S.cloneNode(!0);M.removeAttribute("style"),M.removeAttribute("class"),M.querySelectorAll("td, th").forEach(_=>{_.removeAttribute("style"),_.removeAttribute("class")});const B=document.createElement("div");B.className="table-wrapper",B.style.overflowX="auto",B.style.maxWidth="100%",B.style.margin="8px 0",B.appendChild(M),P.appendChild(B)}else if(S.tagName==="P"||S.tagName==="DIV"){const M=document.createElement("p"),_=S.innerHTML.replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<!--[\s\S]*?-->/g,"");M.innerHTML=_,M.removeAttribute("style"),M.removeAttribute("class"),P.appendChild(M)}else if(S.tagName==="BR")P.appendChild(S.cloneNode(!0));else{const M=S.textContent||"";if(M.trim()){const B=document.createElement("p");B.textContent=M.trim(),P.appendChild(B)}}}else if(w.nodeType===Node.TEXT_NODE){const S=w.textContent||"";if(S.trim()){const M=document.createElement("p");M.textContent=S.trim(),P.appendChild(M)}}}),P.childNodes.length===0&&b.getData("text/plain").split(`
|
||
`).forEach(M=>{if(M.trim()){const B=document.createElement("p");B.textContent=M.trim(),P.appendChild(B)}else P.appendChild(document.createElement("br"))}),D.insertNode(P),D.collapse(!1),A.removeAllRanges(),A.addRange(D),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 A=b.getRangeAt(0).commonAncestorContainer;let D=null;for(A.nodeType===Node.TEXT_NODE?D=A.parentElement:D=A;D&&D!==o.current;){const T=D.tagName.toLowerCase();(T==="strong"||T==="b")&&j.add("bold"),(T==="em"||T==="i")&&j.add("italic"),T==="u"&&j.add("underline"),T==="h1"&&j.add("h1"),T==="h2"&&j.add("h2"),T==="h3"&&j.add("h3"),T==="ul"&&j.add("ul"),T==="ol"&&j.add("ol");const P=window.getComputedStyle(D);P.textAlign==="center"&&j.add("center"),P.textAlign==="right"&&j.add("right"),P.textAlign==="left"&&j.add("left"),D=D.parentElement}}m(j)},[l]),g=x.useCallback((j,b)=>{if(!o.current)return;l||o.current.focus();const N=window.getSelection();if(!N||N.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(R,{type:"button",variant:"ghost",size:"sm",className:fe("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(Dx,{className:"h-4 w-4"})}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:fe("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(Rx,{className:"h-4 w-4"})}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:fe("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(Px,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-1 border-r border-gray-300 pr-2",children:[e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:fe("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(Ex,{className:"h-4 w-4"})}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:fe("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(Ix,{className:"h-4 w-4"})}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:fe("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(Mx,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-1 border-r border-gray-300 pr-2",children:[e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:fe("h-7 w-7 p-0",d.has("ul")&&"bg-blue-100 text-blue-700"),onClick:()=>g("insertUnorderedList"),title:"Bullet List",children:e.jsx(Bd,{className:"h-4 w-4"})}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:fe("h-7 w-7 p-0",d.has("ol")&&"bg-blue-100 text-blue-700"),onClick:()=>g("insertOrderedList"),title:"Numbered List",children:e.jsx(Fx,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:fe("h-7 w-7 p-0",d.has("left")&&"bg-blue-100 text-blue-700"),onClick:()=>g("justifyLeft"),title:"Align Left",children:e.jsx(_x,{className:"h-4 w-4"})}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:fe("h-7 w-7 p-0",d.has("center")&&"bg-blue-100 text-blue-700"),onClick:()=>g("justifyCenter"),title:"Align Center",children:e.jsx(Lx,{className:"h-4 w-4"})}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:fe("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:fe("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 oa({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:fe("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 Im={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(xn,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 $=["th","st","nd","rd"],k=_%100;return"["+_+($[(k-20)%10]||$[k]||$[0])+"]"}},j=function(_,$,k){var I=String(_);return!I||I.length>=$?_:""+Array($+1-I.length).join(k)+_},b={s:j,z:function(_){var $=-_.utcOffset(),k=Math.abs($),I=Math.floor(k/60),E=k%60;return($<=0?"+":"-")+j(I,2,"0")+":"+j(E,2,"0")},m:function _($,k){if($.date()<k.date())return-_(k,$);var I=12*(k.year()-$.year())+(k.month()-$.month()),E=$.clone().add(I,u),F=k-E<0,O=$.clone().add(I+(F?-1:1),u);return+(-(I+(k-E)/(F?E-O:O-E))||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}},N="en",A={};A[N]=f;var D="$isDayjsObject",T=function(_){return _ instanceof M||!(!_||!_[D])},P=function _($,k,I){var E;if(!$)return N;if(typeof $=="string"){var F=$.toLowerCase();A[F]&&(E=F),k&&(A[F]=k,E=F);var O=$.split("-");if(!E&&O.length>1)return _(O[0])}else{var L=$.name;A[L]=$,E=L}return!I&&E&&(N=E),E||!I&&N},w=function(_,$){if(T(_))return _.clone();var k=typeof $=="object"?$:{};return k.date=_,k.args=arguments,new M(k)},S=b;S.l=P,S.i=T,S.w=function(_,$){return w(_,{locale:$.$L,utc:$.$u,x:$.$x,$offset:$.$offset})};var M=function(){function _(k){this.$L=P(k.locale,null,!0),this.parse(k),this.$x=this.$x||k.x||{},this[D]=!0}var $=_.prototype;return $.parse=function(k){this.$d=function(I){var E=I.date,F=I.utc;if(E===null)return new Date(NaN);if(S.u(E))return new Date;if(E instanceof Date)return new Date(E);if(typeof E=="string"&&!/Z$/i.test(E)){var O=E.match(v);if(O){var L=O[2]-1||0,J=(O[7]||"0").substring(0,3);return F?new Date(Date.UTC(O[1],L,O[3]||1,O[4]||0,O[5]||0,O[6]||0,J)):new Date(O[1],L,O[3]||1,O[4]||0,O[5]||0,O[6]||0,J)}}return new Date(E)}(k),this.init()},$.init=function(){var k=this.$d;this.$y=k.getFullYear(),this.$M=k.getMonth(),this.$D=k.getDate(),this.$W=k.getDay(),this.$H=k.getHours(),this.$m=k.getMinutes(),this.$s=k.getSeconds(),this.$ms=k.getMilliseconds()},$.$utils=function(){return S},$.isValid=function(){return this.$d.toString()!==y},$.isSame=function(k,I){var E=w(k);return this.startOf(I)<=E&&E<=this.endOf(I)},$.isAfter=function(k,I){return w(k)<this.startOf(I)},$.isBefore=function(k,I){return this.endOf(I)<w(k)},$.$g=function(k,I,E){return S.u(k)?this[I]:this.set(E,k)},$.unix=function(){return Math.floor(this.valueOf()/1e3)},$.valueOf=function(){return this.$d.getTime()},$.startOf=function(k,I){var E=this,F=!!S.u(I)||I,O=S.p(k),L=function(V,q){var ie=S.w(E.$u?Date.UTC(E.$y,q,V):new Date(E.$y,q,V),E);return F?ie:ie.endOf(d)},J=function(V,q){return S.w(E.toDate()[V].apply(E.toDate("s"),(F?[0,0,0,0]:[23,59,59,999]).slice(q)),E)},U=this.$W,oe=this.$M,ge=this.$D,G="set"+(this.$u?"UTC":"");switch(O){case p:return F?L(1,0):L(31,11);case u:return F?L(1,oe):L(0,oe+1);case m:var me=this.$locale().weekStart||0,re=(U<me?U+7:U)-me;return L(F?ge-re:ge+(6-re),oe);case d:case g:return J(G+"Hours",0);case c:return J(G+"Minutes",1);case l:return J(G+"Seconds",2);case o:return J(G+"Milliseconds",3);default:return this.clone()}},$.endOf=function(k){return this.startOf(k,!1)},$.$set=function(k,I){var E,F=S.p(k),O="set"+(this.$u?"UTC":""),L=(E={},E[d]=O+"Date",E[g]=O+"Date",E[u]=O+"Month",E[p]=O+"FullYear",E[c]=O+"Hours",E[l]=O+"Minutes",E[o]=O+"Seconds",E[i]=O+"Milliseconds",E)[F],J=F===d?this.$D+(I-this.$W):I;if(F===u||F===p){var U=this.clone().set(g,1);U.$d[L](J),U.init(),this.$d=U.set(g,Math.min(this.$D,U.daysInMonth())).$d}else L&&this.$d[L](J);return this.init(),this},$.set=function(k,I){return this.clone().$set(k,I)},$.get=function(k){return this[S.p(k)]()},$.add=function(k,I){var E,F=this;k=Number(k);var O=S.p(I),L=function(oe){var ge=w(F);return S.w(ge.date(ge.date()+Math.round(oe*k)),F)};if(O===u)return this.set(u,this.$M+k);if(O===p)return this.set(p,this.$y+k);if(O===d)return L(1);if(O===m)return L(7);var J=(E={},E[l]=r,E[c]=n,E[o]=a,E)[O]||1,U=this.$d.getTime()+k*J;return S.w(U,this)},$.subtract=function(k,I){return this.add(-1*k,I)},$.format=function(k){var I=this,E=this.$locale();if(!this.isValid())return E.invalidDate||y;var F=k||"YYYY-MM-DDTHH:mm:ssZ",O=S.z(this),L=this.$H,J=this.$m,U=this.$M,oe=E.weekdays,ge=E.months,G=E.meridiem,me=function(q,ie,ue,Te){return q&&(q[ie]||q(I,F))||ue[ie].slice(0,Te)},re=function(q){return S.s(L%12||12,q,"0")},V=G||function(q,ie,ue){var Te=q<12?"AM":"PM";return ue?Te.toLowerCase():Te};return F.replace(C,function(q,ie){return ie||function(ue){switch(ue){case"YY":return String(I.$y).slice(-2);case"YYYY":return S.s(I.$y,4,"0");case"M":return U+1;case"MM":return S.s(U+1,2,"0");case"MMM":return me(E.monthsShort,U,ge,3);case"MMMM":return me(ge,U);case"D":return I.$D;case"DD":return S.s(I.$D,2,"0");case"d":return String(I.$W);case"dd":return me(E.weekdaysMin,I.$W,oe,2);case"ddd":return me(E.weekdaysShort,I.$W,oe,3);case"dddd":return oe[I.$W];case"H":return String(L);case"HH":return S.s(L,2,"0");case"h":return re(1);case"hh":return re(2);case"a":return V(L,J,!0);case"A":return V(L,J,!1);case"m":return String(J);case"mm":return S.s(J,2,"0");case"s":return String(I.$s);case"ss":return S.s(I.$s,2,"0");case"SSS":return S.s(I.$ms,3,"0");case"Z":return O}return null}(q)||O.replace(":","")})},$.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},$.diff=function(k,I,E){var F,O=this,L=S.p(I),J=w(k),U=(J.utcOffset()-this.utcOffset())*r,oe=this-J,ge=function(){return S.m(O,J)};switch(L){case p:F=ge()/12;break;case u:F=ge();break;case h:F=ge()/3;break;case m:F=(oe-U)/6048e5;break;case d:F=(oe-U)/864e5;break;case c:F=oe/n;break;case l:F=oe/r;break;case o:F=oe/a;break;default:F=oe}return E?F:S.a(F)},$.daysInMonth=function(){return this.endOf(u).$D},$.$locale=function(){return A[this.$L]},$.locale=function(k,I){if(!k)return this.$L;var E=this.clone(),F=P(k,I,!0);return F&&(E.$L=F),E},$.clone=function(){return S.w(this.$d,this)},$.toDate=function(){return new Date(this.valueOf())},$.toJSON=function(){return this.isValid()?this.toISOString():null},$.toISOString=function(){return this.$d.toISOString()},$.toString=function(){return this.$d.toUTCString()},_}(),B=M.prototype;return w.prototype=B,[["$ms",i],["$s",o],["$m",l],["$H",c],["$W",d],["$M",u],["$y",p],["$D",g]].forEach(function(_){B[_[1]]=function($){return this.$g($,_[0],_[1])}}),w.extend=function(_,$){return _.$i||(_($,M,w),_.$i=!0),w},w.locale=P,w.isDayjs=T,w.unix=function(_){return w(1e3*_)},w.en=A[N],w.Ls=A,w.p={},w})})(Im);var lb=Im.exports;const bt=gn(lb);var Mm={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(xn,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 N=f[b];N.d&&(g=h?n(d).diff(u,N.d,!0):u.diff(d,N.d,!0));var A=(a.rounding||Math.round)(Math.abs(g));if(v=g>0,A<=N.r||!N.r){A<=1&&b>0&&(N=f[b-1]);var D=C[N.l];p&&(A=p(""+A)),y=typeof D=="string"?D.replace("%d",A):D(A,m,N.l,v);break}}if(m)return y;var T=v?C.future:C.past;return typeof T=="function"?T(y):T.replace("%s",y)},i.to=function(d,m){return l(d,m,this,!0)},i.from=function(d,m){return l(d,m,this)};var c=function(d){return d.$u?n.utc():n()};i.toNow=function(d){return this.to(c(this),d)},i.fromNow=function(d){return this.from(c(this),d)}}})})(Mm);var cb=Mm.exports;const db=gn(cb);bt.extend(db);function mb({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 D,T,P,w,S,M,B,_;const{user:v}=ts(),C=t==null?void 0:t.pauseInfo,f=(C==null?void 0:C.isPaused)||!1,j=(D=C==null?void 0:C.pausedBy)==null?void 0:D.userId,b=(v==null?void 0:v.userId)||"",N=f&&u&&(p||s),A=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(Z,{"data-testid":"initiator-card",children:[e.jsx(ae,{className:"pb-3 sm:pb-4",children:e.jsxs(ne,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(St,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Initiator"]})}),e.jsx(X,{children:e.jsxs("div",{className:"flex items-start gap-3 sm:gap-4",children:[e.jsx($t,{className:"h-10 w-10 sm:h-12 sm:w-12 ring-2 ring-white shadow-sm flex-shrink-0",children:e.jsx(Ut,{className:"bg-gray-700 text-white font-semibold text-sm",children:((T=t.initiator)==null?void 0:T.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:((P=t.initiator)==null?void 0:P.name)||"N/A"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 truncate",children:((w=t.initiator)==null?void 0:w.role)||"N/A"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-500 truncate",children:((S=t.initiator)==null?void 0:S.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(Xa,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:((M=t.initiator)==null?void 0:M.email)||"N/A"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs sm:text-sm text-gray-600",children:[e.jsx(bn,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{children:((B=t.initiator)==null?void 0:B.phone)||"N/A"})]})]})]})]})})]}),e.jsxs(Z,{"data-testid":"request-details-card",children:[e.jsx(ae,{className:"pb-3 sm:pb-4",children:e.jsxs(ne,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Re,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Details"]})}),e.jsxs(X,{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(oa,{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:Yt(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:Yt(t.updatedAt)})]})]})]})]}),f&&C&&e.jsxs(Z,{className:"border-orange-300 bg-orange-50/50","data-testid":"pause-status-card",children:[e.jsx(ae,{className:"pb-3 sm:pb-4",children:e.jsxs(ne,{className:"flex items-center gap-2 text-sm sm:text-base text-orange-800",children:[e.jsx(ca,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Workflow Paused"]})}),e.jsxs(X,{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:[Yt(C.pauseResumeDate),bt(C.pauseResumeDate).isAfter(bt())&&e.jsxs("span",{className:"ml-2 text-xs text-gray-500",children:["(",bt(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:Yt(C.pausedAt)})]})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-2 border-t border-orange-200",children:[N&&u&&e.jsxs(R,{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(nn,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-1.5"}),"Resume Now"]}),A&&h&&e.jsxs(R,{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(Z,{children:[e.jsx(ae,{className:"pb-4",children:e.jsxs(ne,{className:"flex items-center gap-2 text-base",children:[e.jsx(Re,{className:"w-5 h-5 text-purple-600"}),"Claim Management Details"]})}),e.jsxs(X,{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?Am(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(oa,{content:t.claimDetails.requestDescription,className:"text-sm"})})]})]})]}),t.status==="closed"&&t.conclusionRemark&&e.jsxs(Z,{children:[e.jsxs(ae,{className:"bg-gradient-to-r from-gray-50 to-slate-50 border-b border-gray-200",children:[e.jsxs(ne,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ce,{className:"w-5 h-5 text-gray-600"}),"Conclusion Remark"]}),e.jsx(we,{className:"mt-1 text-xs sm:text-sm",children:"Final summary of this closed request"})]}),e.jsxs(X,{className:"pt-4",children:[e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-4",children:e.jsx(oa,{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 ",Yt(t.closureDate)]}),e.jsxs("span",{children:["By ",((_=t.initiator)==null?void 0:_.name)||"Initiator"]})]})]})]}),a&&e.jsxs(Z,{"data-testid":"conclusion-remark-card",children:[e.jsx(ae,{className:`bg-gradient-to-r border-b ${t.status==="rejected"?"from-red-50 to-rose-50 border-red-200":"from-green-50 to-emerald-50 border-green-200"}`,children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(ne,{className:`flex items-center gap-2 text-base sm:text-lg ${t.status==="rejected"?"text-red-700":"text-green-700"}`,children:[e.jsx(Ce,{className:`w-5 h-5 ${t.status==="rejected"?"text-red-600":"text-green-600"}`}),"Conclusion Remark - Final Step"]}),e.jsx(we,{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(R,{variant:"outline",size:"sm",onClick:c,disabled:i,className:"gap-2 shrink-0","data-testid":"generate-ai-conclusion-button",children:[e.jsx(es,{className:`w-3.5 h-3.5 ${i?"animate-spin":""}`}),l?"Regenerate":"Generate with AI"]})]})}),e.jsx(X,{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(Xe,{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(Em,{value:r,onChange:$=>n($),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(R,{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(Xe,{className:"w-4 h-4 mr-2 animate-spin"}),"Finalizing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ce,{className:"w-4 h-4 mr-2"}),"Finalize & Close Request"]})})})]})})]})]})}function ub({activityInfo:t,className:s}){if(!t)return console.warn("[ActivityInformationCard] activityInfo is missing"),e.jsx(Z,{className:s,children:e.jsx(X,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Activity information not available"})})});const a=n=>{const i=typeof n=="string"?parseFloat(n):n;return isNaN(i)?"N/A":`₹${i.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`},r=n=>{if(!n)return"N/A";try{return Ne(new Date(n),"MMM d, yyyy")}catch{return n}};return e.jsxs(Z,{className:s,children:[e.jsx(ae,{children:e.jsxs(ne,{className:"flex items-center gap-2 text-base",children:[e.jsx(et,{className:"w-5 h-5 text-blue-600"}),"Activity Information"]})}),e.jsxs(X,{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.activityName})]}),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.activityType})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Location"}),e.jsxs("p",{className:"text-sm text-gray-900 font-medium mt-1 flex items-center gap-2",children:[e.jsx(uo,{className:"w-4 h-4 text-gray-400"}),t.location]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Requested Date"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:r(t.requestedDate)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Estimated Budget"}),e.jsxs("p",{className:"text-sm text-gray-900 font-medium mt-1 flex items-center gap-2",children:[e.jsx(Fs,{className:"w-4 h-4 text-green-600"}),t.estimatedBudget?a(t.estimatedBudget):"TBD"]})]}),t.closedExpenses!==void 0&&t.closedExpenses!==null&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Closed Expenses"}),e.jsxs("p",{className:"text-sm text-gray-900 font-medium mt-1 flex items-center gap-2",children:[e.jsx(hs,{className:"w-4 h-4 text-blue-600"}),a(t.closedExpenses)]})]}),t.period&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Period"}),e.jsxs("p",{className:"text-sm text-gray-900 font-medium mt-1",children:[r(t.period.startDate)," - ",r(t.period.endDate)]})]})]}),t.closedExpensesBreakdown&&t.closedExpensesBreakdown.length>0&&e.jsxs("div",{className:"pt-4 border-t",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide mb-3 block",children:"Closed Expenses Breakdown"}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3 space-y-2",children:[t.closedExpensesBreakdown.map((n,i)=>e.jsxs("div",{className:"flex justify-between items-center text-sm",children:[e.jsx("span",{className:"text-gray-700",children:n.description}),e.jsx("span",{className:"font-medium text-gray-900",children:a(n.amount)})]},i)),e.jsxs("div",{className:"pt-2 border-t border-blue-300 flex justify-between items-center",children:[e.jsx("span",{className:"font-semibold text-gray-900",children:"Total"}),e.jsx("span",{className:"font-bold text-blue-600",children:a(t.closedExpensesBreakdown.reduce((n,i)=>n+i.amount,0))})]})]})]}),t.description&&e.jsxs("div",{className:"pt-4 border-t",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Description"}),e.jsx("p",{className:"text-sm text-gray-700 mt-2 bg-gray-50 p-3 rounded-lg whitespace-pre-line",children:t.description})]})]})]})}function hb({dealerInfo:t,className:s}){return t?!t.dealerCode&&!t.dealerName?(console.warn("[DealerInformationCard] Dealer info missing essential fields:",t),e.jsx(Z,{className:s,children:e.jsx(X,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Dealer information incomplete"})})})):e.jsxs(Z,{className:s,children:[e.jsx(ae,{children:e.jsxs(ne,{className:"flex items-center gap-2 text-base",children:[e.jsx(ho,{className:"w-5 h-5 text-purple-600"}),"Dealer Information"]})}),e.jsxs(X,{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:"Dealer Code"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.dealerCode})]}),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.dealerName})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Contact Information"}),e.jsxs("div",{className:"mt-2 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-700",children:[e.jsx(Xa,{className:"w-4 h-4 text-gray-400"}),e.jsx("span",{children:t.email})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-700",children:[e.jsx(bn,{className:"w-4 h-4 text-gray-400"}),e.jsx("span",{children:t.phone})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm text-gray-700",children:[e.jsx(uo,{className:"w-4 h-4 text-gray-400 mt-0.5"}),e.jsx("span",{children:t.address})]})]})]})]})]}):(console.warn("[DealerInformationCard] dealerInfo is missing"),e.jsx(Z,{className:s,children:e.jsx(X,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Dealer information not available"})})}))}function pb({proposalDetails:t,className:s}){const a=i=>i==null||Number.isNaN(i)?"₹0.00":`₹${i.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,r=i=>{if(!i)return"";try{return Ne(new Date(i),"MMM d, yyyy, h:mm a")}catch{return i||""}},n=i=>{if(!i)return"-";try{return Ne(new Date(i),"MMM d, yyyy")}catch{return i||"-"}};return e.jsxs(Z,{className:s,children:[e.jsxs(ae,{children:[e.jsxs(ne,{className:"flex items-center gap-2 text-base",children:[e.jsx(hs,{className:"w-5 h-5 text-green-600"}),"Proposal Details"]}),t.submittedOn&&e.jsxs(we,{children:["Submitted on ",r(t.submittedOn)]})]}),e.jsxs(X,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide mb-3 block",children:"Cost Breakup"}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{className:"bg-gray-50",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-2 text-left text-xs font-semibold text-gray-700 uppercase tracking-wide",children:"Item Description"}),e.jsx("th",{className:"px-4 py-2 text-right text-xs font-semibold text-gray-700 uppercase tracking-wide",children:"Amount"})]})}),e.jsxs("tbody",{className:"divide-y divide-gray-200",children:[(t.costBreakup||[]).map((i,o)=>e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 text-sm text-gray-900",children:i.description}),e.jsx("td",{className:"px-4 py-3 text-sm text-gray-900 text-right font-medium",children:a(i.amount)})]},o)),e.jsxs("tr",{className:"bg-green-50 font-semibold",children:[e.jsx("td",{className:"px-4 py-3 text-sm text-gray-900",children:"Estimated Budget (Total)"}),e.jsx("td",{className:"px-4 py-3 text-sm text-green-700 text-right",children:a(t.estimatedBudgetTotal)})]})]})]})})]}),e.jsxs("div",{className:"pt-2",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Timeline for Closure"}),e.jsx("div",{className:"mt-2 bg-blue-50 border border-blue-200 rounded-lg p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(et,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{className:"text-sm font-medium text-gray-900",children:["Expected completion by: ",n(t.timelineForClosure)]})]})})]}),t.dealerComments&&e.jsxs("div",{className:"pt-2",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Dealer Comments"}),e.jsx("p",{className:"text-sm text-gray-700 mt-2 bg-gray-50 p-3 rounded-lg whitespace-pre-line",children:t.dealerComments})]})]})]})}function xb({ioDetails:t,dmsDetails:s,claimAmount:a,estimatedBudgetBreakdown:r,closedExpensesBreakdown:n,visibility:i,onEditClaimAmount:o,className:l}){const c=h=>h==null||Number.isNaN(h)?"₹0.00":`₹${h.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,d=h=>{if(!h)return"";try{return Ne(new Date(h),"MMM d, yyyy, h:mm a")}catch{return h||""}},m=h=>!h||h.length===0?0:h.reduce((p,g)=>p+(g.amount??0),0);return i.showIODetails&&t||i.showDMSDetails&&s||i.showClaimAmount&&a&&a.amount!==void 0&&a.amount!==null||r&&r.length>0||n&&n.length>0?e.jsxs(Z,{className:`bg-gradient-to-br from-blue-50 to-purple-50 border-2 border-blue-200 ${l}`,children:[e.jsxs(ae,{children:[e.jsxs(ne,{className:"text-base flex items-center gap-2",children:[e.jsx(qt,{className:"w-4 h-4 text-blue-600"}),"Process Details"]}),e.jsx(we,{children:"Workflow reference numbers"})]}),e.jsxs(X,{className:"space-y-3",children:[i.showIODetails&&t&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-blue-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(hs,{className:"w-4 h-4 text-blue-600"}),e.jsx(Y,{className:"text-xs font-semibold text-blue-900 uppercase tracking-wide",children:"IO Number"})]}),e.jsx("p",{className:"font-bold text-gray-900 mb-2",children:t.ioNumber}),t.remarks&&e.jsxs("div",{className:"pt-2 border-t border-blue-100",children:[e.jsx("p",{className:"text-xs text-gray-600 mb-1",children:"Remark:"}),e.jsx("p",{className:"text-xs text-gray-900",children:t.remarks})]}),(t.availableBalance!==void 0||t.blockedAmount!==void 0)&&e.jsxs("div",{className:"pt-2 border-t border-blue-100 mt-2 space-y-1",children:[t.availableBalance!==void 0&&e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Available Balance:"}),e.jsx("span",{className:"font-medium text-gray-900",children:c(t.availableBalance)})]}),t.blockedAmount!==void 0&&e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Blocked Amount:"}),e.jsx("span",{className:"font-medium text-blue-700",children:c(t.blockedAmount)})]}),t.remainingBalance!==void 0&&e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Remaining Balance:"}),e.jsx("span",{className:"font-medium text-green-700",children:c(t.remainingBalance)})]})]}),e.jsxs("div",{className:"pt-2 border-t border-blue-100 mt-2",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:["By ",t.blockedByName]}),e.jsx("p",{className:"text-xs text-gray-500",children:d(t.blockedAt)})]})]}),i.showDMSDetails&&s&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(qt,{className:"w-4 h-4 text-purple-600"}),e.jsx(Y,{className:"text-xs font-semibold text-purple-900 uppercase tracking-wide",children:"DMS Number"})]}),e.jsx("p",{className:"font-bold text-gray-900 mb-2",children:s.dmsNumber}),s.remarks&&e.jsxs("div",{className:"pt-2 border-t border-purple-100",children:[e.jsx("p",{className:"text-xs text-gray-600 mb-1",children:"Remarks:"}),e.jsx("p",{className:"text-xs text-gray-900",children:s.remarks})]}),e.jsxs("div",{className:"pt-2 border-t border-purple-100 mt-2",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:["By ",s.createdByName]}),e.jsx("p",{className:"text-xs text-gray-500",children:d(s.createdAt)})]})]}),i.showClaimAmount&&a&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-green-200",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fs,{className:"w-4 h-4 text-green-600"}),e.jsx(Y,{className:"text-xs font-semibold text-green-900 uppercase tracking-wide",children:"Claim Amount"})]}),i.canEditClaimAmount&&o&&e.jsxs(R,{variant:"outline",size:"sm",onClick:o,className:"h-7 px-2 text-xs border-green-300 hover:bg-green-50",children:[e.jsx(Kd,{className:"w-3 h-3 mr-1 text-green-700"}),"Edit"]})]}),e.jsx("p",{className:"text-2xl font-bold text-green-700",children:c(a.amount)}),a.lastUpdatedBy&&e.jsxs("div",{className:"mt-2 pt-2 border-t border-green-100",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:["Last updated by ",a.lastUpdatedBy]}),a.lastUpdatedAt&&e.jsx("p",{className:"text-xs text-gray-500",children:d(a.lastUpdatedAt)})]})]}),r&&r.length>0&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-amber-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(hs,{className:"w-4 h-4 text-amber-600"}),e.jsx(Y,{className:"text-xs font-semibold text-amber-900 uppercase tracking-wide",children:"Estimated Budget Breakdown"})]}),e.jsxs("div",{className:"space-y-1.5 pt-1",children:[r.map((h,p)=>e.jsxs("div",{className:"flex justify-between items-center text-xs",children:[e.jsx("span",{className:"text-gray-700",children:h.description}),e.jsx("span",{className:"font-medium text-gray-900",children:c(h.amount)})]},p)),e.jsxs("div",{className:"pt-2 border-t border-amber-200 flex justify-between items-center",children:[e.jsx("span",{className:"font-semibold text-gray-900 text-xs",children:"Total"}),e.jsx("span",{className:"font-bold text-amber-700",children:c(m(r))})]})]})]}),n&&n.length>0&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-indigo-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(hs,{className:"w-4 h-4 text-indigo-600"}),e.jsx(Y,{className:"text-xs font-semibold text-indigo-900 uppercase tracking-wide",children:"Closed Expenses Breakdown"})]}),e.jsxs("div",{className:"space-y-1.5 pt-1",children:[n.map((h,p)=>e.jsxs("div",{className:"flex justify-between items-center text-xs",children:[e.jsx("span",{className:"text-gray-700",children:h.description}),e.jsx("span",{className:"font-medium text-gray-900",children:c(h.amount)})]},p)),e.jsxs("div",{className:"pt-2 border-t border-indigo-200 flex justify-between items-center",children:[e.jsx("span",{className:"font-semibold text-gray-900 text-xs",children:"Total"}),e.jsx("span",{className:"font-bold text-indigo-700",children:c(m(n))})]})]})]})]})]}):null}function gb({initiatorInfo:t,className:s}){const a=r=>r.split(" ").map(n=>n[0]).join("").toUpperCase().slice(0,2);return e.jsxs(Z,{className:s,children:[e.jsx(ae,{children:e.jsx(ne,{className:"text-base",children:"Request Initiator"})}),e.jsx(X,{children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx($t,{className:"h-14 w-14 ring-2 ring-white shadow-md",children:e.jsx(Ut,{className:"bg-gray-700 text-white font-semibold text-lg",children:a(t.name)})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-gray-900",children:t.name}),t.role&&e.jsx("p",{className:"text-sm text-gray-600",children:t.role}),t.department&&e.jsx("p",{className:"text-sm text-gray-500",children:t.department}),e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:[e.jsx(Xa,{className:"w-4 h-4"}),e.jsx("span",{children:t.email})]}),t.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:[e.jsx(bn,{className:"w-4 h-4"}),e.jsx("span",{children:t.phone})]})]})]})]})})]})}function Ta(t){return t?t.workflowType==="CLAIM_MANAGEMENT"||t.templateType==="claim-management"||t.template==="claim-management"||t.templateName==="Claim Management"||t.templateCode==="CLAIM_MANAGEMENT":!1}function Fm(t,s){var a,r;try{if(!Ta(t))return null;const n=t.claimDetails||{},i=t.proposalDetails||{},o=t.completionDetails||{},l=t.internalOrder||t.internal_order||{},c=t.budgetTracking||t.budget_tracking||{},d=t.invoice||{},m=t.creditNote||t.credit_note||{},u=t.completionExpenses||t.completion_expenses||[];console.debug("[claimDataMapper] Raw claimDetails:",n),console.debug("[claimDataMapper] Raw apiRequest:",{hasClaimDetails:!!t.claimDetails,hasProposalDetails:!!t.proposalDetails,hasCompletionDetails:!!t.completionDetails,hasBudgetTracking:!!c,hasInvoice:!!d,hasCreditNote:!!m,hasCompletionExpenses:Array.isArray(u)&&u.length>0,workflowType:t.workflowType});const h=n.periodStartDate||n.period_start_date,p=n.periodEndDate||n.period_end_date,g=n.activityName||n.activity_name||"",y=n.activityType||n.activity_type||"",v=n.location||"";console.debug("[claimDataMapper] Mapped activity fields:",{activityName:g,activityType:y,location:v,hasActivityName:!!g,hasActivityType:!!y,hasLocation:!!v});const C=c.proposalEstimatedBudget||c.proposal_estimated_budget||c.initialEstimatedBudget||c.initial_estimated_budget||n.estimatedBudget||n.estimated_budget,f=(c==null?void 0:c.closedExpenses)||(c==null?void 0:c.closed_expenses)||(o==null?void 0:o.totalClosedExpenses)||(o==null?void 0:o.total_closed_expenses)||(n==null?void 0:n.closedExpenses)||(n==null?void 0:n.closed_expenses),j=f!=null?Number(f):void 0,b=Array.isArray(u)&&u.length>0?u.map(S=>({description:S.description||S.itemDescription||"",amount:Number(S.amount)||0})):(o==null?void 0:o.closedExpenses)||(o==null?void 0:o.closed_expenses)||(o==null?void 0:o.closedExpensesBreakdown)||[],N={activityName:g,activityType:y,requestedDate:n.activityDate||n.activity_date||t.createdAt,location:v,period:h&&p?{startDate:h,endDate:p}:void 0,estimatedBudget:C,closedExpenses:j,closedExpensesBreakdown:b,description:t.description||""},A={dealerCode:(n==null?void 0:n.dealerCode)||(n==null?void 0:n.dealer_code)||(n==null?void 0:n.DealerCode)||"",dealerName:(n==null?void 0:n.dealerName)||(n==null?void 0:n.dealer_name)||(n==null?void 0:n.DealerName)||"",email:(n==null?void 0:n.dealerEmail)||(n==null?void 0:n.dealer_email)||(n==null?void 0:n.DealerEmail)||"",phone:(n==null?void 0:n.dealerPhone)||(n==null?void 0:n.dealer_phone)||(n==null?void 0:n.DealerPhone)||"",address:(n==null?void 0:n.dealerAddress)||(n==null?void 0:n.dealer_address)||(n==null?void 0:n.DealerAddress)||""};(!A.dealerCode||!A.dealerName)&&console.warn("[claimDataMapper] Dealer information is missing from claimDetails:",{hasClaimDetails:!!n,dealerCode:A.dealerCode,dealerName:A.dealerName,rawClaimDetails:n,availableKeys:n?Object.keys(n):[]});const D=i?{proposalDocumentUrl:i.proposalDocumentUrl||i.proposal_document_url,costBreakup:i.costBreakup||i.cost_breakup||[],totalEstimatedBudget:i.totalEstimatedBudget||i.total_estimated_budget||0,timelineMode:i.timelineMode||i.timeline_mode,expectedCompletionDate:i.expectedCompletionDate||i.expected_completion_date,expectedCompletionDays:i.expectedCompletionDays||i.expected_completion_days,dealerComments:i.dealerComments||i.dealer_comments,submittedAt:i.submittedAt||i.submitted_at}:void 0,T={ioNumber:l.ioNumber||l.io_number||n.ioNumber||n.io_number,ioRemark:l.ioRemark||l.io_remark||"",availableBalance:l.ioAvailableBalance||l.io_available_balance||n.ioAvailableBalance||n.io_available_balance,blockedAmount:l.ioBlockedAmount||l.io_blocked_amount||n.ioBlockedAmount||n.io_blocked_amount,remainingBalance:l.ioRemainingBalance||l.io_remaining_balance||n.ioRemainingBalance||n.io_remaining_balance,organizedBy:((a=l.organizer)==null?void 0:a.displayName)||((r=l.organizer)==null?void 0:r.name)||l.organizedBy||"",organizedAt:l.organizedAt||l.organized_at||""},P={eInvoiceNumber:d.invoiceNumber||d.invoice_number||n.eInvoiceNumber||n.e_invoice_number,eInvoiceDate:d.invoiceDate||d.invoice_date||n.eInvoiceDate||n.e_invoice_date,dmsNumber:d.dmsNumber||d.dms_number||n.dmsNumber||n.dms_number,creditNoteNumber:m.creditNoteNumber||m.credit_note_number||n.creditNoteNumber||n.credit_note_number,creditNoteDate:m.creditNoteDate||m.credit_note_date||n.creditNoteDate||n.credit_note_date,creditNoteAmount:m.creditNoteAmount?Number(m.creditNoteAmount):m.credit_note_amount?Number(m.credit_note_amount):m.creditNoteAmount?Number(m.creditNoteAmount):n.creditNoteAmount?Number(n.creditNoteAmount):n.credit_note_amount?Number(n.credit_note_amount):void 0},w={estimated:N.estimatedBudget||0,closed:N.closedExpenses||0};return{activityInfo:N,dealerInfo:A,proposalDetails:D,ioDetails:Object.keys(T).some(S=>T[S])?T:void 0,dmsDetails:Object.keys(P).some(S=>P[S])?P:void 0,claimAmount:w}}catch(n){return console.error("[claimDataMapper] Error mapping claim data:",n),null}}function _m(t,s){var a,r;try{if(t.initiatorId===s||((a=t.initiator)==null?void 0:a.userId)===s||((r=t.requestedBy)==null?void 0:r.userId)===s)return"INITIATOR";if((t.participants||[]).find(d=>{var m;return(d.userId===s||((m=d.user)==null?void 0:m.userId)===s)&&(d.participantType==="DEALER"||d.type==="DEALER")}))return"DEALER";const o=t.approvalLevels||[];return o.find(d=>{var m;return d.levelNumber===3&&(d.approverId===s||((m=d.approver)==null?void 0:m.userId)===s)})?"DEPARTMENT_LEAD":o.find(d=>{var m;return(d.approverId===s||((m=d.approver)==null?void 0:m.userId)===s)&&d.status==="PENDING"})?"APPROVER":"SPECTATOR"}catch(n){return console.error("[claimDataMapper] Error determining user role:",n),"SPECTATOR"}}function Lm(t){switch(t){case"INITIATOR":return{showDealerInfo:!0,showProposalDetails:!0,showIODetails:!0,showDMSDetails:!0,showClaimAmount:!0,canEditClaimAmount:!1};case"DEALER":return{showDealerInfo:!0,showProposalDetails:!0,showIODetails:!1,showDMSDetails:!1,showClaimAmount:!0,canEditClaimAmount:!1};case"DEPARTMENT_LEAD":return{showDealerInfo:!0,showProposalDetails:!0,showIODetails:!0,showDMSDetails:!0,showClaimAmount:!0,canEditClaimAmount:!1};case"APPROVER":return{showDealerInfo:!0,showProposalDetails:!0,showIODetails:!0,showDMSDetails:!0,showClaimAmount:!0,canEditClaimAmount:!1};case"SPECTATOR":default:return{showDealerInfo:!1,showProposalDetails:!1,showIODetails:!1,showDMSDetails:!1,showClaimAmount:!1,canEditClaimAmount:!1}}}function fb({request:t,apiRequest:s,currentUserId:a,isInitiator:r,onEditClaimAmount:n,className:i=""}){var m,u,h,p,g,y,v,C,f,j,b,N,A,D,T;if(!Ta(s))return e.jsx("div",{className:"text-center py-8 text-gray-500",children:e.jsx("p",{children:"This is not a claim management request."})});const o=Fm(s);if(!o)return console.warn("[ClaimManagementOverviewTab] Failed to map claim data:",{apiRequest:s,hasClaimDetails:!!(s!=null&&s.claimDetails),hasProposalDetails:!!(s!=null&&s.proposalDetails),hasCompletionDetails:!!(s!=null&&s.completionDetails)}),e.jsxs("div",{className:"text-center py-8 text-gray-500",children:[e.jsx("p",{children:"Unable to load claim management data."}),e.jsx("p",{className:"text-xs mt-2",children:"Please ensure the request has been properly initialized."})]});console.debug("[ClaimManagementOverviewTab] Mapped claim data:",{activityInfo:o.activityInfo,dealerInfo:o.dealerInfo,hasProposalDetails:!!o.proposalDetails,closedExpenses:(m=o.activityInfo)==null?void 0:m.closedExpenses,closedExpensesBreakdown:(u=o.activityInfo)==null?void 0:u.closedExpensesBreakdown,hasDealerCode:!!((h=o.dealerInfo)!=null&&h.dealerCode),hasDealerName:!!((p=o.dealerInfo)!=null&&p.dealerName)});const l=_m(s,a),c=Lm(l);console.debug("[ClaimManagementOverviewTab] User role and visibility:",{userRole:l,visibility:c,currentUserId:a,showDealerInfo:c.showDealerInfo,dealerInfoPresent:!!((g=o.dealerInfo)!=null&&g.dealerCode||(y=o.dealerInfo)!=null&&y.dealerName)});const d={name:((v=s.initiator)==null?void 0:v.name)||((C=s.initiator)==null?void 0:C.displayName)||((f=s.initiator)==null?void 0:f.email)||"Unknown",role:((j=s.initiator)==null?void 0:j.role)||((b=s.initiator)==null?void 0:b.designation)||"Initiator",department:((N=s.initiator)==null?void 0:N.department)||s.department||"",email:((A=s.initiator)==null?void 0:A.email)||"N/A",phone:((D=s.initiator)==null?void 0:D.phone)||((T=s.initiator)==null?void 0:T.mobile)};return e.jsxs("div",{className:`space-y-6 ${i}`,children:[e.jsx(ub,{activityInfo:o.activityInfo}),e.jsx(hb,{dealerInfo:o.dealerInfo}),c.showProposalDetails&&o.proposalDetails&&e.jsx(pb,{proposalDetails:o.proposalDetails}),e.jsx(gb,{initiatorInfo:d})]})}function Jr({delayDuration:t=0,...s}){return e.jsx(zp,{"data-slot":"tooltip-provider",delayDuration:t,...s})}function Xn({...t}){return e.jsx(Jr,{children:e.jsx(Hp,{"data-slot":"tooltip",...t})})}function Jn({...t}){return e.jsx(Wp,{"data-slot":"tooltip-trigger",...t})}function Qn({className:t,sideOffset:s=0,children:a,...r}){return e.jsx(Kp,{children:e.jsxs(Gp,{"data-slot":"tooltip-content",sideOffset:s,className:fe("bg-primary text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",t),...r,children:[a,e.jsx(Yp,{className:"bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function os({className:t,...s}){return e.jsx("textarea",{"data-slot":"textarea",className:fe("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 Bl=t=>{if(t<8)return At(t);const a=Math.floor(t/8),r=t%8;return r>0?`${a}d ${At(r)}`:`${a}d`},yb=(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(Ce,{className:"w-4 h-4 sm:w-5 sm:w-5 text-green-600"});case"rejected":return e.jsx(ht,{className:"w-4 h-4 sm:w-5 sm:h-5 text-red-600"});case"paused":return e.jsx(Gd,{className:"w-4 h-4 sm:w-5 sm:h-5 text-yellow-600"});case"pending":case"in-review":return e.jsx(Ue,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"});case"waiting":return e.jsx(Ue,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400"});default:return e.jsx(Ue,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400"})}};function bb({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}=ts(),[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",N=t.status==="paused",A=Number(t.tatHours||0),D=t.actualHours??0,T=f&&D?Math.max(0,A-D):0,P=A>0?D/A*100:0,w=P>=100,S=(d==null?void 0:d.role)==="ADMIN",M=Cn(d),B=t.approverId===(d==null?void 0:d.userId),_=S||M||B,$=async()=>{var k,I;if(!h.trim()){te.error("Breach Reason Required",{description:"Please enter a reason for the breach."});return}y(!0);try{await oy(t.levelId,h.trim()),u(!1),p(""),te.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(E){console.error("Error updating breach reason:",E);const F=((I=(k=E==null?void 0:E.response)==null?void 0:k.data)==null?void 0:I.error)||(E==null?void 0:E.message)||"Failed to update breach reason. Please try again.";te.error("Failed to Update Breach Reason",{description:F,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":N?"bg-yellow-100":C?"bg-blue-100":f?"bg-green-100":j?"bg-red-100":b?"bg-gray-200":"bg-gray-100"}`,children:yb(t.status,t.isSkipped)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-2 sm:gap-4 mb-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2 mb-2",children:[e.jsxs("h4",{className:"font-semibold text-gray-900 text-base sm:text-lg","data-testid":`${c}-approver-label`,children:["Approver ",s+1]}),e.jsx(ee,{variant:"outline",className:`text-xs shrink-0 capitalize ${t.isSkipped?"bg-orange-100 text-orange-800 border-orange-200":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(Jr,{delayDuration:200,children:e.jsxs(Xn,{children:[e.jsx(Jn,{asChild:!0,children:e.jsx("button",{type:"button",className:"inline-flex items-center justify-center cursor-pointer hover:opacity-80 transition-opacity",onClick:k=>k.stopPropagation(),children:e.jsx(Pe,{className:"w-4 h-4 text-orange-600"})})}),e.jsxs(Qn,{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(Nl,{className:"w-3 h-3"}),"Skip Reason:"]}),e.jsx("p",{className:"text-xs text-gray-700",children:t.skipReason})]})]})}),f&&D&&e.jsx(ee,{className:"bg-green-600 text-white text-xs","data-testid":`${c}-completion-time`,children:Bl(D)})]}),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:[A," hours"]})]})]}),f&&D!==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?Yt(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:Bl(D)})]}),e.jsx("div",{className:"space-y-2",children:(()=>{const k=Math.min(100,P),I=()=>w?"bg-red-600":P>=75?"bg-orange-500":P>=50?"bg-amber-500":"bg-green-600",E=()=>w?"text-red-600":P>=75?"text-orange-600":P>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(_s,{value:k,className:"h-2 bg-gray-200",indicatorClassName:I(),"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 ${E()}`,children:[Math.round(k),"% of TAT used"]}),w&&_&&e.jsx(Jr,{children:e.jsxs(Xn,{children:[e.jsx(Jn,{asChild:!0,children:e.jsx(R,{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(Br,{className:"w-3 h-3"})})}),e.jsx(Qn,{children:e.jsx("p",{children:v?"Edit breach reason":"Add breach reason"})})]})})]}),T>0&&e.jsxs("span",{className:"text-green-600 font-semibold",children:["Saved ",At(T)]})]})]})})()}),w&&v&&e.jsxs("div",{className:"mt-4 p-3 sm:p-4 bg-red-50 border-l-4 border-red-500 rounded-r-lg",children:[e.jsxs("p",{className:"text-xs font-semibold text-red-700 mb-2 flex items-center gap-1.5",children:[e.jsx(Br,{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(Ds,{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||N)&&(a==null?void 0:a.sla)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Due by:"}),e.jsx("span",{className:"font-medium text-gray-900",children:a.sla.deadline?Ls(a.sla.deadline,!0):"Not set"})]}),e.jsxs("div",{className:`border rounded-lg p-3 ${N?"bg-gray-100 border-gray-300":(a.sla.percentageUsed||0)>=100?"bg-red-50 border-red-200":(a.sla.percentageUsed||0)>=75?"bg-orange-50 border-orange-200":(a.sla.percentageUsed||0)>=50?"bg-amber-50 border-amber-200":"bg-green-50 border-green-200"}`,children:[e.jsxs("p",{className:"text-xs font-semibold text-gray-900 mb-3 flex items-center gap-2",children:[e.jsx(Ue,{className:"w-4 h-4"}),"Current Approver - Time Tracking ",N&&"(Paused)"]}),e.jsxs("div",{className:"space-y-2 text-xs mb-3",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-600",children:"Time elapsed since assigned:"}),e.jsx("span",{className:"font-medium text-gray-900",children:a.sla.elapsedText})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-600",children:"Time used:"}),e.jsxs("span",{className:"font-medium text-gray-900",children:[a.sla.elapsedText," / ",At(A)," allocated"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[(()=>{const k=a.sla.percentageUsed||0,I=()=>N?"bg-gray-500":k>=100?"bg-red-600":k>=75?"bg-orange-500":k>=50?"bg-amber-500":"bg-green-600",E=()=>N?"text-gray-600":k>=100?"text-red-600":k>=75?"text-orange-600":k>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(_s,{value:a.sla.percentageUsed,className:"h-3",indicatorClassName:I(),"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 ${E()}`,children:["Progress: ",Math.min(100,a.sla.percentageUsed),"% of TAT used"]}),a.sla.status==="breached"&&_&&e.jsx(Jr,{children:e.jsxs(Xn,{children:[e.jsx(Jn,{asChild:!0,children:e.jsx(R,{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(Br,{className:"w-3 h-3"})})}),e.jsx(Qn,{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(ki,{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(Br,{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(Cs,{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(Gd,{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 ",A," 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(ht,{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(Nl,{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 ",Yt(t.timestamp)]})]}),t.tatAlerts&&t.tatAlerts.length>0&&e.jsx("div",{className:"mt-2 sm:mt-3 space-y-2",children:t.tatAlerts.map((k,I)=>{var E,F,O,L,J,U;return e.jsx("div",{className:`p-2 sm:p-3 rounded-lg border ${k.isBreached?"bg-red-50 border-red-200":(k.thresholdPercentage||0)===75?"bg-orange-50 border-orange-200":"bg-yellow-50 border-yellow-200"}`,"data-testid":`${c}-tat-alert-${I}`,children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("div",{className:"flex-shrink-0 mt-0.5",children:[(k.thresholdPercentage||0)===50&&e.jsx($x,{className:"w-5 h-5 text-yellow-600"}),(k.thresholdPercentage||0)===75&&e.jsx(Cs,{className:"w-5 h-5 text-orange-600"}),(k.thresholdPercentage||0)===100&&e.jsx(ki,{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 ",I+1," - ",k.thresholdPercentage||0,"% TAT"]}),e.jsx(ee,{variant:"outline",className:`text-[10px] sm:text-xs shrink-0 ${k.isBreached?"bg-red-100 text-red-800 border-red-300":"bg-amber-100 text-amber-800 border-amber-300"}`,children:k.isBreached?"BREACHED":"WARNING"})]}),e.jsxs("p",{className:"text-[10px] sm:text-xs md:text-sm text-gray-700 mt-1",children:[k.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:At(Number(k.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:[At(Number(k.tatHoursElapsed||0)),((E=k.metadata)==null?void 0:E.tatTestMode)&&e.jsxs("span",{className:"text-purple-600 ml-1",children:["(",(Number(k.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 ${(k.tatHoursRemaining||0)<2?"text-red-600":"text-gray-900"}`,children:[At(Number(k.tatHoursRemaining||0)),((F=k.metadata)==null?void 0:F.tatTestMode)&&e.jsxs("span",{className:"text-purple-600 ml-1",children:["(",(Number(k.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:k.expectedCompletionTime?Ls(k.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"}),(((O=k.metadata)==null?void 0:O.testMode)||((L=k.metadata)==null?void 0:L.tatTestMode))&&e.jsx(ee,{variant:"outline",className:"bg-purple-50 text-purple-700 border-purple-300 text-[10px] px-1.5 py-0 shrink-0",children:"TEST MODE"})]}),e.jsxs("p",{className:"text-[10px] sm:text-xs text-gray-600 font-medium mt-0.5",children:["Sent at: ",k.alertSentAt?Yt(k.alertSentAt):"N/A"]}),(((J=k.metadata)==null?void 0:J.testMode)||((U=k.metadata)==null?void 0:U.tatTestMode))&&e.jsx("p",{className:"text-[10px] text-purple-600 mt-1 italic",children:"Note: Test mode active (1 hour = 1 minute)"})]})]})]})},I)})}),t.timestamp&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:[f?"Approved":j?"Rejected":"Actioned"," on ",Yt(t.timestamp)]}),n&&!N&&(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(R,{variant:"outline",size:"sm",className:"w-full border-orange-300 text-orange-700 hover:bg-orange-50 h-9 sm:h-10 text-xs sm:text-sm",onClick:()=>o({levelId:t.levelId,approverName:t.approver,levelNumber:t.step}),"data-testid":`${c}-skip-button`,children:[e.jsx(Pe,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Skip This Approver"]}),e.jsx("p",{className:"text-[10px] sm:text-xs text-gray-500 mt-1 text-center",children:N?"Skip this approver to resume the workflow and move to next level":"Skip if approver is unavailable and move to next level"})]})]})]}),e.jsx(nt,{open:m,onOpenChange:u,children:e.jsxs(at,{className:"sm:max-w-[500px]",children:[e.jsxs(it,{children:[e.jsx(rt,{children:v?"Edit Breach Reason":"Add Breach Reason"}),e.jsx(Ht,{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(os,{placeholder:"Enter the reason for the breach...",value:h,onChange:k=>p(k.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(yt,{children:[e.jsx(R,{variant:"outline",onClick:()=>{u(!1),p("")},disabled:g,children:"Cancel"}),e.jsx(R,{onClick:$,disabled:!h.trim()||g,className:"bg-red-600 hover:bg-red-700",children:g?"Saving...":"Save Reason"})]})]})})]})}function vb({request:t,user:s,isInitiator:a,onSkipApprover:r,onRefresh:n}){return e.jsxs(Z,{children:[e.jsx(ae,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-4",children:[e.jsxs("div",{children:[e.jsxs(ne,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Ys,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Approval Workflow"]}),e.jsx(we,{className:"mt-1 sm:mt-2 text-xs sm:text-sm",children:"Track the approval progress through each step"})]}),t.totalSteps&&(()=>{var p;const i=t.totalSteps||1,o=t.currentStepRaw!==void 0?t.currentStepRaw:t.currentStep||1,l=((p=t.approvalFlow)==null?void 0:p.filter(g=>{const y=(g.status||"").toLowerCase();return y==="approved"||y==="rejected"}).length)||0,c=l>=i,d=(t.status||"").toLowerCase(),m=d==="approved"||d==="rejected"||d==="closed",u=o>i,h=Math.min(Math.max(1,o),i);return u?e.jsxs(ee,{variant:"outline",className:"font-medium text-xs sm:text-sm shrink-0 bg-blue-50 text-blue-700 border-blue-200",children:["Closure Step - ",l," of ",i," steps completed"]}):m||c?e.jsxs(ee,{variant:"outline",className:"font-medium text-xs sm:text-sm shrink-0 bg-green-50 text-green-700 border-green-200",children:["Completed - ",l," of ",i," steps"]}):e.jsxs(ee,{variant:"outline",className:"font-medium text-xs sm:text-sm shrink-0",children:["Step ",h," of ",i," - ",l," completed"]})})()]})}),e.jsx(X,{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(bb,{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"})})]})}function jb({isOpen:t,onClose:s,onSubmit:a,dealerName:r="Jaipur Royal Enfield",activityName:n="Activity",requestId:i}){const[o,l]=x.useState(null),[c,d]=x.useState([{id:"1",description:"",amount:0}]),[m,u]=x.useState("date"),[h,p]=x.useState(""),[g,y]=x.useState(""),[v,C]=x.useState([]),[f,j]=x.useState(""),[b,N]=x.useState(!1),A=x.useRef(null),D=x.useRef(null),T=x.useMemo(()=>c.reduce((O,L)=>O+(L.amount||0),0),[c]),P=x.useMemo(()=>{const O=o!==null,L=c.length>0&&c.every(oe=>oe.description.trim()!==""&&oe.amount>0),J=m==="date"?h!=="":g!==""&&parseInt(g)>0,U=f.trim().length>0;return O&&L&&J&&U},[o,c,m,h,g,f]),w=O=>{var J,U;const L=(J=O.target.files)==null?void 0:J[0];if(L){const oe=[".pdf",".doc",".docx"],ge="."+((U=L.name.split(".").pop())==null?void 0:U.toLowerCase());if(!oe.includes(ge)){te.error("Please upload a PDF, DOC, or DOCX file");return}l(L)}},S=O=>{const L=Array.from(O.target.files||[]);C(J=>[...J,...L])},M=()=>{d(O=>[...O,{id:Date.now().toString(),description:"",amount:0}])},B=O=>{c.length>1&&d(L=>L.filter(J=>J.id!==O))},_=(O,L,J)=>{d(U=>U.map(oe=>oe.id===O?{...oe,[L]:L==="amount"?parseFloat(J.toString())||0:J}:oe))},$=O=>{C(L=>L.filter((J,U)=>U!==O))},k=async()=>{if(!P){te.error("Please fill all required fields");return}let O=h||"";if(m==="days"&&g){const L=parseInt(g),J=new Date;J.setDate(J.getDate()+L),O=J.toISOString().split("T")[0]}try{N(!0),await a({proposalDocument:o,costBreakup:c.filter(L=>L.description.trim()!==""&&L.amount>0),expectedCompletionDate:O,otherDocuments:v,dealerComments:f}),I(),s()}catch(L){console.error("Failed to submit proposal:",L),te.error("Failed to submit proposal. Please try again.")}finally{N(!1)}},I=()=>{l(null),d([{id:"1",description:"",amount:0}]),u("date"),p(""),y(""),C([]),j(""),A.current&&(A.current.value=""),D.current&&(D.current.value="")},E=()=>{b||(I(),s())},F=new Date().toISOString().split("T")[0];return e.jsx(nt,{open:t,onOpenChange:E,children:e.jsxs(at,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(it,{children:[e.jsxs(rt,{className:"flex items-center gap-2 text-2xl",children:[e.jsx(ps,{className:"w-6 h-6 text-[--re-green]"}),"Dealer Proposal Submission"]}),e.jsx(Ht,{className:"text-base",children:"Step 1: Upload proposal and planning details"}),e.jsxs("div",{className:"space-y-1 mt-2 text-sm text-gray-600",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Dealer:"})," ",r]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Activity:"})," ",n]}),e.jsx("div",{className:"mt-2",children:"Please upload proposal document, provide cost breakdown, timeline, and detailed comments."})]})]}),e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Proposal Document"}),e.jsx(ee,{className:"bg-red-500 text-white text-xs",children:"Required"})]}),e.jsxs("div",{children:[e.jsx(Y,{className:"text-base font-semibold flex items-center gap-2",children:"Proposal Document *"}),e.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Detailed proposal with activity details and requested information"}),e.jsxs("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-4 hover:border-blue-500 transition-colors",children:[e.jsx("input",{ref:A,type:"file",accept:".pdf,.doc,.docx",className:"hidden",id:"proposalDoc",onChange:w}),e.jsxs("label",{htmlFor:"proposalDoc",className:"cursor-pointer flex flex-col items-center gap-2",children:[e.jsx(ps,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600",children:o?o.name:"Click to upload proposal (PDF, DOC, DOCX)"})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Cost Breakup"}),e.jsx(ee,{className:"bg-red-500 text-white text-xs",children:"Required"})]}),e.jsxs(R,{type:"button",onClick:M,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white",size:"sm",children:[e.jsx(Is,{className:"w-4 h-4 mr-1"}),"Add Item"]})]}),e.jsx("div",{className:"space-y-3",children:c.map(O=>e.jsxs("div",{className:"flex gap-2 items-start",children:[e.jsx("div",{className:"flex-1",children:e.jsx(je,{placeholder:"Item description (e.g., Banner printing, Event setup)",value:O.description,onChange:L=>_(O.id,"description",L.target.value)})}),e.jsx("div",{className:"w-40",children:e.jsx(je,{type:"number",placeholder:"Amount",min:"0",step:"0.01",value:O.amount||"",onChange:L=>_(O.id,"amount",L.target.value)})}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:"mt-0.5 hover:bg-red-100 hover:text-red-700",onClick:()=>B(O.id),disabled:c.length===1,children:e.jsx(ut,{className:"w-4 h-4"})})]},O.id))}),e.jsx("div",{className:"border-2 border-gray-300 rounded-lg p-4 bg-white",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fs,{className:"w-5 h-5 text-gray-700"}),e.jsx("span",{className:"font-semibold text-gray-900",children:"Estimated Budget"})]}),e.jsxs("div",{className:"text-2xl font-bold text-gray-900",children:["₹",T.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Timeline for Closure"}),e.jsx(ee,{className:"bg-red-500 text-white text-xs",children:"Required"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(R,{type:"button",onClick:()=>u("date"),className:m==="date"?"bg-[#2d4a3e] hover:bg-[#1f3329] text-white":"border-2 hover:bg-gray-50",size:"sm",children:[e.jsx(et,{className:"w-4 h-4 mr-1"}),"Specific Date"]}),e.jsx(R,{type:"button",onClick:()=>u("days"),className:m==="days"?"bg-[#2d4a3e] hover:bg-[#1f3329] text-white":"border-2 hover:bg-gray-50",size:"sm",children:"Number of Days"})]}),m==="date"?e.jsxs("div",{children:[e.jsx(Y,{className:"text-sm font-medium mb-2 block",children:"Expected Completion Date"}),e.jsx(je,{type:"date",min:F,value:h,onChange:O=>p(O.target.value)})]}):e.jsxs("div",{children:[e.jsx(Y,{className:"text-sm font-medium mb-2 block",children:"Number of Days"}),e.jsx(je,{type:"number",placeholder:"Enter number of days",min:"1",value:g,onChange:O=>y(O.target.value)})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Other Supporting Documents"}),e.jsx(ee,{variant:"secondary",className:"text-xs",children:"Optional"})]}),e.jsxs("div",{children:[e.jsx(Y,{className:"flex items-center gap-2 text-base font-semibold",children:"Additional Documents"}),e.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Any other supporting documents (invoices, receipts, photos, etc.)"}),e.jsxs("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-4 hover:border-blue-500 transition-colors",children:[e.jsx("input",{ref:D,type:"file",multiple:!0,className:"hidden",id:"otherDocs",onChange:S}),e.jsxs("label",{htmlFor:"otherDocs",className:"cursor-pointer flex flex-col items-center gap-2",children:[e.jsx(ps,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600",children:"Click to upload additional documents (multiple files allowed)"})]})]}),v.length>0&&e.jsx("div",{className:"mt-2 space-y-1",children:v.map((O,L)=>e.jsxs("div",{className:"flex items-center justify-between bg-gray-50 p-2 rounded text-sm",children:[e.jsx("span",{className:"text-gray-700",children:O.name}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-red-100",onClick:()=>$(L),children:e.jsx(ut,{className:"w-3 h-3"})})]},L))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Y,{htmlFor:"dealerComments",className:"text-base font-semibold flex items-center gap-2",children:"Dealer Comments / Details *"}),e.jsx(os,{id:"dealerComments",placeholder:"Provide detailed comments about this claim request, including any special considerations, execution details, or additional information...",value:f,onChange:O=>j(O.target.value),className:"min-h-[120px]"}),e.jsxs("p",{className:"text-xs text-gray-500",children:[f.length," characters"]})]}),!P&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-4 flex items-start gap-3",children:[e.jsx(Pe,{className:"w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-sm text-amber-800",children:[e.jsx("p",{className:"font-semibold mb-1",children:"Missing Required Information"}),e.jsx("p",{children:"Please ensure proposal document, cost breakup, timeline, and dealer comments are provided before submitting."})]})]})]}),e.jsxs(yt,{className:"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",children:[e.jsx(R,{variant:"outline",onClick:E,disabled:b,className:"border-2",children:"Cancel"}),e.jsx(R,{onClick:k,disabled:!P||b,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white disabled:bg-gray-300 disabled:text-gray-500",children:b?"Submitting...":"Submit Documents"})]})]})})}function Nb({isOpen:t,onClose:s,onApprove:a,onReject:r,proposalData:n,dealerName:i="Dealer",activityName:o="Activity",requestId:l}){const[c,d]=x.useState(""),[m,u]=x.useState(!1),[h,p]=x.useState(null),g=x.useMemo(()=>{if(!(n!=null&&n.costBreakup))return 0;const b=Array.isArray(n.costBreakup)?n.costBreakup:typeof n.costBreakup=="string"?JSON.parse(n.costBreakup):[];return Array.isArray(b)?b.reduce((N,A)=>{const D=typeof A=="object"&&A.amount||0;return N+(Number(D)||0)},0):0},[n]),y=b=>{if(!b)return"—";try{return new Date(b).toLocaleDateString("en-IN",{year:"numeric",month:"long",day:"numeric"})}catch{return b}},v=async()=>{if(!c.trim()){te.error("Please provide approval comments");return}try{u(!0),p("approve"),await a(c),f(),s()}catch(b){console.error("Failed to approve proposal:",b),te.error("Failed to approve proposal. Please try again.")}finally{u(!1),p(null)}},C=async()=>{if(!c.trim()){te.error("Please provide rejection reason");return}try{u(!0),p("reject"),await r(c),f(),s()}catch(b){console.error("Failed to reject proposal:",b),te.error("Failed to reject proposal. Please try again.")}finally{u(!1),p(null)}},f=()=>{d(""),p(null)},j=()=>{m||(f(),s())};return t?e.jsx(nt,{open:t,onOpenChange:j,children:e.jsxs(at,{className:"max-w-4xl max-h-[90vh] flex flex-col p-0 overflow-hidden",children:[e.jsxs(it,{className:"px-6 pt-6 pb-4 flex-shrink-0 border-b",children:[e.jsxs(rt,{className:"flex items-center gap-2 text-2xl",children:[e.jsx(Ce,{className:"w-6 h-6 text-green-600"}),"Requestor Evaluation & Confirmation"]}),e.jsx(Ht,{className:"text-base",children:"Step 2: Review dealer proposal and make a decision"}),e.jsxs("div",{className:"space-y-1 mt-2 text-sm text-gray-600",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Dealer:"})," ",i]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Activity:"})," ",o]}),e.jsxs("div",{className:"mt-2 text-amber-600 font-medium",children:["Decision: ",e.jsx("strong",{children:"Confirms?"})," (YES → Continue to Dept Lead / NO → Request is cancelled)"]})]})]}),e.jsxs("div",{className:"space-y-6 py-4 px-6 overflow-y-auto flex-1",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("h3",{className:"font-semibold text-lg flex items-center gap-2",children:[e.jsx(Re,{className:"w-5 h-5 text-blue-600"}),"Proposal Document"]})}),n!=null&&n.proposalDocument?e.jsxs("div",{className:"border rounded-lg p-4 bg-gray-50 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Re,{className:"w-8 h-8 text-blue-600"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:n.proposalDocument.name}),(n==null?void 0:n.submittedAt)&&e.jsxs("p",{className:"text-xs text-gray-500",children:["Submitted on ",y(n.submittedAt)]})]})]}),e.jsx("div",{className:"flex gap-2",children:n.proposalDocument.url&&e.jsxs(e.Fragment,{children:[e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>{var b;return window.open((b=n.proposalDocument)==null?void 0:b.url,"_blank")},children:[e.jsx(zt,{className:"w-4 h-4 mr-1"}),"View"]}),e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>{var N,A;const b=document.createElement("a");b.href=((N=n.proposalDocument)==null?void 0:N.url)||"",b.download=((A=n.proposalDocument)==null?void 0:A.name)||"",b.click()},children:[e.jsx(Qt,{className:"w-4 h-4 mr-1"}),"Download"]})]})})]}):e.jsx("p",{className:"text-sm text-gray-500 italic",children:"No proposal document available"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("h3",{className:"font-semibold text-lg flex items-center gap-2",children:[e.jsx(Fs,{className:"w-5 h-5 text-green-600"}),"Cost Breakup"]})}),(()=>{const b=n!=null&&n.costBreakup?Array.isArray(n.costBreakup)?n.costBreakup:typeof n.costBreakup=="string"?JSON.parse(n.costBreakup):[]:[];return b&&Array.isArray(b)&&b.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsx("div",{className:"bg-gray-50 px-4 py-2 border-b",children:e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm font-semibold text-gray-700",children:[e.jsx("div",{children:"Item Description"}),e.jsx("div",{className:"text-right",children:"Amount"})]})}),e.jsx("div",{className:"divide-y",children:b.map((N,A)=>e.jsxs("div",{className:"px-4 py-3 grid grid-cols-2 gap-4",children:[e.jsx("div",{className:"text-sm text-gray-700",children:(N==null?void 0:N.description)||"N/A"}),e.jsxs("div",{className:"text-sm font-semibold text-gray-900 text-right",children:["₹",(Number(N==null?void 0:N.amount)||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]},(N==null?void 0:N.id)||(N==null?void 0:N.description)||A))})]}),e.jsx("div",{className:"border-2 border-[--re-green] rounded-lg p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fs,{className:"w-5 h-5 text-[--re-green]"}),e.jsx("span",{className:"font-semibold text-gray-700",children:"Total Estimated Budget"})]}),e.jsxs("div",{className:"text-2xl font-bold text-[--re-green]",children:["₹",g.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})})]}):e.jsx("p",{className:"text-sm text-gray-500 italic",children:"No cost breakdown available"})})()]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("h3",{className:"font-semibold text-lg flex items-center gap-2",children:[e.jsx(et,{className:"w-5 h-5 text-purple-600"}),"Expected Completion Date"]})}),e.jsx("div",{className:"border rounded-lg p-4 bg-gray-50",children:e.jsx("p",{className:"text-lg font-semibold text-gray-900",children:n!=null&&n.expectedCompletionDate?y(n.expectedCompletionDate):"Not specified"})})]}),(n==null?void 0:n.otherDocuments)&&n.otherDocuments.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("h3",{className:"font-semibold text-lg flex items-center gap-2",children:[e.jsx(Re,{className:"w-5 h-5 text-gray-600"}),"Other Supporting Documents"]}),e.jsxs(ee,{variant:"secondary",className:"text-xs",children:[n.otherDocuments.length," file(s)"]})]}),e.jsx("div",{className:"space-y-2",children:n.otherDocuments.map((b,N)=>e.jsxs("div",{className:"border rounded-lg p-3 bg-gray-50 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Re,{className:"w-5 h-5 text-gray-600"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:b.name})]}),b.url&&e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>window.open(b.url,"_blank"),children:e.jsx(Qt,{className:"w-4 h-4"})})]},N))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("h3",{className:"font-semibold text-lg flex items-center gap-2",children:[e.jsx(Ds,{className:"w-5 h-5 text-blue-600"}),"Dealer Comments"]})}),e.jsx("div",{className:"border rounded-lg p-4 bg-gray-50",children:e.jsx("p",{className:"text-sm text-gray-700 whitespace-pre-wrap",children:(n==null?void 0:n.dealerComments)||"No comments provided"})})]}),e.jsxs("div",{className:"space-y-3 border-t pt-4",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Your Decision & Comments"}),e.jsx(os,{placeholder:"Provide your evaluation comments, approval conditions, or rejection reasons...",value:c,onChange:b=>d(b.target.value),className:"min-h-[120px]"}),e.jsxs("p",{className:"text-xs text-gray-500",children:[c.length," characters"]})]}),!c.trim()&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-3 flex items-start gap-2",children:[e.jsx(ht,{className:"w-4 h-4 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-sm text-amber-800",children:"Please provide comments before making a decision. Comments are required and will be visible to all participants."})]})]}),e.jsxs(yt,{className:"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end px-6 pb-6 pt-4 flex-shrink-0 border-t bg-gray-50",children:[e.jsx(R,{variant:"outline",onClick:j,disabled:m,className:"border-2",children:"Cancel"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(R,{onClick:C,disabled:!c.trim()||m,variant:"destructive",className:"bg-red-600 hover:bg-red-700",children:m&&h==="reject"?"Rejecting...":e.jsxs(e.Fragment,{children:[e.jsx(ht,{className:"w-4 h-4 mr-2"}),"Reject (Cancel Request)"]})}),e.jsx(R,{onClick:v,disabled:!c.trim()||m,className:"bg-green-600 hover:bg-green-700 text-white",children:m&&h==="approve"?"Approving...":e.jsxs(e.Fragment,{children:[e.jsx(Ce,{className:"w-4 h-4 mr-2"}),"Approve (Continue to Dept Lead)"]})})]})]})]})}):null}function wb({isOpen:t,onClose:s,onApprove:a,onReject:r,requestTitle:n,requestId:i}){const[o,l]=x.useState("approve"),[c,d]=x.useState(""),[m,u]=x.useState(""),[h,p]=x.useState(""),[g,y]=x.useState(!1),v=m.length,C=h.length,f=300,j=500,b=x.useMemo(()=>(o==="reject"||c.trim().length>0&&m.trim().length>0)&&h.trim().length>0,[o,c,m,h]),N=async()=>{if(!b){if(o==="approve"){if(!c.trim()){te.error("Please enter IO number");return}if(!m.trim()){te.error("Please enter IO remark");return}}if(!h.trim()){te.error("Please provide comments");return}return}try{y(!0),o==="approve"?await a({ioNumber:c.trim(),ioRemark:m.trim(),comments:h.trim()}):await r(h.trim()),A(),s()}catch(T){console.error(`Failed to ${o} request:`,T),te.error(`Failed to ${o} request. Please try again.`)}finally{y(!1)}},A=()=>{l("approve"),d(""),u(""),p("")},D=()=>{g||(A(),s())};return e.jsx(nt,{open:t,onOpenChange:D,children:e.jsxs(at,{className:"max-w-2xl",children:[e.jsxs(it,{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"p-2 rounded-lg bg-green-100",children:e.jsx(Ce,{className:"w-6 h-6 text-green-600"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(rt,{className:"font-semibold text-xl",children:"Approve and Organise IO"}),e.jsx(Ht,{className:"text-sm mt-1",children:"Enter blocked IO details and provide your approval comments"})]})]}),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:"Workflow Step:"}),e.jsx(ee,{variant:"outline",className:"font-mono",children:"Step 3"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-gray-900",children:"Title:"}),e.jsx("p",{className:"text-gray-700 mt-1",children:n||"—"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-gray-900",children:"Action:"}),e.jsxs(ee,{className:"bg-green-100 text-green-800 border-green-200",children:[e.jsx(Ce,{className:"w-3 h-3 mr-1"}),"APPROVE"]})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex gap-2 p-1 bg-gray-100 rounded-lg",children:[e.jsxs(R,{type:"button",onClick:()=>l("approve"),className:`flex-1 ${o==="approve"?"bg-green-600 text-white shadow-sm":"text-gray-700 hover:bg-gray-200"}`,variant:o==="approve"?"default":"ghost",children:[e.jsx(Ce,{className:"w-4 h-4 mr-1"}),"Approve"]}),e.jsxs(R,{type:"button",onClick:()=>l("reject"),className:`flex-1 ${o==="reject"?"bg-red-600 text-white shadow-sm":"text-gray-700 hover:bg-gray-200"}`,variant:o==="reject"?"destructive":"ghost",children:[e.jsx(ht,{className:"w-4 h-4 mr-1"}),"Reject"]})]}),o==="approve"&&e.jsxs("div",{className:"p-3 bg-blue-50 border border-blue-200 rounded-lg space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(hs,{className:"w-4 h-4 text-blue-600"}),e.jsx("h4",{className:"font-semibold text-blue-900",children:"IO Organisation Details"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(Y,{htmlFor:"ioNumber",className:"text-sm font-semibold text-gray-900 flex items-center gap-2",children:["Blocked IO Number ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(je,{id:"ioNumber",placeholder:"Enter IO number from SAP",value:c,onChange:T=>d(T.target.value),className:"bg-white h-8"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(Y,{htmlFor:"ioRemark",className:"text-sm font-semibold text-gray-900 flex items-center gap-2",children:["IO Remark ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(os,{id:"ioRemark",placeholder:"Enter remarks about IO blocking",value:m,onChange:T=>{const P=T.target.value;P.length<=f&&u(P)},rows:2,className:"bg-white text-sm min-h-[60px] resize-none"}),e.jsx("div",{className:"flex justify-end text-xs text-gray-600",children:e.jsxs("span",{children:[v,"/",f]})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(Y,{htmlFor:"comment",className:"text-sm font-semibold text-gray-900 flex items-center gap-2",children:["Comments & Remarks ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(os,{id:"comment",placeholder:o==="approve"?"Enter your approval comments and any conditions or notes...":"Enter detailed reasons for rejection...",value:h,onChange:T=>{const P=T.target.value;P.length<=j&&p(P)},rows:4,className:"text-sm min-h-[80px] resize-none"}),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(Cs,{className:"w-3 h-3"}),"Required and visible to all"]}),e.jsxs("span",{children:[C,"/",j]})]})]})]}),e.jsxs(yt,{className:"flex flex-col-reverse sm:flex-row sm:justify-end gap-2",children:[e.jsx(R,{variant:"outline",onClick:D,disabled:g,children:"Cancel"}),e.jsx(R,{onClick:N,disabled:!b||g,className:`${o==="approve"?"bg-green-600 hover:bg-green-700":"bg-red-600 hover:bg-red-700"} text-white`,children:g?`${o==="approve"?"Approving":"Rejecting"}...`:e.jsxs(e.Fragment,{children:[e.jsx(Ce,{className:"w-4 h-4 mr-2"}),o==="approve"?"Approve Request":"Reject Request"]})})]})]})})}function Cb({isOpen:t,onClose:s,onSubmit:a,dealerName:r="Jaipur Royal Enfield",activityName:n="Activity",requestId:i}){const[o,l]=x.useState(""),[c,d]=x.useState(""),[m,u]=x.useState([]),[h,p]=x.useState([]),[g,y]=x.useState([]),[v,C]=x.useState([]),[f,j]=x.useState(null),[b,N]=x.useState(""),[A,D]=x.useState(!1),T=x.useRef(null),P=x.useRef(null),w=x.useRef(null),S=x.useRef(null),M=x.useMemo(()=>m.reduce((re,V)=>re+(V.amount||0),0),[m]),B=x.useMemo(()=>{const re=o!=="",V=h.length>0,q=g.length>0,ie=b.trim().length>0;return re&&V&&q&&ie},[o,h,g,b]),_=new Date().toISOString().split("T")[0],$=()=>{u([...m,{id:Date.now().toString(),description:"",amount:0}])},k=(re,V,q)=>{u(m.map(ie=>ie.id===re?{...ie,[V]:q}:ie))},I=re=>{u(m.filter(V=>V.id!==re))},E=re=>{const V=Array.from(re.target.files||[]);if(V.length>0){const q=[".pdf",".doc",".docx",".zip",".rar"];if(V.filter(ue=>!q.some(Te=>ue.name.toLowerCase().endsWith(Te))).length>0){te.error("Please upload PDF, DOC, DOCX, ZIP, or RAR files only");return}p([...h,...V])}},F=re=>{p(h.filter((V,q)=>q!==re))},O=re=>{const V=Array.from(re.target.files||[]);if(V.length>0){if(V.filter(ie=>!ie.type.startsWith("image/")).length>0){te.error("Please upload image files only (JPG, PNG, etc.)");return}y([...g,...V])}},L=re=>{y(g.filter((V,q)=>q!==re))},J=re=>{const V=Array.from(re.target.files||[]);if(V.length>0){const q=[".pdf",".jpg",".jpeg",".png"];if(V.filter(ue=>!q.some(Te=>ue.name.toLowerCase().endsWith(Te))).length>0){te.error("Please upload PDF, JPG, or PNG files only");return}C([...v,...V])}},U=re=>{C(v.filter((V,q)=>q!==re))},oe=re=>{var q,ie;const V=(q=re.target.files)==null?void 0:q[0];if(V){const ue=[".pdf",".xlsx",".xls",".csv"],Te="."+((ie=V.name.split(".").pop())==null?void 0:ie.toLowerCase());if(!ue.includes(Te)){te.error("Please upload PDF, Excel, or CSV files only");return}j(V)}},ge=async()=>{if(!B){te.error("Please fill all required fields");return}const re=m.filter(V=>V.description.trim()!==""&&V.amount>0);try{D(!0),await a({activityCompletionDate:o,numberOfParticipants:c?parseInt(c):void 0,closedExpenses:re,totalClosedExpenses:M,completionDocuments:h,activityPhotos:g,invoicesReceipts:v.length>0?v:void 0,attendanceSheet:f||void 0,completionDescription:b}),G(),s()}catch(V){console.error("Failed to submit completion documents:",V),te.error("Failed to submit completion documents. Please try again.")}finally{D(!1)}},G=()=>{l(""),d(""),u([]),p([]),y([]),C([]),j(null),N(""),T.current&&(T.current.value=""),P.current&&(P.current.value=""),w.current&&(w.current.value=""),S.current&&(S.current.value="")},me=()=>{A||(G(),s())};return e.jsx(nt,{open:t,onOpenChange:me,children:e.jsxs(at,{className:"sm:max-w-lg max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(it,{children:[e.jsxs(rt,{className:"font-semibold flex items-center gap-2 text-2xl",children:[e.jsx(ps,{className:"w-6 h-6 text-[--re-green]"}),"Activity Completion Documents"]}),e.jsx(Ht,{className:"text-base",children:"Step 5: Upload completion proof and final documents"}),e.jsxs("div",{className:"space-y-1 mt-2 text-sm text-gray-600",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Dealer:"})," ",r]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Activity:"})," ",n]}),e.jsx("div",{className:"mt-2",children:"Please upload completion documents, photos, and provide details about the completed activity."})]})]}),e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Y,{className:"text-base font-semibold flex items-center gap-2",htmlFor:"completionDate",children:[e.jsx(et,{className:"w-4 h-4"}),"Activity Completion Date *"]}),e.jsx(je,{type:"date",id:"completionDate",max:_,value:o,onChange:re=>l(re.target.value)})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Closed Expenses"}),e.jsx(ee,{className:"bg-secondary text-secondary-foreground text-xs",children:"Optional"})]}),e.jsxs(R,{type:"button",onClick:$,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white",size:"sm",children:[e.jsx(Is,{className:"w-4 h-4 mr-1"}),"Add Expense"]})]}),e.jsxs("div",{className:"space-y-3",children:[m.map(re=>e.jsxs("div",{className:"flex gap-2 items-start",children:[e.jsx("div",{className:"flex-1",children:e.jsx(je,{placeholder:"Item name (e.g., Venue rental, Refreshments, Printing)",value:re.description,onChange:V=>k(re.id,"description",V.target.value)})}),e.jsx("div",{className:"w-40",children:e.jsx(je,{type:"number",placeholder:"Amount",min:"0",step:"0.01",value:re.amount||"",onChange:V=>k(re.id,"amount",parseFloat(V.target.value)||0)})}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:"mt-0.5 hover:bg-red-100 hover:text-red-700",onClick:()=>I(re.id),children:e.jsx(ut,{className:"w-4 h-4"})})]},re.id)),m.length===0&&e.jsx("p",{className:"text-sm text-gray-500 italic",children:'No expenses added. Click "Add Expense" to add expense items.'}),m.length>0&&M>0&&e.jsx("div",{className:"pt-2 border-t",children:e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"font-semibold",children:"Total Closed Expenses:"}),e.jsxs("span",{className:"font-semibold text-lg",children:["₹",M.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Completion Evidence"}),e.jsx(ee,{className:"bg-destructive text-white text-xs",children:"Required"})]}),e.jsxs("div",{children:[e.jsxs(Y,{className:"text-base font-semibold flex items-center gap-2",children:[e.jsx(Re,{className:"w-4 h-4"}),"Completion Documents *"]}),e.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Upload documents proving activity completion (reports, certificates, etc.) - Can upload multiple files or ZIP folder"}),e.jsxs("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-4 hover:border-blue-500 transition-colors",children:[e.jsx("input",{ref:T,type:"file",multiple:!0,accept:".pdf,.doc,.docx,.zip,.rar",className:"hidden",id:"completionDocs",onChange:E}),e.jsxs("label",{htmlFor:"completionDocs",className:"cursor-pointer flex flex-col items-center gap-2",children:[e.jsx(ps,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600",children:"Click to upload documents (PDF, DOC, ZIP - multiple files allowed)"})]})]}),h.length>0&&e.jsx("div",{className:"mt-2 space-y-1",children:h.map((re,V)=>e.jsxs("div",{className:"flex items-center justify-between bg-gray-50 p-2 rounded text-sm",children:[e.jsx("span",{className:"truncate flex-1",children:re.name}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>F(V),children:e.jsx(ut,{className:"w-3 h-3"})})]},V))})]}),e.jsxs("div",{children:[e.jsxs(Y,{className:"text-base font-semibold flex items-center gap-2",children:[e.jsx(Ti,{className:"w-4 h-4"}),"Activity Photos *"]}),e.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Upload photos from the completed activity (event photos, installations, etc.)"}),e.jsxs("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-4 hover:border-blue-500 transition-colors",children:[e.jsx("input",{ref:P,type:"file",multiple:!0,accept:"image/*",className:"hidden",id:"completionPhotos",onChange:O}),e.jsxs("label",{htmlFor:"completionPhotos",className:"cursor-pointer flex flex-col items-center gap-2",children:[e.jsx(Ti,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600",children:"Click to upload photos (JPG, PNG - multiple files allowed)"})]})]}),g.length>0&&e.jsx("div",{className:"mt-2 space-y-1",children:g.map((re,V)=>e.jsxs("div",{className:"flex items-center justify-between bg-gray-50 p-2 rounded text-sm",children:[e.jsx("span",{className:"truncate flex-1",children:re.name}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>L(V),children:e.jsx(ut,{className:"w-3 h-3"})})]},V))})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Supporting Documents"}),e.jsx(ee,{className:"bg-secondary text-secondary-foreground text-xs",children:"Optional"})]}),e.jsxs("div",{children:[e.jsxs(Y,{className:"text-base font-semibold flex items-center gap-2",children:[e.jsx(hs,{className:"w-4 h-4"}),"Invoices / Receipts"]}),e.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Upload invoices and receipts for expenses incurred"}),e.jsxs("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-4 hover:border-blue-500 transition-colors",children:[e.jsx("input",{ref:w,type:"file",multiple:!0,accept:".pdf,.jpg,.jpeg,.png",className:"hidden",id:"invoiceReceipts",onChange:J}),e.jsxs("label",{htmlFor:"invoiceReceipts",className:"cursor-pointer flex flex-col items-center gap-2",children:[e.jsx(hs,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600",children:"Click to upload invoices/receipts (PDF, JPG, PNG)"})]})]}),v.length>0&&e.jsx("div",{className:"mt-2 space-y-1",children:v.map((re,V)=>e.jsxs("div",{className:"flex items-center justify-between bg-gray-50 p-2 rounded text-sm",children:[e.jsx("span",{className:"truncate flex-1",children:re.name}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>U(V),children:e.jsx(ut,{className:"w-3 h-3"})})]},V))})]}),e.jsxs("div",{children:[e.jsx(Y,{className:"text-base font-semibold",children:"Attendance Sheet / Participant List"}),e.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Upload attendance records or participant lists (if applicable)"}),e.jsxs("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-4 hover:border-blue-500 transition-colors",children:[e.jsx("input",{ref:S,type:"file",accept:".pdf,.xlsx,.xls,.csv",className:"hidden",id:"attendanceDoc",onChange:oe}),e.jsxs("label",{htmlFor:"attendanceDoc",className:"cursor-pointer flex flex-col items-center gap-2",children:[e.jsx(ps,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600",children:"Click to upload attendance sheet (Excel, PDF, CSV)"})]})]}),f&&e.jsxs("div",{className:"mt-2 flex items-center justify-between bg-gray-50 p-2 rounded text-sm",children:[e.jsx("span",{className:"truncate flex-1",children:f.name}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>{j(null),S.current&&(S.current.value="")},children:e.jsx(ut,{className:"w-3 h-3"})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Y,{className:"text-base font-semibold flex items-center gap-2",htmlFor:"completionDescription",children:"Brief Description of Completion *"}),e.jsx(os,{id:"completionDescription",placeholder:"Provide a brief description of the completed activity, including key highlights, outcomes, challenges faced, and any relevant observations...",value:b,onChange:re=>N(re.target.value),className:"min-h-[120px]"}),e.jsxs("p",{className:"text-xs text-gray-500",children:[b.length," characters"]})]}),!B&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-4 flex items-start gap-3",children:[e.jsx(Pe,{className:"w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-sm text-amber-800",children:[e.jsx("p",{className:"font-semibold mb-1",children:"Missing Required Information"}),e.jsx("p",{children:"Please ensure completion date, at least one document/photo, and description are provided before submitting."})]})]})]}),e.jsxs(yt,{className:"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",children:[e.jsx(R,{variant:"outline",onClick:me,disabled:A,className:"border-2",children:"Cancel"}),e.jsx(R,{onClick:ge,disabled:A||!B,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white disabled:bg-gray-300 disabled:text-gray-500",children:A?"Submitting...":"Submit Documents"})]})]})})}function Sb({isOpen:t,onClose:s,onDownload:a,onSendToDealer:r,creditNoteData:n,dealerInfo:i,activityName:o,requestNumber:l,requestId:c,dueDate:d}){const[m,u]=x.useState(!1),[h,p]=x.useState(!1),g=(n==null?void 0:n.creditNoteNumber)||"CN-RE-REQ-2024-CM-101-312580",y=n!=null&&n.creditNoteDate?Yt(n.creditNoteDate,{includeTime:!1,format:"short"}):"Dec 5, 2025",v=(n==null?void 0:n.creditNoteAmount)||800,C=(n==null?void 0:n.status)||"APPROVED",f=(i==null?void 0:i.dealerName)||"Jaipur Royal Enfield",j=(i==null?void 0:i.dealerCode)||"RE-JP-009",b=o||"Activity",N=l||"RE-REQ-2024-CM-101",A=d?Yt(d,{includeTime:!1,format:"short"}):"Jan 4, 2026",D=async()=>{if(a)try{u(!0),await a(),te.success("Credit note downloaded successfully")}catch(w){console.error("Failed to download credit note:",w),te.error("Failed to download credit note. Please try again.")}finally{u(!1)}else te.info("Credit note will be automatically saved to Documents tab")},T=async()=>{if(r)try{p(!0),await r(),te.success("Credit note sent to dealer successfully"),s()}catch(w){console.error("Failed to send credit note to dealer:",w),te.error("Failed to send credit note. Please try again.")}finally{p(!1)}else te.info("Email notification will be sent to dealer with credit note attachment")},P=w=>`₹${w.toLocaleString("en-IN",{minimumFractionDigits:0,maximumFractionDigits:0})}`;return e.jsx(nt,{open:t,onOpenChange:s,children:e.jsxs(at,{className:"sm:max-w-lg max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(it,{children:[e.jsxs(rt,{className:"font-semibold flex items-center gap-2 text-2xl",children:[e.jsx(hs,{className:"w-6 h-6 text-[--re-green]"}),"Credit Note from SAP"]}),e.jsx(Ht,{className:"text-base",children:"Review and send credit note to dealer"})]}),e.jsxs("div",{className:"space-y-5 py-4",children:[e.jsxs("div",{className:"bg-gradient-to-r from-green-50 to-emerald-50 border-2 border-green-200 rounded-lg p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-green-900 text-xl mb-1",children:"Royal Enfield"}),e.jsx("p",{className:"text-sm text-green-700",children:"Credit Note Document"})]}),e.jsxs(ee,{className:"bg-green-600 text-white px-4 py-2 text-base",children:[e.jsx(Ce,{className:"w-4 h-4 mr-2"}),C==="APPROVED"?"Approved":C==="ISSUED"?"Issued":C==="SENT"?"Sent":"Pending"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 mt-4",children:[e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-green-100",children:[e.jsxs(Y,{className:"font-medium text-xs text-gray-600 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(Ux,{className:"w-3 h-3"}),"Credit Note Number"]}),e.jsx("p",{className:"font-bold text-gray-900 mt-1 text-lg",children:g})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-green-100",children:[e.jsxs(Y,{className:"font-medium text-xs text-gray-600 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(et,{className:"w-3 h-3"}),"Issue Date"]}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:y})]})]})]}),e.jsxs("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-5",children:[e.jsxs(Y,{className:"font-medium text-xs text-gray-600 uppercase tracking-wider flex items-center gap-1 mb-3",children:[e.jsx(Fs,{className:"w-4 h-4"}),"Credit Note Amount"]}),e.jsx("p",{className:"text-4xl font-bold text-blue-700",children:P(v)})]}),e.jsxs("div",{className:"bg-purple-50 border-2 border-purple-200 rounded-lg p-5",children:[e.jsxs("h3",{className:"font-semibold text-purple-900 mb-4 flex items-center gap-2",children:[e.jsx(ho,{className:"w-5 h-5"}),"Dealer Information"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(Y,{className:"flex items-center gap-2 font-medium text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:f})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(Y,{className:"flex items-center gap-2 font-medium text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Code"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:j})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(Y,{className:"flex items-center gap-2 font-medium text-xs text-gray-600 uppercase tracking-wider",children:"Activity"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:b})]})]})]}),e.jsxs("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-4",children:[e.jsxs("h3",{className:"font-semibold text-gray-900 mb-3 flex items-center gap-2",children:[e.jsx(Re,{className:"w-4 h-4"}),"Reference Details"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx(Y,{className:"flex items-center gap-2 font-medium text-xs text-gray-600",children:"Request ID"}),e.jsx("p",{className:"font-medium text-gray-900 mt-1",children:N})]}),e.jsxs("div",{children:[e.jsx(Y,{className:"flex items-center gap-2 font-medium text-xs text-gray-600",children:"Due Date"}),e.jsx("p",{className:"font-medium text-gray-900 mt-1",children:A})]})]})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start gap-3",children:[e.jsx(Re,{className:"w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-sm text-blue-800",children:[e.jsx("p",{className:"font-semibold mb-2",children:"Available Actions"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-xs",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Download:"})," Credit note will be automatically saved to Documents tab"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Send to Dealer:"})," Email notification will be sent to dealer with credit note attachment"]}),e.jsx("li",{children:"All actions will be recorded in activity trail for audit purposes"})]})]})]})]}),e.jsxs(yt,{className:"flex-col-reverse gap-2 sm:flex-row flex items-center justify-between sm:justify-between",children:[e.jsx(R,{variant:"outline",onClick:s,disabled:m||h,className:"border-2",children:"Close"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(R,{variant:"outline",onClick:D,disabled:m||h,className:"border-blue-600 text-blue-600 hover:bg-blue-50",children:[e.jsx(Qt,{className:"w-4 h-4 mr-2"}),m?"Downloading...":"Download"]}),e.jsxs(R,{onClick:T,disabled:m||h,className:"bg-green-600 hover:bg-green-700 text-white shadow-md",children:[e.jsx(Yd,{className:"w-4 h-4 mr-2"}),h?"Sending...":"Send to Dealer"]})]})]})]})})}async function Ab(t){var s;try{const a=await ce.post("/dealer-claims",t);return((s=a.data)==null?void 0:s.data)||a.data}catch(a){throw console.error("[DealerClaimAPI] Error creating claim request:",a),a}}async function Vl(t){var s;try{const a=await ce.get(`/dealer-claims/${t}`);return((s=a.data)==null?void 0:s.data)||a.data}catch(a){throw console.error("[DealerClaimAPI] Error fetching claim details:",a),a}}async function kb(t,s){var a;try{const r=new FormData;s.proposalDocument&&r.append("proposalDocument",s.proposalDocument),s.costBreakup&&r.append("costBreakup",JSON.stringify(s.costBreakup)),s.totalEstimatedBudget!==void 0&&r.append("totalEstimatedBudget",s.totalEstimatedBudget.toString()),s.timelineMode&&r.append("timelineMode",s.timelineMode),s.expectedCompletionDate&&r.append("expectedCompletionDate",s.expectedCompletionDate),s.expectedCompletionDays!==void 0&&r.append("expectedCompletionDays",s.expectedCompletionDays.toString()),s.dealerComments&&r.append("dealerComments",s.dealerComments);const n=await ce.post(`/dealer-claims/${t}/proposal`,r,{headers:{"Content-Type":"multipart/form-data"}});return((a=n.data)==null?void 0:a.data)||n.data}catch(r){throw console.error("[DealerClaimAPI] Error submitting proposal:",r),r}}async function Tb(t,s){var a;try{const r=new FormData;r.append("activityCompletionDate",s.activityCompletionDate),s.numberOfParticipants!==void 0&&r.append("numberOfParticipants",s.numberOfParticipants.toString()),s.closedExpenses&&r.append("closedExpenses",JSON.stringify(s.closedExpenses)),s.totalClosedExpenses!==void 0&&r.append("totalClosedExpenses",s.totalClosedExpenses.toString()),s.completionDocuments&&s.completionDocuments.forEach(i=>{r.append("completionDocuments",i)}),s.activityPhotos&&s.activityPhotos.forEach(i=>{r.append("activityPhotos",i)});const n=await ce.post(`/dealer-claims/${t}/completion`,r,{headers:{"Content-Type":"multipart/form-data"}});return((a=n.data)==null?void 0:a.data)||n.data}catch(r){throw console.error("[DealerClaimAPI] Error submitting completion:",r),r}}async function Qr(t,s){var a;try{const r={ioNumber:s.ioNumber,ioRemark:s.ioRemark||"",availableBalance:s.ioAvailableBalance??0,blockedAmount:s.ioBlockedAmount??0,remainingBalance:s.ioRemainingBalance??0},n=await ce.put(`/dealer-claims/${t}/io`,r);return((a=n.data)==null?void 0:a.data)||n.data}catch(r){throw console.error("Error updating IO details:",r),r}}async function Db(t,s){var a;try{const r=await ce.put(`/dealer-claims/${t}/e-invoice`,s);return((a=r.data)==null?void 0:a.data)||r.data}catch(r){throw console.error("[DealerClaimAPI] Error updating e-invoice:",r),r}}const zr=t=>{if(!t)return"";try{return Yt(t)}catch{try{return new Date(t).toLocaleString("en-IN",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0})}catch{return t}}},Rb=t=>{switch(t){case"approved":return e.jsx(Ce,{className:"w-5 h-5 text-green-600"});case"pending":return e.jsx(Ue,{className:"w-5 h-5 text-blue-600"});case"rejected":return e.jsx(Ce,{className:"w-5 h-5 text-red-600"});default:return e.jsx(Ue,{className:"w-5 h-5 text-gray-400"})}},Pb=t=>{switch(t){case"approved":return"bg-green-100 text-green-800 border-green-200";case"pending":return"bg-purple-100 text-purple-800 border-purple-200";case"rejected":return"bg-red-100 text-red-800 border-red-200";default:return"bg-gray-100 text-gray-800 border-gray-200"}},Eb=(t,s)=>s&&(t==="pending"||t==="in_progress")?"border-purple-500 bg-purple-50 shadow-md":t==="approved"?"border-green-500 bg-green-50":t==="rejected"?"border-red-500 bg-red-50":"border-gray-200 bg-white",Ib=t=>{switch(t){case"approved":return"bg-green-100";case"pending":return"bg-purple-100";case"rejected":return"bg-red-100";default:return"bg-gray-100"}};function Mb({request:t,user:s,isInitiator:a,onSkipApprover:r,onRefresh:n}){var Te,qe,ze,Ze,Ge,He,xt,Q,xe,ot,de,Ee,lt,jt,ct,Ss,Zs,Xs,W,le,z,ye,be,De,ve,Fe,ke,Be,ls,Dt,Je,Ve,tt,Zt,Nt,ga,Js,fa,ya,dt,ar,$r,Ur,rr;const[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([]),[C,f]=x.useState(0);x.useEffect(()=>{(async()=>{if(t!=null&&t.approvalFlow&&t.approvalFlow.length>0){v(t.approvalFlow);return}if(t!=null&&t.id||t!=null&&t.requestId){const Ke=t.id||t.requestId;try{const Ae=await ds(Ke),se=(Ae==null?void 0:Ae.approvalLevels)||(Ae==null?void 0:Ae.approvals)||[];if(se&&se.length>0){const he=se.map(pe=>{var Se;return{step:pe.levelNumber||pe.level_number||0,approver:pe.approverName||pe.approver_name||"",approverEmail:(pe.approverEmail||pe.approver_email||"").toLowerCase(),status:((Se=pe.status)==null?void 0:Se.toLowerCase())||"waiting",tatHours:pe.tatHours||pe.tat_hours||24,elapsedHours:pe.elapsedHours||pe.elapsed_hours,approvedAt:pe.actionDate||pe.action_date,comment:pe.comments||pe.comment,levelId:pe.levelId||pe.level_id}});v(he)}}catch(Ae){console.warn("Failed to load approval flows from API:",Ae)}}})()},[t,C]),x.useEffect(()=>{if(t!=null&&t.id||t!=null&&t.requestId){const K=t.id||t.requestId;(async()=>{try{const Ae=await ds(K),se=(Ae==null?void 0:Ae.approvalLevels)||(Ae==null?void 0:Ae.approvals)||[];if(se&&se.length>0){const he=se.map(pe=>{var Se;return{step:pe.levelNumber||pe.level_number||0,approver:pe.approverName||pe.approver_name||"",approverEmail:(pe.approverEmail||pe.approver_email||"").toLowerCase(),status:((Se=pe.status)==null?void 0:Se.toLowerCase())||"waiting",tatHours:pe.tatHours||pe.tat_hours||24,elapsedHours:pe.elapsedHours||pe.elapsed_hours,approvedAt:pe.actionDate||pe.action_date,comment:pe.comments||pe.comment,levelId:pe.levelId||pe.level_id}});v(he)}}catch(Ae){console.warn("Failed to load approval flows from API:",Ae)}})()}},[t==null?void 0:t.currentStep]);const j=()=>{f(K=>K+1),n==null||n()},b=y.map((K,Ke)=>{var We,_a,Qs,$s;const Ae=["Dealer - Proposal Submission","Requestor Evaluation & Confirmation","Dept Lead Approval","Activity Creation","Dealer - Completion Documents","Requestor - Claim Approval","E-Invoice Generation","Credit Note from SAP"],se=["Dealer submits the proposal for the activity with comments including proposal document with requested details, cost break-up, timeline for closure, and other requests","Requestor evaluates the request and confirms with comments. Decision point: Confirms? (YES → Continue to Dept Lead / NO → Request is cancelled)","Department Lead approval. Decision point: Approved? (YES → Budget is blocked in the respective IO for the activity / NO → More clarification required → Request is cancelled)","Activity is created. Activity confirmation email is auto-triggered to dealer / requestor / Lead. IO confirmation to be made.","Dealer submits the necessary documents upon completion of the activity including document attachments (Zip Folder) and brief description","Requestor approves the claim in full or can modify the amount. If more information is required, can request additional details from dealer.","E-invoice will be generated through DMS.","Got credit note from SAP. Review and send to dealer to complete the claim management process."],he=(We=t==null?void 0:t.approvals)==null?void 0:We.find(Rt=>Rt.levelId===K.levelId);let pe;if(K.step===3){const Rt=(t==null?void 0:t.internalOrder)||(t==null?void 0:t.internal_order);(Rt!=null&&Rt.ioNumber||Rt!=null&&Rt.io_number)&&(pe={ioNumber:Rt.ioNumber||Rt.io_number||"",ioRemark:Rt.ioRemark||Rt.io_remark||"N/A",organizedBy:((_a=Rt.organizer)==null?void 0:_a.displayName)||((Qs=Rt.organizer)==null?void 0:Qs.name)||Rt.organizedBy||K.approver||"N/A",organizedAt:Rt.organizedAt||Rt.organized_at||K.approvedAt||(t==null?void 0:t.updatedAt)||""},console.log("[DealerClaimWorkflowTab] Step 3 IO Details Debug:",{step:K.step,status:K.status,internalOrder:Rt,ioDetails:pe}))}let Se;K.step===6&&(he!=null&&he.dmsDetails?Se={dmsNumber:he.dmsDetails.dmsNumber||"",dmsRemarks:he.dmsDetails.dmsRemarks||"",pushedBy:he.dmsDetails.pushedBy||K.approver,pushedAt:he.dmsDetails.pushedAt||K.approvedAt||""}:t!=null&&t.dmsNumber&&(Se={dmsNumber:t.dmsNumber||"",dmsRemarks:t.dmsRemarks||(($s=t.dmsDetails)==null?void 0:$s.dmsRemarks)||"",pushedBy:K.approver,pushedAt:K.approvedAt||t.updatedAt||""}));let Qe=(K.status||"waiting").toLowerCase();return(Qe==="in-review"||Qe==="in_review"||Qe==="in review")&&(Qe="in_progress"),{step:K.step||Ke+1,title:Ae[Ke]||`Step ${K.step||Ke+1}`,approver:K.approver||"Unknown",description:se[Ke]||K.description||"",tatHours:K.tatHours||24,status:Qe,comment:K.comment||(he==null?void 0:he.comment),approvedAt:K.approvedAt||(he==null?void 0:he.timestamp),elapsedHours:K.elapsedHours,ioDetails:pe,dmsDetails:Se,einvoiceUrl:K.step===7?he==null?void 0:he.einvoiceUrl:void 0,emailTemplateUrl:K.step===4?he==null?void 0:he.emailTemplateUrl:void 0}}),N=(t==null?void 0:t.totalSteps)||8,A=b.find(K=>{var Ae;const Ke=((Ae=K.status)==null?void 0:Ae.toLowerCase())||"";return Ke==="pending"||Ke==="in_progress"||Ke==="in-review"||Ke==="in_review"}),D=A?A.step:(t==null?void 0:t.currentStep)||1,T=((Te=s==null?void 0:s.email)==null?void 0:Te.toLowerCase())||"",P=((qe=t==null?void 0:t.dealerEmail)==null?void 0:qe.toLowerCase())||((Ze=(ze=t==null?void 0:t.dealer)==null?void 0:ze.email)==null?void 0:Ze.toLowerCase())||((He=(Ge=t==null?void 0:t.claimDetails)==null?void 0:Ge.dealerEmail)==null?void 0:He.toLowerCase())||((Q=(xt=t==null?void 0:t.claimDetails)==null?void 0:xt.dealer_email)==null?void 0:Q.toLowerCase())||"",w=P&&T===P,S=y.find(K=>(K.step||K.levelNumber||K.level_number)===D),M=((S==null?void 0:S.approverEmail)||"").toLowerCase(),B=M&&T===M,_=y.find(K=>(K.step||K.levelNumber||K.level_number)===2),$=((_==null?void 0:_.approverEmail)||"").toLowerCase(),k=$&&T===$,I=y.find(K=>(K.step||K.levelNumber||K.level_number)===1),E=((I==null?void 0:I.approverEmail)||"").toLowerCase(),F=E&&T===E,O=y.find(K=>(K.step||K.levelNumber||K.level_number)===3),L=((O==null?void 0:O.approverEmail)||"").toLowerCase(),J=L&&T===L,U=async K=>{var Ke,Ae;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const se=t.id||t.requestId;K.proposalDocument&&await dr(K.proposalDocument,se,"APPROVAL");for(const pe of K.otherDocuments)await dr(pe,se,"SUPPORTING");const he=K.costBreakup.reduce((pe,Se)=>pe+Se.amount,0);await kb(se,{proposalDocument:K.proposalDocument||void 0,costBreakup:K.costBreakup.map(pe=>({description:pe.description,amount:pe.amount})),totalEstimatedBudget:he,expectedCompletionDate:K.expectedCompletionDate,dealerComments:K.dealerComments}),await sa(se,{message:`Dealer submitted proposal with ${K.costBreakup.length} cost items and estimated budget of ₹${he.toLocaleString("en-IN")}. ${K.dealerComments?`Comments: ${K.dealerComments}`:""}`,isPriority:!1},[]),te.success("Proposal submitted successfully"),j()}catch(se){console.error("Failed to submit proposal:",se);const he=((Ae=(Ke=se==null?void 0:se.response)==null?void 0:Ke.data)==null?void 0:Ae.message)||(se==null?void 0:se.message)||"Failed to submit proposal. Please try again.";throw te.error(he),se}},oe=async K=>{var Ke,Ae;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const se=t.id||t.requestId,he=await ds(se),Se=((he==null?void 0:he.approvalLevels)||(he==null?void 0:he.approvals)||[]).find(We=>(We.levelNumber||We.level_number)===2);if(!(Se!=null&&Se.levelId)&&!(Se!=null&&Se.level_id))throw new Error("Step 2 approval level not found");const Qe=Se.levelId||Se.level_id;await Mi(se,Qe,K),await sa(se,{message:`Requestor approved the dealer proposal. ${K?`Comments: ${K}`:"Proceeding to Dept Lead approval."}`,isPriority:!1},[]),te.success("Proposal approved successfully"),j()}catch(se){console.error("Failed to approve proposal:",se);const he=((Ae=(Ke=se==null?void 0:se.response)==null?void 0:Ke.data)==null?void 0:Ae.message)||(se==null?void 0:se.message)||"Failed to approve proposal. Please try again.";throw te.error(he),se}},ge=async K=>{var Ke,Ae;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const se=t.id||t.requestId,he=await ds(se),Se=((he==null?void 0:he.approvalLevels)||(he==null?void 0:he.approvals)||[]).find(We=>(We.levelNumber||We.level_number)===2);if(!(Se!=null&&Se.levelId)&&!(Se!=null&&Se.level_id))throw new Error("Step 2 approval level not found");const Qe=Se.levelId||Se.level_id;await Fi(se,Qe,"Proposal rejected by requestor",K),await sa(se,{message:`Requestor rejected the dealer proposal. Request has been cancelled. ${K?`Reason: ${K}`:""}`,isPriority:!1},[]),te.success("Proposal rejected. Request has been cancelled."),j()}catch(se){console.error("Failed to reject proposal:",se);const he=((Ae=(Ke=se==null?void 0:se.response)==null?void 0:Ke.data)==null?void 0:Ae.message)||(se==null?void 0:se.message)||"Failed to reject proposal. Please try again.";throw te.error(he),se}},G=async K=>{var Ke,Ae;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const se=t.id||t.requestId,he=await ds(se),Se=((he==null?void 0:he.approvalLevels)||(he==null?void 0:he.approvals)||[]).find(We=>(We.levelNumber||We.level_number)===3);if(!(Se!=null&&Se.levelId)&&!(Se!=null&&Se.level_id))throw new Error("Step 3 approval level not found");const Qe=Se.levelId||Se.level_id;await Qr(se,{ioNumber:K.ioNumber,ioRemark:K.ioRemark,ioAvailableBalance:0,ioBlockedAmount:0,ioRemainingBalance:0}),await Mi(se,Qe,K.comments),await sa(se,{message:`Dept Lead approved request and organized IO ${K.ioNumber}. ${K.ioRemark?`IO Remark: ${K.ioRemark}. `:""}${K.comments?`Comments: ${K.comments}`:"Budget will be blocked in SAP."}`,isPriority:!1},[]),te.success("Request approved and IO organized successfully"),j()}catch(se){console.error("Failed to approve and organize IO:",se);const he=((Ae=(Ke=se==null?void 0:se.response)==null?void 0:Ke.data)==null?void 0:Ae.message)||(se==null?void 0:se.message)||"Failed to approve request. Please try again.";throw te.error(he),se}},me=async K=>{var Ke,Ae;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const se=t.id||t.requestId,he=K.closedExpenses.map(pe=>({description:pe.description,amount:pe.amount}));if(await Tb(se,{activityCompletionDate:K.activityCompletionDate,numberOfParticipants:K.numberOfParticipants,closedExpenses:he,totalClosedExpenses:K.totalClosedExpenses,completionDocuments:K.completionDocuments,activityPhotos:K.activityPhotos}),K.invoicesReceipts&&K.invoicesReceipts.length>0)for(const pe of K.invoicesReceipts)await dr(pe,se,"SUPPORTING");K.attendanceSheet&&await dr(K.attendanceSheet,se,"SUPPORTING"),await sa(se,{message:`Dealer submitted completion documents. ${K.completionDescription?`Description: ${K.completionDescription}`:""}${K.totalClosedExpenses>0?` Total closed expenses: ₹${K.totalClosedExpenses.toLocaleString("en-IN")}`:""}`,isPriority:!1},[]),te.success("Completion documents submitted successfully"),j()}catch(se){console.error("Failed to submit completion documents:",se);const he=((Ae=(Ke=se==null?void 0:se.response)==null?void 0:Ke.data)==null?void 0:Ae.message)||(se==null?void 0:se.message)||"Failed to submit completion documents. Please try again.";throw te.error(he),se}},re=async K=>{var Ke,Ae;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const se=t.id||t.requestId,he=await ds(se),Se=((he==null?void 0:he.approvalLevels)||(he==null?void 0:he.approvals)||[]).find(We=>(We.levelNumber||We.level_number)===3);if(!(Se!=null&&Se.levelId)&&!(Se!=null&&Se.level_id))throw new Error("Step 3 approval level not found");const Qe=Se.levelId||Se.level_id;await Fi(se,Qe,"Dept Lead rejected - More clarification required",K),await sa(se,{message:`Dept Lead rejected the request. More clarification required. Request has been cancelled. ${K?`Reason: ${K}`:""}`,isPriority:!1},[]),te.success("Request rejected. Request has been cancelled."),j()}catch(se){console.error("Failed to reject request:",se);const he=((Ae=(Ke=se==null?void 0:se.response)==null?void 0:Ke.data)==null?void 0:Ae.message)||(se==null?void 0:se.message)||"Failed to reject request. Please try again.";throw te.error(he),se}},[V,q]=x.useState(null);x.useEffect(()=>{if(!t){q(null);return}(async()=>{try{const Ke=t.id||t.requestId;if(!Ke){q(null);return}const Ae=await ds(Ke),se=(Ae==null?void 0:Ae.documents)||[],he=t.proposalDetails||(Ae==null?void 0:Ae.proposalDetails)||{},pe=se.find(We=>We.category==="APPROVAL"||We.type==="proposal"||We.documentCategory==="APPROVAL"),Se=se.filter(We=>We.category==="SUPPORTING"||We.type==="supporting"||We.documentCategory==="SUPPORTING");let Qe=he.costBreakup||[];if(typeof Qe=="string")try{Qe=JSON.parse(Qe)}catch(We){console.warn("Failed to parse costBreakup JSON:",We),Qe=[]}Array.isArray(Qe)||(Qe=[]),q({proposalDocument:pe?{name:pe.fileName||pe.file_name||pe.name,id:pe.documentId||pe.document_id||pe.id}:void 0,costBreakup:Qe,expectedCompletionDate:he.expectedCompletionDate||"",otherDocuments:Se.map(We=>({name:We.fileName||We.file_name||We.name,id:We.documentId||We.document_id||We.id})),dealerComments:he.dealerComments||"",submittedAt:he.submittedAt})}catch(Ke){console.warn("Failed to load proposal data:",Ke);const Ae=t.proposalDetails||{};let se=Ae.costBreakup||[];if(typeof se=="string")try{se=JSON.parse(se)}catch(he){console.warn("Failed to parse costBreakup JSON:",he),se=[]}Array.isArray(se)||(se=[]),q({proposalDocument:void 0,costBreakup:se,expectedCompletionDate:Ae.expectedCompletionDate||"",otherDocuments:[],dealerComments:Ae.dealerComments||"",submittedAt:Ae.submittedAt})}})()},[t]);const ie=((xe=t==null?void 0:t.claimDetails)==null?void 0:xe.dealerName)||((ot=t==null?void 0:t.dealerInfo)==null?void 0:ot.name)||"Dealer",ue=((de=t==null?void 0:t.claimDetails)==null?void 0:de.activityName)||((Ee=t==null?void 0:t.activityInfo)==null?void 0:Ee.activityName)||(t==null?void 0:t.title)||"Activity";return e.jsxs(e.Fragment,{children:[e.jsxs(Z,{children:[e.jsx(ae,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(ne,{className:"flex items-center gap-2",children:[e.jsx(Ys,{className:"w-5 h-5 text-purple-600"}),"Claim Management Workflow"]}),e.jsx(we,{className:"mt-2",children:"8-Step approval process for dealer claim management"})]}),e.jsxs(ee,{variant:"outline",className:"font-medium",children:["Step ",D," of ",N]})]})}),e.jsx(X,{children:e.jsx("div",{className:"space-y-4",children:b.map((K,Ke)=>{var he;const Ae=(K.status==="pending"||K.status==="in_progress")&&K.step===D,se=K.status==="approved";return K.step===1&&console.log("[DealerClaimWorkflowTab] Step 1 Debug:",{step:K.step,status:K.status,currentStep:D,isActive:Ae,isDealer:w,isStep1Approver:F,step1ApproverEmail:E,userEmail:T,dealerEmail:P}),K.step===2&&console.log("[DealerClaimWorkflowTab] Step 2 Debug:",{step:K.step,status:K.status,currentStep:D,isActive:Ae,isInitiator:a,isStep2Approver:k,showApprovalModal:l}),K.step===3&&console.log("[DealerClaimWorkflowTab] Step 3 Debug:",{step:K.step,status:K.status,currentStep:D,isActive:Ae,isCurrentApprover:B,isStep3Approver:J,step3ApproverEmail:L,userEmail:T,approverEmail:M}),K.step===5&&console.log("[DealerClaimWorkflowTab] Step 5 Debug:",{step:K.step,status:K.status,currentStep:D,isActive:Ae,isDealer:w,dealerEmail:P,userEmail:T,requestDealerEmail:t==null?void 0:t.dealerEmail,requestClaimDetails:t==null?void 0:t.claimDetails,claimDetailsDealerEmail:(he=t==null?void 0:t.claimDetails)==null?void 0:he.dealerEmail}),e.jsx("div",{className:`relative p-5 rounded-lg border-2 transition-all ${Eb(K.status,Ae)}`,children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:`p-3 rounded-xl ${Ib(K.status)}`,children:Rb(K.status)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsxs("h4",{className:"font-semibold text-gray-900",children:["Step ",K.step,": ",K.title]}),e.jsx(ee,{className:Pb(K.status),children:K.status.toLowerCase()}),K.step===4&&K.emailTemplateUrl&&e.jsx(R,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-blue-100",title:"View email template",onClick:()=>window.open(K.emailTemplateUrl,"_blank"),children:e.jsx(Xa,{className:"w-3.5 h-3.5 text-blue-600"})}),K.step===7&&K.einvoiceUrl&&se&&e.jsx(R,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-green-100",title:"Download E-Invoice",onClick:()=>window.open(K.einvoiceUrl,"_blank"),children:e.jsx(Qt,{className:"w-3.5 h-3.5 text-green-600"})})]}),e.jsx("p",{className:"text-sm text-gray-600",children:K.approver}),e.jsx("p",{className:"text-sm text-gray-500 mt-2 italic",children:K.description})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:["TAT: ",K.tatHours,"h"]}),K.elapsedHours&&e.jsxs("p",{className:"text-xs text-gray-600 font-medium",children:["Elapsed: ",K.elapsedHours,"h"]})]})]}),K.comment&&e.jsx("div",{className:"mt-3 p-3 bg-white rounded-lg border border-gray-200",children:e.jsx("p",{className:"text-sm text-gray-700",children:K.comment})}),K.step===3&&K.status==="approved"&&K.ioDetails&&K.ioDetails.ioNumber&&e.jsxs("div",{className:"mt-3 p-3 bg-blue-50 rounded-lg border border-blue-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(hs,{className:"w-4 h-4 text-blue-600"}),e.jsx("p",{className:"text-xs font-semibold text-blue-900 uppercase tracking-wide",children:"IO Organisation Details"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs text-gray-600",children:"IO Number:"}),e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:K.ioDetails.ioNumber})]}),e.jsxs("div",{className:"pt-1.5 border-t border-blue-100",children:[e.jsx("p",{className:"text-xs text-gray-600 mb-1",children:"IO Remark:"}),e.jsx("p",{className:"text-sm text-gray-900",children:K.ioDetails.ioRemark||"N/A"})]}),e.jsxs("div",{className:"pt-1.5 border-t border-blue-100 text-xs text-gray-500",children:["Organised by ",K.ioDetails.organizedBy||K.approver||"N/A"," on"," ",K.ioDetails.organizedAt?zr(K.ioDetails.organizedAt):K.approvedAt?zr(K.approvedAt):"N/A"]})]})]}),K.step===6&&K.dmsDetails&&K.dmsDetails.dmsNumber&&e.jsxs("div",{className:"mt-3 p-3 bg-purple-50 rounded-lg border border-purple-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(qt,{className:"w-4 h-4 text-purple-600"}),e.jsx("p",{className:"text-xs font-semibold text-purple-900 uppercase tracking-wide",children:"DMS Processing Details"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs text-gray-600",children:"DMS Number:"}),e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:K.dmsDetails.dmsNumber})]}),K.dmsDetails.dmsRemarks&&e.jsxs("div",{className:"pt-1.5 border-t border-purple-100",children:[e.jsx("p",{className:"text-xs text-gray-600 mb-1",children:"DMS Remarks:"}),e.jsx("p",{className:"text-sm text-gray-900",children:K.dmsDetails.dmsRemarks})]}),K.dmsDetails.pushedAt&&e.jsxs("div",{className:"pt-1.5 border-t border-purple-100 text-xs text-gray-500",children:["Pushed by ",K.dmsDetails.pushedBy," on"," ",zr(K.dmsDetails.pushedAt)]})]})]}),Ae&&e.jsxs("div",{className:"mt-4 flex gap-2",children:[K.step===1&&(w||F)&&e.jsxs(R,{className:"bg-purple-600 hover:bg-purple-700",onClick:()=>{console.log("[DealerClaimWorkflowTab] Opening proposal submission modal for Step 1"),o(!0)},children:[e.jsx(ps,{className:"w-4 h-4 mr-2"}),"Submit Proposal"]}),K.step===2&&(a||k)&&e.jsxs(R,{className:"bg-blue-600 hover:bg-blue-700",onClick:()=>{console.log("[DealerClaimWorkflowTab] Opening approval modal for Step 2"),c(!0)},children:[e.jsx(Ce,{className:"w-4 h-4 mr-2"}),"Confirm Request"]}),K.step===3&&(()=>{const pe=y.find(We=>(We.step||We.levelNumber||We.level_number)===3),Se=((pe==null?void 0:pe.approverEmail)||"").toLowerCase();return Se&&T===Se||J||B})()&&e.jsxs(R,{className:"bg-green-600 hover:bg-green-700",onClick:()=>{console.log("[DealerClaimWorkflowTab] Opening IO approval modal for Step 3"),m(!0)},children:[e.jsx(Ce,{className:"w-4 h-4 mr-2"}),"Approve and Organise IO"]}),K.step===5&&w&&e.jsxs(R,{className:"bg-purple-600 hover:bg-purple-700",onClick:()=>{console.log("[DealerClaimWorkflowTab] Opening completion documents modal for Step 5"),h(!0)},children:[e.jsx(ps,{className:"w-4 h-4 mr-2"}),"Upload Completion Docs"]}),K.step===6&&(a||(()=>{const pe=y.find(Qe=>(Qe.step||Qe.levelNumber||Qe.level_number)===6),Se=((pe==null?void 0:pe.approverEmail)||"").toLowerCase();return Se&&T===Se})())&&e.jsxs(R,{className:"bg-indigo-600 hover:bg-indigo-700",onClick:async()=>{var pe,Se;console.log("[DealerClaimWorkflowTab] Pushing to DMS for Step 6");try{const Qe=(t==null?void 0:t.requestId)||(t==null?void 0:t.id);if(!Qe){te.error("Request ID not found");return}const We=new Date().toISOString().slice(0,10);await Db(Qe,{eInvoiceDate:We}),te.success("Pushed to DMS successfully"),j()}catch(Qe){console.error("[DealerClaimWorkflowTab] Error pushing to DMS:",Qe),te.error(((Se=(pe=Qe==null?void 0:Qe.response)==null?void 0:pe.data)==null?void 0:Se.message)||"Failed to push to DMS")}},children:[e.jsx(qt,{className:"w-4 h-4 mr-2"}),"Push to DMS"]}),K.step===8&&(()=>{var Qs;const pe=y.find($s=>($s.step||$s.levelNumber||$s.level_number)===8),Se=((pe==null?void 0:pe.approverEmail)||"").toLowerCase(),Qe=Se&&T===Se,We=((Qs=s==null?void 0:s.role)==null?void 0:Qs.toUpperCase())||"";return Qe||(We==="FINANCE"||We==="ADMIN")})()&&e.jsxs(R,{className:"bg-green-600 hover:bg-green-700",onClick:()=>{console.log("[DealerClaimWorkflowTab] Opening credit note modal for Step 8"),g(!0)},children:[e.jsx(hs,{className:"w-4 h-4 mr-2"}),"View & Send Credit Note"]})]}),K.approvedAt&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Approved on ",zr(K.approvedAt)]})]})]})},Ke)})})})]}),e.jsx(jb,{isOpen:i,onClose:()=>o(!1),onSubmit:U,dealerName:ie,activityName:ue,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId)}),e.jsx(Nb,{isOpen:l,onClose:()=>{console.log("[DealerClaimWorkflowTab] Closing approval modal"),c(!1)},onApprove:oe,onReject:ge,proposalData:V,dealerName:ie,activityName:ue,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId)}),e.jsx(wb,{isOpen:d,onClose:()=>m(!1),onApprove:G,onReject:re,requestTitle:t==null?void 0:t.title,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId)}),e.jsx(Cb,{isOpen:u,onClose:()=>h(!1),onSubmit:me,dealerName:ie,activityName:ue,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId)}),e.jsx(Sb,{isOpen:p,onClose:()=>g(!1),onDownload:async()=>{te.info("Download functionality will be implemented")},onSendToDealer:async()=>{te.info("Send to dealer functionality will be implemented")},creditNoteData:{creditNoteNumber:((lt=t==null?void 0:t.creditNote)==null?void 0:lt.creditNoteNumber)||((jt=t==null?void 0:t.creditNote)==null?void 0:jt.credit_note_number)||((Ss=(ct=t==null?void 0:t.claimDetails)==null?void 0:ct.creditNote)==null?void 0:Ss.creditNoteNumber)||((Zs=t==null?void 0:t.claimDetails)==null?void 0:Zs.creditNoteNumber)||((Xs=t==null?void 0:t.claimDetails)==null?void 0:Xs.credit_note_number),creditNoteDate:((W=t==null?void 0:t.creditNote)==null?void 0:W.creditNoteDate)||((le=t==null?void 0:t.creditNote)==null?void 0:le.credit_note_date)||((ye=(z=t==null?void 0:t.claimDetails)==null?void 0:z.creditNote)==null?void 0:ye.creditNoteDate)||((be=t==null?void 0:t.claimDetails)==null?void 0:be.creditNoteDate)||((De=t==null?void 0:t.claimDetails)==null?void 0:De.credit_note_date),creditNoteAmount:(ve=t==null?void 0:t.creditNote)!=null&&ve.creditNoteAmount?Number((Fe=t==null?void 0:t.creditNote)==null?void 0:Fe.creditNoteAmount):(ke=t==null?void 0:t.creditNote)!=null&&ke.credit_note_amount?Number((Be=t==null?void 0:t.creditNote)==null?void 0:Be.credit_note_amount):(Dt=(ls=t==null?void 0:t.claimDetails)==null?void 0:ls.creditNote)!=null&&Dt.creditNoteAmount?Number((Ve=(Je=t==null?void 0:t.claimDetails)==null?void 0:Je.creditNote)==null?void 0:Ve.creditNoteAmount):(tt=t==null?void 0:t.claimDetails)!=null&&tt.creditNoteAmount?Number((Zt=t==null?void 0:t.claimDetails)==null?void 0:Zt.creditNoteAmount):(Nt=t==null?void 0:t.claimDetails)!=null&&Nt.credit_note_amount?Number((ga=t==null?void 0:t.claimDetails)==null?void 0:ga.credit_note_amount):void 0,status:"APPROVED"},dealerInfo:{dealerName:((Js=t==null?void 0:t.claimDetails)==null?void 0:Js.dealerName)||((fa=t==null?void 0:t.claimDetails)==null?void 0:fa.dealer_name),dealerCode:((ya=t==null?void 0:t.claimDetails)==null?void 0:ya.dealerCode)||((dt=t==null?void 0:t.claimDetails)==null?void 0:dt.dealer_code),dealerEmail:((ar=t==null?void 0:t.claimDetails)==null?void 0:ar.dealerEmail)||(($r=t==null?void 0:t.claimDetails)==null?void 0:$r.dealer_email)},activityName:((Ur=t==null?void 0:t.claimDetails)==null?void 0:Ur.activityName)||((rr=t==null?void 0:t.claimDetails)==null?void 0:rr.activity_name),requestNumber:(t==null?void 0:t.requestNumber)||(t==null?void 0:t.id),requestId:(t==null?void 0:t.requestId)||(t==null?void 0:t.id),dueDate:t==null?void 0:t.dueDate})]})}const Fb=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 zl({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(Re,{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 ",Yt(t.uploadedAt)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&Fb(t.fileType)&&s&&e.jsx(R,{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(zt,{className:"w-4 h-4"})}),a&&e.jsx(R,{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(Qt,{className:"w-4 h-4"})})]})]})}function _b({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(Z,{children:[e.jsx(ae,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-4",children:[e.jsxs("div",{children:[e.jsxs(ne,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Re,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Documents"]}),e.jsx(we,{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(R,{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(ps,{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(X,{children:t.documents&&t.documents.length>0?e.jsx("div",{className:"space-y-3",children:t.documents.map((l,c)=>e.jsx(zl,{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(Z,{children:[e.jsxs(ae,{children:[e.jsxs(ne,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Ds,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"Work Note Attachments"]}),e.jsx(we,{className:"text-xs sm:text-sm",children:"Files shared in work notes discussions"})]}),e.jsx(X,{children:s&&s.length>0?e.jsx("div",{className:"space-y-3",children:s.map((l,c)=>e.jsx(zl,{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 Lb({request:t}){return e.jsxs(Z,{children:[e.jsxs(ae,{children:[e.jsxs(ne,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(qt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Activity Timeline"]}),e.jsx(we,{className:"text-xs sm:text-sm",children:"Complete audit trail of all request activities"})]}),e.jsx(X,{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:Yy(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:Yt(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(qt,{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 Co({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 M=a;a.startsWith("/")&&!a.startsWith("//")&&(M=`${window.location.origin}${a}`);const _=await fetch(M,{headers:{Accept:j?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!_.ok){const I=await _.text().catch(()=>"");throw new Error(`Failed to load file: ${_.status} ${_.statusText}. ${I}`)}const $=await _.blob();if($.size===0)throw new Error("File is empty or could not be loaded");j&&!$.type.includes("pdf")&&$.type!=="application/octet-stream"&&console.warn(`Expected PDF but got ${$.type}`);const k=window.URL.createObjectURL($);p(k)}catch(w){console.error("Failed to load file for preview:",w),C(w instanceof Error?w.message:"Failed to load file for preview")}finally{y(!1)}})(),()=>{h&&(window.URL.revokeObjectURL(h),p(null))}},[o,a,b,j]);const N=async()=>{if(i&&n)try{await i(n)}catch{alert("Failed to download file")}},A=()=>d(P=>Math.min(P+25,200)),D=()=>d(P=>Math.max(P-25,50)),T=()=>u(P=>(P+90)%360);return e.jsx(nt,{open:o,onOpenChange:l,children:e.jsx(at,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(it,{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(zt,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(rt,{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(R,{variant:"ghost",size:"sm",onClick:D,disabled:c<=50,title:"Zoom out",className:"h-8 w-8 p-0",children:e.jsx(Bx,{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(R,{variant:"ghost",size:"sm",onClick:A,disabled:c>=200,title:"Zoom in",className:"h-8 w-8 p-0",children:e.jsx(Vx,{className:"h-4 w-4"})}),e.jsx(R,{variant:"ghost",size:"sm",onClick:T,title:"Rotate",className:"h-8 w-8 p-0",children:e.jsx(zx,{className:"h-4 w-4"})})]}),i&&n&&e.jsxs(R,{variant:"outline",size:"sm",onClick:N,className:"gap-2 h-9",children:[e.jsx(Qt,{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(Xe,{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(ut,{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(R,{onClick:N,className:"gap-2",children:[e.jsx(Qt,{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(zt,{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(R,{onClick:N,className:"gap-2",children:[e.jsx(Qt,{className:"h-4 w-4"}),"Download ",t]})]})})]})})})}function Om({open:t,onClose:s,success:a,title:r,message:n}){return e.jsx(nt,{open:t,onOpenChange:s,children:e.jsxs(at,{className:"sm:max-w-md",children:[e.jsx(it,{children:e.jsxs(rt,{className:"flex items-center gap-2",children:[a?e.jsx(Ce,{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(Ce,{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(ht,{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(yt,{children:e.jsx(R,{onClick:s,className:`w-full ${a?"bg-green-600 hover:bg-green-700":"bg-gray-600 hover:bg-gray-700"}`,children:"OK"})})]})})}function $m({open:t,onClose:s,violations:a,policyDetails:r}){return e.jsx(nt,{open:t,onOpenChange:s,children:e.jsxs(at,{className:"sm:max-w-lg",children:[e.jsxs(it,{children:[e.jsxs(rt,{className:"flex items-center gap-2",children:[e.jsx(Pe,{className:"w-5 h-5 text-red-600"}),"Policy Violation"]}),e.jsx(Ht,{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(yt,{children:e.jsx(R,{onClick:s,className:"w-full sm:w-auto",children:"OK"})})]})})}function Um({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,N]=x.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20});x.useEffect(()=>{t&&(async()=>{var S;try{const M=await Pa("WORKFLOW_SHARING"),B=await Pa("TAT_SETTINGS"),_=[...M,...B],$={};_.forEach(k=>{$[k.configKey]=k.configValue}),N({maxApprovalLevels:parseInt($.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt($.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((S=$.ALLOW_ADD_SPECTATOR)==null?void 0:S.toLowerCase())==="true",maxSpectators:parseInt($.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(M){console.error("Failed to load system policy:",M)}})()},[t]);const A=async()=>{var I,E;const w=n.trim().toLowerCase();if(!w){C({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(w)){C({open:!0,type:"error",email:w,message:"Please enter a valid email address"});return}const M=r.find(F=>(F.email||"").toLowerCase()===w);if(M){const F=((I=M.participantType)==null?void 0:I.toUpperCase())||"PARTICIPANT",O=M.name||w;if(F==="INITIATOR"){C({open:!0,type:"error",email:w,message:`${O} is the request initiator and cannot be added as a spectator.`});return}else if(F==="APPROVER"){C({open:!0,type:"error",email:w,message:`${O} is already an approver on this request and cannot be added as a spectator.`});return}else if(F==="SPECTATOR"){C({open:!0,type:"error",email:w,message:`${O} is already a spectator on this request.`});return}else{C({open:!0,type:"error",email:w,message:`${O} is already a participant on this request.`});return}}const B=[];b.allowSpectators||B.push({type:"Spectators Not Allowed",message:"Adding spectators is not allowed by system policy."});const $=r.filter(F=>(F.participantType||"").toUpperCase()==="SPECTATOR").length;$>=b.maxSpectators&&B.push({type:"Maximum Spectators Exceeded",message:"This request has reached the maximum number of spectators allowed.",currentValue:$,maxValue:b.maxSpectators});const k=r.length+1;if(k>b.maxParticipants&&B.push({type:"Maximum Participants Exceeded",message:"Adding this spectator would exceed the maximum participants limit.",currentValue:k,maxValue:b.maxParticipants}),B.length>0){j({open:!0,violations:B});return}if(!h||h.email.toLowerCase()!==w)try{const O=((E=(await Os(w,1)).data)==null?void 0:E.data)||[];if(O.length===0){C({open:!0,type:"not-found",email:w,message:""});return}const L=O[0];await Ws({userId:L.userId,email:L.email,displayName:L.displayName,firstName:L.firstName,lastName:L.lastName,department:L.department,phone:L.phone,mobilePhone:L.mobilePhone,designation:L.designation,jobTitle:L.jobTitle,manager:L.manager,employeeId:L.employeeId,employeeNumber:L.employeeNumber,secondEmail:L.secondEmail,location:L.location})}catch(F){console.error("Failed to validate spectator:",F),C({open:!0,type:"error",email:w,message:"Failed to validate user. Please try again."});return}try{l(!0),await a(w),i(""),p(null),s()}catch(F){console.error("Failed to add spectator:",F)}finally{l(!1)}},D=()=>{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 T=w=>{if(i(w),h&&h.email.toLowerCase()!==w.toLowerCase()&&p(null),g.current&&clearTimeout(g.current),!w||!w.startsWith("@")||w.length<2){d([]),u(!1);return}u(!0),g.current=setTimeout(async()=>{var S;try{const M=w.slice(1),_=((S=(await Os(M,10)).data)==null?void 0:S.data)||[];d(_)}catch(M){console.error("Search failed:",M),d([])}finally{u(!1)}},300)},P=async w=>{try{await Ws({userId:w.userId,email:w.email,displayName:w.displayName,firstName:w.firstName,lastName:w.lastName,department:w.department,phone:w.phone,mobilePhone:w.mobilePhone,designation:w.designation,jobTitle:w.jobTitle,manager:w.manager,employeeId:w.employeeId,employeeNumber:w.employeeNumber,secondEmail:w.secondEmail,location:w.location}),i(w.email),p(w),d([]),u(!1)}catch(S){console.error("Failed to ensure user exists:",S),C({open:!0,type:"error",email:w.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(nt,{open:t,onOpenChange:D,children:[e.jsxs(at,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:D,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:o,children:[e.jsx(ut,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(it,{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(zt,{className:"w-5 h-5 text-purple-600"})}),e.jsx(rt,{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(po,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(je,{type:"text",placeholder:"@username or user@example.com",value:n,onChange:w=>T(w.target.value),className:"pl-10 h-11 border-gray-300",disabled:o,autoFocus:!0}),(m||c.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg max-h-60 overflow-auto",children:m?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):c.length>0?e.jsx("ul",{className:"divide-y",children:c.map(w=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>P(w),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx($t,{className:"h-8 w-8",children:e.jsx(Ut,{className:"bg-purple-100 text-purple-800 text-xs font-semibold",children:(w.displayName||w.email).split(" ").map(S=>S[0]).join("").slice(0,2).toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:w.displayName||[w.firstName,w.lastName].filter(Boolean).join(" ")||w.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:w.email}),w.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:w.designation})]})]})},w.userId))}):null})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Type ",e.jsx("span",{className:"font-semibold",children:"@username"})," to search for users, or enter email directly."]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(R,{type:"button",variant:"outline",onClick:D,className:"flex-1 h-11 border-gray-300",disabled:o,children:"Cancel"}),e.jsxs(R,{type:"button",onClick:A,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:o||!n.trim(),children:[e.jsx(zt,{className:"w-4 h-4 mr-2"}),o?"Adding...":"Add Spectator"]})]})]}),e.jsx(nt,{open:v.open,onOpenChange:w=>C(S=>({...S,open:w})),children:e.jsxs(at,{className:"sm:max-w-md",children:[e.jsxs(it,{children:[e.jsx(rt,{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(Ht,{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(vn,{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(yt,{children:e.jsx(R,{onClick:()=>C(w=>({...w,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx($m,{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 Bm({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),[N,A]=x.useState({open:!1,type:"error",email:"",message:""}),D=n.filter(k=>k&&(k.status==="approved"||k.status==="rejected"||k.status==="skipped")),T=Math.max(1,D.length+1),P=Math.max(1,n.length+1),w=P>=T?Array.from({length:P-T+1},(k,I)=>T+I):[T];x.useEffect(()=>{w.length>0&&d===null&&m(w[0]||null)},[w.length,d]);const S=async()=>{var F,O;const k=i.trim().toLowerCase();if(!k){A({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(k)){A({open:!0,type:"error",email:k,message:"Please enter a valid email address"});return}if(!l||l<=0){A({open:!0,type:"error",email:"",message:"Please enter valid TAT hours (minimum 1 hour)"});return}if(l>720){A({open:!0,type:"error",email:"",message:"TAT hours cannot exceed 720 hours (30 days)"});return}if(!d){A({open:!0,type:"error",email:"",message:"Please select an approval level"});return}if(d<T){A({open:!0,type:"error",email:"",message:`Cannot add approver at level ${d}. Minimum allowed level is ${T} (after completed levels)`});return}const E=r.find(L=>(L.email||"").toLowerCase()===k);if(E){const L=((F=E.participantType)==null?void 0:F.toUpperCase())||"PARTICIPANT",J=E.name||k;if(L==="INITIATOR"){A({open:!0,type:"error",email:k,message:`${J} is the request initiator and cannot be added as an approver.`});return}else if(L==="APPROVER"){A({open:!0,type:"error",email:k,message:`${J} is already an approver on this request.`});return}else if(L==="SPECTATOR"){A({open:!0,type:"error",email:k,message:`${J} is currently a spectator on this request and cannot be added as an approver. Please remove them as spectator first.`});return}else{A({open:!0,type:"error",email:k,message:`${J} is already a participant on this request.`});return}}if(!C||C.email.toLowerCase()!==k)try{const J=((O=(await Os(k,1)).data)==null?void 0:O.data)||[];if(J.length===0){A({open:!0,type:"not-found",email:k,message:""});return}const U=J[0];await Ws({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})}catch(L){console.error("Failed to validate approver:",L),A({open:!0,type:"error",email:k,message:"Failed to validate user. Please try again."});return}try{h(!0),await a(k,l,d),o(""),c(24),m(null),f(null),s()}catch(L){console.error("Failed to add approver:",L)}finally{h(!1)}},M=()=>{u||(o(""),c(24),m(null),f(null),g([]),v(!1),s())},B=k=>{const I=k.toLowerCase();return I==="approved"?e.jsx(Ce,{className:"w-4 h-4 text-green-600"}):I==="rejected"?e.jsx(ht,{className:"w-4 h-4 text-red-600"}):I==="skipped"?e.jsx(Pe,{className:"w-4 h-4 text-orange-600"}):I==="in-review"||I==="pending"?e.jsx(Ue,{className:"w-4 h-4 text-blue-600"}):e.jsx(Ue,{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 _=k=>{if(o(k),C&&C.email.toLowerCase()!==k.toLowerCase()&&f(null),j.current&&clearTimeout(j.current),!k||!k.startsWith("@")||k.length<2){g([]),v(!1);return}v(!0),j.current=setTimeout(async()=>{var I;try{const E=k.slice(1),O=((I=(await Os(E,10)).data)==null?void 0:I.data)||[];g(O)}catch(E){console.error("Search failed:",E),g([])}finally{v(!1)}},300)},$=async k=>{try{await Ws({userId:k.userId,email:k.email,displayName:k.displayName,firstName:k.firstName,lastName:k.lastName,department:k.department,phone:k.phone,mobilePhone:k.mobilePhone,designation:k.designation,jobTitle:k.jobTitle,manager:k.manager,employeeId:k.employeeId,employeeNumber:k.employeeNumber,secondEmail:k.secondEmail,location:k.location}),o(k.email),f(k),g([]),v(!1)}catch(I){console.error("Failed to ensure user exists:",I),A({open:!0,type:"error",email:k.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(nt,{open:t,onOpenChange:M,children:[e.jsxs(at,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:M,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(ut,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(it,{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(Ct,{className:"w-5 h-5 text-blue-600"})}),e.jsx(rt,{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(Y,{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(k=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-md ${k.status==="approved"?"bg-green-100 border border-green-200":k.status==="rejected"?"bg-red-100 border border-red-200":k.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:k.levelNumber}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:k.approverName}),e.jsxs("p",{className:"text-xs text-gray-500",children:[k.tatHours,"h TAT"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[B(k.status),e.jsx(ee,{variant:"outline",className:`text-xs ${k.status==="approved"?"bg-green-50 text-green-700 border-green-300":k.status==="rejected"?"bg-red-50 text-red-700 border-red-300":k.status==="skipped"?"bg-orange-50 text-orange-700 border-orange-300":"bg-blue-50 text-blue-700 border-blue-300"}`,children:k.status})]})]},k.levelNumber))}),e.jsxs("p",{className:"text-xs text-gray-500",children:["ℹ️ New approver can only be added at level ",T," or higher (after completed levels)"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Y,{className:"text-sm font-medium text-gray-700",children:"Approval Level *"}),e.jsxs(_e,{value:(d==null?void 0:d.toString())||"",onValueChange:k=>m(Number(k)),disabled:u,children:[e.jsx(Oe,{className:"h-11 border-gray-300",children:e.jsx(Le,{placeholder:"Select level"})}),e.jsx($e,{children:w.map(k=>e.jsx(H,{value:k.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ss,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Level ",k]}),k<=n.length&&e.jsxs("span",{className:"text-xs text-gray-500",children:["(will shift existing Level ",k,")"]})]})},k))})]}),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(Y,{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(je,{type:"number",min:"1",max:"720",value:l,onChange:k=>c(Number(k.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(Ue,{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(po,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(je,{type:"text",placeholder:"@username or user@example.com",value:i,onChange:k=>_(k.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(k=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>$(k),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx($t,{className:"h-8 w-8",children:e.jsx(Ut,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:(k.displayName||k.email).split(" ").map(I=>I[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:k.displayName||[k.firstName,k.lastName].filter(Boolean).join(" ")||k.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:k.email}),k.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:k.designation})]})]})},k.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(R,{type:"button",variant:"outline",onClick:M,className:"flex-1 h-11 border-gray-300",disabled:u,children:"Cancel"}),e.jsxs(R,{type:"button",onClick:S,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:u||!i.trim()||!d||!l,children:[e.jsx(Ct,{className:"w-4 h-4 mr-2"}),u?"Adding...":`Add at Level ${d||"?"}`]})]})]}),e.jsx(nt,{open:N.open,onOpenChange:k=>A(I=>({...I,open:k})),children:e.jsxs(at,{className:"sm:max-w-md",children:[e.jsxs(it,{children:[e.jsx(rt,{className:"flex items-center gap-2",children:N.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(Pe,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Pe,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(Ht,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[N.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:N.email})," was not found in the organization directory."]}),e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3 space-y-2",children:[e.jsx("p",{className:"text-sm text-red-800 font-semibold",children:"Please verify:"}),e.jsxs("ul",{className:"text-sm text-red-700 space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"Email address is spelled correctly"}),e.jsx("li",{children:"User exists in Okta/SSO system"}),e.jsx("li",{children:"User has an active account"})]})]}),e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-blue-800 flex items-center gap-1",children:[e.jsx(vn,{className:"w-4 h-4"}),e.jsx("strong",{children:"Tip:"})," Use ",e.jsx("span",{className:"font-mono bg-blue-100 px-1 rounded",children:"@"})," sign to search users from the directory."]})})]}),N.type==="error"&&e.jsxs(e.Fragment,{children:[N.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:N.email}),"."]}),N.message&&e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-3",children:e.jsx("p",{className:"text-sm text-gray-700",children:N.message})})]})]})})]}),e.jsx(yt,{children:e.jsx(R,{onClick:()=>A(k=>({...k,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const Ob=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"}},$b=t=>{switch(t){case"online":return"Online";case"away":return"Away";case"offline":return"Offline";default:return"Unknown"}},Ub=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 />"),Bb=t=>t<1024?t+" B":t<1024*1024?(t/1024).toFixed(1)+" KB":(t/(1024*1024)).toFixed(1)+" MB",Hl=({type:t})=>{const s="w-4 h-4",a=t.toLowerCase();return a.includes("pdf")?e.jsx(Re,{className:`${s} text-red-600`}):a.includes("excel")||a.includes("spreadsheet")||a.includes("xlsx")?e.jsx(Kx,{className:`${s} text-green-600`}):a.includes("powerpoint")||a.includes("presentation")||a.includes("pptx")?e.jsx(Re,{className:`${s} text-orange-600`}):a.includes("word")||a.includes("document")||a.includes("docx")?e.jsx(Re,{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(Ti,{className:`${s} text-purple-600`}):e.jsx(fn,{className:`${s} text-gray-600`})};function Vm({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=Dr(),u=t||m.requestId||"",[h,p]=x.useState(""),[g,y]=x.useState(""),[v,C]=x.useState(!1),[f,j]=x.useState([]),[b,N]=x.useState(!1),[A,D]=x.useState([]),[T,P]=x.useState(null),[w,S]=x.useState(null),[M,B]=x.useState(!1),[_,$]=x.useState(!1),[k,I]=x.useState(!1),[E,F]=x.useState({success:!0,title:"",message:""}),O=x.useRef(null),L=x.useRef(null),J=x.useRef(null),U=x.useRef(!1),[oe,ge]=x.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[G,me]=x.useState({open:!1,errors:[]}),re=x.useMemo(()=>({id:u,title:n||"Request Details"}),[u,n]),[V,q]=x.useState([]),ie=V.filter(W=>W.status==="online"),ue=f.filter(W=>W.content.toLowerCase().includes(g.toLowerCase())||W.user.name.toLowerCase().includes(g.toLowerCase())),Te=x.useMemo(()=>l!==void 0?l:!T||V.length===0?!1:V.some(W=>{const le=W.userId||W.user_id,z=(W.role||"").toString().toUpperCase(),ye=(W.participantType||W.participant_type||"").toString().toUpperCase();return le===T&&(z==="SPECTATOR"||ye==="SPECTATOR")}),[l,T,V]);x.useEffect(()=>{},[V]),x.useEffect(()=>{!u||!T||s||(async()=>{try{const W=await Ha(u),le=Array.isArray(W)?W.map(z=>{const ye=z.userId||z.user_id;return{id:z.noteId||z.id||String(Math.random()),user:{name:z.userName||"User",avatar:(z.userName||"U").slice(0,2).toUpperCase(),role:z.userRole||"Participant"},content:z.message||"",timestamp:z.createdAt||new Date().toISOString(),isCurrentUser:ye===T,attachments:Array.isArray(z.attachments)?z.attachments.map(be=>({attachmentId:be.attachmentId||be.attachment_id,name:be.fileName||be.file_name||be.name,fileName:be.fileName||be.file_name||be.name,url:be.storageUrl||be.storage_url||be.url||"#",type:be.fileType||be.file_type||be.type||"file",fileType:be.fileType||be.file_type||be.type||"file",fileSize:be.fileSize||be.file_size})):void 0}}):[];j(le)}catch(W){console.error("[WorkNoteChat] Failed to load messages:",W)}})()},[u,T,s]);const qe=x.useMemo(()=>{const W=[];return f.forEach(le=>{le.attachments&&le.attachments.length>0&&le.attachments.forEach(z=>{W.push({attachmentId:z.attachmentId||z.attachment_id,name:z.fileName||z.file_name||z.name||"Untitled",fileName:z.fileName||z.file_name||z.name||"Untitled",size:z.fileSize||z.file_size,type:z.fileType||z.file_type||z.type||"file",uploadedBy:le.user.name,uploadedAt:le.timestamp,url:z.storageUrl||z.storage_url||z.url||"#"})})}),W},[f]);x.useEffect(()=>{i&&qe.length>=0&&i(qe)},[qe,i]);const ze=x.useMemo(()=>V.map(W=>({email:(W.email||"").toLowerCase(),participantType:W.role==="Initiator"?"INITIATOR":W.role==="Approver"?"APPROVER":W.role==="Spectator"?"SPECTATOR":"PARTICIPANT",name:W.name})),[V]),Ze=W=>{if(!W)return"Participant";switch(W.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return W.charAt(0).toUpperCase()+W.slice(1).toLowerCase()}},Ge=()=>{var W;(W=O.current)==null||W.scrollIntoView({behavior:"smooth"})};x.useEffect(()=>{Ge()},[f]);const He=W=>{switch(W.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return W.charAt(0).toUpperCase()+W.slice(1).toLowerCase()}};x.useEffect(()=>{U.current||u&&(async()=>{try{const W=await ds(u),le=Array.isArray(W==null?void 0:W.participants)?W.participants:[];if(le.length===0)return;const z=le.map(ve=>{const Fe=ve.participantType||ve.participant_type||"participant",ke=ve.userId||ve.user_id||"";return{name:ve.userName||ve.user_name||ve.user_email||ve.userEmail||"User",avatar:(ve.userName||ve.user_name||ve.user_email||"U").toString().split(" ").map(Be=>Be[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:He(Fe.toString()),status:"offline",email:ve.userEmail||ve.user_email||"",permissions:["read","write","mention"],userId:ke}});U.current=!0,q(z);let ye=0;const be=3,De=()=>{J.current&&J.current.connected?(J.current.emit("request:online-users",{requestId:u}),ye++,ye<be&&setTimeout(De,500)):(ye++,ye<be&&setTimeout(De,200))};setTimeout(De,100)}catch(W){console.error("[WorkNoteChat] ❌ Failed to load participants:",W)}})()},[u]),x.useEffect(()=>()=>{u&&(U.current=!1)},[u]),x.useEffect(()=>{const W=localStorage.getItem("userData");if(W)try{const le=JSON.parse(W),z=(le==null?void 0:le.id)||(le==null?void 0:le.userId)||(le==null?void 0:le.user_id)||null;P(z)}catch(le){console.error("[WorkNoteChat] Failed to parse userData:",le)}},[]),x.useEffect(()=>{(async()=>{try{const le=await Pa("DOCUMENT_POLICY"),z={};le.forEach(ve=>{z[ve.configKey]=ve.configValue});const ye=parseInt(z.MAX_FILE_SIZE_MB||"10"),De=(z.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(ve=>ve.trim().toLowerCase());ge({maxFileSizeMB:ye,allowedFileTypes:De})}catch(le){console.error("Failed to load document policy:",le)}})()},[]),x.useEffect(()=>{if(!T)return;let W=u;return(async()=>{var le;try{const z=await ds(u);(le=z==null?void 0:z.workflow)!=null&&le.requestId&&(W=z.workflow.requestId)}catch{}try{const z=vr();r?q(Je=>Je.map(tt=>tt.userId===T?{...tt,status:"online"}:tt)):(Ei(z,W,T),q(Je=>Je.map(tt=>tt.userId===T?{...tt,status:"online"}:tt)));const ye=Je=>{const Ve=(Je==null?void 0:Je.note)||Je;if(!Ve)return;const tt=Ve.noteId||Ve.id;j(Zt=>{if(Zt.some(dt=>dt.id===tt))return Zt;const Nt=Ve.userName||Ve.user_name||"User",ga=Ve.userRole||Ve.user_role,Js=Ze(ga),fa=Ve.userId||Ve.user_id,ya={id:tt||String(Date.now()),user:{name:Nt,avatar:Nt.split(" ").map(dt=>dt[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Js},content:Ve.message||"",timestamp:Ve.createdAt||new Date().toISOString(),isCurrentUser:fa===T,attachments:Array.isArray(Ve.attachments)?Ve.attachments.map(dt=>({attachmentId:dt.attachmentId||dt.attachment_id,name:dt.fileName||dt.file_name||dt.name,fileName:dt.fileName||dt.file_name||dt.name,url:dt.storageUrl||dt.storage_url||dt.url||"#",type:dt.fileType||dt.file_type||dt.type||"file",fileType:dt.fileType||dt.file_type||dt.type||"file",fileSize:dt.fileSize||dt.file_size})):void 0};return[...Zt,ya]})},be=Je=>{q(Ve=>Ve.length===0||!Ve.find(Nt=>Nt.userId===Je.userId)?Ve:Ve.map(Nt=>Nt.userId===Je.userId?{...Nt,status:"online"}:Nt))},De=Je=>{Je.userId!==T&&q(Ve=>Ve.length===0||!Ve.find(Nt=>Nt.userId===Je.userId)?Ve:Ve.map(Nt=>Nt.userId===Je.userId?{...Nt,status:"offline"}:Nt))},ve=Je=>{q(Ve=>Ve.length===0?Ve:Ve.map(Zt=>{const Nt=Zt.userId||"";if(Nt===T)return{...Zt,status:"online"};const Js=Je.userIds.includes(Nt);return{...Zt,status:Js?"online":"offline"}}))},Fe=()=>{q(Je=>Je.map(tt=>tt.userId===T?{...tt,status:"online"}:tt)),r||Ei(z,W,T),U.current&&(z.emit("request:online-users",{requestId:W}),setTimeout(()=>z.emit("request:online-users",{requestId:W}),300),setTimeout(()=>z.emit("request:online-users",{requestId:W}),800))},ke=Je=>{console.error("[WorkNoteChat] ❌ Socket error:",Je)},Be=Je=>{console.warn("[WorkNoteChat] ⚠️ Socket disconnected:",Je),q(Ve=>Ve.map(tt=>tt.userId===T?tt:{...tt,status:"offline"}))},ls=Je=>{Je.includes("presence")||Je.includes("worknote")||Je.includes("request")};z.on("connect",Fe),z.on("disconnect",Be),z.on("error",ke),z.on("worknote:new",ye),z.on("presence:join",be),z.on("presence:leave",De),z.on("presence:online",ve),z.onAny(ls),J.current=z,z.connected&&U.current&&(z.emit("request:online-users",{requestId:W}),setTimeout(()=>{z.emit("request:online-users",{requestId:W})},300),setTimeout(()=>{z.emit("request:online-users",{requestId:W})},800),setTimeout(()=>{z.emit("request:online-users",{requestId:W})},1500));const Dt=()=>{z.off("connect",Fe),z.off("disconnect",Be),z.off("error",ke),z.off("worknote:new",ye),z.off("presence:join",be),z.off("presence:leave",De),z.off("presence:online",ve),z.offAny(ls),r||fm(z,W),J.current=null};window.__wn_cleanup=Dt}catch{}})(),()=>{var le;try{(le=window.__wn_cleanup)==null||le.call(window)}catch{}}},[u,T,r]);const xt=async()=>{if(h.trim()||A.length>0){const W=Ss(h),le=W.map(be=>{const De=V.find(ve=>ve.name.toLowerCase().includes(be.toLowerCase()));return De==null?void 0:De.userId}).filter(Boolean),z=A.map(be=>({name:be.name,url:URL.createObjectURL(be),type:be.type.split("/")[1]||"file"})),ye={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:W,isHighPriority:h.includes("!important")||h.includes("urgent"),attachments:z.length>0?z:void 0,isCurrentUser:!0};if(a)try{await a(h,A)}catch{}else try{await sa(u,{message:h,mentions:le},A);const be=await Ha(u),De=Array.isArray(be)?be.map(ve=>{const Fe=ve.userId||ve.user_id;return{id:ve.noteId||ve.id||String(Math.random()),user:{name:ve.userName||"User",avatar:(ve.userName||"U").slice(0,2).toUpperCase(),role:ve.userRole||"Participant"},content:ve.message||"",timestamp:ve.createdAt||new Date().toISOString(),isCurrentUser:Fe===T,attachments:Array.isArray(ve.attachments)?ve.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}}):[];j(De)}catch{j(be=>[...be,ye])}p(""),D([])}};x.useEffect(()=>{if(s&&Array.isArray(s))try{const le=s.filter(z=>(z.type||"").toLowerCase()!=="sla_warning").map(z=>{var be;if(z.type||z.activityType||z.isSystem)return{id:z.id||`activity-${z.timestamp||Date.now()}-${Math.random()}`,user:{name:"System",avatar:"SY",role:"System"},content:z.details||z.action||z.content||"",timestamp:z.timestamp||z.createdAt||z.created_at||new Date().toISOString(),isSystem:!0,isCurrentUser:!1};{const De=z.userName||z.user_name||((be=z.user)==null?void 0:be.name)||"User",ve=z.userRole||z.user_role,Fe=Ze(ve),ke=z.userId||z.user_id;return{id:z.noteId||z.note_id||z.id||String(Math.random()),user:{name:De,avatar:De.split(" ").map(Be=>Be[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Fe},content:z.message||z.content||"",timestamp:z.createdAt||z.created_at||z.timestamp||new Date().toISOString(),isSystem:!1,attachments:Array.isArray(z.attachments)?z.attachments.map(Be=>({attachmentId:Be.attachmentId||Be.attachment_id,name:Be.fileName||Be.file_name||Be.name,fileName:Be.fileName||Be.file_name||Be.name,url:Be.storageUrl||Be.storage_url||Be.url||"#",type:Be.fileType||Be.file_type||Be.type||"file",fileType:Be.fileType||Be.file_type||Be.type||"file",fileSize:Be.fileSize||Be.file_size})):void 0,isCurrentUser:ke===T}}}).sort((z,ye)=>new Date(z.timestamp).getTime()-new Date(ye.timestamp).getTime());j(le)}catch(W){console.error("[WorkNoteChat] Error mapping messages:",W)}else(async()=>{try{const W=await Ha(u),le=Array.isArray(W)?W.map(z=>{const ye=z.userName||z.user_name||"User",be=z.userRole||z.user_role,De=Ze(be),ve=z.userId||z.user_id;return{id:z.noteId||z.note_id||z.id||String(Math.random()),user:{name:ye,avatar:ye.split(" ").map(Fe=>Fe[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:De},content:z.message||"",timestamp:z.createdAt||z.created_at||new Date().toISOString(),attachments:Array.isArray(z.attachments)?z.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===T}}):[];j(le)}catch(W){console.error("[WorkNoteChat] Error loading work notes:",W)}})()},[s,u,V]);const Q=W=>{const le=oe.maxFileSizeMB*1024*1024;if(W.size>le)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${oe.maxFileSizeMB}MB. Current size: ${(W.size/(1024*1024)).toFixed(2)}MB`};const z=W.name.toLowerCase(),ye=z.substring(z.lastIndexOf(".")+1);return oe.allowedFileTypes.includes(ye)?{valid:!0}:{valid:!1,reason:`File type "${ye}" is not allowed. Allowed types: ${oe.allowedFileTypes.join(", ")}`}},xe=W=>{if(!W.target.files||W.target.files.length===0)return;const le=Array.from(W.target.files),z=[],ye=[];le.forEach(be=>{const De=Q(be);De.valid?ye.push(be):z.push({fileName:be.name,reason:De.reason||"Unknown validation error"})}),z.length>0&&me({open:!0,errors:z}),ye.length>0&&(D(be=>[...be,...ye]),ye.length<le.length?te.warning(`${ye.length} of ${le.length} file(s) were added. ${z.length} file(s) were rejected.`):te.success(`${ye.length} file(s) added successfully`)),W.target&&(W.target.value="")},ot=W=>{D(le=>le.filter((z,ye)=>ye!==W)),L.current&&(L.current.value="")},de=W=>{p(le=>le+W),C(!1)},Ee=()=>{var W;(W=L.current)==null||W.click()},lt=async W=>{var le,z;try{await wm(u,W);const ye=await ds(u),be=Array.isArray(ye==null?void 0:ye.participants)?ye.participants:[];if(be.length){const De=be.map(ve=>{const Fe=ve.participantType||ve.participant_type||"participant",ke=ve.userId||ve.user_id||"",Be=ve.userName||ve.user_name||ve.userEmail||ve.user_email||"User",ls=ve.userEmail||ve.user_email||"",Dt=Be.split(" ").map(Je=>Je[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:Be,avatar:Dt,role:He(Fe),status:"offline",email:ls,lastSeen:void 0,permissions:["read"],userId:ke}});q(De),J.current&&J.current.connected&&J.current.emit("request:online-users",{requestId:u})}B(!1),F({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),I(!0)}catch(ye){throw console.error("Failed to add spectator:",ye),F({success:!1,title:"Failed to Add Spectator",message:((z=(le=ye==null?void 0:ye.response)==null?void 0:le.data)==null?void 0:z.error)||"Failed to add spectator. Please try again."}),I(!0),ye}},jt=async(W,le,z)=>{var ye,be;if(d)await d(W,le,z),$(!1);else try{await Nm(u,W,le,z);const De=await ds(u),ve=Array.isArray(De==null?void 0:De.participants)?De.participants:[];if(ve.length){const Fe=ve.map(ke=>{const Be=ke.participantType||ke.participant_type||"participant",ls=ke.userId||ke.user_id||"",Dt=ke.userName||ke.user_name||ke.userEmail||ke.user_email||"User",Je=ke.userEmail||ke.user_email||"",Ve=Dt.split(" ").map(tt=>tt[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:Dt,avatar:Ve,role:He(Be),status:"offline",email:Je,lastSeen:void 0,permissions:["read"],userId:ls}});q(Fe),J.current&&J.current.connected&&J.current.emit("request:online-users",{requestId:u})}$(!1),F({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${z} with ${le}h TAT`}),I(!0)}catch(De){throw console.error("Failed to add approver:",De),F({success:!1,title:"Failed to Add Approver",message:((be=(ye=De==null?void 0:De.response)==null?void 0:ye.data)==null?void 0:be.error)||"Failed to add approver. Please try again."}),I(!0),De}},ct=["😊","😂","🤣","😁","😃","😄","😅","😆","😉","😌","😍","🥰","😘","😗","😙","😚","🙂","🤗","🤩","🤔","🤨","😐","😑","😶","🙄","😏","😒","🙃","😬","🤐","😴","😪","😵","🤯","🤪","😜","😝","😛","🤤","😋","😎","🤓","🧐","😕","😟","🙁","☹️","😮","😯","😲","😳","🥺","😦","😧","😨","😰","😥","😢","😭","😱","😖","😣","😞","😓","😩","😫","🥱","😤","😡","😠","🤬","😈","👿","💀","☠️","💩","🤡","👹","👺","👻","👋","🤚","🖐️","✋","🖖","👌","🤌","🤏","✌️","🤞","🤟","🤘","🤙","👈","👉","👆","🖕","👇","☝️","👍","👎","✊","👊","🤛","🤜","👏","🙌","👐","🤲","🤝","🙏","💪","🦾","🦿","🦵","🦶","👂","🦻","👃","🧠","❤️","🧡","💛","💚","💙","💜","🖤","🤍","🤎","💔","❣️","💕","💞","💓","💗","💖","💘","💝","💟","❤️🔥","💼","📊","📈","📉","💻","⌨️","🖥️","🖨️","🖱️","💾","💿","📱","☎️","📞","📟","📠","📧","✉️","📨","📩","📮","📪","📫","📬","📭","📄","📃","📑","📝","✏️","✒️","🖊️","🖋️","📏","📐","📌","📍","🗂️","📁","📂","✅","✔️","☑️","🎯","🎖️","🏆","🥇","🥈","🥉","⭐","🌟","✨","💫","🔥","💥","⚡","💯","🎉","🎊","🎈","⚠️","🚫","❌","⛔","🚷","🚯","🚱","🚳","🔞","📵","❗","❓","❕","❔","‼️","⁉️","💢","💬","💭","🗯️","⏰","⏱️","⏲️","⏳","⌛","📅","📆","🗓️","📇","🕐","🕑","🕒","🕓","🕔","🕕","🕖","🕗","🕘","🕙","🕚","🚀","🎯","🎲","🎰","🧩","🔍","🔎","🔑","🗝️","🔒","🔓","🔐","🔏","🔔","🔕","📣","📢","💡","🔦","🏮","➕","➖","✖️","➗","♾️","‼️","⁉️","❓","❔","❕","🔄","🔃","🔂","▶️","⏸️","⏯️","⏹️","⏺️","⏭️","⏮️","⏩","⏪","⏫","⏬","◀️","🔼","🔽","➡️","⬅️","⬆️","⬇️","↗️","↘️","↙️","↖️","↕️","↔️","↪️","↩️","⤴️"],Ss=W=>{const le=/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,z=[];let ye;for(;(ye=le.exec(W))!==null;)if(ye[1]){const be=ye.index+ye[0].length,De=W.slice(be),ve=W[be];(De.startsWith("@")||!ve||/\s|[.,!?;:]|@/.test(ve))&&z.push(ye[1].trim())}return z},Zs=W=>{W.key==="Enter"&&!W.shiftKey&&(W.preventDefault(),xt())},Xs=(W,le)=>{j(z=>z.map(ye=>{if(ye.id===W){const be=ye.reactions||[],De=be.find(ve=>ve.emoji===le);if(De)if(De.users.includes("You")){if(De.users=De.users.filter(ve=>ve!=="You"),De.users.length===0)return{...ye,reactions:be.filter(ve=>ve.emoji!==le)}}else De.users.push("You");else be.push({emoji:le,users:["You"]});return{...ye,reactions:be}}return ye}))};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(Ds,{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:re.title}),e.jsx(ee,{variant:"outline",className:"text-xs shrink-0",children:t})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:e.jsxs("div",{className:"flex -space-x-2",children:[ie.slice(0,3).map((W,le)=>e.jsx($t,{className:"h-8 w-8 ring-2 ring-white shadow-sm",children:e.jsx(Ut,{className:"bg-blue-500 text-white text-xs font-semibold",children:W.avatar})},le)),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(R,{variant:"outline",size:"sm",onClick:()=>N(!b),className:"lg:hidden",children:e.jsx(Ct,{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(bs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(je,{placeholder:"Search messages...",value:g,onChange:W=>y(W.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:[ue.map(W=>{const le=W.isCurrentUser||!1;return e.jsxs("div",{className:`flex gap-2 sm:gap-3 lg:gap-4 ${W.isSystem?"justify-center":le?"justify-end":""}`,children:[!W.isSystem&&!le&&e.jsx($t,{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(Ut,{className:`text-white font-semibold text-xs sm:text-sm ${W.user.role==="Initiator"?"bg-green-600":W.user.role==="Current User"?"bg-blue-500":W.user.role==="System"?"bg-gray-500":"bg-slate-600"}`,children:W.user.avatar})}),e.jsx("div",{className:`${le?"max-w-[70%]":"flex-1"} min-w-0 ${W.isSystem?"text-center max-w-xs sm:max-w-md mx-auto":""}`,children:W.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(qt,{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:W.content}),e.jsx("span",{className:"text-xs text-gray-500 hidden sm:inline",children:Yt(W.timestamp)})]}):e.jsxs("div",{children:[e.jsxs("div",{className:`flex items-center gap-2 sm:gap-3 mb-1 sm:mb-2 flex-wrap ${le?"justify-end":""}`,children:[e.jsxs("span",{className:"font-semibold text-gray-900 text-sm sm:text-base truncate",children:[W.user.name," ",le&&e.jsx("span",{className:"text-xs text-gray-500 font-normal",children:"(you)"})]}),e.jsx(ee,{variant:"outline",className:"text-xs flex-shrink-0",children:W.user.role}),e.jsxs("span",{className:"text-xs text-gray-500 flex items-center gap-1 flex-shrink-0",children:[e.jsx(Ue,{className:"w-3 h-3"}),Yt(W.timestamp)]}),W.isHighPriority&&e.jsxs(ee,{variant:"destructive",className:"text-xs flex-shrink-0",children:[e.jsx(Hx,{className:"w-3 h-3 mr-1"}),"Priority"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 sm:p-4 shadow-sm ${le?"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:Ub(W.content)}}),W.attachments&&W.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:W.attachments.map((z,ye)=>{const be=z.fileSize||z.file_size,De=z.fileName||z.file_name||z.name,ve=z.fileType||z.file_type||z.type||"",Fe=z.attachmentId||z.attachment_id;return e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 p-2 sm:p-3 bg-gray-50 rounded-lg border border-gray-200 hover:bg-gray-100 transition-colors",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx(Hl,{type:ve})}),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:De}),be&&e.jsx("p",{className:"text-xs text-gray-500",children:Bb(be)})]}),Fe&&(()=>{const ke=(ve||"").toLowerCase();return ke.includes("image")||ke.includes("pdf")||ke.includes("jpg")||ke.includes("jpeg")||ke.includes("png")||ke.includes("gif")})()&&e.jsx(R,{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:ke=>{ke.preventDefault(),ke.stopPropagation();const Be=ry(Fe);S({fileName:De,fileType:ve,fileUrl:Be,fileSize:be,attachmentId:Fe})},title:"Preview file",children:e.jsx(zt,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),e.jsx(R,{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 ke=>{if(ke.preventDefault(),ke.stopPropagation(),!Fe){te.error("Cannot download: Attachment ID missing");return}try{await $l(Fe)}catch{te.error("Failed to download file")}},title:"Download file",children:e.jsx(Qt,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]},ye)})})}),W.reactions&&W.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:[W.reactions.map((z,ye)=>e.jsxs("button",{onClick:()=>Xs(W.id,z.emoji),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs sm:text-sm transition-colors flex-shrink-0 ${z.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:z.emoji}),e.jsx("span",{className:"text-xs font-medium",children:z.users.length})]},ye)),e.jsx(R,{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(Is,{className:"w-2 h-2 sm:w-3 sm:h-3"})})]})]})]})}),!W.isSystem&&le&&e.jsx($t,{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(Ut,{className:"bg-blue-500 text-white font-semibold text-xs sm:text-sm",children:W.user.avatar})})]},W.id)}),e.jsx("div",{ref:O})]})}),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:L,onChange:xe,className:"hidden",multiple:!0,accept:oe.allowedFileTypes.map(W=>`.${W}`).join(",")}),A.length>0&&e.jsx("div",{className:"mb-3 space-y-2 max-h-32 overflow-y-auto pr-2",children:A.map((W,le)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-blue-50 rounded-lg border border-blue-200",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx(Hl,{type:W.type.split("/")[1]||"file"})}),e.jsx("span",{className:"text-sm text-gray-700 flex-1 truncate min-w-0",children:W.name}),e.jsxs("span",{className:"text-xs text-gray-500 flex-shrink-0",children:[(W.size/1024).toFixed(1)," KB"]}),e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>ot(le),className:"h-6 w-6 p-0 hover:bg-red-100 flex-shrink-0",children:e.jsx(ut,{className:"h-3 w-3 text-red-600"})})]},le))}),e.jsxs("div",{className:"relative mb-2",children:[(()=>{const W=h.lastIndexOf("@"),le=W>=0;if(!le)return null;const z=h.slice(W+1),ye=z.trim(),be=z.endsWith(" "),De=ye.length>0,ve=ye.includes(" ")&&!be,Fe=be&&De;if(!(le&&z.length<=20&&!ve&&!Fe))return null;const Be=ye.toLowerCase(),ls=V.filter(Dt=>Dt.userId===T?!1:Be?Dt.name.toLowerCase().includes(Be):!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:ls.length>0?ls.map((Dt,Je)=>e.jsxs("button",{type:"button",onClick:Ve=>{Ve.preventDefault(),Ve.stopPropagation();const tt=h.lastIndexOf("@"),Zt=h.slice(0,tt);p(Zt+"@"+Dt.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($t,{className:"h-10 w-10",children:e.jsx(Ut,{className:`text-white text-sm font-semibold ${Dt.role==="Initiator"?"bg-green-600":Dt.role==="Approver"?"bg-purple-600":"bg-blue-500"}`,children:Dt.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:Dt.name}),e.jsx("p",{className:"text-xs text-gray-600",children:Dt.role})]})]},Je)):e.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:Be?`No participants found matching "${Be}"`:"No other participants available"})})]})})(),e.jsx(os,{placeholder:"Type your message... Use @username to mention someone",value:h,onChange:W=>p(W.target.value),onKeyPress:Zs,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(R,{variant:"ghost",size:"sm",onClick:()=>C(!1),className:"h-6 w-6 p-0",children:e.jsx(ut,{className:"h-3 w-3"})})]}),e.jsx("div",{className:"grid grid-cols-8 sm:grid-cols-10 gap-1",children:ct.map((W,le)=>e.jsx("button",{onClick:()=>de(W),className:"text-xl sm:text-2xl hover:bg-gray-100 rounded p-1 transition-colors flex items-center justify-center",title:W,children:W},le))})]})]}),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(R,{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:Ee,title:"Attach file",children:e.jsx(fn,{className:"h-4 w-4"})}),e.jsx(R,{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(Wx,{className:"h-4 w-4"})}),e.jsx(R,{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(W=>W+"@"),title:"Mention someone",children:e.jsx(po,{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(R,{onClick:xt,disabled:!h.trim()&&A.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(Yd,{className:"h-4 w-4 sm:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Send"})]})]})]})]})})]}),b&&e.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 z-40 lg:hidden",onClick:()=>N(!1)}),e.jsxs("div",{className:`
|
||
w-72 sm:w-80 bg-white border-l border-gray-200 flex flex-col
|
||
lg:relative lg:translate-x-0 lg:shadow-none
|
||
${b?"fixed right-0 top-0 bottom-0 z-50 shadow-xl":"hidden lg:flex"}
|
||
`,children:[e.jsxs("div",{className:"p-4 sm:p-6 border-b border-gray-200 flex-1 flex flex-col min-h-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4 flex-shrink-0",children:[e.jsx("h3",{className:"text-base sm:text-lg font-semibold text-gray-900",children:"Participants"}),e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>N(!1),className:"lg:hidden h-8 w-8 p-0",children:e.jsx(ut,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-3 sm:space-y-4 overflow-y-auto flex-1 pr-2",children:V.map((W,le)=>{const z=W.userId===T;return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx($t,{className:"h-9 w-9 sm:h-10 sm:w-10",children:e.jsx(Ut,{className:`text-white font-semibold text-sm ${W.role==="Initiator"?"bg-green-600":z?"bg-blue-500":"bg-slate-600"}`,children:W.avatar})}),e.jsx("div",{className:`absolute -bottom-1 -right-1 w-3 h-3 rounded-full border-2 border-white ${Ob(W.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:[W.name," ",z&&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:W.role}),e.jsx("span",{className:"text-xs text-gray-400",children:"•"}),e.jsx("p",{className:"text-xs text-gray-500",children:$b(W.status)})]}),W.lastSeen&&W.status==="offline"&&e.jsx("p",{className:"text-xs text-gray-400",children:W.lastSeen})]})]},le)})})]}),!Te&&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(R,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>$(!0),children:[e.jsx(yn,{className:"h-4 w-4"}),"Add Approver"]}),e.jsxs(R,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>B(!0),children:[e.jsx(zt,{className:"h-4 w-4"}),"Add Spectator"]})]})]})]})]}),w&&e.jsx(Co,{fileName:w.fileName,fileType:w.fileType,fileUrl:w.fileUrl,fileSize:w.fileSize,attachmentId:w.attachmentId,onDownload:$l,open:!!w,onClose:()=>S(null)}),!Te&&e.jsx(Um,{open:M,onClose:()=>B(!1),onConfirm:lt,requestIdDisplay:u,requestTitle:re.title,existingParticipants:ze}),!Te&&o&&e.jsx(Bm,{open:_,onClose:()=>$(!1),onConfirm:jt,requestIdDisplay:u,requestTitle:re.title,existingParticipants:ze,currentLevels:c}),e.jsx(nt,{open:G.open,onOpenChange:W=>me(le=>({...le,open:W})),children:e.jsxs(at,{className:"sm:max-w-lg",children:[e.jsxs(it,{children:[e.jsxs(rt,{className:"flex items-center gap-2",children:[e.jsx(Pe,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Ht,{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:G.errors.map((W,le)=>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:W.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:W.reason})]},le))}),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(yt,{children:e.jsx(R,{onClick:()=>me({open:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(Om,{open:k,onClose:()=>I(!1),success:E.success,title:E.title,message:E.message})]})}function Vb({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(Vm,{requestId:t,requestTitle:s,skipSocketJoin:!0,messages:a,onAttachmentsExtracted:r,isInitiator:n,isSpectator:i,currentLevels:o,onAddApprover:l})})}function zb({summary:t,loading:s,onShare:a,isInitiator:r}){const n=l=>{const c=l.toLowerCase();return c==="approved"?e.jsx(Ce,{className:"h-4 w-4 text-green-600"}):c==="rejected"?e.jsx(ht,{className:"h-4 w-4 text-red-600"}):c==="pending"||c==="in progress"?e.jsx(Ue,{className:"h-4 w-4 text-orange-600"}):e.jsx(Re,{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(Xe,{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(R,{variant:"outline",size:"sm",onClick:a,className:"flex items-center gap-2",children:[e.jsx(Ya,{className:"w-4 h-4"}),e.jsx("span",{children:"Share"})]}):e.jsxs(ee,{className:i(t.workflow.status),children:[n(t.workflow.status),e.jsx("span",{className:"ml-1 capitalize",children:t.workflow.status})]})]}),t.description&&e.jsx("div",{className:"mb-4",children:e.jsx(oa,{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:Ne(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:Ne(new Date(l.timestamp),"MMM dd, yy, HH:mm")})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Remarks"}),e.jsx("p",{className:"text-sm text-gray-700",children:l.remarks||"—"})]})]},c))]}),e.jsxs("div",{className:"p-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Closing Remarks (Conclusion)"}),e.jsxs("div",{className:"bg-gray-50 rounded-lg p-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:t.initiator.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:o(t.initiator.designation,t.initiator.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:"Concluded"})]}),t.isAiGenerated&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Source"}),e.jsx(ee,{variant:"outline",className:"text-xs",children:"AI Generated"})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Remarks"}),t.closingRemarks?e.jsx(oa,{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(Re,{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 Hb({request:t,apiRequest:s,onRefresh:a}){var T,P,w;const r=(s==null?void 0:s.requestId)||(t==null?void 0:t.requestId),n=(s==null?void 0:s.internalOrder)||(s==null?void 0:s.internal_order)||null,i=(n==null?void 0:n.ioNumber)||(n==null?void 0:n.io_number)||(t==null?void 0:t.ioNumber)||"",o=(n==null?void 0:n.ioBlockedAmount)||(n==null?void 0:n.io_blocked_amount)||0,l=(n==null?void 0:n.ioAvailableBalance)||(n==null?void 0:n.io_available_balance)||0,c=(n==null?void 0:n.ioRemainingBalance)||(n==null?void 0:n.io_remaining_balance)||0,d=(n==null?void 0:n.sapDocumentNumber)||(n==null?void 0:n.sap_document_number)||"",[m,u]=x.useState(i),[h,p]=x.useState(!1),[g,y]=x.useState(null),[v,C]=x.useState(null),[f,j]=x.useState(!1);x.useEffect(()=>{n&&i&&(C({ioNumber:i,blockedAmount:Number(o)||0,availableBalance:Number(l)||0,blockedDate:n.organizedAt||n.organized_at||new Date().toISOString(),sapDocumentNumber:d,status:n.status==="BLOCKED"?"blocked":n.status==="RELEASED"?"released":"blocked"}),u(i),l>0&&y(Number(l)))},[n,i,o,l,c,d]);const b=async()=>{var S,M;if(!m.trim()){te.error("Please enter an IO number");return}if(!r){te.error("Request ID not found");return}p(!0);try{await Qr(r,{ioNumber:m.trim(),ioAvailableBalance:0,ioBlockedAmount:0,ioRemainingBalance:0});const B=await Vl(r),_=(B==null?void 0:B.internalOrder)||(B==null?void 0:B.internal_order);if(_){const $=Number(_.ioAvailableBalance||_.io_available_balance||0);$>0?(y($),te.success(`IO validated successfully. Available balance: ₹${$.toLocaleString("en-IN")}`)):(te.error("No available balance found for this IO number"),y(null))}else te.error("Failed to fetch IO details after validation"),y(null)}catch(B){console.error("Failed to fetch IO budget:",B);const _=((M=(S=B==null?void 0:B.response)==null?void 0:S.data)==null?void 0:M.message)||(B==null?void 0:B.message)||"Failed to validate IO number or fetch budget from SAP";te.error(_),y(null)}finally{p(!1)}},N=async()=>{var M,B,_,$,k;if(!m.trim()||g===null){te.error("Please fetch IO amount first");return}if(!r){te.error("Request ID not found");return}const S=((M=s==null?void 0:s.budgetTracking)==null?void 0:M.proposalEstimatedBudget)||((B=s==null?void 0:s.proposalDetails)==null?void 0:B.totalEstimatedBudget)||((_=s==null?void 0:s.claimDetails)==null?void 0:_.estimatedBudget)||(t==null?void 0:t.claimAmount)||(t==null?void 0:t.amount)||0;if(S>g){te.error("Claim amount exceeds available IO budget");return}j(!0);try{await Qr(r,{ioNumber:m.trim(),ioAvailableBalance:g,ioBlockedAmount:S,ioRemainingBalance:g-S});const I=await Vl(r),E=(I==null?void 0:I.internalOrder)||(I==null?void 0:I.internal_order);if(E){const F={ioNumber:E.ioNumber||E.io_number||m,blockedAmount:Number(E.ioBlockedAmount||E.io_blocked_amount||S),availableBalance:Number(E.ioAvailableBalance||E.io_available_balance||g),blockedDate:E.organizedAt||E.organized_at||new Date().toISOString(),sapDocumentNumber:E.sapDocumentNumber||E.sap_document_number||"",status:"blocked"};C(F),te.success("IO budget blocked successfully in SAP"),a==null||a()}else te.error("IO blocked but failed to fetch updated details"),a==null||a()}catch(I){console.error("Failed to block IO budget:",I);const E=((k=($=I==null?void 0:I.response)==null?void 0:$.data)==null?void 0:k.message)||(I==null?void 0:I.message)||"Failed to block IO budget in SAP";te.error(E)}finally{j(!1)}},A=async()=>{var S,M;if(!v||!r){te.error("No blocked budget to release");return}if(!m.trim()){te.error("IO number not found");return}try{await Qr(r,{ioNumber:m.trim(),ioAvailableBalance:v.availableBalance+v.blockedAmount,ioBlockedAmount:0,ioRemainingBalance:v.availableBalance+v.blockedAmount}),C(null),y(null),u(""),te.success("IO budget released successfully"),a==null||a()}catch(B){console.error("Failed to release IO budget:",B);const _=((M=(S=B==null?void 0:B.response)==null?void 0:S.data)==null?void 0:M.message)||(B==null?void 0:B.message)||"Failed to release IO budget";te.error(_)}},D=((T=s==null?void 0:s.budgetTracking)==null?void 0:T.proposalEstimatedBudget)||((P=s==null?void 0:s.proposalDetails)==null?void 0:P.totalEstimatedBudget)||((w=s==null?void 0:s.claimDetails)==null?void 0:w.estimatedBudget)||(t==null?void 0:t.claimAmount)||(t==null?void 0:t.amount)||0;return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(Z,{children:[e.jsxs(ae,{children:[e.jsxs(ne,{className:"flex items-center gap-2",children:[e.jsx(Fs,{className:"w-5 h-5 text-[#2d4a3e]"}),"IO Budget Management"]}),e.jsx(we,{children:"Enter IO number to fetch available budget from SAP"})]}),e.jsxs(X,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(Y,{htmlFor:"ioNumber",children:"IO Number *"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(je,{id:"ioNumber",placeholder:"Enter IO number (e.g., IO-2024-12345)",value:m,onChange:S=>u(S.target.value),disabled:h||!!v,className:"flex-1"}),e.jsxs(R,{onClick:b,disabled:!m.trim()||h||!!v,className:"bg-[#2d4a3e] hover:bg-[#1f3329]",children:[e.jsx(Qt,{className:"w-4 h-4 mr-2"}),h?"Fetching...":"Fetch Amount"]})]})]}),g!==null&&!v&&e.jsxs("div",{className:"bg-green-50 border border-green-200 rounded-lg p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-green-600 font-medium",children:"Available Budget"}),e.jsxs("p",{className:"text-2xl font-bold text-green-900",children:["₹",g.toLocaleString("en-IN")]})]}),e.jsx(Ce,{className:"w-8 h-8 text-green-600"})]}),e.jsxs("div",{className:"border-t border-green-200 pt-3 space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-green-700",children:"Claim Amount:"}),e.jsxs("span",{className:"font-semibold text-green-900",children:["₹",D.toLocaleString("en-IN")]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-green-700",children:"Balance After Block:"}),e.jsxs("span",{className:"font-semibold text-green-900",children:["₹",(g-D).toLocaleString("en-IN")]})]})]}),D>g?e.jsxs("div",{className:"flex items-center gap-2 bg-red-100 text-red-700 p-3 rounded-md",children:[e.jsx(Pe,{className:"w-4 h-4"}),e.jsx("p",{className:"text-xs font-medium",children:"Insufficient budget! Claim amount exceeds available balance."})]}):e.jsx(R,{onClick:N,disabled:f,className:"w-full bg-[#2d4a3e] hover:bg-[#1f3329]",children:f?"Blocking in SAP...":"Block Budget in SAP"})]})]})]}),e.jsxs(Z,{children:[e.jsxs(ae,{children:[e.jsxs(ne,{className:"flex items-center gap-2",children:[e.jsx(Ce,{className:"w-5 h-5 text-green-600"}),"IO Blocked Details"]}),e.jsx(we,{children:"Details of IO blocked in SAP system"})]}),e.jsx(X,{children:v?e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"bg-gradient-to-r from-emerald-50 to-green-50 rounded-lg border-2 border-emerald-300 p-4",children:e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-emerald-500 flex items-center justify-center",children:e.jsx(Ce,{className:"w-6 h-6 text-white"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-emerald-900",children:"Budget Blocked Successfully!"}),e.jsx("p",{className:"text-xs text-emerald-700",children:"SAP integration completed"})]})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between py-2 border-b",children:[e.jsx("span",{className:"text-sm text-gray-600",children:"IO Number:"}),e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:v.ioNumber})]}),e.jsxs("div",{className:"flex justify-between py-2 border-b",children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Blocked Amount:"}),e.jsxs("span",{className:"text-sm font-semibold text-green-700",children:["₹",v.blockedAmount.toLocaleString("en-IN")]})]}),e.jsxs("div",{className:"flex justify-between py-2 border-b",children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Available Balance:"}),e.jsxs("span",{className:"text-sm font-semibold text-gray-900",children:["₹",v.availableBalance.toLocaleString("en-IN")]})]}),e.jsxs("div",{className:"flex justify-between py-2 border-b",children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Blocked Date:"}),e.jsx("span",{className:"text-sm font-medium text-gray-900",children:new Date(v.blockedDate).toLocaleString("en-IN")})]}),e.jsxs("div",{className:"flex justify-between py-2 border-b",children:[e.jsx("span",{className:"text-sm text-gray-600",children:"SAP Document No:"}),e.jsx("span",{className:"text-sm font-mono font-medium text-blue-700",children:v.sapDocumentNumber})]}),e.jsxs("div",{className:"flex justify-between py-2",children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Status:"}),e.jsx("span",{className:"text-xs font-semibold px-2 py-1 bg-green-100 text-green-800 rounded-full",children:v.status.toUpperCase()})]})]}),e.jsx(R,{variant:"outline",onClick:A,className:"w-full border-red-300 text-red-700 hover:bg-red-50",children:"Release Budget"})]}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Fs,{className:"w-16 h-16 text-gray-300 mx-auto mb-4"}),e.jsx("p",{className:"text-sm text-gray-500 mb-2",children:"No IO blocked yet"}),e.jsx("p",{className:"text-xs text-gray-400",children:"Enter IO number and fetch amount to block budget"})]})})]})]})}function Wb({request:t,isInitiator:s,isSpectator:a,currentApprovalLevel:r,onAddApprover:n,onAddSpectator:i,onApprove:o,onReject:l,onPause:c,onResume:d,onRetrigger:m,summaryId:u,refreshTrigger:h,pausedByUserId:p,currentUserId:g,apiRequest:y,onEditClaimAmount:v}){var k,I,E,F,O;const{user:C}=ts(),[f,j]=x.useState([]),[b,N]=x.useState(!1),[A,D]=x.useState(!1),T=(t==null?void 0:t.status)==="closed",P=((k=t==null?void 0:t.pauseInfo)==null?void 0:k.isPaused)||!1,w=p||((E=(I=t==null?void 0:t.pauseInfo)==null?void 0:I.pausedBy)==null?void 0:E.userId),S=g||(C==null?void 0:C.userId)||"",M=!P&&!T&&(r||s),B=P&&d&&(r||s),_=P&&s&&w&&w!==S&&m;x.useEffect(()=>{if(!P||!r||!(t!=null&&t.requestId)){D(!1);return}(async()=>{var J;try{const ge=(((J=(await aa.list({page:1,limit:50,unreadOnly:!0})).data)==null?void 0:J.notifications)||[]).some(G=>G.requestId===t.requestId&&G.notificationType==="pause_retrigger_request");D(ge)}catch(U){console.error("Failed to check retrigger notifications:",U),D(!1)}})()},[P,r,t==null?void 0:t.requestId,h]),x.useEffect(()=>{(async()=>{if(!T||!u||!s){j([]);return}try{N(!0);const J=await tb(u);j(J)}catch(J){console.error("Failed to fetch shared recipients:",J),j([])}finally{N(!1)}})()},[T,u,s,h]);const $=x.useMemo(()=>{if(!y||!Ta(y))return null;const L=Fm(y);if(!L)return null;const J=_m(y,S),U=Lm(J);return{claimRequest:L,visibility:U}},[y,S]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[!a&&t.status!=="closed"&&e.jsxs(Z,{"data-testid":"quick-actions-card",children:[e.jsx(ae,{className:"pb-2",children:e.jsx(ne,{className:"text-sm sm:text-base",children:"Quick Actions"})}),e.jsxs(X,{className:"space-y-2",children:[s&&t.status!=="closed"&&e.jsxs(R,{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(yn,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Add Approver"]}),t.status!=="closed"&&e.jsxs(R,{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(zt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Add Spectator"]}),M&&c&&e.jsxs(R,{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(ca,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Pause Workflow"]}),B&&e.jsxs(R,{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(nn,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Resume Workflow"]}),_&&e.jsxs(R,{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&&!P&&e.jsxs(e.Fragment,{children:[e.jsxs(R,{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(Ce,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Approve Request"]}),e.jsxs(R,{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(ht,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Reject Request"]})]}),P&&e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-3 text-center",children:w===S?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:[A&&e.jsx(Pe,{className:"w-3.5 h-3.5"}),A?"Initiator has requested you to resume":"You paused this workflow"]}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:A?"Please review and resume if appropriate":'Click "Resume Workflow" to continue'})]}):r&&w!==S&&A?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&&w!==S?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&&w&&w!==S?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:_?'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(Z,{"data-testid":"spectators-card",children:[e.jsx(ae,{className:"pb-2",children:e.jsx(ne,{className:"text-sm sm:text-base",children:"Spectators"})}),e.jsx(X,{className:"space-y-3",children:t.spectators&&t.spectators.length>0?t.spectators.map((L,J)=>e.jsxs("div",{className:"flex items-center gap-3","data-testid":`spectator-${J}`,children:[e.jsx($t,{className:"h-8 w-8",children:e.jsx(Ut,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:L.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:L.name}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:L.role})]})]},J)):e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"No spectators added"})})})]}),T&&s&&e.jsxs(Z,{"data-testid":"shared-recipients-card",children:[e.jsx(ae,{className:"pb-2",children:e.jsxs(ne,{className:"text-sm sm:text-base flex items-center gap-2",children:[e.jsx(Ya,{className:"w-4 h-4"}),"Summary Shared With"]})}),e.jsx(X,{className:"space-y-3",children:b?e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Loading..."})}):f.length>0?f.map((L,J)=>{const U=(L.displayName||"NA").split(" ").map(oe=>oe[0]).join("").slice(0,2).toUpperCase();return e.jsxs("div",{className:"flex items-center gap-3","data-testid":`shared-recipient-${J}`,children:[e.jsx($t,{className:"h-8 w-8",children:e.jsx(Ut,{className:"bg-green-100 text-green-800 text-xs font-semibold",children:U})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:L.displayName}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:L.email}),L.isRead&&e.jsx("p",{className:"text-xs text-green-600 mt-0.5",children:"Viewed"})]})]},L.userId||J)}):e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Summary not shared yet"})})})]}),$&&e.jsx(xb,{ioDetails:$.claimRequest.ioDetails,dmsDetails:$.claimRequest.dmsDetails,claimAmount:{amount:$.claimRequest.claimAmount.closed||$.claimRequest.claimAmount.estimated||0},estimatedBudgetBreakdown:(F=$.claimRequest.proposalDetails)==null?void 0:F.costBreakup,closedExpensesBreakdown:(O=$.claimRequest.activityInfo)==null?void 0:O.closedExpensesBreakdown,visibility:$.visibility,onEditClaimAmount:v})]})}function Kb({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(nt,{open:t,onOpenChange:g=>!g&&s(),children:e.jsxs(at,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(it,{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(Ce,{className:"w-7 h-7 text-green-600"})}),e.jsxs("div",{children:[e.jsx(rt,{className:"text-lg",children:n}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Please provide your approval comments and remarks"})]})]})}),e.jsxs("div",{className:"border rounded-lg p-4 bg-white",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800",children:"Request ID"}),e.jsx("span",{className:"text-xs bg-gray-100 border border-gray-300 text-gray-800 rounded-full px-2 py-0.5",children:i||"—"})]}),e.jsxs("div",{className:"mb-3",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800 block",children:"Title"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1 truncate",children:o||"—"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800",children:"Action"}),e.jsx(ee,{className:"bg-green-100 text-green-800 border-green-200",variant:"outline",children:"APPROVE"})]})]}),e.jsxs("div",{className:"space-y-2 mt-4",children:[e.jsx("label",{className:"text-sm font-semibold text-gray-800",children:"Comments & Remarks *"}),e.jsx(os,{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(Ce,{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(yt,{className:"mt-4",children:[e.jsx(R,{variant:"outline",onClick:s,disabled:d,children:"Cancel"}),e.jsxs(R,{onClick:p,disabled:d,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(Ce,{className:"w-4 h-4 mr-2"}),d?"Approving...":"Approve Request"]})]})]})})}function Gb({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(nt,{open:t,onOpenChange:g=>!g&&s(),children:e.jsxs(at,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(it,{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(ht,{className:"w-7 h-7 text-red-600"})}),e.jsxs("div",{children:[e.jsx(rt,{className:"text-lg",children:n}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Please provide detailed reasons for rejection"})]})]})}),e.jsxs("div",{className:"border rounded-lg p-4 bg-white",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800",children:"Request ID"}),e.jsx("span",{className:"text-xs bg-gray-100 border border-gray-300 text-gray-800 rounded-full px-2 py-0.5",children:i||"—"})]}),e.jsxs("div",{className:"mb-3",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800 block",children:"Title"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1 truncate",children:o||"—"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800",children:"Action"}),e.jsx(ee,{className:"bg-red-100 text-red-800 border-red-200",variant:"outline",children:"REJECT"})]})]}),e.jsxs("div",{className:"space-y-3 mt-4",children:[e.jsx("label",{className:"text-sm font-semibold text-gray-800",children:"Comments & Remarks *"}),e.jsx(os,{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(yt,{className:"mt-4",children:[e.jsx(R,{variant:"outline",onClick:s,disabled:d,children:"Cancel"}),e.jsxs(R,{variant:"destructive",onClick:p,disabled:d,children:[e.jsx(ht,{className:"w-4 h-4 mr-2"}),d?"Rejecting...":"Reject Request"]})]})]})})}function Yb({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(nt,{open:t,onOpenChange:h,children:e.jsxs(at,{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(ut,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(it,{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(rt,{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(Y,{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(Y,{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(Y,{htmlFor:"skip-reason",className:"text-sm font-semibold text-gray-700",children:"Reason for Skipping *"}),e.jsx(os,{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(R,{type:"button",variant:"outline",onClick:h,className:"flex-1 h-11 border-gray-300",disabled:d,children:"Cancel"}),e.jsxs(R,{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 Zb({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:N,setActionStatus:A,handleApproveConfirm:D,handleRejectConfirm:T,handleAddApprover:P,handleAddSpectator:w,handleSkipApprover:S,downloadDocument:M,documentPolicy:B}){return e.jsxs(e.Fragment,{children:[e.jsx(Kb,{open:t,onClose:()=>p(!1),onConfirm:D,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(Gb,{open:s,onClose:()=>g(!1),onConfirm:T,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(Bm,{open:a,onClose:()=>y(!1),onConfirm:P,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:u,currentLevels:h}),e.jsx(Um,{open:r,onClose:()=>v(!1),onConfirm:w,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:u}),e.jsx(Yb,{open:n,onClose:()=>{C(!1),N(null)},onConfirm:S,approverName:d==null?void 0:d.approverName,levelNumber:d==null?void 0:d.levelNumber,requestIdDisplay:c.id,requestTitle:c.title}),o&&e.jsx(Co,{fileName:o.fileName,fileType:o.fileType,fileUrl:Cm(o.documentId),fileSize:o.fileSize,attachmentId:o.documentId,onDownload:M,open:!!o,onClose:()=>j(null)}),m&&e.jsx(Om,{open:i,onClose:()=>{f(!1),A(null)},success:m.success,title:m.title,message:m.message}),e.jsx(nt,{open:l.show,onOpenChange:_=>b($=>({...$,show:_})),children:e.jsxs(at,{className:"sm:max-w-lg",children:[e.jsxs(it,{children:[e.jsxs(rt,{className:"flex items-center gap-2",children:[e.jsx(Pe,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Ht,{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((_,$)=>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})]},$))}),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: ",B.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",B.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(yt,{children:e.jsx(R,{onClick:()=>b({show:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})})]})}function Xb({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=()=>bt().add(1,"month").format("YYYY-MM-DD"),h=()=>bt().add(1,"month").format("YYYY-MM-DD"),p=()=>bt().add(1,"day").format("YYYY-MM-DD");x.useEffect(()=>{t&&!l&&c(u())},[t]);const g=async()=>{var j,b,N,A;if(!i.trim()){te.error("Please provide a reason for pausing");return}if(!l){te.error("Please select a resume date");return}const v=bt(l),C=bt().add(1,"month"),f=bt().add(1,"day");if(v.isAfter(C)){te.error("Resume date cannot be more than 1 month from now");return}if(v.isBefore(f,"day")){te.error("Resume date must be at least 1 day from now");return}try{m(!0),await ty(a,r,i.trim(),v.toDate()),te.success("Workflow paused successfully"),n&&await n(),o(""),c(u()),s()}catch(D){console.error("Failed to pause workflow:",D),te.error(((b=(j=D==null?void 0:D.response)==null?void 0:j.data)==null?void 0:b.error)||((A=(N=D==null?void 0:D.response)==null?void 0:N.data)==null?void 0:A.message)||"Failed to pause workflow")}finally{m(!1)}},y=()=>{d||(o(""),c(u()),s())};return e.jsx(nt,{open:t,onOpenChange:y,children:e.jsxs(at,{className:"sm:max-w-[500px]",children:[e.jsx(it,{children:e.jsxs(rt,{className:"flex items-center gap-2",children:[e.jsx(ca,{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(Y,{htmlFor:"pause-reason",className:"text-sm font-medium",children:["Reason for Pausing ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(os,{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(Y,{htmlFor:"resume-date",className:"text-sm font-medium",children:["Resume Date ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(je,{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(yt,{children:[e.jsx(R,{variant:"outline",onClick:y,disabled:d,children:"Cancel"}),e.jsx(R,{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(Xe,{className:"w-4 h-4 mr-2 animate-spin"}),"Pausing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ca,{className:"w-4 h-4 mr-2"}),"Pause Workflow"]})})]})]})})}function Jb({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 sy(a,n.trim()||void 0),te.success("Workflow resumed successfully"),r&&await r(),i(""),s()}catch(g){console.error("Failed to resume workflow:",g),te.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(nt,{open:t,onOpenChange:d,children:e.jsxs(at,{className:"sm:max-w-[500px]",children:[e.jsx(it,{children:e.jsxs(rt,{className:"flex items-center gap-2",children:[e.jsx(nn,{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(Y,{htmlFor:"resume-notes",className:"text-sm font-medium",children:"Notes (Optional)"}),e.jsx(os,{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(yt,{children:[e.jsx(R,{variant:"outline",onClick:d,disabled:o,children:"Cancel"}),e.jsx(R,{onClick:c,disabled:o,className:"bg-green-600 hover:bg-green-700 text-white",children:o?e.jsxs(e.Fragment,{children:[e.jsx(Xe,{className:"w-4 h-4 mr-2 animate-spin"}),"Resuming..."]}):e.jsxs(e.Fragment,{children:[e.jsx(nn,{className:"w-4 h-4 mr-2"}),"Resume Workflow"]})})]})]})})}function Qb({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 ay(a),te.success("Retrigger request sent to approver"),n&&await n(),s()}catch(h){console.error("Failed to retrigger pause:",h),te.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(nt,{open:t,onOpenChange:s,children:e.jsxs(at,{className:"sm:max-w-[450px]",children:[e.jsx(it,{children:e.jsxs(rt,{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(yt,{children:[e.jsx(R,{variant:"outline",onClick:s,disabled:i,children:"Cancel"}),e.jsx(R,{onClick:l,disabled:i,className:"bg-orange-600 hover:bg-orange-700 text-white",children:i?e.jsxs(e.Fragment,{children:[e.jsx(Xe,{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 qb 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(Cs,{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(R,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(R,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}}function ev({requestId:t,onBack:s,dynamicRequests:a=[]}){var se,he,pe,Se,Qe,We,_a,Qs,$s,Rt,fl,yl;const n=Dr().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),[N,A]=x.useState(!1),[D,T]=x.useState(!1),{user:P}=ts(),{request:w,apiRequest:S,loading:M,refreshing:B,refreshDetails:_,currentApprovalLevel:$,isSpectator:k,isInitiator:I,existingParticipants:E,accessDenied:F}=My(n,a,P),O=(P==null?void 0:P.userId)||"",L=((se=P==null?void 0:P.email)==null?void 0:se.toLowerCase())||"",J=(he=S==null?void 0:S.initiator)==null?void 0:he.userId,U=(Se=(pe=S==null?void 0:S.initiator)==null?void 0:pe.email)==null?void 0:Se.toLowerCase(),oe=(S==null?void 0:S.initiator)&&(J&&J===O||U&&U===L),G=((S==null?void 0:S.approvalLevels)||[]).find(Ft=>(Ft.levelNumber||Ft.level_number)===3),me=(G==null?void 0:G.approverId)||((Qe=G==null?void 0:G.approver)==null?void 0:Qe.userId),re=me&&me===O,V=Ta(S)&&(oe||re);console.debug("[RequestDetail] IO Tab visibility:",{isClaimManagement:Ta(S),isUserInitiator:oe,isDeptLead:re,currentUserId:O,currentUserEmail:L,initiatorUserId:J,initiatorEmail:U,step3Level:G?{levelNumber:G.levelNumber||G.level_number,approverId:G.approverId||((We=G.approver)==null?void 0:We.userId)}:null,deptLeadUserId:me,showIOTab:V});const{mergedMessages:q,unreadWorkNotes:ie,workNoteAttachments:ue,setWorkNoteAttachments:Te}=Fy(n,S,l,P),{uploadingDocument:qe,triggerFileInput:ze,previewDocument:Ze,setPreviewDocument:Ge,documentPolicy:He,documentError:xt,setDocumentError:Q}=By(S,_),{showApproveModal:xe,setShowApproveModal:ot,showRejectModal:de,setShowRejectModal:Ee,showAddApproverModal:lt,setShowAddApproverModal:jt,showAddSpectatorModal:ct,setShowAddSpectatorModal:Ss,showSkipApproverModal:Zs,setShowSkipApproverModal:Xs,showActionStatusModal:W,setShowActionStatusModal:le,skipApproverData:z,setSkipApproverData:ye,actionStatus:be,setActionStatus:De,handleApproveConfirm:ve,handleRejectConfirm:Fe,handleAddApprover:ke,handleSkipApprover:Be,handleAddSpectator:ls}=Wy(n,$,_),{conclusionRemark:Dt,setConclusionRemark:Je,conclusionLoading:Ve,conclusionSubmitting:tt,aiGenerated:Zt,handleGenerateConclusion:Nt,handleFinalizeConclusion:ga}=Hy(w,n,I,_,s,De,le);x.useEffect(()=>{const Us=new URLSearchParams(window.location.search).get("tab");Us&&c(Us)},[n]);const Js=()=>{_()},fa=()=>{b(!0)},ya=()=>{A(!0)},dt=async()=>{await _()},ar=()=>{T(!0)},$r=async()=>{await _()},Ur=async()=>{await _()},rr=async()=>{if(!(S!=null&&S.requestId)){te.error("Request ID not found");return}if(!u){te.error("Summary not available. Please ensure the request is closed and the summary has been generated.");return}m(!0)},K=((w==null?void 0:w.status)==="approved"||(w==null?void 0:w.status)==="rejected")&&I,Ke=(w==null?void 0:w.status)==="closed"||(w==null?void 0:w.status)==="approved"&&!I||(w==null?void 0:w.status)==="rejected"&&!I;x.useEffect(()=>{(async()=>{if(!Ke||!(S!=null&&S.requestId)){g(null),h(null);return}try{v(!0);const Us=await eb(S.requestId);if(Us!=null&&Us.summaryId){h(Us.summaryId);try{const Fn=await Rm(Us.summaryId);g(Fn)}catch(Fn){console.error("Failed to fetch summary details:",Fn),g(null),h(null)}}else g(null),h(null)}catch{g(null),h(null)}finally{v(!1)}})()},[Ke,S==null?void 0:S.requestId]);const Ae=((w==null?void 0:w.approvalFlow)||[]).filter(Ft=>Ft&&typeof Ft.step=="number").map(Ft=>({levelNumber:Ft.step||0,approverName:Ft.approver||"Unknown",status:Ft.status||"pending",tatHours:Ft.tatHours||24}));return M&&!w&&!S?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(es,{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..."})]})}):F!=null&&F.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(Gx,{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:F.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(R,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(Ms,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(R,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})}):w?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(Xy,{request:w,refreshing:B,onBack:s||(()=>window.history.back()),onRefresh:Js,onShareSummary:rr,isInitiator:I}),e.jsxs(An,{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(kn,{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(Et,{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"})]}),Ke&&p&&e.jsxs(Et,{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(Zd,{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(Et,{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(Ys,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Workflow"})]}),V&&e.jsxs(Et,{value:"io",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-io",children:[e.jsx(Fs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"IO"})]}),e.jsxs(Et,{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(Re,{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(Et,{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(qt,{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(Et,{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(Ds,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Work Notes"}),ie>0&&e.jsx(ee,{className:"absolute -top-1 -right-1 h-5 w-5 rounded-full bg-red-500 text-white text-[10px] flex items-center justify-center p-0","data-testid":"worknotes-unread-badge",children:ie>9?"9+":ie})]})]})}),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(It,{value:"overview",className:"mt-0","data-testid":"overview-tab-content",children:Ta(S)?e.jsx(fb,{request:w,apiRequest:S,currentUserId:(P==null?void 0:P.userId)||"",isInitiator:I}):e.jsx(mb,{request:w,isInitiator:I,needsClosure:K,conclusionRemark:Dt,setConclusionRemark:Je,conclusionLoading:Ve,conclusionSubmitting:tt,aiGenerated:Zt,handleGenerateConclusion:Nt,handleFinalizeConclusion:ga,onPause:fa,onResume:ya,onRetrigger:ar,currentUserIsApprover:!!$,pausedByUserId:(Qs=(_a=w==null?void 0:w.pauseInfo)==null?void 0:_a.pausedBy)==null?void 0:Qs.userId,currentUserId:P==null?void 0:P.userId})}),Ke&&e.jsx(It,{value:"summary",className:"mt-0","data-testid":"summary-tab-content",children:e.jsx(zb,{summary:p,loading:y,onShare:rr,isInitiator:I})}),e.jsx(It,{value:"workflow",className:"mt-0",children:Ta(S)?e.jsx(Mb,{request:w,user:P,isInitiator:I,onSkipApprover:Ft=>{if(!Ft.levelId){alert("Level ID not available");return}ye(Ft),Xs(!0)},onRefresh:_}):e.jsx(vb,{request:w,user:P,isInitiator:I,onSkipApprover:Ft=>{if(!Ft.levelId){alert("Level ID not available");return}ye(Ft),Xs(!0)},onRefresh:_})}),V&&e.jsx(It,{value:"io",className:"mt-0",children:e.jsx(Hb,{request:w,apiRequest:S,onRefresh:_})}),e.jsx(It,{value:"documents",className:"mt-0",children:e.jsx(_b,{request:w,workNoteAttachments:ue,uploadingDocument:qe,documentPolicy:He,triggerFileInput:ze,setPreviewDocument:Ge,downloadDocument:Ii})}),e.jsx(It,{value:"activity",className:"mt-0",children:e.jsx(Lb,{request:w})}),e.jsx(It,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:l!=="worknotes",children:e.jsx(Vb,{requestId:n,requestTitle:w.title,mergedMessages:q,setWorkNoteAttachments:Te,isInitiator:I,isSpectator:k,currentLevels:Ae,onAddApprover:ke})})]}),l!=="worknotes"&&e.jsx(Wb,{request:w,isInitiator:I,isSpectator:k,currentApprovalLevel:$,onAddApprover:()=>jt(!0),onAddSpectator:()=>Ss(!0),onApprove:()=>ot(!0),onReject:()=>Ee(!0),onPause:fa,onResume:ya,onRetrigger:ar,summaryId:u,refreshTrigger:C,pausedByUserId:(Rt=($s=w==null?void 0:w.pauseInfo)==null?void 0:$s.pausedBy)==null?void 0:Rt.userId,currentUserId:P==null?void 0:P.userId,apiRequest:S})]})]})]})}),d&&u&&e.jsx(ob,{isOpen:d,onClose:()=>m(!1),summaryId:u,requestTitle:(w==null?void 0:w.title)||"N/A",onSuccess:()=>{_(),f(Ft=>Ft+1)}}),j&&(S==null?void 0:S.requestId)&&e.jsx(Xb,{isOpen:j,onClose:()=>b(!1),requestId:S.requestId,levelId:($==null?void 0:$.levelId)||null,onSuccess:$r}),N&&(S==null?void 0:S.requestId)&&e.jsx(Jb,{isOpen:N,onClose:()=>A(!1),requestId:S.requestId,onSuccess:dt}),D&&(S==null?void 0:S.requestId)&&e.jsx(Qb,{isOpen:D,onClose:()=>T(!1),requestId:S.requestId,approverName:(yl=(fl=w==null?void 0:w.pauseInfo)==null?void 0:fl.pausedBy)==null?void 0:yl.name,onSuccess:Ur}),e.jsx(Zb,{showApproveModal:xe,showRejectModal:de,showAddApproverModal:lt,showAddSpectatorModal:ct,showSkipApproverModal:Zs,showActionStatusModal:W,previewDocument:Ze,documentError:xt,request:w,skipApproverData:z,actionStatus:be,existingParticipants:E,currentLevels:Ae,setShowApproveModal:ot,setShowRejectModal:Ee,setShowAddApproverModal:jt,setShowAddSpectatorModal:Ss,setShowSkipApproverModal:Xs,setShowActionStatusModal:le,setPreviewDocument:Ge,setDocumentError:Q,setSkipApproverData:ye,setActionStatus:De,handleApproveConfirm:ve,handleRejectConfirm:Fe,handleAddApprover:ke,handleAddSpectator:ls,handleSkipApprover:Be,downloadDocument:Ii,documentPolicy:He})]}):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(Re,{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(R,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(Ms,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(R,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})})}function tv(t){return e.jsx(qb,{children:e.jsx(ev,{...t})})}function sv({onViewSummary:t}){const s=pa(),[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 qy({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),te.error("Failed to load shared summaries")}finally{i(!1)}},[]);x.useEffect(()=>{y(1)},[y]);const v=async j=>{try{await Pm(j),r(b=>b.map(N=>N.sharedSummaryId===j?{...N,isRead:!0,viewedAt:new Date().toISOString()}:N)),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 N,A,D,T;if(!o)return!0;const b=o.toLowerCase();return((N=j.title)==null?void 0:N.toLowerCase().includes(b))||((A=j.requestNumber)==null?void 0:A.toLowerCase().includes(b))||((D=j.initiatorName)==null?void 0:D.toLowerCase().includes(b))||((T=j.sharedByName)==null?void 0:T.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(bs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(je,{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(Xe,{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(Re,{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(Xr,{className:"h-4 w-4 text-gray-400 flex-shrink-0"}):e.jsx(zt,{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(St,{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(St,{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(et,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Shared: ",Ne(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(zt,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Viewed: ",Ne(new Date(j.viewedAt),"MMM dd, yyyy HH:mm")]})]})]})]}),e.jsx(R,{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(R,{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(R,{variant:"outline",size:"sm",onClick:()=>C(c+1),disabled:c===m,className:"text-xs sm:text-sm",children:"Next"})]})]})]})]})})}function av(){const{sharedSummaryId:t}=Dr(),s=pa(),[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 Pm(t)}catch(p){console.warn("Failed to mark as viewed:",p)}const h=await Rm(t);r(h)}catch(h){console.error("Failed to fetch summary details:",h),te.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(Ce,{className:"h-4 w-4 text-green-600"}):m==="rejected"?e.jsx(ht,{className:"h-4 w-4 text-red-600"}):m==="pending"||m==="in progress"?e.jsx(Ue,{className:"h-4 w-4 text-orange-600"}):e.jsx(Re,{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(Xe,{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(R,{variant:"ghost",size:"sm",onClick:()=>s("/shared-summaries"),className:"mb-4",children:[e.jsx(Ms,{className:"h-4 w-4 mr-2"}),"Back to Shared Summaries"]}),e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold text-gray-900 mb-2",children:"Request Summary"})]}),e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border border-gray-200 mb-6",children:[e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-2",children:a.title}),e.jsxs("p",{className:"text-sm text-gray-600",children:["Request #",a.requestNumber]})]}),e.jsxs(ee,{className:l(a.workflow.status),children:[o(a.workflow.status),e.jsx("span",{className:"ml-1 capitalize",children:a.workflow.status})]})]}),a.description&&e.jsx("div",{className:"mb-4",children:e.jsx(oa,{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:Ne(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:Ne(new Date(d.timestamp),"MMM dd, yy, HH:mm")})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Remarks"}),e.jsx("p",{className:"text-sm text-gray-700",children:d.remarks})]})]},m))]}),e.jsxs("div",{className:"p-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Closing Remarks (Conclusion)"}),e.jsxs("div",{className:"bg-gray-50 rounded-lg p-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:a.initiator.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:c(a.initiator.designation,a.initiator.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:"Concluded"})]}),a.isAiGenerated&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Source"}),e.jsx(ee,{variant:"outline",className:"text-xs",children:"AI Generated"})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Remarks"}),a.closingRemarks?e.jsx(oa,{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(Re,{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(R,{onClick:()=>s("/shared-summaries"),children:"Go Back"})]})})}function rv(){const{requestId:t}=Dr(),s=pa(),a=i=>{s(`/${i}`)},r=()=>{s("/new-request")},n=()=>{s("/login")};return e.jsx(Xt,{currentPage:"work-notes",onNavigate:a,onNewRequest:r,onLogout:n,children:e.jsx("div",{className:"h-full w-full overflow-hidden",children:e.jsx(Vm,{requestId:t||""})})})}const So=x.createContext({});function Ao(t){const s=x.useRef(null);return s.current===null&&(s.current=t()),s.current}const ko=typeof window<"u",zm=ko?x.useLayoutEffect:x.useEffect,Dn=x.createContext(null);function To(t,s){t.indexOf(s)===-1&&t.push(s)}function Do(t,s){const a=t.indexOf(s);a>-1&&t.splice(a,1)}const Ks=(t,s,a)=>a>s?s:a<t?t:a;let Ro=()=>{};const Gs={},Hm=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function Wm(t){return typeof t=="object"&&t!==null}const Km=t=>/^0[^.\s]+$/u.test(t);function Po(t){let s;return()=>(s===void 0&&(s=t()),s)}const ws=t=>t,nv=(t,s)=>a=>s(t(a)),Er=(...t)=>t.reduce(nv),jr=(t,s,a)=>{const r=s-t;return r===0?1:(a-t)/r};class Eo{constructor(){this.subscriptions=[]}add(s){return To(this.subscriptions,s),()=>Do(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 Rs=t=>t*1e3,Ns=t=>t/1e3;function Gm(t,s){return s?t*(1e3/s):0}const Ym=(t,s,a)=>(((1-3*a+3*s)*t+(3*a-6*s))*t+3*s)*t,iv=1e-7,ov=12;function lv(t,s,a,r,n){let i,o,l=0;do o=s+(a-s)/2,i=Ym(o,r,n)-t,i>0?a=o:s=o;while(Math.abs(i)>iv&&++l<ov);return o}function Ir(t,s,a,r){if(t===s&&a===r)return ws;const n=i=>lv(i,0,1,t,a);return i=>i===0||i===1?i:Ym(n(i),s,r)}const Zm=t=>s=>s<=.5?t(2*s)/2:(2-t(2*(1-s)))/2,Xm=t=>s=>1-t(1-s),Jm=Ir(.33,1.53,.69,.99),Io=Xm(Jm),Qm=Zm(Io),qm=t=>(t*=2)<1?.5*Io(t):.5*(2-Math.pow(2,-10*(t-1))),Mo=t=>1-Math.sin(Math.acos(t)),eu=Xm(Mo),tu=Zm(Mo),cv=Ir(.42,0,1,1),dv=Ir(0,0,.58,1),su=Ir(.42,0,.58,1),mv=t=>Array.isArray(t)&&typeof t[0]!="number",au=t=>Array.isArray(t)&&typeof t[0]=="number",uv={linear:ws,easeIn:cv,easeInOut:su,easeOut:dv,circIn:Mo,circInOut:tu,circOut:eu,backIn:Io,backInOut:Qm,backOut:Jm,anticipate:qm},hv=t=>typeof t=="string",Wl=t=>{if(au(t)){Ro(t.length===4);const[s,a,r,n]=t;return Ir(s,a,r,n)}else if(hv(t))return uv[t];return t},Hr=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function pv(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 xv=40;function ru(t,s){let a=!1,r=!0;const n={delta:0,timestamp:0,isProcessing:!1},i=()=>a=!0,o=Hr.reduce((j,b)=>(j[b]=pv(i),j),{}),{setup:l,read:c,resolveKeyframes:d,preUpdate:m,update:u,preRender:h,render:p,postRender:g}=o,y=()=>{const j=Gs.useManualTiming?n.timestamp:performance.now();a=!1,Gs.useManualTiming||(n.delta=r?1e3/60:Math.max(Math.min(j-n.timestamp,xv),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:Hr.reduce((j,b)=>{const N=o[b];return j[b]=(A,D=!1,T=!1)=>(a||v(),N.schedule(A,D,T)),j},{}),cancel:j=>{for(let b=0;b<Hr.length;b++)o[Hr[b]].cancel(j)},state:n,steps:o}}const{schedule:ft,cancel:ma,state:Gt,steps:qn}=ru(typeof requestAnimationFrame<"u"?requestAnimationFrame:ws,!0);let qr;function gv(){qr=void 0}const us={now:()=>(qr===void 0&&us.set(Gt.isProcessing||Gs.useManualTiming?Gt.timestamp:performance.now()),qr),set:t=>{qr=t,queueMicrotask(gv)}},nu=t=>s=>typeof s=="string"&&s.startsWith(t),Fo=nu("--"),fv=nu("var(--"),_o=t=>fv(t)?yv.test(t.split("/*")[0].trim()):!1,yv=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,er={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},Nr={...er,transform:t=>Ks(0,1,t)},Wr={...er,default:1},ur=t=>Math.round(t*1e5)/1e5,Lo=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function bv(t){return t==null}const vv=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Oo=(t,s)=>a=>!!(typeof a=="string"&&vv.test(a)&&a.startsWith(t)||s&&!bv(a)&&Object.prototype.hasOwnProperty.call(a,s)),iu=(t,s,a)=>r=>{if(typeof r!="string")return r;const[n,i,o,l]=r.match(Lo);return{[t]:parseFloat(n),[s]:parseFloat(i),[a]:parseFloat(o),alpha:l!==void 0?parseFloat(l):1}},jv=t=>Ks(0,255,t),ei={...er,transform:t=>Math.round(jv(t))},Da={test:Oo("rgb","red"),parse:iu("red","green","blue"),transform:({red:t,green:s,blue:a,alpha:r=1})=>"rgba("+ei.transform(t)+", "+ei.transform(s)+", "+ei.transform(a)+", "+ur(Nr.transform(r))+")"};function Nv(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 _i={test:Oo("#"),parse:Nv,transform:Da.transform},Mr=t=>({test:s=>typeof s=="string"&&s.endsWith(t)&&s.split(" ").length===1,parse:parseFloat,transform:s=>`${s}${t}`}),ta=Mr("deg"),Ps=Mr("%"),Ie=Mr("px"),wv=Mr("vh"),Cv=Mr("vw"),Kl={...Ps,parse:t=>Ps.parse(t)/100,transform:t=>Ps.transform(t*100)},Oa={test:Oo("hsl","hue"),parse:iu("hue","saturation","lightness"),transform:({hue:t,saturation:s,lightness:a,alpha:r=1})=>"hsla("+Math.round(t)+", "+Ps.transform(ur(s))+", "+Ps.transform(ur(a))+", "+ur(Nr.transform(r))+")"},Lt={test:t=>Da.test(t)||_i.test(t)||Oa.test(t),parse:t=>Da.test(t)?Da.parse(t):Oa.test(t)?Oa.parse(t):_i.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?Da.transform(t):Oa.transform(t),getAnimatableNone:t=>{const s=Lt.parse(t);return s.alpha=0,Lt.transform(s)}},Sv=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function Av(t){var s,a;return isNaN(t)&&typeof t=="string"&&(((s=t.match(Lo))==null?void 0:s.length)||0)+(((a=t.match(Sv))==null?void 0:a.length)||0)>0}const ou="number",lu="color",kv="var",Tv="var(",Gl="${}",Dv=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function wr(t){const s=t.toString(),a=[],r={color:[],number:[],var:[]},n=[];let i=0;const l=s.replace(Dv,c=>(Lt.test(c)?(r.color.push(i),n.push(lu),a.push(Lt.parse(c))):c.startsWith(Tv)?(r.var.push(i),n.push(kv),a.push(c)):(r.number.push(i),n.push(ou),a.push(parseFloat(c))),++i,Gl)).split(Gl);return{values:a,split:l,indexes:r,types:n}}function cu(t){return wr(t).values}function du(t){const{split:s,types:a}=wr(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===ou?i+=ur(n[o]):l===lu?i+=Lt.transform(n[o]):i+=n[o]}return i}}const Rv=t=>typeof t=="number"?0:Lt.test(t)?Lt.getAnimatableNone(t):t;function Pv(t){const s=cu(t);return du(t)(s.map(Rv))}const ua={test:Av,parse:cu,createTransformer:du,getAnimatableNone:Pv};function ti(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 Ev({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=ti(c,l,t+1/3),i=ti(c,l,t),o=ti(c,l,t-1/3)}return{red:Math.round(n*255),green:Math.round(i*255),blue:Math.round(o*255),alpha:r}}function ln(t,s){return a=>a>0?s:t}const vt=(t,s,a)=>t+(s-t)*a,si=(t,s,a)=>{const r=t*t,n=a*(s*s-r)+r;return n<0?0:Math.sqrt(n)},Iv=[_i,Da,Oa],Mv=t=>Iv.find(s=>s.test(t));function Yl(t){const s=Mv(t);if(!s)return!1;let a=s.parse(t);return s===Oa&&(a=Ev(a)),a}const Zl=(t,s)=>{const a=Yl(t),r=Yl(s);if(!a||!r)return ln(t,s);const n={...a};return i=>(n.red=si(a.red,r.red,i),n.green=si(a.green,r.green,i),n.blue=si(a.blue,r.blue,i),n.alpha=vt(a.alpha,r.alpha,i),Da.transform(n))},Li=new Set(["none","hidden"]);function Fv(t,s){return Li.has(t)?a=>a<=0?t:s:a=>a>=1?s:t}function _v(t,s){return a=>vt(t,s,a)}function $o(t){return typeof t=="number"?_v:typeof t=="string"?_o(t)?ln:Lt.test(t)?Zl:$v:Array.isArray(t)?mu:typeof t=="object"?Lt.test(t)?Zl:Lv:ln}function mu(t,s){const a=[...t],r=a.length,n=t.map((i,o)=>$o(i)(i,s[o]));return i=>{for(let o=0;o<r;o++)a[o]=n[o](i);return a}}function Lv(t,s){const a={...t,...s},r={};for(const n in a)t[n]!==void 0&&s[n]!==void 0&&(r[n]=$o(t[n])(t[n],s[n]));return n=>{for(const i in r)a[i]=r[i](n);return a}}function Ov(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 $v=(t,s)=>{const a=ua.createTransformer(s),r=wr(t),n=wr(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?Li.has(t)&&!n.values.length||Li.has(s)&&!r.values.length?Fv(t,s):Er(mu(Ov(r,n),n.values),a):ln(t,s)};function uu(t,s,a){return typeof t=="number"&&typeof s=="number"&&typeof a=="number"?vt(t,s,a):$o(t)(t,s)}const Uv=t=>{const s=({timestamp:a})=>t(a);return{start:(a=!0)=>ft.update(s,a),stop:()=>ma(s),now:()=>Gt.isProcessing?Gt.timestamp:us.now()}},hu=(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)})`},cn=2e4;function Uo(t){let s=0;const a=50;let r=t.next(s);for(;!r.done&&s<cn;)s+=a,r=t.next(s);return s>=cn?1/0:s}function Bv(t,s=100,a){const r=a({...t,keyframes:[0,s]}),n=Math.min(Uo(r),cn);return{type:"keyframes",ease:i=>r.next(n*i).value/s,duration:Ns(n)}}const Vv=5;function pu(t,s,a){const r=Math.max(s-Vv,0);return Gm(a-t(r),s-r)}const wt={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},ai=.001;function zv({duration:t=wt.duration,bounce:s=wt.bounce,velocity:a=wt.velocity,mass:r=wt.mass}){let n,i,o=1-s;o=Ks(wt.minDamping,wt.maxDamping,o),t=Ks(wt.minDuration,wt.maxDuration,Ns(t)),o<1?(n=d=>{const m=d*o,u=m*t,h=m-a,p=Oi(d,o),g=Math.exp(-u);return ai-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=Oi(Math.pow(d,2),o);return(-n(d)+ai>0?-1:1)*((h-p)*g)/y}):(n=d=>{const m=Math.exp(-d*t),u=(d-a)*t+1;return-ai+m*u},i=d=>{const m=Math.exp(-d*t),u=(a-d)*(t*t);return m*u});const l=5/t,c=Wv(n,i,l);if(t=Rs(t),isNaN(c))return{stiffness:wt.stiffness,damping:wt.damping,duration:t};{const d=Math.pow(c,2)*r;return{stiffness:d,damping:o*2*Math.sqrt(r*d),duration:t}}}const Hv=12;function Wv(t,s,a){let r=a;for(let n=1;n<Hv;n++)r=r-t(r)/s(r);return r}function Oi(t,s){return t*Math.sqrt(1-s*s)}const Kv=["duration","bounce"],Gv=["stiffness","damping","mass"];function Xl(t,s){return s.some(a=>t[a]!==void 0)}function Yv(t){let s={velocity:wt.velocity,stiffness:wt.stiffness,damping:wt.damping,mass:wt.mass,isResolvedFromDuration:!1,...t};if(!Xl(t,Gv)&&Xl(t,Kv))if(t.visualDuration){const a=t.visualDuration,r=2*Math.PI/(a*1.2),n=r*r,i=2*Ks(.05,1,1-(t.bounce||0))*Math.sqrt(n);s={...s,mass:wt.mass,stiffness:n,damping:i}}else{const a=zv(t);s={...s,...a,mass:wt.mass},s.isResolvedFromDuration=!0}return s}function dn(t=wt.visualDuration,s=wt.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}=Yv({...a,velocity:-Ns(a.velocity||0)}),g=h||0,y=d/(2*Math.sqrt(c*m)),v=o-i,C=Ns(Math.sqrt(c/m)),f=Math.abs(v)<5;r||(r=f?wt.restSpeed.granular:wt.restSpeed.default),n||(n=f?wt.restDelta.granular:wt.restDelta.default);let j;if(y<1){const N=Oi(C,y);j=A=>{const D=Math.exp(-y*C*A);return o-D*((g+y*C*v)/N*Math.sin(N*A)+v*Math.cos(N*A))}}else if(y===1)j=N=>o-Math.exp(-C*N)*(v+(g+C*v)*N);else{const N=C*Math.sqrt(y*y-1);j=A=>{const D=Math.exp(-y*C*A),T=Math.min(N*A,300);return o-D*((g+y*C*v)*Math.sinh(T)+N*v*Math.cosh(T))/N}}const b={calculatedDuration:p&&u||null,next:N=>{const A=j(N);if(p)l.done=N>=u;else{let D=N===0?g:0;y<1&&(D=N===0?Rs(g):pu(j,N,A));const T=Math.abs(D)<=r,P=Math.abs(o-A)<=n;l.done=T&&P}return l.value=l.done?o:A,l},toString:()=>{const N=Math.min(Uo(b),cn),A=hu(D=>b.next(N*D).value,N,30);return N+"ms "+A},toTransition:()=>{}};return b}dn.applyToOptions=t=>{const s=Bv(t,100,dn);return t.ease=s.ease,t.duration=Rs(s.duration),t.type="keyframes",t};function $i({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=T=>l!==void 0&&T<l||c!==void 0&&T>c,g=T=>l===void 0?c:c===void 0||Math.abs(l-T)<Math.abs(c-T)?l:c;let y=a*s;const v=u+y,C=o===void 0?v:o(v);C!==v&&(y=C-u);const f=T=>-y*Math.exp(-T/r),j=T=>C+f(T),b=T=>{const P=f(T),w=j(T);h.done=Math.abs(P)<=d,h.value=h.done?C:w};let N,A;const D=T=>{p(h.value)&&(N=T,A=dn({keyframes:[h.value,g(h.value)],velocity:pu(j,T,h.value),damping:n,stiffness:i,restDelta:d,restSpeed:m}))};return D(0),{calculatedDuration:null,next:T=>{let P=!1;return!A&&N===void 0&&(P=!0,b(T),D(T)),N!==void 0&&T>=N?A.next(T-N):(!P&&b(T),h)}}}function Zv(t,s,a){const r=[],n=a||Gs.mix||uu,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]||ws:s;l=Er(c,l)}r.push(l)}return r}function Xv(t,s,{clamp:a=!0,ease:r,mixer:n}={}){const i=t.length;if(Ro(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=Zv(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=jr(t[u],t[u+1],m);return l[u](h)};return a?m=>d(Ks(t[0],t[i-1],m)):d}function Jv(t,s){const a=t[t.length-1];for(let r=1;r<=s;r++){const n=jr(0,s,r);t.push(vt(a,1,n))}}function Qv(t){const s=[0];return Jv(s,t.length-1),s}function qv(t,s){return t.map(a=>a*s)}function ej(t,s){return t.map(()=>s||su).splice(0,t.length-1)}function hr({duration:t=300,keyframes:s,times:a,ease:r="easeInOut"}){const n=mv(r)?r.map(Wl):Wl(r),i={done:!1,value:s[0]},o=qv(a&&a.length===s.length?a:Qv(s),t),l=Xv(o,s,{ease:Array.isArray(n)?n:ej(s,n)});return{calculatedDuration:t,next:c=>(i.value=l(c),i.done=c>=t,i)}}const tj=t=>t!==null;function Bo(t,{repeat:s,repeatType:a="loop"},r,n=1){const i=t.filter(tj),l=n<0||s&&a!=="loop"&&s%2===1?0:i.length-1;return!l||r===void 0?i[l]:r}const sj={decay:$i,inertia:$i,tween:hr,keyframes:hr,spring:dn};function xu(t){typeof t.type=="string"&&(t.type=sj[t.type])}class Vo{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 aj=t=>t/100;class zo extends Vo{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!==us.now()&&this.tick(us.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;xu(s);const{type:a=hr,repeat:r=0,repeatDelay:n=0,repeatType:i,velocity:o=0}=s;let{keyframes:l}=s;const c=a||hr;c!==hr&&typeof l[0]!="number"&&(this.mixKeyframes=Er(aj,uu(l[0],l[1])),l=[0,100]);const d=c({...s,keyframes:l});i==="mirror"&&(this.mirroredGenerator=c({...s,keyframes:[...l].reverse(),velocity:-o})),d.calculatedDuration===null&&(d.calculatedDuration=Uo(d));const{calculatedDuration:m}=d;this.calculatedDuration=m,this.resolvedDuration=m+n,this.totalDuration=this.resolvedDuration*(r+1)-n,this.generator=d}updateTime(s){const a=Math.round(s-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=a}tick(s,a=!1){const{generator:r,totalDuration:n,mixKeyframes:i,mirroredGenerator:o,resolvedDuration:l,calculatedDuration:c}=this;if(this.startTime===null)return r.next(0);const{delay:d=0,keyframes:m,repeat:u,repeatType:h,repeatDelay:p,type:g,onUpdate:y,finalKeyframe:v}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,s):this.speed<0&&(this.startTime=Math.min(s-n/this.speed,this.startTime)),a?this.currentTime=s:this.updateTime(s);const 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 T=Math.min(this.currentTime,n)/l;let P=Math.floor(T),w=T%1;!w&&T>=1&&(w=1),w===1&&P--,P=Math.min(P,u+1),!!(P%2)&&(h==="reverse"?(w=1-w,p&&(w-=p/l)):h==="mirror"&&(b=o)),j=Ks(0,1,w)*l}const N=f?{done:!1,value:m[0]}:b.next(j);i&&(N.value=i(N.value));let{done:A}=N;!f&&c!==null&&(A=this.playbackSpeed>=0?this.currentTime>=n:this.currentTime<=0);const D=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&A);return D&&g!==$i&&(N.value=Bo(m,this.options,v,this.speed)),y&&y(N.value),D&&this.finish(),N}then(s,a){return this.finished.then(s,a)}get duration(){return Ns(this.calculatedDuration)}get iterationDuration(){const{delay:s=0}=this.options||{};return this.duration+Ns(s)}get time(){return Ns(this.currentTime)}set time(s){var a;s=Rs(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(us.now());const a=this.playbackSpeed!==s;this.playbackSpeed=s,a&&(this.time=Ns(this.currentTime))}play(){var n,i;if(this.isStopped)return;const{driver:s=Uv,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(us.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 rj(t){for(let s=1;s<t.length;s++)t[s]??(t[s]=t[s-1])}const Ra=t=>t*180/Math.PI,Ui=t=>{const s=Ra(Math.atan2(t[1],t[0]));return Bi(s)},nj={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=>Ra(Math.atan(t[1])),skewY:t=>Ra(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},Bi=t=>(t=t%360,t<0&&(t+=360),t),Jl=Ui,Ql=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),ql=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),ij={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Ql,scaleY:ql,scale:t=>(Ql(t)+ql(t))/2,rotateX:t=>Bi(Ra(Math.atan2(t[6],t[5]))),rotateY:t=>Bi(Ra(Math.atan2(-t[2],t[0]))),rotateZ:Jl,rotate:Jl,skewX:t=>Ra(Math.atan(t[4])),skewY:t=>Ra(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function Vi(t){return t.includes("scale")?1:0}function zi(t,s){if(!t||t==="none")return Vi(s);const a=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,n;if(a)r=ij,n=a;else{const l=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=nj,n=l}if(!n)return Vi(s);const i=r[s],o=n[1].split(",").map(lj);return typeof i=="function"?i(o):o[i]}const oj=(t,s)=>{const{transform:a="none"}=getComputedStyle(t);return zi(a,s)};function lj(t){return parseFloat(t.trim())}const tr=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],sr=new Set(tr),ec=t=>t===er||t===Ie,cj=new Set(["x","y","z"]),dj=tr.filter(t=>!cj.has(t));function mj(t){const s=[];return dj.forEach(a=>{const r=t.getValue(a);r!==void 0&&(s.push([a,r.get()]),r.set(a.startsWith("scale")?1:0))}),s}const Ea={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})=>zi(s,"x"),y:(t,{transform:s})=>zi(s,"y")};Ea.translateX=Ea.x;Ea.translateY=Ea.y;const Ia=new Set;let Hi=!1,Wi=!1,Ki=!1;function gu(){if(Wi){const t=Array.from(Ia).filter(r=>r.needsMeasurement),s=new Set(t.map(r=>r.element)),a=new Map;s.forEach(r=>{const n=mj(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)})}Wi=!1,Hi=!1,Ia.forEach(t=>t.complete(Ki)),Ia.clear()}function fu(){Ia.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(Wi=!0)})}function uj(){Ki=!0,fu(),gu(),Ki=!1}class Ho{constructor(s,a,r,n,i,o=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...s],this.onComplete=a,this.name=r,this.motionValue=n,this.element=i,this.isAsync=o}scheduleResolve(){this.state="scheduled",this.isAsync?(Ia.add(this),Hi||(Hi=!0,ft.read(fu),ft.resolveKeyframes(gu))):(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])}rj(s)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(s=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,s),Ia.delete(this)}cancel(){this.state==="scheduled"&&(Ia.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const hj=t=>t.startsWith("--");function pj(t,s,a){hj(s)?t.style.setProperty(s,a):t.style[s]=a}const xj=Po(()=>window.ScrollTimeline!==void 0),gj={};function fj(t,s){const a=Po(t);return()=>gj[s]??a()}const yu=fj(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),mr=([t,s,a,r])=>`cubic-bezier(${t}, ${s}, ${a}, ${r})`,tc={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:mr([0,.65,.55,1]),circOut:mr([.55,0,1,.45]),backIn:mr([.31,.01,.66,-.59]),backOut:mr([.33,1.53,.69,.99])};function bu(t,s){if(t)return typeof t=="function"?yu()?hu(t,s):"ease-out":au(t)?mr(t):Array.isArray(t)?t.map(a=>bu(a,s)||tc.easeOut):tc[t]}function yj(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=bu(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 vu(t){return typeof t=="function"&&"applyToOptions"in t}function bj({type:t,...s}){return vu(t)&&yu()?t.applyToOptions(s):(s.duration??(s.duration=300),s.ease??(s.ease="easeOut"),s)}class vj extends Vo{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,Ro(typeof s.type!="string");const d=bj(s);this.animation=yj(a,r,n,d,i),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const m=Bo(n,this.options,l,this.speed);this.updateMotionValue?this.updateMotionValue(m):pj(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 Ns(Number(s))}get iterationDuration(){const{delay:s=0}=this.options||{};return this.duration+Ns(s)}get time(){return Ns(Number(this.animation.currentTime)||0)}set time(s){this.finishedTime=null,this.animation.currentTime=Rs(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&&xj()?(this.animation.timeline=s,ws):a(this)}}const ju={anticipate:qm,backInOut:Qm,circInOut:tu};function jj(t){return t in ju}function Nj(t){typeof t.ease=="string"&&jj(t.ease)&&(t.ease=ju[t.ease])}const sc=10;class wj extends vj{constructor(s){Nj(s),xu(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 zo({...o,autoplay:!1}),c=Rs(this.finishedTime??this.time);a.setWithVelocity(l.sample(c-sc).value,l.sample(c).value,sc),l.stop()}}const ac=(t,s)=>s==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(ua.test(t)||t==="0")&&!t.startsWith("url("));function Cj(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 Sj(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=ac(n,s),l=ac(i,s);return!o||!l?!1:Cj(t)||(a==="spring"||vu(a))&&r}function Gi(t){t.duration=0,t.type="keyframes"}const Aj=new Set(["opacity","clipPath","filter","transform"]),kj=Po(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function Tj(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 kj()&&a&&Aj.has(a)&&(a!=="transform"||!d)&&!c&&!r&&n!=="mirror"&&i!==0&&o!=="inertia"}const Dj=40;class Rj extends Vo{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=us.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)||Ho;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=us.now(),Sj(s,i,o,l)||((Gs.instantAnimations||!c)&&(m==null||m(Bo(s,r,a))),s[0]=s[s.length-1],Gi(r),r.repeat=0);const h={startTime:n?this.resolvedAt?this.resolvedAt-this.createdAt>Dj?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:a,...r,keyframes:s},p=!d&&Tj(h)?new wj({...h,element:h.motionValue.owner.current}):new zo(h);p.finished.then(()=>this.notifyFinished()).catch(ws),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(),uj()),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 Pj=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function Ej(t){const s=Pj.exec(t);if(!s)return[,];const[,a,r,n]=s;return[`--${a??r}`,n]}function Nu(t,s,a=1){const[r,n]=Ej(t);if(!r)return;const i=window.getComputedStyle(s).getPropertyValue(r);if(i){const o=i.trim();return Hm(o)?parseFloat(o):o}return _o(n)?Nu(n,s,a+1):n}function Wo(t,s){return(t==null?void 0:t[s])??(t==null?void 0:t.default)??t}const wu=new Set(["width","height","top","left","right","bottom",...tr]),Ij={test:t=>t==="auto",parse:t=>t},Cu=t=>s=>s.test(t),Su=[er,Ie,Ps,ta,Cv,wv,Ij],rc=t=>Su.find(Cu(t));function Mj(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||Km(t):!0}const Fj=new Set(["brightness","contrast","saturate","opacity"]);function _j(t){const[s,a]=t.slice(0,-1).split("(");if(s==="drop-shadow")return t;const[r]=a.match(Lo)||[];if(!r)return t;const n=a.replace(r,"");let i=Fj.has(s)?1:0;return r!==a&&(i*=100),s+"("+i+n+")"}const Lj=/\b([a-z-]*)\(.*?\)/gu,Yi={...ua,getAnimatableNone:t=>{const s=t.match(Lj);return s?s.map(_j).join(" "):t}},nc={...er,transform:Math.round},Oj={rotate:ta,rotateX:ta,rotateY:ta,rotateZ:ta,scale:Wr,scaleX:Wr,scaleY:Wr,scaleZ:Wr,skew:ta,skewX:ta,skewY:ta,distance:Ie,translateX:Ie,translateY:Ie,translateZ:Ie,x:Ie,y:Ie,z:Ie,perspective:Ie,transformPerspective:Ie,opacity:Nr,originX:Kl,originY:Kl,originZ:Ie},Ko={borderWidth:Ie,borderTopWidth:Ie,borderRightWidth:Ie,borderBottomWidth:Ie,borderLeftWidth:Ie,borderRadius:Ie,radius:Ie,borderTopLeftRadius:Ie,borderTopRightRadius:Ie,borderBottomRightRadius:Ie,borderBottomLeftRadius:Ie,width:Ie,maxWidth:Ie,height:Ie,maxHeight:Ie,top:Ie,right:Ie,bottom:Ie,left:Ie,padding:Ie,paddingTop:Ie,paddingRight:Ie,paddingBottom:Ie,paddingLeft:Ie,margin:Ie,marginTop:Ie,marginRight:Ie,marginBottom:Ie,marginLeft:Ie,backgroundPositionX:Ie,backgroundPositionY:Ie,...Oj,zIndex:nc,fillOpacity:Nr,strokeOpacity:Nr,numOctaves:nc},$j={...Ko,color:Lt,backgroundColor:Lt,outlineColor:Lt,fill:Lt,stroke:Lt,borderColor:Lt,borderTopColor:Lt,borderRightColor:Lt,borderBottomColor:Lt,borderLeftColor:Lt,filter:Yi,WebkitFilter:Yi},Au=t=>$j[t];function ku(t,s){let a=Au(t);return a!==Yi&&(a=ua),a.getAnimatableNone?a.getAnimatableNone(s):void 0}const Uj=new Set(["auto","none","0"]);function Bj(t,s,a){let r=0,n;for(;r<t.length&&!n;){const i=t[r];typeof i=="string"&&!Uj.has(i)&&wr(i).values.length&&(n=t[r]),r++}if(n&&a)for(const i of s)t[i]=ku(a,n)}class Vj extends Ho{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(),_o(d))){const m=Nu(d,a.current);m!==void 0&&(s[c]=m),c===s.length-1&&(this.finalKeyframe=d)}}if(this.resolveNoneKeyframes(),!wu.has(r)||s.length!==2)return;const[n,i]=s,o=rc(n),l=rc(i);if(o!==l)if(ec(o)&&ec(l))for(let c=0;c<s.length;c++){const d=s[c];typeof d=="string"&&(s[c]=parseFloat(d))}else Ea[r]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:s,name:a}=this,r=[];for(let n=0;n<s.length;n++)(s[n]===null||Mj(s[n]))&&r.push(n);r.length&&Bj(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=Ea[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]=Ea[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 zj(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 Tu=(t,s)=>s&&typeof t=="number"?s.transform(t):t;function Du(t){return Wm(t)&&"offsetHeight"in t}const ic=30,Hj=t=>!isNaN(parseFloat(t));class Wj{constructor(s,a={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=r=>{var i;const n=us.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=us.now(),this.canTrackVelocity===null&&s!==void 0&&(this.canTrackVelocity=Hj(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 Eo);const r=this.events[s].add(a);return s==="change"?()=>{r(),ft.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=us.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||s-this.updatedAt>ic)return 0;const a=Math.min(this.updatedAt-this.prevUpdatedAt,ic);return Gm(parseFloat(this.current)-parseFloat(this.prevFrameValue),a)}start(s){return this.stop(),new Promise(a=>{this.hasAnimated=!0,this.animation=s(a),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){var s,a;(s=this.dependents)==null||s.clear(),(a=this.events.destroy)==null||a.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function Ka(t,s){return new Wj(t,s)}const{schedule:Go}=ru(queueMicrotask,!1),As={x:!1,y:!1};function Ru(){return As.x||As.y}function Kj(t){return t==="x"||t==="y"?As[t]?null:(As[t]=!0,()=>{As[t]=!1}):As.x||As.y?null:(As.x=As.y=!0,()=>{As.x=As.y=!1})}function Pu(t,s){const a=zj(t),r=new AbortController,n={passive:!0,...s,signal:r.signal};return[a,n,()=>r.abort()]}function oc(t){return!(t.pointerType==="touch"||Ru())}function Gj(t,s,a={}){const[r,n,i]=Pu(t,a),o=l=>{if(!oc(l))return;const{target:c}=l,d=s(c,l);if(typeof d!="function"||!c)return;const m=u=>{oc(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,Yo=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,Yj=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Zj(t){return Yj.has(t.tagName)||t.tabIndex!==-1}const en=new WeakSet;function lc(t){return s=>{s.key==="Enter"&&t(s)}}function ri(t,s){t.dispatchEvent(new PointerEvent("pointer"+s,{isPrimary:!0,bubbles:!0}))}const Xj=(t,s)=>{const a=t.currentTarget;if(!a)return;const r=lc(()=>{if(en.has(a))return;ri(a,"down");const n=lc(()=>{ri(a,"up")}),i=()=>ri(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 cc(t){return Yo(t)&&!Ru()}function Jj(t,s,a={}){const[r,n,i]=Pu(t,a),o=l=>{const c=l.currentTarget;if(!cc(l))return;en.add(c);const d=s(c,l),m=(p,g)=>{window.removeEventListener("pointerup",u),window.removeEventListener("pointercancel",h),en.has(c)&&en.delete(c),cc(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),Du(l)&&(l.addEventListener("focus",d=>Xj(d,n)),!Zj(l)&&!l.hasAttribute("tabindex")&&(l.tabIndex=0))}),i}function Iu(t){return Wm(t)&&"ownerSVGElement"in t}function Qj(t){return Iu(t)&&t.tagName==="svg"}const Jt=t=>!!(t&&t.getVelocity),qj=[...Su,Lt,ua],eN=t=>qj.find(Cu(t)),Zo=x.createContext({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});function dc(t,s){if(typeof t=="function")return t(s);t!=null&&(t.current=s)}function tN(...t){return s=>{let a=!1;const r=t.map(n=>{const i=dc(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():dc(t[n],null)}}}}function sN(...t){return x.useCallback(tN(...t),t)}class aN extends x.Component{getSnapshotBeforeUpdate(s){const a=this.props.childRef.current;if(a&&s.isPresent&&!this.props.isPresent){const r=a.offsetParent,n=Du(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 rN({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(Zo),c=sN(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(aN,{isPresent:s,childRef:i,sizeRef:o,children:x.cloneElement(t,{ref:c})})}const nN=({children:t,initial:s,isPresent:a,onExitComplete:r,custom:n,presenceAffectsLayout:i,mode:o,anchorX:l,root:c})=>{const d=Ao(iN),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(rN,{isPresent:a,anchorX:l,root:c,children:t})),e.jsx(Dn.Provider,{value:h,children:t})};function iN(){return new Map}function Mu(t=!0){const s=x.useContext(Dn);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 Kr=t=>t.key||"";function mc(t){const s=[];return x.Children.forEach(t,a=>{x.isValidElement(a)&&s.push(a)}),s}const Rn=({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]=Mu(o),u=x.useMemo(()=>mc(t),[t]),h=o&&!d?[]:u.map(Kr),p=x.useRef(!0),g=x.useRef(u),y=Ao(()=>new Map),[v,C]=x.useState(u),[f,j]=x.useState(u);zm(()=>{p.current=!1,g.current=u;for(let A=0;A<f.length;A++){const D=Kr(f[A]);h.includes(D)?y.delete(D):y.get(D)!==!0&&y.set(D,!1)}},[f,h.length,h.join("-")]);const b=[];if(u!==v){let A=[...u];for(let D=0;D<f.length;D++){const T=f[D],P=Kr(T);h.includes(P)||(A.splice(D,0,T),b.push(T))}return i==="wait"&&b.length&&(A=b),j(mc(A)),C(u),null}const{forceRender:N}=x.useContext(So);return e.jsx(e.Fragment,{children:f.map(A=>{const D=Kr(A),T=o&&!d?!1:u===f||h.includes(D),P=()=>{if(y.has(D))y.set(D,!0);else return;let w=!0;y.forEach(S=>{S||(w=!1)}),w&&(N==null||N(),j(g.current),o&&(m==null||m()),r&&r())};return e.jsx(nN,{isPresent:T,initial:!p.current||a?void 0:!1,custom:s,presenceAffectsLayout:n,mode:i,root:c,onExitComplete:T?void 0:P,anchorX:l,children:A},D)})})},Fu=x.createContext({strict:!1}),uc={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"]},Ga={};for(const t in uc)Ga[t]={isEnabled:s=>uc[t].some(a=>!!s[a])};function oN(t){for(const s in t)Ga[s]={...Ga[s],...t[s]}}const lN=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 mn(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||lN.has(t)}let _u=t=>!mn(t);function cN(t){typeof t=="function"&&(_u=s=>s.startsWith("on")?!mn(s):t(s))}try{cN(require("@emotion/is-prop-valid").default)}catch{}function dN(t,s,a){const r={};for(const n in t)n==="values"&&typeof t.values=="object"||(_u(n)||a===!0&&mn(n)||!s&&!mn(n)||t.draggable&&n.startsWith("onDrag"))&&(r[n]=t[n]);return r}const Pn=x.createContext({});function En(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function Cr(t){return typeof t=="string"||Array.isArray(t)}const Xo=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Jo=["initial",...Xo];function In(t){return En(t.animate)||Jo.some(s=>Cr(t[s]))}function Lu(t){return!!(In(t)||t.variants)}function mN(t,s){if(In(t)){const{initial:a,animate:r}=t;return{initial:a===!1||Cr(a)?a:void 0,animate:Cr(r)?r:void 0}}return t.inherit!==!1?s:{}}function uN(t){const{initial:s,animate:a}=mN(t,x.useContext(Pn));return x.useMemo(()=>({initial:s,animate:a}),[hc(s),hc(a)])}function hc(t){return Array.isArray(t)?t.join(" "):t}const Sr={};function hN(t){for(const s in t)Sr[s]=t[s],Fo(s)&&(Sr[s].isCSSVariable=!0)}function Ou(t,{layout:s,layoutId:a}){return sr.has(t)||t.startsWith("origin")||(s||a!==void 0)&&(!!Sr[t]||t==="opacity")}const pN={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},xN=tr.length;function gN(t,s,a){let r="",n=!0;for(let i=0;i<xN;i++){const o=tr[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=Tu(l,Ko[o]);if(!c){n=!1;const m=pN[o]||o;r+=`${m}(${d}) `}a&&(s[o]=d)}}return r=r.trim(),a?r=a(s,n?"":r):n&&(r="none"),r}function Qo(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(sr.has(c)){o=!0;continue}else if(Fo(c)){n[c]=d;continue}else{const m=Tu(d,Ko[c]);c.startsWith("origin")?(l=!0,i[c]=m):r[c]=m}}if(s.transform||(o||a?r.transform=gN(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 qo=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function $u(t,s,a){for(const r in s)!Jt(s[r])&&!Ou(r,a)&&(t[r]=s[r])}function fN({transformTemplate:t},s){return x.useMemo(()=>{const a=qo();return Qo(a,s,t),Object.assign({},a.vars,a.style)},[s])}function yN(t,s){const a=t.style||{},r={};return $u(r,a,t),Object.assign(r,fN(t,s)),r}function bN(t,s){const a={},r=yN(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 vN={offset:"stroke-dashoffset",array:"stroke-dasharray"},jN={offset:"strokeDashoffset",array:"strokeDasharray"};function NN(t,s,a=1,r=0,n=!0){t.pathLength=1;const i=n?vN:jN;t[i.offset]=Ie.transform(-r);const o=Ie.transform(s),l=Ie.transform(a);t[i.array]=`${o} ${l}`}function Uu(t,{attrX:s,attrY:a,attrScale:r,pathLength:n,pathSpacing:i=1,pathOffset:o=0,...l},c,d,m){if(Qo(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&&NN(u,n,i,o,!1)}const Bu=()=>({...qo(),attrs:{}}),Vu=t=>typeof t=="string"&&t.toLowerCase()==="svg";function wN(t,s,a,r){const n=x.useMemo(()=>{const i=Bu();return Uu(i,s,Vu(r),t.transformTemplate,t.style),{...i.attrs,style:{...i.style}}},[s]);if(t.style){const i={};$u(i,t.style,t),n.style={...i,...n.style}}return n}const CN=["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 el(t){return typeof t!="string"||t.includes("-")?!1:!!(CN.indexOf(t)>-1||/[A-Z]/u.test(t))}function SN(t,s,a,{latestValues:r},n,i=!1){const l=(el(t)?wN:bN)(s,r,n,t),c=dN(s,typeof t=="string",i),d=t!==x.Fragment?{...c,...l,ref:a}:{},{children:m}=s,u=x.useMemo(()=>Jt(m)?m.get():m,[m]);return x.createElement(t,{...d,children:u})}function pc(t){const s=[{},{}];return t==null||t.values.forEach((a,r)=>{s[0][r]=a.get(),s[1][r]=a.getVelocity()}),s}function tl(t,s,a,r){if(typeof s=="function"){const[n,i]=pc(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]=pc(r);s=s(a!==void 0?a:t.custom,n,i)}return s}function tn(t){return Jt(t)?t.get():t}function AN({scrapeMotionValuesFromProps:t,createRenderState:s},a,r,n){return{latestValues:kN(a,r,n,t),renderState:s()}}function kN(t,s,a,r){const n={},i=r(t,{});for(const h in i)n[h]=tn(i[h]);let{initial:o,animate:l}=t;const c=In(t),d=Lu(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"&&!En(u)){const h=Array.isArray(u)?u:[u];for(let p=0;p<h.length;p++){const g=tl(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 zu=t=>(s,a)=>{const r=x.useContext(Pn),n=x.useContext(Dn),i=()=>AN(t,s,r,n);return a?i():Ao(i)};function sl(t,s,a){var i;const{style:r}=t,n={};for(const o in r)(Jt(r[o])||s.style&&Jt(s.style[o])||Ou(o,t)||((i=a==null?void 0:a.getValue(o))==null?void 0:i.liveStyle)!==void 0)&&(n[o]=r[o]);return n}const TN=zu({scrapeMotionValuesFromProps:sl,createRenderState:qo});function Hu(t,s,a){const r=sl(t,s,a);for(const n in t)if(Jt(t[n])||Jt(s[n])){const i=tr.indexOf(n)!==-1?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n;r[i]=t[n]}return r}const DN=zu({scrapeMotionValuesFromProps:Hu,createRenderState:Bu}),RN=Symbol.for("motionComponentSymbol");function $a(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function PN(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):$a(a)&&(a.current=r))},[s])}const al=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),EN="framerAppearId",Wu="data-"+al(EN),Ku=x.createContext({});function IN(t,s,a,r,n){var y,v;const{visualElement:i}=x.useContext(Pn),o=x.useContext(Fu),l=x.useContext(Dn),c=x.useContext(Zo).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(Ku);m&&!m.projection&&n&&(m.type==="html"||m.type==="svg")&&MN(d.current,a,n,u);const h=x.useRef(!1);x.useInsertionEffect(()=>{m&&h.current&&m.update(a,l)});const p=a[Wu],g=x.useRef(!!p&&!((y=window.MotionHandoffIsComplete)!=null&&y.call(window,p))&&((v=window.MotionHasOptimisedAnimation)==null?void 0:v.call(window,p)));return zm(()=>{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 MN(t,s,a,r){const{layoutId:n,layout:i,drag:o,dragConstraints:l,layoutScroll:c,layoutRoot:d,layoutCrossfade:m}=s;t.projection=new a(t.latestValues,s["data-framer-portal-id"]?void 0:Gu(t.parent)),t.projection.setOptions({layoutId:n,layout:i,alwaysMeasureLayout:!!o||l&&$a(l),visualElement:t,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:m,layoutScroll:c,layoutRoot:d})}function Gu(t){if(t)return t.options.allowProjection!==!1?t.projection:Gu(t.parent)}function ni(t,{forwardMotionProps:s=!1}={},a,r){a&&oN(a);const n=el(t)?DN:TN;function i(l,c){let d;const m={...x.useContext(Zo),...l,layoutId:FN(l)},{isStatic:u}=m,h=uN(l),p=n(l,u);if(!u&&ko){_N();const g=LN(m);d=g.MeasureLayout,h.visualElement=IN(t,p,m,r,g.ProjectionNode)}return e.jsxs(Pn.Provider,{value:h,children:[d&&h.visualElement?e.jsx(d,{visualElement:h.visualElement,...m}):null,SN(t,l,PN(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[RN]=t,o}function FN({layoutId:t}){const s=x.useContext(So).id;return s&&t!==void 0?s+"-"+t:t}function _N(t,s){x.useContext(Fu).strict}function LN(t){const{drag:s,layout:a}=Ga;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 ON(t,s){if(typeof Proxy>"u")return ni;const a=new Map,r=(i,o)=>ni(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,ni(o,void 0,t,s)),a.get(o))})}function Yu({top:t,left:s,right:a,bottom:r}){return{x:{min:s,max:a},y:{min:t,max:r}}}function $N({x:t,y:s}){return{top:s.min,right:t.max,bottom:s.max,left:t.min}}function UN(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 ii(t){return t===void 0||t===1}function Zi({scale:t,scaleX:s,scaleY:a}){return!ii(t)||!ii(s)||!ii(a)}function wa(t){return Zi(t)||Zu(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function Zu(t){return xc(t.x)||xc(t.y)}function xc(t){return t&&t!=="0%"}function un(t,s,a){const r=t-a,n=s*r;return a+n}function gc(t,s,a,r,n){return n!==void 0&&(t=un(t,n,r)),un(t,a,r)+s}function Xi(t,s=0,a=1,r,n){t.min=gc(t.min,s,a,r,n),t.max=gc(t.max,s,a,r,n)}function Xu(t,{x:s,y:a}){Xi(t.x,s.translate,s.scale,s.originPoint),Xi(t.y,a.translate,a.scale,a.originPoint)}const fc=.999999999999,yc=1.0000000000001;function BN(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&&Ba(t,{x:-i.scroll.offset.x,y:-i.scroll.offset.y}),o&&(s.x*=o.x.scale,s.y*=o.y.scale,Xu(t,o)),r&&wa(i.latestValues)&&Ba(t,i.latestValues))}s.x<yc&&s.x>fc&&(s.x=1),s.y<yc&&s.y>fc&&(s.y=1)}function Ua(t,s){t.min=t.min+s,t.max=t.max+s}function bc(t,s,a,r,n=.5){const i=vt(t.min,t.max,n);Xi(t,s,a,i,r)}function Ba(t,s){bc(t.x,s.x,s.scaleX,s.scale,s.originX),bc(t.y,s.y,s.scaleY,s.scale,s.originY)}function Ju(t,s){return Yu(UN(t.getBoundingClientRect(),s))}function VN(t,s,a){const r=Ju(t,a),{scroll:n}=s;return n&&(Ua(r.x,n.offset.x),Ua(r.y,n.offset.y)),r}const vc=()=>({translate:0,scale:1,origin:0,originPoint:0}),Va=()=>({x:vc(),y:vc()}),jc=()=>({min:0,max:0}),Pt=()=>({x:jc(),y:jc()}),Ji={current:null},Qu={current:!1};function zN(){if(Qu.current=!0,!!ko)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),s=()=>Ji.current=t.matches;t.addEventListener("change",s),s()}else Ji.current=!1}const HN=new WeakMap;function WN(t,s,a){for(const r in s){const n=s[r],i=a[r];if(Jt(n))t.addValue(r,n);else if(Jt(i))t.addValue(r,Ka(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,Ka(o!==void 0?o:n,{owner:t}))}}for(const r in a)s[r]===void 0&&t.removeValue(r);return s}const Nc=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class KN{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=Ho,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=us.now();this.renderScheduledAt<h&&(this.renderScheduledAt=h,ft.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=In(a),this.isVariantNode=Lu(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&&Jt(p)&&p.set(c[h])}}mount(s){var a;this.current=s,HN.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)),Qu.current||zN(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Ji.current,(a=this.parent)==null||a.addChild(this),this.update(this.props,this.presenceContext)}unmount(){var s;this.projection&&this.projection.unmount(),ma(this.notifyUpdate),ma(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=sr.has(s);r&&this.onBindTransform&&this.onBindTransform();const n=a.on("change",o=>{this.latestValues[s]=o,this.props.onUpdate&&ft.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 Ga){const a=Ga[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):Pt()}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<Nc.length;r++){const n=Nc[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=WN(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=Ka(a===null?void 0:a,{owner:this}),this.addValue(s,r)),r}readValue(s,a){let r=this.latestValues[s]!==void 0||!this.current?this.latestValues[s]:this.getBaseTargetFromProps(this.props,s)??this.readValueFromInstance(this.current,s,this.options);return r!=null&&(typeof r=="string"&&(Hm(r)||Km(r))?r=parseFloat(r):!eN(r)&&ua.test(a)&&(r=ku(s,a)),this.setBaseTarget(s,Jt(r)?r.get():r)),Jt(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=tl(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&&!Jt(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 Eo),this.events[s].add(a)}notify(s,...a){this.events[s]&&this.events[s].notify(...a)}scheduleRenderMicrotask(){Go.render(this.render)}}class qu extends KN{constructor(){super(...arguments),this.KeyframeResolver=Vj}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;Jt(s)&&(this.childSubscription=s.on("change",a=>{this.current&&(this.current.textContent=`${a}`)}))}}function eh(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 GN(t){return window.getComputedStyle(t)}class YN extends qu{constructor(){super(...arguments),this.type="html",this.renderInstance=eh}readValueFromInstance(s,a){var r;if(sr.has(a))return(r=this.projection)!=null&&r.isProjecting?Vi(a):oj(s,a);{const n=GN(s),i=(Fo(a)?n.getPropertyValue(a):n[a])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(s,{transformPagePoint:a}){return Ju(s,a)}build(s,a,r){Qo(s,a,r.transformTemplate)}scrapeMotionValuesFromProps(s,a,r){return sl(s,a,r)}}const th=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 ZN(t,s,a,r){eh(t,s,void 0,r);for(const n in s.attrs)t.setAttribute(th.has(n)?n:al(n),s.attrs[n])}class XN extends qu{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Pt}getBaseTargetFromProps(s,a){return s[a]}readValueFromInstance(s,a){if(sr.has(a)){const r=Au(a);return r&&r.default||0}return a=th.has(a)?a:al(a),s.getAttribute(a)}scrapeMotionValuesFromProps(s,a,r){return Hu(s,a,r)}build(s,a,r){Uu(s,a,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(s,a,r,n){ZN(s,a,r,n)}mount(s){this.isSVGTag=Vu(s.tagName),super.mount(s)}}const JN=(t,s)=>el(t)?new XN(s):new YN(s,{allowProjection:t!==x.Fragment});function Wa(t,s,a){const r=t.getProps();return tl(r,s,a!==void 0?a:r.custom,t)}const Qi=t=>Array.isArray(t);function QN(t,s,a){t.hasValue(s)?t.getValue(s).set(a):t.addValue(s,Ka(a))}function qN(t){return Qi(t)?t[t.length-1]||0:t}function ew(t,s){const a=Wa(t,s);let{transitionEnd:r={},transition:n={},...i}=a||{};i={...i,...r};for(const o in i){const l=qN(i[o]);QN(t,o,l)}}function tw(t){return!!(Jt(t)&&t.add)}function qi(t,s){const a=t.getValue("willChange");if(tw(a))return a.add(s);if(!a&&Gs.WillChange){const r=new Gs.WillChange("auto");t.addValue("willChange",r),r.add(s)}}function sh(t){return t.props[Wu]}const sw=t=>t!==null;function aw(t,{repeat:s,repeatType:a="loop"},r){const n=t.filter(sw),i=s&&a!=="loop"&&s%2===1?0:n.length-1;return n[i]}const rw={type:"spring",stiffness:500,damping:25,restSpeed:10},nw=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),iw={type:"keyframes",duration:.8},ow={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},lw=(t,{keyframes:s})=>s.length>2?iw:sr.has(t)?t.startsWith("scale")?nw(s[1]):rw:ow;function cw({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 rl=(t,s,a,r={},n,i)=>o=>{const l=Wo(r,t)||{},c=l.delay||r.delay||0;let{elapsed:d=0}=r;d=d-Rs(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};cw(l)||Object.assign(m,lw(t,m)),m.duration&&(m.duration=Rs(m.duration)),m.repeatDelay&&(m.repeatDelay=Rs(m.repeatDelay)),m.from!==void 0&&(m.keyframes[0]=m.from);let u=!1;if((m.type===!1||m.duration===0&&!m.repeatDelay)&&(Gi(m),m.delay===0&&(u=!0)),(Gs.instantAnimations||Gs.skipAnimations)&&(u=!0,Gi(m),m.delay=0),m.allowFlatten=!l.type&&!l.ease,u&&!i&&s.get()!==void 0){const h=aw(m.keyframes,l);if(h!==void 0){ft.update(()=>{m.onUpdate(h),m.onComplete()});return}}return l.isSync?new zo(m):new Rj(m)};function dw({protectedKeys:t,needsAnimating:s},a){const r=t.hasOwnProperty(a)&&s[a]!==!0;return s[a]=!1,r}function ah(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&&dw(d,m))continue;const p={delay:a,...Wo(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=sh(t);if(C){const f=window.MotionHandoffAnimation(C,m,ft);f!==null&&(p.startTime=f,y=!0)}}qi(t,m),u.start(rl(m,u,h,t.shouldReduceMotion&&wu.has(m)?{type:!1}:p,t,y));const v=u.animation;v&&c.push(v)}return o&&Promise.all(c).then(()=>{ft.update(()=>{o&&ew(t,o)})}),c}function rh(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 eo(t,s,a={}){var c;const r=Wa(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(ah(t,r,a)):()=>Promise.resolve(),o=t.variantChildren&&t.variantChildren.size?(d=0)=>{const{delayChildren:m=0,staggerChildren:u,staggerDirection:h}=n;return mw(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 mw(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(eo(c,s,{...o,delay:a+(typeof r=="function"?0:r)+rh(t.variantChildren,c,r,n,i)}).then(()=>c.notify("AnimationComplete",s)));return Promise.all(l)}function uw(t,s,a={}){t.notify("AnimationStart",s);let r;if(Array.isArray(s)){const n=s.map(i=>eo(t,i,a));r=Promise.all(n)}else if(typeof s=="string")r=eo(t,s,a);else{const n=typeof s=="function"?Wa(t,s,a.custom):s;r=Promise.all(ah(t,n,a))}return r.then(()=>{t.notify("AnimationComplete",s)})}function nh(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 hw=Jo.length;function ih(t){if(!t)return;if(!t.isControllingVariants){const a=t.parent?ih(t.parent)||{}:{};return t.props.initial!==void 0&&(a.initial=t.props.initial),a}const s={};for(let a=0;a<hw;a++){const r=Jo[a],n=t.props[r];(Cr(n)||n===!1)&&(s[r]=n)}return s}const pw=[...Xo].reverse(),xw=Xo.length;function gw(t){return s=>Promise.all(s.map(({animation:a,options:r})=>uw(t,a,r)))}function fw(t){let s=gw(t),a=wc(),r=!0;const n=c=>(d,m)=>{var h;const u=Wa(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=ih(t.parent)||{},u=[],h=new Set;let p={},g=1/0;for(let v=0;v<xw;v++){const C=pw[v],f=a[C],j=d[C]!==void 0?d[C]:m[C],b=Cr(j),N=C===c?f.isActive:null;N===!1&&(g=v);let A=j===m[C]&&j!==d[C]&&b;if(A&&r&&t.manuallyAnimateOnMount&&(A=!1),f.protectedKeys={...p},!f.isActive&&N===null||!j&&!f.prevProp||En(j)||typeof j=="boolean")continue;const D=yw(f.prevProp,j);let T=D||C===c&&f.isActive&&!A&&b||v>g&&b,P=!1;const w=Array.isArray(j)?j:[j];let S=w.reduce(n(C),{});N===!1&&(S={});const{prevResolvedValues:M={}}=f,B={...M,...S},_=I=>{T=!0,h.has(I)&&(P=!0,h.delete(I)),f.needsAnimating[I]=!0;const E=t.getValue(I);E&&(E.liveStyle=!1)};for(const I in B){const E=S[I],F=M[I];if(p.hasOwnProperty(I))continue;let O=!1;Qi(E)&&Qi(F)?O=!nh(E,F):O=E!==F,O?E!=null?_(I):h.add(I):E!==void 0&&h.has(I)?_(I):f.protectedKeys[I]=!0}f.prevProp=j,f.prevResolvedValues=S,f.isActive&&(p={...p,...S}),r&&t.blockInitialAnimation&&(T=!1);const $=A&&D;T&&(!$||P)&&u.push(...w.map(I=>{const E={type:C};if(typeof I=="string"&&r&&!$&&t.manuallyAnimateOnMount&&t.parent){const{parent:F}=t,O=Wa(F,I);if(F.enteringChildren&&O){const{delayChildren:L}=O.transition||{};E.delay=rh(F.enteringChildren,t,L)}}return{animation:I,options:E}}))}if(h.size){const v={};if(typeof d.initial!="boolean"){const C=Wa(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=wc()}}}function yw(t,s){return typeof s=="string"?s!==t:Array.isArray(s)?!nh(s,t):!1}function va(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function wc(){return{animate:va(!0),whileInView:va(),whileHover:va(),whileTap:va(),whileDrag:va(),whileFocus:va(),exit:va()}}class xa{constructor(s){this.isMounted=!1,this.node=s}update(){}}class bw extends xa{constructor(s){super(s),s.animationState||(s.animationState=fw(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();En(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 vw=0;class jw extends xa{constructor(){super(...arguments),this.id=vw++}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 Nw={animation:{Feature:bw},exit:{Feature:jw}};function Ar(t,s,a,r={passive:!0}){return t.addEventListener(s,a,r),()=>t.removeEventListener(s,a)}function Fr(t){return{point:{x:t.pageX,y:t.pageY}}}const ww=t=>s=>Yo(s)&&t(s,Fr(s));function pr(t,s,a,r){return Ar(t,s,ww(a),r)}const oh=1e-4,Cw=1-oh,Sw=1+oh,lh=.01,Aw=0-lh,kw=0+lh;function rs(t){return t.max-t.min}function Tw(t,s,a){return Math.abs(t-s)<=a}function Cc(t,s,a,r=.5){t.origin=r,t.originPoint=vt(s.min,s.max,t.origin),t.scale=rs(a)/rs(s),t.translate=vt(a.min,a.max,t.origin)-t.originPoint,(t.scale>=Cw&&t.scale<=Sw||isNaN(t.scale))&&(t.scale=1),(t.translate>=Aw&&t.translate<=kw||isNaN(t.translate))&&(t.translate=0)}function xr(t,s,a,r){Cc(t.x,s.x,a.x,r?r.originX:void 0),Cc(t.y,s.y,a.y,r?r.originY:void 0)}function Sc(t,s,a){t.min=a.min+s.min,t.max=t.min+rs(s)}function Dw(t,s,a){Sc(t.x,s.x,a.x),Sc(t.y,s.y,a.y)}function Ac(t,s,a){t.min=s.min-a.min,t.max=t.min+rs(s)}function gr(t,s,a){Ac(t.x,s.x,a.x),Ac(t.y,s.y,a.y)}function js(t){return[t("x"),t("y")]}const ch=({current:t})=>t?t.ownerDocument.defaultView:null,kc=(t,s)=>Math.abs(t-s);function Rw(t,s){const a=kc(t.x,s.x),r=kc(t.y,s.y);return Math.sqrt(a**2+r**2)}class dh{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=li(this.lastMoveEventInfo,this.history),p=this.startEvent!==null,g=Rw(h.offset,{x:0,y:0})>=this.distanceThreshold;if(!p&&!g)return;const{point:y}=h,{timestamp:v}=Gt;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=oi(p,this.transformPagePoint),ft.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=li(h.type==="pointercancel"?this.lastMoveEventInfo:oi(p,this.transformPagePoint),this.history);this.startEvent&&g&&g(h,C),y&&y(h,C)},!Yo(s))return;this.dragSnapToOrigin=i,this.handlers=a,this.transformPagePoint=r,this.distanceThreshold=o,this.contextWindow=n||window;const l=Fr(s),c=oi(l,this.transformPagePoint),{point:d}=c,{timestamp:m}=Gt;this.history=[{...d,timestamp:m}];const{onSessionStart:u}=a;u&&u(s,li(c,this.history)),this.removeListeners=Er(pr(this.contextWindow,"pointermove",this.handlePointerMove),pr(this.contextWindow,"pointerup",this.handlePointerUp),pr(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(s){this.handlers=s}end(){this.removeListeners&&this.removeListeners(),ma(this.updatePoint)}}function oi(t,s){return s?{point:s(t.point)}:t}function Tc(t,s){return{x:t.x-s.x,y:t.y-s.y}}function li({point:t},s){return{point:t,delta:Tc(t,mh(s)),offset:Tc(t,Pw(s)),velocity:Ew(s,.1)}}function Pw(t){return t[0]}function mh(t){return t[t.length-1]}function Ew(t,s){if(t.length<2)return{x:0,y:0};let a=t.length-1,r=null;const n=mh(t);for(;a>=0&&(r=t[a],!(n.timestamp-r.timestamp>Rs(s)));)a--;if(!r)return{x:0,y:0};const i=Ns(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 Iw(t,{min:s,max:a},r){return s!==void 0&&t<s?t=r?vt(s,t,r.min):Math.max(t,s):a!==void 0&&t>a&&(t=r?vt(a,t,r.max):Math.min(t,a)),t}function Dc(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 Mw(t,{top:s,left:a,bottom:r,right:n}){return{x:Dc(t.x,a,n),y:Dc(t.y,s,r)}}function Rc(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 Fw(t,s){return{x:Rc(t.x,s.x),y:Rc(t.y,s.y)}}function _w(t,s){let a=.5;const r=rs(t),n=rs(s);return n>r?a=jr(s.min,s.max-r,t.min):r>n&&(a=jr(t.min,t.max-n,s.min)),Ks(0,1,a)}function Lw(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 to=.35;function Ow(t=to){return t===!1?t=0:t===!0&&(t=to),{x:Pc(t,"left","right"),y:Pc(t,"top","bottom")}}function Pc(t,s,a){return{min:Ec(t,s),max:Ec(t,a)}}function Ec(t,s){return typeof t=="number"?t:t[s]||0}const $w=new WeakMap;class Uw{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=Pt(),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(Fr(u).point)},o=(u,h)=>{const{drag:p,dragPropagation:g,onDragStart:y}=this.getProps();if(p&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Kj(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),js(C=>{let f=this.getAxisMotionValue(C).get()||0;if(Ps.test(f)){const{projection:j}=this.visualElement;if(j&&j.layout){const b=j.layout.layoutBox[C];b&&(f=rs(b)*(parseFloat(f)/100))}}this.originPoint[C]=f}),y&&ft.postRender(()=>y(u,h)),qi(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=Bw(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=()=>js(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 dh(s,{onSessionStart:i,onStart:o,onMove:l,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:m,distanceThreshold:r,contextWindow:ch(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&&ft.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||!Gr(s,n,this.currentDirection))return;const i=this.getAxisMotionValue(s);let o=this.originPoint[s]+r[s];this.constraints&&this.constraints[s]&&(o=Iw(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&&$a(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&r?this.constraints=Mw(r.layoutBox,s):this.constraints=!1,this.elastic=Ow(a),n!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&js(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=Lw(r.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:s,onMeasureDragConstraints:a}=this.getProps();if(!s||!$a(s))return!1;const r=s.current,{projection:n}=this.visualElement;if(!n||!n.layout)return!1;const i=VN(r,n.root,this.visualElement.getTransformPagePoint());let o=Fw(n.layout.layoutBox,i);if(a){const l=a($N(o));this.hasMutatedConstraints=!!l,l&&(o=Yu(l))}return o}startAnimation(s){const{drag:a,dragMomentum:r,dragElastic:n,dragTransition:i,dragSnapToOrigin:o,onDragTransitionEnd:l}=this.getProps(),c=this.constraints||{},d=js(m=>{if(!Gr(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 qi(this.visualElement,s),r.start(rl(s,r,0,a,this.visualElement,!1))}stopAnimation(){js(s=>this.getAxisMotionValue(s).stop())}pauseAnimation(){js(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){js(a=>{const{drag:r}=this.getProps();if(!Gr(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]-vt(o,l,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:s,dragConstraints:a}=this.getProps(),{projection:r}=this.visualElement;if(!$a(a)||!r||!this.constraints)return;this.stopAnimation();const n={x:0,y:0};js(o=>{const l=this.getAxisMotionValue(o);if(l&&this.constraints!==!1){const c=l.get();n[o]=_w({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(),js(o=>{if(!Gr(o,s,null))return;const l=this.getAxisMotionValue(o),{min:c,max:d}=this.constraints[o];l.set(vt(c,d,n[o]))})}addListeners(){if(!this.visualElement.current)return;$w.set(this.visualElement,this);const s=this.visualElement.current,a=pr(s,"pointerdown",c=>{const{drag:d,dragListener:m=!0}=this.getProps();d&&m&&this.start(c)}),r=()=>{const{dragConstraints:c}=this.getProps();$a(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()),ft.read(r);const o=Ar(window,"resize",()=>this.scalePositionWithinConstraints()),l=n.addEventListener("didUpdate",({delta:c,hasLayoutChanged:d})=>{this.isDragging&&d&&(js(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=to,dragMomentum:l=!0}=s;return{...s,drag:a,dragDirectionLock:r,dragPropagation:n,dragConstraints:i,dragElastic:o,dragMomentum:l}}}function Gr(t,s,a){return(s===!0||s===t)&&(a===null||a===t)}function Bw(t,s=10){let a=null;return Math.abs(t.y)>s?a="y":Math.abs(t.x)>s&&(a="x"),a}class Vw extends xa{constructor(s){super(s),this.removeGroupControls=ws,this.removeListeners=ws,this.controls=new Uw(s)}mount(){const{dragControls:s}=this.node.getProps();s&&(this.removeGroupControls=s.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||ws}unmount(){this.removeGroupControls(),this.removeListeners()}}const Ic=t=>(s,a)=>{t&&ft.postRender(()=>t(s,a))};class zw extends xa{constructor(){super(...arguments),this.removePointerDownListener=ws}onPointerDown(s){this.session=new dh(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:ch(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:a,onPan:r,onPanEnd:n}=this.node.getProps();return{onSessionStart:Ic(s),onStart:Ic(a),onMove:r,onEnd:(i,o)=>{delete this.session,n&&ft.postRender(()=>n(i,o))}}}mount(){this.removePointerDownListener=pr(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 sn={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Mc(t,s){return s.max===s.min?0:t/(s.max-s.min)*100}const lr={correct:(t,s)=>{if(!s.target)return t;if(typeof t=="string")if(Ie.test(t))t=parseFloat(t);else return t;const a=Mc(t,s.target.x),r=Mc(t,s.target.y);return`${a}% ${r}%`}},Hw={correct:(t,{treeScale:s,projectionDelta:a})=>{const r=t,n=ua.parse(t);if(n.length>5)return r;const i=ua.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=vt(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 ci=!1;class Ww extends x.Component{componentDidMount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r,layoutId:n}=this.props,{projection:i}=s;hN(Kw),i&&(a.group&&a.group.add(i),r&&r.register&&n&&r.register(i),ci&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,onExitComplete:()=>this.safeToRemove()})),sn.hasEverUpdated=!0}getSnapshotBeforeUpdate(s){const{layoutDependency:a,visualElement:r,drag:n,isPresent:i}=this.props,{projection:o}=r;return o&&(o.isPresent=i,ci=!0,n||s.layoutDependency!==a||a===void 0||s.isPresent!==i?o.willUpdate():this.safeToRemove(),s.isPresent!==i&&(i?o.promote():o.relegate()||ft.postRender(()=>{const l=o.getStack();(!l||!l.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:s}=this.props.visualElement;s&&(s.root.didUpdate(),Go.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r}=this.props,{projection:n}=s;ci=!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 uh(t){const[s,a]=Mu(),r=x.useContext(So);return e.jsx(Ww,{...t,layoutGroup:r,switchLayoutGroup:x.useContext(Ku),isPresent:s,safeToRemove:a})}const Kw={borderRadius:{...lr,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:lr,borderTopRightRadius:lr,borderBottomLeftRadius:lr,borderBottomRightRadius:lr,boxShadow:Hw};function Gw(t,s,a){const r=Jt(t)?t:Ka(t);return r.start(rl("",r,s,a)),r.animation}const Yw=(t,s)=>t.depth-s.depth;class Zw{constructor(){this.children=[],this.isDirty=!1}add(s){To(this.children,s),this.isDirty=!0}remove(s){Do(this.children,s),this.isDirty=!0}forEach(s){this.isDirty&&this.children.sort(Yw),this.isDirty=!1,this.children.forEach(s)}}function Xw(t,s){const a=us.now(),r=({timestamp:n})=>{const i=n-a;i>=s&&(ma(r),t(i-s))};return ft.setup(r,!0),()=>ma(r)}const hh=["TopLeft","TopRight","BottomLeft","BottomRight"],Jw=hh.length,Fc=t=>typeof t=="string"?parseFloat(t):t,_c=t=>typeof t=="number"||Ie.test(t);function Qw(t,s,a,r,n,i){n?(t.opacity=vt(0,a.opacity??1,qw(r)),t.opacityExit=vt(s.opacity??1,0,eC(r))):i&&(t.opacity=vt(s.opacity??1,a.opacity??1,r));for(let o=0;o<Jw;o++){const l=`border${hh[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||_c(c)===_c(d)?(t[l]=Math.max(vt(Fc(c),Fc(d),r),0),(Ps.test(d)||Ps.test(c))&&(t[l]+="%")):t[l]=d}(s.rotate||a.rotate)&&(t.rotate=vt(s.rotate||0,a.rotate||0,r))}function Lc(t,s){return t[s]!==void 0?t[s]:t.borderRadius}const qw=ph(0,.5,eu),eC=ph(.5,.95,ws);function ph(t,s,a){return r=>r<t?0:r>s?1:a(jr(t,s,r))}function Oc(t,s){t.min=s.min,t.max=s.max}function vs(t,s){Oc(t.x,s.x),Oc(t.y,s.y)}function $c(t,s){t.translate=s.translate,t.scale=s.scale,t.originPoint=s.originPoint,t.origin=s.origin}function Uc(t,s,a,r,n){return t-=s,t=un(t,1/a,r),n!==void 0&&(t=un(t,1/n,r)),t}function tC(t,s=0,a=1,r=.5,n,i=t,o=t){if(Ps.test(s)&&(s=parseFloat(s),s=vt(o.min,o.max,s/100)-o.min),typeof s!="number")return;let l=vt(i.min,i.max,r);t===i&&(l-=s),t.min=Uc(t.min,s,a,l,n),t.max=Uc(t.max,s,a,l,n)}function Bc(t,s,[a,r,n],i,o){tC(t,s[a],s[r],s[n],s.scale,i,o)}const sC=["x","scaleX","originX"],aC=["y","scaleY","originY"];function Vc(t,s,a,r){Bc(t.x,s,sC,a?a.x:void 0,r?r.x:void 0),Bc(t.y,s,aC,a?a.y:void 0,r?r.y:void 0)}function zc(t){return t.translate===0&&t.scale===1}function xh(t){return zc(t.x)&&zc(t.y)}function Hc(t,s){return t.min===s.min&&t.max===s.max}function rC(t,s){return Hc(t.x,s.x)&&Hc(t.y,s.y)}function Wc(t,s){return Math.round(t.min)===Math.round(s.min)&&Math.round(t.max)===Math.round(s.max)}function gh(t,s){return Wc(t.x,s.x)&&Wc(t.y,s.y)}function Kc(t){return rs(t.x)/rs(t.y)}function Gc(t,s){return t.translate===s.translate&&t.scale===s.scale&&t.originPoint===s.originPoint}class nC{constructor(){this.members=[]}add(s){To(this.members,s),s.scheduleRender()}remove(s){if(Do(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 iC(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 di=["","X","Y","Z"],oC=1e3;let lC=0;function mi(t,s,a,r){const{latestValues:n}=s;n[t]&&(a[t]=n[t],s.setStaticValue(t,0),r&&(r[t]=0))}function fh(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:s}=t.options;if(!s)return;const a=sh(s);if(window.MotionHasOptimisedAnimation(a,"transform")){const{layout:n,layoutId:i}=t.options;window.MotionCancelOptimisedAnimation(a,"transform",ft,!(n||i))}const{parent:r}=t;r&&!r.hasCheckedOptimisedAppear&&fh(r)}function yh({attachResizeListener:t,defaultParent:s,measureScroll:a,checkIsScrollRoot:r,resetTransform:n}){return class{constructor(o={},l=s==null?void 0:s()){this.id=lC++,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(mC),this.nodes.forEach(xC),this.nodes.forEach(gC),this.nodes.forEach(uC)},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 Zw)}addEventListener(o,l){return this.eventHandlers.has(o)||this.eventHandlers.set(o,new Eo),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=Iu(o)&&!Qj(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;ft.read(()=>{u=window.innerWidth}),t(o,()=>{const p=window.innerWidth;p!==u&&(u=p,this.root.updateBlockedByResize=!0,m&&m(),m=Xw(h,250),sn.hasAnimatedSinceResize&&(sn.hasAnimatedSinceResize=!1,this.nodes.forEach(Xc)))})}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()||jC,{onLayoutAnimationStart:y,onLayoutAnimationComplete:v}=d.getProps(),C=!this.targetLayout||!gh(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={...Wo(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||Xc(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(),ma(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(fC),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&&fh(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(Yc);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Zc);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(pC),this.nodes.forEach(cC),this.nodes.forEach(dC)):this.nodes.forEach(Zc),this.clearAllSnapshots();const l=us.now();Gt.delta=Ks(0,1e3/60,l-Gt.timestamp),Gt.timestamp=l,Gt.isProcessing=!0,qn.update.process(Gt),qn.preRender.process(Gt),qn.render.process(Gt),Gt.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Go.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(hC),this.sharedNodes.forEach(yC)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,ft.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){ft.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!rs(this.snapshot.measuredBox.x)&&!rs(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=Pt(),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&&!xh(this.projectionDelta),c=this.getTransformTemplate(),d=c?c(this.latestValues,""):void 0,m=d!==this.prevTransformTemplateValue;o&&this.instance&&(l||wa(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)),NC(c),{animationId:this.root.animationId,measuredBox:l,layoutBox:c,latestValues:{},source:this.id}}measurePageBox(){var d;const{visualElement:o}=this.options;if(!o)return Pt();const l=o.measureViewportBox();if(!(((d=this.scroll)==null?void 0:d.wasRoot)||this.path.some(wC))){const{scroll:m}=this.root;m&&(Ua(l.x,m.offset.x),Ua(l.y,m.offset.y))}return l}removeElementScroll(o){var c;const l=Pt();if(vs(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&&vs(l,o),Ua(l.x,u.offset.x),Ua(l.y,u.offset.y))}return l}applyTransform(o,l=!1){const c=Pt();vs(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&&Ba(c,{x:-m.scroll.offset.x,y:-m.scroll.offset.y}),wa(m.latestValues)&&Ba(c,m.latestValues)}return wa(this.latestValues)&&Ba(c,this.latestValues),c}removeTransform(o){const l=Pt();vs(l,o);for(let c=0;c<this.path.length;c++){const d=this.path[c];if(!d.instance||!wa(d.latestValues))continue;Zi(d.latestValues)&&d.updateSnapshot();const m=Pt(),u=d.measurePageBox();vs(m,u),Vc(l,d.latestValues,d.snapshot?d.snapshot.layoutBox:void 0,m)}return wa(this.latestValues)&&Vc(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!==Gt.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=Gt.timestamp,!this.targetDelta&&!this.relativeTarget){const p=this.getClosestProjectingParent();p&&p.layout&&this.animationProgress!==1?(this.relativeParent=p,this.forceRelativeParentToResolveTarget(),this.relativeTarget=Pt(),this.relativeTargetOrigin=Pt(),gr(this.relativeTargetOrigin,this.layout.layoutBox,p.layout.layoutBox),vs(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=Pt(),this.targetWithTransforms=Pt()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),Dw(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):vs(this.target,this.layout.layoutBox),Xu(this.target,this.targetDelta)):vs(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=Pt(),this.relativeTargetOrigin=Pt(),gr(this.relativeTargetOrigin,this.target,p.target),vs(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Zi(this.parent.latestValues)||Zu(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===Gt.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;vs(this.layoutCorrected,this.layout.layoutBox);const u=this.treeScale.x,h=this.treeScale.y;BN(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=Pt());const{target:p}=o;if(!p){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():($c(this.prevProjectionDelta.x,this.projectionDelta.x),$c(this.prevProjectionDelta.y,this.projectionDelta.y)),xr(this.projectionDelta,this.layoutCorrected,p,this.latestValues),(this.treeScale.x!==u||this.treeScale.y!==h||!Gc(this.projectionDelta.x,this.prevProjectionDelta.x)||!Gc(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=Va(),this.projectionDelta=Va(),this.projectionDeltaWithTransform=Va()}setAnimationOrigin(o,l=!1){const c=this.snapshot,d=c?c.latestValues:{},m={...this.latestValues},u=Va();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!l;const h=Pt(),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(vC));this.animationProgress=0;let j;this.mixTargetDelta=b=>{const N=b/1e3;Jc(u.x,o.x,N),Jc(u.y,o.y,N),this.setTargetDelta(u),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(gr(h,this.layout.layoutBox,this.relativeParent.layout.layoutBox),bC(this.relativeTarget,this.relativeTargetOrigin,h,N),j&&rC(this.relativeTarget,j)&&(this.isProjectionDirty=!1),j||(j=Pt()),vs(j,this.relativeTarget)),y&&(this.animationValues=m,Qw(m,d,this.latestValues,N,f,C)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=N},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(o){var l,c,d;this.notifyListeners("animationStart"),(l=this.currentAnimation)==null||l.stop(),(d=(c=this.resumingFrom)==null?void 0:c.currentAnimation)==null||d.stop(),this.pendingAnimation&&(ma(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=ft.update(()=>{sn.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=Ka(0)),this.currentAnimation=Gw(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(oC),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&&bh(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||Pt();const u=rs(this.layout.layoutBox.x);c.x.min=o.target.x.min,c.x.max=c.x.min+u;const h=rs(this.layout.layoutBox.y);c.y.min=o.target.y.min,c.y.max=c.y.min+h}vs(l,c),Ba(l,m),xr(this.projectionDeltaWithTransform,this.layoutCorrected,l,m)}}registerSharedNode(o,l){this.sharedNodes.has(o)||this.sharedNodes.set(o,new nC),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&&mi("z",o,d,this.animationValues);for(let m=0;m<di.length;m++)mi(`rotate${di[m]}`,o,d,this.animationValues),mi(`skew${di[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=tn(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=tn(l==null?void 0:l.pointerEvents)||""),this.hasProjected&&!wa(this.latestValues)&&(o.transform=c?c({},""):"none",this.hasProjected=!1);return}o.visibility="";const m=d.animationValues||d.latestValues;this.applyTransformsToTarget();let u=iC(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 Sr){if(m[g]===void 0)continue;const{correct:y,applyTo:v,isCSSVariable:C}=Sr[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?tn(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(Yc),this.root.sharedNodes.clear()}}}function cC(t){t.updateLayout()}function dC(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"?js(u=>{const h=o?s.measuredBox[u]:s.layoutBox[u],p=rs(h);h.min=r[u].min,h.max=h.min+p}):bh(i,s.layoutBox,r)&&js(u=>{const h=o?s.measuredBox[u]:s.layoutBox[u],p=rs(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=Va();xr(l,r,s.layoutBox);const c=Va();o?xr(c,t.applyTransform(n,!0),s.measuredBox):xr(c,r,s.layoutBox);const d=!xh(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=Pt();gr(g,s.layoutBox,h.layoutBox);const y=Pt();gr(y,r,p.layoutBox),gh(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 mC(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 uC(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function hC(t){t.clearSnapshot()}function Yc(t){t.clearMeasurements()}function Zc(t){t.isLayoutDirty=!1}function pC(t){const{visualElement:s}=t.options;s&&s.getProps().onBeforeLayoutMeasure&&s.notify("BeforeLayoutMeasure"),t.resetTransform()}function Xc(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function xC(t){t.resolveTargetDelta()}function gC(t){t.calcProjection()}function fC(t){t.resetSkewAndRotation()}function yC(t){t.removeLeadSnapshot()}function Jc(t,s,a){t.translate=vt(s.translate,0,a),t.scale=vt(s.scale,1,a),t.origin=s.origin,t.originPoint=s.originPoint}function Qc(t,s,a,r){t.min=vt(s.min,a.min,r),t.max=vt(s.max,a.max,r)}function bC(t,s,a,r){Qc(t.x,s.x,a.x,r),Qc(t.y,s.y,a.y,r)}function vC(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const jC={duration:.45,ease:[.4,0,.1,1]},qc=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),ed=qc("applewebkit/")&&!qc("chrome/")?Math.round:ws;function td(t){t.min=ed(t.min),t.max=ed(t.max)}function NC(t){td(t.x),td(t.y)}function bh(t,s,a){return t==="position"||t==="preserve-aspect"&&!Tw(Kc(s),Kc(a),.2)}function wC(t){var s;return t!==t.root&&((s=t.scroll)==null?void 0:s.wasRoot)}const CC=yh({attachResizeListener:(t,s)=>Ar(t,"resize",s),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),ui={current:void 0},vh=yh({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!ui.current){const t=new CC({});t.mount(window),t.setOptions({layoutScroll:!0}),ui.current=t}return ui.current},resetTransform:(t,s)=>{t.style.transform=s!==void 0?s:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),SC={pan:{Feature:zw},drag:{Feature:Vw,ProjectionNode:vh,MeasureLayout:uh}};function sd(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&&ft.postRender(()=>i(s,Fr(s)))}class AC extends xa{mount(){const{current:s}=this.node;s&&(this.unmount=Gj(s,(a,r)=>(sd(this.node,r,"Start"),n=>sd(this.node,n,"End"))))}unmount(){}}class kC extends xa{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=Er(Ar(this.node.current,"focus",()=>this.onFocus()),Ar(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function ad(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&&ft.postRender(()=>i(s,Fr(s)))}class TC extends xa{mount(){const{current:s}=this.node;s&&(this.unmount=Jj(s,(a,r)=>(ad(this.node,r,"Start"),(n,{success:i})=>ad(this.node,n,i?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const so=new WeakMap,hi=new WeakMap,DC=t=>{const s=so.get(t.target);s&&s(t)},RC=t=>{t.forEach(DC)};function PC({root:t,...s}){const a=t||document;hi.has(a)||hi.set(a,{});const r=hi.get(a),n=JSON.stringify(s);return r[n]||(r[n]=new IntersectionObserver(RC,{root:t,...s})),r[n]}function EC(t,s,a){const r=PC(s);return so.set(t,a),r.observe(t),()=>{so.delete(t),r.unobserve(t)}}const IC={some:0,all:1};class MC extends xa{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:IC[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 EC(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(FC(s,a))&&this.startObserver()}unmount(){}}function FC({viewport:t={}},{viewport:s={}}={}){return a=>t[a]!==s[a]}const _C={inView:{Feature:MC},tap:{Feature:TC},focus:{Feature:kC},hover:{Feature:AC}},LC={layout:{ProjectionNode:vh,MeasureLayout:uh}},OC={...Nw,..._C,...SC,...LC},Kt=ON(OC,JN),rd=[{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:hs,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:Zx,color:"from-green-500 to-emerald-600",estimatedTime:"3-5 days",steps:5,features:["PO matching","Invoice verification","Multi-level approvals","Payment scheduling"]}];function $C({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(nt,{open:t,onOpenChange:s,children:e.jsxs(at,{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(rt,{className:"sr-only",children:"Select a Template"}),e.jsx(Ht,{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(ut,{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(Kt.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(jn,{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:rd.map((c,d)=>{const m=c.icon,u=r===c.id;return e.jsx(Kt.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(Z,{className:`cursor-pointer h-full transition-all duration-300 border-2 ${u?"border-blue-500 shadow-xl bg-blue-50/50 ring-2 ring-blue-200":"border-gray-200 hover:border-blue-300 hover:shadow-lg"}`,onClick:()=>i(c.id),children:[e.jsxs(ae,{className:"space-y-4 pb-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("div",{className:`w-14 h-14 rounded-xl bg-gradient-to-br ${c.color} flex items-center justify-center shadow-md`,children:e.jsx(m,{className:"w-7 h-7 text-white"})}),u&&e.jsx(Kt.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(Za,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsx(ne,{className:"text-xl mb-2",children:c.name}),e.jsx(we,{className:"text-sm leading-relaxed",children:c.description})]})]}),e.jsxs(X,{className:"pt-0 space-y-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(ee,{variant:"secondary",className:"text-xs",children:c.category})}),e.jsx(Tt,{}),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(Ue,{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(kt,{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(Ce,{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(Kt.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(R,{variant:"outline",onClick:s,size:"lg",className:"px-8",children:"Cancel"}),e.jsxs(R,{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(Vt,{className:"w-4 h-4"})]})]}),e.jsx(Rn,{children:r&&e.jsx(Kt.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=rd.find(c=>c.id===r))==null?void 0:l.name})]})})})]})})]})})}const UC={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 BC(t,s,a){const[r,n]=x.useState(UC),[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 Pa("DOCUMENT_POLICY"),j={};f.forEach(S=>{j[S.configKey]=S.configValue});const b=parseInt(j.MAX_FILE_SIZE_MB||"10"),A=(j.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(S=>S.trim().toLowerCase());h({maxFileSizeMB:b,allowedFileTypes:A});const D=await Pa("WORKFLOW_SHARING"),T=await Pa("TAT_SETTINGS"),P=[...D,...T],w={};P.forEach(S=>{w[S.configKey]=S.configValue}),m({maxApprovalLevels:parseInt(w.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(w.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((C=w.ALLOW_ADD_SPECTATOR)==null?void 0:C.toLowerCase())==="true",maxSpectators:parseInt(w.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 ds(s);if(!v||!C)return;const f=C.workflow||{},j=Array.isArray(C.approvals)?C.approvals:[],b=Array.isArray(C.participants)?C.participants:[],N=Array.isArray(C.documents)?C.documents.filter(M=>!M.isDeleted):[];g(N);const A=(f.priority||"").toString().toLowerCase(),D={standard:"standard",express:"express"},T=f.templateType==="TEMPLATE"?"existing-template":"custom",P=a.find(M=>M.id===T)||a[0]||null;o(P);const w=j.sort((M,B)=>(M.levelNumber||0)-(B.levelNumber||0)).map(M=>{const B=Number(M.tatHours||24),_=Math.floor(B/24),$=B%24;return{id:M.approverId||`temp-${M.levelNumber}`,name:M.approverName||M.approverEmail||"",email:M.approverEmail||"",role:M.levelName||`Level ${M.levelNumber}`,department:"",avatar:(M.approverName||M.approverEmail||"XX").substring(0,2).toUpperCase(),level:M.levelNumber||1,canClose:!1,tat:_>0?_:$,tatType:_>0?"days":"hours",userId:M.approverId}}),S=b.filter(M=>(M.participantType||M.participant_type||"").toString().toUpperCase().trim()==="SPECTATOR"?!!(M.userEmail||M.user_email||M.email):!1).map((M,B)=>{const _=M.userId||M.user_id||M.id,$=M.userName||M.user_name||M.name||"",k=M.userEmail||M.user_email||M.email||"",E=($||k||"XX").split(" ").map(F=>F[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{id:_||`spectator-${s}-${B}-${Date.now()}`,userId:_,name:$||k||"Spectator",email:k,role:"Spectator",department:M.department||"",avatar:E,level:1,canClose:!1}});n(M=>({...M,template:T,title:f.title||"",description:f.description||"",priority:D[A]||"standard",approvers:w,approverCount:w.length||1,spectators:S,maxLevel:Math.max(...w.map(B=>B.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 nd=["Template Selection","Basic Information","Approval Workflow","Participants & Access","Documents & Attachments","Review & Submit"];function VC(t,s,a){const[r,n]=x.useState(t?2:1),i=nd.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:nd,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 zC(){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 HC(t,s){const a=typeof t=="number"?t:parseInt(String(t))||0;return s==="days"?a*24:a||24}function WC(t,s,a){var n;const r=HC(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 KC(t,s){return t.slice(0,s).map((a,r)=>{const n=r+1;return WC(a,n,n===s)})}function id(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 od(t,s,a){const r=KC(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 GC(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 jh(t,s){return{id:(await jm(t,s||[],"SUPPORTING")).id}}async function Nh(t,s,a,r){const n=a&&a.length>0,i=r.length>0;n||i?await iy(t,s,a||[],r):await ny(t,s)}async function wh(t){await Sm(t)}async function YC(t,s){const a=await jh(t,s);return await wh(a.id),a}async function ZC(t,s,a,r){await Nh(t,s,a,r),await wh(t)}function XC({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=GC(t.approvers||[],t.approverCount||1);if(!g.valid){alert(g.message);return}d(!0);try{if(i&&o){const y=od(t,n,r);await ZC(o,y,a,r),l==null||l({...t,backendId:o,template:s})}else{const y=id(t,s,n),v=await YC(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=od(t,n,r);await Nh(o,g,a,r),l==null||l({...t,backendId:o,template:s})}else{const g=id(t,s,n),y=await jh(g,a);l==null||l({...t,backendId:y.id,template:s})}}catch(g){console.error("Failed to save draft:",g),u(!1)}}}}}async function JC(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 Os(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 Ws({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 QC(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 JC(o,s);if(!l.success)return{success:!1,error:l.error};try{const m=(((n=(await Os(o.email,1)).data)==null?void 0:n.data)||[])[0];if(m){const u=await Ws({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 qC({selectedTemplate:t,setSelectedTemplate:s,updateFormData:a,formData:r,currentStep:n,isStepValid:i,wizardNextStep:o,wizardPrevStep:l,user:c,openValidationModal:d,onSubmit:m}){const[u,h]=x.useState(!1),[p,g]=x.useState(null);return{showTemplateModal:u,setShowTemplateModal:h,previewDocument:p,selectTemplate:N=>{s(N),a("template",N.id),a("category",N.category),a("priority",N.priority);const A=new Date;A.setDate(A.getDate()+N.suggestedSLA),a("slaEndDate",A),N.id==="existing-template"&&h(!0)},handleTemplateSelection:N=>{m&&m({templateType:N})},nextStep:async()=>{var N;if(i()){if(window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}),n===3){const A=((N=c==null?void 0:c.email)==null?void 0:N.toLowerCase())||"",D=await QC(r.approvers,A);if(!D.success&&D.error){d(D.error.type,D.error.email,D.error.message);return}D.validatedApprovers&&a("approvers",D.validatedApprovers)}o()}},prevStep:()=>{l(),window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"})},handlePreviewDocument:(N,A)=>{if(A){const D=N.documentId||N.document_id||"";g({fileName:N.originalFileName||N.fileName||"Document",fileType:N.fileType||N.file_type||"application/octet-stream",fileUrl:Cm(D),fileSize:Number(N.fileSize||N.file_size||0),documentId:D})}else{const D=URL.createObjectURL(N);g({fileName:N.name,fileType:N.type||"application/octet-stream",fileUrl:D,fileSize:N.size,file:N})}},closePreview:()=>{p!=null&&p.fileUrl&&(p!=null&&p.file)&&URL.revokeObjectURL(p.fileUrl),g(null)}}}const ld=[{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:vn,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:Re,estimatedTime:"1-2 days",commonApprovers:["Department Head","Manager"],suggestedSLA:2,priority:"medium",fields:{timeline:!0}}];function e1({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(Za,{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 t1({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(R,{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(Ms,{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(R,{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(Xe,{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(R,{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(Xe,{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(Xd,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),"Submit"]})}):e.jsxs(R,{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(Vt,{className:"h-3 w-3 sm:h-4 sm:w-4 ml-1 sm:ml-2"})]})]})]})})}const cd=t=>{switch(t){case"high":return e.jsx(Ts,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(kt,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(Ys,{className:"w-4 h-4 text-green-600"});default:return e.jsx(kt,{className:"w-4 h-4 text-gray-600"})}};function s1({templates:t,selectedTemplate:s,onSelectTemplate:a}){return e.jsxs(Kt.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(Kt.div,{whileHover:{scale:1.03},whileTap:{scale:.98},transition:{type:"spring",stiffness:300,damping:20},"data-testid":`template-card-${r.id}`,children:e.jsxs(Z,{className:`cursor-pointer h-full transition-all duration-300 border-2 ${(s==null?void 0:s.id)===r.id?"border-blue-500 shadow-xl bg-blue-50/50 ring-2 ring-blue-200":"border-gray-200 hover:border-blue-300 hover:shadow-lg"}`,onClick:()=>a(r),"data-testid":`template-card-${r.id}-clickable`,children:[e.jsxs(ae,{className:"space-y-4 pb-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("div",{className:`w-14 h-14 rounded-xl flex items-center justify-center ${(s==null?void 0:s.id)===r.id?"bg-blue-100":"bg-gray-100"}`,"data-testid":`template-card-${r.id}-icon`,children:e.jsx(r.icon,{className:`w-7 h-7 ${(s==null?void 0:s.id)===r.id?"text-blue-600":"text-gray-600"}`})}),(s==null?void 0:s.id)===r.id&&e.jsx(Kt.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(Za,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsx(ne,{className:"text-xl mb-2","data-testid":`template-card-${r.id}-name`,children:r.name}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ee,{variant:"secondary",className:"text-xs","data-testid":`template-card-${r.id}-category`,children:r.category}),cd(r.priority)]})]})]}),e.jsxs(X,{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(Tt,{}),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(Ue,{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(Ct,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[r.commonApprovers.length," approvers"]})]})]})]})]})},r.id))}),e.jsx(Rn,{children:s&&e.jsx(Kt.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(Z,{className:"bg-gradient-to-br from-blue-50 to-indigo-50 border-2 border-blue-200",children:[e.jsx(ae,{children:e.jsxs(ne,{className:"flex items-center gap-2 text-blue-900","data-testid":"template-details-title",children:[e.jsx(Tr,{className:"w-5 h-5"}),s.name," - Template Details"]})}),e.jsxs(X,{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(Y,{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(Y,{className:"text-blue-900 font-semibold",children:"Priority Level"}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[cd(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(Y,{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(Y,{className:"text-blue-900 font-semibold",children:"Common Approvers"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:s.commonApprovers.map((r,n)=>e.jsx(ee,{variant:"outline",className:"border-blue-300 text-blue-700 bg-white","data-testid":`template-details-approver-${n}`,children:r},`${s.id}-approver-${n}-${r}`))})]})]})]})})})]})}function a1({className:t,...s}){return e.jsx(Zp,{"data-slot":"radio-group",className:fe("grid gap-3",t),...s})}function dd({className:t,...s}){return e.jsx(Xp,{"data-slot":"radio-group-item",className:fe("border-input text-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 aspect-square size-4 shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",t),...s,children:e.jsx(Jp,{"data-slot":"radio-group-indicator",className:"relative flex items-center justify-center",children:e.jsx(Xx,{className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}function r1({formData:t,selectedTemplate:s,updateFormData:a}){return e.jsxs(Kt.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(Re,{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(Y,{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(je,{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(Y,{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(Em,{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(Y,{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(a1,{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(dd,{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(mo,{className:"w-4 h-4 text-red-600"}),e.jsx(Y,{htmlFor:"express",className:"font-medium text-red-900 cursor-pointer",children:"Express"}),e.jsx(ee,{variant:"destructive",className:"text-xs",children:"URGENT"})]}),e.jsx("p",{className:"text-xs text-red-700",children:"Includes calendar days in TAT - faster processing timeline"})]})]}),e.jsxs("div",{className:`flex items-center space-x-3 p-3 rounded-lg border cursor-pointer transition-all ${t.priority==="standard"?"border-blue-500 bg-blue-50":"border-gray-200 hover:bg-gray-50"}`,onClick:()=>a("priority","standard"),"data-testid":"basic-information-priority-standard-option",children:[e.jsx(dd,{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(Ue,{className:"w-4 h-4 text-blue-600"}),e.jsx(Y,{htmlFor:"standard",className:"font-medium text-blue-900 cursor-pointer",children:"Standard"}),e.jsx(ee,{variant:"secondary",className:"text-xs",children:"DEFAULT"})]}),e.jsx("p",{className:"text-xs text-gray-600",children:"Includes working days in TAT - regular processing timeline"})]})]})]})]})}),((s==null?void 0:s.fields.amount)||(s==null?void 0:s.fields.vendor)||(s==null?void 0:s.fields.timeline)||(s==null?void 0:s.fields.impact))&&e.jsxs("div",{className:"border-t pt-6","data-testid":"basic-information-additional-details",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Additional Details"}),e.jsxs("div",{className:"space-y-6",children:[(s==null?void 0:s.fields.amount)&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4","data-testid":"basic-information-amount-field",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(Y,{htmlFor:"amount",className:"text-base font-semibold",children:"Budget Amount"}),e.jsx(je,{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(Y,{className:"text-base font-semibold",children:"Currency"}),e.jsxs(_e,{value:t.currency,onValueChange:r=>a("currency",r),"data-testid":"basic-information-currency-select",children:[e.jsx(Oe,{className:"h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm",children:e.jsx(Le,{})}),e.jsxs($e,{children:[e.jsx(H,{value:"USD",children:"USD ($)"}),e.jsx(H,{value:"EUR",children:"EUR (€)"}),e.jsx(H,{value:"GBP",children:"GBP (£)"}),e.jsx(H,{value:"INR",children:"INR (₹)"})]})]})]})]}),(s==null?void 0:s.fields.vendor)&&e.jsxs("div",{"data-testid":"basic-information-vendor-field",children:[e.jsx(Y,{htmlFor:"vendor",className:"text-base font-semibold",children:"Vendor/Supplier"}),e.jsx(je,{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(Y,{htmlFor:"costCenter",className:"text-base font-semibold",children:"Cost Center"}),e.jsx(je,{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(Y,{htmlFor:"project",className:"text-base font-semibold",children:"Related Project"}),e.jsx(je,{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 n1(){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 Os(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 Ws({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 i1(){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 Os(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 o1({formData:t,updateFormData:s,onValidationError:a}){var d;const{userSearchResults:r,userSearchLoading:n,searchUsersForIndex:i,clearSearchForIndex:o}=i1();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,N;return j!==m&&(f.userId===u.userId||((b=f.email)==null?void 0:b.toLowerCase())===((N=u.email)==null?void 0:N.toLowerCase()))})){a({type:"error",email:u.email,message:"This user is already added as an approver in another level."});return}if((p=t.spectators)==null?void 0:p.some(f=>{var 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 Ws({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(Kt.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(Ct,{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(Z,{"data-testid":"approval-workflow-config-card",children:[e.jsxs(ae,{children:[e.jsxs(ne,{className:"flex items-center gap-2","data-testid":"approval-workflow-config-title",children:[e.jsx(la,{className:"w-5 h-5"}),"Approval Configuration"]}),e.jsx(we,{children:"Configure how many approvers you need and define the approval sequence."})]}),e.jsx(X,{className:"space-y-6",children:e.jsxs("div",{"data-testid":"approval-workflow-count-field",children:[e.jsx(Y,{className:"text-base font-semibold mb-4 block",children:"Number of Approvers *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(R,{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(R,{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(Is,{className:"w-4 h-4"})})]}),e.jsx("p",{className:"text-sm text-gray-600 mt-2",children:"Maximum 10 approvers allowed. Each approver will review sequentially."})]})})]}),e.jsxs(Z,{"data-testid":"approval-workflow-hierarchy-card",children:[e.jsxs(ae,{children:[e.jsxs(ne,{className:"flex items-center gap-2","data-testid":"approval-workflow-hierarchy-title",children:[e.jsx(ss,{className:"w-5 h-5"}),"Approval Hierarchy *"]}),e.jsxs(we,{children:["Define the approval sequence. Each approver will review the request in order from Level 1 to Level ",t.approverCount||1,"."]})]}),e.jsxs(X,{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(St,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold text-blue-900",children:"Request Initiator"}),e.jsx(ee,{variant:"secondary",className:"text-xs",children:"YOU"})]}),e.jsx("p",{className:"text-sm text-blue-700",children:"Creates and submits the request"})]})]})}),Array.from({length:t.approverCount||1},(m,u)=>{var y,v;const h=u+1,p=h===(t.approverCount||1),g=t.approvers[u]||{email:"",tat:""};return e.jsxs("div",{className:"space-y-3","data-testid":`approval-workflow-approver-level-${h}`,children:[e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"w-px h-6 bg-gray-300"})}),e.jsx("div",{className:`p-4 rounded-lg border-2 transition-all ${g.email?"border-green-200 bg-green-50":"border-gray-200 bg-gray-50"}`,children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${g.email?"bg-green-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold",children:h})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsxs("span",{className:"font-semibold text-gray-900",children:["Approver Level ",h]}),p&&e.jsx(ee,{variant:"destructive",className:"text-xs",children:"FINAL APPROVER"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{"data-testid":`approval-workflow-approver-${h}-email-field`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(Y,{htmlFor:`approver-${h}`,className:"text-sm font-medium",children:"Email Address *"}),g.email&&g.userId&&e.jsxs(ee,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(Ce,{className:"w-3 h-3 mr-1"}),"Verified"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(je,{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(Y,{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(je,{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(_e,{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(Oe,{className:"w-20 h-10 border-2 border-gray-300",children:e.jsx(Le,{})}),e.jsxs($e,{children:[e.jsx(H,{value:"hours",children:"Hours"}),e.jsx(H,{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(Tr,{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(Ue,{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 l1({formData:t,updateFormData:s,onValidationError:a,initiatorEmail:r}){const[n,i]=x.useState(""),{searchResults:o,searchLoading:l,searchUsersDebounced:c,clearSearch:d,ensureUser:m}=n1(),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,N;return j.userId===g.userId||((b=j.email)==null?void 0:b.toLowerCase())===((N=g.email)==null?void 0:N.toLowerCase())}),f=(y=t.approvers)==null?void 0:y.some(j=>{var b,N;return j.userId===g.userId||((b=j.email)==null?void 0:b.toLowerCase())===((N=g.email)==null?void 0:N.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},N=[...t.spectators,b];s("spectators",N),i(""),d()}catch{a({type:"error",email:g.email,message:"Failed to validate user. Please try again."})}}else if(n&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)){if(n.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:n,message:"You cannot add yourself as a spectator."});return}const 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(Kt.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(zt,{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(Z,{"data-testid":"participants-spectators-card",children:[e.jsxs(ae,{children:[e.jsxs(ne,{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(zt,{className:"w-4 h-4"}),"Spectators"]}),e.jsx(ee,{variant:"outline",className:"text-xs","data-testid":"participants-spectators-count",children:t.spectators.length})]}),e.jsx(we,{children:"Users who can view and comment but cannot approve"})]}),e.jsxs(X,{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(je,{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(R,{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(Tr,{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($t,{className:"h-6 w-6",children:e.jsx(Ut,{className:"bg-teal-600 text-white text-xs",children:g.avatar})}),e.jsx("span",{className:"text-sm font-medium",children:g.name})]}),e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>p(g.id),"data-testid":`participants-spectator-${g.id}-remove`,children:e.jsx(ut,{className:"h-3 w-3"})})]},g.id))})]})]})})})]})}function c1({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 N=b.name.toLowerCase(),A=N.substring(N.lastIndexOf(".")+1);if(!t.allowedFileTypes.includes(A)){f.push({fileName:b.name,reason:`File type "${A}" 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(Kt.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(ps,{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(Z,{"data-testid":"documents-upload-card",children:[e.jsxs(ae,{children:[e.jsxs(ne,{className:"flex items-center gap-2","data-testid":"documents-upload-title",children:[e.jsx(Re,{className:"w-5 h-5"}),"File Upload"]}),e.jsxs(we,{children:["Attach supporting documents. Max ",t.maxFileSizeMB,"MB per file. Allowed types: ",t.allowedFileTypes.join(", ")]})]}),e.jsx(X,{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(ps,{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(R,{variant:"outline",size:"lg",type:"button",onClick:()=>{var y;return(y=m.current)==null?void 0:y.click()},"data-testid":"documents-browse-button",children:[e.jsx(Is,{className:"w-4 h-4 mr-2"}),"Browse Files"]}),e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Supported formats: ",t.allowedFileTypes.map(y=>y.toUpperCase()).join(", ")," (Max ",t.maxFileSizeMB,"MB per file)"]})]})})]}),s&&r.length>0&&e.jsxs(Z,{"data-testid":"documents-existing-card",children:[e.jsx(ae,{children:e.jsxs(ne,{className:"flex items-center justify-between","data-testid":"documents-existing-title",children:[e.jsx("span",{children:"Existing Documents"}),e.jsxs(ee,{variant:"secondary","data-testid":"documents-existing-count",children:[r.filter(y=>!n.includes(y.documentId||y.document_id||"")).length," file",r.filter(y=>!n.includes(y.documentId||y.document_id||"")).length!==1?"s":""]})]})}),e.jsx(X,{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(Re,{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(R,{variant:"ghost",size:"sm",onClick:()=>c(y,!0),"data-testid":`documents-existing-${v}-preview`,children:e.jsx(zt,{className:"h-4 w-4"})}),e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>p(v),"data-testid":`documents-existing-${v}-delete`,children:e.jsx(ut,{className:"h-4 w-4 text-red-600"})})]})]},v)})})})]}),a.length>0&&e.jsxs(Z,{"data-testid":"documents-new-card",children:[e.jsx(ae,{children:e.jsxs(ne,{className:"flex items-center justify-between","data-testid":"documents-new-title",children:[e.jsx("span",{children:"New Files to Upload"}),e.jsxs(ee,{variant:"secondary","data-testid":"documents-new-count",children:[a.length," file",a.length!==1?"s":""]})]})}),e.jsx(X,{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(Re,{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(R,{variant:"ghost",size:"sm",onClick:()=>c(y,!1),"data-testid":`documents-new-${v}-preview`,children:e.jsx(zt,{className:"h-4 w-4"})}),e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>h(v),"data-testid":`documents-new-${v}-remove`,children:e.jsx(ut,{className:"h-4 w-4"})})]})]},v))})})]})]})]})}const d1=t=>{switch(t){case"high":return e.jsx(Ts,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(kt,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(Ys,{className:"w-4 h-4 text-green-600"});default:return e.jsx(kt,{className:"w-4 h-4 text-gray-600"})}};function m1({formData:t,selectedTemplate:s}){return e.jsxs(Kt.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(Ce,{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(Z,{className:"border-2 border-green-200 bg-green-50/50","data-testid":"review-submit-overview-card",children:[e.jsx(ae,{children:e.jsxs(ne,{className:"flex items-center gap-2 text-green-900","data-testid":"review-submit-overview-title",children:[e.jsx(Xd,{className:"w-5 h-5"}),"Request Overview"]})}),e.jsxs(X,{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(Y,{className:"text-green-900 font-semibold",children:"Request Type"}),e.jsx("p",{className:"text-green-800 mt-1",children:s==null?void 0:s.name}),e.jsx(ee,{variant:"outline",className:"mt-2 text-xs border-green-300 text-green-700",children:s==null?void 0:s.category})]}),e.jsxs("div",{"data-testid":"review-submit-overview-priority",children:[e.jsx(Y,{className:"text-green-900 font-semibold",children:"Priority"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[d1(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(Y,{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(Y,{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(Z,{"data-testid":"review-submit-basic-info-card",children:[e.jsx(ae,{children:e.jsxs(ne,{className:"flex items-center gap-2","data-testid":"review-submit-basic-info-title",children:[e.jsx(Re,{className:"w-5 h-5"}),"Basic Information"]})}),e.jsxs(X,{className:"space-y-4",children:[e.jsxs("div",{"data-testid":"review-submit-basic-info-description",children:[e.jsx(Y,{className:"font-semibold",children:"Description"}),e.jsx("div",{className:"mt-1 p-3 bg-gray-50 rounded-lg border",children:e.jsx(oa,{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(Fs,{className:"w-4 h-4 text-blue-600"}),e.jsx(Y,{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(Z,{className:"border-2 border-orange-200 bg-orange-50/50","data-testid":"review-submit-approval-card",children:[e.jsxs(ae,{children:[e.jsxs(ne,{className:"flex items-center gap-2 text-orange-900","data-testid":"review-submit-approval-title",children:[e.jsx(Ct,{className:"w-5 h-5"}),"Approval Workflow"]}),e.jsx(we,{className:"text-orange-700",children:"Sequential approval hierarchy with TAT (Turn Around Time) for each level"})]}),e.jsx(X,{className:"space-y-6",children:e.jsx("div",{className:"space-y-4","data-testid":"review-submit-approval-levels",children:Array.from({length:t.approverCount||1},(a,r)=>{const n=r+1,i=n===(t.approverCount||1),o=t.approvers[r];return e.jsx("div",{className:"p-4 bg-white rounded-lg border border-orange-200","data-testid":`review-submit-approval-level-${n}`,children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0 ${o!=null&&o.email?"bg-green-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold",children:n})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsxs("span",{className:"font-semibold text-gray-900",children:["Approver Level ",n]}),i&&e.jsx(ee,{variant:"destructive",className:"text-xs",children:"FINAL APPROVER"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Email Address"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:(o==null?void 0:o.email)||"Not assigned"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-gray-600",children:"TAT (Turn Around Time)"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:o!=null&&o.tat?`${o.tat} ${o.tatType==="days"?"day":"hour"}${o.tat!==1?"s":""}`:"Not set"})]})]})]})]})},n)})})})]}),e.jsxs(Z,{"data-testid":"review-submit-participants-card",children:[e.jsx(ae,{children:e.jsxs(ne,{className:"flex items-center gap-2","data-testid":"review-submit-participants-title",children:[e.jsx(zt,{className:"w-5 h-5"}),"Participants & Access Control"]})}),e.jsx(X,{className:"space-y-4",children:t.spectators.length>0&&e.jsxs("div",{"data-testid":"review-submit-participants-spectators",children:[e.jsxs(Y,{className:"font-semibold text-sm",children:["Spectators (",t.spectators.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:t.spectators.map(a=>e.jsxs(ee,{variant:"outline",className:"text-xs","data-testid":`review-submit-spectator-${a.id}`,children:[a.name," (",a.email,")"]},a.id))})]})})]}),t.documents.length>0&&e.jsxs(Z,{"data-testid":"review-submit-documents-card",children:[e.jsxs(ae,{children:[e.jsxs(ne,{className:"flex items-center gap-2","data-testid":"review-submit-documents-title",children:[e.jsx(ps,{className:"w-5 h-5"}),"Documents & Attachments"]}),e.jsxs(we,{children:[t.documents.length," document",t.documents.length!==1?"s":""," attached to this request"]})]}),e.jsx(X,{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(Re,{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(Z,{className:"border-2 border-blue-200 bg-blue-50/50","data-testid":"review-submit-confirmation-card",children:e.jsx(X,{className:"pt-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(Ce,{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 u1({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(R,{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(Ms,{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 h1({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(Rn,{mode:"wait",children:t})})})}function p1({modal:t,onClose:s}){return e.jsx(nt,{open:t.open,onOpenChange:a=>!a&&s(),"data-testid":"create-request-validation-modal",children:e.jsxs(at,{className:"sm:max-w-md",children:[e.jsxs(it,{children:[e.jsxs(rt,{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(Ht,{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(vn,{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(yt,{children:e.jsx(R,{onClick:s,className:"w-full sm:w-auto","data-testid":"validation-modal-ok-button",children:t.type==="not-found"?"Fix Email":"OK"})})]})})}function x1({modal:t,documentPolicy:s,onClose:a}){return e.jsx(nt,{open:t.open,onOpenChange:r=>!r&&a(),"data-testid":"create-request-document-error-modal",children:e.jsxs(at,{className:"sm:max-w-lg",children:[e.jsxs(it,{children:[e.jsxs(rt,{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(Ht,{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(yt,{children:e.jsx(R,{onClick:a,className:"w-full sm:w-auto","data-testid":"document-error-modal-ok-button",children:"OK"})})]})})}function md({onBack:t,onSubmit:s,requestId:a,isEditMode:r=!1}){const n=Dr(),i=pa(),o=n.requestId||a||"",l=r&&!!o,{user:c}=ts(),{formData:d,updateFormData:m,selectedTemplate:u,setSelectedTemplate:h,loadingDraft:p,systemPolicy:g,documentPolicy:y,existingDocuments:v,setExistingDocuments:C}=BC(l,o,ld),{currentStep:f,totalSteps:j,stepNames:b,isStepValid:N,nextStep:A,prevStep:D}=VC(l,u,d),[T,P]=x.useState([]),[w,S]=x.useState([]),M=x.useRef(null),{validationModal:B,policyViolationModal:_,documentErrorModal:$,openValidationModal:k,closeValidationModal:I,closePolicyViolationModal:E,openDocumentErrorModal:F,closeDocumentErrorModal:O}=zC(),{submitting:L,savingDraft:J,handleSubmit:U,handleSaveDraft:oe}=XC({formData:d,selectedTemplate:u,documents:T,documentsToDelete:w,user:c,isEditing:l,editRequestId:o,onSubmit:s}),{showTemplateModal:ge,setShowTemplateModal:G,previewDocument:me,selectTemplate:re,handleTemplateSelection:V,nextStep:q,prevStep:ie,handlePreviewDocument:ue,closePreview:Te}=qC({selectedTemplate:u,setSelectedTemplate:h,updateFormData:m,formData:d,currentStep:f,isStepValid:N,wizardNextStep:A,wizardPrevStep:D,user:c,openValidationModal:k,onSubmit:s}),qe=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]),ze=x.useRef(!0),Ze=x.useRef(!1);x.useEffect(()=>{ze.current&&d.documents&&d.documents.length>0&&!Ze.current&&(P(d.documents),Ze.current=!0),ze.current=!1},[d.documents]);const Ge=x.useRef(!1),He=x.useRef(T);x.useEffect(()=>{if(Ge.current){Ge.current=!1,He.current=T;return}He.current!==T&&(m("documents",T),He.current=T)},[T]);const xt=()=>{switch(f){case 1:return e.jsx(s1,{templates:ld,selectedTemplate:u,onSelectTemplate:re});case 2:return e.jsx(r1,{formData:d,selectedTemplate:u,updateFormData:m});case 3:return e.jsx(o1,{formData:d,updateFormData:m,onValidationError:Q=>k(Q.type,Q.email,Q.message)});case 4:return e.jsx(l1,{formData:d,updateFormData:m,onValidationError:Q=>k(Q.type,Q.email,Q.message),initiatorEmail:(c==null?void 0:c.email)||""});case 5:return e.jsx(c1,{documentPolicy:y,isEditing:l,documents:T,existingDocuments:v,documentsToDelete:w,onDocumentsChange:P,onExistingDocumentsChange:C,onDocumentsToDeleteChange:S,onPreviewDocument:ue,onDocumentErrors:Q=>F(Q),fileInputRef:M});case 6:return e.jsx(m1,{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(u1,{isEditing:l,currentStep:f,totalSteps:j,stepNames:b,onBack:qe}),e.jsx(e1,{currentStep:f,totalSteps:j,stepNames:b}),e.jsx(h1,{children:xt()}),e.jsx(t1,{currentStep:f,totalSteps:j,isStepValid:N(),onPrev:ie,onNext:q,onSubmit:U,onSaveDraft:oe,submitting:L,savingDraft:J,loadingDraft:p,isEditing:l}),e.jsx($C,{open:ge,onClose:()=>G(!1),onSelectTemplate:V}),me&&e.jsx(Co,{fileName:me.fileName,fileType:me.fileType,fileUrl:me.fileUrl,fileSize:me.fileSize,open:!!me,onClose:Te,onDownload:async()=>{if(me.file){const Q=document.createElement("a");Q.href=me.fileUrl,Q.download=me.fileName,document.body.appendChild(Q),Q.click(),document.body.removeChild(Q)}else me.documentId&&await Ii(me.documentId)},attachmentId:me.documentId}),e.jsx(p1,{modal:B,onClose:I}),e.jsx(x1,{modal:$,documentPolicy:y,onClose:O}),e.jsx($m,{open:_.open,onClose:E,violations:_.violations,policyDetails:{maxApprovalLevels:g.maxApprovalLevels,maxParticipants:g.maxParticipants,allowSpectators:g.allowSpectators,maxSpectators:g.maxSpectators}})]})}var Me=function(){return Me=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},Me.apply(this,arguments)};function g1(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 Ch(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 _r(t){return t.mode==="multiple"}function Lr(t){return t.mode==="range"}function Mn(t){return t.mode==="single"}var f1={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 y1(t,s){return Ne(t,"LLLL y",s)}function b1(t,s){return Ne(t,"d",s)}function v1(t,s){return Ne(t,"LLLL",s)}function j1(t){return"".concat(t)}function N1(t,s){return Ne(t,"cccccc",s)}function w1(t,s){return Ne(t,"yyyy",s)}var C1=Object.freeze({__proto__:null,formatCaption:y1,formatDay:b1,formatMonthCaption:v1,formatWeekNumber:j1,formatWeekdayName:N1,formatYearCaption:w1}),S1=function(t,s,a){return Ne(t,"do MMMM (EEEE)",a)},A1=function(){return"Month: "},k1=function(){return"Go to next month"},T1=function(){return"Go to previous month"},D1=function(t,s){return Ne(t,"cccc",s)},R1=function(t){return"Week n. ".concat(t)},P1=function(){return"Year: "},E1=Object.freeze({__proto__:null,labelDay:S1,labelMonthDropdown:A1,labelNext:k1,labelPrevious:T1,labelWeekNumber:R1,labelWeekday:D1,labelYearDropdown:P1});function I1(){var t="buttons",s=f1,a=ux,r={},n={},i=1,o={},l=new Date;return{captionLayout:t,classNames:s,formatters:C1,labels:E1,locale:a,modifiersClassNames:r,modifiers:n,numberOfMonths:i,styles:o,today:l,mode:"default"}}function M1(t){var s=t.fromYear,a=t.toYear,r=t.fromMonth,n=t.toMonth,i=t.fromDate,o=t.toDate;return r?i=ys(r):s&&(i=new Date(s,0,1)),n?o=io(n):a&&(o=new Date(a,11,31)),{fromDate:i?vl(i):void 0,toDate:o?vl(o):void 0}}var Sh=x.createContext(void 0);function F1(t){var s,a=t.initialProps,r=I1(),n=M1(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;(Mn(a)||_r(a)||Lr(a))&&(c=a.onSelect);var d=Me(Me(Me({},r),a),{captionLayout:l,classNames:Me(Me({},r.classNames),a.classNames),components:Me({},a.components),formatters:Me(Me({},r.formatters),a.formatters),fromDate:i,labels:Me(Me({},r.labels),a.labels),mode:a.mode||r.mode,modifiers:Me(Me({},r.modifiers),a.modifiers),modifiersClassNames:Me(Me({},r.modifiersClassNames),a.modifiersClassNames),onSelect:c,styles:Me(Me({},r.styles),a.styles),toDate:o});return e.jsx(Sh.Provider,{value:d,children:t.children})}function pt(){var t=x.useContext(Sh);if(!t)throw new Error("useDayPicker must be used within a DayPickerProvider.");return t}function Ah(t){var s=pt(),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 _1(t){return e.jsx("svg",Me({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 kh(t){var s,a,r=t.onChange,n=t.value,i=t.children,o=t.caption,l=t.className,c=t.style,d=pt(),m=(a=(s=d.components)===null||s===void 0?void 0:s.IconDropdown)!==null&&a!==void 0?a:_1;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 L1(t){var s,a=pt(),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(yx(r,n))for(var h=ys(r),p=r.getMonth();p<=n.getMonth();p++)u.push($n(h,p));else for(var h=ys(new Date),p=0;p<=11;p++)u.push($n(h,p));var g=function(v){var C=Number(v.target.value),f=$n(ys(t.displayMonth),C);t.onChange(f)},y=(s=d==null?void 0:d.Dropdown)!==null&&s!==void 0?s:kh;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 O1(t){var s,a=t.displayMonth,r=pt(),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(jl(bx(new Date),y));var v=function(f){var j=jl(ys(a),Number(f.target.value));t.onChange(j)},C=(s=d==null?void 0:d.Dropdown)!==null&&s!==void 0?s:kh;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 $1(t,s){var a=x.useState(t),r=a[0],n=a[1],i=s===void 0?r:s;return[i,n]}function U1(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&&fr(i,n)<0){var d=-1*(c-1);n=Es(i,d)}return o&&fr(n,o)<0&&(n=o),ys(n)}function B1(){var t=pt(),s=U1(t),a=$1(s,t.month),r=a[0],n=a[1],i=function(o){var l;if(!t.disableNavigation){var c=ys(o);n(c),(l=t.onMonthChange)===null||l===void 0||l.call(t,c)}};return[r,i]}function V1(t,s){for(var a=s.reverseMonths,r=s.numberOfMonths,n=ys(t),i=ys(Es(n,r)),o=fr(i,n),l=[],c=0;c<o;c++){var d=Es(n,c);l.push(d)}return a&&(l=l.reverse()),l}function z1(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=ys(t);if(!a)return Es(l,o);var c=fr(a,t);if(!(c<i))return Es(l,o)}}function H1(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=ys(t);if(!a)return Es(l,-o);var c=fr(l,a);if(!(c<=0))return Es(l,-o)}}var Th=x.createContext(void 0);function W1(t){var s=pt(),a=B1(),r=a[0],n=a[1],i=V1(r,s),o=z1(r,s),l=H1(r,s),c=function(u){return i.some(function(h){return oo(u,h)})},d=function(u,h){c(u)||(h&&Ld(u,h)?n(Es(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(Th.Provider,{value:m,children:t.children})}function Or(){var t=x.useContext(Th);if(!t)throw new Error("useNavigation must be used within a NavigationProvider");return t}function ud(t){var s,a=pt(),r=a.classNames,n=a.styles,i=a.components,o=Or().goToMonth,l=function(m){o(Es(m,t.displayIndex?-t.displayIndex:0))},c=(s=i==null?void 0:i.CaptionLabel)!==null&&s!==void 0?s:Ah,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(L1,{onChange:l,displayMonth:t.displayMonth}),e.jsx(O1,{onChange:l,displayMonth:t.displayMonth})]})}function K1(t){return e.jsx("svg",Me({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 G1(t){return e.jsx("svg",Me({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 hn=x.forwardRef(function(t,s){var a=pt(),r=a.classNames,n=a.styles,i=[r.button_reset,r.button];t.className&&i.push(t.className);var o=i.join(" "),l=Me(Me({},n.button_reset),n.button);return t.style&&Object.assign(l,t.style),e.jsx("button",Me({},t,{ref:s,type:"button",className:o,style:l}))});function Y1(t){var s,a,r=pt(),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:G1,C=(a=u==null?void 0:u.IconLeft)!==null&&a!==void 0?a:K1;return e.jsxs("div",{className:o.nav,style:l.nav,children:[!t.hidePrevious&&e.jsx(hn,{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(hn,{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 hd(t){var s=pt().numberOfMonths,a=Or(),r=a.previousMonth,n=a.nextMonth,i=a.goToMonth,o=a.displayMonths,l=o.findIndex(function(g){return oo(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(Y1,{displayMonth:t.displayMonth,hideNext:m,hidePrevious:u,nextMonth:n,previousMonth:r,onPreviousClick:h,onNextClick:p})}function Z1(t){var s,a=pt(),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:Ah,d;return n?d=e.jsx(c,{id:t.id,displayMonth:t.displayMonth}):o==="dropdown"?d=e.jsx(ud,{displayMonth:t.displayMonth,id:t.id}):o==="dropdown-buttons"?d=e.jsxs(e.Fragment,{children:[e.jsx(ud,{displayMonth:t.displayMonth,displayIndex:t.displayIndex,id:t.id}),e.jsx(hd,{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(hd,{displayMonth:t.displayMonth,id:t.id})]}),e.jsx("div",{className:r.caption,style:i.caption,children:d})}function X1(t){var s=pt(),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 J1(t,s,a){for(var r=a?lo(new Date):co(new Date,{locale:t,weekStartsOn:s}),n=[],i=0;i<7;i++){var o=xs(r,i);n.push(o)}return n}function Q1(){var t=pt(),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=J1(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 q1(){var t,s=pt(),a=s.classNames,r=s.styles,n=s.components,i=(t=n==null?void 0:n.HeadRow)!==null&&t!==void 0?t:Q1;return e.jsx("thead",{style:r.head,className:a.head,children:e.jsx(i,{})})}function e2(t){var s=pt(),a=s.locale,r=s.formatters.formatDay;return e.jsx(e.Fragment,{children:r(t.date,{locale:a})})}var nl=x.createContext(void 0);function t2(t){if(!_r(t.initialProps)){var s={selected:void 0,modifiers:{disabled:[]}};return e.jsx(nl.Provider,{value:s,children:t.children})}return e.jsx(s2,{initialProps:t.initialProps,children:t.children})}function s2(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?Ch([],r):[];if(m.selected){var C=v.findIndex(function(f){return ms(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 ms(h,d)});return!!(m&&!u)});var c={selected:r,onDayClick:o,modifiers:l};return e.jsx(nl.Provider,{value:c,children:a})}function il(){var t=x.useContext(nl);if(!t)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return t}function a2(t,s){var a=s||{},r=a.from,n=a.to;return r&&n?ms(n,t)&&ms(r,t)?void 0:ms(n,t)?{from:n,to:void 0}:ms(r,t)?void 0:Si(r,t)?{from:t,to:n}:{from:r,to:t}:n?Si(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 ol=x.createContext(void 0);function r2(t){if(!Lr(t.initialProps)){var s={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(ol.Provider,{value:s,children:t.children})}return e.jsx(n2,{initialProps:t.initialProps,children:t.children})}function n2(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=a2(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],ms(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:On(i,l-1),before:xs(i,l-1)}),i&&o&&m.disabled.push({after:i,before:xs(i,l-1)}),!i&&o&&m.disabled.push({after:On(o,l-1),before:xs(o,l-1)})),c){if(i&&!o&&(m.disabled.push({before:xs(i,-c+1)}),m.disabled.push({after:xs(i,c-1)})),i&&o){var u=Hs(o,i)+1,h=c-u;m.disabled.push({before:On(i,h)}),m.disabled.push({after:xs(o,h)})}!i&&o&&(m.disabled.push({before:xs(o,-c+1)}),m.disabled.push({after:xs(o,c-1)}))}return e.jsx(ol.Provider,{value:{selected:r,onDayClick:d,modifiers:m},children:a})}function ll(){var t=x.useContext(ol);if(!t)throw new Error("useSelectRange must be used within a SelectRangeProvider");return t}function an(t){return Array.isArray(t)?Ch([],t):t!==void 0?[t]:[]}function i2(t){var s={};return Object.entries(t).forEach(function(a){var r=a[0],n=a[1];s[r]=an(n)}),s}var ks;(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"})(ks||(ks={}));var o2=ks.Selected,zs=ks.Disabled,l2=ks.Hidden,c2=ks.Today,pi=ks.RangeEnd,xi=ks.RangeMiddle,gi=ks.RangeStart,d2=ks.Outside;function m2(t,s,a){var r,n=(r={},r[o2]=an(t.selected),r[zs]=an(t.disabled),r[l2]=an(t.hidden),r[c2]=[t.today],r[pi]=[],r[xi]=[],r[gi]=[],r[d2]=[],r);return t.fromDate&&n[zs].push({before:t.fromDate}),t.toDate&&n[zs].push({after:t.toDate}),_r(t)?n[zs]=n[zs].concat(s.modifiers[zs]):Lr(t)&&(n[zs]=n[zs].concat(a.modifiers[zs]),n[gi]=a.modifiers[gi],n[xi]=a.modifiers[xi],n[pi]=a.modifiers[pi]),n}var Dh=x.createContext(void 0);function u2(t){var s=pt(),a=il(),r=ll(),n=m2(s,a,r),i=i2(s.modifiers),o=Me(Me({},n),i);return e.jsx(Dh.Provider,{value:o,children:t.children})}function Rh(){var t=x.useContext(Dh);if(!t)throw new Error("useModifiers must be used within a ModifiersProvider");return t}function h2(t){return!!(t&&typeof t=="object"&&"before"in t&&"after"in t)}function p2(t){return!!(t&&typeof t=="object"&&"from"in t)}function x2(t){return!!(t&&typeof t=="object"&&"after"in t)}function g2(t){return!!(t&&typeof t=="object"&&"before"in t)}function f2(t){return!!(t&&typeof t=="object"&&"dayOfWeek"in t)}function y2(t,s){var a,r=s.from,n=s.to;if(r&&n){var i=Hs(n,r)<0;i&&(a=[n,r],r=a[0],n=a[1]);var o=Hs(t,r)>=0&&Hs(n,t)>=0;return o}return n?ms(n,t):r?ms(r,t):!1}function b2(t){return Ud(t)}function v2(t){return Array.isArray(t)&&t.every(Ud)}function j2(t,s){return s.some(function(a){if(typeof a=="boolean")return a;if(b2(a))return ms(t,a);if(v2(a))return a.includes(t);if(p2(a))return y2(t,a);if(f2(a))return a.dayOfWeek.includes(t.getDay());if(h2(a)){var r=Hs(a.before,t),n=Hs(a.after,t),i=r>0,o=n<0,l=Si(a.before,a.after);return l?o&&i:i||o}return x2(a)?Hs(t,a.after)>0:g2(a)?Hs(a.before,t)>0:typeof a=="function"?a(t):!1})}function cl(t,s,a){var r=Object.keys(s).reduce(function(i,o){var l=s[o];return j2(t,l)&&i.push(o),i},[]),n={};return r.forEach(function(i){return n[i]=!0}),a&&!oo(t,a)&&(n.outside=!0),n}function N2(t,s){for(var a=ys(t[0]),r=io(t[t.length-1]),n,i,o=a;o<=r;){var l=cl(o,s),c=!l.disabled&&!l.hidden;if(!c){o=xs(o,1);continue}if(l.selected)return o;l.today&&!i&&(i=o),n||(n=o),o=xs(o,1)}return i||n}var w2=365;function Ph(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:xs,week:Ci,month:Es,year:xx,startOfWeek:function(v){return n.ISOWeek?lo(v):co(v,{locale:u,weekStartsOn:c})},endOfWeek:function(v){return n.ISOWeek?Od(v):$d(v,{locale:u,weekStartsOn:c})}},p=h[a](t,r==="after"?1:-1);r==="before"&&d?p=gx([d,p]):r==="after"&&m&&(p=fx([m,p]));var g=!0;if(i){var y=cl(p,i);g=!y.disabled&&!y.hidden}return g?p:l.count>w2?l.lastFocused:Ph(p,{moveBy:a,direction:r,context:n,modifiers:i,retry:Me(Me({},l),{count:l.count+1})})}var Eh=x.createContext(void 0);function C2(t){var s=Or(),a=Rh(),r=x.useState(),n=r[0],i=r[1],o=x.useState(),l=o[0],c=o[1],d=N2(s.displayMonths,a),m=n??(l&&s.isDateDisplayed(l))?l:d,u=function(){c(n),i(void 0)},h=function(v){i(v)},p=pt(),g=function(v,C){if(n){var f=Ph(n,{moveBy:v,direction:C,context:p,modifiers:a});ms(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 dl(){var t=x.useContext(Eh);if(!t)throw new Error("useFocusContext must be used within a FocusProvider");return t}function S2(t,s){var a=Rh(),r=cl(t,a,s);return r}var ml=x.createContext(void 0);function A2(t){if(!Mn(t.initialProps)){var s={selected:void 0};return e.jsx(ml.Provider,{value:s,children:t.children})}return e.jsx(k2,{initialProps:t.initialProps,children:t.children})}function k2(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(ml.Provider,{value:n,children:a})}function Ih(){var t=x.useContext(ml);if(!t)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return t}function T2(t,s){var a=pt(),r=Ih(),n=il(),i=ll(),o=dl(),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(I){var E,F,O,L;Mn(a)?(E=r.onDayClick)===null||E===void 0||E.call(r,t,s,I):_r(a)?(F=n.onDayClick)===null||F===void 0||F.call(n,t,s,I):Lr(a)?(O=i.onDayClick)===null||O===void 0||O.call(i,t,s,I):(L=a.onDayClick)===null||L===void 0||L.call(a,t,s,I)},b=function(I){var E;h(t),(E=a.onDayFocus)===null||E===void 0||E.call(a,t,s,I)},N=function(I){var E;u(),(E=a.onDayBlur)===null||E===void 0||E.call(a,t,s,I)},A=function(I){var E;(E=a.onDayMouseEnter)===null||E===void 0||E.call(a,t,s,I)},D=function(I){var E;(E=a.onDayMouseLeave)===null||E===void 0||E.call(a,t,s,I)},T=function(I){var E;(E=a.onDayPointerEnter)===null||E===void 0||E.call(a,t,s,I)},P=function(I){var E;(E=a.onDayPointerLeave)===null||E===void 0||E.call(a,t,s,I)},w=function(I){var E;(E=a.onDayTouchCancel)===null||E===void 0||E.call(a,t,s,I)},S=function(I){var E;(E=a.onDayTouchEnd)===null||E===void 0||E.call(a,t,s,I)},M=function(I){var E;(E=a.onDayTouchMove)===null||E===void 0||E.call(a,t,s,I)},B=function(I){var E;(E=a.onDayTouchStart)===null||E===void 0||E.call(a,t,s,I)},_=function(I){var E;(E=a.onDayKeyUp)===null||E===void 0||E.call(a,t,s,I)},$=function(I){var E;switch(I.key){case"ArrowLeft":I.preventDefault(),I.stopPropagation(),a.dir==="rtl"?l():c();break;case"ArrowRight":I.preventDefault(),I.stopPropagation(),a.dir==="rtl"?c():l();break;case"ArrowDown":I.preventDefault(),I.stopPropagation(),d();break;case"ArrowUp":I.preventDefault(),I.stopPropagation(),m();break;case"PageUp":I.preventDefault(),I.stopPropagation(),I.shiftKey?y():p();break;case"PageDown":I.preventDefault(),I.stopPropagation(),I.shiftKey?v():g();break;case"Home":I.preventDefault(),I.stopPropagation(),C();break;case"End":I.preventDefault(),I.stopPropagation(),f();break}(E=a.onDayKeyDown)===null||E===void 0||E.call(a,t,s,I)},k={onClick:j,onFocus:b,onBlur:N,onKeyDown:$,onKeyUp:_,onMouseEnter:A,onMouseLeave:D,onPointerEnter:T,onPointerLeave:P,onTouchCancel:w,onTouchEnd:S,onTouchMove:M,onTouchStart:B};return k}function D2(){var t=pt(),s=Ih(),a=il(),r=ll(),n=Mn(t)?s.selected:_r(t)?a.selected:Lr(t)?r.selected:void 0;return n}function R2(t){return Object.values(ks).includes(t)}function P2(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(R2(r)){var i=t.classNames["day_".concat(r)];i&&a.push(i)}}),a}function E2(t,s){var a=Me({},t.styles.day);return Object.keys(s).forEach(function(r){var n;a=Me(Me({},a),(n=t.modifiersStyles)===null||n===void 0?void 0:n[r])}),a}function I2(t,s,a){var r,n,i,o=pt(),l=dl(),c=S2(t,s),d=T2(t,c),m=D2(),u=!!(o.onDayClick||o.mode!=="default");x.useEffect(function(){var A;c.outside||l.focusedDay&&u&&ms(l.focusedDay,t)&&((A=a.current)===null||A===void 0||A.focus())},[l.focusedDay,t,a,u,c.outside]);var h=P2(o,c).join(" "),p=E2(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:e2,v=e.jsx(y,{date:t,displayMonth:s,activeModifiers:c}),C={style:p,className:h,children:v,role:"gridcell"},f=l.focusTarget&&ms(l.focusTarget,t)&&!c.outside,j=l.focusedDay&&ms(l.focusedDay,t),b=Me(Me(Me({},C),(r={disabled:c.disabled,role:"gridcell"},r["aria-selected"]=c.selected,r.tabIndex=j||f?0:-1,r)),d),N={isButton:u,isHidden:g,activeModifiers:c,selectedDays:m,buttonProps:b,divProps:C};return N}function M2(t){var s=x.useRef(null),a=I2(t.date,t.displayMonth,s);return a.isHidden?e.jsx("div",{role:"gridcell"}):a.isButton?e.jsx(hn,Me({name:"day",ref:s},a.buttonProps)):e.jsx("div",Me({},a.divProps))}function F2(t){var s=t.number,a=t.dates,r=pt(),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(hn,{name:"week-number","aria-label":u,className:o.weeknumber,style:i.weeknumber,onClick:h,children:m})}function _2(t){var s,a,r=pt(),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:M2,d=(a=l==null?void 0:l.WeekNumber)!==null&&a!==void 0?a:F2,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})},px(u))})]})}function pd(t,s,a){for(var r=a!=null&&a.ISOWeek?Od(s):$d(s,a),n=a!=null&&a.ISOWeek?lo(t):co(t,a),i=Hs(r,n),o=[],l=0;l<=i;l++)o.push(xs(n,l));var c=o.reduce(function(d,m){var u=a!=null&&a.ISOWeek?vx(m):jx(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 L2(t,s){var a=pd(ys(t),io(t),s);if(s!=null&&s.useFixedWeeks){var r=hx(t,s);if(r<6){var n=a[a.length-1],i=n.dates[n.dates.length-1],o=Ci(i,6-r),l=pd(Ci(i,1),o,s);a.push.apply(a,l)}}return a}function O2(t){var s,a,r,n=pt(),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=L2(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:q1,v=(a=m==null?void 0:m.Row)!==null&&a!==void 0?a:_2,C=(r=m==null?void 0:m.Footer)!==null&&r!==void 0?r:X1;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 $2(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var U2=$2()?x.useLayoutEffect:x.useEffect,fi=!1,B2=0;function xd(){return"react-day-picker-".concat(++B2)}function V2(t){var s,a=t??(fi?xd():null),r=x.useState(a),n=r[0],i=r[1];return U2(function(){n===null&&i(xd())},[]),x.useEffect(function(){fi===!1&&(fi=!0)},[]),(s=t??n)!==null&&s!==void 0?s:void 0}function z2(t){var s,a,r=pt(),n=r.dir,i=r.classNames,o=r.styles,l=r.components,c=Or().displayMonths,d=V2(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=Me(Me({},h),o.caption_start)),g&&(u.push(i.caption_end),h=Me(Me({},h),o.caption_end)),y&&(u.push(i.caption_between),h=Me(Me({},h),o.caption_between));var v=(a=l==null?void 0:l.Caption)!==null&&a!==void 0?a:Z1;return e.jsxs("div",{className:u.join(" "),style:h,children:[e.jsx(v,{id:d,displayMonth:t.displayMonth,displayIndex:t.displayIndex}),e.jsx(O2,{id:m,"aria-labelledby":d,displayMonth:t.displayMonth})]},t.displayIndex)}function H2(t){var s=pt(),a=s.classNames,r=s.styles;return e.jsx("div",{className:a.months,style:r.months,children:t.children})}function W2(t){var s,a,r=t.initialProps,n=pt(),i=dl(),o=Or(),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=Me(Me({},n.styles.root),n.style),h=Object.keys(r).filter(function(g){return g.startsWith("data-")}).reduce(function(g,y){var v;return Me(Me({},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:H2;return e.jsx("div",Me({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(z2,{displayIndex:y,displayMonth:g},y)})})}))}function K2(t){var s=t.children,a=g1(t,["children"]);return e.jsx(F1,{initialProps:a,children:e.jsx(W1,{children:e.jsx(A2,{initialProps:a,children:e.jsx(t2,{initialProps:a,children:e.jsx(r2,{initialProps:a,children:e.jsx(u2,{children:e.jsx(C2,{children:s})})})})})})})}function G2(t){return e.jsx(K2,Me({},t,{children:e.jsx(W2,{initialProps:t})}))}function yi({className:t,classNames:s,showOutsideDays:a=!0,...r}){return e.jsx(G2,{showOutsideDays:a,className:fe("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:fe(br({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:fe("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:fe(br({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:fe("size-4",n),...i}),IconRight:({className:n,...i})=>e.jsx(xo,{className:fe("size-4",n),...i})},...r})}async function Y2(){var t;try{const s=await ce.get("/dealers");return((t=s.data)==null?void 0:t.data)||s.data||[]}catch(s){throw console.error("[DealerAPI] Error fetching dealers:",s),s}}async function Z2(t){var s;try{const a=await ce.get(`/dealers/code/${t}`);return((s=a.data)==null?void 0:s.data)||a.data||null}catch(a){return console.error("[DealerAPI] Error fetching dealer by code:",a),null}}const X2=["Marketing Activity","Promotional Event","Dealer Training","Infrastructure Development","Customer Experience Initiative","Service Campaign"],bi=["Claim Details","Review & Submit"];function J2({onBack:t,onSubmit:s}){const[a,r]=x.useState(1),[n,i]=x.useState([]),[o,l]=x.useState(!0),[c,d]=x.useState({activityName:"",activityType:"",dealerCode:"",dealerName:"",dealerEmail:"",dealerPhone:"",dealerAddress:"",activityDate:void 0,location:"",requestDescription:"",periodStartDate:void 0,periodEndDate:void 0,estimatedBudget:""}),m=bi.length;x.useEffect(()=>{(async()=>{l(!0);try{const j=await Y2();i(j)}catch(j){te.error("Failed to load dealer list."),console.error("Error fetching dealers:",j)}finally{l(!1)}})()},[]);const u=(f,j)=>{d(b=>({...b,[f]:j}))},h=()=>{switch(a){case 1:return c.activityName&&c.activityType&&c.dealerCode&&c.dealerName&&c.activityDate&&c.location&&c.requestDescription;case 2:return!0;default:return!1}},p=()=>{a<m&&h()&&r(a+1)},g=()=>{a>1&&r(a-1)},y=async f=>{const j=n.find(b=>b.dealerCode===f);if(j){u("dealerCode",f),u("dealerName",j.dealerName),u("dealerEmail",j.email||""),u("dealerPhone",j.phone||""),u("dealerAddress","");try{const b=await Z2(f);b&&(u("dealerEmail",b.email||j.email||""),u("dealerPhone",b.phone||j.phone||""))}catch(b){console.debug("Could not fetch full dealer info:",b)}}},v=()=>{const f={...c,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"}]};te.success("Claim Request Created",{description:"Your claim management request has been submitted successfully."}),s&&s(f)},C=()=>{switch(a){case 1:return e.jsxs(Kt.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(hs,{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(Y,{htmlFor:"activityName",className:"text-base font-semibold",children:"Activity Name *"}),e.jsx(je,{id:"activityName",placeholder:"e.g., Himalayan Adventure Fest 2024",value:c.activityName,onChange:f=>u("activityName",f.target.value),className:"mt-2 h-12"})]}),e.jsxs("div",{children:[e.jsx(Y,{htmlFor:"activityType",className:"text-base font-semibold",children:"Activity Type *"}),e.jsxs(_e,{value:c.activityType,onValueChange:f=>u("activityType",f),children:[e.jsx(Oe,{className:"mt-2 h-12",children:e.jsx(Le,{placeholder:"Select activity type"})}),e.jsx($e,{children:X2.map(f=>e.jsx(H,{value:f,children:f},f))})]})]})]}),e.jsxs("div",{children:[e.jsx(Y,{htmlFor:"dealer",className:"text-base font-semibold",children:"Dealer Code / Dealer Name *"}),e.jsxs(_e,{value:c.dealerCode,onValueChange:y,disabled:o,children:[e.jsx(Oe,{className:"mt-2 h-12",children:e.jsx(Le,{placeholder:o?"Loading dealers...":"Select dealer",children:c.dealerCode&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-sm",children:c.dealerCode}),e.jsx("span",{className:"text-gray-400",children:"•"}),e.jsx("span",{children:c.dealerName})]})})}),e.jsx($e,{children:n.length===0&&!o?e.jsx("div",{className:"p-2 text-sm text-gray-500",children:"No dealers available"}):n.filter(f=>f.dealerCode&&f.dealerCode.trim()!=="").map(f=>e.jsx(H,{value:f.dealerCode,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-sm font-semibold",children:f.dealerCode}),e.jsx("span",{className:"text-gray-400",children:"•"}),e.jsx("span",{children:f.dealerName})]})},f.dealerCode))})]}),c.dealerCode&&e.jsxs("p",{className:"text-sm text-gray-600 mt-2",children:["Selected: ",e.jsx("span",{className:"font-semibold",children:c.dealerName})," (",c.dealerCode,")"]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(Y,{className:"text-base font-semibold",children:"Date *"}),e.jsxs(ra,{children:[e.jsx(na,{asChild:!0,children:e.jsxs(R,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12",children:[e.jsx(et,{className:"mr-2 h-4 w-4"}),c.activityDate?Ne(c.activityDate,"PPP"):"Select date"]})}),e.jsx(ia,{className:"w-auto p-0",align:"start",children:e.jsx(yi,{mode:"single",selected:c.activityDate,onSelect:f=>u("activityDate",f),initialFocus:!0})})]})]}),e.jsxs("div",{children:[e.jsx(Y,{htmlFor:"location",className:"text-base font-semibold",children:"Location *"}),e.jsx(je,{id:"location",placeholder:"e.g., Mumbai, Maharashtra",value:c.location,onChange:f=>u("location",f.target.value),className:"mt-2 h-12"})]})]}),e.jsxs("div",{children:[e.jsx(Y,{htmlFor:"requestDescription",className:"text-base font-semibold",children:"Request in Detail - Brief Requirement *"}),e.jsx(os,{id:"requestDescription",placeholder:"Provide a detailed description of your claim requirement...",value:c.requestDescription,onChange:f=>u("requestDescription",f.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(Y,{className:"text-base font-semibold",children:"Period (If Any)"}),e.jsx(ee,{variant:"secondary",className:"text-xs",children:"Optional"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(Y,{className:"text-sm text-gray-600",children:"Start Date"}),e.jsxs(ra,{children:[e.jsx(na,{asChild:!0,children:e.jsxs(R,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12",children:[e.jsx(et,{className:"mr-2 h-4 w-4"}),c.periodStartDate?Ne(c.periodStartDate,"PPP"):"Start date"]})}),e.jsx(ia,{className:"w-auto p-0",align:"start",children:e.jsx(yi,{mode:"single",selected:c.periodStartDate,onSelect:f=>u("periodStartDate",f),initialFocus:!0})})]})]}),e.jsxs("div",{children:[e.jsx(Y,{className:"text-sm text-gray-600",children:"End Date"}),e.jsxs(ra,{children:[e.jsx(na,{asChild:!0,children:e.jsxs(R,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12",children:[e.jsx(et,{className:"mr-2 h-4 w-4"}),c.periodEndDate?Ne(c.periodEndDate,"PPP"):"End date"]})}),e.jsx(ia,{className:"w-auto p-0",align:"start",children:e.jsx(yi,{mode:"single",selected:c.periodEndDate,onSelect:f=>u("periodEndDate",f),initialFocus:!0})})]})]})]}),(c.periodStartDate||c.periodEndDate)&&e.jsx("p",{className:"text-xs text-gray-600 mt-2",children:c.periodStartDate&&c.periodEndDate?`Period: ${Ne(c.periodStartDate,"MMM dd, yyyy")} - ${Ne(c.periodEndDate,"MMM dd, yyyy")}`:"Please select both start and end dates for the period"})]})]})]});case 2:return e.jsxs(Kt.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(Ce,{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(Z,{className:"border-2",children:[e.jsx(ae,{className:"bg-gradient-to-br from-blue-50 to-indigo-50",children:e.jsxs(ne,{className:"flex items-center gap-2",children:[e.jsx(hs,{className:"w-5 h-5 text-blue-600"}),"Activity Information"]})}),e.jsx(X,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(Y,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:c.activityName})]}),e.jsxs("div",{children:[e.jsx(Y,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Type"}),e.jsx(ee,{variant:"secondary",className:"mt-1",children:c.activityType})]})]})})]}),e.jsxs(Z,{className:"border-2",children:[e.jsx(ae,{className:"bg-gradient-to-br from-green-50 to-emerald-50",children:e.jsxs(ne,{className:"flex items-center gap-2",children:[e.jsx(ho,{className:"w-5 h-5 text-green-600"}),"Dealer Information"]})}),e.jsx(X,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(Y,{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:c.dealerCode})]}),e.jsxs("div",{children:[e.jsx(Y,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:c.dealerName})]}),e.jsxs("div",{children:[e.jsx(Y,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Email"}),e.jsx("p",{className:"text-gray-900 mt-1",children:c.dealerEmail})]}),e.jsxs("div",{children:[e.jsx(Y,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Phone"}),e.jsx("p",{className:"text-gray-900 mt-1",children:c.dealerPhone})]}),c.dealerAddress&&e.jsxs("div",{className:"col-span-2",children:[e.jsx(Y,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Address"}),e.jsx("p",{className:"text-gray-900 mt-1",children:c.dealerAddress})]})]})})]}),e.jsxs(Z,{className:"border-2",children:[e.jsx(ae,{className:"bg-gradient-to-br from-purple-50 to-pink-50",children:e.jsxs(ne,{className:"flex items-center gap-2",children:[e.jsx(et,{className:"w-5 h-5 text-purple-600"}),"Date & Location"]})}),e.jsx(X,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(Y,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:c.activityDate?Ne(c.activityDate,"PPP"):"N/A"})]}),e.jsxs("div",{children:[e.jsx(Y,{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(uo,{className:"w-4 h-4 text-gray-500"}),e.jsx("p",{className:"font-semibold text-gray-900",children:c.location})]})]}),c.estimatedBudget&&e.jsxs("div",{className:"col-span-2",children:[e.jsx(Y,{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:c.estimatedBudget})]})]})})]}),e.jsxs(Z,{className:"border-2",children:[e.jsx(ae,{className:"bg-gradient-to-br from-orange-50 to-amber-50",children:e.jsxs(ne,{className:"flex items-center gap-2",children:[e.jsx(Re,{className:"w-5 h-5 text-orange-600"}),"Request Details"]})}),e.jsx(X,{className:"pt-6 space-y-4",children:e.jsxs("div",{children:[e.jsx(Y,{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:c.requestDescription})})]})})]}),(c.periodStartDate||c.periodEndDate)&&e.jsxs(Z,{className:"border-2",children:[e.jsx(ae,{className:"bg-gradient-to-br from-cyan-50 to-blue-50",children:e.jsxs(ne,{className:"flex items-center gap-2",children:[e.jsx(Ue,{className:"w-5 h-5 text-cyan-600"}),"Period"]})}),e.jsx(X,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(Y,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Start Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:c.periodStartDate?Ne(c.periodStartDate,"PPP"):"Not specified"})]}),e.jsxs("div",{children:[e.jsx(Y,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"End Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:c.periodEndDate?Ne(c.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(Tr,{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(R,{variant:"ghost",onClick:t,className:"mb-3 sm:mb-4 gap-2 text-sm sm:text-base",children:[e.jsx(Ms,{className:"w-3 h-3 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Back to Templates"}),e.jsx("span",{className:"sm:hidden",children:"Back"})]}),e.jsx("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-0",children:e.jsxs("div",{children:[e.jsx(ee,{variant:"secondary",className:"mb-2 text-xs",children:"Claim Management Template"}),e.jsx("h1",{className:"text-xl sm:text-2xl lg:text-3xl font-bold text-gray-900",children:"New Claim Request"}),e.jsxs("p",{className:"text-sm sm:text-base text-gray-600 mt-1",children:["Step ",a," of ",m,": ",e.jsx("span",{className:"hidden sm:inline",children:bi[a-1]})]})]})}),e.jsxs("div",{className:"mt-4 sm:mt-6",children:[e.jsx(_s,{value:a/m*100,className:"h-2"}),e.jsx("div",{className:"flex justify-between mt-2 px-1",children:bi.map((f,j)=>e.jsx("span",{className:`text-xs sm:text-sm ${j+1<=a?"text-blue-600 font-medium":"text-gray-400"}`,children:j+1},j))})]})]}),e.jsx(Z,{className:"mb-6 sm:mb-8",children:e.jsx(X,{className:"p-4 sm:p-6 lg:p-8",children:e.jsx(Rn,{mode:"wait",children:C()})})}),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(R,{variant:"outline",onClick:g,disabled:a===1,className:"gap-2 w-full sm:w-auto order-2 sm:order-1",children:[e.jsx(Ms,{className:"w-4 h-4"}),"Previous"]}),a<m?e.jsxs(R,{onClick:p,disabled:!h(),className:"gap-2 w-full sm:w-auto order-1 sm:order-2",children:["Next",e.jsx(Vt,{className:"w-4 h-4"})]}):e.jsxs(R,{onClick:v,disabled:!h(),className:"gap-2 bg-green-600 hover:bg-green-700 w-full sm:w-auto order-1 sm:order-2",children:[e.jsx(Za,{className:"w-4 h-4"}),"Submit Claim Request"]})]})]})})}function Mh({icon:t,title:s,description:a,badge:r,actions:n,testId:i="page-header"}){return e.jsxs("div",{className:"flex flex-col lg:flex-row lg:items-center justify-between gap-3 sm:gap-4 md:gap-6","data-testid":i,children:[e.jsx("div",{className:"space-y-1 sm:space-y-2",children:e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("div",{className:"w-10 h-10 sm:w-12 sm:h-12 bg-gradient-to-br from-slate-800 to-slate-900 rounded-xl flex items-center justify-center shadow-lg","data-testid":`${i}-icon-container`,children:e.jsx(t,{className:"w-5 h-5 sm:w-6 sm:h-6 text-white","data-testid":`${i}-icon`})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl sm:text-2xl md:text-3xl font-bold text-gray-900","data-testid":`${i}-title`,children:s}),e.jsx("p",{className:"text-sm sm:text-base text-gray-600","data-testid":`${i}-description`,children:a})]})]})}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[r&&e.jsxs(ee,{variant:"secondary",className:"text-xs sm:text-sm md:text-base px-2 sm:px-3 md:px-4 py-1 sm:py-1.5 md:py-2 bg-slate-100 text-slate-800 font-semibold","data-testid":`${i}-badge`,children:[r.loading?"Loading…":r.value,e.jsx("span",{className:"hidden sm:inline ml-1",children:r.label})]}),n]})]})}function gs({label:t,value:s,icon:a,iconColor:r,gradient:n,textColor:i,valueColor:o,testId:l="stats-card",onClick:c}){return e.jsx(Z,{className:`${n} border transition-shadow ${c?"cursor-pointer hover:shadow-lg":"hover:shadow-md"}`,"data-testid":l,onClick:c,children:e.jsx(X,{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 Q2({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(gs,{label:"Total",value:t.total,icon:Re,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(gs,{label:"Pending",value:t.pending,icon:Ue,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(gs,{label:"Paused",value:t.paused,icon:ca,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(gs,{label:"Approved",value:t.approved,icon:Ce,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(gs,{label:"Rejected",value:t.rejected,icon:ht,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(gs,{label:"Draft",value:t.draft,icon:Nn,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(gs,{label:"Closed",value:t.closed,icon:wn,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 q2({searchTerm:t,statusFilter:s,priorityFilter:a,onSearchChange:r,onStatusChange:n,onPriorityChange:i}){return e.jsx(Z,{className:"border-gray-200","data-testid":"my-requests-filters",children:e.jsx(X,{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(bs,{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(je,{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(_e,{value:s,onValueChange:n,children:[e.jsx(Oe,{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(Le,{placeholder:"Status"})}),e.jsxs($e,{children:[e.jsx(H,{value:"all",children:"All Status"}),e.jsx(H,{value:"draft",children:"Draft"}),e.jsx(H,{value:"pending",children:"Pending"}),e.jsx(H,{value:"paused",children:"Paused"}),e.jsx(H,{value:"approved",children:"Approved"}),e.jsx(H,{value:"rejected",children:"Rejected"}),e.jsx(H,{value:"closed",children:"Closed"})]})]}),e.jsxs(_e,{value:a,onValueChange:i,children:[e.jsx(Oe,{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(Le,{placeholder:"Priority"})}),e.jsxs($e,{children:[e.jsx(H,{value:"all",children:"All Priority"}),e.jsx(H,{value:"express",children:"Express"}),e.jsx(H,{value:"standard",children:"Standard"})]})]})]})]})})})}function eS(t){switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ts,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:kt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:kt,iconColor:"text-gray-600"}}}function tS(t){switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:Ce,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:ht,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:Ue,iconColor:"text-yellow-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ce,iconColor:"text-gray-600"};case"draft":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Nn,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Pe,iconColor:"text-gray-600"}}}const sS=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 aS({request:t,index:s,onViewRequest:a}){var l;const r=tS(t.status),n=eS(t.priority),i=r.icon,o=n.icon;return e.jsx(Kt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:s*.1},children:e.jsx(Z,{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(X,{className:"p-3 sm:p-6",children:e.jsxs("div",{className:"space-y-3 sm:space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"text-base sm:text-lg font-semibold text-gray-900 mb-2 group-hover:text-blue-600 transition-colors line-clamp-2","data-testid":"request-title",children:t.title}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2 mb-2",children:[e.jsxs(ee,{variant:"outline",className:`${r.color} border font-medium text-xs shrink-0`,"data-testid":"status-badge",children:[e.jsx(i,{className:"w-3 h-3 mr-1"}),e.jsx("span",{className:"capitalize",children:t.status})]}),(((l=t.pauseInfo)==null?void 0:l.isPaused)||t.isPaused)&&e.jsxs(ee,{variant:"outline",className:"bg-orange-50 text-orange-700 border-orange-300 font-medium text-xs shrink-0","data-testid":"pause-badge",children:[e.jsx(ca,{className:"w-3 h-3 mr-1"}),"Paused"]}),e.jsxs(ee,{variant:"outline",className:`${n.color} border font-medium text-xs capitalize shrink-0`,"data-testid":"priority-badge",children:[e.jsx(o,{className:"w-3 h-3 mr-1"}),t.priority]}),t.templateType&&e.jsxs(ee,{variant:"secondary",className:"bg-purple-100 text-purple-700 text-xs shrink-0 hidden sm:inline-flex","data-testid":"template-badge",children:[e.jsx(Re,{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:sS(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:"})," ",Ls(t.submittedDate)]})]})]}),e.jsx(Vt,{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(St,{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(Ys,{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(Ue,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{"data-testid":"submitted-timestamp",children:["Submitted: ",Ls(t.submittedDate)]})]})]})]})})})})}function rS({requests:t,loading:s,searchTerm:a,statusFilter:r,priorityFilter:n,onViewRequest:i}){if(s)return e.jsx(Z,{"data-testid":"loading-state",children:e.jsx(X,{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(Z,{"data-testid":"empty-state",children:e.jsxs(X,{className:"p-12 text-center",children:[e.jsx(Re,{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(aS,{request:o,index:l,onViewRequest:i},o.id))})}function nS(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 Fh(t){return Array.isArray(t)?t.map(nS):[]}function iS({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 is.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=Fh(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 oS={searchTerm:"",statusFilter:"all",priorityFilter:"all",currentPage:1},_h=Ja({name:"myRequests",initialState:oS,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:lS,setStatusFilter:cS,setPriorityFilter:dS,setCurrentPage:mS,clearFilters:uS}=_h.actions;function hS({onFiltersChange:t,debounceMs:s=500}={}){const a=Pr(),r=x.useRef(null),n=x.useRef(!0),{searchTerm:i,statusFilter:o,priorityFilter:l,currentPage:c}=qa(y=>y.myRequests),d=x.useCallback(y=>a(lS(y)),[a]),m=x.useCallback(y=>a(cS(y)),[a]),u=x.useCallback(y=>a(dS(y)),[a]),h=x.useCallback(y=>a(mS(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(uS())},[a]);return{searchTerm:i,statusFilter:o,priorityFilter:l,currentPage:c,setSearchTerm:d,setStatusFilter:m,setPriorityFilter:u,setCurrentPage:h,getFilters:p,resetFilters:g}}function pS({onViewRequest:t,dynamicRequests:s=[]}){const{user:a}=ts(),r=iS({itemsPerPage:10}),n=x.useRef(r.fetchMyRequests);n.current=r.fetchMyRequests;const i=hS(),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 mt.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=Fh(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(Mh,{icon:Re,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(Q2,{stats:y,onStatusFilter:C=>{i.setStatusFilter(C)}}),e.jsx(q2,{searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,onSearchChange:i.setSearchTerm,onStatusChange:i.setStatusFilter,onPriorityChange:i.setPriorityFilter}),e.jsx(rS,{requests:g,loading:r.loading,searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,onViewRequest:t}),e.jsx(Fa,{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 Lh({isOrgLevel:t,isAdmin:s,loading:a,exporting:r,onExport:n}){const i=()=>"All Requests",o=()=>t?"View and filter all organization-wide workflow requests":s?"Viewing requests where you are initiator, approver, or participant":"View and filter your workflow requests";return e.jsxs("div",{className:"flex items-start justify-between gap-4","data-testid":"requests-header-container",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Mh,{icon:Re,title:i(),description:o(),testId:"requests-header"}),e.jsx(ee,{variant:"outline",className:t?"bg-blue-50 text-blue-700 border-blue-200":"bg-green-50 text-green-700 border-green-200",children:t?"Organization":"Personal"})]}),e.jsx(R,{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(es,{className:"w-4 h-4 mr-2 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Qt,{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(gs,{label:"Total",value:t.total,icon:Re,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(gs,{label:"Pending",value:t.pending,icon:Ue,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(gs,{label:"Paused",value:t.paused,icon:ca,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(gs,{label:"Approved",value:t.approved,icon:Ce,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(gs,{label:"Rejected",value:t.rejected,icon:ht,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(gs,{label:"Closed",value:t.closed,icon:wn,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 xS=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ts,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:kt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:kt,iconColor:"text-gray-600"}}},gS=t=>{switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:Ce,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:ht,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:Ue,iconColor:"text-yellow-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ce,iconColor:"text-gray-600"};case"draft":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Nn,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Pe,iconColor:"text-gray-600"}}},fS=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 yS({request:t,index:s,onViewRequest:a}){var l;const r=gS(t.status),n=xS(t.priority),i=r.icon,o=n.icon;return e.jsx(Kt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:s*.1},children:e.jsx(Z,{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(X,{className:"p-3 sm:p-6",children:e.jsxs("div",{className:"space-y-3 sm:space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"text-base sm:text-lg font-semibold text-gray-900 mb-2 group-hover:text-blue-600 transition-colors line-clamp-2","data-testid":"request-title",children:t.title}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2 mb-2",children:[e.jsxs(ee,{variant:"outline",className:`${r.color} border font-medium text-xs shrink-0`,"data-testid":"status-badge",children:[e.jsx(i,{className:"w-3 h-3 mr-1"}),e.jsx("span",{className:"capitalize",children:t.status})]}),(((l=t.pauseInfo)==null?void 0:l.isPaused)||t.isPaused)&&e.jsxs(ee,{variant:"outline",className:"bg-orange-50 text-orange-700 border-orange-300 font-medium text-xs shrink-0","data-testid":"pause-badge",children:[e.jsx(ca,{className:"w-3 h-3 mr-1"}),"Paused"]}),e.jsxs(ee,{variant:"outline",className:`${n.color} border font-medium text-xs capitalize shrink-0`,"data-testid":"priority-badge",children:[e.jsx(o,{className:"w-3 h-3 mr-1"}),t.priority]}),t.department&&e.jsx(ee,{variant:"secondary",className:"bg-purple-100 text-purple-700 text-xs shrink-0","data-testid":"department-badge",children:t.department})]}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 mb-2 sm:mb-3 line-clamp-2 leading-relaxed","data-testid":"request-description",children:fS(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:"})," ",Ls(t.submittedDate)]})]})]}),e.jsx(Vt,{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(St,{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(Ys,{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(Ue,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{"data-testid":"submitted-timestamp",children:["Submitted: ",Ls(t.submittedDate)]})]})]})]})})})})}function $h({requests:t,loading:s,hasActiveFilters:a,onViewRequest:r}){return s?e.jsx(Z,{"data-testid":"loading-state",children:e.jsx(X,{className:"p-6 text-sm text-gray-600",children:"Loading requests…"})}):t.length===0?e.jsx(Z,{"data-testid":"empty-state",children:e.jsxs(X,{className:"p-12 text-center",children:[e.jsx(Re,{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(yS,{request:n,index:i,onViewRequest:r},n.id))})}const bS={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},Uh=Ja({name:"requests",initialState:bS,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:vS,setStatusFilter:jS,setPriorityFilter:NS,setSlaComplianceFilter:wS,setDepartmentFilter:CS,setInitiatorFilter:SS,setApproverFilter:AS,setApproverFilterType:kS,setDateRange:gd,setCustomStartDate:vi,setCustomEndDate:ji,setShowCustomDatePicker:Yr,setCurrentPage:TS,clearFilters:DS}=Uh.actions;function Bh(){const t=Pr(),{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}=qa(k=>k.requests),g=x.useCallback(k=>t(vS(k)),[t]),y=x.useCallback(k=>t(jS(k)),[t]),v=x.useCallback(k=>t(NS(k)),[t]),C=x.useCallback(k=>t(wS(k)),[t]),f=x.useCallback(k=>t(CS(k)),[t]),j=x.useCallback(k=>t(SS(k)),[t]),b=x.useCallback(k=>t(AS(k)),[t]),N=x.useCallback(k=>t(kS(k)),[t]),A=x.useCallback(k=>t(gd(k)),[t]),D=x.useCallback(k=>t(vi(k)),[t]),T=x.useCallback(k=>t(ji(k)),[t]),P=x.useCallback(k=>t(Yr(k)),[t]),w=x.useCallback(k=>t(TS(k)),[t]),S=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]),M=x.useCallback(()=>{t(DS())},[t]),B=x.useCallback(k=>{const I=k;t(gd(I)),I!=="custom"?(t(vi(void 0)),t(ji(void 0)),t(Yr(!1))):t(Yr(!0))},[t]),_=x.useCallback(()=>{m&&u&&(m>u&&(t(vi(u)),t(ji(m))),t(Yr(!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:N,setDateRange:A,setCustomStartDate:D,setCustomEndDate:T,setShowCustomDatePicker:P,setCurrentPage:w,getFilters:S,clearFilters:M,handleDateRangeChange:B,handleApplyCustomDate:_}}function pn({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 RS(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 N=j.levelNumber||j.level_number||0;return(b.levelNumber||b.level_number||0)-N})[0];f&&(n=f.approverName||((h=f.approver)==null?void 0:h.name)||((p=f.approver)==null?void 0:p.displayName)||f.approverEmail||((g=f.approver)==null?void 0:g.email)||"—")}}const l=t.currentLevel||t.current_level||t.currentLevelNumber||t.current_level_number,c=t.totalLevels||t.total_levels||t.totalLevelsCount||t.total_levels_count;if(l&&c)i=`${l} of ${c}`;else if(t.approvals&&Array.isArray(t.approvals)&&t.approvals.length>0){const v=t.approvals.find(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 Vh(t){return Array.isArray(t)?t.map(RS):[]}function PS(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 zh={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(xn,function(){return function(a,r){r.prototype.isSameOrBefore=function(n,i){return this.isSame(n,i)||this.isBefore(n,i)}}})})(zh);var ES=zh.exports;const Hh=gn(ES);var Wh={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(xn,function(){return function(a,r){r.prototype.isSameOrAfter=function(n,i){return this.isSame(n,i)||this.isAfter(n,i)}}})})(Wh);var IS=Wh.exports;const Kh=gn(IS);bt.extend(Kh);bt.extend(Hh);function MS(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 A=((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 A?A!=="breached"&&A.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=bt(s.startDate).startOf("day").toDate(),n=bt(s.endDate).endOf("day").toDate();else{const i=bt();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=bt(m).startOf("day").toDate(),h=bt(r).startOf("day").toDate(),p=bt(n).endOf("day").toDate();return u>=h&&u<=p}const l=bt(o).startOf("day").toDate(),c=bt(r).startOf("day").toDate(),d=bt(n).endOf("day").toDate();return l>=c&&l<=d}))}return a}bt.extend(Hh);bt.extend(Kh);function FS(t){if(!t)return"N/A";try{const s=typeof t=="string"?new Date(t):t;return Ne(s,"yyyy-MM-dd HH:mm:ss")}catch{return"N/A"}}async function Gh(t,s){const a=MS(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,N,A;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=((N=c.currentApprover)==null?void 0:N.displayName)||((A=c.currentApprover)==null?void 0:A.email)||c.currentApproverName||"N/A",g=c.currentApproverLevel||c.approvalLevel||c.currentLevel||"N/A",y=FS(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 _S({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 is.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 is.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 LS(t){const a=[];let r=1,n=!0;const i=100;for(;n&&r<=i;){const o=t?await is.listWorkflows({page:r,limit:100}):await is.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 OS({onViewRequest:t}){const{user:s}=ts(),a=qa(U=>U.dashboard.viewAsUser),r=x.useMemo(()=>Cn(s),[s]),n=x.useMemo(()=>r&&!a,[r,a]),i=Bh(),[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,N]=x.useState(1),[A,D]=x.useState(0),[T]=x.useState(10),P=pn({allUsers:f,filterValue:i.initiatorFilter,onFilterChange:i.setInitiatorFilter}),w=pn({allUsers:f,filterValue:i.approverFilter,onFilterChange:i.setApproverFilter}),S=x.useCallback(async(U,oe,ge,G)=>{try{const me=G==null?void 0:G.slaCompliance;if(me&&me!=="all"&&me!=="breached"&&me!=="compliant"){const V={};G!=null&&G.search&&(V.search=G.search),G!=null&&G.priority&&G.priority!=="all"&&(V.priority=G.priority),G!=null&&G.department&&G.department!=="all"&&(V.department=G.department),G!=null&&G.initiator&&G.initiator!=="all"&&(V.initiator=G.initiator),G!=null&&G.approver&&G.approver!=="all"&&(V.approver=G.approver,V.approverType=G.approverType||"current"),V.slaCompliance=me,U&&(V.dateRange=U),oe&&(V.startDate=oe.toISOString()),ge&&(V.endDate=ge.toISOString());const q=n?await is.listWorkflows({page:1,limit:1e3,...V}):await is.listParticipantRequests({page:1,limit:1e3,...V}),ie=Array.isArray(q==null?void 0:q.data)?q.data:[],ue=ie.length,Te=ie.filter(Ge=>{const He=(Ge.status||"").toString().toUpperCase();return He==="PENDING"||He==="IN_PROGRESS"}).length,qe=ie.filter(Ge=>(Ge.status||"").toString().toUpperCase()==="APPROVED").length,ze=ie.filter(Ge=>(Ge.status||"").toString().toUpperCase()==="REJECTED").length,Ze=ie.filter(Ge=>(Ge.status||"").toString().toUpperCase()==="CLOSED").length;p({total:ue,pending:Te,paused:0,approved:qe,rejected:ze,draft:0,closed:Ze})}else{const V=await mt.getRequestStats(U,oe?oe.toISOString():void 0,ge?ge.toISOString():void 0,void 0,G==null?void 0:G.priority,G==null?void 0:G.department,G==null?void 0:G.initiator,G==null?void 0:G.approver,G==null?void 0:G.approverType,G==null?void 0:G.search,G==null?void 0:G.slaCompliance,!n);p({total:V.totalRequests||0,pending:V.openRequests||0,paused:V.pausedRequests||0,approved:V.approvedRequests||0,rejected:V.rejectedRequests||0,draft:V.draftRequests||0,closed:V.closedRequests||0})}}catch(me){console.error("Failed to fetch backend stats:",me)}finally{}},[n]),M=x.useCallback(async()=>{try{C(!0);const U=await mt.getDepartments();y(U)}catch{}finally{C(!1)}},[]),B=x.useCallback(async()=>{try{const oe=(await fs.getAllUsers()).map(ge=>({userId:ge.userId,email:ge.email,displayName:ge.displayName||ge.email}));j(oe)}catch(U){console.error("Failed to fetch users:",U)}},[]),_=x.useRef(i),$=x.useRef(S);x.useEffect(()=>{_.current=i,$.current=S},[i,S]);const k=x.useCallback(async(U=1)=>{try{U===1&&(d(!0),l([]));const oe=_.current.getFilters(),ge=await _S({page:U,itemsPerPage:T,filters:oe,isOrgLevel:n});l(ge.data),i.setCurrentPage(ge.pagination.page),N(ge.pagination.totalPages),D(ge.pagination.total)}catch{l([])}finally{d(!1)}},[T,n]),I=x.useCallback(async()=>{try{u(!0);const U=await LS(n);await Gh(U,i.getFilters())}catch(U){console.error("Failed to export requests:",U),alert("Failed to export requests. Please try again.")}finally{u(!1)}},[n,i]);x.useEffect(()=>{M(),B()},[M,B]),x.useEffect(()=>{const U=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";$.current(ge,i.customStartDate,i.customEndDate,oe)},i.searchTerm?500:0);return()=>clearTimeout(U)},[n,i.dateRange,i.customStartDate,i.customEndDate,i.priorityFilter,i.departmentFilter,i.initiatorFilter,i.approverFilter,i.approverFilterType,i.searchTerm,i.slaComplianceFilter]);const E=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}),F=x.useRef(!1);x.useEffect(()=>{const U=i.currentPage||1;k(U),F.current=!0},[]),x.useEffect(()=>{if(!F.current)return;const U=E.current;if(!(U.searchTerm!==i.searchTerm||U.statusFilter!==i.statusFilter||U.priorityFilter!==i.priorityFilter||U.slaComplianceFilter!==i.slaComplianceFilter||U.departmentFilter!==i.departmentFilter||U.initiatorFilter!==i.initiatorFilter||U.approverFilter!==i.approverFilter||U.approverFilterType!==i.approverFilterType||U.dateRange!==i.dateRange||U.customStartDate!==i.customStartDate||U.customEndDate!==i.customEndDate||U.isOrgLevel!==n))return;const ge=setTimeout(()=>{i.setCurrentPage(1),k(1),E.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!==U.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 O=x.useCallback(U=>{U>=1&&U<=b&&(i.setCurrentPage(U),k(U))},[b,k,i]),L=x.useMemo(()=>Vh(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}:PS([],n,h,!1,A,L),[n,h,A,L]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"requests-page",children:[e.jsx(Lh,{isOrgLevel:n,isAdmin:r,loading:c,exporting:m,onExport:I}),e.jsx(Oh,{stats:J,onStatusFilter:U=>{i.setStatusFilter(U)}}),e.jsx(Z,{className:"border-gray-200 shadow-md","data-testid":"requests-filters",children:e.jsx(X,{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(kr,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),i.hasActiveFilters&&e.jsx(ee,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),i.hasActiveFilters&&e.jsxs(R,{variant:"ghost",size:"sm",onClick:i.clearFilters,className:"gap-2",children:[e.jsx(es,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Tt,{}),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(bs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(je,{placeholder:"Search requests...",value:i.searchTerm,onChange:U=>i.setSearchTerm(U.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(_e,{value:i.statusFilter,onValueChange:i.setStatusFilter,children:[e.jsx(Oe,{className:"h-10","data-testid":"status-filter",children:e.jsx(Le,{placeholder:"All Status"})}),e.jsxs($e,{children:[e.jsx(H,{value:"all",children:"All Status"}),e.jsx(H,{value:"pending",children:"Pending"}),e.jsx(H,{value:"paused",children:"Paused"}),e.jsx(H,{value:"approved",children:"Approved"}),e.jsx(H,{value:"rejected",children:"Rejected"}),e.jsx(H,{value:"closed",children:"Closed"})]})]}),e.jsxs(_e,{value:i.priorityFilter,onValueChange:i.setPriorityFilter,children:[e.jsx(Oe,{className:"h-10","data-testid":"priority-filter",children:e.jsx(Le,{placeholder:"All Priority"})}),e.jsxs($e,{children:[e.jsx(H,{value:"all",children:"All Priority"}),e.jsx(H,{value:"express",children:"Express"}),e.jsx(H,{value:"standard",children:"Standard"})]})]}),e.jsxs(_e,{value:i.departmentFilter,onValueChange:i.setDepartmentFilter,disabled:v||g.length===0,children:[e.jsx(Oe,{className:"h-10","data-testid":"department-filter",children:e.jsx(Le,{placeholder:v?"Loading...":"All Departments"})}),e.jsxs($e,{children:[e.jsx(H,{value:"all",children:"All Departments"}),g.map(U=>e.jsx(H,{value:U,children:U},U))]})]}),e.jsxs(_e,{value:i.slaComplianceFilter,onValueChange:i.setSlaComplianceFilter,children:[e.jsx(Oe,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(Le,{placeholder:"All SLA Status"})}),e.jsxs($e,{children:[e.jsx(H,{value:"all",children:"All SLA Status"}),e.jsx(H,{value:"compliant",children:"Compliant"}),e.jsx(H,{value:"on-track",children:"On Track"}),e.jsx(H,{value:"approaching",children:"Approaching"}),e.jsx(H,{value:"critical",children:"Critical"}),e.jsx(H,{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(Y,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:P.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:P.selectedUser.displayName||P.selectedUser.email}),e.jsx(R,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:P.handleClear,children:e.jsx(ut,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(je,{placeholder:"Search initiator...",value:P.searchQuery,onChange:U=>P.handleSearch(U.target.value),onFocus:()=>{P.searchResults.length>0&&P.setShowResults(!0)},onBlur:()=>setTimeout(()=>P.setShowResults(!1),200),className:"h-10","data-testid":"initiator-search-input"}),P.showResults&&P.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:P.searchResults.map(U=>e.jsx("button",{type:"button",onClick:()=>P.handleSelect(U),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:U.displayName||U.email}),U.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:U.email})]})},U.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(Y,{className:"text-sm font-medium text-gray-700",children:"Approver"}),i.approverFilter!=="all"&&e.jsxs(_e,{value:i.approverFilterType,onValueChange:U=>i.setApproverFilterType(U),children:[e.jsx(Oe,{className:"h-7 w-32 text-xs",children:e.jsx(Le,{})}),e.jsxs($e,{children:[e.jsx(H,{value:"current",children:"Current Only"}),e.jsx(H,{value:"any",children:"Any Approver"})]})]})]}),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(R,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:w.handleClear,children:e.jsx(ut,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(je,{placeholder:"Search approver...",value:w.searchQuery,onChange:U=>w.handleSearch(U.target.value),onFocus:()=>{w.searchResults.length>0&&w.setShowResults(!0)},onBlur:()=>setTimeout(()=>w.setShowResults(!1),200),className:"h-10","data-testid":"approver-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(U=>e.jsx("button",{type:"button",onClick:()=>w.handleSelect(U),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:U.displayName||U.email}),U.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:U.email})]})},U.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(et,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(_e,{value:i.dateRange,onValueChange:i.handleDateRangeChange,children:[e.jsx(Oe,{className:"w-[160px] h-10",children:e.jsx(Le,{placeholder:"Date Range"})}),e.jsxs($e,{children:[e.jsx(H,{value:"all",children:"All Time"}),e.jsx(H,{value:"today",children:"Today"}),e.jsx(H,{value:"week",children:"This Week"}),e.jsx(H,{value:"month",children:"This Month"}),e.jsx(H,{value:"last7days",children:"Last 7 Days"}),e.jsx(H,{value:"last30days",children:"Last 30 Days"}),e.jsx(H,{value:"custom",children:"Custom Range"})]})]}),i.dateRange==="custom"&&e.jsxs(ra,{open:i.showCustomDatePicker,onOpenChange:i.setShowCustomDatePicker,children:[e.jsx(na,{asChild:!0,children:e.jsxs(R,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(et,{className:"w-4 h-4"}),i.customStartDate&&i.customEndDate?`${Ne(i.customStartDate,"MMM d, yyyy")} - ${Ne(i.customEndDate,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(ia,{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(Y,{htmlFor:"start-date",children:"Start Date"}),e.jsx(je,{id:"start-date",type:"date",value:i.customStartDate?Ne(i.customStartDate,"yyyy-MM-dd"):"",onChange:U=>{const oe=U.target.value?new Date(U.target.value):void 0;oe?(i.setCustomStartDate(oe),i.customEndDate&&oe>i.customEndDate&&i.setCustomEndDate(oe)):i.setCustomStartDate(void 0)},max:Ne(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Y,{htmlFor:"end-date",children:"End Date"}),e.jsx(je,{id:"end-date",type:"date",value:i.customEndDate?Ne(i.customEndDate,"yyyy-MM-dd"):"",onChange:U=>{const oe=U.target.value?new Date(U.target.value):void 0;oe?(i.setCustomEndDate(oe),i.customStartDate&&oe<i.customStartDate&&i.setCustomStartDate(oe)):i.setCustomEndDate(void 0)},min:i.customStartDate?Ne(i.customStartDate,"yyyy-MM-dd"):void 0,max:Ne(new Date,"yyyy-MM-dd"),className:"w-full"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(R,{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(R,{size:"sm",variant:"outline",onClick:()=>{i.setShowCustomDatePicker(!1),i.setCustomStartDate(void 0),i.setCustomEndDate(void 0),i.setDateRange("month")},children:"Cancel"})]})]})})]})]})]})})}),e.jsx($h,{requests:L,loading:c,hasActiveFilters:i.hasActiveFilters,onViewRequest:t}),e.jsx(Fa,{currentPage:i.currentPage||1,totalPages:b,totalRecords:A,itemsPerPage:T,onPageChange:O,loading:c,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}async function $S({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 is.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 fd=100;async function US(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 is.listParticipantRequests({page:r,limit:fd,...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===fd}}return s}function BS({onViewRequest:t}){const s=Bh(),[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),N=pn({allUsers:g,filterValue:s.initiatorFilter,onFilterChange:s.setInitiatorFilter}),A=pn({allUsers:g,filterValue:s.approverFilter,onFilterChange:s.setApproverFilter}),D=x.useCallback(async(F,O,L,J)=>{try{const U=await mt.getRequestStats(F,O?O.toISOString():void 0,L?L.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:U.totalRequests||0,pending:U.openRequests||0,paused:U.pausedRequests||0,approved:U.approvedRequests||0,rejected:U.rejectedRequests||0,draft:U.draftRequests||0,closed:U.closedRequests||0})}catch(U){console.error("Failed to fetch backend stats:",U)}},[]),T=x.useCallback(async()=>{try{p(!0);const F=await mt.getDepartments();u(F)}catch{}finally{p(!1)}},[]),P=x.useCallback(async()=>{try{const O=(await fs.getAllUsers()).map(L=>({userId:L.userId,email:L.email,displayName:L.displayName||L.email}));y(O)}catch(F){console.error("Failed to fetch users:",F)}},[]),w=x.useRef(s),S=x.useRef(D);x.useEffect(()=>{w.current=s,S.current=D},[s,D]);const M=x.useCallback(async(F=1)=>{try{F===1&&(i(!0),r([]));const O=w.current.getFilters(),L=await $S({page:F,itemsPerPage:b,filters:O});r(L.data),s.setCurrentPage(L.pagination.page),C(L.pagination.totalPages),j(L.pagination.total)}catch{r([])}finally{i(!1)}},[b]),B=x.useCallback(async()=>{try{l(!0);const F=await US(s.getFilters());await Gh(F,s.getFilters())}catch(F){console.error("Failed to export requests:",F),alert("Failed to export requests. Please try again.")}finally{l(!1)}},[s]);x.useEffect(()=>{T(),P()},[T,P]),x.useEffect(()=>{const F=setTimeout(()=>{const O={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},L=s.dateRange||"month";S.current(L,s.customStartDate,s.customEndDate,O)},s.searchTerm?500:0);return()=>clearTimeout(F)},[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}),$=x.useRef(!1);x.useEffect(()=>{const F=s.currentPage||1;M(F),$.current=!0},[]),x.useEffect(()=>{if(!$.current)return;const F=_.current;if(!(F.searchTerm!==s.searchTerm||F.statusFilter!==s.statusFilter||F.priorityFilter!==s.priorityFilter||F.slaComplianceFilter!==s.slaComplianceFilter||F.departmentFilter!==s.departmentFilter||F.initiatorFilter!==s.initiatorFilter||F.approverFilter!==s.approverFilter||F.approverFilterType!==s.approverFilterType||F.dateRange!==s.dateRange||F.customStartDate!==s.customStartDate||F.customEndDate!==s.customEndDate))return;const L=setTimeout(()=>{s.setCurrentPage(1),M(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!==F.searchTerm?500:0);return()=>clearTimeout(L)},[s.searchTerm,s.statusFilter,s.priorityFilter,s.slaComplianceFilter,s.departmentFilter,s.initiatorFilter,s.approverFilter,s.approverFilterType,s.dateRange,s.customStartDate,s.customEndDate]);const k=x.useCallback(F=>{F>=1&&F<=v&&(s.setCurrentPage(F),M(F))},[v,M,s]),I=x.useMemo(()=>Vh(a),[a]),E=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 F=I.filter(oe=>{const ge=(oe.status||"").toString().toLowerCase();return ge==="pending"||ge==="in-progress"}).length,O=I.filter(oe=>(oe.status||"").toString().toLowerCase()==="paused").length,L=I.filter(oe=>(oe.status||"").toString().toLowerCase()==="approved").length,J=I.filter(oe=>(oe.status||"").toString().toLowerCase()==="rejected").length,U=I.filter(oe=>(oe.status||"").toString().toLowerCase()==="closed").length;return{total:f>0?f:I.length,pending:F,paused:O,approved:L,rejected:J,draft:0,closed:U}},[c,f,I]);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(Lh,{isOrgLevel:!1,isAdmin:!1,loading:n,exporting:o,onExport:B}),e.jsx(Oh,{stats:E,onStatusFilter:F=>{s.setStatusFilter(F)}}),e.jsx(Z,{className:"border-gray-200 shadow-md","data-testid":"requests-filters",children:e.jsx(X,{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(kr,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),s.hasActiveFilters&&e.jsx(ee,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),s.hasActiveFilters&&e.jsxs(R,{variant:"ghost",size:"sm",onClick:s.clearFilters,className:"gap-2",children:[e.jsx(es,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Tt,{}),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(bs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(je,{placeholder:"Search requests...",value:s.searchTerm,onChange:F=>s.setSearchTerm(F.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(_e,{value:s.statusFilter,onValueChange:s.setStatusFilter,children:[e.jsx(Oe,{className:"h-10","data-testid":"status-filter",children:e.jsx(Le,{placeholder:"All Status"})}),e.jsxs($e,{children:[e.jsx(H,{value:"all",children:"All Status"}),e.jsx(H,{value:"pending",children:"Pending"}),e.jsx(H,{value:"paused",children:"Paused"}),e.jsx(H,{value:"approved",children:"Approved"}),e.jsx(H,{value:"rejected",children:"Rejected"}),e.jsx(H,{value:"closed",children:"Closed"})]})]}),e.jsxs(_e,{value:s.priorityFilter,onValueChange:s.setPriorityFilter,children:[e.jsx(Oe,{className:"h-10","data-testid":"priority-filter",children:e.jsx(Le,{placeholder:"All Priority"})}),e.jsxs($e,{children:[e.jsx(H,{value:"all",children:"All Priority"}),e.jsx(H,{value:"express",children:"Express"}),e.jsx(H,{value:"standard",children:"Standard"})]})]}),e.jsxs(_e,{value:s.departmentFilter,onValueChange:s.setDepartmentFilter,disabled:h||m.length===0,children:[e.jsx(Oe,{className:"h-10","data-testid":"department-filter",children:e.jsx(Le,{placeholder:h?"Loading...":"All Departments"})}),e.jsxs($e,{children:[e.jsx(H,{value:"all",children:"All Departments"}),m.map(F=>e.jsx(H,{value:F,children:F},F))]})]}),e.jsxs(_e,{value:s.slaComplianceFilter,onValueChange:s.setSlaComplianceFilter,children:[e.jsx(Oe,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(Le,{placeholder:"All SLA Status"})}),e.jsxs($e,{children:[e.jsx(H,{value:"all",children:"All SLA Status"}),e.jsx(H,{value:"compliant",children:"Compliant"}),e.jsx(H,{value:"on-track",children:"On Track"}),e.jsx(H,{value:"approaching",children:"Approaching"}),e.jsx(H,{value:"critical",children:"Critical"}),e.jsx(H,{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(Y,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:N.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:N.selectedUser.displayName||N.selectedUser.email}),e.jsx(R,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:N.handleClear,children:e.jsx(ut,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(je,{placeholder:"Search initiator...",value:N.searchQuery,onChange:F=>N.handleSearch(F.target.value),onFocus:()=>{N.searchResults.length>0&&N.setShowResults(!0)},onBlur:()=>setTimeout(()=>N.setShowResults(!1),200),className:"h-10","data-testid":"initiator-search-input"}),N.showResults&&N.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:N.searchResults.map(F=>e.jsx("button",{type:"button",onClick:()=>N.handleSelect(F),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:F.displayName||F.email}),F.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:F.email})]})},F.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(Y,{className:"text-sm font-medium text-gray-700",children:"Approver"}),s.approverFilter!=="all"&&e.jsxs(_e,{value:s.approverFilterType,onValueChange:F=>s.setApproverFilterType(F),children:[e.jsx(Oe,{className:"h-7 w-32 text-xs",children:e.jsx(Le,{})}),e.jsxs($e,{children:[e.jsx(H,{value:"current",children:"Current Only"}),e.jsx(H,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:A.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:A.selectedUser.displayName||A.selectedUser.email}),e.jsx(R,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:A.handleClear,children:e.jsx(ut,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(je,{placeholder:"Search approver...",value:A.searchQuery,onChange:F=>A.handleSearch(F.target.value),onFocus:()=>{A.searchResults.length>0&&A.setShowResults(!0)},onBlur:()=>setTimeout(()=>A.setShowResults(!1),200),className:"h-10","data-testid":"approver-search-input"}),A.showResults&&A.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:A.searchResults.map(F=>e.jsx("button",{type:"button",onClick:()=>A.handleSelect(F),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:F.displayName||F.email}),F.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:F.email})]})},F.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(et,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(_e,{value:s.dateRange,onValueChange:s.handleDateRangeChange,children:[e.jsx(Oe,{className:"w-[160px] h-10",children:e.jsx(Le,{placeholder:"Date Range"})}),e.jsxs($e,{children:[e.jsx(H,{value:"all",children:"All Time"}),e.jsx(H,{value:"today",children:"Today"}),e.jsx(H,{value:"week",children:"This Week"}),e.jsx(H,{value:"month",children:"This Month"}),e.jsx(H,{value:"last7days",children:"Last 7 Days"}),e.jsx(H,{value:"last30days",children:"Last 30 Days"}),e.jsx(H,{value:"custom",children:"Custom Range"})]})]}),s.dateRange==="custom"&&e.jsxs(ra,{open:s.showCustomDatePicker,onOpenChange:s.setShowCustomDatePicker,children:[e.jsx(na,{asChild:!0,children:e.jsxs(R,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(et,{className:"w-4 h-4"}),s.customStartDate&&s.customEndDate?`${Ne(s.customStartDate,"MMM d, yyyy")} - ${Ne(s.customEndDate,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(ia,{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(Y,{htmlFor:"start-date",children:"Start Date"}),e.jsx(je,{id:"start-date",type:"date",value:s.customStartDate?Ne(s.customStartDate,"yyyy-MM-dd"):"",onChange:F=>{const O=F.target.value?new Date(F.target.value):void 0;O?(s.setCustomStartDate(O),s.customEndDate&&O>s.customEndDate&&s.setCustomEndDate(O)):s.setCustomStartDate(void 0)},max:Ne(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Y,{htmlFor:"end-date",children:"End Date"}),e.jsx(je,{id:"end-date",type:"date",value:s.customEndDate?Ne(s.customEndDate,"yyyy-MM-dd"):"",onChange:F=>{const O=F.target.value?new Date(F.target.value):void 0;O?(s.setCustomEndDate(O),s.customStartDate&&O<s.customStartDate&&s.setCustomStartDate(O)):s.setCustomEndDate(void 0)},min:s.customStartDate?Ne(s.customStartDate,"yyyy-MM-dd"):void 0,max:Ne(new Date,"yyyy-MM-dd"),className:"w-full"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(R,{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(R,{size:"sm",variant:"outline",onClick:()=>{s.setShowCustomDatePicker(!1),s.setCustomStartDate(void 0),s.setCustomEndDate(void 0),s.setDateRange("month")},children:"Cancel"})]})]})})]})]})]})})}),e.jsx($h,{requests:I,loading:n,hasActiveFilters:s.hasActiveFilters,onViewRequest:t}),e.jsx(Fa,{currentPage:s.currentPage||1,totalPages:v,totalRecords:f,itemsPerPage:b,onPageChange:k,loading:n,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}function VS(){const t=pa();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(Z,{children:e.jsxs(X,{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(R,{onClick:()=>t(-1),className:"mt-4","data-testid":"back-button",children:[e.jsx(Ms,{className:"w-4 h-4 mr-2"}),"Back"]})]})})})})}function zS({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(Ct,{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(R,{variant:"outline",size:"sm",onClick:a,disabled:s,className:"gap-2","data-testid":"refresh-button",children:[e.jsx(es,{className:`w-4 h-4 ${s?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:"Refresh"})]})]})}function HS({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(Z,{children:[e.jsx(ae,{className:"pb-3",children:e.jsx(ne,{className:"text-sm font-medium text-gray-600",children:"TAT Compliance"})}),e.jsxs(X,{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(kt,{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(_s,{value:s,className:"mt-2 h-2"})]})]}),e.jsxs(Z,{children:[e.jsx(ae,{className:"pb-3",children:e.jsx(ne,{className:"text-sm font-medium text-gray-600",children:"Total Approved"})}),e.jsxs(X,{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(Ce,{className:"w-5 h-5 text-blue-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Requests handled"})]})]}),e.jsxs(Z,{children:[e.jsx(ae,{className:"pb-3",children:e.jsx(ne,{className:"text-sm font-medium text-gray-600",children:"Avg Response Time"})}),e.jsxs(X,{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(go,{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(Z,{children:[e.jsx(ae,{className:"pb-3",children:e.jsx(ne,{className:"text-sm font-medium text-gray-600",children:"Pending Actions"})}),e.jsxs(X,{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(Ue,{className:"w-5 h-5 text-orange-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Awaiting approval"})]})]})]})}function WS({approverName:t,approverStats:s,dateRange:a="all",customStartDate:r,customEndDate:n}){return e.jsxs(Z,{"data-testid":"approver-actions-stats",children:[e.jsxs(ae,{children:[e.jsx(ne,{children:"Approver's Actions"}),e.jsxs(we,{children:["Statistics for all requests by ",t," ",a&&a!=="all"?R0(a,r,n,""):"(all time)"]})]}),e.jsxs(X,{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(Ct,{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(Ce,{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(ht,{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(Ue,{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(wn,{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(Re,{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(kt,{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(Qx,{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(Qd,{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 KS({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(Z,{"data-testid":"approver-performance-filters",children:[e.jsx(ae,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{children:"Filters"}),e.jsx(R,{variant:"ghost",size:"sm",onClick:j,className:"text-xs","data-testid":"clear-filters-button",children:"Clear All"})]})}),e.jsx(X,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-6 gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(bs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(je,{placeholder:"Search requests...",value:t,onChange:b=>m(b.target.value),className:"pl-10","data-testid":"search-input"})]}),e.jsxs(_e,{value:s,onValueChange:u,children:[e.jsx(Oe,{"data-testid":"status-filter",children:e.jsx(Le,{placeholder:"Status"})}),e.jsxs($e,{children:[e.jsx(H,{value:"all",children:"All Status"}),e.jsx(H,{value:"pending",children:"Pending"}),e.jsx(H,{value:"approved",children:"Approved"}),e.jsx(H,{value:"rejected",children:"Rejected"}),e.jsx(H,{value:"closed",children:"Closed"})]})]}),e.jsxs(_e,{value:a,onValueChange:h,children:[e.jsx(Oe,{"data-testid":"priority-filter",children:e.jsx(Le,{placeholder:"Priority"})}),e.jsxs($e,{children:[e.jsx(H,{value:"all",children:"All Priority"}),e.jsx(H,{value:"express",children:"Express"}),e.jsx(H,{value:"standard",children:"Standard"})]})]}),e.jsxs(_e,{value:r,onValueChange:p,children:[e.jsx(Oe,{"data-testid":"sla-compliance-filter",children:e.jsx(Le,{placeholder:"SLA Compliance"})}),e.jsxs($e,{children:[e.jsx(H,{value:"all",children:"All SLA"}),e.jsx(H,{value:"compliant",children:"Compliant"}),e.jsx(H,{value:"on-track",children:"On Track"}),e.jsx(H,{value:"approaching",children:"Approaching"}),e.jsx(H,{value:"critical",children:"Critical"}),e.jsx(H,{value:"breached",children:"Breached"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(et,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(_e,{value:n,onValueChange:g,children:[e.jsx(Oe,{className:"flex-1","data-testid":"date-range-filter",children:e.jsx(Le,{placeholder:"Date Range"})}),e.jsxs($e,{children:[e.jsx(H,{value:"all",children:"All Time"}),e.jsx(H,{value:"today",children:"Today"}),e.jsx(H,{value:"week",children:"This Week"}),e.jsx(H,{value:"month",children:"This Month"}),e.jsx(H,{value:"last7days",children:"Last 7 Days"}),e.jsx(H,{value:"last30days",children:"Last 30 Days"}),e.jsx(H,{value:"custom",children:"Custom Range"})]})]}),n==="custom"&&e.jsxs(ra,{open:l,onOpenChange:y,children:[e.jsx(na,{asChild:!0,children:e.jsxs(R,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(et,{className:"w-4 h-4"}),c&&d?`${Ne(c,"MMM d")} - ${Ne(d,"MMM d")}`:"Select dates"]})}),e.jsx(ia,{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(Y,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(je,{id:"start-date",type:"date",value:c?Ne(c,"yyyy-MM-dd"):"",onChange:b=>{const N=b.target.value?new Date(b.target.value):void 0;N?(v(N),d&&N>d&&C(N)):v(void 0)},max:Ne(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Y,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(je,{id:"end-date",type:"date",value:d?Ne(d,"yyyy-MM-dd"):"",onChange:b=>{const N=b.target.value?new Date(b.target.value):void 0;N?(C(N),c&&N<c&&v(N)):C(void 0)},min:c?Ne(c,"yyyy-MM-dd"):void 0,max:Ne(new Date,"yyyy-MM-dd"),className:"w-full"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(R,{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(R,{size:"sm",variant:"outline",onClick:()=>{y(!1),v(i),C(o),(!i||!o)&&g("all")},"data-testid":"cancel-date-button",children:"Cancel"})]})]})})]})]})]})})]})}const GS=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ys,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:kt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:kt,iconColor:"text-gray-600"}}},YS=t=>{switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:Ce,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:ht,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:Ue,iconColor:"text-yellow-600"};case"in-progress":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Ue,iconColor:"text-blue-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ce,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Re,iconColor:"text-gray-600"}}},ZS=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 XS(t){if(!t)return"N/A";try{return Ne(new Date(t),"MMM d, yyyy")}catch{return"N/A"}}function JS(t){if(!t)return"N/A";try{return Ne(new Date(t),"MMM d, yyyy HH:mm")}catch{return"N/A"}}function QS({requests:t,loading:s,approverName:a,currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:o,onPageChange:l}){const c=pa();return e.jsxs(Z,{"data-testid":"approver-performance-request-list",children:[e.jsxs(ae,{children:[e.jsx(ne,{children:"Request Details"}),e.jsxs(we,{children:["All requests handled by ",a," with applied filters"]})]}),e.jsxs(X,{children:[s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"loading-state",children:[e.jsx(es,{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(Re,{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=GS(d.priority),u=YS(d.status),h=ZS(d.slaStatus||""),p=m.icon,g=u.icon;return e.jsx(Z,{className:"hover:shadow-md transition-shadow cursor-pointer",onClick:()=>c(`/request/${d.requestId}`),"data-testid":`request-card-${d.requestId}`,children:e.jsx(X,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-sm text-blue-600 hover:underline","data-testid":"request-number",children:d.requestNumber}),e.jsxs(ee,{className:m.color,"data-testid":"priority-badge",children:[e.jsx(p,{className:`w-3 h-3 mr-1 ${m.iconColor}`}),d.priority]}),e.jsxs(ee,{className:u.color,"data-testid":"status-badge",children:[e.jsx(g,{className:`w-3 h-3 mr-1 ${u.iconColor}`}),d.status]}),d.approvalStatus&&e.jsx(ee,{className:d.approvalStatus==="approved"||d.approvalStatus==="APPROVED"?"bg-green-100 text-green-800 border-green-200":d.approvalStatus==="rejected"||d.approvalStatus==="REJECTED"?"bg-red-100 text-red-800 border-red-200":"bg-yellow-100 text-yellow-800 border-yellow-200","data-testid":"approval-status-badge",children:d.approvalStatus==="approved"||d.approvalStatus==="APPROVED"?e.jsxs(e.Fragment,{children:[e.jsx(Ce,{className:"w-3 h-3 mr-1"}),"Approved"]}):d.approvalStatus==="rejected"||d.approvalStatus==="REJECTED"?e.jsxs(e.Fragment,{children:[e.jsx(ht,{className:"w-3 h-3 mr-1"}),"Rejected"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ue,{className:"w-3 h-3 mr-1"}),"Pending"]})}),d.slaStatus&&e.jsx(ee,{className:h.color,"data-testid":"sla-status-badge",children:h.label})]}),e.jsx("h3",{className:"font-medium text-gray-900 mb-1 truncate","data-testid":"request-title",children:d.title}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-xs text-gray-500 mt-2",children:[e.jsxs("span",{className:"flex items-center gap-1","data-testid":"initiator-info",children:[e.jsx(St,{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(Ue,{className:"w-3 h-3"}),"Submitted: ",XS(d.submissionDate)]}),d.approvalActionDate&&e.jsxs("span",{className:"flex items-center gap-1","data-testid":"action-date",children:[e.jsx(Ce,{className:"w-3 h-3"}),"Action: ",JS(d.approvalActionDate)]}),e.jsxs("span",{className:"flex items-center gap-1","data-testid":"approval-level",children:[e.jsx(kt,{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(go,{className:"w-3 h-3"}),At(d.levelElapsedHours)," / ",At(d.levelTatHours||0)," TAT"]})]})]}),e.jsx(R,{variant:"ghost",size:"sm",onClick:y=>{y.stopPropagation(),c(`/request/${d.requestId}`)},"data-testid":"view-request-button",children:e.jsx(Vt,{className:"w-4 h-4"})})]})})},d.requestId)})}),n>0&&e.jsx("div",{className:"mt-6","data-testid":"pagination-container",children:e.jsx(Fa,{currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:o,onPageChange:l,itemLabel:"requests",testIdPrefix:"approver-performance"})})]})]})}function qS(){const[t]=tm(),[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),N=x.useCallback(()=>{a(""),n("all"),o("all"),c("all"),m("all"),h(void 0),g(void 0),f(void 0),b(void 0),v(!1)},[]),A=x.useCallback(T=>{const P=T;m(P),P!=="custom"?(h(void 0),g(void 0),f(void 0),b(void 0),v(!1)):(f(u),b(p),v(!0))},[u,p]),D=x.useCallback(()=>{if(C&&j){if(C>j){const T=C;h(j),g(T),f(j),b(T)}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:N,handleDateRangeChange:A,handleApplyCustomDate:D}}function eA({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),[N,A]=x.useState(1),[D,T]=x.useState(0),P=x.useRef(!0),w=x.useCallback(async()=>{if(t)try{const _=s==="all"?void 0:s,$=await mt.getSingleApproverStats(t,_,a,r,i!=="all"?i:void 0,o!=="all"?o:void 0);h($)}catch(_){console.error("[ApproverPerformance] Failed to fetch approver stats:",_),h(null)}},[t,s,a,r,i,o]),S=x.useCallback(async(_=1)=>{if(!t){v(!1);return}try{v(!0);const $=await mt.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($.requests),T($.pagination.totalRecords),A($.pagination.totalPages),b($.pagination.currentPage),g($.requests)}catch($){console.error("Failed to fetch requests:",$)}finally{v(!1),f(!1)}},[t,s,a,r,n,i,o,l,c]);x.useEffect(()=>{P.current&&(P.current=!1,w(),S(1))},[]),x.useEffect(()=>{P.current||w()},[s,a,r,i,o]),x.useEffect(()=>{P.current||S(1)},[s,a,r,n,i,o,l]);const M=x.useCallback(()=>{f(!0),w(),S(1)},[w,S]),B=x.useCallback(_=>{S(_)},[S]);return{requests:d,approverStats:u,allFilteredRequests:p,loading:y,refreshing:C,currentPage:j,totalPages:N,totalRecords:D,handleRefresh:M,handlePageChange:B}}const yd=10;function tA(){const[t]=tm(),s=t.get("approverId")||"",a=t.get("approverName")||"Unknown Approver",r=qS(),n=eA({approverId:s,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,slaComplianceFilter:r.slaComplianceFilter,searchTerm:r.searchTerm,itemsPerPage:yd});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(zS,{approverName:a,refreshing:n.refreshing,onRefresh:n.handleRefresh}),n.approverStats&&e.jsx(HS,{approverStats:n.approverStats}),n.approverStats&&e.jsx(WS,{approverName:a,approverStats:n.approverStats,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate}),e.jsx(KS,{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(QS,{requests:n.requests,loading:n.loading,approverName:a,currentPage:n.currentPage,totalPages:n.totalPages,totalRecords:n.totalRecords,itemsPerPage:yd,onPageChange:n.handlePageChange})]}):e.jsx(VS,{})}function sA(){const{user:t}=ts(),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(Z,{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(X,{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($t,{className:"h-24 w-24 ring-4 ring-white/20 shadow-xl",children:[e.jsx(Sn,{src:(t==null?void 0:t.picture)||""}),e.jsx(Ut,{className:"bg-yellow-400 text-slate-900 text-2xl font-bold",children:s()})]}),Na(t)&&e.jsx("div",{className:"absolute -bottom-2 -right-2 bg-yellow-400 rounded-full p-1.5 shadow-lg",children:e.jsx(ss,{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:[Na(t)&&e.jsxs(ee,{className:"bg-yellow-400 text-slate-900 hover:bg-yellow-400 font-semibold",children:[e.jsx(ss,{className:"w-3 h-3 mr-1"}),"Administrator"]}),nr(t)&&e.jsxs(ee,{className:"bg-blue-400 text-slate-900 hover:bg-blue-400 font-semibold",children:[e.jsx(Ct,{className:"w-3 h-3 mr-1"}),"Management"]}),(t==null?void 0:t.employeeId)&&e.jsxs(ee,{variant:"outline",className:"border-white/30 text-white bg-white/10",children:["ID: ",t.employeeId]})]})]})})})]})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(Z,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(ae,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-blue-100 rounded-lg",children:e.jsx(St,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-lg text-gray-900",children:"Personal Information"}),e.jsx(we,{className:"text-gray-600",children:"Your personal details"})]})]})}),e.jsx(X,{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(Xa,{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(St,{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(St,{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(St,{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(bn,{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(Z,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(ae,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-emerald-100 rounded-lg",children:e.jsx(wl,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-lg text-gray-900",children:"Professional Information"}),e.jsx(we,{className:"text-gray-600",children:"Work-related details"})]})]})}),e.jsx(X,{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(St,{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(Vd,{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(wl,{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(ss,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"Role"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(ee,{variant:Na(t)||nr(t)?"default":"secondary",className:Na(t)?"bg-yellow-400 text-slate-900":nr(t)?"bg-blue-400 text-slate-900":"",children:Na(t)?"Administrator":nr(t)?"Management":"User"}),(Na(t)||nr(t))&&e.jsx(Ce,{className:"w-4 h-4 text-green-600"})]})]})]})]})})]})]}),e.jsxs(Z,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(ae,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-purple-100 rounded-lg",children:e.jsx(et,{className:"h-5 w-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-lg text-gray-900",children:"Account Status"}),e.jsx(we,{className:"text-gray-600",children:"Account information and activity"})]})]})}),e.jsx(X,{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(Ce,{className:"w-4 h-4 text-white"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:"Account Status"}),e.jsx("p",{className:"text-xs text-gray-600",children:"Active and verified"})]})]}),e.jsx(ee,{className:"bg-green-500 hover:bg-green-600 text-white",children:"Active"})]}),(t==null?void 0:t.userId)&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"p-4 bg-gray-50 rounded-lg",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500 mb-1",children:"User ID"}),e.jsx("p",{className:"text-sm text-gray-900 font-mono break-all",children:t.userId})]}),t.employeeId&&e.jsxs("div",{className:"p-4 bg-gray-50 rounded-lg",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500 mb-1",children:"Employee ID"}),e.jsx("p",{className:"text-sm text-gray-900 font-mono",children:t.employeeId})]})]})]})})]})]})}const Zr="BBb78N3tSTEw6mPbBmvEDX2bhYEDKPc_zffL-vxPV8FBSmR1qSpy9gdV8zt-WFF-q2NPpVmL4BhbUzLSHVAPjcI",aA="https://re-workflow-nt-dev.siplsolutions.com";function Ni(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 rA(){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 nA(t){if(Zr.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:Ni(Zr)})}else try{s=await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Ni(Zr)})}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:Ni(Zr)})}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(`${aA}/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 iA(){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 rA()}catch(a){throw new Error(`Service worker registration failed: ${(a==null?void 0:a.message)||"Unknown error"}`)}try{await nA(s)}catch(a){throw a}}function ao({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(Qp,{"data-slot":"slider",defaultValue:s,value:a,min:r,max:n,className:fe("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(qp,{"data-slot":"slider-track",className:fe("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(ex,{"data-slot":"slider-range",className:fe("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full")})}),Array.from({length:o.length},(l,c)=>e.jsx(tx,{"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 oA({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 w,S;try{n(!0),c(null);const M=await Tn();a(M)}catch(M){c(((S=(w=M.response)==null?void 0:w.data)==null?void 0:S.error)||"Failed to load configurations")}finally{n(!1)}},g=async w=>{var S,M;try{o(w.configKey),c(null);const B=d[w.configKey]??w.configValue;if(w.validationRules){const _=parseFloat(B);if(w.valueType==="NUMBER"){if(w.validationRules.min!==void 0&&_<w.validationRules.min)throw new Error(`Value must be at least ${w.validationRules.min}`);if(w.validationRules.max!==void 0&&_>w.validationRules.max)throw new Error(`Value must be at most ${w.validationRules.max}`)}}await Bt(w.configKey,B),a(_=>_.map($=>$.configKey===w.configKey?{...$,configValue:B}:$)),m(_=>{const $={..._};return delete $[w.configKey],$}),h(`${w.displayName} updated successfully`),setTimeout(()=>h(null),3e3),t&&t()}catch(B){c(B.message||((M=(S=B.response)==null?void 0:S.data)==null?void 0:M.error)||"Failed to save configuration")}finally{o(null)}},y=async w=>{var S,M;if(confirm(`Reset "${w.displayName}" to default value?`))try{o(w.configKey),c(null),await _y(w.configKey),a(B=>B.map(_=>_.configKey===w.configKey?{..._,configValue:_.defaultValue||""}:_)),m(B=>{const _={...B};return delete _[w.configKey],_}),h(`${w.displayName} reset to default`),setTimeout(()=>h(null),3e3)}catch(B){c(((M=(S=B.response)==null?void 0:S.data)==null?void 0:M.error)||"Failed to reset configuration")}finally{o(null)}},v=(w,S)=>{m(M=>({...M,[w]:S}))},C=w=>d[w.configKey]??w.configValue,f=w=>d[w.configKey]!==void 0&&d[w.configKey]!==w.configValue,j=w=>{var B,_,$,k;const S=C(w),M=i===w.configKey;if(!w.isEditable)return e.jsxs("div",{className:"p-3 bg-slate-100 border border-slate-200 rounded-md",children:[e.jsx("p",{className:"text-sm text-slate-700 font-mono",children:w.configValue}),e.jsxs("p",{className:"text-xs text-slate-500 mt-1.5 flex items-center gap-1",children:[e.jsx(Pe,{className:"w-3 h-3"}),"This setting cannot be modified"]})]});switch(w.uiComponent||w.valueType.toLowerCase()){case"toggle":return e.jsxs("div",{className:"flex items-center justify-between p-3 bg-slate-50 border border-slate-200 rounded-md hover:bg-slate-100 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`w-2 h-2 rounded-full ${S==="true"?"bg-green-500":"bg-slate-400"}`}),e.jsx("span",{className:`text-sm font-medium ${S==="true"?"text-green-700":"text-slate-600"}`,children:S==="true"?"Enabled":"Disabled"})]}),e.jsx(ns,{checked:S==="true",onCheckedChange:O=>v(w.configKey,O?"true":"false"),disabled:M})]});case"slider":const I=parseInt(S)||0,E=((B=w.validationRules)==null?void 0:B.min)||0,F=((_=w.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:[I,"%"]}),e.jsxs("span",{className:"text-xs text-slate-500 bg-slate-100 px-2 py-1 rounded-sm border border-slate-200",children:["Range: ",E,"-",F]})]}),e.jsx(ao,{value:[I],min:E,max:F,step:1,onValueChange:([O])=>{O!==void 0&&v(w.configKey,O.toString())},disabled:M,className:"w-full"})]});case"number":return e.jsx(je,{type:"number",value:S,onChange:O=>v(w.configKey,O.target.value),disabled:M,min:($=w.validationRules)==null?void 0:$.min,max:(k=w.validationRules)==null?void 0:k.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(je,{type:"text",value:S,onChange:O=>v(w.configKey,O.target.value),disabled:M,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=w=>{switch(w){case"TAT_SETTINGS":return e.jsx(Ue,{className:"w-5 h-5"});case"DOCUMENT_POLICY":return e.jsx(Re,{className:"w-5 h-5"});case"NOTIFICATION_RULES":return e.jsx(as,{className:"w-5 h-5"});case"AI_CONFIGURATION":return e.jsx(jn,{className:"w-5 h-5"});case"WORKFLOW_SHARING":return e.jsx(Ya,{className:"w-5 h-5"});default:return e.jsx(la,{className:"w-5 h-5"})}},N=["DASHBOARD_LAYOUT"],A=["ALLOW_EXTERNAL_SHARING","NOTIFICATION_BATCH_DELAY_MS","AI_REMARK_MAX_CHARACTERS"],D=s.filter(w=>!N.includes(w.configCategory)&&!A.includes(w.configKey)),T=D.reduce((w,S)=>(w[S.configCategory]||(w[S.configCategory]=[]),w[S.configCategory].push(S),w),{});if(Object.keys(T).forEach(w=>{const S=T[w];S&&S.sort((M,B)=>M.sortOrder-B.sortOrder)}),r)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Xe,{className:"w-8 h-8 animate-spin text-gray-400"})});if(D.length===0)return e.jsx(Z,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(X,{className:"p-12 text-center",children:[e.jsx("div",{className:"p-4 bg-slate-100 rounded-full w-20 h-20 flex items-center justify-center mx-auto mb-4",children:e.jsx(la,{className:"w-10 h-10 text-slate-400"})}),e.jsx("p",{className:"text-slate-700 font-medium text-lg",children:"No configurations found"}),e.jsx("p",{className:"text-sm text-slate-500 mt-2 max-w-md mx-auto",children:"System configurations will appear here once they are initialized"})]})});const P=Object.keys(T);return e.jsxs("div",{className:"space-y-6",children:[u&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-green-50 to-emerald-50 border border-green-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-green-500 rounded-md",children:e.jsx(Ce,{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(R,{size:"sm",variant:"ghost",onClick:()=>c(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsxs(An,{defaultValue:P[0],className:"w-full",children:[e.jsx(kn,{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:P.map(w=>e.jsx(Et,{value:w,className:"flex-1 min-w-[120px] text-[10px] xs:text-xs sm:text-sm font-medium py-2 sm:py-2.5 px-2 sm:px-3 rounded-sm data-[state=active]:bg-white data-[state=active]:shadow-sm data-[state=active]:text-slate-900 transition-all",children:e.jsx("span",{className:"truncate block",children:w.replace(/_/g," ")})},w))}),P.map(w=>{var S,M,B;return e.jsx(It,{value:w,className:"space-y-4 mt-6",children:e.jsxs(Z,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ae,{className:"pb-4 border-b border-slate-100",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx("div",{className:"text-white",children:b(w)})}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-lg font-semibold text-slate-900",children:w.replace(/_/g," ")}),e.jsxs(we,{className:"text-sm",children:[((S=T[w])==null?void 0:S.length)||0," setting",(((M=T[w])==null?void 0:M.length)||0)!==1?"s":""," available"]})]})]})}),e.jsx(X,{className:"space-y-6",children:(B=T[w])==null?void 0:B.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(Y,{className:"text-sm font-semibold text-slate-900",children:_.displayName}),f(_)&&e.jsx(ee,{variant:"outline",className:"text-xs bg-gradient-to-r from-yellow-50 to-amber-50 text-yellow-800 border-yellow-400 font-medium shadow-sm",children:"Modified"}),_.requiresRestart&&e.jsx(ee,{variant:"outline",className:"text-xs bg-gradient-to-r from-orange-50 to-red-50 text-orange-800 border-orange-400 font-medium shadow-sm",children:"Requires Restart"})]}),_.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(R,{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(Xe,{className:"w-4 h-4 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ha,{className:"w-4 h-4"}),"Save Changes"]})}),_.defaultValue&&e.jsxs(R,{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(qx,{className:"w-4 h-4"}),"Reset to Default"]})]})]},_.configKey))})]})},w)})]})]})}function lA(){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 w,S;try{r(!0),u(null);const M=await Ly(n);s(M)}catch(M){u(((S=(w=M.response)==null?void 0:w.data)==null?void 0:S.error)||"Failed to load holidays")}finally{r(!1)}},C=()=>{y({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1}),d(null),l(!0)},f=w=>{y({holidayDate:w.holidayDate,holidayName:w.holidayName,description:w.description||"",holidayType:w.holidayType,isRecurring:w.isRecurring}),d(w),l(!0)},j=()=>{if(c)return;const w=new Date;return w.setDate(w.getDate()+1),w.toISOString().split("T")[0]},b=async()=>{var w,S;try{if(u(null),!g.holidayDate||!g.holidayName){u("Holiday date and name are required");return}c?(await $y(c.holidayId,g),p("Holiday updated successfully")):(await Oy(g),p("Holiday created successfully")),await v(),l(!1),setTimeout(()=>p(null),3e3)}catch(M){u(((S=(w=M.response)==null?void 0:w.data)==null?void 0:S.error)||"Failed to save holiday")}},N=async w=>{var S,M;if(confirm(`Delete "${w.holidayName}"?`))try{u(null),await Uy(w.holidayId),p("Holiday deleted successfully"),await v(),setTimeout(()=>p(null),3e3)}catch(B){u(((M=(S=B.response)==null?void 0:S.data)==null?void 0:M.error)||"Failed to delete holiday")}},A=w=>{switch(w){case"NATIONAL":return"bg-gradient-to-r from-red-50 to-rose-50 text-red-800 border-red-300";case"REGIONAL":return"bg-gradient-to-r from-blue-50 to-cyan-50 text-blue-800 border-blue-300";case"ORGANIZATIONAL":return"bg-gradient-to-r from-purple-50 to-violet-50 text-purple-800 border-purple-300";case"OPTIONAL":return"bg-gradient-to-r from-slate-50 to-gray-50 text-slate-700 border-slate-300"}},D=Array.from({length:5},(w,S)=>new Date().getFullYear()-1+S),T=t.reduce((w,S)=>{const M=new Date(S.holidayDate).toLocaleString("default",{month:"long"});return w[M]||(w[M]=[]),w[M].push(S),w},{}),P=Object.keys(T).sort((w,S)=>{const M=new Date(Date.parse(w+" 1, 2000")).getMonth(),B=new Date(Date.parse(S+" 1, 2000")).getMonth();return M-B});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(Ce,{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(R,{size:"sm",variant:"ghost",onClick:()=>u(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsx(Z,{className:"shadow-lg border-0 rounded-md",children:e.jsx(ae,{className:"border-b border-slate-100 py-4 sm:py-5",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(et,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Holiday Calendar"}),e.jsx(we,{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(_e,{value:n.toString(),onValueChange:w=>i(parseInt(w)),children:[e.jsx(Oe,{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(Le,{})}),e.jsx($e,{className:"rounded-md",children:D.map(w=>e.jsx(H,{value:w.toString(),children:w},w))})]}),e.jsxs(R,{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(Is,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Add Holiday"}),e.jsx("span",{className:"xs:hidden",children:"Add"})]})]})]})})}),a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Xe,{className:"w-8 h-8 animate-spin text-gray-400"})}):t.length===0?e.jsx(Z,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(X,{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(et,{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(R,{onClick:C,variant:"outline",className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(Is,{className:"w-4 h-4"}),"Add First Holiday"]})]})}):e.jsx("div",{className:"space-y-4 sm:space-y-6",children:P.map(w=>{var S,M,B;return e.jsxs(Z,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ae,{className:"pb-3 sm:pb-4 border-b border-slate-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(ne,{className:"text-base sm:text-lg font-semibold text-slate-900",children:[w," ",n]}),e.jsxs(we,{className:"text-xs sm:text-sm",children:[((S=T[w])==null?void 0:S.length)||0," holiday",(((M=T[w])==null?void 0:M.length)||0)!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-blue-50 rounded-md",children:e.jsx(et,{className:"w-4 h-4 text-blue-600"})})]})}),e.jsx(X,{className:"space-y-3 pt-4",children:(B=T[w])==null?void 0:B.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(ee,{variant:"outline",className:`${A(_.holidayType)} text-[10px] sm:text-xs font-medium shadow-sm`,children:_.holidayType}),_.isRecurring&&e.jsx(ee,{variant:"outline",className:"bg-gradient-to-r from-indigo-50 to-purple-50 text-indigo-700 border-indigo-300 text-[10px] sm:text-xs font-medium shadow-sm",children:"Recurring"})]}),e.jsx("p",{className:"text-xs sm:text-sm text-slate-600 font-medium",children:Am(_.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(R,{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(Kd,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]}),e.jsxs(R,{size:"sm",variant:"ghost",onClick:()=>N(_),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(fo,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Delete"})]})]})]},_.holidayId))})]},w)})}),e.jsx(nt,{open:o,onOpenChange:l,children:e.jsxs(at,{className:"sm:max-w-[550px] max-h-[90vh] rounded-lg flex flex-col p-0",children:[e.jsx(it,{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(et,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(rt,{className:"text-xl font-semibold text-slate-900",children:c?"Edit Holiday":"Add New Holiday"}),e.jsx(Ht,{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(Y,{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(je,{id:"date",type:"date",value:g.holidayDate,onChange:w=>y({...g,holidayDate:w.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(Y,{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(je,{id:"name",placeholder:"e.g., Diwali, Republic Day, Christmas",value:g.holidayName,onChange:w=>y({...g,holidayName:w.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Enter the official name of the holiday"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Y,{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(je,{id:"description",placeholder:"Add additional details about this holiday...",value:g.description,onChange:w=>y({...g,description:w.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Optional description or notes about the holiday"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Y,{htmlFor:"type",className:"text-sm font-semibold text-slate-900",children:"Holiday Type"}),e.jsxs(_e,{value:g.holidayType,onValueChange:w=>y({...g,holidayType:w}),children:[e.jsx(Oe,{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(Le,{})}),e.jsxs($e,{className:"rounded-lg",children:[e.jsx(H,{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(H,{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(H,{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(H,{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:w=>y({...g,isRecurring:w.target.checked}),className:"mt-0.5 rounded border-slate-300 text-re-green focus:ring-2 focus:ring-re-green/20 focus:ring-offset-0 w-4 h-4 cursor-pointer"}),e.jsxs("div",{className:"flex-1",children:[e.jsx(Y,{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(yt,{className:"gap-3 pt-4 border-t border-slate-100 px-6 pb-6 flex-shrink-0",children:[e.jsx(R,{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(R,{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(et,{className:"w-4 h-4 mr-2"}),c?"Update Holiday":"Add Holiday"]})]})]})})]})}function cA(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function dA(){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,N]=x.useState("ELEVATED"),[A,D]=x.useState(1),[T,P]=x.useState(1),[w,S]=x.useState(0),M=10,B=x.useRef(null),_=x.useRef(null),$=x.useCallback(cA(async G=>{var me,re,V;if(!G||!G.startsWith("@")||G.length<2){r([]),i(!1);return}i(!0);try{const q=G.slice(1),ue=((me=(await fs.searchUsers(q,20)).data)==null?void 0:me.data)||[];r(ue)}catch(q){console.error("Search failed:",q),p({type:"error",text:((V=(re=q.response)==null?void 0:re.data)==null?void 0:V.message)||"Failed to search users"})}finally{i(!1)}},300),[]),k=G=>{const me=G.target.value;s(me),$(me)},I=async G=>{l(G),s(G.email),r([]);const me=g.find(re=>re.email.toLowerCase()===G.email.toLowerCase()||re.userId===G.userId);if(me&&me.role)d(me.role);else try{const V=(await fs.getAllUsers()).find(q=>q.email&&q.email.toLowerCase()===G.email.toLowerCase()||q.userId&&q.userId===G.userId);V&&V.role?d(V.role):d("USER")}catch(re){console.error("Failed to check user role:",re),d("USER")}},E=async()=>{var G,me;if(!o||!c){p({type:"error",text:"Please select a user and role"});return}u(!0),p(null);try{await fs.assignRole(o.email,c),p({type:"success",text:`Successfully assigned ${c} role to ${o.displayName||o.email}`}),l(null),s(""),d("USER"),await F(),await O()}catch(re){console.error("Role assignment failed:",re),p({type:"error",text:((me=(G=re.response)==null?void 0:G.data)==null?void 0:me.error)||"Failed to assign role"})}finally{u(!1)}},F=async(G=A)=>{var me,re,V,q,ie,ue;C(!0);try{const Te=await fs.getUsersByRole(b,G,M),qe=((re=(me=Te.data)==null?void 0:me.data)==null?void 0:re.users)||[],ze=(q=(V=Te.data)==null?void 0:V.data)==null?void 0:q.pagination,Ze=(ue=(ie=Te.data)==null?void 0:ie.data)==null?void 0:ue.summary;y(qe),ze&&(D(ze.currentPage),P(ze.totalPages),S(ze.totalUsers)),Ze&&j({admins:Ze.ADMIN||0,management:Ze.MANAGEMENT||0,users:Ze.USER||0})}catch(Te){console.error("Failed to fetch users:",Te)}finally{C(!1)}},O=async()=>{var G,me,re,V,q,ie;try{const ue=await fs.getRoleStatistics(),Te=((me=(G=ue.data)==null?void 0:G.data)==null?void 0:me.statistics)||((re=ue.data)==null?void 0:re.statistics)||[];j({admins:parseInt(((V=Te.find(qe=>qe.role==="ADMIN"))==null?void 0:V.count)||"0"),management:parseInt(((q=Te.find(qe=>qe.role==="MANAGEMENT"))==null?void 0:q.count)||"0"),users:parseInt(((ie=Te.find(qe=>qe.role==="USER"))==null?void 0:ie.count)||"0")})}catch(ue){console.error("Failed to fetch statistics:",ue)}};x.useEffect(()=>{F(1),O()},[b]);const L=G=>{N(G),D(1)},J=G=>{F(G)},U=G=>{N(G),D(1),requestAnimationFrame(()=>{const me=_.current;me&&me.scrollIntoView({behavior:"smooth",block:"start"})})};x.useEffect(()=>{const G=me=>{B.current&&!B.current.contains(me.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",G),()=>{document.removeEventListener("mousedown",G)}},[a]);const oe=G=>{switch(G){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=G=>{switch(G){case"ADMIN":return e.jsx(La,{className:"w-5 h-5 text-slate-800"});case"MANAGEMENT":return e.jsx(Ct,{className:"w-5 h-5 text-slate-800"});default:return e.jsx(St,{className:"w-5 h-5 text-slate-800"})}};return e.jsxs(Z,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ae,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(eg,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-lg font-semibold text-gray-900",children:"User Role Management"}),e.jsx(we,{className:"text-sm text-gray-600",children:"Search for users, assign roles, and manage user permissions across the system"})]})]})}),e.jsxs(X,{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(Z,{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:()=>U("ADMIN"),children:e.jsx(X,{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(La,{className:"w-6 h-6 text-slate-800"})})]})})}),e.jsx(Z,{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:()=>U("MANAGEMENT"),children:e.jsx(X,{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(Ct,{className:"w-6 h-6 text-slate-800"})})]})})}),e.jsx(Z,{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:()=>U("USER"),children:e.jsx(X,{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(St,{className:"w-6 h-6 text-slate-800"})})]})})})]}),e.jsx(Tt,{}),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:B,children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Search User"}),e.jsxs("div",{className:"relative",children:[e.jsx(bs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none"}),e.jsx(je,{type:"text",placeholder:"Type @ to search users...",value:t,onChange:k,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(Xe,{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(G=>e.jsxs("button",{onClick:()=>I(G),className:"w-full text-left p-2 hover:bg-purple-50 rounded-lg transition-colors mb-1 last:mb-0","data-testid":`user-result-${G.email}`,children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:G.displayName||G.email}),e.jsx("p",{className:"text-xs text-gray-600",children:G.email}),G.department&&e.jsxs("p",{className:"text-xs text-gray-500",children:[G.department,G.designation?` • ${G.designation}`:""]})]},G.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(R,{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(_e,{value:c,onValueChange:G=>d(G),children:[e.jsx(Oe,{className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20","data-testid":"role-select",children:e.jsx(Le,{placeholder:"Select role"})}),e.jsxs($e,{children:[e.jsx(H,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(St,{className:"w-4 h-4 text-gray-600"}),e.jsx("span",{children:"User - Regular access"})]})}),e.jsx(H,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ct,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Management - Read all data"})]})}),e.jsx(H,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(La,{className:"w-4 h-4 text-yellow-600"}),e.jsx("span",{children:"Administrator - Full access"})]})})]})]})]}),e.jsx(R,{onClick:E,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(Xe,{className:"w-4 h-4 mr-2 animate-spin"}),"Assigning Role..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ss,{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(Ce,{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(Tt,{}),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 (",w," ",b!=="ALL"&&b!=="ELEVATED"?b.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(_e,{value:b,onValueChange:L,children:[e.jsx(Oe,{className:"w-[200px] h-10 border rounded-lg border-gray-300",children:e.jsx(Le,{placeholder:"Filter by role"})}),e.jsxs($e,{children:[e.jsx(H,{value:"ELEVATED",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ss,{className:"w-4 h-4 text-purple-600"}),e.jsxs("span",{children:["Elevated (",f.admins+f.management,")"]})]})}),e.jsx(H,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(La,{className:"w-4 h-4 text-yellow-600"}),e.jsxs("span",{children:["Admins (",f.admins,")"]})]})}),e.jsx(H,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ct,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Management (",f.management,")"]})]})}),e.jsx(H,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(St,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["Users (",f.users,")"]})]})}),e.jsx(H,{value:"ALL",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ct,{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(Xe,{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(Ct,{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(G=>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-${G.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(G.role)} flex items-center justify-center shadow-sm`,children:ge(G.role)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-semibold text-gray-900 truncate",children:G.displayName}),e.jsx("p",{className:"text-sm text-gray-600 truncate",children:G.email}),G.department&&e.jsxs("p",{className:"text-xs text-gray-500 mt-1 truncate",children:[G.department,G.designation?` • ${G.designation}`:""]})]})]}),e.jsx(ee,{className:`${oe(G.role)} shrink-0`,"data-testid":`role-badge-${G.role}`,children:G.role})]})},G.userId))}),T>1&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("div",{className:"text-sm text-gray-600",children:["Showing ",(A-1)*M+1," to ",Math.min(A*M,w)," of ",w," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(R,{variant:"outline",size:"sm",onClick:()=>J(A-1),disabled:A===1,"data-testid":"prev-page-button",children:"Previous"}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,T)},(G,me)=>{let re;return T<=5||A<=3?re=me+1:A>=T-2?re=T-4+me:re=A-2+me,e.jsx(R,{variant:A===re?"default":"outline",size:"sm",onClick:()=>J(re),className:`w-9 h-9 p-0 ${A===re?"bg-re-green hover:bg-re-green/90 text-white":""}`,"data-testid":`page-${re}-button`,children:re},re)})}),e.jsx(R,{variant:"outline",size:"sm",onClick:()=>J(A+1),disabled:A===T,"data-testid":"next-page-button",children:"Next"})]})]})]})})]})]})]})}function mA({open:t,onClose:s,success:a,message:r}){return e.jsx(nt,{open:t,onOpenChange:s,children:e.jsxs(at,{className:"sm:max-w-md",children:[e.jsxs(it,{children:[e.jsxs(rt,{className:"flex items-center gap-2",children:[e.jsx(as,{className:"w-5 h-5 text-blue-600"}),"Push Notifications"]}),e.jsx(Ht,{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(Ce,{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(ht,{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(yt,{children:e.jsx(R,{onClick:s,className:"w-full",children:a?"Done":"Close"})})]})})}const uA=async()=>(await ce.get("/user/preferences/notifications")).data.data,hA=async t=>(await ce.put("/user/preferences/notifications",t)).data.data;function pA({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 uA();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 hA(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(nt,{open:t,onOpenChange:s,children:e.jsxs(at,{className:"sm:max-w-[600px] max-h-[85vh] overflow-y-auto",children:[e.jsx(it,{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(la,{className:"h-6 w-6 text-white"})}),e.jsxs("div",{children:[e.jsx(rt,{className:"text-xl font-semibold",children:"Notification Preferences"}),e.jsx(Ht,{className:"text-sm",children:"Customize how you receive notifications for workflow updates"})]})]})}),e.jsx(Tt,{className:"my-4"}),n?e.jsx("div",{className:"p-12 flex items-center justify-center",children:e.jsx(Xe,{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(Ce,{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(Xa,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(Y,{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(Xe,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(ns,{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(as,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(Y,{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(Xe,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(ns,{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(Ds,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(Y,{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(Xe,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(ns,{id:"inapp-notifications-modal",checked:a.inAppNotificationsEnabled,onCheckedChange:g=>p("inAppNotificationsEnabled",g),disabled:o==="inAppNotificationsEnabled"})]})]})}),e.jsx(Tt,{}),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 xA(){const{user:t}=ts(),s=Na(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 Bf();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 iA(),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(Z,{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(X,{className:"relative z-10 p-6 sm:p-8 lg:p-12",children:e.jsxs("div",{className:"flex items-center gap-4 sm:gap-6",children:[e.jsx("div",{className:"w-14 h-14 sm:w-16 sm:h-16 bg-gradient-to-br from-yellow-400 to-yellow-500 rounded-2xl flex items-center justify-center shadow-xl transform hover:scale-105 transition-transform",children:e.jsx(la,{className:"w-7 h-7 sm:w-8 sm:h-8 text-slate-900"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl sm:text-3xl lg:text-4xl font-bold text-white mb-1 sm:mb-2",children:"Settings"}),e.jsx("p",{className:"text-sm sm:text-base lg:text-lg text-gray-300",children:"Manage your account and preferences"})]})]})})]}),s?e.jsxs(An,{defaultValue:"user",className:"w-full",children:[e.jsxs(kn,{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(Et,{value:"user",className:"flex items-center justify-center gap-2 py-3 rounded-lg data-[state=active]:bg-white data-[state=active]:shadow-md transition-all",children:[e.jsx(la,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"User Settings"}),e.jsx("span",{className:"sm:hidden",children:"User"})]}),e.jsxs(Et,{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(ss,{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(Et,{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(qd,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Configuration"}),e.jsx("span",{className:"sm:hidden",children:"Config"})]}),e.jsxs(Et,{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(et,{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(It,{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(Z,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ae,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(as,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-lg font-semibold text-gray-900",children:"Browser Push Setup"}),e.jsx(we,{className:"text-sm text-gray-600",children:"Register this browser for push notifications"})]})]})}),e.jsx(X,{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(R,{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(as,{className:`w-4 h-4 mr-2 ${c?"animate-pulse":""}`}),c?"Registering...":h?"Already Registered":"Register Browser for Push"]})]})})]}),e.jsxs(Z,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ae,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(yr,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-lg font-semibold text-gray-900",children:"Security"}),e.jsx(we,{className:"text-sm text-gray-600",children:"Password and security settings"})]})]})}),e.jsx(X,{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(Z,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ae,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(Cl,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-lg font-semibold text-gray-900",children:"Appearance"}),e.jsx(we,{className:"text-sm text-gray-600",children:"Theme and display preferences"})]})]})}),e.jsx(X,{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(Z,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ae,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(ss,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-lg font-semibold text-gray-900",children:"Preferences"}),e.jsx(we,{className:"text-sm text-gray-600",children:"Notification and application preferences"})]})]})}),e.jsx(X,{children:e.jsxs(R,{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(ss,{className:"w-4 h-4 mr-2"}),"Manage Preferences"]})})]})]})}),e.jsx(It,{value:"roles",className:"mt-0",children:e.jsx(dA,{})}),e.jsx(It,{value:"system",className:"mt-0",children:e.jsx(oA,{})}),e.jsx(It,{value:"holidays",className:"mt-0",children:e.jsx(lA,{})})]})]}):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(Z,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ae,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(as,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-lg font-semibold text-gray-900",children:"Browser Push Setup"}),e.jsx(we,{className:"text-sm text-gray-600",children:"Register this browser for push notifications"})]})]})}),e.jsx(X,{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(R,{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(as,{className:`w-4 h-4 mr-2 ${c?"animate-pulse":""}`}),c?"Registering...":h?"Already Registered":"Register Browser for Push"]})]})})]}),e.jsxs(Z,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ae,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(yr,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-lg font-semibold text-gray-900",children:"Security"}),e.jsx(we,{className:"text-sm text-gray-600",children:"Password and security settings"})]})]})}),e.jsx(X,{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(Z,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ae,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(Cl,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-lg font-semibold text-gray-900",children:"Appearance"}),e.jsx(we,{className:"text-sm text-gray-600",children:"Theme and display preferences"})]})]})}),e.jsx(X,{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(Z,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ae,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(ss,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-lg font-semibold text-gray-900",children:"Preferences"}),e.jsx(we,{className:"text-sm text-gray-600",children:"Notification and application preferences"})]})]})}),e.jsx(X,{children:e.jsxs(R,{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(ss,{className:"w-4 h-4 mr-2"}),"Manage Preferences"]})})]})]})})]}),e.jsx(mA,{open:a,onClose:()=>r(!1),success:n,message:o}),e.jsx(pA,{open:m,onClose:()=>u(!1)})]})}function gA({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(P=i,w=u==="unread")=>{var S,M;try{n(P===1);const B=await aa.list({page:P,limit:y,unreadOnly:w}),_=((S=B.data)==null?void 0:S.notifications)||[],$=((M=B.data)==null?void 0:M.total)||0;a(_),m($),c(Math.ceil($/y))}catch(B){console.error("[Notifications] Failed to fetch:",B)}finally{n(!1),g(!1)}};x.useEffect(()=>{v(1,u==="unread")},[u]);const C=async P=>{var w;try{if(P.isRead||(await aa.markAsRead(P.notificationId),a(S=>S.map(M=>M.notificationId===P.notificationId?{...M,isRead:!0}:M))),P.actionUrl&&t){const S=(w=P.metadata)==null?void 0:w.requestNumber;if(S){let M=`request/${S}`;(P.notificationType==="mention"||P.notificationType==="comment"||P.notificationType==="worknote")&&(M+="?tab=worknotes"),t(M)}}}catch(S){console.error("[Notifications] Error handling notification click:",S)}},f=async()=>{try{g(!0),await aa.markAllAsRead(),await v(i,u==="unread")}catch(P){console.error("[Notifications] Error marking all as read:",P),g(!1)}},j=async P=>{try{await aa.delete(P),a(w=>w.filter(S=>S.notificationId!==P)),m(w=>w-1)}catch(w){console.error("[Notifications] Error deleting notification:",w)}},b=()=>{g(!0),v(i,u==="unread")},N=P=>{P<1||P>l||(o(P),v(P,u==="unread"))},A=P=>{const w="w-6 h-6";switch(P){case"mention":case"comment":return e.jsx(Ds,{className:`${w} text-blue-600`});case"worknote":return e.jsx(Re,{className:`${w} text-purple-600`});case"assignment":return e.jsx(yn,{className:`${w} text-indigo-600`});case"approval":return e.jsx(Ce,{className:`${w} text-green-600`});case"rejection":return e.jsx(ht,{className:`${w} text-red-600`});case"tat_alert":return e.jsx(Ue,{className:`${w} text-orange-600`});case"tat_breach":return e.jsx(Pe,{className:`${w} text-red-600`});case"tat_breach_initiator":return e.jsx(Cs,{className:`${w} text-amber-600`});default:return e.jsx(as,{className:`${w} text-gray-600`})}},D=P=>{switch(P==null?void 0:P.toUpperCase()){case"URGENT":return"bg-red-100 text-red-800 border-red-200";case"HIGH":return"bg-orange-100 text-orange-800 border-orange-200";case"MEDIUM":return"bg-blue-100 text-blue-800 border-blue-200";default:return"bg-gray-100 text-gray-800 border-gray-200"}},T=s.filter(P=>!P.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(as,{className:"w-8 h-8 text-blue-600"}),"Notifications"]}),e.jsxs("p",{className:"text-gray-600 mt-1",children:[d," total notification",d!==1?"s":"",T>0&&` • ${T} unread`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(R,{variant:"outline",size:"sm",onClick:b,disabled:p,className:"gap-2",children:[e.jsx(es,{className:`w-4 h-4 ${p?"animate-spin":""}`}),"Refresh"]}),T>0&&e.jsxs(R,{variant:"outline",size:"sm",onClick:f,disabled:p,className:"gap-2",children:[e.jsx(tg,{className:"w-4 h-4"}),"Mark All Read"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(R,{variant:u==="all"?"default":"outline",size:"sm",onClick:()=>{h("all"),o(1)},children:"All Notifications"}),e.jsxs(R,{variant:u==="unread"?"default":"outline",size:"sm",onClick:()=>{h("unread"),o(1)},children:["Unread",T>0&&e.jsx(ee,{className:"ml-2 bg-red-500 text-white",children:T})]})]}),e.jsxs(Z,{children:[e.jsxs(ae,{children:[e.jsx(ne,{children:"Recent Activity"}),e.jsx(we,{children:"Stay updated with all your workflow activities and mentions"})]}),e.jsx(X,{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(as,{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(P=>{var w;return e.jsx("div",{className:`p-4 rounded-lg border transition-all cursor-pointer hover:shadow-md ${P.isRead?"bg-white border-gray-200 hover:bg-gray-50":"bg-blue-50 border-blue-200 hover:bg-blue-100"}`,onClick:()=>C(P),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"shrink-0 mt-0.5",children:A(P.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 ${P.isRead?"font-semibold":"font-bold"} text-gray-900`,children:P.title}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[P.priority&&P.priority!=="LOW"&&e.jsx(ee,{variant:"outline",className:`text-xs ${D(P.priority)}`,children:P.priority}),!P.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:P.message}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:[_d(new Date(P.createdAt),{addSuffix:!0}),((w=P.metadata)==null?void 0:w.requestNumber)&&e.jsxs("span",{className:"ml-2",children:["• ",P.metadata.requestNumber]})]}),e.jsx(R,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-600",onClick:S=>{S.stopPropagation(),j(P.notificationId)},children:e.jsx(fo,{className:"w-3.5 h-3.5"})})]})]})]})},P.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(R,{variant:"outline",size:"sm",onClick:()=>N(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)},(P,w)=>{let S;return l<=5||i<=3?S=w+1:i>=l-2?S=l-4+w:S=i-2+w,e.jsx(R,{variant:i===S?"default":"outline",size:"sm",className:"w-9 h-9 p-0",onClick:()=>N(S),children:S},S)})}),e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>N(i+1),disabled:i===l,children:["Next",e.jsx(xo,{className:"w-4 h-4"})]})]})]})]})}function fA({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(R,{variant:"outline",onClick:t,className:"inline-flex items-center gap-2","data-testid":"back-button",children:[e.jsx(Ms,{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(Re,{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 ul({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?`${Ne(s,"MMM d, yyyy")} - ${Ne(a,"MMM d, yyyy")}`:"Select dates";return e.jsxs("div",{className:"flex items-center gap-2","data-testid":`${h}-container`,children:[e.jsx(et,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(_e,{value:t,onValueChange:o,"data-testid":`${h}-select`,children:[e.jsx(Oe,{className:"w-[160px]",children:e.jsx(Le,{placeholder:"Date Range"})}),e.jsxs($e,{children:[e.jsx(H,{value:"today",children:"Today"}),e.jsx(H,{value:"week",children:"This Week"}),e.jsx(H,{value:"month",children:"This Month"}),e.jsx(H,{value:"custom",children:"Custom Range"})]})]}),t==="custom"&&e.jsxs(ra,{open:r,onOpenChange:l,children:[e.jsx(na,{asChild:!0,children:e.jsxs(R,{variant:"outline",size:"sm",className:"gap-2","data-testid":`${h}-custom-trigger`,children:[e.jsx(et,{className:"w-4 h-4"}),p]})}),e.jsx(ia,{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(Y,{htmlFor:`${h}-start-date`,className:"text-sm font-medium",children:"Start Date"}),e.jsx(je,{id:`${h}-start-date`,type:"date",value:n?Ne(n,"yyyy-MM-dd"):"",onChange:g=>{const y=g.target.value?new Date(g.target.value):void 0;c(y)},max:Ne(new Date,"yyyy-MM-dd"),className:"w-full","data-testid":`${h}-start-input`})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Y,{htmlFor:`${h}-end-date`,className:"text-sm font-medium",children:"End Date"}),e.jsx(je,{id:`${h}-end-date`,type:"date",value:i?Ne(i,"yyyy-MM-dd"):"",onChange:g=>{const y=g.target.value?new Date(g.target.value):void 0;d(y)},min:n?Ne(n,"yyyy-MM-dd"):void 0,max:Ne(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(R,{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(R,{size:"sm",variant:"outline",onClick:u,"data-testid":`${h}-cancel-button`,children:"Cancel"})]})]})})]})]})}function yA(t){switch(t){case"Login":return"text-blue-700 bg-blue-100 border-blue-200";case"Created Request":return"text-purple-700 bg-purple-100 border-purple-200";case"Approved Request":return"text-emerald-700 bg-emerald-100 border-emerald-200";case"Rejected Request":return"text-red-700 bg-red-100 border-red-200";case"Added Comment":return"text-amber-700 bg-amber-100 border-amber-200";case"Viewed Request":return"text-gray-700 bg-gray-100 border-gray-200";case"Uploaded Document":return"text-indigo-700 bg-indigo-100 border-indigo-200";default:return"text-gray-700 bg-gray-100 border-gray-200"}}function Yh(t){switch(t){case"high":return"bg-red-100 text-red-800 border-red-200";case"medium":return"bg-orange-100 text-orange-800 border-orange-200";case"low":return"bg-green-100 text-green-800 border-green-200";default:return"bg-gray-100 text-gray-800 border-gray-200"}}function Zh(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 bA(t){return t>=20?"bg-red-600":t>=10?"bg-orange-500":"bg-amber-500"}function vA({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(Z,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"request-lifecycle-report",children:[e.jsxs(ae,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-blue-100 rounded-lg",children:e.jsx(qt,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-lg text-gray-900",children:"Request Lifecycle Report"}),e.jsx(we,{className:"text-gray-600",children:"End-to-end workflow status including all approval levels, approvers, dates, and TAT compliance"})]})]}),e.jsxs(R,{variant:"outline",size:"sm",className:"gap-2",onClick:j,disabled:u,"data-testid":"export-lifecycle-button",children:[e.jsx(Qt,{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(ul,{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(X,{children:[s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"lifecycle-loading",children:[e.jsx(Xe,{className:"w-6 h-6 animate-spin text-gray-400"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading lifecycle data..."})]}):r?e.jsxs("div",{className:"flex items-center justify-center py-12 text-red-600","data-testid":"lifecycle-error",children:[e.jsx(Pe,{className:"w-5 h-5 mr-2"}),e.jsx("span",{className:"text-sm",children:r})]}):t.length===0?e.jsx("div",{className:"text-center py-12 text-gray-500","data-testid":"lifecycle-empty",children:e.jsx("p",{className:"text-sm",children:"No lifecycle data available"})}):e.jsx("div",{className:"space-y-4",children:t.map(N=>e.jsx("div",{className:"border rounded-xl overflow-hidden","data-testid":`lifecycle-request-${N.id}`,children:e.jsx("div",{className:"p-4 bg-gradient-to-r from-gray-50 to-white hover:bg-gray-100 cursor-pointer transition-all",onClick:()=>b(N.requestId||N.id),children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"flex items-center gap-4",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("button",{onClick:A=>{A.stopPropagation(),b(N.requestId||N.id)},className:"font-semibold text-sm text-blue-600 hover:text-blue-800 hover:underline cursor-pointer transition-colors","data-testid":`lifecycle-request-link-${N.id}`,children:N.id}),e.jsx(ee,{className:Yh(N.priority),"data-testid":`lifecycle-priority-${N.id}`,children:N.priority}),e.jsx(ee,{className:Zh(N.status),"data-testid":`lifecycle-status-${N.id}`,children:N.status})]}),e.jsx("p",{className:"text-sm text-gray-700",children:N.title}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["Initiated by ",e.jsx("span",{className:"font-medium",children:N.initiator})," on ",N.initDate]}),N.currentStage&&!N.currentStage.includes("Level")&&e.jsxs("p",{className:"text-xs text-gray-400 mt-0.5",children:["Stage: ",N.currentStage]})]})}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Current Stage"}),e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:N.currentStage}),e.jsxs("p",{className:"text-xs text-gray-400 mt-0.5",children:["(Level ",N.currentLevel,"/",N.totalLevels,")"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Overall TAT"}),e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:N.overallTAT}),N.breachCount>0&&e.jsxs("p",{className:"text-xs text-red-500 mt-0.5",children:[N.breachCount," breach",N.breachCount>1?"es":""]})]}),e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>b(N.requestId||N.id),className:"gap-1.5","data-testid":`lifecycle-view-button-${N.id}`,children:e.jsx(xo,{className:"w-4 h-4"})})]})]})})},N.id))}),n.totalPages>1&&e.jsxs("div",{className:"flex items-center justify-between p-4 border-t relative","data-testid":"lifecycle-pagination",children:[a&&e.jsx("div",{className:"absolute inset-0 bg-white/80 flex items-center justify-center z-10 rounded-b-lg",children:e.jsx(Xe,{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(R,{variant:"outline",size:"sm",onClick:()=>f(n.page-1),disabled:n.page<=1||a,"data-testid":"lifecycle-pagination-prev",children:"Previous"}),e.jsx(R,{variant:"outline",size:"sm",onClick:()=>f(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"lifecycle-pagination-next",children:"Next"})]})]})]})]})}function hl({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:fe("w-full caption-bottom text-sm",t),...s})})}function pl({className:t,...s}){return e.jsx("thead",{"data-slot":"table-header",className:fe("[&_tr]:border-b",t),...s})}function xl({className:t,...s}){return e.jsx("tbody",{"data-slot":"table-body",className:fe("[&_tr:last-child]:border-0",t),...s})}function Ma({className:t,...s}){return e.jsx("tr",{"data-slot":"table-row",className:fe("hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",t),...s})}function Ot({className:t,...s}){return e.jsx("th",{"data-slot":"table-head",className:fe("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:fe("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",t),...s})}function jA({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:N,onClearFilters:A,onPageChange:D,onExport:T,onViewRequest:P}){const w=u!=="all"||h!=="all"||i!=="month"||o||l;return e.jsxs(Z,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"user-activity-log-report",children:[e.jsxs(ae,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-indigo-100 rounded-lg",children:e.jsx(sg,{className:"h-5 w-5 text-indigo-600"})}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-lg text-gray-900",children:"User Activity Log Report"}),e.jsx(we,{className:"text-gray-600",children:"Consolidated user actions and activity history"})]})]}),e.jsxs(R,{variant:"outline",size:"sm",className:"gap-2",onClick:T,disabled:p,"data-testid":"export-activity-button",children:[e.jsx(Qt,{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(ul,{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(_e,{value:u,onValueChange:b,"data-testid":"activity-category-filter",children:[e.jsx(Oe,{className:"w-40",children:e.jsx(Le,{placeholder:"All Categories"})}),e.jsxs($e,{children:[e.jsx(H,{value:"all",children:"All Categories"}),e.jsx(H,{value:"WORKFLOW",children:"Workflow"}),e.jsx(H,{value:"COLLABORATION",children:"Collaboration"}),e.jsx(H,{value:"DOCUMENT",children:"Document"}),e.jsx(H,{value:"AUTHENTICATION",children:"Authentication"}),e.jsx(H,{value:"SYSTEM",children:"System"}),e.jsx(H,{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(_e,{value:h,onValueChange:N,"data-testid":"activity-severity-filter",children:[e.jsx(Oe,{className:"w-40",children:e.jsx(Le,{placeholder:"All Severities"})}),e.jsxs($e,{children:[e.jsx(H,{value:"all",children:"All Severities"}),e.jsx(H,{value:"INFO",children:"Info"}),e.jsx(H,{value:"WARNING",children:"Warning"}),e.jsx(H,{value:"ERROR",children:"Error"}),e.jsx(H,{value:"CRITICAL",children:"Critical"})]})]})]}),w&&e.jsx(R,{variant:"ghost",size:"sm",onClick:A,className:"text-xs","data-testid":"activity-clear-filters",children:"Clear Filters"})]})]}),e.jsx(X,{children:s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"activity-loading",children:[e.jsx(Xe,{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(hl,{children:[e.jsx(pl,{children:e.jsxs(Ma,{className:"bg-gray-50",children:[e.jsx(Ot,{className:"font-semibold",children:"Timestamp"}),e.jsx(Ot,{className:"font-semibold",children:"User"}),e.jsx(Ot,{className:"font-semibold",children:"Action"}),e.jsx(Ot,{className:"font-semibold",children:"Details"}),e.jsx(Ot,{className:"font-semibold",children:"IP Address"}),e.jsx(Ot,{className:"font-semibold",children:"Request ID"})]})}),e.jsx(xl,{children:t.map((S,M)=>e.jsxs(Ma,{className:"hover:bg-gray-50","data-testid":`activity-row-${M}`,children:[e.jsx(Mt,{className:"text-xs font-medium",children:S.timestamp}),e.jsx(Mt,{className:"text-sm",children:S.user}),e.jsx(Mt,{children:e.jsx(ee,{className:yA(S.action),"data-testid":`activity-action-${M}`,children:S.action})}),e.jsx(Mt,{className:"text-sm text-gray-600",children:S.details}),e.jsx(Mt,{className:"text-xs font-mono text-gray-500",children:S.ip&&S.ip!=="N/A"?e.jsx("span",{title:S.userAgent||"",children:S.ip}):e.jsx("span",{className:"text-gray-400 italic",title:"IP address not yet captured",children:"N/A"})}),e.jsx(Mt,{children:S.requestId!=="-"&&S.requestId!=="System Login"?e.jsx("button",{onClick:()=>{const B=S.requestId;B&&P(B)},className:"hover:underline","data-testid":`activity-request-link-${M}`,children:e.jsx(ee,{variant:"outline",className:"text-xs cursor-pointer hover:bg-blue-50 hover:border-blue-300 transition-colors",children:S.requestId})}):e.jsx("span",{className:"text-xs text-gray-400",children:"-"})})]},M))})]}),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(Xe,{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(R,{variant:"outline",size:"sm",onClick:()=>D(n.page-1),disabled:n.page<=1||a,"data-testid":"activity-pagination-prev",children:"Previous"}),e.jsx(R,{variant:"outline",size:"sm",onClick:()=>D(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"activity-pagination-next",children:"Next"})]})]})]})})]})}function NA({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:N,onCancelCustomDate:A,onSearchChange:D,onPageChange:T,onExport:P,onViewRequest:w}){return e.jsxs(Z,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"workflow-aging-report",children:[e.jsxs(ae,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-amber-100 rounded-lg",children:e.jsx(go,{className:"h-5 w-5 text-amber-600"})}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-lg text-gray-900",children:"Workflow Aging Report"}),e.jsx(we,{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(je,{type:"number",min:"1",value:i,onChange:S=>y(S.target.value),onBlur:v,className:`w-24 ${o?"border-red-500 focus:border-red-500 focus:ring-red-500":""}`,placeholder:"Days","data-testid":"aging-threshold-input"}),e.jsx("span",{className:"text-sm text-gray-600 whitespace-nowrap",children:"days"})]}),o&&e.jsx("span",{className:"text-xs text-red-600",children:o})]})]}),e.jsxs(ee,{variant:"outline",className:"font-semibold","data-testid":"aging-total-badge",children:[n.totalRecords," workflows"]}),e.jsxs(R,{variant:"outline",size:"sm",className:"gap-2",onClick:P,disabled:g,"data-testid":"export-aging-button",children:[e.jsx(Qt,{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(ul,{dateRange:l,customStartDate:c,customEndDate:d,showCustomDatePicker:m,tempCustomStartDate:u,tempCustomEndDate:h,onDateRangeChange:C,onShowCustomDatePickerChange:f,onStartDateChange:j,onEndDateChange:b,onApply:N,onCancel:A,testIdPrefix:"aging"}),e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(bs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(je,{placeholder:"Search by Request ID, Title, or Initiator...",value:p,onChange:S=>D(S.target.value),className:"pl-10","data-testid":"aging-search-input"})]})]})]}),e.jsx(X,{children:s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"aging-loading",children:[e.jsx(Xe,{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(hl,{children:[e.jsx(pl,{children:e.jsxs(Ma,{className:"bg-gray-50",children:[e.jsx(Ot,{className:"font-semibold",children:"Request ID"}),e.jsx(Ot,{className:"font-semibold",children:"Title"}),e.jsx(Ot,{className:"font-semibold",children:"Initiator"}),e.jsx(Ot,{className:"font-semibold",children:"Start Date"}),e.jsx(Ot,{className:"font-semibold",children:"Days Open"}),e.jsx(Ot,{className:"font-semibold",children:"Current Stage"}),e.jsx(Ot,{className:"font-semibold",children:"Assigned To"}),e.jsx(Ot,{className:"font-semibold",children:"Priority"}),e.jsx(Ot,{className:"font-semibold",children:"Status"})]})}),e.jsx(xl,{children:t.map(S=>e.jsxs(Ma,{className:"hover:bg-gray-50","data-testid":`aging-workflow-${S.id}`,children:[e.jsx(Mt,{className:"font-medium text-sm",children:e.jsx("button",{onClick:()=>w(S.requestId||S.id),className:"text-blue-600 hover:text-blue-800 hover:underline cursor-pointer transition-colors","data-testid":`aging-request-link-${S.id}`,children:S.id})}),e.jsx(Mt,{className:"text-sm",children:S.title}),e.jsx(Mt,{className:"text-sm",children:S.initiator}),e.jsx(Mt,{className:"text-sm text-gray-600",children:S.startDate}),e.jsx(Mt,{children:e.jsxs(ee,{className:`${bA(S.daysOpen)} text-white border-transparent`,"data-testid":`aging-days-${S.id}`,children:[S.daysOpen," days",e.jsx("span",{className:"ml-1 text-xs opacity-75",children:"(business)"})]})}),e.jsx(Mt,{className:"text-sm",children:S.currentStage}),e.jsx(Mt,{className:"text-sm",children:S.assignedTo&&S.assignedTo!=="N/A"?S.assignedTo:e.jsx("span",{className:"text-gray-400 italic",title:"Assigned approver not available",children:"N/A"})}),e.jsx(Mt,{children:e.jsx(ee,{className:Yh(S.priority),"data-testid":`aging-priority-${S.id}`,children:S.priority})}),e.jsx(Mt,{children:e.jsx(ee,{className:Zh(S.status),"data-testid":`aging-status-${S.id}`,children:S.status})})]},S.id))})]}),n.totalPages>1&&e.jsxs("div",{className:"flex items-center justify-between p-4 border-t relative","data-testid":"aging-pagination",children:[a&&e.jsx("div",{className:"absolute inset-0 bg-white/80 flex items-center justify-center z-10 rounded-b-lg",children:e.jsx(Xe,{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(R,{variant:"outline",size:"sm",onClick:()=>T(n.page-1),disabled:n.page<=1||a,"data-testid":"aging-pagination-prev",children:"Previous"}),e.jsx(R,{variant:"outline",size:"sm",onClick:()=>T(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"aging-pagination-next",children:"Next"})]})]})]})})]})}function wi(t="month"){const[s,a]=x.useState(t),[r,n]=x.useState(void 0),[i,o]=x.useState(void 0),[l,c]=x.useState(!1),[d,m]=x.useState(void 0),[u,h]=x.useState(void 0),p=x.useCallback(b=>{const N=b;a(N),N!=="custom"?(n(void 0),o(void 0),m(void 0),h(void 0),c(!1)):(m(r),h(i),c(!0))},[r,i]),g=x.useCallback(()=>{if(d&&u){if(d>u){const b=d;n(u),o(b),m(u),h(b)}else n(d),o(u);c(!1)}},[d,u]),y=x.useCallback(()=>{c(!1),m(r),h(i),(!r||!i)&&(n(void 0),o(void 0),a("month"))},[r,i]),v=x.useCallback(b=>{b?(m(b),u&&b>u&&h(b)):m(void 0)},[u]),C=x.useCallback(b=>{b?(h(b),d&&b<d&&m(b)):h(void 0)},[d]),f=x.useCallback(()=>r&&i?`${Ne(r,"MMM d, yyyy")} - ${Ne(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 wA(t){if(!t&&t!==0)return"N/A";const s=8;if(t<s)return At(t);const a=Math.floor(t/s),r=t%s;return r>0?`${a}d ${At(r)}`:`${a}d`}function Xh(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 Sa(t){if(!t)return"N/A";try{const s=new Date(t),a=s.getFullYear(),r=String(s.getMonth()+1).padStart(2,"0"),n=String(s.getDate()).padStart(2,"0"),i=String(s.getHours()).padStart(2,"0"),o=String(s.getMinutes()).padStart(2,"0");return`${a}-${r}-${n} ${i}:${o}`}catch{return t}}function Jh(t,s){const a=(t||"").toLowerCase();return a.includes("created")||a.includes("create")?"Created Request":a.includes("approval")||a.includes("approved")?"Approved Request":a.includes("rejection")||a.includes("rejected")?"Rejected Request":a.includes("comment")?"Added Comment":a.includes("view")||a.includes("viewed")?"Viewed Request":a.includes("upload")||a.includes("document")?"Uploaded Document":a.includes("login")?"Login":t||"Activity"}const CA=10;function SA({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 mt.getLifecycleReport(y,CA,t,s,a),f=C.lifecycleData.map(j=>{const b=wA(j.overallTATHours);return{id:j.requestNumber,requestId:j.requestId,title:j.title,priority:j.priority||"medium",status:j.status,initiator:j.initiatorName||"Unknown",initDate:Xh(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 AA=20;function kA({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 mt.getActivityLogReport(C,AA,t,void 0,void 0,r&&r!=="all"?r:void 0,n&&n!=="all"?n:void 0,s,a),b=j.activities.map(N=>{const A=Jh(N.type||"",N.details),D=(N.type||"").toLowerCase()==="login"||N.requestId==="00000000-0000-0000-0000-000000000001"||N.requestId==="SYSTEM_LOGIN",T=D?N.details||"User login":N.requestTitle||N.requestNumber||N.details||"N/A";return{timestamp:N.timestamp?Xh(N.timestamp):"N/A",user:N.userName||"Unknown",action:A,details:T,ip:N.ipAddress||"N/A",userAgent:N.userAgent||null,requestId:D?"System Login":N.requestNumber||N.requestId||"-",userId:N.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 TA=20;function DA({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 N=await mt.getWorkflowAgingReport(b,f,TA,s,a,r),A=N.agingData.map(D=>({id:D.requestNumber||D.requestId,requestId:D.requestId,title:D.title,initiator:D.initiatorName||"Unknown",startDate:D.submissionDate?new Date(D.submissionDate).toLocaleDateString():"N/A",daysOpen:D.daysOpen,currentStage:D.currentStageName||`Level ${D.currentLevel}`,assignedTo:D.currentApproverName||"N/A",priority:D.priority||"medium",status:D.status||"pending"}));o(A),g({page:N.pagination.currentPage,totalPages:N.pagination.totalPages,totalRecords:N.pagination.totalRecords})}catch(b){console.error("Failed to fetch aging data:",b),h((b==null?void 0:b.message)||"Failed to load aging data")}finally{j?c(!1):m(!1)}j&&(y.current=!1)},[t,s,a,r]),C=x.useMemo(()=>i.filter(f=>{var b,N,A;if(!n)return!0;const j=n.toLowerCase();return((b=f.id)==null?void 0:b.toLowerCase().includes(j))||((N=f.title)==null?void 0:N.toLowerCase().includes(j))||((A=f.initiator)==null?void 0:A.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 RA(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 PA(t,s,a){const r=await mt.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 ds(i.requestId||i.requestNumber),l=i.submissionDate?Sa(i.submissionDate):"N/A",c=i.closureDate?Sa(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?Sa(g.levelStartTime):"N/A",v=g.levelEndTime||g.completedAt?Sa(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",N="N/A",A="N/A";if(g.levelStartTime){const T=new Date(g.levelStartTime);if(b=(((g.levelEndTime||g.completedAt?new Date(g.levelEndTime||g.completedAt):new Date).getTime()-T.getTime())/(1e3*60*60)).toFixed(2),C>0){const S=parseFloat(b);N=Math.max(0,C-S).toFixed(2),A=(S/C*100).toFixed(2),g.status==="APPROVED"||g.status==="REJECTED"?j=S<=C?"Compliant":"Breached":g.status==="IN_PROGRESS"||g.status==="PENDING"?j=S<=C?"On Track":"At Risk":j="N/A"}}const D=[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,N,A];n.push(D.join(","))})}catch(o){console.error(`Failed to fetch details for request ${i.requestNumber}:`,o);const l=i.submissionDate?Sa(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(","))}gl(n,`lifecycle-report-end-to-end-${new Date().toISOString().split("T")[0]}.csv`)}async function EA(t,s,a,r,n){const i=await mt.getActivityLogReport(1,1e4,t,void 0,void 0,r&&r!=="all"?r:void 0,n&&n!=="all"?n:void 0,s,a),o=[["Timestamp","User","Action","Details","IP Address","User Agent","Request ID"].join(",")];i.activities.forEach(l=>{const c=Jh(l.type||"",l.details),m=[l.timestamp?Sa(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(","))}),gl(o,`activity-log-report-${new Date().toISOString().split("T")[0]}.csv`)}async function IA(t,s,a,r){const n=await mt.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?Sa(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(","))}),gl(i,`workflow-aging-report-${new Date().toISOString().split("T")[0]}.csv`)}function gl(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 MA(){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 PA(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 EA(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 IA(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 FA({onBack:t}){const s=pa(),[a,r]=x.useState(""),[n,i]=x.useState("all"),[o,l]=x.useState("all"),c=wi("month"),d=wi("month"),m=wi("month"),u=RA("7"),h=SA({dateRange:c.dateRange,customStartDate:c.customStartDate,customEndDate:c.customEndDate}),p=kA({dateRange:d.dateRange,customStartDate:d.customStartDate,customEndDate:d.customEndDate,filterCategory:n,filterSeverity:o}),g=DA({threshold:u.threshold,dateRange:m.dateRange,customStartDate:m.customStartDate,customEndDate:m.customEndDate,searchQuery:a}),y=MA(),v=x.useCallback(()=>{t?t():s("/dashboard")},[t,s]),C=x.useCallback(A=>{s(`/request/${A}`)},[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 A=parseInt(u.threshold,10);!isNaN(A)&&A>=1&&y.handleExportAging(A,m.dateRange,m.customStartDate,m.customEndDate)},[y,u.threshold,m]),N=x.useCallback(()=>{i("all"),l("all"),d.reset()},[d]);return e.jsx("div",{className:"flex-1 p-3 lg:p-6 overflow-auto min-w-0","data-testid":"detailed-reports",children:e.jsxs("div",{className:"space-y-6 max-w-7xl mx-auto p-4",children:[e.jsx(fA,{onBack:v}),e.jsx(vA,{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(jA,{activityLog:p.activityLog,loading:p.loading,loadingPage:p.loadingPage,error:p.error,pagination:p.pagination,dateRange:d.dateRange,customStartDate:d.customStartDate,customEndDate:d.customEndDate,showCustomDatePicker:d.showCustomDatePicker,tempCustomStartDate:d.tempCustomStartDate,tempCustomEndDate:d.tempCustomEndDate,filterCategory:n,filterSeverity:o,exporting:y.exportingActivity,onDateRangeChange:d.handleDateRangeChange,onShowCustomDatePickerChange:d.setShowCustomDatePicker,onStartDateChange:d.handleStartDateChange,onEndDateChange:d.handleEndDateChange,onApplyCustomDate:d.handleApplyCustomDate,onCancelCustomDate:d.handleCancelCustomDate,onCategoryChange:i,onSeverityChange:l,onClearFilters:N,onPageChange:p.fetchData,onExport:j,onViewRequest:C}),e.jsx(NA,{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 _A({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(Y,{htmlFor:"default-period",children:"Default Reporting Period"}),e.jsxs(_e,{value:t,onValueChange:a,children:[e.jsx(Oe,{id:"default-period",children:e.jsx(Le,{})}),e.jsx($e,{children:n.map(i=>e.jsx(H,{value:i,children:i},i))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Y,{htmlFor:"refresh-interval",children:"Auto-Refresh Interval (minutes)"}),e.jsx(je,{id:"refresh-interval",type:"number",min:"1",max:"60",value:s,onChange:i=>r(parseInt(i.target.value)||5)})]})]})}function LA({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(ns,{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(ns,{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(ns,{checked:a,onCheckedChange:i})]})]})}const OA=["CSV","Excel","PDF","JSON"];function $A({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(Y,{children:"Allowed Export Formats"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:OA.map(r=>e.jsxs("div",{className:"flex items-center space-x-2 p-2 bg-muted/50 rounded",children:[e.jsx(wo,{id:`export-${r}`,checked:t.includes(r),onCheckedChange:n=>a(r,n)}),e.jsx(Y,{htmlFor:`export-${r}`,className:"text-sm cursor-pointer",children:r})]},r))})]})}function UA({dataRetention:t,onDataRetentionChange:s}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(Y,{htmlFor:"data-retention",children:"Historical Data Retention (months)"}),e.jsx(je,{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 BA(){const[t,s]=x.useState({defaultPeriod:"This Month",refreshInterval:5,autoRefresh:!0,realTimeUpdates:!0,dataExport:!0,exportFormats:["CSV","Excel","PDF"],dataRetention:24}),a=()=>{te.success("Analytics configuration saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(Z,{children:[e.jsxs(ae,{children:[e.jsx(ne,{children:"Analytics & Reporting Configuration"}),e.jsx(we,{children:"Configure default reporting periods, auto-refresh, export settings, and data retention"})]}),e.jsxs(X,{className:"space-y-6",children:[e.jsx(_A,{defaultPeriod:t.defaultPeriod,refreshInterval:t.refreshInterval,onDefaultPeriodChange:n=>r({defaultPeriod:n}),onRefreshIntervalChange:n=>r({refreshInterval:n})}),e.jsx(Tt,{}),e.jsx(LA,{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(Tt,{}),e.jsx($A,{exportFormats:t.exportFormats,onExportFormatsChange:n=>r({exportFormats:n})}),e.jsx(UA,{dataRetention:t.dataRetention,onDataRetentionChange:n=>r({dataRetention:n})}),e.jsxs(R,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(ha,{className:"w-4 h-4 mr-2"}),"Save Analytics Configuration"]})]})]})}const VA=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"}},zA=t=>t.split(" ").map(s=>s[0]).join("").toUpperCase().substring(0,2);function HA({users:t,onEdit:s,onToggleStatus:a,onDelete:r}){return e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(hl,{children:[e.jsx(pl,{children:e.jsxs(Ma,{children:[e.jsx(Ot,{children:"User"}),e.jsx(Ot,{children:"Role"}),e.jsx(Ot,{children:"Department"}),e.jsx(Ot,{children:"Status"}),e.jsx(Ot,{className:"text-right",children:"Actions"})]})}),e.jsx(xl,{children:t.length===0?e.jsx(Ma,{children:e.jsx(Mt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No users found"})}):t.map(n=>e.jsxs(Ma,{className:"hover:bg-muted/50",children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx($t,{className:"size-10",children:e.jsx(Ut,{className:"bg-re-green text-white",children:zA(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(ee,{className:VA(n.role),children:n.role})}),e.jsx(Mt,{children:n.department}),e.jsx(Mt,{children:e.jsxs(ee,{className:"bg-green-100 text-green-800 border-green-200",children:[e.jsx(Ai,{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(R,{variant:"ghost",size:"sm",onClick:()=>s(n.id),className:"h-8",children:e.jsx(Nn,{className:"w-4 h-4"})}),e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>a(n.id),disabled:n.role.toUpperCase()==="ADMIN",className:"h-8",children:e.jsx(ag,{className:"w-4 h-4"})}),e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>r(n.id),disabled:n.role.toUpperCase()==="ADMIN",className:"h-8 text-destructive hover:text-destructive",children:e.jsx(fo,{className:"w-4 h-4"})})]})})]},n.id))})]})})}function WA({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 KA(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function GA(){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,N]=x.useState({admins:0,management:0,users:0,total:0,active:0,inactive:0}),[A,D]=x.useState("ELEVATED"),[T,P]=x.useState(1),[w,S]=x.useState(1),[M,B]=x.useState(0),_=10,$=x.useRef(null),k=x.useCallback(KA(async V=>{var q,ie,ue;if(!V||!V.startsWith("@")||V.length<2){r([]),i(!1);return}i(!0);try{const Te=V.slice(1),ze=((q=(await fs.searchUsers(Te,20)).data)==null?void 0:q.data)||[];r(ze)}catch(Te){console.error("Search failed:",Te),y({type:"error",text:((ue=(ie=Te.response)==null?void 0:ie.data)==null?void 0:ue.message)||"Failed to search users"})}finally{i(!1)}},300),[]),I=V=>{const q=V.target.value;s(q),k(q)},E=async V=>{var q,ie;try{const ue=v.find(Ze=>Ze.email.toLowerCase()===V.toLowerCase());if(ue)return ue.role;const ze=(((ie=(q=(await fs.getUsersByRole("ALL",1,1e3)).data)==null?void 0:q.data)==null?void 0:ie.users)||[]).find(Ze=>{var Ge;return((Ge=Ze.email)==null?void 0:Ge.toLowerCase())===V.toLowerCase()});return ze&&ze.role?ze.role:null}catch(ue){return console.error("Failed to fetch user role:",ue),null}},F=async V=>{l(V),s(V.email),r([]),p(!0);try{const q=await E(V.email);d(q||"USER")}catch(q){console.error("Failed to fetch user role:",q),d("USER")}finally{p(!1)}},O=async()=>{var V,q;if(!o||!c){y({type:"error",text:"Please select a user and role"});return}u(!0),y(null);try{await fs.assignRole(o.email,c),y({type:"success",text:`Successfully assigned ${c} role to ${o.displayName||o.email}`}),l(null),s(""),d("USER"),await L(),await J(),te.success("Role assigned successfully")}catch(ie){console.error("Role assignment failed:",ie);const ue=((q=(V=ie.response)==null?void 0:V.data)==null?void 0:q.error)||"Failed to assign role";y({type:"error",text:ue}),te.error(ue)}finally{u(!1)}},L=async(V=T)=>{var q,ie,ue,Te,qe,ze;j(!0);try{const Ze=await fs.getUsersByRole(A,V,_),Ge=((ie=(q=Ze.data)==null?void 0:q.data)==null?void 0:ie.users)||[],He=(Te=(ue=Ze.data)==null?void 0:ue.data)==null?void 0:Te.pagination,xt=(ze=(qe=Ze.data)==null?void 0:qe.data)==null?void 0:ze.summary;C(Ge.map(Q=>({userId:Q.userId,email:Q.email,displayName:Q.displayName||Q.email,role:Q.role||"USER",department:Q.department,designation:Q.designation,isActive:Q.isActive!==!1}))),He&&(P(He.currentPage),S(He.totalPages),B(He.totalUsers)),xt&&N(Q=>({...Q,admins:xt.ADMIN||0,management:xt.MANAGEMENT||0,users:xt.USER||0,total:(xt.ADMIN||0)+(xt.MANAGEMENT||0)+(xt.USER||0)}))}catch(Ze){console.error("Failed to fetch users:",Ze),te.error("Failed to load users")}finally{j(!1)}},J=async()=>{var V,q,ie,ue,Te,qe;try{const ze=await fs.getRoleStatistics(),Ze=((q=(V=ze.data)==null?void 0:V.data)==null?void 0:q.statistics)||((ie=ze.data)==null?void 0:ie.statistics)||[],Ge={admins:parseInt(((ue=Ze.find(He=>He.role==="ADMIN"))==null?void 0:ue.count)||"0"),management:parseInt(((Te=Ze.find(He=>He.role==="MANAGEMENT"))==null?void 0:Te.count)||"0"),users:parseInt(((qe=Ze.find(He=>He.role==="USER"))==null?void 0:qe.count)||"0")};N(He=>({...He,...Ge,total:Ge.admins+Ge.management+Ge.users,active:He.active||Ge.admins+Ge.management+Ge.users,inactive:He.inactive||0}))}catch(ze){console.error("Failed to fetch statistics:",ze)}};x.useEffect(()=>{L(1),J()},[A]);const U=V=>{D(V),P(1)},oe=V=>{L(V)},ge=async(V,q)=>{var ie,ue;try{await fs.updateUserRole(V,q),te.success("User role updated successfully"),await L(),await J()}catch(Te){console.error("Failed to update user role:",Te),te.error(((ue=(ie=Te.response)==null?void 0:ie.data)==null?void 0:ue.error)||"Failed to update user role")}},G=async V=>{v.find(ie=>ie.userId===V)&&te.info("User status toggle functionality coming soon")},me=async V=>{const q=v.find(ie=>ie.userId===V);if(q){if(q.role==="ADMIN"){te.error("Cannot delete admin user");return}te.info("User deletion functionality coming soon")}};x.useEffect(()=>{const V=q=>{$.current&&!$.current.contains(q.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",V),()=>{document.removeEventListener("mousedown",V)}},[a]);const re={total:b.total,active:b.active,inactive:b.inactive,admins:b.admins};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(WA,{stats:re}),e.jsxs(Z,{children:[e.jsx(ae,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Assign User Role"}),e.jsx(we,{children:"Search for a user in Okta and assign them a role"})]}),e.jsx(R,{onClick:O,disabled:!o||m,className:"bg-re-green hover:bg-re-green/90",children:m?e.jsxs(e.Fragment,{children:[e.jsx(Xe,{className:"w-4 h-4 mr-2 animate-spin"}),"Assigning..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Is,{className:"w-4 h-4 mr-2"}),"Assign Role"]})})]})}),e.jsxs(X,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",ref:$,children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:"relative flex-1",children:[e.jsx(bs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(je,{type:"text",placeholder:"Type @ to search users...",value:t,onChange:I,className:"pl-10 border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),n&&e.jsx(Xe,{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(V=>e.jsxs("button",{onClick:()=>F(V),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:V.displayName||V.email}),e.jsx("p",{className:"text-sm text-muted-foreground",children:V.email}),V.department&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[V.department,V.designation?` • ${V.designation}`:""]})]},V.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(Xe,{className:"w-3 h-3 animate-spin"}),"Checking current role..."]})]})]}),e.jsx(R,{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(_e,{value:c,onValueChange:V=>d(V),disabled:h,children:[e.jsx(Oe,{className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Le,{placeholder:h?"Loading current role...":"Select role"})}),e.jsxs($e,{className:"rounded-lg",children:[e.jsx(H,{value:"USER",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(St,{className:"w-4 h-4 text-gray-600"}),e.jsx("span",{children:"User - Regular access"})]})}),e.jsx(H,{value:"MANAGEMENT",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ct,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Management - Read all data"})]})}),e.jsx(H,{value:"ADMIN",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(La,{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(Ce,{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(Z,{children:[e.jsx(ae,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs(ne,{className:"flex items-center gap-2",children:[e.jsx(Ct,{className:"w-5 h-5 text-re-green"}),"User Management"]}),e.jsxs(we,{children:["View and manage user accounts and roles (",M," ",A!=="ALL"&&A!=="ELEVATED"?A.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(_e,{value:A,onValueChange:U,children:[e.jsx(Oe,{className:"w-[200px] border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Le,{placeholder:"Filter by role"})}),e.jsxs($e,{children:[e.jsx(H,{value:"ELEVATED",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ss,{className:"w-4 h-4 text-purple-600"}),e.jsxs("span",{children:["Elevated (",b.admins+b.management,")"]})]})}),e.jsx(H,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(La,{className:"w-4 h-4 text-yellow-600"}),e.jsxs("span",{children:["Admins (",b.admins,")"]})]})}),e.jsx(H,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ct,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Management (",b.management,")"]})]})}),e.jsx(H,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(St,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["Users (",b.users,")"]})]})}),e.jsx(H,{value:"ALL",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ct,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["All Users (",b.admins+b.management+b.users,")"]})]})})]})]})})]})}),e.jsx(X,{className:"pt-6",children:f?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsx(Xe,{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(Ct,{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:A==="ELEVATED"?"Assign ADMIN or MANAGEMENT roles to see users here":"No users match the selected filter"})]}):e.jsxs(e.Fragment,{children:[e.jsx(HA,{users:v.map(V=>({id:V.userId,name:V.displayName,email:V.email,role:V.role,department:V.department||"N/A",status:V.isActive?"active":"inactive"})),onEdit:V=>{const q=v.find(ie=>ie.userId===V);if(q){const ie=q.role==="USER"?"MANAGEMENT":q.role==="MANAGEMENT"?"ADMIN":"USER";ge(V,ie)}},onToggleStatus:G,onDelete:me}),w>1&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t mt-4",children:[e.jsxs("div",{className:"text-sm text-gray-600",children:["Showing ",(T-1)*_+1," to ",Math.min(T*_,M)," of ",M," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(R,{variant:"outline",size:"sm",onClick:()=>oe(T-1),disabled:T===1,children:"Previous"}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,w)},(V,q)=>{let ie;return w<=5||T<=3?ie=q+1:T>=w-2?ie=w-4+q:ie=T-2+q,e.jsx(R,{variant:T===ie?"default":"outline",size:"sm",onClick:()=>oe(ie),className:`w-9 h-9 p-0 ${T===ie?"bg-re-green hover:bg-re-green/90":""}`,children:ie},ie)})}),e.jsx(R,{variant:"outline",size:"sm",onClick:()=>oe(T+1),disabled:T===w,children:"Next"})]})]})]})})]})]})}function YA({expressHours:t,standardHours:s,onExpressChange:a,onStandardChange:r}){return e.jsxs(Z,{className:"border-0 shadow-sm",children:[e.jsxs(ae,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mo,{className:"w-5 h-5 text-re-green"}),e.jsx(ne,{className:"text-base font-semibold",children:"Priority TAT Settings"})]}),e.jsx(we,{className:"text-sm",children:"Set default turnaround time in hours for each priority level"})]}),e.jsx(X,{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(Y,{htmlFor:"tat-express",className:"text-sm font-medium",children:"Express Priority (hours)"}),e.jsx(je,{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(Ue,{className:"w-3 h-3"}),"Critical/Emergency requests (24/7, includes weekends)"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Y,{htmlFor:"tat-standard",className:"text-sm font-medium",children:"Standard Priority (hours)"}),e.jsx(je,{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(Ue,{className:"w-3 h-3"}),"Regular priority requests (working hours only, excludes weekends & holidays)"]})]})]})})]})}function ZA({reminderThreshold1:t,reminderThreshold2:s,onReminderThreshold1Change:a,onReminderThreshold2Change:r}){return e.jsxs(Z,{className:"border-0 shadow-sm",children:[e.jsxs(ae,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(as,{className:"w-5 h-5 text-re-green"}),e.jsx(ne,{className:"text-base font-semibold",children:"Auto-Reminder & Escalation"})]}),e.jsx(we,{className:"text-sm",children:"Configure automatic reminder thresholds based on TAT percentage"})]}),e.jsx(X,{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(Y,{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(ao,{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(as,{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(Y,{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(ao,{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(Cs,{className:"w-3 h-3"}),"Send escalation warning when ",s,"% of TAT elapsed"]})]})]})})]})}const cr=[{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 XA({workStartHour:t,workEndHour:s,workStartDay:a,workEndDay:r,onWorkStartHourChange:n,onWorkEndHourChange:i,onWorkStartDayChange:o,onWorkEndDayChange:l}){var c,d,m;return e.jsxs(Z,{className:"border-0 shadow-sm",children:[e.jsxs(ae,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(et,{className:"w-5 h-5 text-re-green"}),e.jsx(ne,{className:"text-base font-semibold",children:"Working Hours Configuration"})]}),e.jsx(we,{className:"text-sm",children:"Define your organization's working hours and days for TAT calculations"})]}),e.jsxs(X,{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(Y,{htmlFor:"work-start-hour",className:"text-sm font-medium",children:"Working Day Start Hour"}),e.jsx(je,{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(Ue,{className:"w-3 h-3"}),"24-hour format (0-23). Default: 9 AM"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Y,{htmlFor:"work-end-hour",className:"text-sm font-medium",children:"Working Day End Hour"}),e.jsx(je,{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(Ue,{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(Y,{htmlFor:"work-start-day",className:"text-sm font-medium",children:"Working Week Start Day"}),e.jsxs(_e,{value:a.toString(),onValueChange:u=>o(parseInt(u)),children:[e.jsx(Oe,{id:"work-start-day",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Le,{placeholder:"Select start day"})}),e.jsx($e,{children:cr.map(u=>e.jsx(H,{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(Y,{htmlFor:"work-end-day",className:"text-sm font-medium",children:"Working Week End Day"}),e.jsxs(_e,{value:r.toString(),onValueChange:u=>l(parseInt(u)),children:[e.jsx(Oe,{id:"work-end-day",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Le,{placeholder:"Select end day"})}),e.jsx($e,{children:cr.map(u=>e.jsx(H,{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=cr.find(u=>u.value===a))==null?void 0:c.label} only`:` ${(d=cr.find(u=>u.value===a))==null?void 0:d.label} to ${(m=cr.find(u=>u.value===r))==null?void 0:m.label}`]})})]})]})}function JA(){const[t,s]=x.useState(!0),[a,r]=x.useState(!1),[n,i]=x.useState({expressHours:24,standardHours:72,reminderThreshold1:50,reminderThreshold2:75,workStartHour:9,workEndHour:18,workStartDay:1,workEndDay:5});x.useEffect(()=>{o()},[]);const o=async()=>{try{s(!0);const d=await Tn("TAT_SETTINGS"),m={};d.forEach(u=>{m[u.configKey]=u.configValue}),i({expressHours:parseInt(m.DEFAULT_TAT_EXPRESS_HOURS||"24"),standardHours:parseInt(m.DEFAULT_TAT_STANDARD_HOURS||"72"),reminderThreshold1:parseInt(m.TAT_REMINDER_THRESHOLD_1||"50"),reminderThreshold2:parseInt(m.TAT_REMINDER_THRESHOLD_2||"75"),workStartHour:parseInt(m.WORK_START_HOUR||"9"),workEndHour:parseInt(m.WORK_END_HOUR||"18"),workStartDay:parseInt(m.WORK_START_DAY||"1"),workEndDay:parseInt(m.WORK_END_DAY||"5")})}catch(d){console.error("Failed to load TAT configurations:",d),te.error("Failed to load TAT configurations")}finally{s(!1)}},l=async()=>{var d,m;try{r(!0),await Promise.all([Bt("DEFAULT_TAT_EXPRESS_HOURS",n.expressHours.toString()),Bt("DEFAULT_TAT_STANDARD_HOURS",n.standardHours.toString()),Bt("TAT_REMINDER_THRESHOLD_1",n.reminderThreshold1.toString()),Bt("TAT_REMINDER_THRESHOLD_2",n.reminderThreshold2.toString()),Bt("WORK_START_HOUR",n.workStartHour.toString()),Bt("WORK_END_HOUR",n.workEndHour.toString()),Bt("WORK_START_DAY",n.workStartDay.toString()),Bt("WORK_END_DAY",n.workEndDay.toString())]),te.success("TAT configuration saved successfully"),await o()}catch(u){console.error("Failed to save TAT configuration:",u),te.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(Z,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(X,{className:"p-12 text-center",children:[e.jsx(Xe,{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(Z,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ae,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(Ue,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-lg font-semibold text-gray-900",children:"Turn Around Time (TAT) Configuration"}),e.jsx(we,{className:"text-sm text-gray-600",children:"Set default TAT hours per priority level, working hours, and configure auto-escalation thresholds"})]})]})}),e.jsxs(X,{className:"space-y-6",children:[e.jsx(YA,{expressHours:n.expressHours,standardHours:n.standardHours,onExpressChange:d=>c({expressHours:d}),onStandardChange:d=>c({standardHours:d})}),e.jsx(Tt,{}),e.jsx(XA,{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(Tt,{}),e.jsx(ZA,{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(R,{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(Xe,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ha,{className:"w-4 h-4 mr-2"}),"Save TAT Settings"]})})})]})]})}function QA({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(ns,{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(ns,{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(ns,{checked:a,onCheckedChange:i})]})]})}function qA({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(Y,{htmlFor:"notification-frequency",children:"Notification Frequency"}),e.jsxs(_e,{value:t,onValueChange:a,children:[e.jsx(Oe,{id:"notification-frequency",children:e.jsx(Le,{placeholder:"Select frequency"})}),e.jsxs($e,{children:[e.jsx(H,{value:"Immediate",children:"Immediate"}),e.jsx(H,{value:"Hourly",children:"Hourly"}),e.jsx(H,{value:"Daily",children:"Daily"}),e.jsx(H,{value:"Weekly",children:"Weekly"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Y,{htmlFor:"reminder-frequency",children:"Reminder Frequency (hours)"}),e.jsx(je,{id:"reminder-frequency",type:"number",min:"1",max:"168",value:s,onChange:n=>r(parseInt(n.target.value)||12)})]})]})}function ek({emailTemplate:t,onEmailTemplateChange:s}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(Y,{htmlFor:"email-template",children:"Email Template Message"}),e.jsx(os,{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 tk(){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=()=>{te.success("Notification configuration saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(Z,{children:[e.jsxs(ae,{children:[e.jsx(ne,{children:"Notification Configuration"}),e.jsx(we,{children:"Configure notification channels, frequency, and message templates"})]}),e.jsxs(X,{className:"space-y-6",children:[e.jsx(QA,{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(Tt,{}),e.jsx(qA,{notificationFrequency:t.notificationFrequency,reminderFrequency:t.reminderFrequency,onNotificationFrequencyChange:n=>r({notificationFrequency:n}),onReminderFrequencyChange:n=>r({reminderFrequency:n})}),e.jsx(ek,{emailTemplate:t.emailTemplate,onEmailTemplateChange:n=>r({emailTemplate:n})}),e.jsxs(R,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(ha,{className:"w-4 h-4 mr-2"}),"Save Notification Settings"]})]})]})}function sk({maxFileSizeMB:t,retentionDays:s,onMaxFileSizeChange:a,onRetentionDaysChange:r}){const n=Math.round(s/365*10)/10;return e.jsxs(Z,{className:"border-0 shadow-sm",children:[e.jsxs(ae,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ps,{className:"w-5 h-5 text-re-green"}),e.jsx(ne,{className:"text-base font-semibold",children:"Upload & Retention Settings"})]}),e.jsx(we,{className:"text-sm",children:"Configure file size limits and document retention period"})]}),e.jsx(X,{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(Y,{htmlFor:"max-upload",className:"text-sm font-medium",children:"Maximum Upload Size (MB)"}),e.jsx(je,{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(ps,{className:"w-3 h-3"}),"Maximum allowed file size for document uploads"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Y,{htmlFor:"retention",className:"text-sm font-medium",children:"Retention Period (Days)"}),e.jsx(je,{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(wn,{className:"w-3 h-3"}),"Days to retain documents after workflow closure (",n," years)"]})]})]})})]})}const ak=[{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 rk({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(Z,{className:"border-0 shadow-sm",children:[e.jsxs(ae,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zd,{className:"w-5 h-5 text-re-green"}),e.jsx(ne,{className:"text-base font-semibold",children:"Allowed File Types"})]}),e.jsx(we,{className:"text-sm",children:"Select which file types are allowed for upload"})]}),e.jsxs(X,{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:ak.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(Y,{htmlFor:"file-types-manual",className:"text-sm font-medium",children:"File Extensions (comma-separated)"}),e.jsx(je,{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 nk(){const[t,s]=x.useState(!0),[a,r]=x.useState(!1),[n,i]=x.useState({maxFileSizeMB:10,retentionDays:365,allowedFileTypes:"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif"});x.useEffect(()=>{o()},[]);const o=async()=>{try{s(!0);const d=await Tn("DOCUMENT_POLICY"),m={};d.forEach(u=>{m[u.configKey]=u.configValue}),i({maxFileSizeMB:parseInt(m.MAX_FILE_SIZE_MB||"10"),retentionDays:parseInt(m.DOCUMENT_RETENTION_DAYS||"365"),allowedFileTypes:m.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif"})}catch(d){console.error("Failed to load document configurations:",d),te.error("Failed to load document configurations")}finally{s(!1)}},l=async()=>{var d,m;try{r(!0),await Promise.all([Bt("MAX_FILE_SIZE_MB",n.maxFileSizeMB.toString()),Bt("DOCUMENT_RETENTION_DAYS",n.retentionDays.toString()),Bt("ALLOWED_FILE_TYPES",n.allowedFileTypes)]),te.success("Document policy saved successfully"),await o()}catch(u){console.error("Failed to save document configuration:",u),te.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(Z,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(X,{className:"p-12 text-center",children:[e.jsx(Xe,{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(Z,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ae,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(Re,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-lg font-semibold text-gray-900",children:"Document Upload Policy"}),e.jsx(we,{className:"text-sm text-gray-600",children:"Configure file upload limits, allowed types, and retention policies"})]})]})}),e.jsxs(X,{className:"space-y-6",children:[e.jsx(sk,{maxFileSizeMB:n.maxFileSizeMB,retentionDays:n.retentionDays,onMaxFileSizeChange:d=>c({maxFileSizeMB:d}),onRetentionDaysChange:d=>c({retentionDays:d})}),e.jsx(Tt,{}),e.jsx(rk,{allowedFileTypes:n.allowedFileTypes,onAllowedFileTypesChange:d=>c({allowedFileTypes:d})}),e.jsx("div",{className:"flex justify-end pt-4",children:e.jsx(R,{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(Xe,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ha,{className:"w-4 h-4 mr-2"}),"Save Document Policy"]})})})]})]})}function ik(){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 ok=["Total Requests","Open Requests","Approved Requests","Rejected Requests","My Pending Actions","TAT Compliance","Delayed Workflows","Average Cycle Time"],lk=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 ck({role:t,kpis:s,onKPIToggle:a}){return e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"font-medium flex items-center gap-2",children:e.jsxs(ee,{className:lk(t),children:[t," Dashboard"]})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-2 ml-4",children:ok.map(r=>e.jsxs("div",{className:"flex items-center space-x-2 p-2 bg-muted/50 rounded",children:[e.jsx(wo,{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 dk(){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=()=>{te.success("Dashboard layout saved successfully")},r=(i,o,l)=>{s(c=>({...c,[i]:{...c[i],[o]:l}}))},n=["Initiator","Approver","Spectator"];return e.jsxs(Z,{children:[e.jsxs(ae,{children:[e.jsx(ne,{children:"Dashboard Layout Configuration"}),e.jsx(we,{children:"Control which KPI cards are visible for each user role"})]}),e.jsxs(X,{className:"space-y-4",children:[e.jsx(ik,{}),e.jsx("div",{className:"space-y-6",children:n.map(i=>e.jsx(ck,{role:i,kpis:t[i]||{},onKPIToggle:(o,l)=>r(i,o,l)},i))}),e.jsxs(R,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(ha,{className:"w-4 h-4 mr-2"}),"Save Dashboard Layout"]})]})]})}const mk=[{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 uk({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(Z,{className:"border-0 shadow-sm",children:[e.jsxs(ae,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(em,{className:"w-5 h-5 text-re-green"}),e.jsx(ne,{className:"text-base font-semibold",children:"AI Provider & API Keys"})]}),e.jsx(we,{className:"text-sm",children:"Select your AI provider and configure API keys"})]}),e.jsxs(X,{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(ns,{checked:t,onCheckedChange:o})]}),t&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Y,{htmlFor:"ai-provider",className:"text-sm font-medium",children:"AI Provider"}),e.jsxs(_e,{value:s,onValueChange:p=>l(p),children:[e.jsx(Oe,{id:"ai-provider",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Le,{placeholder:"Select AI provider"})}),e.jsx($e,{children:mk.map(p=>e.jsx(H,{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(Y,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(rg,{className:"w-4 h-4"}),"API Keys"]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Y,{htmlFor:"claude-key",className:"text-xs text-muted-foreground",children:"Claude API Key"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(je,{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(R,{type:"button",variant:"outline",size:"icon",onClick:()=>u("claude"),className:"border-gray-200",children:i.claude?e.jsx(Xr,{className:"w-4 h-4"}):e.jsx(zt,{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(Y,{htmlFor:"openai-key",className:"text-xs text-muted-foreground",children:"OpenAI API Key"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(je,{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(R,{type:"button",variant:"outline",size:"icon",onClick:()=>u("openai"),className:"border-gray-200",children:i.openai?e.jsx(Xr,{className:"w-4 h-4"}):e.jsx(zt,{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(Y,{htmlFor:"gemini-key",className:"text-xs text-muted-foreground",children:"Gemini API Key"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(je,{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(R,{type:"button",variant:"outline",size:"icon",onClick:()=>u("gemini"),className:"border-gray-200",children:i.gemini?e.jsx(Xr,{className:"w-4 h-4"}):e.jsx(zt,{className:"w-4 h-4"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Get your API key from ai.google.dev"})]})]})]})]})]})}function hk({aiRemarkGeneration:t,onRemarkGenerationChange:s}){return e.jsxs(Z,{className:"border-0 shadow-sm",children:[e.jsxs(ae,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jn,{className:"w-5 h-5 text-re-green"}),e.jsx(ne,{className:"text-base font-semibold",children:"AI Features"})]}),e.jsx(we,{className:"text-sm",children:"Enable/disable specific AI-powered features"})]}),e.jsx(X,{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(ns,{checked:t,onCheckedChange:s})]})})})]})}function pk({maxRemarkChars:t,onMaxRemarkCharsChange:s}){return e.jsxs(Z,{className:"border-0 shadow-sm",children:[e.jsxs(ae,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qd,{className:"w-5 h-5 text-re-green"}),e.jsx(ne,{className:"text-base font-semibold",children:"AI Parameters"})]}),e.jsx(we,{className:"text-sm",children:"Configure AI generation parameters"})]}),e.jsx(X,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(Y,{htmlFor:"max-remark-chars",className:"text-sm font-medium",children:"Maximum Remark Length"}),e.jsx(je,{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 xk(){const[t,s]=x.useState(!0),[a,r]=x.useState(!1),[n,i]=x.useState({claude:!1,openai:!1,gemini:!1}),[o,l]=x.useState({aiEnabled:!0,aiProvider:"claude",claudeApiKey:"",openaiApiKey:"",geminiApiKey:"",aiRemarkGeneration:!0,maxRemarkChars:500});x.useEffect(()=>{c()},[]);const c=async()=>{try{s(!0);const p=await Tn("AI_CONFIGURATION"),g={};p.forEach(y=>{g[y.configKey]=y.configValue}),l({aiEnabled:g.AI_ENABLED==="true",aiProvider:g.AI_PROVIDER||"claude",claudeApiKey:g.CLAUDE_API_KEY||"",openaiApiKey:g.OPENAI_API_KEY||"",geminiApiKey:g.GEMINI_API_KEY||"",aiRemarkGeneration:g.AI_REMARK_GENERATION_ENABLED==="true",maxRemarkChars:parseInt(g.AI_MAX_REMARK_LENGTH||"2000")})}catch(p){console.error("Failed to load AI configurations:",p),te.error("Failed to load AI configurations")}finally{s(!1)}},d=async()=>{var p,g;try{r(!0),await Promise.all([Bt("AI_ENABLED",o.aiEnabled.toString()),Bt("AI_PROVIDER",o.aiProvider),Bt("CLAUDE_API_KEY",o.claudeApiKey),Bt("OPENAI_API_KEY",o.openaiApiKey),Bt("GEMINI_API_KEY",o.geminiApiKey),Bt("AI_REMARK_GENERATION_ENABLED",o.aiRemarkGeneration.toString()),Bt("AI_MAX_REMARK_LENGTH",o.maxRemarkChars.toString())]),te.success("AI configuration saved successfully"),await c()}catch(y){console.error("Failed to save AI configuration:",y),te.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(Z,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(X,{className:"p-12 text-center",children:[e.jsx(Xe,{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(Z,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ae,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(jn,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-lg font-semibold text-gray-900",children:"AI Features Configuration"}),e.jsx(we,{className:"text-sm text-gray-600",children:"Configure AI provider, API keys, and enable/disable AI-powered features"})]})]})}),e.jsxs(X,{className:"space-y-6",children:[e.jsx(uk,{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(Tt,{}),e.jsx(hk,{aiRemarkGeneration:o.aiRemarkGeneration,onRemarkGenerationChange:p=>m({aiRemarkGeneration:p})}),e.jsx(Tt,{}),e.jsx(pk,{maxRemarkChars:o.maxRemarkChars,onMaxRemarkCharsChange:p=>m({maxRemarkChars:p})}),e.jsx("div",{className:"flex justify-end pt-4",children:e.jsx(R,{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(Xe,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ha,{className:"w-4 h-4 mr-2"}),"Save AI Configuration"]})})})]})]})}const bd=["Admin Only","Initiator Only","Approver Only","Initiator & Approver","Admin & Initiator","Admin & Approver","All Roles"];function gk({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(Y,{htmlFor:"spectator-permission",children:"Spectator Addition Permission"}),e.jsxs(_e,{value:t,onValueChange:a,children:[e.jsx(Oe,{id:"spectator-permission",children:e.jsx(Le,{placeholder:"Select permission"})}),e.jsx($e,{children:bd.map(n=>e.jsx(H,{value:n,children:n},n))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Y,{htmlFor:"link-sharing-permission",children:"Link Sharing Permission"}),e.jsxs(_e,{value:s,onValueChange:r,children:[e.jsx(Oe,{id:"link-sharing-permission",children:e.jsx(Le,{placeholder:"Select permission"})}),e.jsx($e,{children:bd.map(n=>e.jsx(H,{value:n,children:n},n))})]})]})]})}function fk({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(ns,{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(ns,{checked:s,onCheckedChange:r})]})]})}function yk(){const[t,s]=x.useState({spectatorPermission:"Initiator & Approver",linkSharingPermission:"Admin & Initiator",requirePassword:!0,allowExternalSharing:!1}),a=()=>{te.success("Sharing policy saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(Z,{children:[e.jsxs(ae,{children:[e.jsx(ne,{children:"Workflow Sharing Policy"}),e.jsx(we,{children:"Control who can add spectators and share workflow links"})]}),e.jsxs(X,{className:"space-y-6",children:[e.jsx(gk,{spectatorPermission:t.spectatorPermission,linkSharingPermission:t.linkSharingPermission,onSpectatorPermissionChange:n=>r({spectatorPermission:n}),onLinkSharingPermissionChange:n=>r({linkSharingPermission:n})}),e.jsx(Tt,{}),e.jsx(fk,{requirePassword:t.requirePassword,allowExternalSharing:t.allowExternalSharing,onRequirePasswordChange:n=>r({requirePassword:n}),onAllowExternalSharingChange:n=>r({allowExternalSharing:n})}),e.jsxs(R,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(ha,{className:"w-4 h-4 mr-2"}),"Save Sharing Policy"]})]})]})}function bk(){const{user:t}=ts(),[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(ss,{className:"w-8 h-8 text-re-green"}),"Admin Control Panel"]}),e.jsx("p",{className:"text-muted-foreground",children:"Manage users, configure system settings, and control portal behavior"})]}),e.jsxs(ee,{className:"bg-re-green/10 text-re-green border-re-green/20 px-4 py-2",children:[e.jsx(ss,{className:"w-4 h-4 mr-2"}),"Administrator: ",(t==null?void 0:t.displayName)||"Admin User"]})]}),e.jsx(Tt,{}),e.jsxs(An,{value:r,onValueChange:n,className:"flex flex-col gap-2 space-y-4",children:[e.jsxs(kn,{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(Et,{value:"kpi",className:"flex items-center gap-2",children:[e.jsx(Qd,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"KPI Config"})]}),e.jsxs(Et,{value:"analytics",className:"flex items-center gap-2",children:[e.jsx(Ys,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Analytics"})]}),e.jsxs(Et,{value:"users",className:"flex items-center gap-2",children:[e.jsx(Ct,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Users"})]}),e.jsxs(Et,{value:"tat",className:"flex items-center gap-2",children:[e.jsx(Ue,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"TAT"})]}),e.jsxs(Et,{value:"notifications",className:"flex items-center gap-2",children:[e.jsx(as,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Notify"})]}),e.jsxs(Et,{value:"documents",className:"flex items-center gap-2",children:[e.jsx(Re,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Docs"})]}),e.jsxs(Et,{value:"dashboard",className:"flex items-center gap-2",children:[e.jsx(ng,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Dashboard"})]}),e.jsxs(Et,{value:"ai",className:"flex items-center gap-2",children:[e.jsx(em,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"AI"})]}),e.jsxs(Et,{value:"sharing",className:"flex items-center gap-2",children:[e.jsx(Ya,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Sharing"})]})]}),e.jsx(It,{value:"kpi",className:"flex-1 outline-none space-y-4",children:e.jsxs(Z,{children:[e.jsx(ae,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"KPI Configuration"}),e.jsx(we,{children:"Configure which KPIs are enabled, visible to specific roles, and set alert thresholds"})]}),e.jsxs(ee,{className:"bg-blue-50 text-blue-700",children:[l," / ",l," KPIs Active"]})]})}),e.jsxs(X,{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(bs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(je,{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(qt,{className:"w-5 h-5 text-re-green"}),e.jsx("h3",{className:"font-semibold",children:d.name}),e.jsxs(ee,{variant:"outline",className:"ml-auto",children:[d.kpis.length," Active"]})]}),e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3",children:d.kpis.map(m=>e.jsx("div",{className:`p-4 border rounded-lg ${m.bgColor} ${m.borderColor} transition-all hover:shadow-md ${m.thresholdBreached?"ring-2 ring-orange-500":""}`,children:e.jsx("div",{className:"flex items-start justify-between gap-4",children:e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("h4",{className:"font-medium text-sm mb-1",children:m.title}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:m.description})]}),e.jsx(ee,{className:"bg-green-100 text-green-800 text-xs",children:"Active"})]}),e.jsxs("div",{className:"flex items-end gap-3 py-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"flex items-baseline gap-1",children:[e.jsx("span",{className:"text-4xl font-bold text-re-black",children:m.value}),m.unit&&e.jsx("span",{className:"text-lg text-muted-foreground",children:m.unit})]})}),m.change!==void 0&&e.jsxs("div",{className:`flex items-center gap-1 text-xs px-2 py-1 rounded ${m.changeType==="up"?"bg-green-100 text-green-700":"bg-red-100 text-red-700"}`,children:[m.changeType==="up"?e.jsx(ig,{className:"w-3 h-3"}):e.jsx(og,{className:"w-3 h-3"}),e.jsxs("span",{className:"font-semibold",children:[Math.abs(m.change),"%"]})]})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Visible:"}),m.visibleTo.map(u=>e.jsx(ee,{className:`${c(u)} text-xs px-1.5 py-0`,children:u},u))]}),e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:["Period: ",m.period]}),m.thresholdBreached&&e.jsxs("div",{className:"flex items-center gap-1 text-orange-600",children:[e.jsx(Pe,{className:"w-3 h-3"}),e.jsx("span",{className:"font-medium",children:"Threshold Breached!"})]})]})]})]})})},m.id))})]},d.name))]})]})}),e.jsx(It,{value:"analytics",className:"flex-1 outline-none space-y-4",children:e.jsx(BA,{})}),e.jsx(It,{value:"users",className:"flex-1 outline-none space-y-4",children:e.jsx(GA,{})}),e.jsx(It,{value:"tat",className:"flex-1 outline-none space-y-4",children:e.jsx(JA,{})}),e.jsx(It,{value:"notifications",className:"flex-1 outline-none space-y-4",children:e.jsx(tk,{})}),e.jsx(It,{value:"documents",className:"flex-1 outline-none space-y-4",children:e.jsx(nk,{})}),e.jsx(It,{value:"dashboard",className:"flex-1 outline-none space-y-4",children:e.jsx(dk,{})}),e.jsx(It,{value:"ai",className:"flex-1 outline-none space-y-4",children:e.jsx(xk,{})}),e.jsx(It,{value:"sharing",className:"flex-1 outline-none space-y-4",children:e.jsx(yk,{})})]})]})}function vk({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:Ce,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:ht,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(nt,{open:t,onOpenChange:u,children:e.jsxs(at,{className:"max-w-2xl bg-white",children:[e.jsxs(it,{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(rt,{className:"text-xl",children:p.title}),e.jsx(Ht,{className:"mt-1",children:p.description})]})]}),e.jsxs("div",{className:"space-y-3 p-4 bg-gray-50 rounded-lg border",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium text-gray-900",children:"Request ID:"}),e.jsx(ee,{variant:"outline",className:"font-mono",children:r})]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-gray-900",children:"Title:"}),e.jsx("p",{className:"text-gray-700 mt-1",children:n})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-gray-900",children:"Action:"}),e.jsxs(ee,{className:p.badgeColor,variant:"outline",children:[e.jsx(g,{className:"w-3 h-3 mr-1"}),a==="approve"?"APPROVE":"REJECT"]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Y,{htmlFor:"comment",className:"text-sm font-semibold text-gray-900",children:"Comments & Remarks *"}),e.jsx(os,{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(Cs,{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(Cs,{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(Ce,{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(yt,{className:"gap-2",children:[e.jsx(R,{variant:"outline",onClick:u,disabled:c,children:"Cancel"}),e.jsx(R,{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 jk=(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{}},Nk=x.createContext(void 0),wk={setTheme:t=>{},themes:[]},Ck=()=>{var t;return(t=x.useContext(Nk))!=null?t:wk};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:`(${jk.toString()})(${m})`}})});const Sk=({...t})=>{const{theme:s="system"}=Ck();return e.jsx(lg,{theme:s,className:"toaster group",style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)"},...t})};function Ak({onViewRequest:t}){const{user:s}=ts();return Cn(s)?e.jsx(OS,{onViewRequest:t}):e.jsx(BS,{onViewRequest:t})}function kk({onLogout:t}){const s=pa(),[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 N=(b==null?void 0:b.toLowerCase())==="draft"||b==="DRAFT";s(N?`/edit-request/${f}`:`/request/${f}`)},h=()=>{s(-1)},p=()=>{s("/new-request")},g=f=>{var N,A,D,T,P,w,S,M,B,_,$;if(f.templateType){f.templateType==="claim-management"&&s("/claim-management");return}const j=`RE-REQ-2024-${String(Object.keys(Tm).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:((N=f.approvers)==null?void 0:N.length)||1,currentApprover:((D=(A=f.approvers)==null?void 0:A[0])==null?void 0:D.name)||((w=(P=(T=f.approvers)==null?void 0:T[0])==null?void 0:P.email)==null?void 0:w.split("@")[0])||"Pending Assignment",approverLevel:`1 of ${((S=f.approvers)==null?void 0:S.length)||1}`,template:"custom",initiator:{name:"Current User",role:f.initiatorRole||"Employee",department:f.department||"General",email:"current.user@royalenfield.com",phone:"+91 98765 43290",avatar:"CU"},department:f.department||"General",createdAt:new Date().toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0}),updatedAt:new Date().toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0}),dueDate:new Date(Date.now()+5*24*60*60*1e3).toISOString(),submittedDate:new Date().toISOString(),estimatedCompletion:new Date(Date.now()+5*24*60*60*1e3).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),conclusionRemark:"",approvalFlow:(f.approvers||[]).filter(k=>k).map((k,I)=>{var O;const E=(k==null?void 0:k.name)||((O=k==null?void 0:k.email)==null?void 0:O.split("@")[0])||`Approver ${I+1}`,F=(k==null?void 0:k.email)||"";return{step:I+1,approver:`${E}${F?` (${F})`:""}`,role:(k==null?void 0:k.role)||`Level ${(k==null?void 0:k.level)||I+1} Approver`,status:I===0?"pending":"waiting",tatHours:k!=null&&k.tat?typeof k.tat=="string"?parseInt(k.tat):k.tat:48,elapsedHours:0,assignedAt:I===0?new Date().toISOString():null,comment:null,timestamp:null}}),documents:[],spectators:(f.spectators||[]).filter(k=>k&&(k.name||k.email)).map(k=>{var E;const I=(k==null?void 0:k.name)||((E=k==null?void 0:k.email)==null?void 0:E.split("@")[0])||"Observer";return{name:I,role:(k==null?void 0:k.role)||(k==null?void 0:k.department)||"Observer",avatar:I.split(" ").map(F=>F[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 ${((B=(M=f.approvers)==null?void 0:M[0])==null?void 0:B.name)||(($=(_=f.approvers)==null?void 0:_[0])==null?void 0:$.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"),te.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"?te.success("Request Approved",{description:"The request has been approved and forwarded to the next step.",duration:5e3}):te.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=async f=>{var j,b;try{const N={activityName:f.activityName,activityType:f.activityType,dealerCode:f.dealerCode,dealerName:f.dealerName,dealerEmail:f.dealerEmail||void 0,dealerPhone:f.dealerPhone||void 0,dealerAddress:f.dealerAddress||void 0,activityDate:f.activityDate?new Date(f.activityDate).toISOString():void 0,location:f.location,requestDescription:f.requestDescription,periodStartDate:f.periodStartDate?new Date(f.periodStartDate).toISOString():void 0,periodEndDate:f.periodEndDate?new Date(f.periodEndDate).toISOString():void 0,estimatedBudget:f.estimatedBudget||void 0},D=(await Ab(N)).request;te.success("Claim Request Submitted",{description:"Your claim management request has been created successfully."}),D!=null&&D.requestId?s(`/request/${D.requestId}`):s("/my-requests")}catch(N){console.error("[App] Error creating claim request:",N);const A=((b=(j=N==null?void 0:N.response)==null?void 0:j.data)==null?void 0:b.message)||(N==null?void 0:N.message)||"Failed to create claim request";te.error("Failed to Submit Claim Request",{description:A})}};return e.jsxs("div",{className:"min-h-screen h-screen flex flex-col overflow-hidden bg-background",children:[e.jsxs(ug,{children:[e.jsx(_t,{path:"/login/callback",element:e.jsx(pm,{})}),e.jsx(_t,{path:"/",element:e.jsx(Xt,{currentPage:"dashboard",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(Ll,{onNavigate:m,onNewRequest:p})})}),e.jsx(_t,{path:"/dashboard",element:e.jsx(Xt,{currentPage:"dashboard",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(Ll,{onNavigate:m,onNewRequest:p})})}),e.jsx(_t,{path:"/open-requests",element:e.jsx(Xt,{currentPage:"open-requests",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(dy,{onViewRequest:u})})}),e.jsx(_t,{path:"/closed-requests",element:e.jsx(Xt,{currentPage:"closed-requests",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(Ey,{onViewRequest:u})})}),e.jsx(_t,{path:"/shared-summaries",element:e.jsx(Xt,{currentPage:"shared-summaries",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(sv,{})})}),e.jsx(_t,{path:"/shared-summaries/:sharedSummaryId",element:e.jsx(Xt,{currentPage:"shared-summaries",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(av,{})})}),e.jsx(_t,{path:"/my-requests",element:e.jsx(Xt,{currentPage:"my-requests",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(pS,{onViewRequest:u,dynamicRequests:n})})}),e.jsx(_t,{path:"/requests",element:e.jsx(Xt,{currentPage:"requests",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(Ak,{onViewRequest:u})})}),e.jsx(_t,{path:"/approver-performance",element:e.jsx(Xt,{currentPage:"approver-performance",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(tA,{})})}),e.jsx(_t,{path:"/request/:requestId",element:e.jsx(Xt,{currentPage:"request-detail",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(tv,{requestId:"",onBack:h,dynamicRequests:n})})}),e.jsx(_t,{path:"/work-notes/:requestId",element:e.jsx(rv,{})}),e.jsx(_t,{path:"/new-request",element:e.jsx(md,{onBack:h,onSubmit:g})}),e.jsx(_t,{path:"/edit-request/:requestId",element:e.jsx(md,{onBack:h,onSubmit:g,requestId:void 0,isEditMode:!0})}),e.jsx(_t,{path:"/claim-management",element:e.jsx(J2,{onBack:h,onSubmit:C})}),e.jsx(_t,{path:"/profile",element:e.jsx(Xt,{currentPage:"profile",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(sA,{})})}),e.jsx(_t,{path:"/settings",element:e.jsx(Xt,{currentPage:"settings",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(xA,{})})}),e.jsx(_t,{path:"/notifications",element:e.jsx(Xt,{currentPage:"notifications",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(gA,{onNavigate:m})})}),e.jsx(_t,{path:"/detailed-reports",element:e.jsx(Xt,{currentPage:"detailed-reports",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(FA,{})})}),e.jsx(_t,{path:"/admin",element:e.jsx(Xt,{currentPage:"admin",onNavigate:m,onNewRequest:p,onLogout:t,children:e.jsx(bk,{})})})]}),e.jsx(Sk,{position:"top-right",toastOptions:{style:{background:"var(--card)",color:"var(--card-foreground)",border:"1px solid var(--border)"}}}),a&&e.jsx(vk,{isOpen:!!a,onClose:v,action:a,requestId:o,requestTitle:c,onSubmit:y})]})}function Tk(t){const{onLogout:s}=t||{};return e.jsx(mg,{children:e.jsx(kk,{onLogout:s})})}function Dk(){const{isAuthenticated:t,isLoading:s,error:a,user:r,logout:n}=ts(),[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(pm,{}):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(Tk,{onLogout:c}),i&&e.jsx(Ef,{isOpen:i,onClose:()=>o(!1)})]}):e.jsx(Rf,{})}const rn=()=>{try{return!0}catch{return!1}},Rk=()=>{if(rn())return null;try{return localStorage.getItem("token")}catch{return null}},Pk={user:null,token:Rk(),isAuthenticated:!1,isLoading:!1,error:null},Qh=Ja({name:"auth",initialState:Pk,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,!rn())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,!rn())try{localStorage.removeItem("token")}catch{}},logout:t=>{if(t.isAuthenticated=!1,t.user=null,t.token=null,t.error=null,!rn())try{localStorage.removeItem("token")}catch{}},clearError:t=>{t.error=null},updateUser:(t,s)=>{t.user=s.payload}}}),{loginStart:Vk,loginSuccess:zk,loginFailure:Hk,logout:Wk,clearError:Kk,updateUser:Gk}=Qh.actions,Ek=dg({reducer:{auth:Qh.reducer,dashboard:ym.reducer,requests:Uh.reducer,myRequests:_h.reducer,openRequests:vm.reducer,closedRequests:km.reducer},middleware:t=>t({serializableCheck:{ignoredActions:["persist/PERSIST"]}}),devTools:!1});Di.createRoot(document.getElementById("root")).render(e.jsx(lx.StrictMode,{children:e.jsx(Eg,{store:Ek,children:e.jsx(Xg,{children:e.jsx(Dk,{})})})}));export{ce as a};
|
||
//# sourceMappingURL=index-CogACwP9.js.map
|