76 lines
1.2 MiB
76 lines
1.2 MiB
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/conclusionApi-DFZpYv7A.js","assets/radix-vendor-DA0cB_hD.js","assets/charts-vendor-Cji9-Yri.js","assets/utils-vendor-DHm03ykU.js","assets/ui-vendor-DtH22-aU.js","assets/socket-vendor-TjCxX7sJ.js","assets/redux-vendor-tbZCm13o.js","assets/router-vendor-CRr9x_Jp.js","assets/requestNavigation-DVuzZmST.js"])))=>i.map(i=>d[i]);
|
||
var Ux=Object.defineProperty;var Vx=(t,s,a)=>s in t?Ux(t,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[s]=a;var ki=(t,s,a)=>Vx(t,typeof s!="symbol"?s+"":s,a);import{j as e,S as Jm,R as Qm,I as qm,F as eu,a as zx,T as Hx,P as Wx,C as Gx,b as Kx,O as tu,c as su,d as Yx,e as Zx,f as Xx,D as Jx,g as Qx,A as qx,h as eg,i as tg,k as sg,l as ag,m as rg,n as ng,V as ig,o as lg,p as og,q as cg,r as dg,s as mg,t as ug,u as hg,v as pg,w as xg,x as gg,y as fg,z as yg,B as bg,E as vg,G as jg,H as Ng,J as wg,K as Cg,L as Sg,M as Ag,N as Tg,Q as au,U as ru,W as kg,X as nu,Y as iu,Z as Dg,_ as Rg,$ as Pg,a0 as Ig,a1 as Eg,a2 as Mg,a3 as Fg,a4 as _g,a5 as Lg,a6 as Og,a7 as $g,a8 as Bg,a9 as Ug,aa as Vg,ab as zg}from"./radix-vendor-DA0cB_hD.js";import{a as Hg,r as x,c as lu,d as Kl,B as Wg,C as ou,X as cu,Y as du,T as Yl,L as mu,e as Di,P as Gg,f as Kg,g as Yg,h as Zg,i as Jc,j as ri,k as ni,b as Xg}from"./charts-vendor-Cji9-Yri.js";import{a as Zl,f as uu,b as Ie,d as Jg,c as Qg,e as qg,s as _s,g as Xl,h as Qc,i as ef,j as ca,k as ln,l as Jl,m as hu,n as ks,o as Is,p as Ri,q as ba,r as tf,t as gl,u as sf,v as fl,w as af,x as rf,y as nf,z as lf,A as Pi,B as qc,C as of,D as pu,E as xu,F as Ql,G as ql,H as cf,I as df,J as gu}from"./utils-vendor-DHm03ykU.js";import{L as mf,S as cs,C as We,a as Fs,b as Qe,X as pt,H as uf,c as fu,U as Pt,F as Le,d as Ce,e as vr,P as Ls,f as hf,g as pf,B as vs,h as Da,i as Ii,j as eo,k as yu,l as jr,m as xf,n as gn,o as mt,R as ns,I as Nr,T as Bt,p as Ze,q as ta,r as gf,A as rs,s as hs,M as Os,t as ii,u as ts,v as ff,D as Nt,Z as to,w as Mt,x as $s,y as bu,z as vu,E as on,G as xt,J as yf,K as bf,N as vf,O as jf,Q as Nf,V as wf,W as Cf,Y as Sf,_ as Af,$ as Tf,a0 as kf,a1 as Df,a2 as va,a3 as li,a4 as Ra,a5 as Yn,a6 as ed,a7 as Rn,a8 as Zn,a9 as ju,aa as Rf,ab as q,ac as da,ad as oi,ae as us,af as Pf,ag as bt,ah as If,ai as Ef,aj as Mf,ak as ci,al as Ys,am as Nu,an as Ff,ao as _f,ap as Rs,aq as Pa,ar as di,as as mi,at as Lf,au as Of,av as wu,aw as $f,ax as $n,ay as so,az as ui,aA as Cu,aB as Su,aC as Au,aD as ao,aE as Bf,aF as yl,aG as ro,aH as Tu,aI as Uf,aJ as hi,aK as pi,aL as no,aM as Vf,aN as ku,aO as td,aP as Fa,aQ as zf,aR as io,aS as Hf,aT as or,aU as Du,aV as sd,aW as Wf,aX as Gf,aY as Kf,aZ as Ru,a_ as Yf,a$ as Zf,b0 as Xf,b1 as Jf}from"./ui-vendor-DtH22-aU.js";import{l as Qf}from"./socket-vendor-TjCxX7sJ.js";import{c as wr,a as qf}from"./redux-vendor-tbZCm13o.js";import{u as ir,a as _a,b as Pu,B as e0,R as t0,c as Zt}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 l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&r(l)}).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 bl={},ad=Hg;bl.createRoot=ad.createRoot,bl.hydrateRoot=ad.hydrateRoot;var Iu={exports:{}},Eu={};/**
|
||
* @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 fn=x;function s0(t,s){return t===s&&(t!==0||1/t===1/s)||t!==t&&s!==s}var a0=typeof Object.is=="function"?Object.is:s0,r0=fn.useSyncExternalStore,n0=fn.useRef,i0=fn.useEffect,l0=fn.useMemo,o0=fn.useDebugValue;Eu.useSyncExternalStoreWithSelector=function(t,s,a,r,n){var i=n0(null);if(i.current===null){var l={hasValue:!1,value:null};i.current=l}else l=i.current;i=l0(function(){function c(g){if(!d){if(d=!0,m=g,g=r(g),n!==void 0&&l.hasValue){var p=l.value;if(n(p,g))return u=p}return u=g}if(p=u,a0(m,g))return p;var y=r(g);return n!==void 0&&n(p,y)?(m=g,p):(m=g,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 o=r0(t,i[0],i[1]);return i0(function(){l.hasValue=!0,l.value=o},[o]),o0(o),o};Iu.exports=Eu;var c0=Iu.exports;function d0(t){t()}function m0(){let t=null,s=null;return{clear(){t=null,s=null},notify(){d0(()=>{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 rd={notify(){},get:()=>[]};function u0(t,s){let a,r=rd,n=0,i=!1;function l(y){m();const b=r.subscribe(y);let j=!1;return()=>{j||(j=!0,b(),u())}}function o(){r.notify()}function c(){p.onStateChange&&p.onStateChange()}function d(){return i}function m(){n++,a||(a=t.subscribe(c),r=m0())}function u(){n--,a&&n===0&&(a(),a=void 0,r.clear(),r=rd)}function h(){i||(i=!0,m())}function g(){i&&(i=!1,u())}const p={addNestedSub:l,notifyNestedSubs:o,handleChangeWrapper:c,isSubscribed:d,trySubscribe:h,tryUnsubscribe:g,getListeners:()=>r};return p}var h0=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",p0=h0(),x0=()=>typeof navigator<"u"&&navigator.product==="ReactNative",g0=x0(),f0=()=>p0||g0?x.useLayoutEffect:x.useEffect,y0=f0(),Ei=Symbol.for("react-redux-context"),Mi=typeof globalThis<"u"?globalThis:{};function b0(){if(!x.createContext)return{};const t=Mi[Ei]??(Mi[Ei]=new Map);let s=t.get(x.createContext);return s||(s=x.createContext(null),t.set(x.createContext,s)),s}var Ia=b0();function v0(t){const{children:s,context:a,serverState:r,store:n}=t,i=x.useMemo(()=>{const c=u0(n);return{store:n,subscription:c,getServerState:r?()=>r:void 0}},[n,r]),l=x.useMemo(()=>n.getState(),[n]);y0(()=>{const{subscription:c}=i;return c.onStateChange=c.notifyNestedSubs,c.trySubscribe(),l!==n.getState()&&c.notifyNestedSubs(),()=>{c.tryUnsubscribe(),c.onStateChange=void 0}},[i,l]);const o=a||Ia;return x.createElement(o.Provider,{value:i},s)}var j0=v0;function lo(t=Ia){return function(){return x.useContext(t)}}var Mu=lo();function Fu(t=Ia){const s=t===Ia?Mu:lo(t),a=()=>{const{store:r}=s();return r};return Object.assign(a,{withTypes:()=>a}),a}var N0=Fu();function w0(t=Ia){const s=t===Ia?N0:Fu(t),a=()=>s().dispatch;return Object.assign(a,{withTypes:()=>a}),a}var C0=w0(),S0=(t,s)=>t===s;function A0(t=Ia){const s=t===Ia?Mu:lo(t),a=(r,n={})=>{const{equalityFn:i=S0}=typeof n=="function"?{equalityFn:n}:n,l=s(),{store:o,subscription:c,getServerState:d}=l;x.useRef(!0);const m=x.useCallback({[r.name](h){return r(h)}}[r.name],[r]),u=c0.useSyncExternalStoreWithSelector(c.addNestedSub,o.getState,d||o.getState,m,i);return x.useDebugValue(u),u};return Object.assign(a,{withTypes:()=>a}),a}var T0=A0(),vl=function(t,s){return vl=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])},vl(t,s)};function k0(t,s){if(typeof s!="function"&&s!==null)throw new TypeError("Class extends value "+String(s)+" is not a constructor or null");vl(t,s);function a(){this.constructor=t}t.prototype=s===null?Object.create(s):(a.prototype=s.prototype,new a)}var Xn=function(){return Xn=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},Xn.apply(this,arguments)};var Za=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function oo(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function co(t,s){return t(s={exports:{}},s.exports),s.exports}var Ga=co(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,l){var o=n.locked.get(i);o===void 0?l===void 0?n.locked.set(i,[]):n.locked.set(i,[l]):l!==void 0&&(o.unshift(l),n.locked.set(i,o))},this.isLocked=function(i){return n.locked.has(i)},this.lock=function(i){return new Promise(function(l,o){n.isLocked(i)?n.addToLocked(i,l):(n.addToLocked(i),l())})},this.unlock=function(i){var l=n.locked.get(i);if(l!==void 0&&l.length!==0){var o=l.pop();n.locked.set(i,l),o!==void 0&&setTimeout(o,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()}});oo(Ga);var D0=oo(co(function(t,s){var a=Za&&Za.__awaiter||function(m,u,h,g){return new(h||(h=Promise))(function(p,y){function b(w){try{v(g.next(w))}catch(N){y(N)}}function j(w){try{v(g.throw(w))}catch(N){y(N)}}function v(w){w.done?p(w.value):new h(function(N){N(w.value)}).then(b,j)}v((g=g.apply(m,u||[])).next())})},r=Za&&Za.__generator||function(m,u){var h,g,p,y,b={label:0,sent:function(){if(1&p[0])throw p[1];return p[1]},trys:[],ops:[]};return y={next:j(0),throw:j(1),return:j(2)},typeof Symbol=="function"&&(y[Symbol.iterator]=function(){return this}),y;function j(v){return function(w){return function(N){if(h)throw new TypeError("Generator is already executing.");for(;b;)try{if(h=1,g&&(p=2&N[0]?g.return:N[0]?g.throw||((p=g.return)&&p.call(g),0):g.next)&&!(p=p.call(g,N[1])).done)return p;switch(g=0,p&&(N=[2&N[0],p.value]),N[0]){case 0:case 1:p=N;break;case 4:return b.label++,{value:N[1],done:!1};case 5:b.label++,g=N[1],N=[0];continue;case 7:N=b.ops.pop(),b.trys.pop();continue;default:if(p=b.trys,!((p=p.length>0&&p[p.length-1])||N[0]!==6&&N[0]!==2)){b=0;continue}if(N[0]===3&&(!p||N[1]>p[0]&&N[1]<p[3])){b.label=N[1];break}if(N[0]===6&&b.label<p[1]){b.label=p[1],p=N;break}if(p&&b.label<p[2]){b.label=p[2],b.ops.push(N);break}p[2]&&b.ops.pop(),b.trys.pop();continue}N=u.call(m,b)}catch(C){N=[6,C],g=0}finally{h=p=0}if(5&N[0])throw N[1];return{value:N[0]?N[1]:void 0,done:!0}}([v,w])}}},n=Za;Object.defineProperty(s,"__esModule",{value:!0});var i="browser-tabs-lock-key",l={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 o(m){return new Promise(function(u){return setTimeout(u,m)})}function c(m){for(var u="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",h="",g=0;g<m;g++)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 g,p,y,b,j,v,w;return r(this,function(N){switch(N.label){case 0:g=Date.now()+c(4),p=Date.now()+h,y=i+"-"+u,b=this.storageHandler===void 0?l:this.storageHandler,N.label=1;case 1:return Date.now()<p?[4,o(30)]:[3,8];case 2:return N.sent(),b.getItemSync(y)!==null?[3,5]:(j=this.id+"-"+u+"-"+g,[4,o(Math.floor(25*Math.random()))]);case 3:return N.sent(),b.setItemSync(y,JSON.stringify({id:this.id,iat:g,timeoutKey:j,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,o(30)];case 4:return N.sent(),(v=b.getItemSync(y))!==null&&(w=JSON.parse(v)).id===this.id&&w.iat===g?(this.acquiredIatSet.add(g),this.refreshLockWhileAcquired(y,g),[2,!0]):[3,7];case 5:return m.lockCorrector(this.storageHandler===void 0?l:this.storageHandler),[4,this.waitForSomethingToChange(p)];case 6:N.sent(),N.label=7;case 7:return g=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 g=this;return r(this,function(p){return setTimeout(function(){return a(g,void 0,void 0,function(){var y,b,j;return r(this,function(v){switch(v.label){case 0:return[4,Ga.default().lock(h)];case 1:return v.sent(),this.acquiredIatSet.has(h)?(y=this.storageHandler===void 0?l:this.storageHandler,(b=y.getItemSync(u))===null?(Ga.default().unlock(h),[2]):((j=JSON.parse(b)).timeRefreshed=Date.now(),y.setItemSync(u,JSON.stringify(j)),Ga.default().unlock(h),this.refreshLockWhileAcquired(u,h),[2])):(Ga.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(g){var p=!1,y=Date.now(),b=!1;function j(){if(b||(window.removeEventListener("storage",j),m.removeFromWaiting(j),clearTimeout(v),b=!0),!p){p=!0;var w=50-(Date.now()-y);w>0?setTimeout(g,w):g(null)}}window.addEventListener("storage",j),m.addToWaiting(j);var v=setTimeout(j,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,g,p,y;return r(this,function(b){switch(b.label){case 0:return h=this.storageHandler===void 0?l:this.storageHandler,g=i+"-"+u,(p=h.getItemSync(g))===null?[2]:(y=JSON.parse(p)).id!==this.id?[3,2]:[4,Ga.default().lock(y.iat)];case 1:b.sent(),this.acquiredIatSet.delete(y.iat),h.removeItemSync(g),Ga.default().unlock(y.iat),m.notifyWaiters(),b.label=2;case 2:return[2]}})})},m.lockCorrector=function(u){for(var h=Date.now()-5e3,g=u,p=[],y=0;;){var b=g.keySync(y);if(b===null)break;p.push(b),y++}for(var j=!1,v=0;v<p.length;v++){var w=p[v];if(w.includes(i)){var N=g.getItemSync(w);if(N!==null){var C=JSON.parse(N);(C.timeRefreshed===void 0&&C.timeAcquired<h||C.timeRefreshed!==void 0&&C.timeRefreshed<h)&&(g.removeItemSync(w),j=!0)}}}j&&m.notifyWaiters()},m.waiters=void 0,m}();s.default=d}));new TextEncoder;new TextDecoder;var Ja=co(function(t,s){var a=Za&&Za.__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 g=m[h].split("="),p=g.slice(1).join("=");p.charAt(0)==='"'&&(p=p.slice(1,-1));try{d[g[0].replace(u,decodeURIComponent)]=p.replace(u,decodeURIComponent)}catch{}}return d}function l(){return i(document.cookie)}function o(c,d,m){document.cookie=n(c,d,a({path:"/"},m))}s.__esModule=!0,s.encode=n,s.parse=i,s.getAll=l,s.get=function(c){return l()[c]},s.set=o,s.remove=function(c,d){o(c,"",a(a({},d),{expires:-1}))}});oo(Ja),Ja.encode,Ja.parse,Ja.getAll;Ja.get;Ja.set;Ja.remove;var nd;(function(t){t.Code="code",t.ConnectCode="connect_code"})(nd||(nd={}));var id;(function(t){t.Bearer="Bearer",t.DPoP="DPoP"})(id||(id={}));new D0;var R0={isAuthenticated:!1,isLoading:!0,error:void 0,user:void 0},Ss=function(){throw new Error("You forgot to wrap your component in <Auth0Provider>.")},P0=Xn(Xn({},R0),{buildAuthorizeUrl:Ss,buildLogoutUrl:Ss,getAccessTokenSilently:Ss,getAccessTokenWithPopup:Ss,getIdTokenClaims:Ss,loginWithRedirect:Ss,loginWithPopup:Ss,connectAccountWithRedirect:Ss,logout:Ss,handleRedirectCallback:Ss,getDpopNonce:Ss,setDpopNonce:Ss,generateDpopProof:Ss,createFetcher:Ss}),I0=x.createContext(P0);(function(t){k0(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 E0=function(t){return t===void 0&&(t=I0),x.useContext(t)};const Fi="idToken",_i="userData",M0=()=>!0;class lt{static setAccessToken(s){}static getAccessToken(){return null}static setRefreshToken(s){}static getRefreshToken(){return null}static setIdToken(s){sessionStorage.setItem(Fi,s)}static getIdToken(){return sessionStorage.getItem(Fi)}static setUserData(s){localStorage.setItem(_i,JSON.stringify(s))}static getUserData(){const s=localStorage.getItem(_i);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(_i),sessionStorage.removeItem(Fi)}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 M0()}}function Li(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(),l=s*60*1e3;return n-i<l}catch{return!0}}const _u="https://re-workflow-nt-dev.siplsolutions.com/api/v1",ye=Zl.create({baseURL:_u,headers:{"Content-Type":"application/json"},withCredentials:!0});ye.interceptors.request.use(t=>t,t=>Promise.reject(t));ye.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=lt.getRefreshToken(),l=await Zl.post(`${_u}/auth/refresh`,n?{}:{refreshToken:i},{withCredentials:!0}),c=(l.data.data||l.data).accessToken;return ye(s)}catch(i){return lt.clearAll(),window.location.href="/",Promise.reject(i)}}return Promise.reject(t)});async function F0(t,s){var a,r;try{const n=await ye.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,l=i.data||i;return l.user&<.setUserData(l.user),l.idToken&<.setIdToken(l.idToken),l.accessToken&&l.refreshToken&&(lt.setAccessToken(l.accessToken),lt.setRefreshToken(l.refreshToken)),l}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 _0(){var r;const t={},a=(await ye.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 Xr(){const s=(await ye.get("/auth/me")).data;return s.data||s}async function L0(){var t,s;try{await ye.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 jl="https://ssodev.rebridge.co.in/realms/RE",Lu="REFLOW",mo=`${window.location.origin}/login/callback`;function O0(){const t=new URLSearchParams(window.location.search),s=t.has("logout")||t.has("tanflow_logged_out");s&&(sessionStorage.removeItem("tanflow_logged_out"),sessionStorage.removeItem("__logout_in_progress__"),sessionStorage.removeItem("__force_logout__"),console.log("🚪 Cleared logout flags before initiating Tanflow login"));const a=Math.random().toString(36).substring(7);sessionStorage.setItem("auth_provider","tanflow"),sessionStorage.setItem("tanflow_auth_state",a);let r=`${jl}/protocol/openid-connect/auth?client_id=${Lu}&response_type=code&scope=openid&redirect_uri=${encodeURIComponent(mo)}&state=${a}`;s&&(r+="&prompt=login",console.log("🚪 Adding prompt=login to force re-authentication after logout")),console.log("🚪 Initiating Tanflow login",{isAfterLogout:s,hasPrompt:s}),window.location.href=r}async function $0(t,s){var r,n,i;const a="https://re-workflow-nt-dev.siplsolutions.com/api/v1";try{const l=await Zl.post(`${a}/auth/tanflow/token-exchange`,{code:t,redirectUri:mo,state:s},{withCredentials:!0,headers:{"Content-Type":"application/json"}}),o=((r=l.data)==null?void 0:r.data)||l.data;return o.accessToken&<.setAccessToken(o.accessToken),o.refreshToken&<.setRefreshToken(o.refreshToken),o.idToken&<.setIdToken(o.idToken),o.user&<.setUserData(o.user),o}catch(l){throw console.error("❌ Tanflow token exchange failed:",{message:l.message,response:(n=l.response)==null?void 0:n.data,status:(i=l.response)==null?void 0:i.status}),l}}function B0(t){if(!t){console.warn("🚪 No id_token available for Tanflow logout, redirecting to home");const n=`${window.location.origin}/?tanflow_logged_out=true&logout=${Date.now()}`;window.location.replace(n);return}const s=mo,a=new URL(`${jl}/protocol/openid-connect/logout`);a.searchParams.set("client_id",Lu),a.searchParams.set("id_token_hint",t),a.searchParams.set("post_logout_redirect_uri",s);const r=a.toString();console.log("🚪 Tanflow logout initiated",{hasIdToken:!!t,idTokenPrefix:t?t.substring(0,20)+"...":"none",postLogoutRedirectUri:s,logoutUrlBase:`${jl}/protocol/openid-connect/logout`,finalLogoutUrl:r.replace(t.substring(0,20),"***")}),sessionStorage.setItem("__logout_in_progress__","true"),sessionStorage.setItem("__force_logout__","true"),console.log("🚪 Redirecting to Tanflow logout endpoint..."),window.location.href=r}const Ou=x.createContext(void 0);function U0({children:t}){const[s,a]=x.useState(!1),[r,n]=x.useState(!0),[i,l]=x.useState(null),[o,c]=x.useState(null),[d,m]=x.useState(!1);x.useEffect(()=>{const v=sessionStorage.getItem("__logout_in_progress__"),w=sessionStorage.getItem("__force_logout__");if(v==="true"||w==="true"){sessionStorage.removeItem("__logout_in_progress__"),sessionStorage.removeItem("__force_logout__"),lt.clearAll();try{localStorage.clear(),sessionStorage.clear()}catch(C){console.error("Error clearing storage:",C)}a(!1),l(null),n(!1),c(null);return}const N=new URLSearchParams(window.location.search);if(N.has("logout")||N.has("okta_logged_out")||N.has("tanflow_logged_out")){console.log("🚪 Logout parameter detected in URL, clearing all tokens"),lt.clearAll(),sessionStorage.removeItem("auth_provider"),sessionStorage.removeItem("tanflow_auth_state"),sessionStorage.removeItem("__logout_in_progress__"),sessionStorage.removeItem("__force_logout__"),sessionStorage.removeItem("tanflow_logged_out"),localStorage.clear(),a(!1),l(null),n(!1);const C=new URLSearchParams;N.has("okta_logged_out")&&C.set("okta_logged_out","true"),N.has("tanflow_logged_out")&&C.set("tanflow_logged_out","true");const S=C.toString()?`/?${C.toString()}`:"/";window.history.replaceState({},document.title,S);return}window.location.pathname==="/login/callback"||window.location.pathname==="/login/tanflow/callback"||(lt.getUserData(),d?n(!1):h())},[d]),x.useEffect(()=>{if(!s)return;const v=async()=>{try{await b()}catch(C){console.error("Silent refresh failed:",C)}},w=10*60*1e3,N=setInterval(v,w);return()=>clearInterval(N)},[s]);const u=x.useRef(!1);x.useEffect(()=>{if(u.current||window.location.pathname!=="/login/callback")return;(async()=>{const w=new URLSearchParams(window.location.search);if((w.has("logout")||w.has("tanflow_logged_out")||w.has("okta_logged_out"))&&!w.get("code")){console.log("🚪 Logout redirect detected in callback, redirecting to home");const E=new URLSearchParams;w.has("tanflow_logged_out")&&E.set("tanflow_logged_out","true"),w.has("okta_logged_out")&&E.set("okta_logged_out","true"),w.has("logout")&&E.set("logout",w.get("logout")||Date.now().toString());const P=E.toString()?`/?${E.toString()}`:"/?logout="+Date.now();window.location.replace(P);return}u.current=!0;const N=w.get("code"),C=w.get("error");if(window.history.replaceState({},document.title,"/login/callback"),sessionStorage.getItem("auth_provider")==="tanflow"){u.current=!1;return}if(C){c(new Error(`Authentication error: ${C}`)),n(!1),sessionStorage.removeItem("auth_provider");return}if(!N){n(!1),sessionStorage.removeItem("auth_provider");return}try{n(!0),a(!1),c(null);const E=`${window.location.origin}/login/callback`,P=await F0(N,E);l(P.user),a(!0),c(null),sessionStorage.removeItem("auth_provider"),window.history.replaceState({},document.title,"/")}catch(E){console.error("❌ Token exchange error in AuthContext:",E),c(E),a(!1),l(null),sessionStorage.removeItem("auth_provider"),u.current=!1}finally{n(!1)}})()},[]);const h=async()=>{var w;if(d){n(!1);return}const v=!0;try{if(n(!0),v){const S=lt.getUserData();try{const E=await Xr();l(E),lt.setUserData(E),a(!0)}catch(E){if(((w=E==null?void 0:E.response)==null?void 0:w.status)===401)try{await b();const P=await Xr();l(P),lt.setUserData(P),a(!0)}catch{lt.clearAll(),a(!1),l(null)}else E!=null&&E.isConnectionError?S?(l(S),a(!0)):(a(!1),l(null)):(lt.clearAll(),a(!1),l(null))}return}const N=lt.getAccessToken(),C=lt.getUserData();if(!N){a(!1),l(null),n(!1);return}if(Li(N))try{await b();const S=lt.getAccessToken();if(S&&!Li(S)){const E=lt.getUserData();if(E)l(E),a(!0);else try{const P=await Xr();l(P),lt.setUserData(P),a(!0)}catch{lt.clearAll(),a(!1),l(null)}}else lt.clearAll(),a(!1),l(null)}catch{lt.clearAll(),a(!1),l(null)}else if(C)l(C),a(!0);else try{const S=await Xr();l(S),lt.setUserData(S),a(!0)}catch{lt.clearAll(),a(!1),l(null)}}catch(N){console.error("Error checking auth status:",N),c(N),lt.clearAll(),a(!1),l(null)}finally{n(!1)}},g=async()=>{try{c(null);const v="https://royalenfield.okta.com",w="0oa18b98aari6I6eo2p8",N=`${window.location.origin}/login/callback`,C="code",S="openid profile email",E=Math.random().toString(36).substring(7);sessionStorage.setItem("auth_provider","okta");const P=new URLSearchParams(window.location.search),R=P.has("logout")||P.has("okta_logged_out")||P.has("tanflow_logged_out");let f=`${v}/oauth2/default/v1/authorize?client_id=${w}&redirect_uri=${encodeURIComponent(N)}&response_type=${C}&scope=${encodeURIComponent(S)}&state=${E}`;R&&(f+="&prompt=login"),window.location.href=f}catch(v){throw c(v),v}},p=async()=>{try{const v=lt.getIdToken(),w=sessionStorage.getItem("auth_provider")||(v&&v.includes("tanflow")?"tanflow":null)||"okta";sessionStorage.setItem("__logout_in_progress__","true"),sessionStorage.setItem("__force_logout__","true"),m(!0),a(!1),l(null),c(null),n(!0);try{await L0(),console.log("🚪 Backend logout API called successfully")}catch(P){console.error("🚪 Logout API error:",P),console.warn("🚪 Backend logout failed - httpOnly cookies may not be cleared")}const N=sessionStorage.getItem("__logout_in_progress__"),C=sessionStorage.getItem("__force_logout__"),S=sessionStorage.getItem("auth_provider");if(lt.clearAll(),N&&sessionStorage.setItem("__logout_in_progress__",N),C&&sessionStorage.setItem("__force_logout__",C),v&<.setIdToken(v),S&&sessionStorage.setItem("auth_provider",S),await new Promise(P=>setTimeout(P,100)),w==="tanflow"&&v){console.log("🚪 Initiating Tanflow logout...");try{B0(v);return}catch(P){console.error("🚪 Tanflow logout error:",P)}}console.log("🚪 Using OKTA logout flow or fallback"),sessionStorage.removeItem("auth_provider"),v&<.clearAll();const E=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(E)}catch(v){console.error("🚪 Logout error:",v);try{localStorage.clear(),sessionStorage.clear(),sessionStorage.setItem("__logout_in_progress__","true");const w=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(w)}catch{window.location.replace("/?logout="+Date.now())}}},y=async()=>{{if(s)return"cookie-based-auth";try{return await b(),s?"cookie-based-auth":null}catch{return null}}const v=lt.getAccessToken();if(v&&!Li(v))return v;try{return await b(),lt.getAccessToken()}catch{return null}},b=async()=>{try{const w=await _0();return}catch(w){throw lt.clearAll(),a(!1),l(null),w}},j={isAuthenticated:s,isLoading:r,user:i,error:o,login:g,logout:p,getAccessTokenSilently:y,refreshTokenSilently:b};return e.jsx(Ou.Provider,{value:j,children:t})}function V0({children:t}){return e.jsx(U0,{children:t})}function Kt(){const t=x.useContext(Ou);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t}function Ka(t){return(t==null?void 0:t.role)==="ADMIN"}function Wr(t){return(t==null?void 0:t.role)==="MANAGEMENT"}function xi(t){return(t==null?void 0:t.role)==="MANAGEMENT"||(t==null?void 0:t.role)==="ADMIN"}const ld=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,od=lu,$u=(t,s)=>a=>{var r;if((s==null?void 0:s.variants)==null)return od(t,a==null?void 0:a.class,a==null?void 0:a.className);const{variants:n,defaultVariants:i}=s,l=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=ld(m)||ld(u);return n[d][h]}),o=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,...g}=m;return Object.entries(g).every(p=>{let[y,b]=p;return Array.isArray(b)?b.includes({...i,...o}[y]):{...i,...o}[y]===b})?[...d,u,h]:d},[]);return od(t,l,c,a==null?void 0:a.class,a==null?void 0:a.className)},uo="-",z0=t=>{const s=W0(t),{conflictingClassGroups:a,conflictingClassGroupModifiers:r}=t;return{getClassGroupId:l=>{const o=l.split(uo);return o[0]===""&&o.length!==1&&o.shift(),Bu(o,s)||H0(l)},getConflictingClassGroupIds:(l,o)=>{const c=a[l]||[];return o&&r[l]?[...c,...r[l]]:c}}},Bu=(t,s)=>{var l;if(t.length===0)return s.classGroupId;const a=t[0],r=s.nextPart.get(a),n=r?Bu(t.slice(1),r):void 0;if(n)return n;if(s.validators.length===0)return;const i=t.join(uo);return(l=s.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},cd=/^\[(.+)\]$/,H0=t=>{if(cd.test(t)){const s=cd.exec(t)[1],a=s==null?void 0:s.substring(0,s.indexOf(":"));if(a)return"arbitrary.."+a}},W0=t=>{const{theme:s,prefix:a}=t,r={nextPart:new Map,validators:[]};return K0(Object.entries(t.classGroups),a).forEach(([i,l])=>{Nl(l,r,i,s)}),r},Nl=(t,s,a,r)=>{t.forEach(n=>{if(typeof n=="string"){const i=n===""?s:dd(s,n);i.classGroupId=a;return}if(typeof n=="function"){if(G0(n)){Nl(n(r),s,a,r);return}s.validators.push({validator:n,classGroupId:a});return}Object.entries(n).forEach(([i,l])=>{Nl(l,dd(s,i),a,r)})})},dd=(t,s)=>{let a=t;return s.split(uo).forEach(r=>{a.nextPart.has(r)||a.nextPart.set(r,{nextPart:new Map,validators:[]}),a=a.nextPart.get(r)}),a},G0=t=>t.isThemeGetter,K0=(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(([l,o])=>[s+l,o])):i);return[a,n]}):t,Y0=t=>{if(t<1)return{get:()=>{},set:()=>{}};let s=0,a=new Map,r=new Map;const n=(i,l)=>{a.set(i,l),s++,s>t&&(s=0,r=a,a=new Map)};return{get(i){let l=a.get(i);if(l!==void 0)return l;if((l=r.get(i))!==void 0)return n(i,l),l},set(i,l){a.has(i)?a.set(i,l):n(i,l)}}},Uu="!",Z0=t=>{const{separator:s,experimentalParseClassName:a}=t,r=s.length===1,n=s[0],i=s.length,l=o=>{const c=[];let d=0,m=0,u;for(let b=0;b<o.length;b++){let j=o[b];if(d===0){if(j===n&&(r||o.slice(b,b+i)===s)){c.push(o.slice(m,b)),m=b+i;continue}if(j==="/"){u=b;continue}}j==="["?d++:j==="]"&&d--}const h=c.length===0?o:o.substring(m),g=h.startsWith(Uu),p=g?h.substring(1):h,y=u&&u>m?u-m:void 0;return{modifiers:c,hasImportantModifier:g,baseClassName:p,maybePostfixModifierPosition:y}};return a?o=>a({className:o,parseClassName:l}):l},X0=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},J0=t=>({cache:Y0(t.cacheSize),parseClassName:Z0(t),...z0(t)}),Q0=/\s+/,q0=(t,s)=>{const{parseClassName:a,getClassGroupId:r,getConflictingClassGroupIds:n}=s,i=[],l=t.trim().split(Q0);let o="";for(let c=l.length-1;c>=0;c-=1){const d=l[c],{modifiers:m,hasImportantModifier:u,baseClassName:h,maybePostfixModifierPosition:g}=a(d);let p=!!g,y=r(p?h.substring(0,g):h);if(!y){if(!p){o=d+(o.length>0?" "+o:o);continue}if(y=r(h),!y){o=d+(o.length>0?" "+o:o);continue}p=!1}const b=X0(m).join(":"),j=u?b+Uu:b,v=j+y;if(i.includes(v))continue;i.push(v);const w=n(y,p);for(let N=0;N<w.length;++N){const C=w[N];i.push(j+C)}o=d+(o.length>0?" "+o:o)}return o};function ey(){let t=0,s,a,r="";for(;t<arguments.length;)(s=arguments[t++])&&(a=Vu(s))&&(r&&(r+=" "),r+=a);return r}const Vu=t=>{if(typeof t=="string")return t;let s,a="";for(let r=0;r<t.length;r++)t[r]&&(s=Vu(t[r]))&&(a&&(a+=" "),a+=s);return a};function ty(t,...s){let a,r,n,i=l;function l(c){const d=s.reduce((m,u)=>u(m),t());return a=J0(d),r=a.cache.get,n=a.cache.set,i=o,o(c)}function o(c){const d=r(c);if(d)return d;const m=q0(c,a);return n(c,m),m}return function(){return i(ey.apply(null,arguments))}}const Rt=t=>{const s=a=>a[t]||[];return s.isThemeGetter=!0,s},zu=/^\[(?:([a-z-]+):)?(.+)\]$/i,sy=/^\d+\/\d+$/,ay=new Set(["px","full","screen"]),ry=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,ny=/\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$/,iy=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,ly=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,oy=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,ga=t=>pr(t)||ay.has(t)||sy.test(t),Sa=t=>Cr(t,"length",gy),pr=t=>!!t&&!Number.isNaN(Number(t)),Oi=t=>Cr(t,"number",pr),Gr=t=>!!t&&Number.isInteger(Number(t)),cy=t=>t.endsWith("%")&&pr(t.slice(0,-1)),tt=t=>zu.test(t),Aa=t=>ry.test(t),dy=new Set(["length","size","percentage"]),my=t=>Cr(t,dy,Hu),uy=t=>Cr(t,"position",Hu),hy=new Set(["image","url"]),py=t=>Cr(t,hy,yy),xy=t=>Cr(t,"",fy),Kr=()=>!0,Cr=(t,s,a)=>{const r=zu.exec(t);return r?r[1]?typeof s=="string"?r[1]===s:s.has(r[1]):a(r[2]):!1},gy=t=>ny.test(t)&&!iy.test(t),Hu=()=>!1,fy=t=>ly.test(t),yy=t=>oy.test(t),by=()=>{const t=Rt("colors"),s=Rt("spacing"),a=Rt("blur"),r=Rt("brightness"),n=Rt("borderColor"),i=Rt("borderRadius"),l=Rt("borderSpacing"),o=Rt("borderWidth"),c=Rt("contrast"),d=Rt("grayscale"),m=Rt("hueRotate"),u=Rt("invert"),h=Rt("gap"),g=Rt("gradientColorStops"),p=Rt("gradientColorStopPositions"),y=Rt("inset"),b=Rt("margin"),j=Rt("opacity"),v=Rt("padding"),w=Rt("saturate"),N=Rt("scale"),C=Rt("sepia"),S=Rt("skew"),E=Rt("space"),P=Rt("translate"),R=()=>["auto","contain","none"],f=()=>["auto","hidden","clip","visible","scroll"],T=()=>["auto",tt,s],F=()=>[tt,s],K=()=>["",ga,Sa],B=()=>["auto",pr,tt],U=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],D=()=>["solid","dashed","dotted","double","none"],A=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],k=()=>["start","end","center","between","around","evenly","stretch"],M=()=>["","0",tt],O=()=>["auto","avoid","all","avoid-page","page","left","right","column"],L=()=>[pr,tt];return{cacheSize:500,separator:":",theme:{colors:[Kr],spacing:[ga,Sa],blur:["none","",Aa,tt],brightness:L(),borderColor:[t],borderRadius:["none","","full",Aa,tt],borderSpacing:F(),borderWidth:K(),contrast:L(),grayscale:M(),hueRotate:L(),invert:M(),gap:F(),gradientColorStops:[t],gradientColorStopPositions:[cy,Sa],inset:T(),margin:T(),opacity:L(),padding:F(),saturate:L(),scale:L(),sepia:M(),skew:L(),space:F(),translate:F()},classGroups:{aspect:[{aspect:["auto","square","video",tt]}],container:["container"],columns:[{columns:[Aa]}],"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:[...U(),tt]}],overflow:[{overflow:f()}],"overflow-x":[{"overflow-x":f()}],"overflow-y":[{"overflow-y":f()}],overscroll:[{overscroll:R()}],"overscroll-x":[{"overscroll-x":R()}],"overscroll-y":[{"overscroll-y":R()}],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",Gr,tt]}],basis:[{basis:T()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",tt]}],grow:[{grow:M()}],shrink:[{shrink:M()}],order:[{order:["first","last","none",Gr,tt]}],"grid-cols":[{"grid-cols":[Kr]}],"col-start-end":[{col:["auto",{span:["full",Gr,tt]},tt]}],"col-start":[{"col-start":B()}],"col-end":[{"col-end":B()}],"grid-rows":[{"grid-rows":[Kr]}],"row-start-end":[{row:["auto",{span:[Gr,tt]},tt]}],"row-start":[{"row-start":B()}],"row-end":[{"row-end":B()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",tt]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",tt]}],gap:[{gap:[h]}],"gap-x":[{"gap-x":[h]}],"gap-y":[{"gap-y":[h]}],"justify-content":[{justify:["normal",...k()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...k(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...k(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[v]}],px:[{px:[v]}],py:[{py:[v]}],ps:[{ps:[v]}],pe:[{pe:[v]}],pt:[{pt:[v]}],pr:[{pr:[v]}],pb:[{pb:[v]}],pl:[{pl:[v]}],m:[{m:[b]}],mx:[{mx:[b]}],my:[{my:[b]}],ms:[{ms:[b]}],me:[{me:[b]}],mt:[{mt:[b]}],mr:[{mr:[b]}],mb:[{mb:[b]}],ml:[{ml:[b]}],"space-x":[{"space-x":[E]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[E]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",tt,s]}],"min-w":[{"min-w":[tt,s,"min","max","fit"]}],"max-w":[{"max-w":[tt,s,"none","full","min","max","fit","prose",{screen:[Aa]},Aa]}],h:[{h:[tt,s,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[tt,s,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[tt,s,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[tt,s,"auto","min","max","fit"]}],"font-size":[{text:["base",Aa,Sa]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Oi]}],"font-family":[{font:[Kr]}],"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",tt]}],"line-clamp":[{"line-clamp":["none",pr,Oi]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",ga,tt]}],"list-image":[{"list-image":["none",tt]}],"list-style-type":[{list:["none","disc","decimal",tt]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[t]}],"placeholder-opacity":[{"placeholder-opacity":[j]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[t]}],"text-opacity":[{"text-opacity":[j]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...D(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",ga,Sa]}],"underline-offset":[{"underline-offset":["auto",ga,tt]}],"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:F()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",tt]}],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",tt]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[j]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...U(),uy]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",my]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},py]}],"bg-color":[{bg:[t]}],"gradient-from-pos":[{from:[p]}],"gradient-via-pos":[{via:[p]}],"gradient-to-pos":[{to:[p]}],"gradient-from":[{from:[g]}],"gradient-via":[{via:[g]}],"gradient-to":[{to:[g]}],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:[o]}],"border-w-x":[{"border-x":[o]}],"border-w-y":[{"border-y":[o]}],"border-w-s":[{"border-s":[o]}],"border-w-e":[{"border-e":[o]}],"border-w-t":[{"border-t":[o]}],"border-w-r":[{"border-r":[o]}],"border-w-b":[{"border-b":[o]}],"border-w-l":[{"border-l":[o]}],"border-opacity":[{"border-opacity":[j]}],"border-style":[{border:[...D(),"hidden"]}],"divide-x":[{"divide-x":[o]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[o]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[j]}],"divide-style":[{divide:D()}],"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:["",...D()]}],"outline-offset":[{"outline-offset":[ga,tt]}],"outline-w":[{outline:[ga,Sa]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:K()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[j]}],"ring-offset-w":[{"ring-offset":[ga,Sa]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",Aa,xy]}],"shadow-color":[{shadow:[Kr]}],opacity:[{opacity:[j]}],"mix-blend":[{"mix-blend":[...A(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":A()}],filter:[{filter:["","none"]}],blur:[{blur:[a]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",Aa,tt]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[m]}],invert:[{invert:[u]}],saturate:[{saturate:[w]}],sepia:[{sepia:[C]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[a]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[m]}],"backdrop-invert":[{"backdrop-invert":[u]}],"backdrop-opacity":[{"backdrop-opacity":[j]}],"backdrop-saturate":[{"backdrop-saturate":[w]}],"backdrop-sepia":[{"backdrop-sepia":[C]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[l]}],"border-spacing-x":[{"border-spacing-x":[l]}],"border-spacing-y":[{"border-spacing-y":[l]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",tt]}],duration:[{duration:L()}],ease:[{ease:["linear","in","out","in-out",tt]}],delay:[{delay:L()}],animate:[{animate:["none","spin","ping","pulse","bounce",tt]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[N]}],"scale-x":[{"scale-x":[N]}],"scale-y":[{"scale-y":[N]}],rotate:[{rotate:[Gr,tt]}],"translate-x":[{"translate-x":[P]}],"translate-y":[{"translate-y":[P]}],"skew-x":[{"skew-x":[S]}],"skew-y":[{"skew-y":[S]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",tt]}],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",tt]}],"caret-color":[{caret:[t]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":F()}],"scroll-mx":[{"scroll-mx":F()}],"scroll-my":[{"scroll-my":F()}],"scroll-ms":[{"scroll-ms":F()}],"scroll-me":[{"scroll-me":F()}],"scroll-mt":[{"scroll-mt":F()}],"scroll-mr":[{"scroll-mr":F()}],"scroll-mb":[{"scroll-mb":F()}],"scroll-ml":[{"scroll-ml":F()}],"scroll-p":[{"scroll-p":F()}],"scroll-px":[{"scroll-px":F()}],"scroll-py":[{"scroll-py":F()}],"scroll-ps":[{"scroll-ps":F()}],"scroll-pe":[{"scroll-pe":F()}],"scroll-pt":[{"scroll-pt":F()}],"scroll-pr":[{"scroll-pr":F()}],"scroll-pb":[{"scroll-pb":F()}],"scroll-pl":[{"scroll-pl":F()}],"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",tt]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[ga,Sa,Oi]}],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"]}}},vy=ty(by);function we(...t){return vy(lu(t))}const cn=$u("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"}}),I=x.forwardRef(({className:t,variant:s,size:a,asChild:r=!1,...n},i)=>{const l=r?Jm:"button";return e.jsx(l,{"data-slot":"button",className:we(cn({variant:s,size:a,className:t})),ref:i,...n})});I.displayName="Button";function te({className:t,...s}){return e.jsx("div",{"data-slot":"card",className:we("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border",t),...s})}function me({className:t,...s}){return e.jsx("div",{"data-slot":"card-header",className:we("@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 he({className:t,...s}){return e.jsx("h4",{"data-slot":"card-title",className:we("leading-none",t),...s})}function De({className:t,...s}){return e.jsx("p",{"data-slot":"card-description",className:we("text-muted-foreground",t),...s})}function se({className:t,...s}){return e.jsx("div",{"data-slot":"card-content",className:we("px-6 [&:last-child]:pb-6",t),...s})}const gi="/assets/Re_Logo-By51taPS.png";function jy(){const{login:t,isLoading:s,error:a}=Kt(),[r,n]=x.useState(!1),i=async()=>{localStorage.clear(),sessionStorage.clear();try{await t()}catch(o){console.error("========================================"),console.error("OKTA LOGIN ERROR"),console.error("Error details:",o),console.error("Error message:",o==null?void 0:o.message),console.error("Error stack:",o==null?void 0:o.stack),console.error("========================================")}},l=()=>{localStorage.clear(),sessionStorage.clear(),n(!0);try{O0()}catch(o){console.error("========================================"),console.error("TANFLOW LOGIN ERROR"),console.error("Error details:",o),n(!1)}};return a&&console.error("Auth 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(te,{className:"w-full max-w-md shadow-xl",children:[e.jsx(me,{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:gi,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(se,{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.jsxs("div",{className:"space-y-3",children:[e.jsx(I,{onClick:i,disabled:s||r,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(mf,{className:"mr-2 h-5 w-5"}),"Login with OKTA"]})}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t border-gray-300"})}),e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"bg-white px-2 text-gray-500",children:"Or"})})]}),e.jsx(I,{onClick:l,disabled:s||r,className:"w-full h-12 text-base font-semibold bg-indigo-600 hover:bg-indigo-700 text-white",size:"lg",children:r?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"}),"Redirecting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(cs,{className:"mr-2 h-5 w-5"}),"Login with Tanflow"]})})]}),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:"Choose your authentication provider"})]})]})]})})}function Wu(){const{isAuthenticated:t,isLoading:s,error:a,user:r}=Kt(),[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 l=()=>{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:gi,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(We,{className:"w-16 h-16 text-red-500"})}),e.jsx(We,{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(Fs,{className:"w-16 h-16 text-green-500"})}),e.jsx(Fs,{className:"w-16 h-16 text-green-500 relative"})]}):e.jsxs("div",{className:"relative",children:[e.jsx(Qe,{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:l()})]}),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"})]})]})}function Ny(){const{isAuthenticated:t,isLoading:s,error:a,user:r}=Kt(),[n,i]=x.useState("exchanging"),[l,o]=x.useState(""),c=x.useRef(!1);x.useEffect(()=>{if(a){i("error");return}if(s){const u=new URLSearchParams(window.location.search).get("code");i(u&&!r?"exchanging":r&&!t?"fetching":"exchanging")}else r&&t&&(i("complete"),setTimeout(()=>{window.location.href="/"},1e3))},[t,s,a,r]),x.useEffect(()=>{if(c.current||window.location.pathname!=="/login/callback")return;const m=new URLSearchParams(window.location.search),u=m.get("code"),h=m.get("error");if(!u&&!h){console.log("🚪 Logout redirect detected: no code, no error - redirecting to home immediately"),c.current=!0;const y=new URLSearchParams;y.set("tanflow_logged_out","true"),y.set("logout",Date.now().toString());const b=`/?${y.toString()}`;console.log("🚪 Redirecting to:",b),window.location.replace(b);return}if(sessionStorage.getItem("auth_provider")!=="tanflow")return;(async()=>{c.current=!0;const y=new URLSearchParams(window.location.search),b=y.get("code"),j=y.get("state"),v=y.get("error");if(window.history.replaceState({},document.title,"/login/callback"),v){i("error"),sessionStorage.removeItem("auth_provider"),sessionStorage.removeItem("tanflow_auth_state");return}const w=sessionStorage.getItem("tanflow_auth_state");if(j&&j!==w){i("error"),sessionStorage.removeItem("auth_provider"),sessionStorage.removeItem("tanflow_auth_state");return}if(!b){i("error"),sessionStorage.removeItem("auth_provider"),sessionStorage.removeItem("tanflow_auth_state");return}try{i("exchanging");const N=await $0(b,j||"");sessionStorage.removeItem("tanflow_auth_state"),i("fetching");const C=N.user||await Xr();if(C)lt.setUserData(C),i("complete"),setTimeout(()=>{window.history.replaceState({},document.title,"/"),window.location.href="/"},1e3);else throw new Error("User data not received")}catch(N){console.error("Tanflow callback error:",N),i("error"),o(N.message||"Authentication failed"),sessionStorage.removeItem("auth_provider"),sessionStorage.removeItem("tanflow_auth_state")}})()},[]);const d=()=>{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:gi,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(We,{className:"w-16 h-16 text-red-500"})}),e.jsx(We,{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(Fs,{className:"w-16 h-16 text-green-500"})}),e.jsx(Fs,{className:"w-16 h-16 text-green-500 relative"})]}):e.jsxs("div",{className:"relative",children:[e.jsx(Qe,{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:d()})]}),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"&&l&&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:l}),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 wy=$u("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 ie({className:t,variant:s,asChild:a=!1,...r}){const n=a?Jm:"span";return e.jsx(n,{"data-slot":"badge",className:we(wy({variant:s}),t),...r})}function Cy({isOpen:t,onClose:s}){const{user:a,isAuthenticated:r,isLoading:n,error:i}=E0();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(te,{className:"w-full max-w-2xl max-h-[90vh] overflow-auto",children:[e.jsx(me,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{children:"Authentication Debug Information"}),e.jsx(I,{variant:"ghost",size:"icon",onClick:s,children:e.jsx(pt,{className:"h-4 w-4"})})]})}),e.jsxs(se,{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(ie,{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 Sy="modulepreload",Ay=function(t){return"/"+t},md={},Bn=function(s,a,r){let n=Promise.resolve();if(a&&a.length>0){document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),o=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));n=Promise.allSettled(a.map(c=>{if(c=Ay(c),c in md)return;md[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":Sy,d||(u.as="script"),u.crossOrigin="",u.href=c,o&&u.setAttribute("nonce",o),document.head.appendChild(u),d)return new Promise((h,g)=>{u.addEventListener("load",h),u.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${c}`)))})}))}function i(l){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=l,window.dispatchEvent(o),!o.defaultPrevented)throw l}return n.then(l=>{for(const o of l||[])o.status==="rejected"&&i(o.reason);return s().catch(i)})},Qt=x.forwardRef(({className:t,...s},a)=>e.jsx(Qm,{ref:a,"data-slot":"avatar",className:we("relative flex size-10 shrink-0 overflow-hidden rounded-full",t),...s}));Qt.displayName=Qm.displayName;const fi=x.forwardRef(({className:t,...s},a)=>e.jsx(qm,{ref:a,"data-slot":"avatar-image",className:we("aspect-square size-full",t),...s}));fi.displayName=qm.displayName;const qt=x.forwardRef(({className:t,...s},a)=>e.jsx(eu,{ref:a,"data-slot":"avatar-fallback",className:we("bg-muted flex size-full items-center justify-center rounded-full",t),...s}));qt.displayName=eu.displayName;function ud({...t}){return e.jsx(zx,{"data-slot":"dropdown-menu",...t})}function hd({...t}){return e.jsx(Hx,{"data-slot":"dropdown-menu-trigger",...t})}function pd({className:t,sideOffset:s=4,...a}){return e.jsx(Wx,{children:e.jsx(Gx,{"data-slot":"dropdown-menu-content",sideOffset:s,className:we("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 $i({className:t,inset:s,variant:a="default",...r}){return e.jsx(Kx,{"data-slot":"dropdown-menu-item","data-inset":s,"data-variant":a,className:we("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 Ty({...t}){return e.jsx(Zx,{"data-slot":"alert-dialog",...t})}function ky({...t}){return e.jsx(Yx,{"data-slot":"alert-dialog-portal",...t})}const Gu=x.forwardRef(({className:t,...s},a)=>e.jsx(tu,{"data-slot":"alert-dialog-overlay",className:we("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}));Gu.displayName=tu.displayName;const Ku=x.forwardRef(({className:t,...s},a)=>e.jsxs(ky,{children:[e.jsx(Gu,{}),e.jsx(su,{"data-slot":"alert-dialog-content",ref:a,className:we("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})]}));Ku.displayName=su.displayName;function Dy({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-header",className:we("flex flex-col gap-2 text-center sm:text-left",t),...s})}function Ry({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-footer",className:we("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s})}function Py({className:t,...s}){return e.jsx(Xx,{"data-slot":"alert-dialog-title",className:we("text-lg font-semibold",t),...s})}function Iy({className:t,...s}){return e.jsx(Jx,{"data-slot":"alert-dialog-description",className:we("text-muted-foreground text-sm",t),...s})}function Ey({className:t,...s}){return e.jsx(qx,{className:we(cn(),t),...s})}function My({className:t,...s}){return e.jsx(Qx,{className:we(cn({variant:"outline"}),t),...s})}const ka={async list(t){return(await ye.get("/notifications",{params:t})).data},async getUnreadCount(){return(await ye.get("/notifications/unread-count")).data},async markAsRead(t){return(await ye.patch(`/notifications/${t}/read`)).data},async markAllAsRead(){return(await ye.post("/notifications/mark-all-read")).data},async delete(t){return(await ye.delete(`/notifications/${t}`)).data}},Fy=async()=>(await ye.get("/notifications/subscriptions")).data.data.subscriptions;let Ha=null;function _y(){return"https://re-workflow-nt-dev.siplsolutions.com/"}function fr(t){const s=_y();return Ha||(Ha=Qf(s,{withCredentials:!0,transports:["websocket","polling"],path:"/socket.io",reconnection:!0,reconnectionDelay:1e3,reconnectionAttempts:5}),Ha.on("connect",()=>{}),Ha.on("connect_error",a=>{console.error("[Socket] Connection error:",a.message)}),Ha.on("disconnect",a=>{}),Ha)}function wl(t,s,a){a?t.emit("join:request",{requestId:s,userId:a}):t.emit("join:request",s)}function Yu(t,s){t.emit("leave:request",s)}function Zu(t,s){t.emit("join:user",{userId:s})}function fs({children:t,currentPage:s="dashboard",onNavigate:a,onNewRequest:r,onLogout:n}){const[i,l]=x.useState(!1),[o,c]=x.useState(!1),[d,m]=x.useState([]),[u,h]=x.useState(0),[g,p]=x.useState(!1),{user:y}=Kt(),b=()=>{var C,S;try{if(y!=null&&y.displayName&&typeof y.displayName=="string"){const E=y.displayName.split(" ").filter(Boolean);return E.length>=2?`${((C=E[0])==null?void 0:C[0])||""}${((S=E[E.length-1])==null?void 0:S[0])||""}`.toUpperCase():y.displayName.substring(0,2).toUpperCase()}return y!=null&&y.email&&typeof y.email=="string"?y.email.substring(0,2).toUpperCase():"U"}catch(E){return console.error("[PageLayout] Error getting user initials:",E),"U"}},j=x.useMemo(()=>{const C=[{id:"dashboard",label:"Dashboard",icon:uf},{id:"requests",label:"All Requests",icon:fu}];return C.push({id:"my-requests",label:"My Requests",icon:Pt},{id:"open-requests",label:"Open Requests",icon:Le},{id:"closed-requests",label:"Closed Requests",icon:Ce},{id:"shared-summaries",label:"Shared Summary",icon:vr}),C},[]),v=()=>{l(!i)},w=async C=>{var S;try{if(C.isRead||(await ka.markAsRead(C.notificationId),m(E=>E.map(P=>P.notificationId===C.notificationId?{...P,isRead:!0}:P)),h(E=>Math.max(0,E-1))),C.actionUrl&&a){const E=(S=C.metadata)==null?void 0:S.requestNumber;if(E){let P=`request/${E}`;(C.notificationType==="mention"||C.notificationType==="comment"||C.notificationType==="worknote")&&(P+="?tab=worknotes"),a(P)}}p(!1)}catch(E){console.error("[PageLayout] Error handling notification click:",E)}},N=async()=>{try{await ka.markAllAsRead(),m(C=>C.map(S=>({...S,isRead:!0}))),h(0)}catch(C){console.error("[PageLayout] Error marking all as read:",C)}};return x.useEffect(()=>{const C=y==null?void 0:y.userId;if(!C)return;let S=!0;(async()=>{var R,f;try{const T=await ka.list({page:1,limit:4,unreadOnly:!1});if(!S)return;const F=((R=T.data)==null?void 0:R.notifications)||[];m(F),h(((f=T.data)==null?void 0:f.unreadCount)||0)}catch(T){console.error("[PageLayout] Failed to fetch notifications:",T)}})();const P=fr();if(P){Zu(P,C);const R=f=>{S&&(m(T=>[f.notification,...T].slice(0,4)),h(T=>T+1))};return P.on("notification:new",R),()=>{S=!1,P.off("notification:new",R)}}return()=>{S=!1}},[y]),x.useEffect(()=>{const C=()=>{window.innerWidth>=768?l(!0):l(!1)};return C(),window.addEventListener("resize",C),()=>window.removeEventListener("resize",C)},[]),e.jsxs("div",{className:"min-h-screen flex w-full bg-background",children:[i&&e.jsx("div",{className:"fixed inset-0 bg-black/50 z-40 md:hidden",onClick:()=>l(!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:gi,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:j.map(C=>e.jsxs("button",{onClick:()=>{a==null||a(C.id),window.innerWidth<768&&l(!1)},className:`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-colors ${s===C.id?"bg-re-green text-white font-medium":"text-gray-300 hover:bg-gray-900 hover:text-white"}`,children:[e.jsx(C.icon,{className:"w-4 h-4 shrink-0"}),e.jsx("span",{className:"truncate",children:C.label})]},C.id))}),e.jsx("div",{className:"mt-6 pt-6 border-t border-gray-800 px-3",children:e.jsxs(I,{onClick:r,className:"w-full bg-re-green hover:bg-re-green/90 text-white text-sm font-medium",size:"sm",children:[e.jsx(Ls,{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(I,{variant:"ghost",size:"icon",onClick:v,className:"shrink-0 h-10 w-10 sidebar-toggle",children:i?e.jsx(hf,{className:"w-5 h-5 text-gray-600"}):e.jsx(pf,{className:"w-5 h-5 text-gray-600"})})}),e.jsxs("div",{className:"flex items-center gap-4 shrink-0",children:[e.jsxs(I,{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(Ls,{className:"w-4 h-4"}),"New Request"]}),e.jsxs(ud,{open:g,onOpenChange:p,children:[e.jsx(hd,{asChild:!0,children:e.jsxs(I,{variant:"ghost",size:"icon",className:"relative shrink-0 h-10 w-10",children:[e.jsx(vs,{className:"w-5 h-5"}),u>0&&e.jsx(ie,{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(pd,{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(I,{variant:"ghost",size:"sm",className:"text-xs text-blue-600 hover:text-blue-700 h-auto p-1",onClick:C=>{C.stopPropagation(),N()},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(vs,{className:"w-12 h-12 text-gray-300 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-gray-500",children:"No notifications yet"})]}):e.jsx("div",{className:"divide-y",children:d.map(C=>e.jsx("div",{className:`p-3 hover:bg-gray-50 cursor-pointer transition-colors ${C.isRead?"":"bg-blue-50"}`,onClick:()=>w(C),children:e.jsxs("div",{className:"flex gap-2",children:[!C.isRead&&e.jsx("div",{className:"w-2 h-2 rounded-full bg-blue-600 mt-1.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`text-sm ${C.isRead?"font-medium":"font-semibold"}`,children:C.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-2",children:C.message}),e.jsx("p",{className:"text-xs text-gray-400 mt-1",children:uu(new Date(C.createdAt),{addSuffix:!0})})]})]})},C.notificationId))})}),d.length>0&&e.jsx("div",{className:"p-2 border-t",children:e.jsx(I,{variant:"ghost",className:"w-full text-sm text-blue-600 hover:text-blue-700",onClick:()=>{p(!1),a==null||a("notifications")},children:"View all notifications"})})]})]}),e.jsxs(ud,{children:[e.jsx(hd,{asChild:!0,children:e.jsxs(Qt,{className:"cursor-pointer shrink-0 h-10 w-10",children:[e.jsx(fi,{src:(y==null?void 0:y.picture)||""}),e.jsx(qt,{className:"bg-re-green text-white text-sm",children:b()})]})}),e.jsxs(pd,{align:"end",children:[e.jsxs($i,{onClick:()=>a==null?void 0:a("profile"),children:[e.jsx(Pt,{className:"w-4 h-4 mr-2"}),"Profile"]}),e.jsxs($i,{onClick:()=>a==null?void 0:a("settings"),children:[e.jsx(Da,{className:"w-4 h-4 mr-2"}),"Settings"]}),e.jsxs($i,{onClick:()=>c(!0),className:"text-red-600 focus:text-red-600",children:[e.jsx(Ii,{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(Ty,{open:o,onOpenChange:c,children:e.jsxs(Ku,{children:[e.jsxs(Dy,{children:[e.jsxs(Py,{className:"flex items-center gap-2",children:[e.jsx(Ii,{className:"w-5 h-5 text-red-600"}),"Confirm Logout"]}),e.jsx(Iy,{className:"pt-2",children:"Are you sure you want to logout? You will need to sign in again to access your account."})]}),e.jsxs(Ry,{children:[e.jsx(My,{onClick:()=>c(!1),children:"Cancel"}),e.jsxs(Ey,{onClick:async()=>{if(c(!1),n)try{await n()}catch(C){console.error("🔴 Error calling onLogout:",C)}else console.error("🔴 ERROR: onLogout is undefined!")},className:"bg-red-600 hover:bg-red-700 text-white focus:ring-red-600",children:[e.jsx(Ii,{className:"w-4 h-4 mr-2"}),"Logout"]})]})]})})]})}const yn=()=>C0(),Sr=T0,Ly=()=>{try{const t=localStorage.getItem("dashboard_viewAsUser");return t?JSON.parse(t):!1}catch{return!1}},Oy={viewAsUser:Ly()},Xu=wr({name:"dashboard",initialState:Oy,reducers:{setViewAsUser:(t,s)=>{t.viewAsUser=s.payload,localStorage.setItem("dashboard_viewAsUser",JSON.stringify(s.payload))}}}),{setViewAsUser:$y}=Xu.actions;function By(){const[t,s]=x.useState("all"),[a,r]=x.useState(void 0),[n,i]=x.useState(void 0),[l,o]=x.useState(!1),c=x.useCallback(u=>{const h=u;s(h),h!=="custom"?(r(void 0),i(void 0),o(!1)):o(!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);o(!1)}},[a,n]),m=x.useCallback(()=>{r(void 0),i(void 0),o(!1),s("all")},[]);return{dateRange:t,customStartDate:a,customEndDate:n,showCustomDatePicker:l,setDateRange:s,setCustomStartDate:r,setCustomEndDate:i,setShowCustomDatePicker:o,handleDateRangeChange:c,handleApplyCustomDate:d,resetCustomDates:m}}function Uy(){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}),[l,o]=x.useState({page:1,totalPages:1,totalRecords:0}),c=x.useCallback((b,j,v)=>{s({page:b,totalPages:j,totalRecords:v})},[]),d=x.useCallback((b,j,v)=>{r({page:b,totalPages:j,totalRecords:v})},[]),m=x.useCallback((b,j,v)=>{i({page:b,totalPages:j,totalRecords:v})},[]),u=x.useCallback((b,j,v)=>{o({page:b,totalPages:j,totalRecords:v})},[]),h=x.useCallback((b,j)=>{b>=1&&b<=t.totalPages&&(s(v=>({...v,page:b})),j(b))},[t.totalPages]),g=x.useCallback((b,j)=>{b>=1&&b<=a.totalPages&&(r(v=>({...v,page:b})),j(b))},[a.totalPages]),p=x.useCallback((b,j)=>{b>=1&&b<=n.totalPages&&(i(v=>({...v,page:b})),j(b))},[n.totalPages]),y=x.useCallback((b,j)=>{b>=1&&b<=l.totalPages&&(o(v=>({...v,page:b})),j(b))},[l.totalPages]);return{activity:t,critical:a,deadlines:n,approver:l,updateActivityPagination:c,updateCriticalPagination:d,updateDeadlinesPagination:m,updateApproverPagination:u,handleActivityPageChange:h,handleCriticalPageChange:g,handleDeadlinesPageChange:p,handleApproverPageChange:y}}class Vy{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 ye.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,l,o,c,d,m,u,h,g){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),l&&l!=="all"&&(p.templateType=l),o&&o!=="all"&&(p.department=o),c&&c!=="all"&&(p.initiator=c),d&&d!=="all"&&(p.approver=d),m&&(p.approverType=m),u&&(p.search=u),h&&h!=="all"&&(p.slaCompliance=h),g&&(p.viewAsUser="true"),(await ye.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 ye.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 ye.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 ye.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 ye.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 ye.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 ye.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 ye.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 ye.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 ye.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 ye.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,l,o){try{const c={dateRange:s,page:a,limit:r||10};s==="custom"&&n&&i&&(c.startDate=n.toISOString(),c.endDate=i.toISOString()),l&&l!=="all"&&(c.priority=l),o&&o!=="all"&&(c.slaCompliance=o),console.log("[Dashboard Service] Fetching approver performance with params:",c);const d=await ye.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 l={page:s,limit:a};r&&(l.dateRange=r),r==="custom"&&n&&i&&(l.startDate=n.toISOString(),l.endDate=i.toISOString());const o=await ye.get("/dashboard/reports/lifecycle",{params:l});return{lifecycleData:o.data.data,pagination:o.data.pagination}}catch(l){throw console.error("Failed to fetch lifecycle report:",l),l}}async getActivityLogReport(s=1,a=50,r,n,i,l,o,c,d){try{const m={page:s,limit:a,filterUserId:n,filterType:i,filterCategory:l,filterSeverity:o};r&&(m.dateRange=r),r==="custom"&&c&&d&&(m.startDate=c.toISOString(),m.endDate=d.toISOString());const u=await ye.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 ye.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,l){try{const o={threshold:s,page:a,limit:r};n&&(o.dateRange=n),n==="custom"&&i&&l&&(o.startDate=i.toISOString(),o.endDate=l.toISOString());const c=await ye.get("/dashboard/reports/workflow-aging",{params:o});return{agingData:c.data.data,pagination:c.data.pagination}}catch(o){throw console.error("Failed to fetch workflow aging report:",o),o}}async getSingleApproverStats(s,a,r,n,i,l){try{const o={approverId:s};return a&&(o.dateRange=a),a==="custom"&&r&&n&&(o.startDate=r.toISOString(),o.endDate=n.toISOString()),i&&i!=="all"&&(o.priority=i),l&&l!=="all"&&(o.slaCompliance=l),(await ye.get("/dashboard/stats/single-approver",{params:o})).data.data}catch(o){throw console.error("Failed to fetch single approver stats:",o),o}}async getRequestsByApprover(s,a=1,r=50,n,i,l,o,c,d,m){try{const u={approverId:s,page:a,limit:r};n&&(u.dateRange=n),n==="custom"&&i&&l&&(u.startDate=i.toISOString(),u.endDate=l.toISOString()),o&&(u.status=o),c&&(u.priority=c),d&&(u.slaCompliance=d),m&&(u.search=m);const h=await ye.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 jt=new Vy;function zy({isAdmin:t,viewAsUser:s=!1,userId:a,dateRange:r,customStartDate:n,customEndDate:i,onPaginationUpdate:l}){const[o,c]=x.useState(null),[d,m]=x.useState([]),[u,h]=x.useState([]),[g,p]=x.useState([]),[y,b]=x.useState([]),[j,v]=x.useState([]),[w,N]=x.useState(null),[C,S]=x.useState([]),[E,P]=x.useState(!0),[R,f]=x.useState(!1),T=x.useRef(l);T.current=l;const F=x.useCallback(async(A=!1)=>{try{A?f(!0):P(!0);const k=[jt.getKPIs(r,n,i,s),jt.getRecentActivity(1,10,s),jt.getCriticalRequests(1,10,s),jt.getUpcomingDeadlines(1,10,s)],M=!t&&a?jt.getRequestStats(r,n==null?void 0:n.toISOString(),i==null?void 0:i.toISOString(),void 0,void 0,void 0,void 0,a,void 0,void 0,void 0,void 0,s):null,O=t?[jt.getDepartmentStats(r,n,i),jt.getPriorityDistribution(r,n,i),jt.getAIRemarkUtilization(r,n,i),jt.getApproverPerformance(r,1,10,n,i)]:[],[L,Z,z]=await Promise.all([Promise.all(k),M,Promise.all(O)]),$=L[0],W=L[1],_=L[2],G=L[3];if(!t&&Z&&($.requestVolume=Z),c($),m(W.activities),T.current.activity(W.pagination.currentPage,W.pagination.totalPages,W.pagination.totalRecords),h(_.criticalRequests),T.current.critical(_.pagination.currentPage,_.pagination.totalPages,_.pagination.totalRecords),v(G.deadlines),T.current.deadlines(G.pagination.currentPage,G.pagination.totalPages,G.pagination.totalRecords),t&&z.length>=4){const H=z[0],V=z[1],ee=z[2],oe=z[3];p(H),b(V),N(ee),S(oe.performance),T.current.approver(oe.pagination.currentPage,oe.pagination.totalPages,oe.pagination.totalRecords)}else t||(p([]),b([]),N(null),S([]))}catch(k){console.error("Failed to fetch dashboard data:",k)}finally{P(!1),f(!1)}},[t,s,a,r,n,i]),K=x.useCallback(async(A=1)=>{try{const k=await jt.getRecentActivity(A,10,s);m(k.activities),T.current.activity(k.pagination.currentPage,k.pagination.totalPages,k.pagination.totalRecords)}catch(k){console.error("Failed to fetch recent activities:",k)}},[s]),B=x.useCallback(async(A=1)=>{try{const k=await jt.getCriticalRequests(A,10,s);h(k.criticalRequests),T.current.critical(k.pagination.currentPage,k.pagination.totalPages,k.pagination.totalRecords)}catch(k){console.error("Failed to fetch critical requests:",k)}},[s]),U=x.useCallback(async(A=1)=>{try{const k=await jt.getUpcomingDeadlines(A,10,s);v(k.deadlines),T.current.deadlines(k.pagination.currentPage,k.pagination.totalPages,k.pagination.totalRecords)}catch(k){console.error("Failed to fetch upcoming deadlines:",k)}},[s]),D=x.useCallback(async(A=1)=>{try{const k=await jt.getApproverPerformance(r,A,10,n,i);S(k.performance),T.current.approver(k.pagination.currentPage,k.pagination.totalPages,k.pagination.totalRecords)}catch(k){console.error("Failed to fetch approver performance:",k)}},[r,n,i]);return{kpis:o,recentActivity:d,criticalRequests:u,departmentStats:g,priorityDistribution:y,upcomingDeadlines:j,aiRemarkUtilization:w,approverPerformance:C,loading:E,refreshing:R,fetchDashboardData:F,fetchRecentActivities:K,fetchCriticalRequests:B,fetchUpcomingDeadlines:U,fetchApproverPerformance:D}}const fa={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 Hy{constructor(){ki(this,"config",null);ki(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 ye.get("/config"),r=((s=a.data)==null?void 0:s.data)||a.data;return{...fa,...r,workingHours:{...fa.workingHours,...r.workingHours},tat:{...fa.tat,...r.tat},upload:{...fa.upload,...r.upload},workflow:{...fa.workflow,...r.workflow},workNotes:{...fa.workNotes,...r.workNotes},features:{...fa.features,...r.features},ui:{...fa.ui,...r.ui}}}catch(a){return console.error("[ConfigService] ⚠️ Failed to fetch config from server, using defaults:",a),fa}}async refreshConfig(){return this.config=null,this.loading=null,this.getConfig()}getCachedConfig(){return this.config}isLoaded(){return this.config!==null}}const Wy=new Hy;let Gy=9,Ky=18,Yy=1,Zy=5,xd=!1;async function Xy(){if(!xd)try{const t=await Wy.getConfig();Gy=t.workingHours.START_HOUR,Ky=t.workingHours.END_HOUR,Yy=t.workingHours.START_DAY,Zy=t.workingHours.END_DAY,xd=!0}catch{console.warn("[SLA Tracker] ⚠️ Using default working hours (9 AM - 6 PM)")}}Xy().catch(()=>{});function It(t){if(t==null||t<0||t===0)return"0 hours";const s=8;if(t<1){const o=Math.round(t*60);return o>0?`${o}m`:"0 hours"}const a=Math.floor(t/s),r=Math.floor(t%s),n=Math.round(t%1*60);if(a>0){const o=a===1?"day":"days",c=r===1?"hour":"hours",d=n===1?"min":"m";return n>0?`${a} ${o} ${r} ${c} ${n}${d}`:`${a} ${o} ${r} ${c}`}const i=r===1?"hour":"hours",l=n===1?"min":"m";return n>0?`${r} ${i} ${n}${l}`:`${r} ${i}`}async function Jy(t,s,a){const r=[];let n=1,i=!0;const l=100;for(;i&&n<=l;){const h=await jt.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 o=[["Approver Name","Total Approved","TAT Compliance (%)","Avg Response Time","Pending Count"].join(",")];r.forEach(h=>{const g=[`"${(h.approverName||"Unknown").replace(/"/g,'""')}"`,h.totalApproved||0,h.tatCompliancePercent||0,It(h.avgResponseHours),h.pendingCount||0];o.push(g.join(","))});const c=o.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 Qy(t,s,a){const r=await jt.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(`
|
||
`),l=new Blob([i],{type:"text/csv;charset=utf-8;"}),o=document.createElement("a"),c=URL.createObjectURL(l);o.setAttribute("href",c),o.setAttribute("download",`department-workflow-summary-${new Date().toISOString().split("T")[0]}.csv`),o.style.visibility="hidden",document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(c)}function qy(){const[t,s]=x.useState(!1),[a,r]=x.useState(!1),n=x.useCallback(async(l,o,c)=>{try{s(!0),await Qy(l,o,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(l,o,c)=>{try{r(!0),await Jy(l,o,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(eg,{"data-slot":"switch",className:we("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(tg,{"data-slot":"switch-thumb",className:we("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 re({className:t,...s}){return e.jsx(sg,{"data-slot":"label",className:we("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 eb({isAdmin:t,effectiveIsAdmin:s,viewAsUser:a,onToggleView:r,quickActions:n,userDisplayName:i,userEmail:l}){const o=i||(l==null?void 0:l.split("@")[0])||"User";return e.jsxs(te,{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(se,{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(eo,{className:`w-3 h-3 sm:w-3.5 sm:h-3.5 ${a?"text-gray-300":"text-red-600"}`}),e.jsx(re,{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(Pt,{className:`w-3 h-3 sm:w-3.5 sm:h-3.5 ${a?"text-red-600":"text-gray-300"}`}),e.jsx(re,{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, ",o,"!"]}),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(I,{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 Ue({...t}){return e.jsx(ag,{"data-slot":"select",...t})}function Ve({...t}){return e.jsx(ig,{"data-slot":"select-value",...t})}function ze({className:t,size:s="default",children:a,...r}){return e.jsxs(rg,{"data-slot":"select-trigger","data-size":s,className:we("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(ng,{asChild:!0,children:e.jsx(yu,{className:"size-4 opacity-50"})})]})}function He({className:t,children:s,position:a="popper",...r}){return e.jsx(lg,{children:e.jsxs(og,{"data-slot":"select-content",className:we("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(tb,{}),e.jsx(cg,{className:we("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(sb,{})]})})}function Y({className:t,children:s,...a}){return e.jsxs(dg,{"data-slot":"select-item",className:we("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(mg,{children:e.jsx(jr,{className:"size-4"})})}),e.jsx(ug,{children:s})]})}function tb({className:t,...s}){return e.jsx(hg,{"data-slot":"select-scroll-up-button",className:we("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(xf,{className:"size-4"})})}function sb({className:t,...s}){return e.jsx(pg,{"data-slot":"select-scroll-down-button",className:we("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(yu,{className:"size-4"})})}function Vt({className:t,orientation:s="horizontal",decorative:a=!0,...r}){return e.jsx(xg,{"data-slot":"separator-root",decorative:a,orientation:s,className:we("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(gg,{"data-slot":"popover",...t})}function na({...t}){return e.jsx(fg,{"data-slot":"popover-trigger",...t})}function ia({className:t,align:s="center",sideOffset:a=4,...r}){return e.jsx(yg,{children:e.jsx(bg,{"data-slot":"popover-content",align:s,sideOffset:a,className:we("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 Re({className:t,type:s,...a}){return e.jsx("input",{type:s,"data-slot":"input",className:we("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 ab({isAdmin:t,dateRange:s,customStartDate:a,customEndDate:r,showCustomDatePicker:n,refreshing:i,onDateRangeChange:l,onCustomStartDateChange:o,onCustomEndDateChange:c,onShowCustomDatePickerChange:d,onApplyCustomDate:m,onResetCustomDates:u,onRefresh:h}){return e.jsx(te,{className:"shadow-md","data-testid":"dashboard-filters-bar",children:e.jsx(se,{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(gn,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Filters"}),t&&e.jsx(ie,{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(mt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ue,{value:s,onValueChange:l,"data-testid":"date-range-select",children:[e.jsx(ze,{className:"w-[140px]",children:e.jsx(Ve,{placeholder:"Select period"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"all",children:"All Time"}),e.jsx(Y,{value:"today",children:"Today"}),e.jsx(Y,{value:"week",children:"This Week"}),e.jsx(Y,{value:"month",children:"This Month"}),e.jsx(Y,{value:"last7days",children:"Last 7 Days"}),e.jsx(Y,{value:"last30days",children:"Last 30 Days"}),e.jsx(Y,{value:"custom",children:"Custom Range"})]})]}),s==="custom"&&e.jsxs(ra,{open:n,onOpenChange:d,children:[e.jsx(na,{asChild:!0,children:e.jsxs(I,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(mt,{className:"w-4 h-4"}),a&&r?`${Ie(a,"MMM d, yyyy")} - ${Ie(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(re,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(Re,{id:"start-date",type:"date",value:a?Ie(a,"yyyy-MM-dd"):"",onChange:g=>{const p=g.target.value?new Date(g.target.value):void 0;p?(o(p),r&&p>r&&c(p)):o(void 0)},max:Ie(new Date,"yyyy-MM-dd"),className:"w-full","data-testid":"start-date-input"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(Re,{id:"end-date",type:"date",value:r?Ie(r,"yyyy-MM-dd"):"",onChange:g=>{const p=g.target.value?new Date(g.target.value):void 0;p?(c(p),a&&p<a&&o(p)):c(void 0)},min:a?Ie(a,"yyyy-MM-dd"):void 0,max:Ie(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(I,{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(I,{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(mt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ue,{value:s,onValueChange:g=>l(g),"data-testid":"date-range-select-user",children:[e.jsx(ze,{className:"w-[140px]",children:e.jsx(Ve,{placeholder:"Select period"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"all",children:"All Time"}),e.jsx(Y,{value:"today",children:"Today"}),e.jsx(Y,{value:"week",children:"This Week"}),e.jsx(Y,{value:"month",children:"This Month"}),e.jsx(Y,{value:"last7days",children:"Last 7 Days"}),e.jsx(Y,{value:"last30days",children:"Last 30 Days"}),e.jsx(Y,{value:"custom",children:"Custom Range"})]})]})]}),e.jsx(Vt,{orientation:"vertical",className:"h-6 hidden sm:block"}),e.jsxs(I,{variant:"outline",size:"sm",onClick:h,disabled:i,className:"gap-2 min-w-[110px]","data-testid":"refresh-button",children:[e.jsx(ns,{className:`w-4 h-4 ${i?"animate-spin":""}`}),e.jsx("span",{className:"inline-block w-[60px] text-center",children:i?"Refreshing...":"Refresh"})]})]})]})})})}function Qa({title:t,value:s,icon:a,iconBgColor:r,iconColor:n,subtitle:i,children:l,testId:o="kpi-card",onClick:c,onJustifyClick:d,showJustifyButton:m=!1}){const u=h=>{h.stopPropagation(),d==null||d()};return e.jsxs(te,{className:"hover:shadow-lg transition-all duration-200 shadow-md cursor-pointer h-full flex flex-col",onClick:c,"data-testid":o,children:[e.jsxs(me,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(he,{className:"text-sm font-medium text-muted-foreground","data-testid":`${o}-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":`${o}-justify-button`,title:"View detailed breakdown of numbers","aria-label":"View detailed breakdown",children:e.jsx(Nr,{className:"h-4 w-4"})}),e.jsx("div",{className:`p-1.5 sm:p-2 rounded-lg ${r}`,"data-testid":`${o}-icon-wrapper`,children:e.jsx(a,{className:`h-4 w-4 sm:h-4 sm:w-4 ${n}`,"data-testid":`${o}-icon`})})]})]}),e.jsxs(se,{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":`${o}-value`,children:s}),i&&e.jsx("div",{className:"text-xs text-muted-foreground mb-2","data-testid":`${o}-subtitle`,children:i}),l&&e.jsx("div",{className:"flex-1 flex flex-col","data-testid":`${o}-children`,children:l})]})]})}function os({label:t,value:s,bgColor:a,textColor:r,testId:n="stat-card",children:i,onClick:l}){return e.jsxs("div",{className:`${a} rounded-lg p-2 sm:p-3 ${l?"cursor-pointer hover:shadow-md transition-shadow":""}`,"data-testid":n,onClick:l,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 Qs({className:t,value:s,indicatorClassName:a,...r}){return e.jsx(vg,{"data-slot":"progress",className:we("bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",t),...r,children:e.jsx(jg,{"data-slot":"progress-indicator",className:we("bg-primary h-full w-full flex-1 transition-all",a),style:{transform:`translateX(-${100-(s||0)}%)`}})})}function rb({kpis:t,priorityDistribution:s,dateRange:a,customStartDate:r,customEndDate:n,onKPIClick:i}){const l=()=>({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(Qa,{title:"Total Requests",value:(t==null?void 0:t.requestVolume.totalRequests)||0,icon:Le,iconBgColor:"bg-blue-50",iconColor:"text-blue-600",testId:"kpi-total-requests",onClick:()=>i(l()),children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-2",children:[e.jsx(os,{label:"Approved",value:(t==null?void 0:t.requestVolume.approvedRequests)||0,bgColor:"bg-green-50",textColor:"text-green-600",testId:"stat-approved",onClick:o=>{o.stopPropagation(),i({...l(),status:"approved"})}}),e.jsx(os,{label:"Rejected",value:(t==null?void 0:t.requestVolume.rejectedRequests)||0,bgColor:"bg-red-50",textColor:"text-red-600",testId:"stat-rejected",onClick:o=>{o.stopPropagation(),i({...l(),status:"rejected"})}})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-2",children:[e.jsx(os,{label:"Pending",value:(t==null?void 0:t.requestVolume.openRequests)||0,bgColor:"bg-orange-50",textColor:"text-orange-600",testId:"stat-pending",onClick:o=>{o.stopPropagation(),i({...l(),status:"pending"})}}),e.jsx(os,{label:"Closed",value:(t==null?void 0:t.requestVolume.closedRequests)||0,bgColor:"bg-gray-50",textColor:"text-gray-600",testId:"stat-closed",onClick:o=>{o.stopPropagation(),i({...l(),status:"closed"})}})]}),(t==null?void 0:t.requestVolume.pausedRequests)!==void 0&&e.jsx("div",{className:"grid grid-cols-2 gap-2",children:e.jsx(os,{label:"Paused",value:t.requestVolume.pausedRequests||0,bgColor:"bg-orange-100",textColor:"text-orange-700",testId:"stat-paused",onClick:o=>{o.stopPropagation(),i({...l(),status:"paused"})}})})]}),e.jsx(Qa,{title:"SLA Compliance",value:`${(t==null?void 0:t.tatEfficiency.avgTATCompliance)||0}%`,icon:Bt,iconBgColor:"bg-green-50",iconColor:"text-green-600",testId:"kpi-sla-compliance",onClick:()=>i(l()),children:e.jsxs("div",{className:"flex flex-col flex-1",children:[e.jsx(Qs,{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(os,{label:"Compliant",value:(t==null?void 0:t.tatEfficiency.compliantWorkflows)||0,bgColor:"bg-green-50",textColor:"text-green-600",testId:"stat-compliant",onClick:o=>{o.stopPropagation(),i({...l(),slaCompliance:"compliant"})}}),e.jsx(os,{label:"Breached",value:(t==null?void 0:t.tatEfficiency.delayedWorkflows)||0,bgColor:"bg-red-50",textColor:"text-red-600",testId:"stat-breached",onClick:o=>{o.stopPropagation(),i({...l(),slaCompliance:"breached"})}})]})]})}),e.jsx(Qa,{title:"Avg Cycle Time",value:t!=null&&t.tatEfficiency.avgCycleTimeHours?It(t.tatEfficiency.avgCycleTimeHours):"0 hours",icon:Ze,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(l()),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(os,{label:"Express",value:(()=>{const o=s.find(d=>d.priority==="express"),c=o?Number(o.avgCycleTimeHours):0;return c>0?It(c):"N/A"})(),bgColor:"bg-orange-50",textColor:"text-orange-600",testId:"stat-express-time",onClick:o=>{o.stopPropagation(),i({...l(),priority:"express"})}}),e.jsx(os,{label:"Standard",value:(()=>{const o=s.find(d=>d.priority==="standard"),c=o?Number(o.avgCycleTimeHours):0;return c>0?It(c):"N/A"})(),bgColor:"bg-blue-50",textColor:"text-blue-600",testId:"stat-standard-time",onClick:o=>{o.stopPropagation(),i({...l(),priority:"standard"})}})]})})})]})}function nb({kpis:t,criticalRequests:s,dateRange:a,customStartDate:r,customEndDate:n,onKPIClick:i,onNavigate:l,userId:o,userDisplayName:c}){const d=()=>({dateRange:a,startDate:r,endDate:n}),m=()=>{if(!o)return;const h=new URLSearchParams;h.set("approverId",o),h.set("approverName",c||"My Performance"),h.set("dateRange",a),a==="custom"&&r&&n&&(h.set("startDate",r.toISOString()),h.set("endDate",n.toISOString())),l==null||l(`/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(Qa,{title:"My Requests (Submitted)",value:(t==null?void 0:t.requestVolume.totalRequests)||0,icon:Le,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(os,{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(os,{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(os,{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(os,{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(os,{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(Qa,{title:"Awaiting My Approval",value:(t==null?void 0:t.approverLoad.pendingActions)||0,icon:Ze,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:!!o,children:e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-auto",children:[e.jsx(os,{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(os,{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(Qa,{title:"Critical Alerts",value:s.length,icon:ta,iconBgColor:"bg-red-50",iconColor:"text-red-600",testId:"kpi-user-critical",onClick:()=>i({...d(),targetPage:"open-requests"}),onJustifyClick:m,showJustifyButton:!!o,children:e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-auto",children:[e.jsx(os,{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(os,{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(Qa,{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(Qs,{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 ib=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)))},lb=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 ob({alert:t,onNavigate:s,testId:a="critical-alert-card"}){const r=ib(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(gf,{className:"h-3 w-3 text-red-500 flex-shrink-0","data-testid":`${a}-priority-icon`}),t.breachCount>0&&e.jsx(ie,{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(ie,{variant:"outline",className:"text-xs bg-white border-red-200 text-red-700 font-medium whitespace-nowrap","data-testid":`${a}-remaining-time`,children:lb(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(Qs,{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 cb(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 db(t){return t.filter(s=>{const a=Number(s.tatPercentageUsed)||0;return(Number(s.remainingHours)||0)>0&&a<100})}function mb(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 ub(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 Ju(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 l=n;l<=i;l++)r.push(l);return r}function hb({isAdmin:t,breachedRequests:s,pagination:a,onPageChange:r,onNavigate:n}){return e.jsxs(te,{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(me,{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(ta,{className:"h-4 w-4 sm:h-5 sm:w-5 text-red-600"})}),e.jsxs("div",{children:[e.jsx(he,{className:"text-base sm:text-lg text-gray-900",children:"Critical Alerts"}),e.jsx(De,{className:"text-xs sm:text-sm text-gray-600",children:t?"Organization-wide":"My requests"})]})]}),e.jsx(ie,{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(se,{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(ob,{alert:i,onNavigate:l=>n==null?void 0:n(`request/${l}`),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(I,{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(rs,{className:"h-3 w-3 rotate-180"})}),Ju(a.page,a.totalPages,3).map(i=>e.jsx(I,{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(I,{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(rs,{className:"h-3 w-3"})})]})]})})]})}const pb=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"}},xb=t=>{const s=new Date,a=new Date(t),r=Jg(s,a);if(r<1)return"just now";if(r<60)return`${r} minute${r>1?"s":""} ago`;const n=Qg(s,a);if(n<24)return`${n} hour${n>1?"s":""} ago`;const i=qg(s,a);return`${i} day${i>1?"s":""} ago`},gb=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()},fb=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(hs,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-red-600"}):s.includes("comment")?e.jsx(Os,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-blue-600"}):s.includes("escalat")?e.jsx(ta,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-orange-600"}):s.includes("submit")?e.jsx(Le,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-purple-600"}):s.includes("document")?e.jsx(ii,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-indigo-600"}):e.jsx(ts,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-gray-600"})};function yb({activity:t,currentUserId:s,currentUserDisplayName:a,currentUserEmail:r,onNavigate:n,testId:i="activity-feed-item"}){const l=t.userId===s,o=l?"You":t.userName||"System",c=l?(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(Qt,{className:`h-8 w-8 sm:h-10 sm:w-10 ring-2 shadow-sm ${l?"ring-blue-200":"ring-white"}`,"data-testid":`${i}-avatar`,children:[e.jsx(fi,{src:""}),e.jsx(qt,{className:`text-white font-semibold text-xs sm:text-sm ${l?"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:fb(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(ie,{variant:"outline",className:`text-xs ${pb(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:gb(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] ${l?"text-blue-600":"text-gray-900"}`,"data-testid":`${i}-user-name`,children:o}),e.jsx("span",{children:"•"}),e.jsx("span",{className:"whitespace-nowrap","data-testid":`${i}-timestamp`,children:xb(t.timestamp)})]})]}),e.jsx(rs,{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 bb({isAdmin:t,recentActivity:s,pagination:a,refreshing:r,onPageChange:n,onRefresh:i,onNavigate:l,currentUserId:o,currentUserDisplayName:c,currentUserEmail:d}){return e.jsxs(te,{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(me,{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(ts,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx(he,{className:"text-base sm:text-lg text-gray-900",children:"Recent Activity"}),e.jsx(De,{className:"text-xs sm:text-sm text-gray-600 truncate",children:t?"All workflow updates":"My workflow updates"})]})]}),e.jsxs(I,{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(ns,{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(se,{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(ts,{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(yb,{activity:m,currentUserId:o,currentUserDisplayName:c,currentUserEmail:d,onNavigate:u=>l==null?void 0:l(`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(I,{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(rs,{className:"h-3 w-3 rotate-180"})}),Ju(a.page,a.totalPages,3).map(m=>e.jsx(I,{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(I,{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(rs,{className:"h-3 w-3"})})]})]})})]})}function vb({kpis:t,upcomingDeadlines:s,criticalRequests:a,departmentStats:r,dateRange:n,customStartDate:i,customEndDate:l,exportingDeptStats:o,onKPIClick:c,onExportDepartmentStats:d}){if(!t)return null;const m=()=>({dateRange:n,startDate:i,endDate:l});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(te,{className:"shadow-md hover:shadow-lg transition-shadow flex-1","data-testid":"active-levels-card",children:[e.jsx(me,{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(ts,{className:"h-4 w-4 text-blue-600"})}),e.jsx(he,{className:"text-sm",children:"Active Levels"})]})}),e.jsx(se,{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(Vt,{}),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(te,{className:"shadow-md hover:shadow-lg transition-shadow flex-1","data-testid":"collaboration-card",children:[e.jsx(me,{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(Os,{className:"h-4 w-4 text-indigo-600"})}),e.jsx(he,{className:"text-sm",children:"Collaboration"})]})}),e.jsx(se,{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(Vt,{}),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(te,{className:"shadow-md hover:shadow-lg transition-shadow lg:col-span-2","data-testid":"department-stats-card",children:[e.jsx(me,{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(ff,{className:"h-5 w-5 sm:h-6 sm:w-6 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(he,{className:"text-base sm:text-lg lg:text-xl",children:"Department-wise Workflow Summary"}),e.jsx(De,{className:"text-xs sm:text-sm",children:"Workflow distribution across departments"})]})]}),e.jsxs(I,{variant:"outline",size:"sm",className:"gap-2 self-start sm:self-auto",onClick:()=>d(n,i,l),disabled:o,"data-testid":"export-dept-stats-button",children:[e.jsx(Nt,{className:`w-3 h-3 sm:w-4 sm:h-4 ${o?"animate-pulse":""}`}),e.jsx("span",{className:"text-xs sm:text-sm",children:o?"Exporting...":"Export"})]})]})}),e.jsx(se,{children:e.jsx(Kl,{width:"100%",height:400,children:e.jsxs(Wg,{data:r,children:[e.jsx(ou,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(cu,{dataKey:"department",stroke:"#999",tick:u=>{const{x:h,y:g,payload:p}=u;return e.jsx("g",{transform:`translate(${h},${g})`,children:e.jsx("text",{x:0,y:0,dy:16,textAnchor:"middle",fill:"#999",fontSize:11,className:"cursor-pointer hover:text-blue-600 hover:underline",onClick:()=>{c({...m(),department:p.value})},children:p.value})})}}),e.jsx(du,{stroke:"#999",tick:{fontSize:11}}),e.jsx(Yl,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(mu,{verticalAlign:"bottom",height:36,iconType:"square",wrapperStyle:{fontSize:"12px",paddingTop:"10px"}}),e.jsx(Di,{dataKey:"approved",fill:"#10b981",name:"Approved"}),e.jsx(Di,{dataKey:"inProgress",fill:"#f59e0b",name:"Pending"}),e.jsx(Di,{dataKey:"rejected",fill:"#ef4444",name:"Rejected"})]})})})]})]})}function jb({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(te,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"user-activity-card",children:[e.jsx(me,{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(Os,{className:"h-4 w-4 text-indigo-600"})}),e.jsx(he,{className:"text-sm",children:"My Activity"})]})}),e.jsx(se,{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(te,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"user-response-time-card",children:[e.jsx(me,{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(Ze,{className:"h-4 w-4 text-purple-600"})}),e.jsx(he,{className:"text-sm",children:"Avg Response Time"})]})}),e.jsx(se,{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:It(t.tatEfficiency.avgCycleTimeHours)})}),e.jsx(Vt,{}),e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["≈ ",t.tatEfficiency.avgCycleTimeDays.toFixed(1)," working days"]})]})})]})]}):null}function Nb({priorityDistribution:t,onNavigate:s}){return t.length===0?null:e.jsxs(te,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"priority-distribution-report",children:[e.jsx(me,{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(Bt,{className:"h-5 w-5 sm:h-6 sm:w-6 text-green-600"})}),e.jsxs("div",{children:[e.jsx(he,{className:"text-base sm:text-lg lg:text-xl",children:"Priority Distribution Report"}),e.jsx(De,{className:"text-xs sm:text-sm",children:"Express vs Standard workflow analysis"})]})]})}),e.jsxs(se,{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",l=i?"bg-red-50":"bg-blue-50",o=i?"bg-red-500":"bg-blue-500";return e.jsxs("div",{className:`${l} 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 ${o} 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: ",It(n)," cycle"]})]},r)})}),e.jsx("div",{className:"flex justify-center",children:e.jsx(Kl,{width:"100%",height:300,children:e.jsxs(Gg,{children:[e.jsx(Kg,{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:l,percentage:o})=>{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:`${l}: ${o}%`})},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(Yg,{fill:a.priority==="express"?"#ef4444":"#3b82f6",style:{cursor:"pointer"}},`cell-${r}`))}),e.jsx(Yl,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"},formatter:(a,r,n)=>{var l;const i=((l=n.payload)==null?void 0:l.priority)||"";return[`${a} requests`,`Click for ${i}`]}})]})})})]})]})}function lr({currentPage:t,totalPages:s,itemsPerPage:a,totalRecords:r,onPageChange:n,loading:i=!1,itemLabel:l="items",testIdPrefix:o="pagination"}){const c=()=>{const u=[];let g=Math.max(1,t-Math.floor(2.5)),p=Math.min(s,g+5-1);p-g<4&&(g=Math.max(1,p-5+1));for(let y=g;y<=p;y++)u.push(y);return u},d=r>0?(t-1)*a+1:0,m=Math.min(t*a,r);return s<=1?e.jsx(te,{className:"shadow-md border-gray-200","data-testid":`${o}-container`,children:e.jsx(se,{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":`${o}-info`,children:i?`Loading ${l}...`:r===0?`No ${l} found`:r===1?`Showing 1 ${l.slice(0,-1)}`:d===m?`Showing ${d} of ${r} ${l}`:`Showing ${d} to ${m} of ${r} ${l}`})})})}):e.jsx(te,{className:"shadow-md border-gray-200","data-testid":`${o}-container`,children:e.jsx(se,{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":`${o}-info`,children:["Showing ",d," to ",m," of ",r," ",l]}),e.jsxs("div",{className:"flex items-center gap-2","data-testid":`${o}-controls`,children:[e.jsx(I,{variant:"outline",size:"sm",onClick:()=>n(t-1),disabled:t===1,className:"h-8 w-8 p-0","data-testid":`${o}-prev-btn`,"aria-label":"Previous page",children:e.jsx(rs,{className:"h-4 w-4 rotate-180"})}),t>3&&s>5&&e.jsxs(e.Fragment,{children:[e.jsx(I,{variant:"outline",size:"sm",onClick:()=>n(1),className:"h-8 w-8 p-0","data-testid":`${o}-page-1`,children:"1"}),e.jsx("span",{className:"text-muted-foreground","data-testid":`${o}-ellipsis-start`,children:"..."})]}),c().map(u=>e.jsx(I,{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":`${o}-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":`${o}-ellipsis-end`,children:"..."}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>n(s),className:"h-8 w-8 p-0","data-testid":`${o}-page-${s}`,children:s})]}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>n(t+1),disabled:t===s,className:"h-8 w-8 p-0","data-testid":`${o}-next-btn`,"aria-label":"Next page",children:e.jsx(rs,{className:"h-4 w-4"})})]})]})})})}function wb(t,s,a,r="for"){return t==="custom"&&s&&a?`${r} ${Ie(s,"MMM d, yyyy")} - ${Ie(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 Cb(t,s,a){return t==="all"?"All historical data":t==="custom"&&s&&a?`Data from ${Ie(s,"MMM d, yyyy")} to ${Ie(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 Sb({breachedRequests:t,pagination:s,dateRange:a,customStartDate:r,customEndDate:n,onPageChange:i,onKPIClick:l,onNavigate:o}){if(t.length===0)return null;const c=()=>({dateRange:a,startDate:r,endDate:n});return e.jsxs(te,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"tat-breach-report",children:[e.jsx(me,{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(hs,{className:"h-5 w-5 sm:h-6 sm:w-6 text-red-600"})}),e.jsxs("div",{children:[e.jsx(he,{className:"text-base sm:text-lg lg:text-xl",children:"TAT Breach Report"}),e.jsxs(De,{className:"text-xs sm:text-sm",children:["Requests that breached TAT - ",Cb(a,r,n)]})]})]}),e.jsxs(ie,{variant:"destructive",className:"text-sm font-medium self-start sm:self-auto",children:[t.length," ",t.length===1?"Breach":"Breaches"]})]})}),e.jsxs(se,{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:()=>o==null?void 0:o(`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"&&l({...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(o){const h=new URLSearchParams;h.set("approver",d.approverId),h.set("approverType","current"),h.set("slaCompliance","breached"),o(`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:mb(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(ie,{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(lr,{currentPage:s.page,totalPages:s.totalPages,totalRecords:s.totalRecords,itemsPerPage:10,onPageChange:i,itemLabel:"critical requests",testIdPrefix:"dashboard-critical-pagination"})})]})]})}function Ab({isAdmin:t,upcomingDeadlines:s,pagination:a,onPageChange:r,onNavigate:n}){return s.length===0?null:e.jsxs(te,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"upcoming-deadlines-section",children:[e.jsx(me,{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(mt,{className:"h-4 w-4 sm:h-5 sm:w-5 text-orange-600"}),e.jsxs("div",{children:[e.jsx(he,{className:"text-base sm:text-lg",children:"Upcoming Deadlines"}),e.jsx(De,{className:"text-xs sm:text-sm",children:t?"Current active levels organization-wide":"Requests awaiting your approval"})]})]})})}),e.jsxs(se,{children:[e.jsx("div",{className:"space-y-2 sm:space-y-3",children:s.map((i,l)=>{const o=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(ie,{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(ie,{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 ${o>=80?"text-red-600":o>=50?"text-orange-600":"text-green-600"}`,children:[o.toFixed(0),"%"]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(Qs,{value:o,className:`h-1.5 sm:h-2 ${o>=80?"bg-red-100":o>=50?"bg-orange-100":"bg-green-100"}`}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[It(c)," elapsed"]}),e.jsxs("span",{children:[It(d)," left"]})]})]})]},l)})}),e.jsx("div",{className:"mt-4",children:e.jsx(lr,{currentPage:a.page,totalPages:a.totalPages,totalRecords:a.totalRecords,itemsPerPage:10,onPageChange:r,itemLabel:"deadlines",testIdPrefix:"dashboard-deadlines-pagination"})})]})]})}function Tb({aiRemarkUtilization:t}){return t?e.jsxs(te,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"ai-remark-utilization-report",children:[e.jsx(me,{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(to,{className:"h-5 w-5 sm:h-6 sm:w-6 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(he,{className:"text-base sm:text-lg lg:text-xl",children:"AI Remark Utilization Report"}),e.jsx(De,{className:"text-xs sm:text-sm",children:"AI-generated remarks usage and edits"})]})]})}),e.jsxs(se,{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(Kl,{width:"100%",height:250,children:e.jsxs(Zg,{data:t.monthlyTrends,children:[e.jsx(ou,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(cu,{dataKey:"month",stroke:"#999",tick:{fontSize:11}}),e.jsx(du,{stroke:"#999",tick:{fontSize:11}}),e.jsx(Yl,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(mu,{verticalAlign:"bottom",height:36,iconType:"circle",wrapperStyle:{fontSize:"12px",paddingTop:"10px"}}),e.jsx(Jc,{type:"monotone",dataKey:"aiUsage",stroke:"#8b5cf6",strokeWidth:2,name:"AI Usage",dot:{fill:"#8b5cf6",r:4}}),e.jsx(Jc,{type:"monotone",dataKey:"manualEdits",stroke:"#ec4899",strokeWidth:2,name:"Manual Edits",dot:{fill:"#ec4899",r:4}})]})})]})]}):null}function kb({approverPerformance:t,pagination:s,dateRange:a,customStartDate:r,customEndDate:n,loading:i,exportingApproverPerformance:l,onPageChange:o,onExport:c,onNavigate:d}){return t.length===0?null:e.jsxs(te,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"approver-performance-report",children:[e.jsx(me,{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(Mt,{className:"h-5 w-5 sm:h-6 sm:w-6 text-yellow-600"})}),e.jsxs("div",{children:[e.jsx(he,{className:"text-base sm:text-lg lg:text-xl",children:"Approver Performance Report"}),e.jsx(De,{className:"text-xs sm:text-sm",children:"Response time & TAT compliance tracking"})]})]}),e.jsx(I,{onClick:()=>c(a,r,n),disabled:l||i,className:"bg-re-green hover:bg-re-green/90 text-white shrink-0",size:"sm","data-testid":"export-approver-performance-button",children:l?e.jsxs(e.Fragment,{children:[e.jsx(ns,{className:"w-4 h-4 mr-2 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Nt,{className:"w-4 h-4 mr-2"}),"Export"]})})]})}),e.jsxs(se,{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 g=new URLSearchParams;g.set("approverId",m.approverId),g.set("approverName",m.approverName),g.set("dateRange",a),a==="custom"&&r&&n&&(g.set("startDate",r.toISOString()),g.set("endDate",n.toISOString())),d==null||d(`/approver-performance?${g.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 ${ub(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:It(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(lr,{currentPage:s.page,totalPages:s.totalPages,totalRecords:s.totalRecords,itemsPerPage:10,onPageChange:o,itemLabel:"approvers",testIdPrefix:"dashboard-approver-pagination"})})]})]})}function Db(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 Rb(t,s,a){const r=[{label:"New Request",icon:Le,action:()=>s==null?void 0:s(),color:"bg-emerald-600 hover:bg-emerald-700"},{label:"View Pending",icon:Ze,action:()=>a==null?void 0:a("open-requests"),color:"bg-blue-600 hover:bg-blue-700"},{label:"Settings",icon:Da,action:()=>a==null?void 0:a("settings"),color:"bg-slate-600 hover:bg-slate-700"}];return t&&r.splice(2,0,{label:"Reports",icon:ts,action:()=>a==null?void 0:a("detailed-reports"),color:"bg-purple-600 hover:bg-purple-700"}),r}function gd({onNavigate:t,onNewRequest:s}){const{user:a}=Kt(),r=yn(),n=Sr(dt=>dt.dashboard.viewAsUser),i=x.useMemo(()=>xi(a),[a]),l=i&&!n,o=x.useCallback(dt=>{r($y(dt))},[r]),c=By(),{dateRange:d,customStartDate:m,customEndDate:u,showCustomDatePicker:h,handleDateRangeChange:g,handleApplyCustomDate:p,resetCustomDates:y,setCustomStartDate:b,setCustomEndDate:j,setShowCustomDatePicker:v}=c,w=Uy(),{activity:N,critical:C,deadlines:S,approver:E,updateActivityPagination:P,updateCriticalPagination:R,updateDeadlinesPagination:f,updateApproverPagination:T,handleActivityPageChange:F,handleCriticalPageChange:K,handleDeadlinesPageChange:B,handleApproverPageChange:U}=w,D=zy({isAdmin:l,viewAsUser:i&&n,userId:a==null?void 0:a.userId,dateRange:d,customStartDate:m,customEndDate:u,onPaginationUpdate:{activity:P,critical:R,deadlines:f,approver:T}}),{kpis:A,recentActivity:k,criticalRequests:M,departmentStats:O,priorityDistribution:L,upcomingDeadlines:Z,aiRemarkUtilization:z,approverPerformance:$,loading:W,refreshing:_,fetchDashboardData:G,fetchRecentActivities:H,fetchCriticalRequests:V,fetchUpcomingDeadlines:ee,fetchApproverPerformance:oe}=D,pe=qy(),{exportingDeptStats:Pe,exportingApproverPerformance:Se,handleExportDepartmentStats:ne,handleExportApproverPerformance:de}=pe,le=x.useMemo(()=>cb(M),[M]),fe=x.useMemo(()=>db(Z),[Z]),st=x.useCallback(()=>{G(!0)},[d,m,u,G]),ae=x.useCallback(()=>{p(()=>{m&&u&&G(!1)})},[m,u,p,G]),je=x.useCallback(dt=>{F(dt,H)},[F,H]),gt=x.useCallback(dt=>{K(dt,V)},[K,V]),be=x.useCallback(dt=>{B(dt,ee)},[B,ee]),Oe=x.useCallback(dt=>{U(dt,()=>oe(dt))},[U,oe]);x.useEffect(()=>{d==="custom"?m&&u&&G(!1):G(!1)},[d,m,u,n]);const ut=x.useMemo(()=>Rb(i,s,t),[i,s,t]),wt=x.useCallback(dt=>{const is=Db(dt);t==null||t(is)},[t]);return W?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(ns,{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(eb,{isAdmin:i,effectiveIsAdmin:l,viewAsUser:n,onToggleView:o,quickActions:ut,userDisplayName:a==null?void 0:a.displayName,userEmail:a==null?void 0:a.email}),e.jsx(ab,{isAdmin:l,dateRange:d,customStartDate:m,customEndDate:u,showCustomDatePicker:h,refreshing:_,onDateRangeChange:g,onCustomStartDateChange:b,onCustomEndDateChange:j,onShowCustomDatePickerChange:v,onApplyCustomDate:ae,onResetCustomDates:y,onRefresh:st}),l?e.jsx(rb,{kpis:A,priorityDistribution:L,dateRange:d,customStartDate:m,customEndDate:u,onKPIClick:wt}):e.jsx(nb,{kpis:A,criticalRequests:M,dateRange:d,customStartDate:m,customEndDate:u,onKPIClick:wt,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(hb,{isAdmin:l,breachedRequests:le,pagination:C,onPageChange:gt,onNavigate:t}),e.jsx(bb,{isAdmin:l,recentActivity:k,pagination:N,refreshing:_,onPageChange:je,onRefresh:st,onNavigate:t,currentUserId:a==null?void 0:a.userId,currentUserDisplayName:a==null?void 0:a.displayName,currentUserEmail:a==null?void 0:a.email})]}),l&&A&&e.jsx(vb,{kpis:A,upcomingDeadlines:Z,criticalRequests:M,departmentStats:O,dateRange:d,customStartDate:m,customEndDate:u,exportingDeptStats:Pe,onKPIClick:wt,onExportDepartmentStats:ne}),!l&&A&&e.jsx(jb,{kpis:A}),l&&L.length>0&&e.jsx(Nb,{priorityDistribution:L,onNavigate:t}),l&&le.length>0&&e.jsx(Sb,{breachedRequests:le,pagination:C,dateRange:d,customStartDate:m,customEndDate:u,onPageChange:gt,onKPIClick:wt,onNavigate:t}),fe.length>0&&e.jsx(Ab,{isAdmin:l,upcomingDeadlines:fe,pagination:S,onPageChange:be,onNavigate:t}),l&&z&&e.jsx(Tb,{aiRemarkUtilization:z}),l&&$.length>0&&e.jsx(kb,{approverPerformance:$,pagination:E,dateRange:d,customStartDate:m,customEndDate:u,loading:W,exportingApproverPerformance:Se,onPageChange:Oe,onExport:de,onNavigate:t})]})}const Pb={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",sortBy:"created",sortOrder:"desc",currentPage:1},Qu=wr({name:"openRequests",initialState:Pb,reducers:{setSearchTerm:(t,s)=>{t.searchTerm=s.payload},setStatusFilter:(t,s)=>{t.statusFilter=s.payload},setPriorityFilter:(t,s)=>{t.priorityFilter=s.payload},setTemplateTypeFilter:(t,s)=>{t.templateTypeFilter=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.templateTypeFilter="all",t.currentPage=1}}}),{setSearchTerm:Ib,setStatusFilter:Eb,setPriorityFilter:Mb,setTemplateTypeFilter:Fb,setSortBy:_b,setSortOrder:Lb,setCurrentPage:Ob,clearFilters:$b}=Qu.actions;function Bb(){const t=yn(),{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,sortBy:i,sortOrder:l,currentPage:o}=Sr(j=>j.openRequests),c=x.useCallback(j=>t(Ib(j)),[t]),d=x.useCallback(j=>t(Eb(j)),[t]),m=x.useCallback(j=>t(Mb(j)),[t]),u=x.useCallback(j=>t(Fb(j)),[t]),h=x.useCallback(j=>t(_b(j)),[t]),g=x.useCallback(j=>t(Lb(j)),[t]),p=x.useCallback(j=>t(Ob(j)),[t]),y=x.useCallback(()=>t($b()),[t]),b=[s,r!=="all"?r:null,a!=="all"?a:null,n!=="all"?n:null].filter(Boolean).length;return{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,sortBy:i,sortOrder:l,currentPage:o,setSearchTerm:c,setStatusFilter:d,setPriorityFilter:m,setTemplateTypeFilter:u,setSortBy:h,setSortOrder:g,setCurrentPage:p,clearFilters:y,activeFiltersCount:b}}function Bi(){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 Ub(t){var o;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,g=u.tat??"";let p=0;typeof g=="number"&&(p=u.tatType==="days"?g*24:g);const y=u.email||"",b=u.name&&u.name.trim()||y.split("@")[0]||`Approver ${h}`;return{levelNumber:h,levelName:`Level ${h}`,approverId:Bi(),approverEmail:y,approverName:b,tatHours:p>0?p:24,isFinalApprover:h===(t.approverCount||1)}}),r=[...(t.spectators||[]).map(c=>({userId:Bi(),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:Bi(),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 ye.post("/workflows",n),l=((o=i.data)==null?void 0:o.data)||i.data;return{id:l.id||l.workflowId||""}}async function qu(t,s,a="SUPPORTING"){var o;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 ye.post("/workflows/multipart",n,{headers:{"Content-Type":"multipart/form-data"}}),l=((o=i.data)==null?void 0:o.data)||i.data;return{id:l==null?void 0:l.requestId}}async function Vb(t={}){var y;const{page:s=1,limit:a=20,search:r,status:n,priority:i,templateType:l,department:o,initiator:c,approver:d,slaCompliance:m,dateRange:u,startDate:h,endDate:g}=t,p=await ye.get("/workflows",{params:{page:s,limit:a,search:r,status:n,priority:i,templateType:l,department:o,initiator:c,approver:d,slaCompliance:m,dateRange:u,startDate:h,endDate:g}});return((y=p.data)==null?void 0:y.data)||p.data}async function zb(t={}){var b,j,v,w,N;const{page:s=1,limit:a=20,search:r,status:n,priority:i,templateType:l,department:o,initiator:c,approver:d,approverType:m,slaCompliance:u,dateRange:h,startDate:g,endDate:p}=t,y=await ye.get("/workflows/participant-requests",{params:{page:s,limit:a,search:r,status:n,priority:i,templateType:l,department:o,initiator:c,approver:d,approverType:m,slaCompliance:u,dateRange:h,startDate:g,endDate:p}});return{data:((j=(b=y.data)==null?void 0:b.data)==null?void 0:j.data)||((v=y.data)==null?void 0:v.data)||[],pagination:((N=(w=y.data)==null?void 0:w.data)==null?void 0:N.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Hb(t={}){var p,y,b,j,v;const{page:s=1,limit:a=20,search:r,status:n,priority:i,department:l,initiator:o,approver:c,slaCompliance:d,dateRange:m,startDate:u,endDate:h}=t,g=await ye.get("/workflows/my",{params:{page:s,limit:a,search:r,status:n,priority:i,department:l,initiator:o,approver:c,slaCompliance:d,dateRange:m,startDate:u,endDate:h}});return{data:((y=(p=g.data)==null?void 0:p.data)==null?void 0:y.data)||((b=g.data)==null?void 0:b.data)||[],pagination:((v=(j=g.data)==null?void 0:j.data)==null?void 0:v.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Wb(t={}){var g,p,y,b,j;const{page:s=1,limit:a=20,search:r,status:n,priority:i,templateType:l,department:o,slaCompliance:c,dateRange:d,startDate:m,endDate:u}=t,h=await ye.get("/workflows/my-initiated",{params:{page:s,limit:a,search:r,status:n,priority:i,templateType:l,department:o,slaCompliance:c,dateRange:d,startDate:m,endDate:u}});return{data:((p=(g=h.data)==null?void 0:g.data)==null?void 0:p.data)||((y=h.data)==null?void 0:y.data)||[],pagination:((j=(b=h.data)==null?void 0:b.data)==null?void 0:j.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Gb(t={}){var m,u,h,g,p;const{page:s=1,limit:a=20,search:r,status:n,priority:i,templateType:l,sortBy:o,sortOrder:c}=t,d=await ye.get("/workflows/open-for-me",{params:{page:s,limit:a,search:r,status:n,priority:i,templateType:l,sortBy:o,sortOrder:c}});return{data:((u=(m=d.data)==null?void 0:m.data)==null?void 0:u.data)||((h=d.data)==null?void 0:h.data)||[],pagination:((p=(g=d.data)==null?void 0:g.data)==null?void 0:p.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Kb(t={}){var m,u,h,g,p;const{page:s=1,limit:a=20,search:r,status:n,priority:i,templateType:l,sortBy:o,sortOrder:c}=t,d=await ye.get("/workflows/closed-by-me",{params:{page:s,limit:a,search:r,status:n,priority:i,templateType:l,sortBy:o,sortOrder:c}});return{data:((u=(m=d.data)==null?void 0:m.data)==null?void 0:u.data)||((h=d.data)==null?void 0:h.data)||[],pagination:((p=(g=d.data)==null?void 0:g.data)==null?void 0:p.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Ts(t,s){var r;const a=await ye.get(`/workflows/${t}/details`);return((r=a.data)==null?void 0:r.data)||a.data}async function xr(t){var a;const s=await ye.get(`/workflows/${t}/work-notes`);return((a=s.data)==null?void 0:a.data)||s.data}async function eh(t,s,a=[]){var i;const r=new FormData;r.append("payload",JSON.stringify(s||{})),a.forEach(l=>r.append("files",l));const n=await ye.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 th(t,s,a,r){var i;const n=await ye.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 Yb(t,s,a){var n;const r=await ye.post(`/workflows/${t}/approvals/${s}/skip`,{reason:a});return((n=r.data)==null?void 0:n.data)||r.data}async function sh(t,s){var r;const a=await ye.post(`/workflows/${t}/participants/spectator`,{email:s});return((r=a.data)==null?void 0:r.data)||a.data}async function Zb(t,s,a,r){var i;const n=await ye.post(`/workflows/${t}/pause`,{levelId:s,reason:a,resumeDate:r.toISOString()});return((i=n.data)==null?void 0:i.data)||n.data}async function Xb(t,s){var r;const a=await ye.post(`/workflows/${t}/resume`,{notes:s});return((r=a.data)==null?void 0:r.data)||a.data}async function Jb(t){var a;const s=await ye.post(`/workflows/${t}/pause/retrigger`);return((a=s.data)==null?void 0:a.data)||s.data}async function fd(t){var a;const s=await ye.get(`/workflows/${t}/pause`);return((a=s.data)==null?void 0:a.data)||s.data}function Qb(t){return`https://re-workflow-nt-dev.siplsolutions.com//api/v1/workflows/work-notes/attachments/${t}/preview`}function ho(t){return`https://re-workflow-nt-dev.siplsolutions.com//api/v1/workflows/documents/${t}/preview`}function ah(t){var r;if(!t)return"download";const s=t.match(/filename\*=UTF-8''([^;]+)/);if(s&&s[1])try{return decodeURIComponent(s[1])}catch{}const a=t.match(/filename="?([^";]+)"?/);return a&&a.length>1&&a[1]&&((r=a[1].replace(/^"|"$/g,"").split(";")[0])==null?void 0:r.trim())||"download"}async function nr(t){const a=`https://re-workflow-nt-dev.siplsolutions.com//api/v1/workflows/documents/${t}/download`,r=!0;try{const i=await fetch(a,{credentials:"include"});if(!i.ok){const u=await i.text();throw new Error(`Download failed: ${i.status} - ${u}`)}const l=await i.blob(),o=window.URL.createObjectURL(l),c=i.headers.get("Content-Disposition"),d=ah(c),m=document.createElement("a");m.href=o,m.download=d,document.body.appendChild(m),m.click(),document.body.removeChild(m),window.URL.revokeObjectURL(o)}catch(n){throw console.error("[Download] Failed:",n),n}}async function yd(t){const a=`https://re-workflow-nt-dev.siplsolutions.com//api/v1/workflows/work-notes/attachments/${t}/download`,r=!0;try{const i=await fetch(a,{credentials:"include"});if(!i.ok){const u=await i.text();throw new Error(`Download failed: ${i.status} - ${u}`)}const l=await i.blob(),o=window.URL.createObjectURL(l),c=i.headers.get("Content-Disposition"),d=ah(c),m=document.createElement("a");m.href=o,m.download=d,document.body.appendChild(m),m.click(),document.body.removeChild(m),window.URL.revokeObjectURL(o)}catch(n){throw console.error("[Download] Failed:",n),n}}const ws={createWorkflowFromForm:Ub,createWorkflowMultipart:qu,listWorkflows:Vb,listParticipantRequests:zb,listMyWorkflows:Hb,listMyInitiatedWorkflows:Wb,listOpenForMe:Gb,listClosedByMe:Kb,submitWorkflow:rh,getWorkflowDetails:Ts,getWorkNotes:xr,createWorkNoteMultipart:eh};async function rh(t){var a;const s=await ye.patch(`/workflows/${t}/submit`);return((a=s.data)==null?void 0:a.data)||s.data}async function qb(t,s){var r;const a=await ye.put(`/workflows/${t}`,s);return((r=a.data)==null?void 0:r.data)||a.data}async function ev(t,s,a,r){var o;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 l=await ye.put(`/workflows/${t}/multipart`,i,{headers:{"Content-Type":"multipart/form-data"}});return((o=l.data)==null?void 0:o.data)||l.data}async function Jr(t,s,a){var n;const r=await ye.patch(`/workflows/${t}/approvals/${s}/approve`,{action:"APPROVE",comments:a||""});return((n=r.data)==null?void 0:n.data)||r.data}async function Qr(t,s,a,r){var i;const n=await ye.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 tv(t,s){const a=await ye.put(`/tat/breach-reason/${t}`,{breachReason:s});if(!a.data.success)throw new Error(a.data.error||"Failed to update breach reason")}function es(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 nh(t){return es(t,{includeTime:!1,format:"short"})}function qs(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()],l=a.getFullYear();if(s){const o=a.getHours(),c=o%12||12,d=String(a.getMinutes()).padStart(2,"0"),m=String(a.getSeconds()).padStart(2,"0"),u=o>=12?"PM":"AM";return`${r} ${i} ${l}, ${c}:${d}:${m} ${u}`}return`${r} ${i} ${l}`}catch(a){return console.error("Error formatting date:",a),String(t)}}const sv=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:ta,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Bt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Bt,iconColor:"text-gray-600"}}},av=t=>{switch(t){case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:Ze,iconColor:"text-yellow-600",label:"Pending"};case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:We,iconColor:"text-green-600",label:"Needs Closure"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:xt,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:We,iconColor:"text-gray-600",label:t}}};function rv({onViewRequest:t}){const[s,a]=x.useState([]),[r,n]=x.useState(!1),[i,l]=x.useState(!1),[o,c]=x.useState(1),[d,m]=x.useState(0),[u]=x.useState(10),h=x.useRef(null),g=Bb(),p=x.useCallback(async(N=1,C)=>{try{N===1&&(n(!0),a([]));const S=await ws.listOpenForMe({page:N,limit:u,search:C==null?void 0:C.search,status:C==null?void 0:C.status,priority:C==null?void 0:C.priority,templateType:C==null?void 0:C.templateType,sortBy:C==null?void 0:C.sortBy,sortOrder:C==null?void 0:C.sortOrder}),E=Array.isArray(S==null?void 0:S.data)?S.data:[],P=S==null?void 0:S.pagination;P&&(g.setCurrentPage(P.page||1),c(P.totalPages||1),m(P.total||0));const R=E.map(f=>{var F,K,B,U;const T=f.submittedAt||f.submitted_at||f.createdAt||f.created_at;return{id:f.requestNumber||f.request_number||f.requestId,requestId:f.requestId,displayId:f.requestNumber||f.request_number||f.requestId,title:f.title,description:f.description,status:(f.status||"").toString().toLowerCase().replace("_","-"),priority:(f.priority||"").toString().toLowerCase(),initiator:{name:((F=f.initiator)==null?void 0:F.displayName)||((K=f.initiator)==null?void 0:K.email)||"—",avatar:(((B=f.initiator)==null?void 0:B.displayName)||((U=f.initiator)==null?void 0:U.email)||"NA").split(" ").map(D=>D[0]).join("").slice(0,2).toUpperCase()},currentApprover:f.currentApprover?{name:f.currentApprover.name||f.currentApprover.email||"—",avatar:(f.currentApprover.name||f.currentApprover.email||"CA").split(" ").map(D=>D[0]).join("").slice(0,2).toUpperCase(),sla:f.currentApprover.sla}:void 0,createdAt:T||"—",approvalStep:f.currentLevel?`Step ${f.currentLevel} of ${f.totalLevels||"?"}`:void 0,department:f.department,currentLevelSLA:f.currentLevelSLA,templateType:f.templateType||f.template_type}});a(R)}finally{n(!1),l(!1)}},[u,g]);h.current=p;const y=()=>{l(!0),p(g.currentPage,{search:g.searchTerm||void 0,status:g.statusFilter!=="all"?g.statusFilter:void 0,priority:g.priorityFilter!=="all"?g.priorityFilter:void 0,templateType:g.templateTypeFilter!=="all"?g.templateTypeFilter:void 0,sortBy:g.sortBy,sortOrder:g.sortOrder})},b=N=>{N>=1&&N<=o&&(g.setCurrentPage(N),p(N,{search:g.searchTerm||void 0,status:g.statusFilter!=="all"?g.statusFilter:void 0,priority:g.priorityFilter!=="all"?g.priorityFilter:void 0,templateType:g.templateTypeFilter!=="all"?g.templateTypeFilter:void 0,sortBy:g.sortBy,sortOrder:g.sortOrder}))},j=()=>{const N=[];let S=Math.max(1,g.currentPage-Math.floor(2.5)),E=Math.min(o,S+5-1);E-S<4&&(S=Math.max(1,E-5+1));for(let P=S;P<=E;P++)N.push(P);return N},v=x.useRef(!1);x.useEffect(()=>{if(!v.current){v.current=!0;const N=g.currentPage||1;p(N,{search:g.searchTerm||void 0,status:g.statusFilter!=="all"?g.statusFilter:void 0,priority:g.priorityFilter!=="all"?g.priorityFilter:void 0,templateType:g.templateTypeFilter!=="all"?g.templateTypeFilter:void 0,sortBy:g.sortBy,sortOrder:g.sortOrder})}},[]),x.useEffect(()=>{if(!v.current)return;const N=setTimeout(()=>{g.setCurrentPage(1),p(1,{search:g.searchTerm||void 0,status:g.statusFilter!=="all"?g.statusFilter:void 0,priority:g.priorityFilter!=="all"?g.priorityFilter:void 0,templateType:g.templateTypeFilter!=="all"?g.templateTypeFilter:void 0,sortBy:g.sortBy,sortOrder:g.sortOrder})},g.searchTerm?500:0);return()=>clearTimeout(N)},[g.searchTerm,g.statusFilter,g.priorityFilter,g.templateTypeFilter,g.sortBy,g.sortOrder]);const w=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(Le,{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(ie,{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(I,{variant:"outline",size:"sm",className:"gap-1 sm:gap-2 h-8 sm:h-9",onClick:y,disabled:i,children:[e.jsx(ns,{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(te,{className:"shadow-lg border-0",children:[e.jsx(me,{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(gn,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(he,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(De,{className:"text-xs sm:text-sm",children:g.activeFiltersCount>0&&e.jsxs("span",{className:"text-blue-600 font-medium",children:[g.activeFiltersCount," filter",g.activeFiltersCount>1?"s":""," active"]})})]})]}),g.activeFiltersCount>0&&e.jsxs(I,{variant:"ghost",size:"sm",onClick:g.clearFilters,className:"text-red-600 hover:bg-red-50 gap-1 h-8 sm:h-9 px-2 sm:px-3",children:[e.jsx(pt,{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(se,{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-5 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx($s,{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(Re,{placeholder:"Search requests, IDs...",value:g.searchTerm,onChange:N=>g.setSearchTerm(N.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(Ue,{value:g.priorityFilter,onValueChange:g.setPriorityFilter,children:[e.jsx(ze,{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(Ve,{placeholder:"All Priorities"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"all",children:"All Priorities"}),e.jsx(Y,{value:"express",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ta,{className:"w-4 h-4 text-orange-600"}),e.jsx("span",{children:"Express"})]})}),e.jsx(Y,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bt,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(Ue,{value:g.statusFilter,onValueChange:g.setStatusFilter,children:[e.jsx(ze,{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(Ve,{placeholder:"All Statuses"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"all",children:"All Statuses"}),e.jsx(Y,{value:"pending",children:"Pending (In Approval)"}),e.jsx(Y,{value:"approved",children:"Approved (Needs Closure)"})]})]}),e.jsxs(Ue,{value:g.templateTypeFilter,onValueChange:g.setTemplateTypeFilter,children:[e.jsx(ze,{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(Ve,{placeholder:"All Templates"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"all",children:"All Templates"}),e.jsx(Y,{value:"CUSTOM",children:"Custom"}),e.jsx(Y,{value:"DEALER CLAIM",children:"Dealer Claim"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ue,{value:g.sortBy,onValueChange:N=>g.setSortBy(N),children:[e.jsx(ze,{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(Ve,{placeholder:"Sort by"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"due",children:"Due Date"}),e.jsx(Y,{value:"created",children:"Date Created"}),e.jsx(Y,{value:"priority",children:"Priority"}),e.jsx(Y,{value:"sla",children:"SLA Progress"})]})]}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>g.setSortOrder(g.sortOrder==="asc"?"desc":"asc"),className:"px-2 sm:px-3 h-9 sm:h-10 md:h-11",children:g.sortOrder==="asc"?e.jsx(bu,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(vu,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]}),e.jsx("div",{className:"space-y-3",children:w.map(N=>{const C=sv(N.priority),S=av(N.status);return e.jsx(te,{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(N.id,N.title),children:e.jsx(se,{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 ${C.color} border shadow-sm`,children:e.jsx(C.icon,{className:`w-5 h-5 ${C.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:N.displayId||N.id}),e.jsxs(ie,{variant:"outline",className:`${S.color} text-xs px-2.5 py-0.5 font-semibold shrink-0`,children:[e.jsx(S.icon,{className:"w-3.5 h-3.5 mr-1"}),S.label||N.status]}),N.department&&e.jsx(ie,{variant:"secondary",className:"bg-blue-50 text-blue-700 text-xs px-2.5 py-0.5 hidden sm:inline-flex",children:N.department}),e.jsx(ie,{variant:"outline",className:`${C.color} text-xs px-2.5 py-0.5 capitalize hidden md:inline-flex`,children:N.priority}),(()=>{const E=(N==null?void 0:N.templateType)||(N==null?void 0:N.template_type)||"",P=(E==null?void 0:E.toUpperCase())||"";let R="Custom",f="bg-purple-100 !text-purple-600 border-purple-200";return P==="DEALER CLAIM"?(R="Dealer Claim",f="bg-blue-100 !text-blue-700 border-blue-200"):P==="TEMPLATE"&&(R="Template"),e.jsx(ie,{variant:"outline",className:`${f} text-xs px-2.5 py-0.5 shrink-0 hidden md:inline-flex`,"data-testid":"template-type-badge",children:R})})()]}),e.jsx("h4",{className:"text-sm font-semibold text-gray-800 line-clamp-1 leading-relaxed",children:N.title}),N.currentLevelSLA&&(()=>{var T;const E=!!(N.isPaused||(T=N.pauseInfo)!=null&&T.isPaused||N.status==="paused"),P=N.currentLevelSLA.percentageUsed||0,f=E?{bg:"bg-gray-100 border border-gray-300",progress:"bg-gray-500",text:"text-gray-600",icon:"text-gray-600"}:P>=100?{bg:"bg-red-50 border border-red-200",progress:"bg-red-600",text:"text-red-600",icon:"text-blue-600"}:P>=75?{bg:"bg-orange-50 border border-orange-200",progress:"bg-orange-500",text:"text-orange-600",icon:"text-blue-600"}:P>=50?{bg:"bg-amber-50 border border-amber-200",progress:"bg-amber-500",text:"text-amber-600",icon:"text-blue-600"}:{bg:"bg-green-50 border border-green-200",progress:"bg-green-600",text:"text-gray-700",icon:"text-blue-600"};return e.jsxs("div",{className:`p-2 rounded-md ${f.bg}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[E?e.jsx(on,{className:`w-3.5 h-3.5 ${f.icon}`}):e.jsx(Ze,{className:`w-3.5 h-3.5 ${f.icon}`}),e.jsxs("span",{className:"text-xs font-medium text-gray-900",children:["TAT: ",P,"% ",E&&"(paused)"]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"text-gray-600",children:N.currentLevelSLA.elapsedText}),e.jsxs("span",{className:`font-semibold ${f.text}`,children:[N.currentLevelSLA.remainingText," left"]})]})]}),e.jsx(Qs,{value:P,className:"h-1.5",indicatorClassName:f.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(Qt,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(qt,{className:"bg-gradient-to-br from-slate-700 to-slate-900 text-white text-[10px] font-bold",children:N.initiator.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:N.initiator.name})]}),N.currentApprover&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Qt,{className:"h-6 w-6 ring-2 ring-yellow-200 shadow-sm",children:e.jsx(qt,{className:"bg-yellow-500 text-white text-[10px] font-bold",children:N.currentApprover.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:N.currentApprover.name})]}),N.approvalStep&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(We,{className:"w-3.5 h-3.5 text-blue-500"}),e.jsx("span",{className:"font-medium",children:N.approvalStep})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(mt,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",N.createdAt!=="—"?qs(N.createdAt):"—"]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(rs,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})},N.id)})}),w.length===0&&e.jsx(te,{className:"shadow-lg border-0",children:e.jsxs(se,{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(Le,{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:g.searchTerm||g.activeFiltersCount>0?"Try adjusting your filters or search terms to see more results.":"No open requests available at the moment."}),g.activeFiltersCount>0&&e.jsx(I,{variant:"outline",className:"mt-4",onClick:g.clearFilters,children:"Clear all filters"})]})}),o>1&&!r&&e.jsx(te,{className:"shadow-md",children:e.jsx(se,{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 ",(g.currentPage-1)*u+1," to ",Math.min(g.currentPage*u,d)," of ",d," open requests"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(I,{variant:"outline",size:"sm",onClick:()=>b(g.currentPage-1),disabled:g.currentPage===1,className:"h-8 w-8 p-0",children:e.jsx(rs,{className:"h-4 w-4 rotate-180"})}),g.currentPage>3&&o>5&&e.jsxs(e.Fragment,{children:[e.jsx(I,{variant:"outline",size:"sm",onClick:()=>b(1),className:"h-8 w-8 p-0",children:"1"}),e.jsx("span",{className:"text-muted-foreground",children:"..."})]}),j().map(N=>e.jsx(I,{variant:N===g.currentPage?"default":"outline",size:"sm",onClick:()=>b(N),className:`h-8 w-8 p-0 ${N===g.currentPage?"bg-re-green text-white hover:bg-re-green/90":""}`,children:N},N)),g.currentPage<o-2&&o>5&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"..."}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>b(o),className:"h-8 w-8 p-0",children:o})]}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>b(g.currentPage+1),disabled:g.currentPage===o,className:"h-8 w-8 p-0",children:e.jsx(rs,{className:"h-4 w-4"})})]})]})})})]})}function nv({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(Le,{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(ie,{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(I,{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(ns,{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 iv({searchTerm:t,priorityFilter:s,statusFilter:a,templateTypeFilter:r,sortBy:n,sortOrder:i,activeFiltersCount:l,onSearchChange:o,onPriorityChange:c,onStatusChange:d,onTemplateTypeChange:m,onSortByChange:u,onSortOrderChange:h,onClearFilters:g}){return e.jsxs(te,{className:"shadow-lg border-0","data-testid":"closed-requests-filters",children:[e.jsx(me,{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(gn,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(he,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(De,{className:"text-xs sm:text-sm",children:l>0&&e.jsxs("span",{className:"text-blue-600 font-medium",children:[l," filter",l>1?"s":""," active"]})})]})]}),l>0&&e.jsxs(I,{variant:"ghost",size:"sm",onClick:g,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(pt,{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(se,{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-5 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx($s,{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(Re,{placeholder:"Search requests, IDs...",value:t,onChange:p=>o(p.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(Ue,{value:s,onValueChange:c,children:[e.jsx(ze,{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(Ve,{placeholder:"All Priorities"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"all",children:"All Priorities"}),e.jsx(Y,{value:"express",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ta,{className:"w-4 h-4 text-orange-600"}),e.jsx("span",{children:"Express"})]})}),e.jsx(Y,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bt,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(Ue,{value:a,onValueChange:d,children:[e.jsx(ze,{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(Ve,{placeholder:"Closure Type"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"all",children:"All Closures"}),e.jsx(Y,{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(Y,{value:"rejected",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xt,{className:"w-4 h-4 text-red-600"}),e.jsx("span",{children:"Closed After Rejection"})]})})]})]}),e.jsxs(Ue,{value:r,onValueChange:m,children:[e.jsx(ze,{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-template-type-filter",children:e.jsx(Ve,{placeholder:"All Templates"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"all",children:"All Templates"}),e.jsx(Y,{value:"CUSTOM",children:"Custom"}),e.jsx(Y,{value:"DEALER CLAIM",children:"Dealer Claim"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ue,{value:n,onValueChange:p=>u(p),children:[e.jsx(ze,{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(Ve,{placeholder:"Sort by"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"due",children:"Due Date"}),e.jsx(Y,{value:"created",children:"Date Created"}),e.jsx(Y,{value:"priority",children:"Priority"})]})]}),e.jsx(I,{variant:"outline",size:"sm",onClick:h,className:"px-2 sm:px-3 h-9 sm:h-10 md:h-11","data-testid":"closed-requests-sort-order",children:i==="asc"?e.jsx(bu,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(vu,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function lv(t){switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:ta,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Bt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Bt,iconColor:"text-gray-600"}}}function ov(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:xt,iconColor:"text-red-600",label:"Rejected",description:"Request was declined"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:We,iconColor:"text-gray-600",label:t,description:""}}}function cv({request:t,onViewRequest:s}){const a=lv(t.priority),r=ov(t.status),n=a.icon,i=r.icon;return e.jsx(te,{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(se,{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(ie,{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(ie,{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(ie,{variant:"outline",className:`${a.color} text-xs px-2.5 py-0.5 capitalize hidden md:inline-flex`,children:t.priority}),(()=>{const l=t.templateType||"",o=(l==null?void 0:l.toUpperCase())||"";let c="Custom",d="bg-purple-100 !text-purple-600 border-purple-200";return o==="DEALER CLAIM"?(c="Dealer Claim",d="bg-blue-100 !text-blue-700 border-blue-200"):o==="TEMPLATE"&&(c="Template"),e.jsx(ie,{variant:"outline",className:`${d} text-xs px-2.5 py-0.5 shrink-0 hidden md:inline-flex`,"data-testid":"template-type-badge",children:c})})()]}),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(Qt,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(qt,{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(mt,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",t.createdAt!=="—"?qs(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: ",qs(t.dueDate,!0)]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(rs,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})})}function dv({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(cv,{request:r,onViewRequest:a},r.id))})}function mv({searchTerm:t,activeFiltersCount:s,onClearFilters:a}){return e.jsx(te,{className:"shadow-lg border-0","data-testid":"closed-requests-empty",children:e.jsxs(se,{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(Le,{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(I,{variant:"outline",className:"mt-4",onClick:a,"data-testid":"closed-requests-empty-clear-filters",children:"Clear all filters"})]})})}function uv(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 l=n;l<=i;l++)a.push(l);return a}function hv({pagination:t,onPageChange:s}){const{currentPage:a,totalPages:r,totalRecords:n,itemsPerPage:i}=t;if(r<=1)return null;const l=uv(a,r);return e.jsx(te,{className:"shadow-md","data-testid":"closed-requests-pagination",children:e.jsx(se,{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(I,{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(rs,{className:"h-4 w-4 rotate-180"})}),a>3&&r>5&&e.jsxs(e.Fragment,{children:[e.jsx(I,{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:"..."})]}),l.map(o=>e.jsx(I,{variant:o===a?"default":"outline",size:"sm",onClick:()=>s(o),className:`h-8 w-8 p-0 ${o===a?"bg-re-green text-white hover:bg-re-green/90":""}`,"data-testid":`closed-requests-pagination-page-${o}`,children:o},o)),a<r-2&&r>5&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"..."}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>s(r),className:"h-8 w-8 p-0","data-testid":"closed-requests-pagination-last",children:r})]}),e.jsx(I,{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(rs,{className:"h-4 w-4"})})]})]})})})}function pv(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,templateType:t.templateType||t.template_type}}function xv(t){return t.map(pv)}function gv({itemsPerPage:t=10}={}){const[s,a]=x.useState([]),[r,n]=x.useState(!1),[i,l]=x.useState(!1),[o,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 g=await ws.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,templateType:h==null?void 0:h.templateType,sortBy:h==null?void 0:h.sortBy,sortOrder:h==null?void 0:h.sortOrder}),p=Array.isArray(g==null?void 0:g.data)?g.data:[],y=xv(p);a(y);const b=g==null?void 0:g.pagination;b&&c({currentPage:b.page||1,totalPages:b.totalPages||1,totalRecords:b.total||0,itemsPerPage:t})}catch(g){console.error("[ClosedRequests] Error fetching requests:",g),a([])}finally{n(!1),l(!1)}},[t]),m=x.useCallback(u=>{l(!0),d(o.currentPage,u)},[d,o.currentPage]);return{requests:s,loading:r,refreshing:i,pagination:o,fetchRequests:d,handleRefresh:m}}const fv={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",sortBy:"created",sortOrder:"desc",currentPage:1},ih=wr({name:"closedRequests",initialState:fv,reducers:{setSearchTerm:(t,s)=>{t.searchTerm=s.payload},setStatusFilter:(t,s)=>{t.statusFilter=s.payload},setPriorityFilter:(t,s)=>{t.priorityFilter=s.payload},setTemplateTypeFilter:(t,s)=>{t.templateTypeFilter=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.templateTypeFilter="all",t.currentPage=1}}}),{setSearchTerm:yv,setStatusFilter:bv,setPriorityFilter:vv,setTemplateTypeFilter:jv,setSortBy:Nv,setSortOrder:wv,setCurrentPage:Cv,clearFilters:Sv}=ih.actions;function Av({onFiltersChange:t,debounceMs:s=500}={}){const a=yn(),r=x.useRef(null),n=x.useRef(!0),{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:c,sortBy:d,sortOrder:m,currentPage:u}=Sr(S=>S.closedRequests),h=x.useCallback(S=>a(yv(S)),[a]),g=x.useCallback(S=>a(bv(S)),[a]),p=x.useCallback(S=>a(vv(S)),[a]),y=x.useCallback(S=>a(jv(S)),[a]),b=x.useCallback(S=>a(Nv(S)),[a]),j=x.useCallback(S=>a(wv(S)),[a]),v=x.useCallback(S=>a(Cv(S)),[a]),w=x.useCallback(()=>({search:i,status:l,priority:o,templateType:c!=="all"?c:void 0,sortBy:d,sortOrder:m}),[i,l,o,c,d,m]);x.useEffect(()=>{if(n.current){n.current=!1;return}r.current&&clearTimeout(r.current);const S=setTimeout(()=>{t&&t(w())},i?s:0);return r.current=S,()=>{r.current&&clearTimeout(r.current)}},[i,l,o,c,d,m,t,w,s]);const N=x.useCallback(()=>{a(Sv())},[a]),C=[i,o!=="all"?o:null,l!=="all"?l:null,c!=="all"?c:null].filter(Boolean).length;return{searchTerm:i,priorityFilter:o,statusFilter:l,templateTypeFilter:c,sortBy:d,sortOrder:m,currentPage:u,setSearchTerm:h,setPriorityFilter:p,setStatusFilter:g,setTemplateTypeFilter:y,setSortBy:b,setSortOrder:j,setCurrentPage:v,clearFilters:N,activeFiltersCount:C,getFilters:w}}function Tv({onViewRequest:t}){const s=gv({itemsPerPage:10}),a=x.useRef(s.fetchRequests);a.current=s.fetchRequests;const r=Av(),n=x.useRef({searchTerm:r.searchTerm,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,templateTypeFilter:r.templateTypeFilter,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,templateType:r.templateTypeFilter!=="all"?r.templateTypeFilter: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.templateTypeFilter!==r.templateTypeFilter||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,templateType:r.templateTypeFilter!=="all"?r.templateTypeFilter:void 0,sortBy:r.sortBy,sortOrder:r.sortOrder}),n.current={searchTerm:r.searchTerm,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,templateTypeFilter:r.templateTypeFilter,sortBy:r.sortBy,sortOrder:r.sortOrder}},r.searchTerm!==c.searchTerm?500:0);return()=>clearTimeout(m)},[r.searchTerm,r.statusFilter,r.priorityFilter,r.templateTypeFilter,r.sortBy,r.sortOrder]);const l=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,templateType:r.templateTypeFilter!=="all"?r.templateTypeFilter:void 0,sortBy:r.sortBy,sortOrder:r.sortOrder}))},[s,r]),o=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,templateType:r.templateTypeFilter!=="all"?r.templateTypeFilter: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(nv,{totalRecords:s.pagination.totalRecords,loading:s.loading,refreshing:s.refreshing,onRefresh:o}),e.jsx(iv,{searchTerm:r.searchTerm,priorityFilter:r.priorityFilter,statusFilter:r.statusFilter,templateTypeFilter:r.templateTypeFilter,sortBy:r.sortBy,sortOrder:r.sortOrder,activeFiltersCount:r.activeFiltersCount,onSearchChange:r.setSearchTerm,onPriorityChange:r.setPriorityFilter,onStatusChange:r.setStatusFilter,onTemplateTypeChange:r.setTemplateTypeFilter,onSortByChange:r.setSortBy,onSortOrderChange:()=>r.setSortOrder(r.sortOrder==="asc"?"desc":"asc"),onClearFilters:r.clearFilters}),e.jsx(dv,{requests:s.requests,loading:s.loading,onViewRequest:t}),s.requests.length===0&&!s.loading&&e.jsx(mv,{searchTerm:r.searchTerm,activeFiltersCount:r.activeFiltersCount,onClearFilters:r.clearFilters}),!s.loading&&e.jsx(hv,{pagination:s.pagination,onPageChange:l})]})}const lh={"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"]}},kv={"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 po(t,s=[],a){const[r,n]=x.useState(null),[i,l]=x.useState(!1),[o,c]=x.useState(!0),[d,m]=x.useState(null),[u,h]=x.useState(null),[g,p]=x.useState(!1),y=(C,S)=>(C||S||"NA").toString().split(" ").map(P=>P[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),b=C=>{const S=(C||"").toUpperCase();return S==="IN_PROGRESS"?"in-review":S==="PENDING"?"pending":S==="APPROVED"?"approved":S==="REJECTED"?"rejected":S==="CLOSED"?"closed":S==="SKIPPED"?"skipped":(C||"").toLowerCase()},j=x.useCallback(async()=>{var C,S,E,P,R,f,T,F,K,B,U,D,A;l(!0);try{const k=await ws.getWorkflowDetails(t);if(!k){console.warn("[useRequestDetails] No details returned from API");return}const M=k.workflow||{},O=Array.isArray(k.approvals)?k.approvals:[],L=Array.isArray(k.participants)?k.participants:[],Z=Array.isArray(k.documents)?k.documents:[],z=k.summary||{},$=Array.isArray(k.tatAlerts)?k.tatAlerts:[];$.length>0;const W=(z==null?void 0:z.currentLevel)||M.currentLevel||1,_=O.map(ae=>{const je=ae.levelNumber||0,gt=(ae.status||"").toString().toUpperCase(),be=ae.levelId||ae.level_id;let Oe=b(ae.status);je>W&>!=="APPROVED"&>!=="REJECTED"?Oe="waiting":je===W&>==="PENDING"&&(Oe="pending");const ut=$.filter(wt=>wt.levelId===be);return{step:je,levelId:be,role:ae.levelName||ae.approverName||"Approver",status:Oe,approver:ae.approverName||ae.approverEmail,approverId:ae.approverId||ae.approver_id,approverEmail:ae.approverEmail,tatHours:Number(ae.tatHours||0),elapsedHours:Number(ae.elapsedHours||0),remainingHours:Number(ae.remainingHours||0),tatPercentageUsed:Number(ae.tatPercentageUsed||0),actualHours:ae.levelEndTime&&ae.levelStartTime?Math.max(0,(new Date(ae.levelEndTime).getTime()-new Date(ae.levelStartTime).getTime())/(1e3*60*60)):void 0,comment:ae.comments||void 0,timestamp:ae.actionDate||void 0,levelStartTime:ae.levelStartTime||ae.tatStartTime,tatAlerts:ut,skipReason:ae.skipReason||void 0,isSkipped:gt==="SKIPPED"||ae.isSkipped||!1}}),G=L.filter(ae=>(ae.participantType||ae.participant_type||"").toUpperCase()==="SPECTATOR").map(ae=>({name:ae.userName||ae.user_name||ae.userEmail||ae.user_email,role:"Spectator",email:ae.userEmail||ae.user_email,avatar:y(ae.userName||ae.user_name,ae.userEmail||ae.user_email)})),H=ae=>{var gt,be;if(!ae)return;const je=L.find(Oe=>Oe.userId===ae||Oe.user_id===ae);return je!=null&&je.userName||je!=null&&je.user_name?je.userName||je.user_name:M.initiatorId===ae?((gt=M.initiator)==null?void 0:gt.displayName)||((be=M.initiator)==null?void 0:be.email):ae},V=Z.map(ae=>{const je=Number(ae.fileSize||ae.file_size||0),gt=(je/(1024*1024)).toFixed(2)+" MB";return{documentId:ae.documentId||ae.document_id,name:ae.originalFileName||ae.fileName||ae.file_name,fileType:ae.fileType||ae.file_type||"",size:gt,sizeBytes:je,uploadedBy:H(ae.uploadedBy||ae.uploaded_by),uploadedAt:ae.uploadedAt||ae.uploaded_at}}),ee=Array.isArray(k.activities)?k.activities.filter(ae=>(ae.type||"").toLowerCase()!=="sla_warning"):[];let oe=null;try{oe=await fd(M.requestId)}catch(ae){console.debug("Pause details not available:",ae)}let pe=null,Pe=null,Se=null,ne=null;if(M.workflowType==="CLAIM_MANAGEMENT"||M.templateType==="claim-management")try{console.debug("[useRequestDetails] Fetching claim details for requestId:",M.requestId);const ae=await ye.get(`/dealer-claims/${M.requestId}`);console.debug("[useRequestDetails] Claim API response:",{status:ae.status,hasData:!!ae.data,dataKeys:ae.data?Object.keys(ae.data):[],fullResponse:ae.data});const je=((C=ae.data)==null?void 0:C.data)||ae.data;if(console.debug("[useRequestDetails] Extracted claimData:",{hasClaimData:!!je,claimDataKeys:je?Object.keys(je):[],hasClaimDetails:!!(je!=null&&je.claimDetails||je!=null&&je.claim_details),hasProposalDetails:!!(je!=null&&je.proposalDetails||je!=null&&je.proposal_details),hasCompletionDetails:!!(je!=null&&je.completionDetails||je!=null&&je.completion_details),hasInternalOrder:!!(je!=null&&je.internalOrder||je!=null&&je.internal_order)}),je){pe=je.claimDetails||je.claim_details,Pe=je.proposalDetails||je.proposal_details,Se=je.completionDetails||je.completion_details,ne=je.internalOrder||je.internal_order||null;const gt=je.budgetTracking||je.budget_tracking||null,be=je.invoice||null,Oe=je.creditNote||je.credit_note||null,ut=je.completionExpenses||je.completion_expenses||null;pe&&(pe.budgetTracking=gt,pe.invoice=be,pe.creditNote=Oe,pe.completionExpenses=ut),console.debug("[useRequestDetails] Extracted details:",{claimDetails:pe?{hasActivityName:!!(pe.activityName||pe.activity_name),hasActivityType:!!(pe.activityType||pe.activity_type),hasLocation:!!pe.location,activityName:pe.activityName||pe.activity_name,activityType:pe.activityType||pe.activity_type,location:pe.location,allKeys:Object.keys(pe)}:null,hasProposalDetails:!!Pe,hasCompletionDetails:!!Se,hasInternalOrder:!!ne,hasBudgetTracking:!!gt,hasInvoice:!!be,hasCreditNote:!!Oe,hasCompletionExpenses:Array.isArray(ut)&&ut.length>0})}else console.warn("[useRequestDetails] No claimData found in response")}catch(ae){console.error("[useRequestDetails] Error fetching claim details:",{error:(ae==null?void 0:ae.message)||ae,status:(S=ae==null?void 0:ae.response)==null?void 0:S.status,statusText:(E=ae==null?void 0:ae.response)==null?void 0:E.statusText,responseData:(P=ae==null?void 0:ae.response)==null?void 0:P.data,requestId:M.requestId})}const de={...M,id:M.requestNumber||M.requestId,requestId:M.requestId,requestNumber:M.requestNumber,title:M.title,description:M.description,status:b(M.status),priority:(M.priority||"").toString().toLowerCase(),workflowType:M.workflowType||(M.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),approvalFlow:_,approvals:O,participants:L,documents:V,spectators:G,summary:z,sla:(z==null?void 0:z.sla)||M.sla||null,initiator:{name:((R=M.initiator)==null?void 0:R.displayName)||((f=M.initiator)==null?void 0:f.email),role:((T=M.initiator)==null?void 0:T.designation)||void 0,department:((F=M.initiator)==null?void 0:F.department)||void 0,email:((K=M.initiator)==null?void 0:K.email)||void 0,phone:((B=M.initiator)==null?void 0:B.phone)||void 0,avatar:y((U=M.initiator)==null?void 0:U.displayName,(D=M.initiator)==null?void 0:D.email)},createdAt:M.createdAt,updatedAt:M.updatedAt,totalSteps:M.totalLevels||1,currentStepRaw:(z==null?void 0:z.currentLevel)||M.currentLevel||1,currentStep:Math.min(Math.max(1,(z==null?void 0:z.currentLevel)||M.currentLevel||1),M.totalLevels||1),auditTrail:ee,conclusionRemark:M.conclusionRemark||null,closureDate:M.closureDate||null,pauseInfo:oe||null,claimDetails:pe||null,proposalDetails:Pe||null,completionDetails:Se||null,internalOrder:ne||null,budgetTracking:(pe==null?void 0:pe.budgetTracking)||null,invoice:(pe==null?void 0:pe.invoice)||null,creditNote:(pe==null?void 0:pe.creditNote)||null,completionExpenses:(pe==null?void 0:pe.completionExpenses)||null};n(de);const le=(A=a==null?void 0:a.email)==null?void 0:A.toLowerCase(),fe=O.find(ae=>{const je=(ae.status||"").toString().toUpperCase(),gt=(ae.approverEmail||"").toLowerCase(),be=ae.levelNumber||0;return(je==="PENDING"||je==="IN_PROGRESS"||je==="PAUSED")&>===le&&be===W});h(fe||null);const st=a==null?void 0:a.userId;if(st){const ae=L.some(je=>(je.participantType||je.participant_type||"").toUpperCase()==="SPECTATOR"&&(je.userId||je.user_id)===st);p(ae)}else p(!1)}catch(k){console.error("[useRequestDetails] Error refreshing details:",k),alert("Failed to refresh request details. Please try again.")}finally{l(!1)}},[t,a]);x.useEffect(()=>{if(!t){c(!1);return}let C=!0;return c(!0),m(null),(async()=>{var S,E,P,R,f,T,F,K,B,U,D,A,k,M;try{const O=await ws.getWorkflowDetails(t);if(!C||!O){C&&c(!1);return}const L=O.workflow||{},Z=Array.isArray(O.approvals)?O.approvals:[],z=Array.isArray(O.participants)?O.participants:[],$=Array.isArray(O.documents)?O.documents:[],W=O.summary||{},_=Array.isArray(O.tatAlerts)?O.tatAlerts:[],G=(L.priority||"").toString().toLowerCase(),H=(W==null?void 0:W.currentLevel)||L.currentLevel||1,V=Z.map(be=>{const Oe=be.levelNumber||0,ut=(be.status||"").toString().toUpperCase(),wt=be.levelId||be.level_id;let dt=b(be.status);ut==="PAUSED"?dt="paused":Oe>H&&ut!=="APPROVED"&&ut!=="REJECTED"?dt="waiting":Oe===H&&(ut==="PENDING"||ut==="IN_PROGRESS")&&(dt=ut==="IN_PROGRESS"?"in-review":"pending");const is=_.filter(Bs=>Bs.levelId===wt);return{step:Oe,levelId:wt,role:be.levelName||be.approverName||"Approver",status:dt,approver:be.approverName||be.approverEmail,approverId:be.approverId||be.approver_id,approverEmail:be.approverEmail,tatHours:Number(be.tatHours||0),elapsedHours:Number(be.elapsedHours||0),remainingHours:Number(be.remainingHours||0),tatPercentageUsed:Number(be.tatPercentageUsed||0),actualHours:be.elapsedHours!==void 0&&be.elapsedHours!==null?Number(be.elapsedHours):void 0,comment:be.comments||void 0,timestamp:be.actionDate||void 0,levelStartTime:be.levelStartTime||be.tatStartTime,tatAlerts:is}}),ee=z.filter(be=>(be.participantType||"").toUpperCase()==="SPECTATOR").map(be=>({name:be.userName||be.userEmail,role:"Spectator",avatar:y(be.userName,be.userEmail)})),oe=be=>{var ut,wt;if(!be)return;const Oe=z.find(dt=>dt.userId===be);return Oe!=null&&Oe.userName?Oe.userName:L.initiatorId===be?((ut=L.initiator)==null?void 0:ut.displayName)||((wt=L.initiator)==null?void 0:wt.email):be},pe=$.map(be=>{const Oe=Number(be.fileSize||0),ut=(Oe/(1024*1024)).toFixed(2)+" MB";return{documentId:be.documentId||be.document_id,name:be.originalFileName||be.fileName,fileType:be.fileType||be.file_type||"",size:ut,sizeBytes:Oe,uploadedBy:oe(be.uploadedBy),uploadedAt:be.uploadedAt}}),Pe=Array.isArray(O.activities)?O.activities.filter(be=>(be.type||"").toLowerCase()!=="sla_warning"):[];let Se=null;try{Se=await fd(L.requestId)}catch(be){console.debug("Pause details not available:",be)}let ne=null,de=null,le=null,fe=null;if(L.workflowType==="CLAIM_MANAGEMENT"||L.templateType==="claim-management")try{console.debug("[useRequestDetails] Initial load - Fetching claim details for requestId:",L.requestId);const be=await ye.get(`/dealer-claims/${L.requestId}`);console.debug("[useRequestDetails] Initial load - Claim API response:",{status:be.status,hasData:!!be.data,dataKeys:be.data?Object.keys(be.data):[]});const Oe=((S=be.data)==null?void 0:S.data)||be.data;if(Oe){ne=Oe.claimDetails||Oe.claim_details,de=Oe.proposalDetails||Oe.proposal_details,le=Oe.completionDetails||Oe.completion_details,fe=Oe.internalOrder||Oe.internal_order||null;const ut=Oe.budgetTracking||Oe.budget_tracking||null,wt=Oe.invoice||null,dt=Oe.creditNote||Oe.credit_note||null,is=Oe.completionExpenses||Oe.completion_expenses||null;ne&&(ne.budgetTracking=ut,ne.invoice=wt,ne.creditNote=dt,ne.completionExpenses=is),console.debug("[useRequestDetails] Initial load - Extracted details:",{hasClaimDetails:!!ne,claimDetailsKeys:ne?Object.keys(ne):[],hasProposalDetails:!!de,hasCompletionDetails:!!le,hasInternalOrder:!!fe,hasBudgetTracking:!!ut,hasInvoice:!!wt,hasCreditNote:!!dt,hasCompletionExpenses:Array.isArray(is)&&is.length>0})}}catch(be){console.error("[useRequestDetails] Initial load - Error fetching claim details:",{error:(be==null?void 0:be.message)||be,status:(E=be==null?void 0:be.response)==null?void 0:E.status,requestId:L.requestId})}const st={id:L.requestNumber||L.requestId,requestId:L.requestId,title:L.title,description:L.description,priority:G,status:b(L.status),workflowType:L.workflowType||(L.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),summary:W,initiator:{name:((P=L.initiator)==null?void 0:P.displayName)||((R=L.initiator)==null?void 0:R.email),role:((f=L.initiator)==null?void 0:f.designation)||void 0,department:((T=L.initiator)==null?void 0:T.department)||void 0,email:((F=L.initiator)==null?void 0:F.email)||void 0,phone:((K=L.initiator)==null?void 0:K.phone)||void 0,avatar:y((B=L.initiator)==null?void 0:B.displayName,(U=L.initiator)==null?void 0:U.email)},createdAt:L.createdAt,updatedAt:L.updatedAt,totalSteps:L.totalLevels||1,currentStepRaw:(W==null?void 0:W.currentLevel)||L.currentLevel||1,currentStep:Math.min(Math.max(1,(W==null?void 0:W.currentLevel)||L.currentLevel||1),L.totalLevels||1),approvalFlow:V,approvals:Z,documents:pe,spectators:ee,auditTrail:Pe,conclusionRemark:L.conclusionRemark||null,closureDate:L.closureDate||null,pauseInfo:Se||null,claimDetails:ne||null,proposalDetails:de||null,completionDetails:le||null,internalOrder:fe||null,budgetTracking:(ne==null?void 0:ne.budgetTracking)||null,invoice:(ne==null?void 0:ne.invoice)||null,creditNote:(ne==null?void 0:ne.creditNote)||null,completionExpenses:(ne==null?void 0:ne.completionExpenses)||null};n(st);const ae=(D=a==null?void 0:a.email)==null?void 0:D.toLowerCase(),je=Z.find(be=>{const Oe=(be.status||"").toString().toUpperCase(),ut=(be.approverEmail||"").toLowerCase(),wt=be.levelNumber||0;return(Oe==="PENDING"||Oe==="IN_PROGRESS"||Oe==="PAUSED")&&ut===ae&&wt===H});h(je||null);const gt=a==null?void 0:a.userId;if(gt){const be=z.some(Oe=>(Oe.participantType||"").toUpperCase()==="SPECTATOR"&&Oe.userId===gt);p(be)}else p(!1)}catch(O){if(console.error("[useRequestDetails] Error loading request details:",O),C){if(((A=O==null?void 0:O.response)==null?void 0:A.status)===403){const L=((M=(k=O==null?void 0:O.response)==null?void 0:k.data)==null?void 0:M.message)||"You do not have permission to view this request. Access is restricted to the initiator, approvers, and spectators of this request.";m({denied:!0,message:L})}n(null)}}finally{C&&c(!1)}})(),()=>{C=!1}},[t,a]);const v=x.useMemo(()=>{if(r)return r;const C=lh[t];if(C)return C;const S=kv[t];if(S)return S;const E=s.find(P=>P.id===t||P.requestNumber===t||P.request_number===t);return E||null},[t,s,r]),w=x.useMemo(()=>{var E,P,R;if(!v||!a)return!1;const C=(E=a==null?void 0:a.email)==null?void 0:E.toLowerCase(),S=(R=(P=v.initiator)==null?void 0:P.email)==null?void 0:R.toLowerCase();return C===S},[v,a]),N=x.useMemo(()=>{var S;if(!v)return[];const C=[];return(S=v.initiator)!=null&&S.email&&C.push({email:v.initiator.email.toLowerCase(),participantType:"INITIATOR",name:v.initiator.name}),v.approvalFlow&&Array.isArray(v.approvalFlow)&&v.approvalFlow.forEach(E=>{E.approverEmail&&C.push({email:E.approverEmail.toLowerCase(),participantType:"APPROVER",name:E.approver})}),v.spectators&&Array.isArray(v.spectators)&&v.spectators.forEach(E=>{E.email&&C.push({email:E.email.toLowerCase(),participantType:"SPECTATOR",name:E.name})}),v.participants&&Array.isArray(v.participants)&&v.participants.forEach(E=>{const P=(E.userEmail||E.email||"").toLowerCase(),R=(E.participantType||E.participant_type||"").toUpperCase(),f=E.userName||E.user_name||E.name;P&&R&&!C.find(T=>T.email===P)&&C.push({email:P,participantType:R,name:f})}),C},[v]);return x.useEffect(()=>{if(!t||!r)return;const C=fr();if(!C)return;const S=E=>{((E==null?void 0:E.requestId)===r.requestId||(E==null?void 0:E.requestNumber)===t)&&j()};return C.on("request:updated",S),()=>{C.off("request:updated",S)}},[t,r,j]),{request:v,apiRequest:r,loading:o,refreshing:i,refreshDetails:j,currentApprovalLevel:u,isSpectator:g,isInitiator:w,existingParticipants:N,accessDenied:d}}function Dv(t){return t?t.workflowType==="CLAIM_MANAGEMENT"||t.workflowType==="DEALER_CLAIM"||t.templateType==="claim-management"||t.template==="claim-management"||t.templateType==="dealer-claim"||t.templateName==="Claim Management"||t.templateCode==="CLAIM_MANAGEMENT"||t.templateCode==="DEALER_CLAIM":!1}function Rv(t){return Dv(t)?"DEALER_CLAIM":"CUSTOM"}function t4(t,s){return`/request/${t}`}const Pn=[{name:"No Color",value:"transparent",class:"bg-gray-200 border-2 border-gray-400",icon:"×"},{name:"Yellow",value:"#FFEB3B",class:"bg-yellow-400"},{name:"Green",value:"#4CAF50",class:"bg-green-400"},{name:"Blue",value:"#2196F3",class:"bg-blue-400"},{name:"Red",value:"#F44336",class:"bg-red-400"},{name:"Orange",value:"#FF9800",class:"bg-orange-400"},{name:"Purple",value:"#9C27B0",class:"bg-purple-400"},{name:"Pink",value:"#E91E63",class:"bg-pink-400"},{name:"Cyan",value:"#00BCD4",class:"bg-cyan-400"},{name:"Teal",value:"#009688",class:"bg-teal-400"},{name:"Amber",value:"#FFC107",class:"bg-amber-400"},{name:"Indigo",value:"#3F51B5",class:"bg-indigo-400"}];function yi({value:t,onChange:s,placeholder:a="Enter text...",className:r,minHeight:n="120px",...i}){const l=x.useRef(null),[o,c]=x.useState(!1),[d,m]=x.useState(new Set),[u,h]=x.useState(!1),[g,p]=x.useState(null),[y,b]=x.useState("#FFEB3B"),[j,v]=x.useState(!1),[w,N]=x.useState(null),[C,S]=x.useState("#000000");x.useEffect(()=>{l.current&&l.current.innerHTML!==t&&l.current.innerHTML!==t&&(l.current.innerHTML=t||"")},[t]);const E=x.useCallback(A=>(A=A.replace(/<!--[\s\S]*?-->/g,""),A=A.replace(/<style[^>]*>[\s\S]*?<\/style>/gi,""),A=A.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,""),A=A.replace(/<meta[^>]*>/gi,""),A=A.replace(/\s*class="Mso[^"]*"/gi,""),A=A.replace(/\s*class="mso[^"]*"/gi,""),A=A.replace(/\s*style="[^"]*mso-[^"]*"/gi,""),A=A.replace(/\s*style="[^"]*font-family:[^"]*"/gi,""),A=A.replace(/\s*xmlns[^=]*="[^"]*"/gi,""),A=A.replace(/<\/?o:p[^>]*>/gi,""),A=A.replace(/<v:[^>]*>[\s\S]*?<\/v:[^>]*>/gi,""),A=A.replace(/<v:[^>]*\/>/gi,""),A=A.replace(/<p[^>]*>\s*<\/p>/gi,""),A=A.replace(/<div[^>]*>\s*<\/div>/gi,""),A=A.replace(/\s+/g," "),A=A.trim(),A),[]),P=x.useCallback(A=>{A.preventDefault();const k=A.clipboardData;let M=k.getData("text/html")||k.getData("text/plain");if((M.includes("<!--")||M.includes("<style")||M.includes("MsoNormal"))&&(M=E(M)),!l.current)return;const O=window.getSelection();if(!O||O.rangeCount===0)return;const L=O.getRangeAt(0);L.deleteContents();const Z=document.createElement("div");Z.innerHTML=M;const z=document.createDocumentFragment();Array.from(Z.childNodes).forEach($=>{if($.nodeType===Node.ELEMENT_NODE){const W=$;if(W.tagName==="UL"||W.tagName==="OL"){const _=W.cloneNode(!0);_.removeAttribute("style"),_.removeAttribute("class"),_.querySelectorAll("li").forEach(G=>{G.removeAttribute("style"),G.removeAttribute("class");const H=G.textContent||"";H.trim()&&(G.textContent=H.trim())}),z.appendChild(_)}else if(W.tagName==="TABLE"){const _=W.cloneNode(!0);_.removeAttribute("style"),_.removeAttribute("class"),_.querySelectorAll("td, th").forEach(H=>{H.removeAttribute("style"),H.removeAttribute("class")});const G=document.createElement("div");G.className="table-wrapper",G.style.overflowX="auto",G.style.maxWidth="100%",G.style.margin="8px 0",G.appendChild(_),z.appendChild(G)}else if(W.tagName==="P"||W.tagName==="DIV"){const _=document.createElement("p"),H=W.innerHTML.replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<!--[\s\S]*?-->/g,"");_.innerHTML=H,_.removeAttribute("style"),_.removeAttribute("class"),z.appendChild(_)}else if(W.tagName==="BR")z.appendChild(W.cloneNode(!0));else{const _=W.textContent||"";if(_.trim()){const G=document.createElement("p");G.textContent=_.trim(),z.appendChild(G)}}}else if($.nodeType===Node.TEXT_NODE){const W=$.textContent||"";if(W.trim()){const _=document.createElement("p");_.textContent=W.trim(),z.appendChild(_)}}}),z.childNodes.length===0&&k.getData("text/plain").split(`
|
||
`).forEach(_=>{if(_.trim()){const G=document.createElement("p");G.textContent=_.trim(),z.appendChild(G)}else z.appendChild(document.createElement("br"))}),L.insertNode(z),L.collapse(!1),O.removeAllRanges(),O.addRange(L),l.current&&s(l.current.innerHTML)},[s,E]),R=x.useCallback(()=>{if(!l.current||!o)return;const A=new Set,k=window.getSelection();if(k&&k.rangeCount>0){const O=k.getRangeAt(0).commonAncestorContainer;let L=null;for(O.nodeType===Node.TEXT_NODE?L=O.parentElement:L=O;L&&L!==l.current;){const Z=L.tagName.toLowerCase();(Z==="strong"||Z==="b")&&A.add("bold"),(Z==="em"||Z==="i")&&A.add("italic"),Z==="u"&&A.add("underline"),Z==="h1"&&A.add("h1"),Z==="h2"&&A.add("h2"),Z==="h3"&&A.add("h3"),Z==="ul"&&A.add("ul"),Z==="ol"&&A.add("ol");const z=window.getComputedStyle(L);z.textAlign==="center"&&A.add("center"),z.textAlign==="right"&&A.add("right"),z.textAlign==="left"&&A.add("left");const $=H=>{if(H.startsWith("#"))return H.toUpperCase();const V=H.match(/\d+/g);if(!V||V.length<3)return null;const ee=V[0],oe=V[1],pe=V[2];if(!ee||!oe||!pe)return null;const Pe=parseInt(ee).toString(16).padStart(2,"0"),Se=parseInt(oe).toString(16).padStart(2,"0"),ne=parseInt(pe).toString(16).padStart(2,"0");return`#${Pe}${Se}${ne}`.toUpperCase()},W=z.backgroundColor;if(W&&W!=="rgba(0, 0, 0, 0)"&&W!=="transparent"&&W!=="rgb(255, 255, 255)"&&W!=="#ffffff"&&W!=="#FFFFFF"){A.add("highlight");const H=$(W);if(H){const V=Pn.find(ee=>ee.value==="transparent"?!1:ee.value.toUpperCase()===H);p(V?V.value:H)}}else A.has("highlight")||p(null);const _=z.color,G=$(_);if(_&&G&&_!=="rgba(0, 0, 0, 0)"&&G!=="#000000"){A.add("textColor");const H=Pn.find(V=>V.value==="transparent"?!1:V.value.toUpperCase()===G);N(H?H.value:G)}else A.has("textColor")||N(G==="#000000"||!G?"#000000":null);L=L.parentElement}}m(A)},[o]),f=x.useCallback((A,k)=>{if(!l.current)return;o||l.current.focus();const M=window.getSelection();if(!M||M.rangeCount===0){l.current.focus();return}document.execCommand(A,!1,k),l.current&&s(l.current.innerHTML),setTimeout(R,10)},[o,s,R]),T=x.useCallback(A=>{if(!l.current)return;o||l.current.focus();const k=window.getSelection();if(!k||k.rangeCount===0){l.current.focus();return}let M=!1;if(k.rangeCount>0){const Z=k.getRangeAt(0).commonAncestorContainer;let z=null;for(Z.nodeType===Node.TEXT_NODE?z=Z.parentElement:z=Z;z&&z!==l.current;){const W=window.getComputedStyle(z).backgroundColor;if(W&&W!=="rgba(0, 0, 0, 0)"&&W!=="transparent"&&W!=="rgb(255, 255, 255)"&&W!=="#ffffff"&&W!=="#FFFFFF"){const G=(H=>{if(H.startsWith("#"))return H.toUpperCase();const V=H.match(/\d+/g);if(!V||V.length<3)return null;const ee=V[0],oe=V[1],pe=V[2];if(!ee||!oe||!pe)return null;const Pe=parseInt(ee).toString(16).padStart(2,"0"),Se=parseInt(oe).toString(16).padStart(2,"0"),ne=parseInt(pe).toString(16).padStart(2,"0");return`#${Pe}${Se}${ne}`.toUpperCase()})(W);if(G&&G===A.toUpperCase()){M=!0;break}}z=z.parentElement}}if(A==="transparent"||M){const L=k.getRangeAt(0);if(L.collapsed)document.execCommand("removeFormat",!1);else{const Z=L.extractContents(),z=document.createDocumentFragment(),$=W=>{if(W.nodeType===Node.TEXT_NODE)return W.cloneNode(!0);if(W.nodeType===Node.ELEMENT_NODE){const _=W,G=document.createElement(_.tagName.toLowerCase());return Array.from(_.attributes).forEach(H=>{H.name!=="style"&&H.name!=="class"&&G.setAttribute(H.name,H.value)}),Array.from(_.childNodes).forEach(H=>{const V=$(H);V&&G.appendChild(V)}),_.style.backgroundColor&&(G.style.backgroundColor=""),G}return null};Array.from(Z.childNodes).forEach(W=>{const _=$(W);_&&z.appendChild(_)}),L.insertNode(z),document.execCommand("removeFormat",!1)}p(null),b("#FFEB3B")}else if(k.rangeCount>0&&!k.getRangeAt(0).collapsed)document.execCommand("backColor",!1,A),p(A),A!=="transparent"&&/^#[0-9A-Fa-f]{6}$/i.test(A)&&b(A);else return;const O=window.getSelection();O&&O.removeAllRanges(),l.current&&s(l.current.innerHTML),h(!1),setTimeout(()=>{l.current&&l.current.focus(),R()},50)},[o,s,R]),F=x.useCallback(A=>{if(!l.current)return;o||l.current.focus();const k=window.getSelection();if(!k||k.rangeCount===0){l.current.focus();return}let M=!1;if(k.rangeCount>0){const L=k.getRangeAt(0).commonAncestorContainer;let Z=null;for(L.nodeType===Node.TEXT_NODE?Z=L.parentElement:Z=L;Z&&Z!==l.current;){const $=window.getComputedStyle(Z).color;if($){const _=(G=>{if(G.startsWith("#"))return G.toUpperCase();const H=G.match(/\d+/g);if(!H||H.length<3)return null;const V=H[0],ee=H[1],oe=H[2];if(!V||!ee||!oe)return null;const pe=parseInt(V).toString(16).padStart(2,"0"),Pe=parseInt(ee).toString(16).padStart(2,"0"),Se=parseInt(oe).toString(16).padStart(2,"0");return`#${pe}${Pe}${Se}`.toUpperCase()})($);if(A==="#000000"){if(_==="#000000"||!_){M=!0;break}}else if(_&&_===A.toUpperCase()){M=!0;break}}Z=Z.parentElement}}if(A==="transparent"||A==="default"||M){if(A==="#000000"&&M){v(!1);return}document.execCommand("removeFormat",!1),N(null),S("#000000")}else document.execCommand("foreColor",!1,A),N(A),A!=="transparent"&&/^#[0-9A-Fa-f]{6}$/i.test(A)&&S(A);l.current&&s(l.current.innerHTML),v(!1),setTimeout(R,10)},[o,s,R]),K=x.useCallback(()=>{l.current&&s(l.current.innerHTML),R()},[s,R]),B=x.useCallback(A=>{if(A.ctrlKey&&A.key==="b"){A.preventDefault(),f("bold");return}if(A.ctrlKey&&A.key==="i"){A.preventDefault(),f("italic");return}if(A.ctrlKey&&A.key==="u"){A.preventDefault(),f("underline");return}},[f]),U=x.useCallback(()=>{c(!0)},[]),D=x.useCallback(()=>{c(!1),l.current&&s(l.current.innerHTML)},[s]);return x.useEffect(()=>{if(!o)return;const A=()=>{R()};return document.addEventListener("selectionchange",A),()=>{document.removeEventListener("selectionchange",A)}},[o,R]),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(I,{type:"button",variant:"ghost",size:"sm",className:we("h-7 w-7 p-0",d.has("bold")&&"bg-blue-100 text-blue-700"),onClick:()=>f("bold"),title:"Bold (Ctrl+B)",children:e.jsx(yf,{className:"h-4 w-4"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:we("h-7 w-7 p-0",d.has("italic")&&"bg-blue-100 text-blue-700"),onClick:()=>f("italic"),title:"Italic (Ctrl+I)",children:e.jsx(bf,{className:"h-4 w-4"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:we("h-7 w-7 p-0",d.has("underline")&&"bg-blue-100 text-blue-700"),onClick:()=>f("underline"),title:"Underline (Ctrl+U)",children:e.jsx(vf,{className:"h-4 w-4"})}),e.jsxs(ra,{open:u,onOpenChange:h,children:[e.jsx(na,{asChild:!0,children:e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:we("h-7 w-7 p-0",d.has("highlight")&&"bg-blue-100 text-blue-700"),title:"Text Highlight",children:e.jsx(jf,{className:"h-4 w-4"})})}),e.jsx(ia,{className:"w-auto p-2",align:"start",onPointerDownOutside:A=>{A.target.closest("[data-popover-content]")&&A.preventDefault()},children:e.jsxs("div",{className:"space-y-2 relative",onClick:A=>A.stopPropagation(),children:[e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"absolute top-0 right-0 h-6 w-6 p-0 hover:bg-gray-100",onClick:A=>{A.stopPropagation(),h(!1)},title:"Close",children:e.jsx(pt,{className:"h-4 w-4 text-gray-500"})}),e.jsx("div",{className:"text-xs font-semibold text-gray-700 mb-2 pr-6",children:"Highlight Color"}),e.jsx("div",{className:"grid grid-cols-6 gap-1.5 pr-1 mb-2",children:Pn.map(A=>{const k=g===A.value,M=A.value==="transparent";return e.jsxs("button",{type:"button",onClick:O=>{O.preventDefault(),O.stopPropagation(),T(k&&!M?"transparent":A.value)},className:we("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md relative",A.class,k&&"ring-2 ring-blue-600 ring-offset-1 border-blue-600",M&&"border-gray-400 bg-white",!M&&!k&&"border-gray-300"),title:k&&!M?`${A.name} (Click to remove)`:A.name,style:M?{}:{backgroundColor:A.value},children:[M&&e.jsx("span",{className:"text-[10px] text-gray-600 font-bold",children:"×"}),k&&!M&&e.jsx("span",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("span",{className:"w-2 h-2 bg-white rounded-full shadow-sm"})})]},A.value)})}),g&&g!=="transparent"&&e.jsx("div",{className:"mb-2",children:e.jsx(I,{type:"button",variant:"outline",size:"sm",className:"w-full h-7 text-xs",onClick:A=>{A.stopPropagation(),T("transparent")},title:"Remove highlight color",children:"Remove Highlight"})}),e.jsxs("div",{className:"border-t border-gray-200 pt-2 mt-2",children:[e.jsx("div",{className:"text-xs font-semibold text-gray-700 mb-1.5",children:"Custom Color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:g&&g!=="transparent"?g:y,onChange:A=>{const k=A.target.value;b(k);const M=window.getSelection();M&&M.rangeCount>0&&!M.getRangeAt(0).collapsed&&T(k)},className:"w-8 h-8 rounded border border-gray-300 cursor-pointer",title:"Pick a custom color"}),e.jsx("input",{type:"text",value:g&&g!=="transparent"?g:y,onChange:A=>{A.stopPropagation();const k=A.target.value;b(k)},onKeyDown:A=>{if(A.stopPropagation(),A.key==="Enter"){A.preventDefault();const k=A.currentTarget.value.trim();/^#[0-9A-Fa-f]{6}$/i.test(k)&&T(k)}},onPaste:A=>{A.stopPropagation();const k=A.clipboardData.getData("text").trim();A.preventDefault(),setTimeout(()=>{if(/^#[0-9A-Fa-f]{6}$/i.test(k)){b(k);const M=window.getSelection();M&&M.rangeCount>0&&!M.getRangeAt(0).collapsed&&T(k)}else{const M=k.match(/^([0-9A-Fa-f]{6})$/);if(M){const O=`#${M[1]}`;b(O);const L=window.getSelection();L&&L.rangeCount>0&&!L.getRangeAt(0).collapsed&&T(O)}}},0)},onClick:A=>{A.stopPropagation()},onFocus:A=>{A.stopPropagation(),A.target.select()},onBlur:A=>{const k=A.target.value.trim();if(/^#[0-9A-Fa-f]{6}$/i.test(k)){const M=window.getSelection();M&&M.rangeCount>0&&!M.getRangeAt(0).collapsed&&T(k)}else b(k===""?g||"#FFEB3B":k)},placeholder:"#FFEB3B",className:"flex-1 h-7 px-2 text-xs border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500",title:"Enter hex color code (Press Enter or click Apply). Supports copy-paste.",autoComplete:"off",spellCheck:"false"}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>{const A=y.trim();/^#[0-9A-Fa-f]{6}$/i.test(A)?T(A):b(g||"#FFEB3B")},title:"Apply custom color",children:"Apply"})]})]})]})})]}),e.jsxs(ra,{open:j,onOpenChange:v,children:[e.jsx(na,{asChild:!0,children:e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:we("h-7 w-7 p-0",d.has("textColor")&&"bg-blue-100 text-blue-700"),title:"Text Color",children:e.jsx(Nf,{className:"h-4 w-4"})})}),e.jsx(ia,{className:"w-auto p-2",align:"start",onPointerDownOutside:A=>{A.target.closest("[data-popover-content]")&&A.preventDefault()},children:e.jsxs("div",{className:"space-y-2 relative",onClick:A=>A.stopPropagation(),children:[e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"absolute top-0 right-0 h-6 w-6 p-0 hover:bg-gray-100",onClick:A=>{A.stopPropagation(),v(!1)},title:"Close",children:e.jsx(pt,{className:"h-4 w-4 text-gray-500"})}),e.jsx("div",{className:"text-xs font-semibold text-gray-700 mb-2 pr-6",children:"Text Color"}),e.jsxs("div",{className:"grid grid-cols-6 gap-1.5 pr-1 mb-2",children:[e.jsxs("button",{type:"button",onClick:A=>{A.preventDefault(),A.stopPropagation(),w==="#000000"||!w&&!d.has("textColor")||F("#000000")},className:we("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md flex items-center justify-center bg-black",(w==="#000000"||!w&&!d.has("textColor"))&&"ring-2 ring-blue-600 ring-offset-1 border-blue-600",w!=="#000000"&&(w||d.has("textColor"))&&"border-gray-300"),title:"Default (Black)",children:[e.jsx("span",{className:"text-[10px] text-white font-bold",children:"A"}),(w==="#000000"||!w&&!d.has("textColor"))&&e.jsx("span",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("span",{className:"w-2 h-2 bg-white rounded-full shadow-sm"})})]}),Pn.filter(A=>A.value!=="transparent").map(A=>{const k=w===A.value;return e.jsxs("button",{type:"button",onClick:M=>{M.preventDefault(),M.stopPropagation(),F(k?"#000000":A.value)},className:we("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md flex items-center justify-center relative",k&&"ring-2 ring-blue-600 ring-offset-1 border-blue-600",!k&&"border-gray-300"),title:k?`${A.name} (Click to reset to default)`:A.name,style:{color:A.value,borderColor:k?"#2563eb":A.value},children:[e.jsx("span",{className:"text-xs font-bold",children:"A"}),k&&e.jsx("span",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("span",{className:"w-2 h-2 bg-white rounded-full shadow-sm"})})]},`text-${A.value}`)})]}),w&&w!=="#000000"&&e.jsx("div",{className:"mb-2",children:e.jsx(I,{type:"button",variant:"outline",size:"sm",className:"w-full h-7 text-xs",onClick:A=>{A.stopPropagation(),F("#000000")},title:"Reset to default black",children:"Reset to Default"})}),e.jsxs("div",{className:"border-t border-gray-200 pt-2 mt-2",children:[e.jsx("div",{className:"text-xs font-semibold text-gray-700 mb-1.5",children:"Custom Color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:w||C,onChange:A=>{const k=A.target.value;S(k),F(k)},className:"w-8 h-8 rounded border border-gray-300 cursor-pointer",title:"Pick a custom text color"}),e.jsx("input",{type:"text",value:w||C,onChange:A=>{const k=A.target.value;S(k)},onKeyDown:A=>{if(A.key==="Enter"){A.preventDefault();const k=A.currentTarget.value;/^#[0-9A-Fa-f]{6}$/.test(k)&&F(k)}},onBlur:A=>{const k=A.target.value;/^#[0-9A-Fa-f]{6}$/.test(k)?F(k):k===""&&S(w||"#000000")},placeholder:"#000000",className:"flex-1 h-7 px-2 text-xs border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500",title:"Enter hex color code (Press Enter or click Apply)"}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>F(C),title:"Apply custom text color",children:"Apply"})]})]})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-1 border-r border-gray-300 pr-2",children:[e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:we("h-7 w-7 p-0",d.has("h1")&&"bg-blue-100 text-blue-700"),onClick:()=>f("formatBlock","<h1>"),title:"Heading 1",children:e.jsx(wf,{className:"h-4 w-4"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:we("h-7 w-7 p-0",d.has("h2")&&"bg-blue-100 text-blue-700"),onClick:()=>f("formatBlock","<h2>"),title:"Heading 2",children:e.jsx(Cf,{className:"h-4 w-4"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:we("h-7 w-7 p-0",d.has("h3")&&"bg-blue-100 text-blue-700"),onClick:()=>f("formatBlock","<h3>"),title:"Heading 3",children:e.jsx(Sf,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-1 border-r border-gray-300 pr-2",children:[e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:we("h-7 w-7 p-0",d.has("ul")&&"bg-blue-100 text-blue-700"),onClick:()=>f("insertUnorderedList"),title:"Bullet List",children:e.jsx(fu,{className:"h-4 w-4"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:we("h-7 w-7 p-0",d.has("ol")&&"bg-blue-100 text-blue-700"),onClick:()=>f("insertOrderedList"),title:"Numbered List",children:e.jsx(Af,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:we("h-7 w-7 p-0",d.has("left")&&"bg-blue-100 text-blue-700"),onClick:()=>f("justifyLeft"),title:"Align Left",children:e.jsx(Tf,{className:"h-4 w-4"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:we("h-7 w-7 p-0",d.has("center")&&"bg-blue-100 text-blue-700"),onClick:()=>f("justifyCenter"),title:"Align Center",children:e.jsx(kf,{className:"h-4 w-4"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:we("h-7 w-7 p-0",d.has("right")&&"bg-blue-100 text-blue-700"),onClick:()=>f("justifyRight"),title:"Align Right",children:e.jsx(Df,{className:"h-4 w-4"})})]})]}),e.jsx("div",{ref:l,contentEditable:!0,onPaste:P,onInput:K,onFocus:U,onBlur:D,onKeyDown:B,onMouseUp:R,onKeyUp:R,"data-placeholder":a,className:we("w-full rounded-b-md border-0 px-3 py-2 text-base transition-all outline-none","bg-white text-gray-900","min-h-[120px]","overflow-y-auto","overflow-x-auto","md:overflow-x-visible","md:text-sm","empty:before:content-[attr(data-placeholder)] empty:before:text-muted-foreground empty:before:pointer-events-none","focus-visible:outline-none","[&_ul]:list-disc [&_ul]:ml-6 [&_ul]:my-2 [&_ul]:list-outside","[&_ol]:list-decimal [&_ol]:ml-6 [&_ol]:my-2 [&_ol]:list-outside","[&_li]:my-1 [&_li]:pl-2","[&_.table-wrapper]:overflow-x-auto [&_.table-wrapper]:max-w-full [&_.table-wrapper]:my-2","[&_.table-wrapper_table]:border-collapse [&_.table-wrapper_table]:border [&_.table-wrapper_table]:border-gray-300 [&_.table-wrapper_table]:min-w-full","[&_.table-wrapper_table_td]:border [&_.table-wrapper_table_td]:border-gray-300 [&_.table-wrapper_table_td]:px-3 [&_.table-wrapper_table_td]:py-2 [&_.table-wrapper_table_td]:text-sm [&_.table-wrapper_table_td]:whitespace-nowrap","[&_.table-wrapper_table_th]:border [&_.table-wrapper_table_th]:border-gray-300 [&_.table-wrapper_table_th]:px-3 [&_.table-wrapper_table_th]:py-2 [&_.table-wrapper_table_th]:bg-gray-50 [&_.table-wrapper_table_th]:font-semibold [&_.table-wrapper_table_th]:text-sm [&_.table-wrapper_table_th]:text-left [&_.table-wrapper_table_th]:whitespace-nowrap","[&_.table-wrapper_table_tr:nth-child(even)]:bg-gray-50","[&_table]:border-collapse [&_table]:my-2 [&_table]:border [&_table]:border-gray-300 [&_table]:w-full","[&_table_td]:border [&_table_td]:border-gray-300 [&_table_td]:px-3 [&_table_td]:py-2 [&_table_td]:text-sm","[&_table_th]:border [&_table_th]:border-gray-300 [&_table_th]:px-3 [&_table_th]:py-2 [&_table_th]:bg-gray-50 [&_table_th]:font-semibold [&_table_th]:text-sm [&_table_th]:text-left","[&_table_tr:nth-child(even)]:bg-gray-50","[&_p]:my-1 [&_p]:leading-relaxed","[&_strong]:font-bold","[&_em]:italic","[&_u]:underline","[&_span[style*='background']]:px-0.5 [&_span[style*='background']]:rounded","[&_h1]:text-xl [&_h1]:font-bold [&_h1]:my-2","[&_h2]:text-lg [&_h2]:font-semibold [&_h2]:my-2","[&_h3]:text-base [&_h3]:font-semibold [&_h3]:my-1",r),style:{minHeight:n},...i})]})}function Ws({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:we("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 oh={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(ri,function(){var a=1e3,r=6e4,n=36e5,i="millisecond",l="second",o="minute",c="hour",d="day",m="week",u="month",h="quarter",g="year",p="date",y="Invalid Date",b=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,j=/\[([^\]]+)]|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,v={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(B){var U=["th","st","nd","rd"],D=B%100;return"["+B+(U[(D-20)%10]||U[D]||U[0])+"]"}},w=function(B,U,D){var A=String(B);return!A||A.length>=U?B:""+Array(U+1-A.length).join(D)+B},N={s:w,z:function(B){var U=-B.utcOffset(),D=Math.abs(U),A=Math.floor(D/60),k=D%60;return(U<=0?"+":"-")+w(A,2,"0")+":"+w(k,2,"0")},m:function B(U,D){if(U.date()<D.date())return-B(D,U);var A=12*(D.year()-U.year())+(D.month()-U.month()),k=U.clone().add(A,u),M=D-k<0,O=U.clone().add(A+(M?-1:1),u);return+(-(A+(D-k)/(M?k-O:O-k))||0)},a:function(B){return B<0?Math.ceil(B)||0:Math.floor(B)},p:function(B){return{M:u,y:g,w:m,d,D:p,h:c,m:o,s:l,ms:i,Q:h}[B]||String(B||"").toLowerCase().replace(/s$/,"")},u:function(B){return B===void 0}},C="en",S={};S[C]=v;var E="$isDayjsObject",P=function(B){return B instanceof F||!(!B||!B[E])},R=function B(U,D,A){var k;if(!U)return C;if(typeof U=="string"){var M=U.toLowerCase();S[M]&&(k=M),D&&(S[M]=D,k=M);var O=U.split("-");if(!k&&O.length>1)return B(O[0])}else{var L=U.name;S[L]=U,k=L}return!A&&k&&(C=k),k||!A&&C},f=function(B,U){if(P(B))return B.clone();var D=typeof U=="object"?U:{};return D.date=B,D.args=arguments,new F(D)},T=N;T.l=R,T.i=P,T.w=function(B,U){return f(B,{locale:U.$L,utc:U.$u,x:U.$x,$offset:U.$offset})};var F=function(){function B(D){this.$L=R(D.locale,null,!0),this.parse(D),this.$x=this.$x||D.x||{},this[E]=!0}var U=B.prototype;return U.parse=function(D){this.$d=function(A){var k=A.date,M=A.utc;if(k===null)return new Date(NaN);if(T.u(k))return new Date;if(k instanceof Date)return new Date(k);if(typeof k=="string"&&!/Z$/i.test(k)){var O=k.match(b);if(O){var L=O[2]-1||0,Z=(O[7]||"0").substring(0,3);return M?new Date(Date.UTC(O[1],L,O[3]||1,O[4]||0,O[5]||0,O[6]||0,Z)):new Date(O[1],L,O[3]||1,O[4]||0,O[5]||0,O[6]||0,Z)}}return new Date(k)}(D),this.init()},U.init=function(){var D=this.$d;this.$y=D.getFullYear(),this.$M=D.getMonth(),this.$D=D.getDate(),this.$W=D.getDay(),this.$H=D.getHours(),this.$m=D.getMinutes(),this.$s=D.getSeconds(),this.$ms=D.getMilliseconds()},U.$utils=function(){return T},U.isValid=function(){return this.$d.toString()!==y},U.isSame=function(D,A){var k=f(D);return this.startOf(A)<=k&&k<=this.endOf(A)},U.isAfter=function(D,A){return f(D)<this.startOf(A)},U.isBefore=function(D,A){return this.endOf(A)<f(D)},U.$g=function(D,A,k){return T.u(D)?this[A]:this.set(k,D)},U.unix=function(){return Math.floor(this.valueOf()/1e3)},U.valueOf=function(){return this.$d.getTime()},U.startOf=function(D,A){var k=this,M=!!T.u(A)||A,O=T.p(D),L=function(V,ee){var oe=T.w(k.$u?Date.UTC(k.$y,ee,V):new Date(k.$y,ee,V),k);return M?oe:oe.endOf(d)},Z=function(V,ee){return T.w(k.toDate()[V].apply(k.toDate("s"),(M?[0,0,0,0]:[23,59,59,999]).slice(ee)),k)},z=this.$W,$=this.$M,W=this.$D,_="set"+(this.$u?"UTC":"");switch(O){case g:return M?L(1,0):L(31,11);case u:return M?L(1,$):L(0,$+1);case m:var G=this.$locale().weekStart||0,H=(z<G?z+7:z)-G;return L(M?W-H:W+(6-H),$);case d:case p:return Z(_+"Hours",0);case c:return Z(_+"Minutes",1);case o:return Z(_+"Seconds",2);case l:return Z(_+"Milliseconds",3);default:return this.clone()}},U.endOf=function(D){return this.startOf(D,!1)},U.$set=function(D,A){var k,M=T.p(D),O="set"+(this.$u?"UTC":""),L=(k={},k[d]=O+"Date",k[p]=O+"Date",k[u]=O+"Month",k[g]=O+"FullYear",k[c]=O+"Hours",k[o]=O+"Minutes",k[l]=O+"Seconds",k[i]=O+"Milliseconds",k)[M],Z=M===d?this.$D+(A-this.$W):A;if(M===u||M===g){var z=this.clone().set(p,1);z.$d[L](Z),z.init(),this.$d=z.set(p,Math.min(this.$D,z.daysInMonth())).$d}else L&&this.$d[L](Z);return this.init(),this},U.set=function(D,A){return this.clone().$set(D,A)},U.get=function(D){return this[T.p(D)]()},U.add=function(D,A){var k,M=this;D=Number(D);var O=T.p(A),L=function($){var W=f(M);return T.w(W.date(W.date()+Math.round($*D)),M)};if(O===u)return this.set(u,this.$M+D);if(O===g)return this.set(g,this.$y+D);if(O===d)return L(1);if(O===m)return L(7);var Z=(k={},k[o]=r,k[c]=n,k[l]=a,k)[O]||1,z=this.$d.getTime()+D*Z;return T.w(z,this)},U.subtract=function(D,A){return this.add(-1*D,A)},U.format=function(D){var A=this,k=this.$locale();if(!this.isValid())return k.invalidDate||y;var M=D||"YYYY-MM-DDTHH:mm:ssZ",O=T.z(this),L=this.$H,Z=this.$m,z=this.$M,$=k.weekdays,W=k.months,_=k.meridiem,G=function(ee,oe,pe,Pe){return ee&&(ee[oe]||ee(A,M))||pe[oe].slice(0,Pe)},H=function(ee){return T.s(L%12||12,ee,"0")},V=_||function(ee,oe,pe){var Pe=ee<12?"AM":"PM";return pe?Pe.toLowerCase():Pe};return M.replace(j,function(ee,oe){return oe||function(pe){switch(pe){case"YY":return String(A.$y).slice(-2);case"YYYY":return T.s(A.$y,4,"0");case"M":return z+1;case"MM":return T.s(z+1,2,"0");case"MMM":return G(k.monthsShort,z,W,3);case"MMMM":return G(W,z);case"D":return A.$D;case"DD":return T.s(A.$D,2,"0");case"d":return String(A.$W);case"dd":return G(k.weekdaysMin,A.$W,$,2);case"ddd":return G(k.weekdaysShort,A.$W,$,3);case"dddd":return $[A.$W];case"H":return String(L);case"HH":return T.s(L,2,"0");case"h":return H(1);case"hh":return H(2);case"a":return V(L,Z,!0);case"A":return V(L,Z,!1);case"m":return String(Z);case"mm":return T.s(Z,2,"0");case"s":return String(A.$s);case"ss":return T.s(A.$s,2,"0");case"SSS":return T.s(A.$ms,3,"0");case"Z":return O}return null}(ee)||O.replace(":","")})},U.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},U.diff=function(D,A,k){var M,O=this,L=T.p(A),Z=f(D),z=(Z.utcOffset()-this.utcOffset())*r,$=this-Z,W=function(){return T.m(O,Z)};switch(L){case g:M=W()/12;break;case u:M=W();break;case h:M=W()/3;break;case m:M=($-z)/6048e5;break;case d:M=($-z)/864e5;break;case c:M=$/n;break;case o:M=$/r;break;case l:M=$/a;break;default:M=$}return k?M:T.a(M)},U.daysInMonth=function(){return this.endOf(u).$D},U.$locale=function(){return S[this.$L]},U.locale=function(D,A){if(!D)return this.$L;var k=this.clone(),M=R(D,A,!0);return M&&(k.$L=M),k},U.clone=function(){return T.w(this.$d,this)},U.toDate=function(){return new Date(this.valueOf())},U.toJSON=function(){return this.isValid()?this.toISOString():null},U.toISOString=function(){return this.$d.toISOString()},U.toString=function(){return this.$d.toUTCString()},B}(),K=F.prototype;return f.prototype=K,[["$ms",i],["$s",l],["$m",o],["$H",c],["$W",d],["$M",u],["$y",g],["$D",p]].forEach(function(B){K[B[1]]=function(U){return this.$g(U,B[0],B[1])}}),f.extend=function(B,U){return B.$i||(B(U,F,f),B.$i=!0),f},f.locale=R,f.isDayjs=P,f.unix=function(B){return f(1e3*B)},f.en=S[C],f.Ls=S,f.p={},f})})(oh);var Pv=oh.exports;const Ot=ni(Pv);var ch={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(ri,function(){return function(a,r,n){a=a||{};var i=r.prototype,l={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 o(d,m,u,h){return i.fromToBase(d,m,u,h)}n.en.relativeTime=l,i.fromToBase=function(d,m,u,h,g){for(var p,y,b,j=u.$locale().relativeTime||l,v=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"}],w=v.length,N=0;N<w;N+=1){var C=v[N];C.d&&(p=h?n(d).diff(u,C.d,!0):u.diff(d,C.d,!0));var S=(a.rounding||Math.round)(Math.abs(p));if(b=p>0,S<=C.r||!C.r){S<=1&&N>0&&(C=v[N-1]);var E=j[C.l];g&&(S=g(""+S)),y=typeof E=="string"?E.replace("%d",S):E(S,m,C.l,b);break}}if(m)return y;var P=b?j.future:j.past;return typeof P=="function"?P(y):P.replace("%s",y)},i.to=function(d,m){return o(d,m,this,!0)},i.from=function(d,m){return o(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)}}})})(ch);var Iv=ch.exports;const Ev=ni(Iv);Ot.extend(Ev);function Mv({request:t,isInitiator:s,needsClosure:a,conclusionRemark:r,setConclusionRemark:n,conclusionLoading:i,conclusionSubmitting:l,aiGenerated:o,handleGenerateConclusion:c,handleFinalizeConclusion:d,onPause:m,onResume:u,onRetrigger:h,currentUserIsApprover:g=!1,pausedByUserId:p,currentUserId:y}){var E,P,R,f,T,F,K,B;const{user:b}=Kt(),j=t==null?void 0:t.pauseInfo,v=(j==null?void 0:j.isPaused)||!1,w=(E=j==null?void 0:j.pausedBy)==null?void 0:E.userId,N=(b==null?void 0:b.userId)||"",C=v&&u&&(g||s),S=v&&s&&w&&w!==N&&h;return e.jsxs("div",{className:"space-y-4 sm:space-y-6","data-testid":"overview-tab-content",children:[e.jsxs(te,{"data-testid":"initiator-card",children:[e.jsx(me,{className:"pb-3 sm:pb-4",children:e.jsxs(he,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Pt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Initiator"]})}),e.jsx(se,{children:e.jsxs("div",{className:"flex items-start gap-3 sm:gap-4",children:[e.jsx(Qt,{className:"h-10 w-10 sm:h-12 sm:w-12 ring-2 ring-white shadow-sm flex-shrink-0",children:e.jsx(qt,{className:"bg-gray-700 text-white font-semibold text-sm",children:((P=t.initiator)==null?void 0:P.avatar)||"U"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-gray-900 text-sm sm:text-base truncate",children:((R=t.initiator)==null?void 0:R.name)||"N/A"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 truncate",children:((f=t.initiator)==null?void 0:f.role)||"N/A"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-500 truncate",children:((T=t.initiator)==null?void 0:T.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(va,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:((F=t.initiator)==null?void 0:F.email)||"N/A"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs sm:text-sm text-gray-600",children:[e.jsx(li,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{children:((K=t.initiator)==null?void 0:K.phone)||"N/A"})]})]})]})]})})]}),e.jsxs(te,{"data-testid":"request-details-card",children:[e.jsx(me,{className:"pb-3 sm:pb-4",children:e.jsxs(he,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Le,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Details"]})}),e.jsxs(se,{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(Ws,{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:es(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:es(t.updatedAt)})]})]})]})]}),v&&j&&e.jsxs(te,{className:"border-orange-300 bg-orange-50/50","data-testid":"pause-status-card",children:[e.jsx(me,{className:"pb-3 sm:pb-4",children:e.jsxs(he,{className:"flex items-center gap-2 text-sm sm:text-base text-orange-800",children:[e.jsx(Ra,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Workflow Paused"]})}),e.jsxs(se,{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:[j.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:j.pauseReason})]}),j.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:j.pausedBy.name||j.pausedBy.email})]}),j.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:[es(j.pauseResumeDate),Ot(j.pauseResumeDate).isAfter(Ot())&&e.jsxs("span",{className:"ml-2 text-xs text-gray-500",children:["(",Ot(j.pauseResumeDate).fromNow(),")"]})]})]}),j.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:es(j.pausedAt)})]})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-2 border-t border-orange-200",children:[C&&u&&e.jsxs(I,{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(Yn,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-1.5"}),"Resume Now"]}),S&&h&&e.jsxs(I,{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(We,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-1.5"}),"Request Resume"]})]})]})]}),t.claimDetails&&e.jsxs(te,{children:[e.jsx(me,{className:"pb-4",children:e.jsxs(he,{className:"flex items-center gap-2 text-base",children:[e.jsx(Le,{className:"w-5 h-5 text-purple-600"}),"Claim Management Details"]})}),e.jsxs(se,{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?nh(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(Ws,{content:t.claimDetails.requestDescription,className:"text-sm"})})]})]})]}),t.status==="closed"&&t.conclusionRemark&&e.jsxs(te,{children:[e.jsxs(me,{className:"bg-gradient-to-r from-gray-50 to-slate-50 border-b border-gray-200",children:[e.jsxs(he,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ce,{className:"w-5 h-5 text-gray-600"}),"Conclusion Remark"]}),e.jsx(De,{className:"mt-1 text-xs sm:text-sm",children:"Final summary of this closed request"})]}),e.jsxs(se,{className:"pt-4",children:[e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-4",children:e.jsx(Ws,{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 ",es(t.closureDate)]}),e.jsxs("span",{children:["By ",((B=t.initiator)==null?void 0:B.name)||"Initiator"]})]})]})]}),a&&e.jsxs(te,{"data-testid":"conclusion-remark-card",children:[e.jsx(me,{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(he,{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(De,{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(I,{variant:"outline",size:"sm",onClick:c,disabled:i,className:"gap-2 shrink-0","data-testid":"generate-ai-conclusion-button",children:[e.jsx(ns,{className:`w-3.5 h-3.5 ${i?"animate-spin":""}`}),o?"Regenerate":"Generate with AI"]})]})}),e.jsx(se,{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(Qe,{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"}),o&&e.jsx("span",{className:"text-xs text-blue-600","data-testid":"ai-generated-label",children:"✓ System-generated suggestion (editable)"})]}),e.jsx(yi,{value:r,onChange:U=>n(U),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(I,{onClick:d,disabled:l||!r.trim(),className:"bg-green-600 hover:bg-green-700 text-white","data-testid":"finalize-close-button",children:l?e.jsxs(e.Fragment,{children:[e.jsx(Qe,{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 Un({delayDuration:t=0,...s}){return e.jsx(Ng,{"data-slot":"tooltip-provider",delayDuration:t,...s})}function Ui({...t}){return e.jsx(Un,{children:e.jsx(wg,{"data-slot":"tooltip",...t})})}function Vi({...t}){return e.jsx(Cg,{"data-slot":"tooltip-trigger",...t})}function zi({className:t,sideOffset:s=0,children:a,...r}){return e.jsx(Sg,{children:e.jsxs(Ag,{"data-slot":"tooltip-content",sideOffset:s,className:we("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(Tg,{className:"bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function ot({...t}){return e.jsx(Rg,{"data-slot":"dialog",...t})}function Fv({...t}){return e.jsx(Dg,{"data-slot":"dialog-portal",...t})}const dh=x.forwardRef(({className:t,...s},a)=>e.jsx(au,{ref:a,"data-slot":"dialog-overlay",className:we("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}));dh.displayName=au.displayName;const nt=x.forwardRef(({className:t,children:s,...a},r)=>e.jsxs(Fv,{"data-slot":"dialog-portal",children:[e.jsx(dh,{}),e.jsxs(ru,{ref:r,"data-slot":"dialog-content",className:we("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(kg,{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(pt,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));nt.displayName=ru.displayName;const ct=x.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,"data-slot":"dialog-header",className:we("flex flex-col gap-2 text-center sm:text-left",t),...s}));ct.displayName="DialogHeader";const At=x.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,"data-slot":"dialog-footer",className:we("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s}));At.displayName="DialogFooter";const it=x.forwardRef(({className:t,...s},a)=>e.jsx(nu,{ref:a,"data-slot":"dialog-title",className:we("text-lg leading-none font-semibold",t),...s}));it.displayName=nu.displayName;const _t=x.forwardRef(({className:t,...s},a)=>e.jsx(iu,{ref:a,"data-slot":"dialog-description",className:we("text-muted-foreground text-sm",t),...s}));_t.displayName=iu.displayName;function ps({className:t,...s}){return e.jsx("textarea",{"data-slot":"textarea",className:we("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 bd=t=>{if(t<8)return It(t);const a=Math.floor(t/8),r=t%8;return r>0?`${a}d ${It(r)}`:`${a}d`},_v=(t,s)=>{if(s)return e.jsx(We,{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(xt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-red-600"});case"paused":return e.jsx(ju,{className:"w-4 h-4 sm:w-5 sm:h-5 text-yellow-600"});case"pending":case"in-review":return e.jsx(Ze,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"});case"waiting":return e.jsx(Ze,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400"});default:return e.jsx(Ze,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400"})}};function Lv({step:t,index:s,approval:a,isCurrentUser:r=!1,isInitiator:n=!1,isCurrentLevel:i=!1,onSkipApprover:l,onRefresh:o,testId:c="approval-step"}){const{user:d}=Kt(),[m,u]=x.useState(!1),[h,g]=x.useState(""),[p,y]=x.useState(!1),b=(a==null?void 0:a.breachReason)||(t==null?void 0:t.breachReason)||"";x.useEffect(()=>{m||g("")},[m]);const j=t.status==="pending"||t.status==="in-review",v=t.status==="approved",w=t.status==="rejected",N=t.status==="waiting",C=t.status==="paused",S=Number(t.tatHours||0),E=t.actualHours??0,P=v&&E?Math.max(0,S-E):0,R=S>0?E/S*100:0,f=R>=100,T=(d==null?void 0:d.role)==="ADMIN",F=xi(d),K=t.approverId===(d==null?void 0:d.userId),B=T||F||K,U=async()=>{var D,A;if(!h.trim()){q.error("Breach Reason Required",{description:"Please enter a reason for the breach."});return}y(!0);try{await tv(t.levelId,h.trim()),u(!1),g(""),q.success("Breach Reason Updated",{description:"The breach reason has been saved and will appear in the TAT Breach Report.",duration:5e3}),o?await o():setTimeout(()=>{window.location.reload()},1e3)}catch(k){console.error("Error updating breach reason:",k);const M=((A=(D=k==null?void 0:k.response)==null?void 0:D.data)==null?void 0:A.error)||(k==null?void 0:k.message)||"Failed to update breach reason. Please try again.";q.error("Failed to Update Breach Reason",{description:M,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":j?"border-blue-500 bg-blue-50 shadow-md":v?"border-green-500 bg-green-50":w?"border-red-500 bg-red-50":N?"border-gray-300 bg-gray-50":"border-gray-200 bg-white"}`,"data-testid":`${c}-${t.step}`,children:[e.jsxs("div",{className:"flex items-start gap-2 sm:gap-3 md:gap-4",children:[e.jsx("div",{className:`p-2 sm:p-2.5 md:p-3 rounded-xl flex-shrink-0 ${t.isSkipped?"bg-orange-100":C?"bg-yellow-100":j?"bg-blue-100":v?"bg-green-100":w?"bg-red-100":N?"bg-gray-200":"bg-gray-100"}`,children:_v(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(ie,{variant:"outline",className:`text-xs shrink-0 capitalize ${t.isSkipped?"bg-orange-100 text-orange-800 border-orange-200":j?"bg-yellow-100 text-yellow-800 border-yellow-200":v?"bg-green-100 text-green-800 border-green-200":w?"bg-red-100 text-red-800 border-red-200":N?"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(Un,{delayDuration:200,children:e.jsxs(Ui,{children:[e.jsx(Vi,{asChild:!0,children:e.jsx("button",{type:"button",className:"inline-flex items-center justify-center cursor-pointer hover:opacity-80 transition-opacity",onClick:D=>D.stopPropagation(),children:e.jsx(We,{className:"w-4 h-4 text-orange-600"})})}),e.jsxs(zi,{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(ed,{className:"w-3 h-3"}),"Skip Reason:"]}),e.jsx("p",{className:"text-xs text-gray-700",children:t.skipReason})]})]})}),v&&E&&e.jsx(ie,{className:"bg-green-600 text-white text-xs","data-testid":`${c}-completion-time`,children:bd(E)})]}),e.jsx("p",{className:"text-sm font-semibold text-gray-900","data-testid":`${c}-approver-name`,children:r?e.jsx("span",{className:"text-blue-600",children:"You"}):t.approver}),e.jsx("p",{className:"text-xs text-gray-600","data-testid":`${c}-role`,children:t.role})]}),e.jsxs("div",{className:"text-left sm:text-right flex-shrink-0",children:[e.jsx("p",{className:"text-xs text-gray-500 font-medium",children:"Turnaround Time (TAT)"}),e.jsxs("p",{className:"text-lg font-bold text-gray-900","data-testid":`${c}-tat-hours`,children:[S," hours"]})]})]}),v&&E!==void 0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Completed:"}),e.jsx("span",{className:"font-medium text-gray-900",children:t.timestamp?es(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:bd(E)})]}),e.jsx("div",{className:"space-y-2",children:(()=>{const D=Math.min(100,R),A=()=>f?"bg-red-600":R>=75?"bg-orange-500":R>=50?"bg-amber-500":"bg-green-600",k=()=>f?"text-red-600":R>=75?"text-orange-600":R>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(Qs,{value:D,className:"h-2 bg-gray-200",indicatorClassName:A(),"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 ${k()}`,children:[Math.round(D),"% of TAT used"]}),f&&B&&e.jsx(Un,{children:e.jsxs(Ui,{children:[e.jsx(Vi,{asChild:!0,children:e.jsx(I,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",onClick:()=>{g(b),u(!0)},children:e.jsx(Rn,{className:"w-3 h-3"})})}),e.jsx(zi,{children:e.jsx("p",{children:b?"Edit breach reason":"Add breach reason"})})]})})]}),P>0&&e.jsxs("span",{className:"text-green-600 font-semibold",children:["Saved ",It(P)]})]})]})})()}),f&&b&&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(Rn,{className:"w-3.5 h-3.5"}),"Breach Reason:"]}),e.jsx("p",{className:"text-sm text-gray-700 leading-relaxed whitespace-pre-line",children:b})]}),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(Os,{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&&(j||C)&&(a==null?void 0:a.sla)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Due by:"}),e.jsx("span",{className:"font-medium text-gray-900",children:a.sla.deadline?qs(a.sla.deadline,!0):"Not set"})]}),e.jsxs("div",{className:`border rounded-lg p-3 ${C?"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(Ze,{className:"w-4 h-4"}),"Current Approver - Time Tracking ",C&&"(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," / ",It(S)," allocated"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[(()=>{const D=a.sla.percentageUsed||0,A=()=>C?"bg-gray-500":D>=100?"bg-red-600":D>=75?"bg-orange-500":D>=50?"bg-amber-500":"bg-green-600",k=()=>C?"text-gray-600":D>=100?"text-red-600":D>=75?"text-orange-600":D>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(Qs,{value:a.sla.percentageUsed,className:"h-3",indicatorClassName:A(),"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 ${k()}`,children:["Progress: ",Math.min(100,a.sla.percentageUsed),"% of TAT used"]}),a.sla.status==="breached"&&B&&e.jsx(Un,{children:e.jsxs(Ui,{children:[e.jsx(Vi,{asChild:!0,children:e.jsx(I,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",onClick:()=>{g(b),u(!0)},children:e.jsx(Rn,{className:"w-3 h-3"})})}),e.jsx(zi,{children:e.jsx("p",{children:b?"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(Zn,{className:"w-4 h-4"}),"Deadline Breached"]}),b&&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(Rn,{className:"w-3.5 h-3.5"}),"Breach Reason:"]}),e.jsx("p",{className:"text-sm text-gray-700 leading-relaxed whitespace-pre-line",children:b})]})]}),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(hs,{className:"w-4 h-4"}),"Approaching Deadline"]})]})]})]}),N&&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(ju,{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 ",S," hours for approval"]})]})}),w&&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(xt,{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(ed,{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 ",es(t.timestamp)]})]}),t.tatAlerts&&t.tatAlerts.length>0&&e.jsx("div",{className:"mt-2 sm:mt-3 space-y-2",children:t.tatAlerts.map((D,A)=>{var k,M,O,L,Z,z;return e.jsx("div",{className:`p-2 sm:p-3 rounded-lg border ${D.isBreached?"bg-red-50 border-red-200":(D.thresholdPercentage||0)===75?"bg-orange-50 border-orange-200":"bg-yellow-50 border-yellow-200"}`,"data-testid":`${c}-tat-alert-${A}`,children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("div",{className:"flex-shrink-0 mt-0.5",children:[(D.thresholdPercentage||0)===50&&e.jsx(Rf,{className:"w-5 h-5 text-yellow-600"}),(D.thresholdPercentage||0)===75&&e.jsx(hs,{className:"w-5 h-5 text-orange-600"}),(D.thresholdPercentage||0)===100&&e.jsx(Zn,{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 ",A+1," - ",D.thresholdPercentage||0,"% TAT"]}),e.jsx(ie,{variant:"outline",className:`text-[10px] sm:text-xs shrink-0 ${D.isBreached?"bg-red-100 text-red-800 border-red-300":"bg-amber-100 text-amber-800 border-amber-300"}`,children:D.isBreached?"BREACHED":"WARNING"})]}),e.jsxs("p",{className:"text-[10px] sm:text-xs md:text-sm text-gray-700 mt-1",children:[D.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:It(Number(D.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:[It(Number(D.tatHoursElapsed||0)),((k=D.metadata)==null?void 0:k.tatTestMode)&&e.jsxs("span",{className:"text-purple-600 ml-1",children:["(",(Number(D.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 ${(D.tatHoursRemaining||0)<2?"text-red-600":"text-gray-900"}`,children:[It(Number(D.tatHoursRemaining||0)),((M=D.metadata)==null?void 0:M.tatTestMode)&&e.jsxs("span",{className:"text-purple-600 ml-1",children:["(",(Number(D.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:D.expectedCompletionTime?qs(D.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=D.metadata)==null?void 0:O.testMode)||((L=D.metadata)==null?void 0:L.tatTestMode))&&e.jsx(ie,{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: ",D.alertSentAt?es(D.alertSentAt):"N/A"]}),(((Z=D.metadata)==null?void 0:Z.testMode)||((z=D.metadata)==null?void 0:z.tatTestMode))&&e.jsx("p",{className:"text-[10px] text-purple-600 mt-1 italic",children:"Note: Test mode active (1 hour = 1 minute)"})]})]})]})},A)})}),t.timestamp&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:[v?"Approved":w?"Rejected":"Actioned"," on ",es(t.timestamp)]}),n&&!C&&(j||t.status==="pending")&&!v&&!w&&t.levelId&&l&&e.jsxs("div",{className:"mt-2 sm:mt-3 pt-2 sm:pt-3 border-t border-gray-200",children:[e.jsxs(I,{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:()=>l({levelId:t.levelId,approverName:t.approver,levelNumber:t.step}),"data-testid":`${c}-skip-button`,children:[e.jsx(We,{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:C?"Skip this approver to resume the workflow and move to next level":"Skip if approver is unavailable and move to next level"})]})]})]}),e.jsx(ot,{open:m,onOpenChange:u,children:e.jsxs(nt,{className:"sm:max-w-[500px]",children:[e.jsxs(ct,{children:[e.jsx(it,{children:b?"Edit Breach Reason":"Add Breach Reason"}),e.jsx(_t,{children:b?"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(ps,{placeholder:"Enter the reason for the breach...",value:h,onChange:D=>g(D.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(At,{children:[e.jsx(I,{variant:"outline",onClick:()=>{u(!1),g("")},disabled:p,children:"Cancel"}),e.jsx(I,{onClick:U,disabled:!h.trim()||p,className:"bg-red-600 hover:bg-red-700",children:p?"Saving...":"Save Reason"})]})]})})]})}function Ov({request:t,user:s,isInitiator:a,onSkipApprover:r,onRefresh:n}){return e.jsxs(te,{children:[e.jsx(me,{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(he,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(da,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Approval Workflow"]}),e.jsx(De,{className:"mt-1 sm:mt-2 text-xs sm:text-sm",children:"Track the approval progress through each step"})]}),t.totalSteps&&(()=>{var g;const i=t.totalSteps||1,l=t.currentStepRaw!==void 0?t.currentStepRaw:t.currentStep||1,o=((g=t.approvalFlow)==null?void 0:g.filter(p=>{const y=(p.status||"").toLowerCase();return y==="approved"||y==="rejected"}).length)||0,c=o>=i,d=(t.status||"").toLowerCase(),m=d==="approved"||d==="rejected"||d==="closed",u=l>i,h=Math.min(Math.max(1,l),i);return u?e.jsxs(ie,{variant:"outline",className:"font-medium text-xs sm:text-sm shrink-0 bg-blue-50 text-blue-700 border-blue-200",children:["Closure Step - ",o," of ",i," steps completed"]}):m||c?e.jsxs(ie,{variant:"outline",className:"font-medium text-xs sm:text-sm shrink-0 bg-green-50 text-green-700 border-green-200",children:["Completed - ",o," of ",i," steps"]}):e.jsxs(ie,{variant:"outline",className:"font-medium text-xs sm:text-sm shrink-0",children:["Step ",h," of ",i," - ",o," completed"]})})()]})}),e.jsx(se,{children:t.approvalFlow&&t.approvalFlow.length>0?e.jsx("div",{className:"space-y-4 sm:space-y-6",children:t.approvalFlow.map((i,l)=>{var g,p,y;const o=(g=t.approvals)==null?void 0:g.find(b=>b.levelId===i.levelId),c=(p=s==null?void 0:s.email)==null?void 0:p.toLowerCase(),d=(y=i.approverEmail)==null?void 0:y.toLowerCase(),m=c&&d&&c===d,u=t.currentStepRaw!==void 0?t.currentStepRaw:t.currentStep||1,h=i.step===u;return e.jsx(Lv,{step:i,index:l,approval:o,isCurrentUser:m,isInitiator:a,isCurrentLevel:h,onSkipApprover:r,onRefresh:n,testId:"workflow-step"},l)})}):e.jsx("p",{className:"text-sm text-gray-500 text-center py-8","data-testid":"no-workflow-steps",children:"No workflow steps defined"})})]})}const xo=x.createContext({});function go(t){const s=x.useRef(null);return s.current===null&&(s.current=t()),s.current}const fo=typeof window<"u",mh=fo?x.useLayoutEffect:x.useEffect,bi=x.createContext(null);function yo(t,s){t.indexOf(s)===-1&&t.push(s)}function bo(t,s){const a=t.indexOf(s);a>-1&&t.splice(a,1)}const ja=(t,s,a)=>a>s?s:a<t?t:a;let vo=()=>{};const Na={},uh=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function hh(t){return typeof t=="object"&&t!==null}const ph=t=>/^0[^.\s]+$/u.test(t);function jo(t){let s;return()=>(s===void 0&&(s=t()),s)}const Gs=t=>t,$v=(t,s)=>a=>s(t(a)),bn=(...t)=>t.reduce($v),dn=(t,s,a)=>{const r=s-t;return r===0?1:(a-t)/r};class No{constructor(){this.subscriptions=[]}add(s){return yo(this.subscriptions,s),()=>bo(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 l=this.subscriptions[i];l&&l(s,a,r)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const la=t=>t*1e3,Hs=t=>t/1e3;function xh(t,s){return s?t*(1e3/s):0}const gh=(t,s,a)=>(((1-3*a+3*s)*t+(3*a-6*s))*t+3*s)*t,Bv=1e-7,Uv=12;function Vv(t,s,a,r,n){let i,l,o=0;do l=s+(a-s)/2,i=gh(l,r,n)-t,i>0?a=l:s=l;while(Math.abs(i)>Bv&&++o<Uv);return l}function vn(t,s,a,r){if(t===s&&a===r)return Gs;const n=i=>Vv(i,0,1,t,a);return i=>i===0||i===1?i:gh(n(i),s,r)}const fh=t=>s=>s<=.5?t(2*s)/2:(2-t(2*(1-s)))/2,yh=t=>s=>1-t(1-s),bh=vn(.33,1.53,.69,.99),wo=yh(bh),vh=fh(wo),jh=t=>(t*=2)<1?.5*wo(t):.5*(2-Math.pow(2,-10*(t-1))),Co=t=>1-Math.sin(Math.acos(t)),Nh=yh(Co),wh=fh(Co),zv=vn(.42,0,1,1),Hv=vn(0,0,.58,1),Ch=vn(.42,0,.58,1),Wv=t=>Array.isArray(t)&&typeof t[0]!="number",Sh=t=>Array.isArray(t)&&typeof t[0]=="number",Gv={linear:Gs,easeIn:zv,easeInOut:Ch,easeOut:Hv,circIn:Co,circInOut:wh,circOut:Nh,backIn:wo,backInOut:vh,backOut:bh,anticipate:jh},Kv=t=>typeof t=="string",vd=t=>{if(Sh(t)){vo(t.length===4);const[s,a,r,n]=t;return vn(s,a,r,n)}else if(Kv(t))return Gv[t];return t},In=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function Yv(t,s){let a=new Set,r=new Set,n=!1,i=!1;const l=new WeakSet;let o={delta:0,timestamp:0,isProcessing:!1};function c(m){l.has(m)&&(d.schedule(m),t()),m(o)}const d={schedule:(m,u=!1,h=!1)=>{const p=h&&n?a:r;return u&&l.add(m),p.has(m)||p.add(m),m},cancel:m=>{r.delete(m),l.delete(m)},process:m=>{if(o=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 Zv=40;function Ah(t,s){let a=!1,r=!0;const n={delta:0,timestamp:0,isProcessing:!1},i=()=>a=!0,l=In.reduce((w,N)=>(w[N]=Yv(i),w),{}),{setup:o,read:c,resolveKeyframes:d,preUpdate:m,update:u,preRender:h,render:g,postRender:p}=l,y=()=>{const w=Na.useManualTiming?n.timestamp:performance.now();a=!1,Na.useManualTiming||(n.delta=r?1e3/60:Math.max(Math.min(w-n.timestamp,Zv),1)),n.timestamp=w,n.isProcessing=!0,o.process(n),c.process(n),d.process(n),m.process(n),u.process(n),h.process(n),g.process(n),p.process(n),n.isProcessing=!1,a&&s&&(r=!1,t(y))},b=()=>{a=!0,r=!0,n.isProcessing||t(y)};return{schedule:In.reduce((w,N)=>{const C=l[N];return w[N]=(S,E=!1,P=!1)=>(a||b(),C.schedule(S,E,P)),w},{}),cancel:w=>{for(let N=0;N<In.length;N++)l[In[N]].cancel(w)},state:n,steps:l}}const{schedule:Ft,cancel:Ea,state:ms,steps:Hi}=Ah(typeof requestAnimationFrame<"u"?requestAnimationFrame:Gs,!0);let Vn;function Xv(){Vn=void 0}const Ds={now:()=>(Vn===void 0&&Ds.set(ms.isProcessing||Na.useManualTiming?ms.timestamp:performance.now()),Vn),set:t=>{Vn=t,queueMicrotask(Xv)}},Th=t=>s=>typeof s=="string"&&s.startsWith(t),So=Th("--"),Jv=Th("var(--"),Ao=t=>Jv(t)?Qv.test(t.split("/*")[0].trim()):!1,Qv=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,Ar={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},mn={...Ar,transform:t=>ja(0,1,t)},En={...Ar,default:1},tn=t=>Math.round(t*1e5)/1e5,To=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function qv(t){return t==null}const ej=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,ko=(t,s)=>a=>!!(typeof a=="string"&&ej.test(a)&&a.startsWith(t)||s&&!qv(a)&&Object.prototype.hasOwnProperty.call(a,s)),kh=(t,s,a)=>r=>{if(typeof r!="string")return r;const[n,i,l,o]=r.match(To);return{[t]:parseFloat(n),[s]:parseFloat(i),[a]:parseFloat(l),alpha:o!==void 0?parseFloat(o):1}},tj=t=>ja(0,255,t),Wi={...Ar,transform:t=>Math.round(tj(t))},qa={test:ko("rgb","red"),parse:kh("red","green","blue"),transform:({red:t,green:s,blue:a,alpha:r=1})=>"rgba("+Wi.transform(t)+", "+Wi.transform(s)+", "+Wi.transform(a)+", "+tn(mn.transform(r))+")"};function sj(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 Cl={test:ko("#"),parse:sj,transform:qa.transform},jn=t=>({test:s=>typeof s=="string"&&s.endsWith(t)&&s.split(" ").length===1,parse:parseFloat,transform:s=>`${s}${t}`}),Ta=jn("deg"),oa=jn("%"),Ke=jn("px"),aj=jn("vh"),rj=jn("vw"),jd={...oa,parse:t=>oa.parse(t)/100,transform:t=>oa.transform(t*100)},cr={test:ko("hsl","hue"),parse:kh("hue","saturation","lightness"),transform:({hue:t,saturation:s,lightness:a,alpha:r=1})=>"hsla("+Math.round(t)+", "+oa.transform(tn(s))+", "+oa.transform(tn(a))+", "+tn(mn.transform(r))+")"},Xt={test:t=>qa.test(t)||Cl.test(t)||cr.test(t),parse:t=>qa.test(t)?qa.parse(t):cr.test(t)?cr.parse(t):Cl.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?qa.transform(t):cr.transform(t),getAnimatableNone:t=>{const s=Xt.parse(t);return s.alpha=0,Xt.transform(s)}},nj=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function ij(t){var s,a;return isNaN(t)&&typeof t=="string"&&(((s=t.match(To))==null?void 0:s.length)||0)+(((a=t.match(nj))==null?void 0:a.length)||0)>0}const Dh="number",Rh="color",lj="var",oj="var(",Nd="${}",cj=/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 un(t){const s=t.toString(),a=[],r={color:[],number:[],var:[]},n=[];let i=0;const o=s.replace(cj,c=>(Xt.test(c)?(r.color.push(i),n.push(Rh),a.push(Xt.parse(c))):c.startsWith(oj)?(r.var.push(i),n.push(lj),a.push(c)):(r.number.push(i),n.push(Dh),a.push(parseFloat(c))),++i,Nd)).split(Nd);return{values:a,split:o,indexes:r,types:n}}function Ph(t){return un(t).values}function Ih(t){const{split:s,types:a}=un(t),r=s.length;return n=>{let i="";for(let l=0;l<r;l++)if(i+=s[l],n[l]!==void 0){const o=a[l];o===Dh?i+=tn(n[l]):o===Rh?i+=Xt.transform(n[l]):i+=n[l]}return i}}const dj=t=>typeof t=="number"?0:Xt.test(t)?Xt.getAnimatableNone(t):t;function mj(t){const s=Ph(t);return Ih(t)(s.map(dj))}const Ma={test:ij,parse:Ph,createTransformer:Ih,getAnimatableNone:mj};function Gi(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 uj({hue:t,saturation:s,lightness:a,alpha:r}){t/=360,s/=100,a/=100;let n=0,i=0,l=0;if(!s)n=i=l=a;else{const o=a<.5?a*(1+s):a+s-a*s,c=2*a-o;n=Gi(c,o,t+1/3),i=Gi(c,o,t),l=Gi(c,o,t-1/3)}return{red:Math.round(n*255),green:Math.round(i*255),blue:Math.round(l*255),alpha:r}}function Jn(t,s){return a=>a>0?s:t}const $t=(t,s,a)=>t+(s-t)*a,Ki=(t,s,a)=>{const r=t*t,n=a*(s*s-r)+r;return n<0?0:Math.sqrt(n)},hj=[Cl,qa,cr],pj=t=>hj.find(s=>s.test(t));function wd(t){const s=pj(t);if(!s)return!1;let a=s.parse(t);return s===cr&&(a=uj(a)),a}const Cd=(t,s)=>{const a=wd(t),r=wd(s);if(!a||!r)return Jn(t,s);const n={...a};return i=>(n.red=Ki(a.red,r.red,i),n.green=Ki(a.green,r.green,i),n.blue=Ki(a.blue,r.blue,i),n.alpha=$t(a.alpha,r.alpha,i),qa.transform(n))},Sl=new Set(["none","hidden"]);function xj(t,s){return Sl.has(t)?a=>a<=0?t:s:a=>a>=1?s:t}function gj(t,s){return a=>$t(t,s,a)}function Do(t){return typeof t=="number"?gj:typeof t=="string"?Ao(t)?Jn:Xt.test(t)?Cd:bj:Array.isArray(t)?Eh:typeof t=="object"?Xt.test(t)?Cd:fj:Jn}function Eh(t,s){const a=[...t],r=a.length,n=t.map((i,l)=>Do(i)(i,s[l]));return i=>{for(let l=0;l<r;l++)a[l]=n[l](i);return a}}function fj(t,s){const a={...t,...s},r={};for(const n in a)t[n]!==void 0&&s[n]!==void 0&&(r[n]=Do(t[n])(t[n],s[n]));return n=>{for(const i in r)a[i]=r[i](n);return a}}function yj(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],l=t.indexes[i][r[i]],o=t.values[l]??0;a[n]=o,r[i]++}return a}const bj=(t,s)=>{const a=Ma.createTransformer(s),r=un(t),n=un(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?Sl.has(t)&&!n.values.length||Sl.has(s)&&!r.values.length?xj(t,s):bn(Eh(yj(r,n),n.values),a):Jn(t,s)};function Mh(t,s,a){return typeof t=="number"&&typeof s=="number"&&typeof a=="number"?$t(t,s,a):Do(t)(t,s)}const vj=t=>{const s=({timestamp:a})=>t(a);return{start:(a=!0)=>Ft.update(s,a),stop:()=>Ea(s),now:()=>ms.isProcessing?ms.timestamp:Ds.now()}},Fh=(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)})`},Qn=2e4;function Ro(t){let s=0;const a=50;let r=t.next(s);for(;!r.done&&s<Qn;)s+=a,r=t.next(s);return s>=Qn?1/0:s}function jj(t,s=100,a){const r=a({...t,keyframes:[0,s]}),n=Math.min(Ro(r),Qn);return{type:"keyframes",ease:i=>r.next(n*i).value/s,duration:Hs(n)}}const Nj=5;function _h(t,s,a){const r=Math.max(s-Nj,0);return xh(a-t(r),s-r)}const Ut={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},Yi=.001;function wj({duration:t=Ut.duration,bounce:s=Ut.bounce,velocity:a=Ut.velocity,mass:r=Ut.mass}){let n,i,l=1-s;l=ja(Ut.minDamping,Ut.maxDamping,l),t=ja(Ut.minDuration,Ut.maxDuration,Hs(t)),l<1?(n=d=>{const m=d*l,u=m*t,h=m-a,g=Al(d,l),p=Math.exp(-u);return Yi-h/g*p},i=d=>{const u=d*l*t,h=u*a+a,g=Math.pow(l,2)*Math.pow(d,2)*t,p=Math.exp(-u),y=Al(Math.pow(d,2),l);return(-n(d)+Yi>0?-1:1)*((h-g)*p)/y}):(n=d=>{const m=Math.exp(-d*t),u=(d-a)*t+1;return-Yi+m*u},i=d=>{const m=Math.exp(-d*t),u=(a-d)*(t*t);return m*u});const o=5/t,c=Sj(n,i,o);if(t=la(t),isNaN(c))return{stiffness:Ut.stiffness,damping:Ut.damping,duration:t};{const d=Math.pow(c,2)*r;return{stiffness:d,damping:l*2*Math.sqrt(r*d),duration:t}}}const Cj=12;function Sj(t,s,a){let r=a;for(let n=1;n<Cj;n++)r=r-t(r)/s(r);return r}function Al(t,s){return t*Math.sqrt(1-s*s)}const Aj=["duration","bounce"],Tj=["stiffness","damping","mass"];function Sd(t,s){return s.some(a=>t[a]!==void 0)}function kj(t){let s={velocity:Ut.velocity,stiffness:Ut.stiffness,damping:Ut.damping,mass:Ut.mass,isResolvedFromDuration:!1,...t};if(!Sd(t,Tj)&&Sd(t,Aj))if(t.visualDuration){const a=t.visualDuration,r=2*Math.PI/(a*1.2),n=r*r,i=2*ja(.05,1,1-(t.bounce||0))*Math.sqrt(n);s={...s,mass:Ut.mass,stiffness:n,damping:i}}else{const a=wj(t);s={...s,...a,mass:Ut.mass},s.isResolvedFromDuration=!0}return s}function qn(t=Ut.visualDuration,s=Ut.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],l=a.keyframes[a.keyframes.length-1],o={done:!1,value:i},{stiffness:c,damping:d,mass:m,duration:u,velocity:h,isResolvedFromDuration:g}=kj({...a,velocity:-Hs(a.velocity||0)}),p=h||0,y=d/(2*Math.sqrt(c*m)),b=l-i,j=Hs(Math.sqrt(c/m)),v=Math.abs(b)<5;r||(r=v?Ut.restSpeed.granular:Ut.restSpeed.default),n||(n=v?Ut.restDelta.granular:Ut.restDelta.default);let w;if(y<1){const C=Al(j,y);w=S=>{const E=Math.exp(-y*j*S);return l-E*((p+y*j*b)/C*Math.sin(C*S)+b*Math.cos(C*S))}}else if(y===1)w=C=>l-Math.exp(-j*C)*(b+(p+j*b)*C);else{const C=j*Math.sqrt(y*y-1);w=S=>{const E=Math.exp(-y*j*S),P=Math.min(C*S,300);return l-E*((p+y*j*b)*Math.sinh(P)+C*b*Math.cosh(P))/C}}const N={calculatedDuration:g&&u||null,next:C=>{const S=w(C);if(g)o.done=C>=u;else{let E=C===0?p:0;y<1&&(E=C===0?la(p):_h(w,C,S));const P=Math.abs(E)<=r,R=Math.abs(l-S)<=n;o.done=P&&R}return o.value=o.done?l:S,o},toString:()=>{const C=Math.min(Ro(N),Qn),S=Fh(E=>N.next(C*E).value,C,30);return C+"ms "+S},toTransition:()=>{}};return N}qn.applyToOptions=t=>{const s=jj(t,100,qn);return t.ease=s.ease,t.duration=la(s.duration),t.type="keyframes",t};function Tl({keyframes:t,velocity:s=0,power:a=.8,timeConstant:r=325,bounceDamping:n=10,bounceStiffness:i=500,modifyTarget:l,min:o,max:c,restDelta:d=.5,restSpeed:m}){const u=t[0],h={done:!1,value:u},g=P=>o!==void 0&&P<o||c!==void 0&&P>c,p=P=>o===void 0?c:c===void 0||Math.abs(o-P)<Math.abs(c-P)?o:c;let y=a*s;const b=u+y,j=l===void 0?b:l(b);j!==b&&(y=j-u);const v=P=>-y*Math.exp(-P/r),w=P=>j+v(P),N=P=>{const R=v(P),f=w(P);h.done=Math.abs(R)<=d,h.value=h.done?j:f};let C,S;const E=P=>{g(h.value)&&(C=P,S=qn({keyframes:[h.value,p(h.value)],velocity:_h(w,P,h.value),damping:n,stiffness:i,restDelta:d,restSpeed:m}))};return E(0),{calculatedDuration:null,next:P=>{let R=!1;return!S&&C===void 0&&(R=!0,N(P),E(P)),C!==void 0&&P>=C?S.next(P-C):(!R&&N(P),h)}}}function Dj(t,s,a){const r=[],n=a||Na.mix||Mh,i=t.length-1;for(let l=0;l<i;l++){let o=n(t[l],t[l+1]);if(s){const c=Array.isArray(s)?s[l]||Gs:s;o=bn(c,o)}r.push(o)}return r}function Rj(t,s,{clamp:a=!0,ease:r,mixer:n}={}){const i=t.length;if(vo(i===s.length),i===1)return()=>s[0];if(i===2&&s[0]===s[1])return()=>s[1];const l=t[0]===t[1];t[0]>t[i-1]&&(t=[...t].reverse(),s=[...s].reverse());const o=Dj(s,r,n),c=o.length,d=m=>{if(l&&m<t[0])return s[0];let u=0;if(c>1)for(;u<t.length-2&&!(m<t[u+1]);u++);const h=dn(t[u],t[u+1],m);return o[u](h)};return a?m=>d(ja(t[0],t[i-1],m)):d}function Pj(t,s){const a=t[t.length-1];for(let r=1;r<=s;r++){const n=dn(0,s,r);t.push($t(a,1,n))}}function Ij(t){const s=[0];return Pj(s,t.length-1),s}function Ej(t,s){return t.map(a=>a*s)}function Mj(t,s){return t.map(()=>s||Ch).splice(0,t.length-1)}function sn({duration:t=300,keyframes:s,times:a,ease:r="easeInOut"}){const n=Wv(r)?r.map(vd):vd(r),i={done:!1,value:s[0]},l=Ej(a&&a.length===s.length?a:Ij(s),t),o=Rj(l,s,{ease:Array.isArray(n)?n:Mj(s,n)});return{calculatedDuration:t,next:c=>(i.value=o(c),i.done=c>=t,i)}}const Fj=t=>t!==null;function Po(t,{repeat:s,repeatType:a="loop"},r,n=1){const i=t.filter(Fj),o=n<0||s&&a!=="loop"&&s%2===1?0:i.length-1;return!o||r===void 0?i[o]:r}const _j={decay:Tl,inertia:Tl,tween:sn,keyframes:sn,spring:qn};function Lh(t){typeof t.type=="string"&&(t.type=_j[t.type])}class Io{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 Lj=t=>t/100;class Eo extends Io{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!==Ds.now()&&this.tick(Ds.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;Lh(s);const{type:a=sn,repeat:r=0,repeatDelay:n=0,repeatType:i,velocity:l=0}=s;let{keyframes:o}=s;const c=a||sn;c!==sn&&typeof o[0]!="number"&&(this.mixKeyframes=bn(Lj,Mh(o[0],o[1])),o=[0,100]);const d=c({...s,keyframes:o});i==="mirror"&&(this.mirroredGenerator=c({...s,keyframes:[...o].reverse(),velocity:-l})),d.calculatedDuration===null&&(d.calculatedDuration=Ro(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:l,resolvedDuration:o,calculatedDuration:c}=this;if(this.startTime===null)return r.next(0);const{delay:d=0,keyframes:m,repeat:u,repeatType:h,repeatDelay:g,type:p,onUpdate:y,finalKeyframe:b}=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 j=this.currentTime-d*(this.playbackSpeed>=0?1:-1),v=this.playbackSpeed>=0?j<0:j>n;this.currentTime=Math.max(j,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=n);let w=this.currentTime,N=r;if(u){const P=Math.min(this.currentTime,n)/o;let R=Math.floor(P),f=P%1;!f&&P>=1&&(f=1),f===1&&R--,R=Math.min(R,u+1),!!(R%2)&&(h==="reverse"?(f=1-f,g&&(f-=g/o)):h==="mirror"&&(N=l)),w=ja(0,1,f)*o}const C=v?{done:!1,value:m[0]}:N.next(w);i&&(C.value=i(C.value));let{done:S}=C;!v&&c!==null&&(S=this.playbackSpeed>=0?this.currentTime>=n:this.currentTime<=0);const E=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&S);return E&&p!==Tl&&(C.value=Po(m,this.options,b,this.speed)),y&&y(C.value),E&&this.finish(),C}then(s,a){return this.finished.then(s,a)}get duration(){return Hs(this.calculatedDuration)}get iterationDuration(){const{delay:s=0}=this.options||{};return this.duration+Hs(s)}get time(){return Hs(this.currentTime)}set time(s){var a;s=la(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(Ds.now());const a=this.playbackSpeed!==s;this.playbackSpeed=s,a&&(this.time=Hs(this.currentTime))}play(){var n,i;if(this.isStopped)return;const{driver:s=vj,startTime:a}=this.options;this.driver||(this.driver=s(l=>this.tick(l))),(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(Ds.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 Oj(t){for(let s=1;s<t.length;s++)t[s]??(t[s]=t[s-1])}const er=t=>t*180/Math.PI,kl=t=>{const s=er(Math.atan2(t[1],t[0]));return Dl(s)},$j={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:kl,rotateZ:kl,skewX:t=>er(Math.atan(t[1])),skewY:t=>er(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},Dl=t=>(t=t%360,t<0&&(t+=360),t),Ad=kl,Td=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),kd=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),Bj={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Td,scaleY:kd,scale:t=>(Td(t)+kd(t))/2,rotateX:t=>Dl(er(Math.atan2(t[6],t[5]))),rotateY:t=>Dl(er(Math.atan2(-t[2],t[0]))),rotateZ:Ad,rotate:Ad,skewX:t=>er(Math.atan(t[4])),skewY:t=>er(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function Rl(t){return t.includes("scale")?1:0}function Pl(t,s){if(!t||t==="none")return Rl(s);const a=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,n;if(a)r=Bj,n=a;else{const o=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=$j,n=o}if(!n)return Rl(s);const i=r[s],l=n[1].split(",").map(Vj);return typeof i=="function"?i(l):l[i]}const Uj=(t,s)=>{const{transform:a="none"}=getComputedStyle(t);return Pl(a,s)};function Vj(t){return parseFloat(t.trim())}const Tr=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],kr=new Set(Tr),Dd=t=>t===Ar||t===Ke,zj=new Set(["x","y","z"]),Hj=Tr.filter(t=>!zj.has(t));function Wj(t){const s=[];return Hj.forEach(a=>{const r=t.getValue(a);r!==void 0&&(s.push([a,r.get()]),r.set(a.startsWith("scale")?1:0))}),s}const tr={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})=>Pl(s,"x"),y:(t,{transform:s})=>Pl(s,"y")};tr.translateX=tr.x;tr.translateY=tr.y;const sr=new Set;let Il=!1,El=!1,Ml=!1;function Oh(){if(El){const t=Array.from(sr).filter(r=>r.needsMeasurement),s=new Set(t.map(r=>r.element)),a=new Map;s.forEach(r=>{const n=Wj(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,l])=>{var o;(o=r.getValue(i))==null||o.set(l)})}),t.forEach(r=>r.measureEndState()),t.forEach(r=>{r.suspendedScrollY!==void 0&&window.scrollTo(0,r.suspendedScrollY)})}El=!1,Il=!1,sr.forEach(t=>t.complete(Ml)),sr.clear()}function $h(){sr.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(El=!0)})}function Gj(){Ml=!0,$h(),Oh(),Ml=!1}class Mo{constructor(s,a,r,n,i,l=!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=l}scheduleResolve(){this.state="scheduled",this.isAsync?(sr.add(this),Il||(Il=!0,Ft.read($h),Ft.resolveKeyframes(Oh))):(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(),l=s[s.length-1];if(i!==void 0)s[0]=i;else if(r&&a){const o=r.readValue(a,l);o!=null&&(s[0]=o)}s[0]===void 0&&(s[0]=l),n&&i===void 0&&n.set(s[0])}Oj(s)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(s=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,s),sr.delete(this)}cancel(){this.state==="scheduled"&&(sr.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Kj=t=>t.startsWith("--");function Yj(t,s,a){Kj(s)?t.style.setProperty(s,a):t.style[s]=a}const Zj=jo(()=>window.ScrollTimeline!==void 0),Xj={};function Jj(t,s){const a=jo(t);return()=>Xj[s]??a()}const Bh=Jj(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),qr=([t,s,a,r])=>`cubic-bezier(${t}, ${s}, ${a}, ${r})`,Rd={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:qr([0,.65,.55,1]),circOut:qr([.55,0,1,.45]),backIn:qr([.31,.01,.66,-.59]),backOut:qr([.33,1.53,.69,.99])};function Uh(t,s){if(t)return typeof t=="function"?Bh()?Fh(t,s):"ease-out":Sh(t)?qr(t):Array.isArray(t)?t.map(a=>Uh(a,s)||Rd.easeOut):Rd[t]}function Qj(t,s,a,{delay:r=0,duration:n=300,repeat:i=0,repeatType:l="loop",ease:o="easeOut",times:c}={},d=void 0){const m={[s]:a};c&&(m.offset=c);const u=Uh(o,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:l==="reverse"?"alternate":"normal"};return d&&(h.pseudoElement=d),t.animate(m,h)}function Vh(t){return typeof t=="function"&&"applyToOptions"in t}function qj({type:t,...s}){return Vh(t)&&Bh()?t.applyToOptions(s):(s.duration??(s.duration=300),s.ease??(s.ease="easeOut"),s)}class eN extends Io{constructor(s){if(super(),this.finishedTime=null,this.isStopped=!1,!s)return;const{element:a,name:r,keyframes:n,pseudoElement:i,allowFlatten:l=!1,finalKeyframe:o,onComplete:c}=s;this.isPseudoElement=!!i,this.allowFlatten=l,this.options=s,vo(typeof s.type!="string");const d=qj(s);this.animation=Qj(a,r,n,d,i),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const m=Po(n,this.options,o,this.speed);this.updateMotionValue?this.updateMotionValue(m):Yj(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 Hs(Number(s))}get iterationDuration(){const{delay:s=0}=this.options||{};return this.duration+Hs(s)}get time(){return Hs(Number(this.animation.currentTime)||0)}set time(s){this.finishedTime=null,this.animation.currentTime=la(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&&Zj()?(this.animation.timeline=s,Gs):a(this)}}const zh={anticipate:jh,backInOut:vh,circInOut:wh};function tN(t){return t in zh}function sN(t){typeof t.ease=="string"&&tN(t.ease)&&(t.ease=zh[t.ease])}const Pd=10;class aN extends eN{constructor(s){sN(s),Lh(s),super(s),s.startTime&&(this.startTime=s.startTime),this.options=s}updateMotionValue(s){const{motionValue:a,onUpdate:r,onComplete:n,element:i,...l}=this.options;if(!a)return;if(s!==void 0){a.set(s);return}const o=new Eo({...l,autoplay:!1}),c=la(this.finishedTime??this.time);a.setWithVelocity(o.sample(c-Pd).value,o.sample(c).value,Pd),o.stop()}}const Id=(t,s)=>s==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(Ma.test(t)||t==="0")&&!t.startsWith("url("));function rN(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 nN(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],l=Id(n,s),o=Id(i,s);return!l||!o?!1:rN(t)||(a==="spring"||Vh(a))&&r}function Fl(t){t.duration=0,t.type="keyframes"}const iN=new Set(["opacity","clipPath","filter","transform"]),lN=jo(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function oN(t){var m;const{motionValue:s,name:a,repeatDelay:r,repeatType:n,damping:i,type:l}=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 lN()&&a&&iN.has(a)&&(a!=="transform"||!d)&&!c&&!r&&n!=="mirror"&&i!==0&&l!=="inertia"}const cN=40;class dN extends Io{constructor({autoplay:s=!0,delay:a=0,type:r="keyframes",repeat:n=0,repeatDelay:i=0,repeatType:l="loop",keyframes:o,name:c,motionValue:d,element:m,...u}){var p;super(),this.stop=()=>{var y,b;this._animation&&(this._animation.stop(),(y=this.stopTimeline)==null||y.call(this)),(b=this.keyframeResolver)==null||b.cancel()},this.createdAt=Ds.now();const h={autoplay:s,delay:a,type:r,repeat:n,repeatDelay:i,repeatType:l,name:c,motionValue:d,element:m,...u},g=(m==null?void 0:m.KeyframeResolver)||Mo;this.keyframeResolver=new g(o,(y,b,j)=>this.onKeyframesResolved(y,b,h,!j),c,d,m),(p=this.keyframeResolver)==null||p.scheduleResolve()}onKeyframesResolved(s,a,r,n){this.keyframeResolver=void 0;const{name:i,type:l,velocity:o,delay:c,isHandoff:d,onUpdate:m}=r;this.resolvedAt=Ds.now(),nN(s,i,l,o)||((Na.instantAnimations||!c)&&(m==null||m(Po(s,r,a))),s[0]=s[s.length-1],Fl(r),r.repeat=0);const h={startTime:n?this.resolvedAt?this.resolvedAt-this.createdAt>cN?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:a,...r,keyframes:s},g=!d&&oN(h)?new aN({...h,element:h.motionValue.owner.current}):new Eo(h);g.finished.then(()=>this.notifyFinished()).catch(Gs),this.pendingTimeline&&(this.stopTimeline=g.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=g}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(),Gj()),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 mN=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function uN(t){const s=mN.exec(t);if(!s)return[,];const[,a,r,n]=s;return[`--${a??r}`,n]}function Hh(t,s,a=1){const[r,n]=uN(t);if(!r)return;const i=window.getComputedStyle(s).getPropertyValue(r);if(i){const l=i.trim();return uh(l)?parseFloat(l):l}return Ao(n)?Hh(n,s,a+1):n}function Fo(t,s){return(t==null?void 0:t[s])??(t==null?void 0:t.default)??t}const Wh=new Set(["width","height","top","left","right","bottom",...Tr]),hN={test:t=>t==="auto",parse:t=>t},Gh=t=>s=>s.test(t),Kh=[Ar,Ke,oa,Ta,rj,aj,hN],Ed=t=>Kh.find(Gh(t));function pN(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||ph(t):!0}const xN=new Set(["brightness","contrast","saturate","opacity"]);function gN(t){const[s,a]=t.slice(0,-1).split("(");if(s==="drop-shadow")return t;const[r]=a.match(To)||[];if(!r)return t;const n=a.replace(r,"");let i=xN.has(s)?1:0;return r!==a&&(i*=100),s+"("+i+n+")"}const fN=/\b([a-z-]*)\(.*?\)/gu,_l={...Ma,getAnimatableNone:t=>{const s=t.match(fN);return s?s.map(gN).join(" "):t}},Md={...Ar,transform:Math.round},yN={rotate:Ta,rotateX:Ta,rotateY:Ta,rotateZ:Ta,scale:En,scaleX:En,scaleY:En,scaleZ:En,skew:Ta,skewX:Ta,skewY:Ta,distance:Ke,translateX:Ke,translateY:Ke,translateZ:Ke,x:Ke,y:Ke,z:Ke,perspective:Ke,transformPerspective:Ke,opacity:mn,originX:jd,originY:jd,originZ:Ke},_o={borderWidth:Ke,borderTopWidth:Ke,borderRightWidth:Ke,borderBottomWidth:Ke,borderLeftWidth:Ke,borderRadius:Ke,radius:Ke,borderTopLeftRadius:Ke,borderTopRightRadius:Ke,borderBottomRightRadius:Ke,borderBottomLeftRadius:Ke,width:Ke,maxWidth:Ke,height:Ke,maxHeight:Ke,top:Ke,right:Ke,bottom:Ke,left:Ke,padding:Ke,paddingTop:Ke,paddingRight:Ke,paddingBottom:Ke,paddingLeft:Ke,margin:Ke,marginTop:Ke,marginRight:Ke,marginBottom:Ke,marginLeft:Ke,backgroundPositionX:Ke,backgroundPositionY:Ke,...yN,zIndex:Md,fillOpacity:mn,strokeOpacity:mn,numOctaves:Md},bN={..._o,color:Xt,backgroundColor:Xt,outlineColor:Xt,fill:Xt,stroke:Xt,borderColor:Xt,borderTopColor:Xt,borderRightColor:Xt,borderBottomColor:Xt,borderLeftColor:Xt,filter:_l,WebkitFilter:_l},Yh=t=>bN[t];function Zh(t,s){let a=Yh(t);return a!==_l&&(a=Ma),a.getAnimatableNone?a.getAnimatableNone(s):void 0}const vN=new Set(["auto","none","0"]);function jN(t,s,a){let r=0,n;for(;r<t.length&&!n;){const i=t[r];typeof i=="string"&&!vN.has(i)&&un(i).values.length&&(n=t[r]),r++}if(n&&a)for(const i of s)t[i]=Zh(a,n)}class NN extends Mo{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(),Ao(d))){const m=Hh(d,a.current);m!==void 0&&(s[c]=m),c===s.length-1&&(this.finalKeyframe=d)}}if(this.resolveNoneKeyframes(),!Wh.has(r)||s.length!==2)return;const[n,i]=s,l=Ed(n),o=Ed(i);if(l!==o)if(Dd(l)&&Dd(o))for(let c=0;c<s.length;c++){const d=s[c];typeof d=="string"&&(s[c]=parseFloat(d))}else tr[r]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:s,name:a}=this,r=[];for(let n=0;n<s.length;n++)(s[n]===null||pN(s[n]))&&r.push(n);r.length&&jN(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=tr[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 o;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,l=r[i];r[i]=tr[a](s.measureViewportBox(),window.getComputedStyle(s.current)),l!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=l),(o=this.removedTransforms)!=null&&o.length&&this.removedTransforms.forEach(([c,d])=>{s.getValue(c).set(d)}),this.resolveNoneKeyframes()}}function wN(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 Xh=(t,s)=>s&&typeof t=="number"?s.transform(t):t;function Jh(t){return hh(t)&&"offsetHeight"in t}const Fd=30,CN=t=>!isNaN(parseFloat(t));class SN{constructor(s,a={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=r=>{var i;const n=Ds.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 l of this.dependents)l.dirty()},this.hasAnimated=!1,this.setCurrent(s),this.owner=a.owner}setCurrent(s){this.current=s,this.updatedAt=Ds.now(),this.canTrackVelocity===null&&s!==void 0&&(this.canTrackVelocity=CN(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 No);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=Ds.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||s-this.updatedAt>Fd)return 0;const a=Math.min(this.updatedAt-this.prevUpdatedAt,Fd);return xh(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 yr(t,s){return new SN(t,s)}const{schedule:Lo}=Ah(queueMicrotask,!1),Js={x:!1,y:!1};function Qh(){return Js.x||Js.y}function AN(t){return t==="x"||t==="y"?Js[t]?null:(Js[t]=!0,()=>{Js[t]=!1}):Js.x||Js.y?null:(Js.x=Js.y=!0,()=>{Js.x=Js.y=!1})}function qh(t,s){const a=wN(t),r=new AbortController,n={passive:!0,...s,signal:r.signal};return[a,n,()=>r.abort()]}function _d(t){return!(t.pointerType==="touch"||Qh())}function TN(t,s,a={}){const[r,n,i]=qh(t,a),l=o=>{if(!_d(o))return;const{target:c}=o,d=s(c,o);if(typeof d!="function"||!c)return;const m=u=>{_d(u)&&(d(u),c.removeEventListener("pointerleave",m))};c.addEventListener("pointerleave",m,n)};return r.forEach(o=>{o.addEventListener("pointerenter",l,n)}),i}const ep=(t,s)=>s?t===s?!0:ep(t,s.parentElement):!1,Oo=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,kN=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function DN(t){return kN.has(t.tagName)||t.tabIndex!==-1}const zn=new WeakSet;function Ld(t){return s=>{s.key==="Enter"&&t(s)}}function Zi(t,s){t.dispatchEvent(new PointerEvent("pointer"+s,{isPrimary:!0,bubbles:!0}))}const RN=(t,s)=>{const a=t.currentTarget;if(!a)return;const r=Ld(()=>{if(zn.has(a))return;Zi(a,"down");const n=Ld(()=>{Zi(a,"up")}),i=()=>Zi(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 Od(t){return Oo(t)&&!Qh()}function PN(t,s,a={}){const[r,n,i]=qh(t,a),l=o=>{const c=o.currentTarget;if(!Od(o))return;zn.add(c);const d=s(c,o),m=(g,p)=>{window.removeEventListener("pointerup",u),window.removeEventListener("pointercancel",h),zn.has(c)&&zn.delete(c),Od(g)&&typeof d=="function"&&d(g,{success:p})},u=g=>{m(g,c===window||c===document||a.useGlobalTarget||ep(c,g.target))},h=g=>{m(g,!1)};window.addEventListener("pointerup",u,n),window.addEventListener("pointercancel",h,n)};return r.forEach(o=>{(a.useGlobalTarget?window:o).addEventListener("pointerdown",l,n),Jh(o)&&(o.addEventListener("focus",d=>RN(d,n)),!DN(o)&&!o.hasAttribute("tabindex")&&(o.tabIndex=0))}),i}function tp(t){return hh(t)&&"ownerSVGElement"in t}function IN(t){return tp(t)&&t.tagName==="svg"}const ys=t=>!!(t&&t.getVelocity),EN=[...Kh,Xt,Ma],MN=t=>EN.find(Gh(t)),$o=x.createContext({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});function $d(t,s){if(typeof t=="function")return t(s);t!=null&&(t.current=s)}function FN(...t){return s=>{let a=!1;const r=t.map(n=>{const i=$d(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():$d(t[n],null)}}}}function _N(...t){return x.useCallback(FN(...t),t)}class LN extends x.Component{getSnapshotBeforeUpdate(s){const a=this.props.childRef.current;if(a&&s.isPresent&&!this.props.isPresent){const r=a.offsetParent,n=Jh(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 ON({children:t,isPresent:s,anchorX:a,root:r}){const n=x.useId(),i=x.useRef(null),l=x.useRef({width:0,height:0,top:0,left:0,right:0}),{nonce:o}=x.useContext($o),c=_N(i,t==null?void 0:t.ref);return x.useInsertionEffect(()=>{const{width:d,height:m,top:u,left:h,right:g}=l.current;if(s||!i.current||!d||!m)return;const p=a==="left"?`left: ${h}`:`right: ${g}`;i.current.dataset.motionPopId=n;const y=document.createElement("style");o&&(y.nonce=o);const b=r??document.head;return b.appendChild(y),y.sheet&&y.sheet.insertRule(`
|
||
[data-motion-pop-id="${n}"] {
|
||
position: absolute !important;
|
||
width: ${d}px !important;
|
||
height: ${m}px !important;
|
||
${p}px !important;
|
||
top: ${u}px !important;
|
||
}
|
||
`),()=>{b.contains(y)&&b.removeChild(y)}},[s]),e.jsx(LN,{isPresent:s,childRef:i,sizeRef:l,children:x.cloneElement(t,{ref:c})})}const $N=({children:t,initial:s,isPresent:a,onExitComplete:r,custom:n,presenceAffectsLayout:i,mode:l,anchorX:o,root:c})=>{const d=go(BN),m=x.useId();let u=!0,h=x.useMemo(()=>(u=!1,{id:m,initial:s,isPresent:a,custom:n,onExitComplete:g=>{d.set(g,!0);for(const p of d.values())if(!p)return;r&&r()},register:g=>(d.set(g,!1),()=>d.delete(g))}),[a,d,r]);return i&&u&&(h={...h}),x.useMemo(()=>{d.forEach((g,p)=>d.set(p,!1))},[a]),x.useEffect(()=>{!a&&!d.size&&r&&r()},[a]),l==="popLayout"&&(t=e.jsx(ON,{isPresent:a,anchorX:o,root:c,children:t})),e.jsx(bi.Provider,{value:h,children:t})};function BN(){return new Map}function sp(t=!0){const s=x.useContext(bi);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 l=x.useCallback(()=>t&&r&&r(i),[i,r,t]);return!a&&r?[!1,l]:[!0]}const Mn=t=>t.key||"";function Bd(t){const s=[];return x.Children.forEach(t,a=>{x.isValidElement(a)&&s.push(a)}),s}const vi=({children:t,custom:s,initial:a=!0,onExitComplete:r,presenceAffectsLayout:n=!0,mode:i="sync",propagate:l=!1,anchorX:o="left",root:c})=>{const[d,m]=sp(l),u=x.useMemo(()=>Bd(t),[t]),h=l&&!d?[]:u.map(Mn),g=x.useRef(!0),p=x.useRef(u),y=go(()=>new Map),[b,j]=x.useState(u),[v,w]=x.useState(u);mh(()=>{g.current=!1,p.current=u;for(let S=0;S<v.length;S++){const E=Mn(v[S]);h.includes(E)?y.delete(E):y.get(E)!==!0&&y.set(E,!1)}},[v,h.length,h.join("-")]);const N=[];if(u!==b){let S=[...u];for(let E=0;E<v.length;E++){const P=v[E],R=Mn(P);h.includes(R)||(S.splice(E,0,P),N.push(P))}return i==="wait"&&N.length&&(S=N),w(Bd(S)),j(u),null}const{forceRender:C}=x.useContext(xo);return e.jsx(e.Fragment,{children:v.map(S=>{const E=Mn(S),P=l&&!d?!1:u===v||h.includes(E),R=()=>{if(y.has(E))y.set(E,!0);else return;let f=!0;y.forEach(T=>{T||(f=!1)}),f&&(C==null||C(),w(p.current),l&&(m==null||m()),r&&r())};return e.jsx($N,{isPresent:P,initial:!g.current||a?void 0:!1,custom:s,presenceAffectsLayout:n,mode:i,root:c,onExitComplete:P?void 0:R,anchorX:o,children:S},E)})})},ap=x.createContext({strict:!1}),Ud={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"]},br={};for(const t in Ud)br[t]={isEnabled:s=>Ud[t].some(a=>!!s[a])};function UN(t){for(const s in t)br[s]={...br[s],...t[s]}}const VN=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 ei(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||VN.has(t)}let rp=t=>!ei(t);function zN(t){typeof t=="function"&&(rp=s=>s.startsWith("on")?!ei(s):t(s))}try{zN(require("@emotion/is-prop-valid").default)}catch{}function HN(t,s,a){const r={};for(const n in t)n==="values"&&typeof t.values=="object"||(rp(n)||a===!0&&ei(n)||!s&&!ei(n)||t.draggable&&n.startsWith("onDrag"))&&(r[n]=t[n]);return r}const ji=x.createContext({});function Ni(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function hn(t){return typeof t=="string"||Array.isArray(t)}const Bo=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Uo=["initial",...Bo];function wi(t){return Ni(t.animate)||Uo.some(s=>hn(t[s]))}function np(t){return!!(wi(t)||t.variants)}function WN(t,s){if(wi(t)){const{initial:a,animate:r}=t;return{initial:a===!1||hn(a)?a:void 0,animate:hn(r)?r:void 0}}return t.inherit!==!1?s:{}}function GN(t){const{initial:s,animate:a}=WN(t,x.useContext(ji));return x.useMemo(()=>({initial:s,animate:a}),[Vd(s),Vd(a)])}function Vd(t){return Array.isArray(t)?t.join(" "):t}const pn={};function KN(t){for(const s in t)pn[s]=t[s],So(s)&&(pn[s].isCSSVariable=!0)}function ip(t,{layout:s,layoutId:a}){return kr.has(t)||t.startsWith("origin")||(s||a!==void 0)&&(!!pn[t]||t==="opacity")}const YN={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},ZN=Tr.length;function XN(t,s,a){let r="",n=!0;for(let i=0;i<ZN;i++){const l=Tr[i],o=t[l];if(o===void 0)continue;let c=!0;if(typeof o=="number"?c=o===(l.startsWith("scale")?1:0):c=parseFloat(o)===0,!c||a){const d=Xh(o,_o[l]);if(!c){n=!1;const m=YN[l]||l;r+=`${m}(${d}) `}a&&(s[l]=d)}}return r=r.trim(),a?r=a(s,n?"":r):n&&(r="none"),r}function Vo(t,s,a){const{style:r,vars:n,transformOrigin:i}=t;let l=!1,o=!1;for(const c in s){const d=s[c];if(kr.has(c)){l=!0;continue}else if(So(c)){n[c]=d;continue}else{const m=Xh(d,_o[c]);c.startsWith("origin")?(o=!0,i[c]=m):r[c]=m}}if(s.transform||(l||a?r.transform=XN(s,t.transform,a):r.transform&&(r.transform="none")),o){const{originX:c="50%",originY:d="50%",originZ:m=0}=i;r.transformOrigin=`${c} ${d} ${m}`}}const zo=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function lp(t,s,a){for(const r in s)!ys(s[r])&&!ip(r,a)&&(t[r]=s[r])}function JN({transformTemplate:t},s){return x.useMemo(()=>{const a=zo();return Vo(a,s,t),Object.assign({},a.vars,a.style)},[s])}function QN(t,s){const a=t.style||{},r={};return lp(r,a,t),Object.assign(r,JN(t,s)),r}function qN(t,s){const a={},r=QN(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 ew={offset:"stroke-dashoffset",array:"stroke-dasharray"},tw={offset:"strokeDashoffset",array:"strokeDasharray"};function sw(t,s,a=1,r=0,n=!0){t.pathLength=1;const i=n?ew:tw;t[i.offset]=Ke.transform(-r);const l=Ke.transform(s),o=Ke.transform(a);t[i.array]=`${l} ${o}`}function op(t,{attrX:s,attrY:a,attrScale:r,pathLength:n,pathSpacing:i=1,pathOffset:l=0,...o},c,d,m){if(Vo(t,o,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&&sw(u,n,i,l,!1)}const cp=()=>({...zo(),attrs:{}}),dp=t=>typeof t=="string"&&t.toLowerCase()==="svg";function aw(t,s,a,r){const n=x.useMemo(()=>{const i=cp();return op(i,s,dp(r),t.transformTemplate,t.style),{...i.attrs,style:{...i.style}}},[s]);if(t.style){const i={};lp(i,t.style,t),n.style={...i,...n.style}}return n}const rw=["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 Ho(t){return typeof t!="string"||t.includes("-")?!1:!!(rw.indexOf(t)>-1||/[A-Z]/u.test(t))}function nw(t,s,a,{latestValues:r},n,i=!1){const o=(Ho(t)?aw:qN)(s,r,n,t),c=HN(s,typeof t=="string",i),d=t!==x.Fragment?{...c,...o,ref:a}:{},{children:m}=s,u=x.useMemo(()=>ys(m)?m.get():m,[m]);return x.createElement(t,{...d,children:u})}function zd(t){const s=[{},{}];return t==null||t.values.forEach((a,r)=>{s[0][r]=a.get(),s[1][r]=a.getVelocity()}),s}function Wo(t,s,a,r){if(typeof s=="function"){const[n,i]=zd(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]=zd(r);s=s(a!==void 0?a:t.custom,n,i)}return s}function Hn(t){return ys(t)?t.get():t}function iw({scrapeMotionValuesFromProps:t,createRenderState:s},a,r,n){return{latestValues:lw(a,r,n,t),renderState:s()}}function lw(t,s,a,r){const n={},i=r(t,{});for(const h in i)n[h]=Hn(i[h]);let{initial:l,animate:o}=t;const c=wi(t),d=np(t);s&&d&&!c&&t.inherit!==!1&&(l===void 0&&(l=s.initial),o===void 0&&(o=s.animate));let m=a?a.initial===!1:!1;m=m||l===!1;const u=m?o:l;if(u&&typeof u!="boolean"&&!Ni(u)){const h=Array.isArray(u)?u:[u];for(let g=0;g<h.length;g++){const p=Wo(t,h[g]);if(p){const{transitionEnd:y,transition:b,...j}=p;for(const v in j){let w=j[v];if(Array.isArray(w)){const N=m?w.length-1:0;w=w[N]}w!==null&&(n[v]=w)}for(const v in y)n[v]=y[v]}}}return n}const mp=t=>(s,a)=>{const r=x.useContext(ji),n=x.useContext(bi),i=()=>iw(t,s,r,n);return a?i():go(i)};function Go(t,s,a){var i;const{style:r}=t,n={};for(const l in r)(ys(r[l])||s.style&&ys(s.style[l])||ip(l,t)||((i=a==null?void 0:a.getValue(l))==null?void 0:i.liveStyle)!==void 0)&&(n[l]=r[l]);return n}const ow=mp({scrapeMotionValuesFromProps:Go,createRenderState:zo});function up(t,s,a){const r=Go(t,s,a);for(const n in t)if(ys(t[n])||ys(s[n])){const i=Tr.indexOf(n)!==-1?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n;r[i]=t[n]}return r}const cw=mp({scrapeMotionValuesFromProps:up,createRenderState:cp}),dw=Symbol.for("motionComponentSymbol");function dr(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function mw(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):dr(a)&&(a.current=r))},[s])}const Ko=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),uw="framerAppearId",hp="data-"+Ko(uw),pp=x.createContext({});function hw(t,s,a,r,n){var y,b;const{visualElement:i}=x.useContext(ji),l=x.useContext(ap),o=x.useContext(bi),c=x.useContext($o).reducedMotion,d=x.useRef(null);r=r||l.renderer,!d.current&&r&&(d.current=r(t,{visualState:s,parent:i,props:a,presenceContext:o,blockInitialAnimation:o?o.initial===!1:!1,reducedMotionConfig:c}));const m=d.current,u=x.useContext(pp);m&&!m.projection&&n&&(m.type==="html"||m.type==="svg")&&pw(d.current,a,n,u);const h=x.useRef(!1);x.useInsertionEffect(()=>{m&&h.current&&m.update(a,o)});const g=a[hp],p=x.useRef(!!g&&!((y=window.MotionHandoffIsComplete)!=null&&y.call(window,g))&&((b=window.MotionHasOptimisedAnimation)==null?void 0:b.call(window,g)));return mh(()=>{m&&(h.current=!0,window.MotionIsMounted=!0,m.updateFeatures(),m.scheduleRenderMicrotask(),p.current&&m.animationState&&m.animationState.animateChanges())}),x.useEffect(()=>{m&&(!p.current&&m.animationState&&m.animationState.animateChanges(),p.current&&(queueMicrotask(()=>{var j;(j=window.MotionHandoffMarkAsComplete)==null||j.call(window,g)}),p.current=!1),m.enteringChildren=void 0)}),m}function pw(t,s,a,r){const{layoutId:n,layout:i,drag:l,dragConstraints:o,layoutScroll:c,layoutRoot:d,layoutCrossfade:m}=s;t.projection=new a(t.latestValues,s["data-framer-portal-id"]?void 0:xp(t.parent)),t.projection.setOptions({layoutId:n,layout:i,alwaysMeasureLayout:!!l||o&&dr(o),visualElement:t,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:m,layoutScroll:c,layoutRoot:d})}function xp(t){if(t)return t.options.allowProjection!==!1?t.projection:xp(t.parent)}function Xi(t,{forwardMotionProps:s=!1}={},a,r){a&&UN(a);const n=Ho(t)?cw:ow;function i(o,c){let d;const m={...x.useContext($o),...o,layoutId:xw(o)},{isStatic:u}=m,h=GN(o),g=n(o,u);if(!u&&fo){gw();const p=fw(m);d=p.MeasureLayout,h.visualElement=hw(t,g,m,r,p.ProjectionNode)}return e.jsxs(ji.Provider,{value:h,children:[d&&h.visualElement?e.jsx(d,{visualElement:h.visualElement,...m}):null,nw(t,o,mw(g,h.visualElement,c),g,u,s)]})}i.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const l=x.forwardRef(i);return l[dw]=t,l}function xw({layoutId:t}){const s=x.useContext(xo).id;return s&&t!==void 0?s+"-"+t:t}function gw(t,s){x.useContext(ap).strict}function fw(t){const{drag:s,layout:a}=br;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 yw(t,s){if(typeof Proxy>"u")return Xi;const a=new Map,r=(i,l)=>Xi(i,l,t,s),n=(i,l)=>r(i,l);return new Proxy(n,{get:(i,l)=>l==="create"?r:(a.has(l)||a.set(l,Xi(l,void 0,t,s)),a.get(l))})}function gp({top:t,left:s,right:a,bottom:r}){return{x:{min:s,max:a},y:{min:t,max:r}}}function bw({x:t,y:s}){return{top:s.min,right:t.max,bottom:s.max,left:t.min}}function vw(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 Ji(t){return t===void 0||t===1}function Ll({scale:t,scaleX:s,scaleY:a}){return!Ji(t)||!Ji(s)||!Ji(a)}function Ya(t){return Ll(t)||fp(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function fp(t){return Hd(t.x)||Hd(t.y)}function Hd(t){return t&&t!=="0%"}function ti(t,s,a){const r=t-a,n=s*r;return a+n}function Wd(t,s,a,r,n){return n!==void 0&&(t=ti(t,n,r)),ti(t,a,r)+s}function Ol(t,s=0,a=1,r,n){t.min=Wd(t.min,s,a,r,n),t.max=Wd(t.max,s,a,r,n)}function yp(t,{x:s,y:a}){Ol(t.x,s.translate,s.scale,s.originPoint),Ol(t.y,a.translate,a.scale,a.originPoint)}const Gd=.999999999999,Kd=1.0000000000001;function jw(t,s,a,r=!1){const n=a.length;if(!n)return;s.x=s.y=1;let i,l;for(let o=0;o<n;o++){i=a[o],l=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&&ur(t,{x:-i.scroll.offset.x,y:-i.scroll.offset.y}),l&&(s.x*=l.x.scale,s.y*=l.y.scale,yp(t,l)),r&&Ya(i.latestValues)&&ur(t,i.latestValues))}s.x<Kd&&s.x>Gd&&(s.x=1),s.y<Kd&&s.y>Gd&&(s.y=1)}function mr(t,s){t.min=t.min+s,t.max=t.max+s}function Yd(t,s,a,r,n=.5){const i=$t(t.min,t.max,n);Ol(t,s,a,i,r)}function ur(t,s){Yd(t.x,s.x,s.scaleX,s.scale,s.originX),Yd(t.y,s.y,s.scaleY,s.scale,s.originY)}function bp(t,s){return gp(vw(t.getBoundingClientRect(),s))}function Nw(t,s,a){const r=bp(t,a),{scroll:n}=s;return n&&(mr(r.x,n.offset.x),mr(r.y,n.offset.y)),r}const Zd=()=>({translate:0,scale:1,origin:0,originPoint:0}),hr=()=>({x:Zd(),y:Zd()}),Xd=()=>({min:0,max:0}),Wt=()=>({x:Xd(),y:Xd()}),$l={current:null},vp={current:!1};function ww(){if(vp.current=!0,!!fo)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),s=()=>$l.current=t.matches;t.addEventListener("change",s),s()}else $l.current=!1}const Cw=new WeakMap;function Sw(t,s,a){for(const r in s){const n=s[r],i=a[r];if(ys(n))t.addValue(r,n);else if(ys(i))t.addValue(r,yr(n,{owner:t}));else if(i!==n)if(t.hasValue(r)){const l=t.getValue(r);l.liveStyle===!0?l.jump(n):l.hasAnimated||l.set(n)}else{const l=t.getStaticValue(r);t.addValue(r,yr(l!==void 0?l:n,{owner:t}))}}for(const r in a)s[r]===void 0&&t.removeValue(r);return s}const Jd=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class Aw{scrapeMotionValuesFromProps(s,a,r){return{}}constructor({parent:s,props:a,presenceContext:r,reducedMotionConfig:n,blockInitialAnimation:i,visualState:l},o={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=Mo,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=Ds.now();this.renderScheduledAt<h&&(this.renderScheduledAt=h,Ft.render(this.render,!1,!0))};const{latestValues:c,renderState:d}=l;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=o,this.blockInitialAnimation=!!i,this.isControllingVariants=wi(a),this.isVariantNode=np(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 g=u[h];c[h]!==void 0&&ys(g)&&g.set(c[h])}}mount(s){var a;this.current=s,Cw.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)),vp.current||ww(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:$l.current,(a=this.parent)==null||a.addChild(this),this.update(this.props,this.presenceContext)}unmount(){var s;this.projection&&this.projection.unmount(),Ea(this.notifyUpdate),Ea(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=kr.has(s);r&&this.onBindTransform&&this.onBindTransform();const n=a.on("change",l=>{this.latestValues[s]=l,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 br){const a=br[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):Wt()}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<Jd.length;r++){const n=Jd[r];this.propEventSubscriptions[n]&&(this.propEventSubscriptions[n](),delete this.propEventSubscriptions[n]);const i="on"+n,l=s[i];l&&(this.propEventSubscriptions[n]=this.on(n,l))}this.prevMotionValues=Sw(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=yr(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"&&(uh(r)||ph(r))?r=parseFloat(r):!MN(r)&&Ma.test(a)&&(r=Zh(s,a)),this.setBaseTarget(s,ys(r)?r.get():r)),ys(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 l=Wo(this.props,a,(i=this.presenceContext)==null?void 0:i.custom);l&&(r=l[s])}if(a&&r!==void 0)return r;const n=this.getBaseTargetFromProps(this.props,s);return n!==void 0&&!ys(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 No),this.events[s].add(a)}notify(s,...a){this.events[s]&&this.events[s].notify(...a)}scheduleRenderMicrotask(){Lo.render(this.render)}}class jp extends Aw{constructor(){super(...arguments),this.KeyframeResolver=NN}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;ys(s)&&(this.childSubscription=s.on("change",a=>{this.current&&(this.current.textContent=`${a}`)}))}}function Np(t,{style:s,vars:a},r,n){const i=t.style;let l;for(l in s)i[l]=s[l];n==null||n.applyProjectionStyles(i,r);for(l in a)i.setProperty(l,a[l])}function Tw(t){return window.getComputedStyle(t)}class kw extends jp{constructor(){super(...arguments),this.type="html",this.renderInstance=Np}readValueFromInstance(s,a){var r;if(kr.has(a))return(r=this.projection)!=null&&r.isProjecting?Rl(a):Uj(s,a);{const n=Tw(s),i=(So(a)?n.getPropertyValue(a):n[a])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(s,{transformPagePoint:a}){return bp(s,a)}build(s,a,r){Vo(s,a,r.transformTemplate)}scrapeMotionValuesFromProps(s,a,r){return Go(s,a,r)}}const wp=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 Dw(t,s,a,r){Np(t,s,void 0,r);for(const n in s.attrs)t.setAttribute(wp.has(n)?n:Ko(n),s.attrs[n])}class Rw extends jp{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Wt}getBaseTargetFromProps(s,a){return s[a]}readValueFromInstance(s,a){if(kr.has(a)){const r=Yh(a);return r&&r.default||0}return a=wp.has(a)?a:Ko(a),s.getAttribute(a)}scrapeMotionValuesFromProps(s,a,r){return up(s,a,r)}build(s,a,r){op(s,a,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(s,a,r,n){Dw(s,a,r,n)}mount(s){this.isSVGTag=dp(s.tagName),super.mount(s)}}const Pw=(t,s)=>Ho(t)?new Rw(s):new kw(s,{allowProjection:t!==x.Fragment});function gr(t,s,a){const r=t.getProps();return Wo(r,s,a!==void 0?a:r.custom,t)}const Bl=t=>Array.isArray(t);function Iw(t,s,a){t.hasValue(s)?t.getValue(s).set(a):t.addValue(s,yr(a))}function Ew(t){return Bl(t)?t[t.length-1]||0:t}function Mw(t,s){const a=gr(t,s);let{transitionEnd:r={},transition:n={},...i}=a||{};i={...i,...r};for(const l in i){const o=Ew(i[l]);Iw(t,l,o)}}function Fw(t){return!!(ys(t)&&t.add)}function Ul(t,s){const a=t.getValue("willChange");if(Fw(a))return a.add(s);if(!a&&Na.WillChange){const r=new Na.WillChange("auto");t.addValue("willChange",r),r.add(s)}}function Cp(t){return t.props[hp]}const _w=t=>t!==null;function Lw(t,{repeat:s,repeatType:a="loop"},r){const n=t.filter(_w),i=s&&a!=="loop"&&s%2===1?0:n.length-1;return n[i]}const Ow={type:"spring",stiffness:500,damping:25,restSpeed:10},$w=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),Bw={type:"keyframes",duration:.8},Uw={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Vw=(t,{keyframes:s})=>s.length>2?Bw:kr.has(t)?t.startsWith("scale")?$w(s[1]):Ow:Uw;function zw({when:t,delay:s,delayChildren:a,staggerChildren:r,staggerDirection:n,repeat:i,repeatType:l,repeatDelay:o,from:c,elapsed:d,...m}){return!!Object.keys(m).length}const Yo=(t,s,a,r={},n,i)=>l=>{const o=Fo(r,t)||{},c=o.delay||r.delay||0;let{elapsed:d=0}=r;d=d-la(c);const m={keyframes:Array.isArray(a)?a:[null,a],ease:"easeOut",velocity:s.getVelocity(),...o,delay:-d,onUpdate:h=>{s.set(h),o.onUpdate&&o.onUpdate(h)},onComplete:()=>{l(),o.onComplete&&o.onComplete()},name:t,motionValue:s,element:i?void 0:n};zw(o)||Object.assign(m,Vw(t,m)),m.duration&&(m.duration=la(m.duration)),m.repeatDelay&&(m.repeatDelay=la(m.repeatDelay)),m.from!==void 0&&(m.keyframes[0]=m.from);let u=!1;if((m.type===!1||m.duration===0&&!m.repeatDelay)&&(Fl(m),m.delay===0&&(u=!0)),(Na.instantAnimations||Na.skipAnimations)&&(u=!0,Fl(m),m.delay=0),m.allowFlatten=!o.type&&!o.ease,u&&!i&&s.get()!==void 0){const h=Lw(m.keyframes,o);if(h!==void 0){Ft.update(()=>{m.onUpdate(h),m.onComplete()});return}}return o.isSync?new Eo(m):new dN(m)};function Hw({protectedKeys:t,needsAnimating:s},a){const r=t.hasOwnProperty(a)&&s[a]!==!0;return s[a]=!1,r}function Sp(t,s,{delay:a=0,transitionOverride:r,type:n}={}){let{transition:i=t.getDefaultTransition(),transitionEnd:l,...o}=s;r&&(i=r);const c=[],d=n&&t.animationState&&t.animationState.getState()[n];for(const m in o){const u=t.getValue(m,t.latestValues[m]??null),h=o[m];if(h===void 0||d&&Hw(d,m))continue;const g={delay:a,...Fo(i||{},m)},p=u.get();if(p!==void 0&&!u.isAnimating&&!Array.isArray(h)&&h===p&&!g.velocity)continue;let y=!1;if(window.MotionHandoffAnimation){const j=Cp(t);if(j){const v=window.MotionHandoffAnimation(j,m,Ft);v!==null&&(g.startTime=v,y=!0)}}Ul(t,m),u.start(Yo(m,u,h,t.shouldReduceMotion&&Wh.has(m)?{type:!1}:g,t,y));const b=u.animation;b&&c.push(b)}return l&&Promise.all(c).then(()=>{Ft.update(()=>{l&&Mw(t,l)})}),c}function Ap(t,s,a,r=0,n=1){const i=Array.from(t).sort((d,m)=>d.sortNodePosition(m)).indexOf(s),l=t.size,o=(l-1)*r;return typeof a=="function"?a(i,l):n===1?i*r:o-i*r}function Vl(t,s,a={}){var c;const r=gr(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(Sp(t,r,a)):()=>Promise.resolve(),l=t.variantChildren&&t.variantChildren.size?(d=0)=>{const{delayChildren:m=0,staggerChildren:u,staggerDirection:h}=n;return Ww(t,s,d,m,u,h,a)}:()=>Promise.resolve(),{when:o}=n;if(o){const[d,m]=o==="beforeChildren"?[i,l]:[l,i];return d().then(()=>m())}else return Promise.all([i(),l(a.delay)])}function Ww(t,s,a=0,r=0,n=0,i=1,l){const o=[];for(const c of t.variantChildren)c.notify("AnimationStart",s),o.push(Vl(c,s,{...l,delay:a+(typeof r=="function"?0:r)+Ap(t.variantChildren,c,r,n,i)}).then(()=>c.notify("AnimationComplete",s)));return Promise.all(o)}function Gw(t,s,a={}){t.notify("AnimationStart",s);let r;if(Array.isArray(s)){const n=s.map(i=>Vl(t,i,a));r=Promise.all(n)}else if(typeof s=="string")r=Vl(t,s,a);else{const n=typeof s=="function"?gr(t,s,a.custom):s;r=Promise.all(Sp(t,n,a))}return r.then(()=>{t.notify("AnimationComplete",s)})}function Tp(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 Kw=Uo.length;function kp(t){if(!t)return;if(!t.isControllingVariants){const a=t.parent?kp(t.parent)||{}:{};return t.props.initial!==void 0&&(a.initial=t.props.initial),a}const s={};for(let a=0;a<Kw;a++){const r=Uo[a],n=t.props[r];(hn(n)||n===!1)&&(s[r]=n)}return s}const Yw=[...Bo].reverse(),Zw=Bo.length;function Xw(t){return s=>Promise.all(s.map(({animation:a,options:r})=>Gw(t,a,r)))}function Jw(t){let s=Xw(t),a=Qd(),r=!0;const n=c=>(d,m)=>{var h;const u=gr(t,m,c==="exit"?(h=t.presenceContext)==null?void 0:h.custom:void 0);if(u){const{transition:g,transitionEnd:p,...y}=u;d={...d,...y,...p}}return d};function i(c){s=c(t)}function l(c){const{props:d}=t,m=kp(t.parent)||{},u=[],h=new Set;let g={},p=1/0;for(let b=0;b<Zw;b++){const j=Yw[b],v=a[j],w=d[j]!==void 0?d[j]:m[j],N=hn(w),C=j===c?v.isActive:null;C===!1&&(p=b);let S=w===m[j]&&w!==d[j]&&N;if(S&&r&&t.manuallyAnimateOnMount&&(S=!1),v.protectedKeys={...g},!v.isActive&&C===null||!w&&!v.prevProp||Ni(w)||typeof w=="boolean")continue;const E=Qw(v.prevProp,w);let P=E||j===c&&v.isActive&&!S&&N||b>p&&N,R=!1;const f=Array.isArray(w)?w:[w];let T=f.reduce(n(j),{});C===!1&&(T={});const{prevResolvedValues:F={}}=v,K={...F,...T},B=A=>{P=!0,h.has(A)&&(R=!0,h.delete(A)),v.needsAnimating[A]=!0;const k=t.getValue(A);k&&(k.liveStyle=!1)};for(const A in K){const k=T[A],M=F[A];if(g.hasOwnProperty(A))continue;let O=!1;Bl(k)&&Bl(M)?O=!Tp(k,M):O=k!==M,O?k!=null?B(A):h.add(A):k!==void 0&&h.has(A)?B(A):v.protectedKeys[A]=!0}v.prevProp=w,v.prevResolvedValues=T,v.isActive&&(g={...g,...T}),r&&t.blockInitialAnimation&&(P=!1);const U=S&&E;P&&(!U||R)&&u.push(...f.map(A=>{const k={type:j};if(typeof A=="string"&&r&&!U&&t.manuallyAnimateOnMount&&t.parent){const{parent:M}=t,O=gr(M,A);if(M.enteringChildren&&O){const{delayChildren:L}=O.transition||{};k.delay=Ap(M.enteringChildren,t,L)}}return{animation:A,options:k}}))}if(h.size){const b={};if(typeof d.initial!="boolean"){const j=gr(t,Array.isArray(d.initial)?d.initial[0]:d.initial);j&&j.transition&&(b.transition=j.transition)}h.forEach(j=>{const v=t.getBaseTarget(j),w=t.getValue(j);w&&(w.liveStyle=!0),b[j]=v??null}),u.push({animation:b})}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 o(c,d){var u;if(a[c].isActive===d)return Promise.resolve();(u=t.variantChildren)==null||u.forEach(h=>{var g;return(g=h.animationState)==null?void 0:g.setActive(c,d)}),a[c].isActive=d;const m=l(c);for(const h in a)a[h].protectedKeys={};return m}return{animateChanges:l,setActive:o,setAnimateFunction:i,getState:()=>a,reset:()=>{a=Qd()}}}function Qw(t,s){return typeof s=="string"?s!==t:Array.isArray(s)?!Tp(s,t):!1}function Wa(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Qd(){return{animate:Wa(!0),whileInView:Wa(),whileHover:Wa(),whileTap:Wa(),whileDrag:Wa(),whileFocus:Wa(),exit:Wa()}}class La{constructor(s){this.isMounted=!1,this.node=s}update(){}}class qw extends La{constructor(s){super(s),s.animationState||(s.animationState=Jw(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();Ni(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 eC=0;class tC extends La{constructor(){super(...arguments),this.id=eC++}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 sC={animation:{Feature:qw},exit:{Feature:tC}};function xn(t,s,a,r={passive:!0}){return t.addEventListener(s,a,r),()=>t.removeEventListener(s,a)}function Nn(t){return{point:{x:t.pageX,y:t.pageY}}}const aC=t=>s=>Oo(s)&&t(s,Nn(s));function an(t,s,a,r){return xn(t,s,aC(a),r)}const Dp=1e-4,rC=1-Dp,nC=1+Dp,Rp=.01,iC=0-Rp,lC=0+Rp;function js(t){return t.max-t.min}function oC(t,s,a){return Math.abs(t-s)<=a}function qd(t,s,a,r=.5){t.origin=r,t.originPoint=$t(s.min,s.max,t.origin),t.scale=js(a)/js(s),t.translate=$t(a.min,a.max,t.origin)-t.originPoint,(t.scale>=rC&&t.scale<=nC||isNaN(t.scale))&&(t.scale=1),(t.translate>=iC&&t.translate<=lC||isNaN(t.translate))&&(t.translate=0)}function rn(t,s,a,r){qd(t.x,s.x,a.x,r?r.originX:void 0),qd(t.y,s.y,a.y,r?r.originY:void 0)}function em(t,s,a){t.min=a.min+s.min,t.max=t.min+js(s)}function cC(t,s,a){em(t.x,s.x,a.x),em(t.y,s.y,a.y)}function tm(t,s,a){t.min=s.min-a.min,t.max=t.min+js(s)}function nn(t,s,a){tm(t.x,s.x,a.x),tm(t.y,s.y,a.y)}function zs(t){return[t("x"),t("y")]}const Pp=({current:t})=>t?t.ownerDocument.defaultView:null,sm=(t,s)=>Math.abs(t-s);function dC(t,s){const a=sm(t.x,s.x),r=sm(t.y,s.y);return Math.sqrt(a**2+r**2)}class Ip{constructor(s,a,{transformPagePoint:r,contextWindow:n=window,dragSnapToOrigin:i=!1,distanceThreshold:l=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=qi(this.lastMoveEventInfo,this.history),g=this.startEvent!==null,p=dC(h.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!p)return;const{point:y}=h,{timestamp:b}=ms;this.history.push({...y,timestamp:b});const{onStart:j,onMove:v}=this.handlers;g||(j&&j(this.lastMoveEvent,h),this.startEvent=this.lastMoveEvent),v&&v(this.lastMoveEvent,h)},this.handlePointerMove=(h,g)=>{this.lastMoveEvent=h,this.lastMoveEventInfo=Qi(g,this.transformPagePoint),Ft.update(this.updatePoint,!0)},this.handlePointerUp=(h,g)=>{this.end();const{onEnd:p,onSessionEnd:y,resumeAnimation:b}=this.handlers;if(this.dragSnapToOrigin&&b&&b(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const j=qi(h.type==="pointercancel"?this.lastMoveEventInfo:Qi(g,this.transformPagePoint),this.history);this.startEvent&&p&&p(h,j),y&&y(h,j)},!Oo(s))return;this.dragSnapToOrigin=i,this.handlers=a,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=n||window;const o=Nn(s),c=Qi(o,this.transformPagePoint),{point:d}=c,{timestamp:m}=ms;this.history=[{...d,timestamp:m}];const{onSessionStart:u}=a;u&&u(s,qi(c,this.history)),this.removeListeners=bn(an(this.contextWindow,"pointermove",this.handlePointerMove),an(this.contextWindow,"pointerup",this.handlePointerUp),an(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(s){this.handlers=s}end(){this.removeListeners&&this.removeListeners(),Ea(this.updatePoint)}}function Qi(t,s){return s?{point:s(t.point)}:t}function am(t,s){return{x:t.x-s.x,y:t.y-s.y}}function qi({point:t},s){return{point:t,delta:am(t,Ep(s)),offset:am(t,mC(s)),velocity:uC(s,.1)}}function mC(t){return t[0]}function Ep(t){return t[t.length-1]}function uC(t,s){if(t.length<2)return{x:0,y:0};let a=t.length-1,r=null;const n=Ep(t);for(;a>=0&&(r=t[a],!(n.timestamp-r.timestamp>la(s)));)a--;if(!r)return{x:0,y:0};const i=Hs(n.timestamp-r.timestamp);if(i===0)return{x:0,y:0};const l={x:(n.x-r.x)/i,y:(n.y-r.y)/i};return l.x===1/0&&(l.x=0),l.y===1/0&&(l.y=0),l}function hC(t,{min:s,max:a},r){return s!==void 0&&t<s?t=r?$t(s,t,r.min):Math.max(t,s):a!==void 0&&t>a&&(t=r?$t(a,t,r.max):Math.min(t,a)),t}function rm(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 pC(t,{top:s,left:a,bottom:r,right:n}){return{x:rm(t.x,a,n),y:rm(t.y,s,r)}}function nm(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 xC(t,s){return{x:nm(t.x,s.x),y:nm(t.y,s.y)}}function gC(t,s){let a=.5;const r=js(t),n=js(s);return n>r?a=dn(s.min,s.max-r,t.min):r>n&&(a=dn(t.min,t.max-n,s.min)),ja(0,1,a)}function fC(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 zl=.35;function yC(t=zl){return t===!1?t=0:t===!0&&(t=zl),{x:im(t,"left","right"),y:im(t,"top","bottom")}}function im(t,s,a){return{min:lm(t,s),max:lm(t,a)}}function lm(t,s){return typeof t=="number"?t:t[s]||0}const bC=new WeakMap;class vC{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=Wt(),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(Nn(u).point)},l=(u,h)=>{const{drag:g,dragPropagation:p,onDragStart:y}=this.getProps();if(g&&!p&&(this.openDragLock&&this.openDragLock(),this.openDragLock=AN(g),!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),zs(j=>{let v=this.getAxisMotionValue(j).get()||0;if(oa.test(v)){const{projection:w}=this.visualElement;if(w&&w.layout){const N=w.layout.layoutBox[j];N&&(v=js(N)*(parseFloat(v)/100))}}this.originPoint[j]=v}),y&&Ft.postRender(()=>y(u,h)),Ul(this.visualElement,"transform");const{animationState:b}=this.visualElement;b&&b.setActive("whileDrag",!0)},o=(u,h)=>{this.latestPointerEvent=u,this.latestPanInfo=h;const{dragPropagation:g,dragDirectionLock:p,onDirectionLock:y,onDrag:b}=this.getProps();if(!g&&!this.openDragLock)return;const{offset:j}=h;if(p&&this.currentDirection===null){this.currentDirection=jC(j),this.currentDirection!==null&&y&&y(this.currentDirection);return}this.updateAxis("x",h.point,j),this.updateAxis("y",h.point,j),this.visualElement.render(),b&&b(u,h)},c=(u,h)=>{this.latestPointerEvent=u,this.latestPanInfo=h,this.stop(u,h),this.latestPointerEvent=null,this.latestPanInfo=null},d=()=>zs(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 Ip(s,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:m,distanceThreshold:r,contextWindow:Pp(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:l}=n;this.startAnimation(l);const{onDragEnd:o}=this.getProps();o&&Ft.postRender(()=>o(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||!Fn(s,n,this.currentDirection))return;const i=this.getAxisMotionValue(s);let l=this.originPoint[s]+r[s];this.constraints&&this.constraints[s]&&(l=hC(l,this.constraints[s],this.elastic[s])),i.set(l)}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&&dr(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&r?this.constraints=pC(r.layoutBox,s):this.constraints=!1,this.elastic=yC(a),n!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&zs(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=fC(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:s,onMeasureDragConstraints:a}=this.getProps();if(!s||!dr(s))return!1;const r=s.current,{projection:n}=this.visualElement;if(!n||!n.layout)return!1;const i=Nw(r,n.root,this.visualElement.getTransformPagePoint());let l=xC(n.layout.layoutBox,i);if(a){const o=a(bw(l));this.hasMutatedConstraints=!!o,o&&(l=gp(o))}return l}startAnimation(s){const{drag:a,dragMomentum:r,dragElastic:n,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=zs(m=>{if(!Fn(m,a,this.currentDirection))return;let u=c&&c[m]||{};l&&(u={min:0,max:0});const h=n?200:1e6,g=n?40:1e7,p={type:"inertia",velocity:r?s[m]:0,bounceStiffness:h,bounceDamping:g,timeConstant:750,restDelta:1,restSpeed:10,...i,...u};return this.startAxisValueAnimation(m,p)});return Promise.all(d).then(o)}startAxisValueAnimation(s,a){const r=this.getAxisMotionValue(s);return Ul(this.visualElement,s),r.start(Yo(s,r,0,a,this.visualElement,!1))}stopAnimation(){zs(s=>this.getAxisMotionValue(s).stop())}pauseAnimation(){zs(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){zs(a=>{const{drag:r}=this.getProps();if(!Fn(a,r,this.currentDirection))return;const{projection:n}=this.visualElement,i=this.getAxisMotionValue(a);if(n&&n.layout){const{min:l,max:o}=n.layout.layoutBox[a];i.set(s[a]-$t(l,o,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:s,dragConstraints:a}=this.getProps(),{projection:r}=this.visualElement;if(!dr(a)||!r||!this.constraints)return;this.stopAnimation();const n={x:0,y:0};zs(l=>{const o=this.getAxisMotionValue(l);if(o&&this.constraints!==!1){const c=o.get();n[l]=gC({min:c,max:c},this.constraints[l])}});const{transformTemplate:i}=this.visualElement.getProps();this.visualElement.current.style.transform=i?i({},""):"none",r.root&&r.root.updateScroll(),r.updateLayout(),this.resolveConstraints(),zs(l=>{if(!Fn(l,s,null))return;const o=this.getAxisMotionValue(l),{min:c,max:d}=this.constraints[l];o.set($t(c,d,n[l]))})}addListeners(){if(!this.visualElement.current)return;bC.set(this.visualElement,this);const s=this.visualElement.current,a=an(s,"pointerdown",c=>{const{drag:d,dragListener:m=!0}=this.getProps();d&&m&&this.start(c)}),r=()=>{const{dragConstraints:c}=this.getProps();dr(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 l=xn(window,"resize",()=>this.scalePositionWithinConstraints()),o=n.addEventListener("didUpdate",({delta:c,hasLayoutChanged:d})=>{this.isDragging&&d&&(zs(m=>{const u=this.getAxisMotionValue(m);u&&(this.originPoint[m]+=c[m].translate,u.set(u.get()+c[m].translate))}),this.visualElement.render())});return()=>{l(),a(),i(),o&&o()}}getProps(){const s=this.visualElement.getProps(),{drag:a=!1,dragDirectionLock:r=!1,dragPropagation:n=!1,dragConstraints:i=!1,dragElastic:l=zl,dragMomentum:o=!0}=s;return{...s,drag:a,dragDirectionLock:r,dragPropagation:n,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function Fn(t,s,a){return(s===!0||s===t)&&(a===null||a===t)}function jC(t,s=10){let a=null;return Math.abs(t.y)>s?a="y":Math.abs(t.x)>s&&(a="x"),a}class NC extends La{constructor(s){super(s),this.removeGroupControls=Gs,this.removeListeners=Gs,this.controls=new vC(s)}mount(){const{dragControls:s}=this.node.getProps();s&&(this.removeGroupControls=s.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Gs}unmount(){this.removeGroupControls(),this.removeListeners()}}const om=t=>(s,a)=>{t&&Ft.postRender(()=>t(s,a))};class wC extends La{constructor(){super(...arguments),this.removePointerDownListener=Gs}onPointerDown(s){this.session=new Ip(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Pp(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:a,onPan:r,onPanEnd:n}=this.node.getProps();return{onSessionStart:om(s),onStart:om(a),onMove:r,onEnd:(i,l)=>{delete this.session,n&&Ft.postRender(()=>n(i,l))}}}mount(){this.removePointerDownListener=an(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 Wn={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function cm(t,s){return s.max===s.min?0:t/(s.max-s.min)*100}const Yr={correct:(t,s)=>{if(!s.target)return t;if(typeof t=="string")if(Ke.test(t))t=parseFloat(t);else return t;const a=cm(t,s.target.x),r=cm(t,s.target.y);return`${a}% ${r}%`}},CC={correct:(t,{treeScale:s,projectionDelta:a})=>{const r=t,n=Ma.parse(t);if(n.length>5)return r;const i=Ma.createTransformer(t),l=typeof n[0]!="number"?1:0,o=a.x.scale*s.x,c=a.y.scale*s.y;n[0+l]/=o,n[1+l]/=c;const d=$t(o,c,.5);return typeof n[2+l]=="number"&&(n[2+l]/=d),typeof n[3+l]=="number"&&(n[3+l]/=d),i(n)}};let el=!1;class SC extends x.Component{componentDidMount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r,layoutId:n}=this.props,{projection:i}=s;KN(AC),i&&(a.group&&a.group.add(i),r&&r.register&&n&&r.register(i),el&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,onExitComplete:()=>this.safeToRemove()})),Wn.hasEverUpdated=!0}getSnapshotBeforeUpdate(s){const{layoutDependency:a,visualElement:r,drag:n,isPresent:i}=this.props,{projection:l}=r;return l&&(l.isPresent=i,el=!0,n||s.layoutDependency!==a||a===void 0||s.isPresent!==i?l.willUpdate():this.safeToRemove(),s.isPresent!==i&&(i?l.promote():l.relegate()||Ft.postRender(()=>{const o=l.getStack();(!o||!o.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:s}=this.props.visualElement;s&&(s.root.didUpdate(),Lo.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r}=this.props,{projection:n}=s;el=!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 Mp(t){const[s,a]=sp(),r=x.useContext(xo);return e.jsx(SC,{...t,layoutGroup:r,switchLayoutGroup:x.useContext(pp),isPresent:s,safeToRemove:a})}const AC={borderRadius:{...Yr,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Yr,borderTopRightRadius:Yr,borderBottomLeftRadius:Yr,borderBottomRightRadius:Yr,boxShadow:CC};function TC(t,s,a){const r=ys(t)?t:yr(t);return r.start(Yo("",r,s,a)),r.animation}const kC=(t,s)=>t.depth-s.depth;class DC{constructor(){this.children=[],this.isDirty=!1}add(s){yo(this.children,s),this.isDirty=!0}remove(s){bo(this.children,s),this.isDirty=!0}forEach(s){this.isDirty&&this.children.sort(kC),this.isDirty=!1,this.children.forEach(s)}}function RC(t,s){const a=Ds.now(),r=({timestamp:n})=>{const i=n-a;i>=s&&(Ea(r),t(i-s))};return Ft.setup(r,!0),()=>Ea(r)}const Fp=["TopLeft","TopRight","BottomLeft","BottomRight"],PC=Fp.length,dm=t=>typeof t=="string"?parseFloat(t):t,mm=t=>typeof t=="number"||Ke.test(t);function IC(t,s,a,r,n,i){n?(t.opacity=$t(0,a.opacity??1,EC(r)),t.opacityExit=$t(s.opacity??1,0,MC(r))):i&&(t.opacity=$t(s.opacity??1,a.opacity??1,r));for(let l=0;l<PC;l++){const o=`border${Fp[l]}Radius`;let c=um(s,o),d=um(a,o);if(c===void 0&&d===void 0)continue;c||(c=0),d||(d=0),c===0||d===0||mm(c)===mm(d)?(t[o]=Math.max($t(dm(c),dm(d),r),0),(oa.test(d)||oa.test(c))&&(t[o]+="%")):t[o]=d}(s.rotate||a.rotate)&&(t.rotate=$t(s.rotate||0,a.rotate||0,r))}function um(t,s){return t[s]!==void 0?t[s]:t.borderRadius}const EC=_p(0,.5,Nh),MC=_p(.5,.95,Gs);function _p(t,s,a){return r=>r<t?0:r>s?1:a(dn(t,s,r))}function hm(t,s){t.min=s.min,t.max=s.max}function Vs(t,s){hm(t.x,s.x),hm(t.y,s.y)}function pm(t,s){t.translate=s.translate,t.scale=s.scale,t.originPoint=s.originPoint,t.origin=s.origin}function xm(t,s,a,r,n){return t-=s,t=ti(t,1/a,r),n!==void 0&&(t=ti(t,1/n,r)),t}function FC(t,s=0,a=1,r=.5,n,i=t,l=t){if(oa.test(s)&&(s=parseFloat(s),s=$t(l.min,l.max,s/100)-l.min),typeof s!="number")return;let o=$t(i.min,i.max,r);t===i&&(o-=s),t.min=xm(t.min,s,a,o,n),t.max=xm(t.max,s,a,o,n)}function gm(t,s,[a,r,n],i,l){FC(t,s[a],s[r],s[n],s.scale,i,l)}const _C=["x","scaleX","originX"],LC=["y","scaleY","originY"];function fm(t,s,a,r){gm(t.x,s,_C,a?a.x:void 0,r?r.x:void 0),gm(t.y,s,LC,a?a.y:void 0,r?r.y:void 0)}function ym(t){return t.translate===0&&t.scale===1}function Lp(t){return ym(t.x)&&ym(t.y)}function bm(t,s){return t.min===s.min&&t.max===s.max}function OC(t,s){return bm(t.x,s.x)&&bm(t.y,s.y)}function vm(t,s){return Math.round(t.min)===Math.round(s.min)&&Math.round(t.max)===Math.round(s.max)}function Op(t,s){return vm(t.x,s.x)&&vm(t.y,s.y)}function jm(t){return js(t.x)/js(t.y)}function Nm(t,s){return t.translate===s.translate&&t.scale===s.scale&&t.originPoint===s.originPoint}class $C{constructor(){this.members=[]}add(s){yo(this.members,s),s.scheduleRender()}remove(s){if(bo(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 BC(t,s,a){let r="";const n=t.x.translate/s.x,i=t.y.translate/s.y,l=(a==null?void 0:a.z)||0;if((n||i||l)&&(r=`translate3d(${n}px, ${i}px, ${l}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:g,skewY:p}=a;d&&(r=`perspective(${d}px) ${r}`),m&&(r+=`rotate(${m}deg) `),u&&(r+=`rotateX(${u}deg) `),h&&(r+=`rotateY(${h}deg) `),g&&(r+=`skewX(${g}deg) `),p&&(r+=`skewY(${p}deg) `)}const o=t.x.scale*s.x,c=t.y.scale*s.y;return(o!==1||c!==1)&&(r+=`scale(${o}, ${c})`),r||"none"}const tl=["","X","Y","Z"],UC=1e3;let VC=0;function sl(t,s,a,r){const{latestValues:n}=s;n[t]&&(a[t]=n[t],s.setStaticValue(t,0),r&&(r[t]=0))}function $p(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:s}=t.options;if(!s)return;const a=Cp(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&&$p(r)}function Bp({attachResizeListener:t,defaultParent:s,measureScroll:a,checkIsScrollRoot:r,resetTransform:n}){return class{constructor(l={},o=s==null?void 0:s()){this.id=VC++,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(WC),this.nodes.forEach(ZC),this.nodes.forEach(XC),this.nodes.forEach(GC)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=l,this.root=o?o.root||o:this,this.path=o?[...o.path,o]:[],this.parent=o,this.depth=o?o.depth+1:0;for(let c=0;c<this.path.length;c++)this.path[c].shouldResetTransform=!0;this.root===this&&(this.nodes=new DC)}addEventListener(l,o){return this.eventHandlers.has(l)||this.eventHandlers.set(l,new No),this.eventHandlers.get(l).add(o)}notifyListeners(l,...o){const c=this.eventHandlers.get(l);c&&c.notify(...o)}hasListeners(l){return this.eventHandlers.has(l)}mount(l){if(this.instance)return;this.isSVG=tp(l)&&!IN(l),this.instance=l;const{layoutId:o,layout:c,visualElement:d}=this.options;if(d&&!d.current&&d.mount(l),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(c||o)&&(this.isLayoutDirty=!0),t){let m,u=0;const h=()=>this.root.updateBlockedByResize=!1;Ft.read(()=>{u=window.innerWidth}),t(l,()=>{const g=window.innerWidth;g!==u&&(u=g,this.root.updateBlockedByResize=!0,m&&m(),m=RC(h,250),Wn.hasAnimatedSinceResize&&(Wn.hasAnimatedSinceResize=!1,this.nodes.forEach(Sm)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&d&&(o||c)&&this.addEventListener("didUpdate",({delta:m,hasLayoutChanged:u,hasRelativeLayoutChanged:h,layout:g})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const p=this.options.transition||d.getDefaultTransition()||t1,{onLayoutAnimationStart:y,onLayoutAnimationComplete:b}=d.getProps(),j=!this.targetLayout||!Op(this.targetLayout,g),v=!u&&h;if(this.options.layoutRoot||this.resumeFrom||v||u&&(j||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const w={...Fo(p,"layout"),onPlay:y,onComplete:b};(d.shouldReduceMotion||this.options.layoutRoot)&&(w.delay=0,w.type=!1),this.startAnimation(w),this.setAnimationOrigin(m,v)}else u||Sm(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=g})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const l=this.getStack();l&&l.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),Ea(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(JC),this.animationId++)}getTransformTemplate(){const{visualElement:l}=this.options;return l&&l.getProps().transformTemplate}willUpdate(l=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&$p(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:o,layout:c}=this.options;if(o===void 0&&!c)return;const d=this.getTransformTemplate();this.prevTransformTemplateValue=d?d(this.latestValues,""):void 0,this.updateSnapshot(),l&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(wm);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Cm);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(YC),this.nodes.forEach(zC),this.nodes.forEach(HC)):this.nodes.forEach(Cm),this.clearAllSnapshots();const o=Ds.now();ms.delta=ja(0,1e3/60,o-ms.timestamp),ms.timestamp=o,ms.isProcessing=!0,Hi.update.process(ms),Hi.preRender.process(ms),Hi.render.process(ms),ms.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Lo.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(KC),this.sharedNodes.forEach(QC)}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&&!js(this.snapshot.measuredBox.x)&&!js(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 l=this.layout;this.layout=this.measure(!1),this.layoutCorrected=Wt(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);const{visualElement:o}=this.options;o&&o.notify("LayoutMeasure",this.layout.layoutBox,l?l.layoutBox:void 0)}updateScroll(l="measure"){let o=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===l&&(o=!1),o&&this.instance){const c=r(this.instance);this.scroll={animationId:this.root.animationId,phase:l,isRoot:c,offset:a(this.instance),wasRoot:this.scroll?this.scroll.isRoot:c}}}resetTransform(){if(!n)return;const l=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,o=this.projectionDelta&&!Lp(this.projectionDelta),c=this.getTransformTemplate(),d=c?c(this.latestValues,""):void 0,m=d!==this.prevTransformTemplateValue;l&&this.instance&&(o||Ya(this.latestValues)||m)&&(n(this.instance,d),this.shouldResetTransform=!1,this.scheduleRender())}measure(l=!0){const o=this.measurePageBox();let c=this.removeElementScroll(o);return l&&(c=this.removeTransform(c)),s1(c),{animationId:this.root.animationId,measuredBox:o,layoutBox:c,latestValues:{},source:this.id}}measurePageBox(){var d;const{visualElement:l}=this.options;if(!l)return Wt();const o=l.measureViewportBox();if(!(((d=this.scroll)==null?void 0:d.wasRoot)||this.path.some(a1))){const{scroll:m}=this.root;m&&(mr(o.x,m.offset.x),mr(o.y,m.offset.y))}return o}removeElementScroll(l){var c;const o=Wt();if(Vs(o,l),(c=this.scroll)!=null&&c.wasRoot)return o;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(o,l),mr(o.x,u.offset.x),mr(o.y,u.offset.y))}return o}applyTransform(l,o=!1){const c=Wt();Vs(c,l);for(let d=0;d<this.path.length;d++){const m=this.path[d];!o&&m.options.layoutScroll&&m.scroll&&m!==m.root&&ur(c,{x:-m.scroll.offset.x,y:-m.scroll.offset.y}),Ya(m.latestValues)&&ur(c,m.latestValues)}return Ya(this.latestValues)&&ur(c,this.latestValues),c}removeTransform(l){const o=Wt();Vs(o,l);for(let c=0;c<this.path.length;c++){const d=this.path[c];if(!d.instance||!Ya(d.latestValues))continue;Ll(d.latestValues)&&d.updateSnapshot();const m=Wt(),u=d.measurePageBox();Vs(m,u),fm(o,d.latestValues,d.snapshot?d.snapshot.layoutBox:void 0,m)}return Ya(this.latestValues)&&fm(o,this.latestValues),o}setTargetDelta(l){this.targetDelta=l,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(l){this.options={...this.options,...l,crossfade:l.crossfade!==void 0?l.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!==ms.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(l=!1){var h;const o=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=o.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=o.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=o.isSharedProjectionDirty);const c=!!this.resumingFrom||this!==o;if(!(l||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=ms.timestamp,!this.targetDelta&&!this.relativeTarget){const g=this.getClosestProjectingParent();g&&g.layout&&this.animationProgress!==1?(this.relativeParent=g,this.forceRelativeParentToResolveTarget(),this.relativeTarget=Wt(),this.relativeTargetOrigin=Wt(),nn(this.relativeTargetOrigin,this.layout.layoutBox,g.layout.layoutBox),Vs(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=Wt(),this.targetWithTransforms=Wt()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),cC(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):Vs(this.target,this.layout.layoutBox),yp(this.target,this.targetDelta)):Vs(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const g=this.getClosestProjectingParent();g&&!!g.resumingFrom==!!this.resumingFrom&&!g.options.layoutScroll&&g.target&&this.animationProgress!==1?(this.relativeParent=g,this.forceRelativeParentToResolveTarget(),this.relativeTarget=Wt(),this.relativeTargetOrigin=Wt(),nn(this.relativeTargetOrigin,this.target,g.target),Vs(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Ll(this.parent.latestValues)||fp(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 p;const l=this.getLead(),o=!!this.resumingFrom||this!==l;let c=!0;if((this.isProjectionDirty||(p=this.parent)!=null&&p.isProjectionDirty)&&(c=!1),o&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(c=!1),this.resolvedRelativeTargetAt===ms.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;jw(this.layoutCorrected,this.treeScale,this.path,o),l.layout&&!l.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(l.target=l.layout.layoutBox,l.targetWithTransforms=Wt());const{target:g}=l;if(!g){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(pm(this.prevProjectionDelta.x,this.projectionDelta.x),pm(this.prevProjectionDelta.y,this.projectionDelta.y)),rn(this.projectionDelta,this.layoutCorrected,g,this.latestValues),(this.treeScale.x!==u||this.treeScale.y!==h||!Nm(this.projectionDelta.x,this.prevProjectionDelta.x)||!Nm(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",g))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(l=!0){var o;if((o=this.options.visualElement)==null||o.scheduleRender(),l){const c=this.getStack();c&&c.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=hr(),this.projectionDelta=hr(),this.projectionDeltaWithTransform=hr()}setAnimationOrigin(l,o=!1){const c=this.snapshot,d=c?c.latestValues:{},m={...this.latestValues},u=hr();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!o;const h=Wt(),g=c?c.source:void 0,p=this.layout?this.layout.source:void 0,y=g!==p,b=this.getStack(),j=!b||b.members.length<=1,v=!!(y&&!j&&this.options.crossfade===!0&&!this.path.some(e1));this.animationProgress=0;let w;this.mixTargetDelta=N=>{const C=N/1e3;Am(u.x,l.x,C),Am(u.y,l.y,C),this.setTargetDelta(u),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(nn(h,this.layout.layoutBox,this.relativeParent.layout.layoutBox),qC(this.relativeTarget,this.relativeTargetOrigin,h,C),w&&OC(this.relativeTarget,w)&&(this.isProjectionDirty=!1),w||(w=Wt()),Vs(w,this.relativeTarget)),y&&(this.animationValues=m,IC(m,d,this.latestValues,C,v,j)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=C},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(l){var o,c,d;this.notifyListeners("animationStart"),(o=this.currentAnimation)==null||o.stop(),(d=(c=this.resumingFrom)==null?void 0:c.currentAnimation)==null||d.stop(),this.pendingAnimation&&(Ea(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Ft.update(()=>{Wn.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=yr(0)),this.currentAnimation=TC(this.motionValue,[0,1e3],{...l,velocity:0,isSync:!0,onUpdate:m=>{this.mixTargetDelta(m),l.onUpdate&&l.onUpdate(m)},onStop:()=>{},onComplete:()=>{l.onComplete&&l.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 l=this.getStack();l&&l.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(UC),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const l=this.getLead();let{targetWithTransforms:o,target:c,layout:d,latestValues:m}=l;if(!(!o||!c||!d)){if(this!==l&&this.layout&&d&&Up(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||Wt();const u=js(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+u;const h=js(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+h}Vs(o,c),ur(o,m),rn(this.projectionDeltaWithTransform,this.layoutCorrected,o,m)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new $C),this.sharedNodes.get(l).add(o);const d=o.options.initialPromotionConfig;o.promote({transition:d?d.transition:void 0,preserveFollowOpacity:d&&d.shouldPreserveFollowOpacity?d.shouldPreserveFollowOpacity(o):void 0})}isLead(){const l=this.getStack();return l?l.lead===this:!0}getLead(){var o;const{layoutId:l}=this.options;return l?((o=this.getStack())==null?void 0:o.lead)||this:this}getPrevLead(){var o;const{layoutId:l}=this.options;return l?(o=this.getStack())==null?void 0:o.prevLead:void 0}getStack(){const{layoutId:l}=this.options;if(l)return this.root.sharedNodes.get(l)}promote({needsReset:l,transition:o,preserveFollowOpacity:c}={}){const d=this.getStack();d&&d.promote(this,c),l&&(this.projectionDelta=void 0,this.needsReset=!0),o&&this.setOptions({transition:o})}relegate(){const l=this.getStack();return l?l.relegate(this):!1}resetSkewAndRotation(){const{visualElement:l}=this.options;if(!l)return;let o=!1;const{latestValues:c}=l;if((c.z||c.rotate||c.rotateX||c.rotateY||c.rotateZ||c.skewX||c.skewY)&&(o=!0),!o)return;const d={};c.z&&sl("z",l,d,this.animationValues);for(let m=0;m<tl.length;m++)sl(`rotate${tl[m]}`,l,d,this.animationValues),sl(`skew${tl[m]}`,l,d,this.animationValues);l.render();for(const m in d)l.setStaticValue(m,d[m]),this.animationValues&&(this.animationValues[m]=d[m]);l.scheduleRender()}applyProjectionStyles(l,o){if(!this.instance||this.isSVG)return;if(!this.isVisible){l.visibility="hidden";return}const c=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,l.visibility="",l.opacity="",l.pointerEvents=Hn(o==null?void 0:o.pointerEvents)||"",l.transform=c?c(this.latestValues,""):"none";return}const d=this.getLead();if(!this.projectionDelta||!this.layout||!d.target){this.options.layoutId&&(l.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,l.pointerEvents=Hn(o==null?void 0:o.pointerEvents)||""),this.hasProjected&&!Ya(this.latestValues)&&(l.transform=c?c({},""):"none",this.hasProjected=!1);return}l.visibility="";const m=d.animationValues||d.latestValues;this.applyTransformsToTarget();let u=BC(this.projectionDeltaWithTransform,this.treeScale,m);c&&(u=c(m,u)),l.transform=u;const{x:h,y:g}=this.projectionDelta;l.transformOrigin=`${h.origin*100}% ${g.origin*100}% 0`,d.animationValues?l.opacity=d===this?m.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:m.opacityExit:l.opacity=d===this?m.opacity!==void 0?m.opacity:"":m.opacityExit!==void 0?m.opacityExit:0;for(const p in pn){if(m[p]===void 0)continue;const{correct:y,applyTo:b,isCSSVariable:j}=pn[p],v=u==="none"?m[p]:y(m[p],d);if(b){const w=b.length;for(let N=0;N<w;N++)l[b[N]]=v}else j?this.options.visualElement.renderState.vars[p]=v:l[p]=v}this.options.layoutId&&(l.pointerEvents=d===this?Hn(o==null?void 0:o.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(l=>{var o;return(o=l.currentAnimation)==null?void 0:o.stop()}),this.root.nodes.forEach(wm),this.root.sharedNodes.clear()}}}function zC(t){t.updateLayout()}function HC(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,l=s.source!==t.layout.source;i==="size"?zs(u=>{const h=l?s.measuredBox[u]:s.layoutBox[u],g=js(h);h.min=r[u].min,h.max=h.min+g}):Up(i,s.layoutBox,r)&&zs(u=>{const h=l?s.measuredBox[u]:s.layoutBox[u],g=js(r[u]);h.max=h.min+g,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[u].max=t.relativeTarget[u].min+g)});const o=hr();rn(o,r,s.layoutBox);const c=hr();l?rn(c,t.applyTransform(n,!0),s.measuredBox):rn(c,r,s.layoutBox);const d=!Lp(o);let m=!1;if(!t.resumeFrom){const u=t.getClosestProjectingParent();if(u&&!u.resumeFrom){const{snapshot:h,layout:g}=u;if(h&&g){const p=Wt();nn(p,s.layoutBox,h.layoutBox);const y=Wt();nn(y,r,g.layoutBox),Op(p,y)||(m=!0),u.options.layoutRoot&&(t.relativeTarget=y,t.relativeTargetOrigin=p,t.relativeParent=u)}}}t.notifyListeners("didUpdate",{layout:r,snapshot:s,delta:c,layoutDelta:o,hasLayoutChanged:d,hasRelativeLayoutChanged:m})}else if(t.isLead()){const{onExitComplete:r}=t.options;r&&r()}t.options.transition=void 0}function WC(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 GC(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function KC(t){t.clearSnapshot()}function wm(t){t.clearMeasurements()}function Cm(t){t.isLayoutDirty=!1}function YC(t){const{visualElement:s}=t.options;s&&s.getProps().onBeforeLayoutMeasure&&s.notify("BeforeLayoutMeasure"),t.resetTransform()}function Sm(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function ZC(t){t.resolveTargetDelta()}function XC(t){t.calcProjection()}function JC(t){t.resetSkewAndRotation()}function QC(t){t.removeLeadSnapshot()}function Am(t,s,a){t.translate=$t(s.translate,0,a),t.scale=$t(s.scale,1,a),t.origin=s.origin,t.originPoint=s.originPoint}function Tm(t,s,a,r){t.min=$t(s.min,a.min,r),t.max=$t(s.max,a.max,r)}function qC(t,s,a,r){Tm(t.x,s.x,a.x,r),Tm(t.y,s.y,a.y,r)}function e1(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const t1={duration:.45,ease:[.4,0,.1,1]},km=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),Dm=km("applewebkit/")&&!km("chrome/")?Math.round:Gs;function Rm(t){t.min=Dm(t.min),t.max=Dm(t.max)}function s1(t){Rm(t.x),Rm(t.y)}function Up(t,s,a){return t==="position"||t==="preserve-aspect"&&!oC(jm(s),jm(a),.2)}function a1(t){var s;return t!==t.root&&((s=t.scroll)==null?void 0:s.wasRoot)}const r1=Bp({attachResizeListener:(t,s)=>xn(t,"resize",s),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),al={current:void 0},Vp=Bp({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!al.current){const t=new r1({});t.mount(window),t.setOptions({layoutScroll:!0}),al.current=t}return al.current},resetTransform:(t,s)=>{t.style.transform=s!==void 0?s:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),n1={pan:{Feature:wC},drag:{Feature:NC,ProjectionNode:Vp,MeasureLayout:Mp}};function Pm(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,Nn(s)))}class i1 extends La{mount(){const{current:s}=this.node;s&&(this.unmount=TN(s,(a,r)=>(Pm(this.node,r,"Start"),n=>Pm(this.node,n,"End"))))}unmount(){}}class l1 extends La{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=bn(xn(this.node.current,"focus",()=>this.onFocus()),xn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Im(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,Nn(s)))}class o1 extends La{mount(){const{current:s}=this.node;s&&(this.unmount=PN(s,(a,r)=>(Im(this.node,r,"Start"),(n,{success:i})=>Im(this.node,n,i?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Hl=new WeakMap,rl=new WeakMap,c1=t=>{const s=Hl.get(t.target);s&&s(t)},d1=t=>{t.forEach(c1)};function m1({root:t,...s}){const a=t||document;rl.has(a)||rl.set(a,{});const r=rl.get(a),n=JSON.stringify(s);return r[n]||(r[n]=new IntersectionObserver(d1,{root:t,...s})),r[n]}function u1(t,s,a){const r=m1(s);return Hl.set(t,a),r.observe(t),()=>{Hl.delete(t),r.unobserve(t)}}const h1={some:0,all:1};class p1 extends La{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,l={root:a?a.current:void 0,rootMargin:r,threshold:typeof n=="number"?n:h1[n]},o=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 u1(this.node.current,l,o)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:s,prevProps:a}=this.node;["amount","margin","root"].some(x1(s,a))&&this.startObserver()}unmount(){}}function x1({viewport:t={}},{viewport:s={}}={}){return a=>t[a]!==s[a]}const g1={inView:{Feature:p1},tap:{Feature:o1},focus:{Feature:l1},hover:{Feature:i1}},f1={layout:{ProjectionNode:Vp,MeasureLayout:Mp}},y1={...sC,...g1,...n1,...f1},as=yw(y1,Pw),Em=[{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:us,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:Pf,color:"from-green-500 to-emerald-600",estimatedTime:"3-5 days",steps:5,features:["PO matching","Invoice verification","Multi-level approvals","Payment scheduling"]}];function b1({open:t,onClose:s,onSelectTemplate:a}){var o;const[r,n]=x.useState(null),i=c=>{n(c)},l=()=>{r&&(a(r),s())};return e.jsx(ot,{open:t,onOpenChange:s,children:e.jsxs(nt,{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(it,{className:"sr-only",children:"Select a Template"}),e.jsx(_t,{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(pt,{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(as.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(oi,{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:Em.map((c,d)=>{const m=c.icon,u=r===c.id;return e.jsx(as.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(te,{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(me,{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(as.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(jr,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsx(he,{className:"text-xl mb-2",children:c.name}),e.jsx(De,{className:"text-sm leading-relaxed",children:c.description})]})]}),e.jsxs(se,{className:"pt-0 space-y-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(ie,{variant:"secondary",className:"text-xs",children:c.category})}),e.jsx(Vt,{}),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(Ze,{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(Bt,{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,g)=>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})]},g)),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(as.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(I,{variant:"outline",onClick:s,size:"lg",className:"px-8",children:"Cancel"}),e.jsxs(I,{onClick:l,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(rs,{className:"w-4 h-4"})]})]}),e.jsx(vi,{children:r&&e.jsx(as.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:(o=Em.find(c=>c.id===r))==null?void 0:o.name})]})})})]})})]})})}function Zo({fileName:t,fileType:s,fileUrl:a,fileSize:r,attachmentId:n,onDownload:i,open:l,onClose:o}){const[c,d]=x.useState(100),[m,u]=x.useState(0),[h,g]=x.useState(null),[p,y]=x.useState(!1),[b,j]=x.useState(null),v=s.toLowerCase().includes("image")||s.toLowerCase().includes("png")||s.toLowerCase().includes("jpg")||s.toLowerCase().includes("jpeg")||s.toLowerCase().includes("gif")||s.toLowerCase().includes("webp"),w=s.toLowerCase().includes("pdf"),N=v||w;x.useEffect(()=>{if(!l||!N||!a){g(null);return}return(async()=>{y(!0),j(null);try{let F=a;a.startsWith("/")&&!a.startsWith("//")&&(F=`${window.location.origin}${a}`);const B=await fetch(F,{headers:{Accept:w?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!B.ok){const A=await B.text().catch(()=>"");throw new Error(`Failed to load file: ${B.status} ${B.statusText}. ${A}`)}const U=await B.blob();if(U.size===0)throw new Error("File is empty or could not be loaded");w&&!U.type.includes("pdf")&&U.type!=="application/octet-stream"&&console.warn(`Expected PDF but got ${U.type}`);const D=window.URL.createObjectURL(U);g(D)}catch(f){console.error("Failed to load file for preview:",f),j(f instanceof Error?f.message:"Failed to load file for preview")}finally{y(!1)}})(),()=>{h&&(window.URL.revokeObjectURL(h),g(null))}},[l,a,N,w]);const C=async()=>{if(i&&n)try{await i(n)}catch{alert("Failed to download file")}},S=()=>d(R=>Math.min(R+25,200)),E=()=>d(R=>Math.max(R-25,50)),P=()=>u(R=>(R+90)%360);return e.jsx(ot,{open:l,onOpenChange:o,children:e.jsx(nt,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(ct,{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(bt,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(it,{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:[v&&e.jsxs("div",{className:"flex items-center gap-1 mr-2",children:[e.jsx(I,{variant:"ghost",size:"sm",onClick:E,disabled:c<=50,title:"Zoom out",className:"h-8 w-8 p-0",children:e.jsx(If,{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(I,{variant:"ghost",size:"sm",onClick:S,disabled:c>=200,title:"Zoom in",className:"h-8 w-8 p-0",children:e.jsx(Ef,{className:"h-4 w-4"})}),e.jsx(I,{variant:"ghost",size:"sm",onClick:P,title:"Rotate",className:"h-8 w-8 p-0",children:e.jsx(Mf,{className:"h-4 w-4"})})]}),i&&n&&e.jsxs(I,{variant:"outline",size:"sm",onClick:C,className:"gap-2 h-9",children:[e.jsx(Nt,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Download"})]})]})]})}),e.jsx("div",{className:"file-preview-body bg-gray-100 rounded-lg p-2 sm:p-4",children:p?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full",children:[e.jsx(Qe,{className:"w-12 h-12 text-blue-600 animate-spin mb-4"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Loading preview..."})]}):b?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(pt,{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:b}),i&&n&&e.jsxs(I,{onClick:C,className:"gap-2",children:[e.jsx(Nt,{className:"h-4 w-4"}),"Download ",t]})]}):N&&h?e.jsxs(e.Fragment,{children:[v&&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"})}),w&&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:()=>{j("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(bt,{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(I,{onClick:C,className:"gap-2",children:[e.jsx(Nt,{className:"h-4 w-4"}),"Download ",t]})]})})]})})})}function zp({open:t,onClose:s,violations:a,policyDetails:r}){return e.jsx(ot,{open:t,onOpenChange:s,children:e.jsxs(nt,{className:"sm:max-w-lg",children:[e.jsxs(ct,{children:[e.jsxs(it,{className:"flex items-center gap-2",children:[e.jsx(We,{className:"w-5 h-5 text-red-600"}),"Policy Violation"]}),e.jsx(_t,{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(At,{children:e.jsx(I,{onClick:s,className:"w-full sm:w-auto",children:"OK"})})]})})}const ar=async t=>{const s=t?{category:t}:{};return(await ye.get("/users/configurations",{params:s})).data.data},Ci=async t=>{const s=t?{category:t}:{};return(await ye.get("/admin/configurations",{params:s})).data.data},bs=async(t,s)=>{await ye.put(`/admin/configurations/${t}`,{configValue:s})},v1=async t=>{await ye.post(`/admin/configurations/${t}/reset`)},j1=async t=>{const s=t?{year:t}:{};return(await ye.get("/admin/holidays",{params:s})).data.data},N1=async t=>(await ye.post("/admin/holidays",t)).data.data,w1=async(t,s)=>(await ye.put(`/admin/holidays/${t}`,s)).data.data,C1=async t=>{await ye.delete(`/admin/holidays/${t}`)},S1={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 A1(t,s,a){const[r,n]=x.useState(S1),[i,l]=x.useState(null),[o,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"]}),[g,p]=x.useState([]);return x.useEffect(()=>{(async()=>{var j;try{const v=await ar("DOCUMENT_POLICY"),w={};v.forEach(T=>{w[T.configKey]=T.configValue});const N=parseInt(w.MAX_FILE_SIZE_MB||"10"),S=(w.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(T=>T.trim().toLowerCase());h({maxFileSizeMB:N,allowedFileTypes:S});const E=await ar("WORKFLOW_SHARING"),P=await ar("TAT_SETTINGS"),R=[...E,...P],f={};R.forEach(T=>{f[T.configKey]=T.configValue}),m({maxApprovalLevels:parseInt(f.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(f.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((j=f.ALLOW_ADD_SPECTATOR)==null?void 0:j.toLowerCase())==="true",maxSpectators:parseInt(f.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(v){console.error("Failed to load policies:",v)}})()},[]),x.useEffect(()=>{if(!t||!s)return;let b=!0;return(async()=>{try{c(!0);const j=await Ts(s);if(!b||!j)return;const v=j.workflow||{},w=Array.isArray(j.approvals)?j.approvals:[],N=Array.isArray(j.participants)?j.participants:[],C=Array.isArray(j.documents)?j.documents.filter(F=>!F.isDeleted):[];p(C);const S=(v.priority||"").toString().toLowerCase(),E={standard:"standard",express:"express"},P=v.templateType==="TEMPLATE"?"existing-template":"custom",R=a.find(F=>F.id===P)||a[0]||null;l(R);const f=w.sort((F,K)=>(F.levelNumber||0)-(K.levelNumber||0)).map(F=>{const K=Number(F.tatHours||24),B=Math.floor(K/24),U=K%24;return{id:F.approverId||`temp-${F.levelNumber}`,name:F.approverName||F.approverEmail||"",email:F.approverEmail||"",role:F.levelName||`Level ${F.levelNumber}`,department:"",avatar:(F.approverName||F.approverEmail||"XX").substring(0,2).toUpperCase(),level:F.levelNumber||1,canClose:!1,tat:B>0?B:U,tatType:B>0?"days":"hours",userId:F.approverId}}),T=N.filter(F=>(F.participantType||F.participant_type||"").toString().toUpperCase().trim()==="SPECTATOR"?!!(F.userEmail||F.user_email||F.email):!1).map((F,K)=>{const B=F.userId||F.user_id||F.id,U=F.userName||F.user_name||F.name||"",D=F.userEmail||F.user_email||F.email||"",k=(U||D||"XX").split(" ").map(M=>M[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{id:B||`spectator-${s}-${K}-${Date.now()}`,userId:B,name:U||D||"Spectator",email:D,role:"Spectator",department:F.department||"",avatar:k,level:1,canClose:!1}});n(F=>({...F,template:P,title:v.title||"",description:v.description||"",priority:E[S]||"standard",approvers:f,approverCount:f.length||1,spectators:T,maxLevel:Math.max(...f.map(K=>K.level||1),1)}))}catch(j){console.error("Failed to load draft:",j)}finally{b&&c(!1)}})(),()=>{b=!1}},[t,s,a]),{formData:r,setFormData:n,updateFormData:(b,j)=>{n(v=>({...v,[b]:j}))},selectedTemplate:i,setSelectedTemplate:l,loadingDraft:o,systemPolicy:d,documentPolicy:u,existingDocuments:g,setExistingDocuments:p}}const Mm=["Template Selection","Basic Information","Approval Workflow","Participants & Access","Documents & Attachments","Review & Submit"];function T1(t,s,a){const[r,n]=x.useState(t?2:1),i=Mm.length,l=u=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(u),o=()=>{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||!l(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:Mm,isStepValid:o,nextStep:()=>{o()&&(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:l}}function k1(){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,g,p="")=>{s({open:!0,type:h,email:g,message:p})},closeValidationModal:()=>{s(h=>({...h,open:!1}))},openPolicyViolationModal:h=>{r({open:!0,violations:h})},closePolicyViolationModal:()=>{r({open:!1,violations:[]})},openDocumentErrorModal:h=>{i({open:!0,errors:h})},closeDocumentErrorModal:()=>{i({open:!1,errors:[]})}}}function D1(t,s){const a=typeof t=="number"?t:parseInt(String(t))||0;return s==="days"?a*24:a||24}function R1(t,s,a){var n;const r=D1(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 P1(t,s){return t.slice(0,s).map((a,r)=>{const n=r+1;return R1(a,n,n===s)})}function Fm(t,s,a){const r=new Set((t.approvers||[]).map(i=>{var l;return(l=i==null?void 0:i.email)==null?void 0:l.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 _m(t,s,a){const r=P1(t.approvers||[],t.approverCount||1);return{title:t.title,description:t.description,priority:t.priority==="express"?"EXPRESS":"STANDARD",approvalLevels:r,participants:[],deleteDocumentIds:a.length>0?a:void 0}}function I1(t,s){const a=t.slice(0,s);if(a.some(l=>!(l!=null&&l.email)||!l.email.trim()))return{valid:!1,message:"Please provide email addresses for all approvers."};const n=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return a.some(l=>!n.test((l==null?void 0:l.email)||""))?{valid:!1,message:"Please provide valid email addresses for all approvers."}:{valid:!0}}async function Hp(t,s){return{id:(await qu(t,s||[],"SUPPORTING")).id}}async function Wp(t,s,a,r){const n=a&&a.length>0,i=r.length>0;n||i?await ev(t,s,a||[],r):await qb(t,s)}async function Gp(t){await rh(t)}async function E1(t,s){const a=await Hp(t,s);return await Gp(a.id),a}async function M1(t,s,a,r){await Wp(t,s,a,r),await Gp(t)}function F1({formData:t,selectedTemplate:s,documents:a,documentsToDelete:r,user:n,isEditing:i,editRequestId:l,onSubmit:o}){const[c,d]=x.useState(!1),[m,u]=x.useState(!1);return{submitting:c,savingDraft:m,handleSubmit:async()=>{if(c||m)return;const p=I1(t.approvers||[],t.approverCount||1);if(!p.valid){alert(p.message);return}d(!0);try{if(i&&l){const y=_m(t,n,r);await M1(l,y,a,r),o==null||o({...t,backendId:l,template:s})}else{const y=Fm(t,s,n),b=await E1(y,a);o==null||o({...t,backendId:b.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&&l){const p=_m(t,n,r);await Wp(l,p,a,r),o==null||o({...t,backendId:l,template:s})}else{const p=Fm(t,s,n),y=await Hp(p,a);o==null||o({...t,backendId:y.id,template:s})}}catch(p){console.error("Failed to save draft:",p),u(!1)}}}}}async function Zs(t,s=10){return await ye.get("/users/search",{params:{q:t,limit:s}})}async function Ks(t){var a;const s=await ye.post("/users/ensure",t);return((a=s.data)==null?void 0:a.data)||s.data}async function _1(t,s){return await ye.post("/admin/users/assign-role",{email:t,role:s})}async function L1(t,s){return await ye.put(`/admin/users/${t}/role`,{role:s})}async function O1(t,s=1,a=10){return await ye.get("/admin/users/by-role",{params:{role:t||"ELEVATED",page:s,limit:a}})}async function $1(){return await ye.get("/admin/users/role-statistics")}async function B1(){var s,a;return((a=(s=(await ye.get("/users")).data)==null?void 0:s.data)==null?void 0:a.users)||[]}const Ms={searchUsers:Zs,ensureUserExists:Ks,assignRole:_1,updateUserRole:L1,getUsersByRole:O1,getRoleStatistics:$1,getAllUsers:B1};async function U1(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 Zs(t.email,1)).data)==null?void 0:a.data)||[];if(n.length===0)return{success:!1,error:{type:"not-found",email:t.email,message:""}};const i=n[0];return i?(await Ks({userId:i.userId,email:i.email,displayName:i.displayName,firstName:i.firstName,lastName:i.lastName,department:i.department,phone:i.phone,mobilePhone:i.mobilePhone,designation:i.designation,jobTitle:i.jobTitle,manager:i.manager,employeeId:i.employeeId,employeeNumber:i.employeeNumber,secondEmail:i.secondEmail,location:i.location}),{success:!0}):{success:!1,error:{type:"error",email:t.email,message:"Could not retrieve user details. Please try again."}}}catch(r){return console.error(`Failed to validate approver ${t.email}:`,r),{success:!1,error:{type:"error",email:t.email,message:"Failed to validate user. Please try again or select a different user."}}}}async function V1(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 l=r[i];if(l.userId||!l.email)continue;const o=await U1(l,s);if(!o.success)return{success:!1,error:o.error};try{const m=(((n=(await Zs(l.email,1)).data)==null?void 0:n.data)||[])[0];if(m){const u=await Ks({userId:m.userId,email:m.email,displayName:m.displayName,firstName:m.firstName,lastName:m.lastName,department:m.department,phone:m.phone,mobilePhone:m.mobilePhone,designation:m.designation,jobTitle:m.jobTitle,manager:m.manager,employeeId:m.employeeId,employeeNumber:m.employeeNumber,secondEmail:m.secondEmail,location:m.location});r[i]={...l,userId:u.userId,name:u.displayName||l.name,department:u.department||l.department,avatar:(u.displayName||u.email).substring(0,2).toUpperCase()}}}catch(c){console.error(`Failed to update approver ${l.email}:`,c)}}return{success:!0,validatedApprovers:r}}function z1({selectedTemplate:t,setSelectedTemplate:s,updateFormData:a,formData:r,currentStep:n,isStepValid:i,wizardNextStep:l,wizardPrevStep:o,user:c,openValidationModal:d,onSubmit:m}){const[u,h]=x.useState(!1),[g,p]=x.useState(null);return{showTemplateModal:u,setShowTemplateModal:h,previewDocument:g,selectTemplate:C=>{s(C),a("template",C.id),a("category",C.category),a("priority",C.priority);const S=new Date;S.setDate(S.getDate()+C.suggestedSLA),a("slaEndDate",S),C.id==="existing-template"&&h(!0)},handleTemplateSelection:C=>{m&&m({templateType:C})},nextStep:async()=>{var C;if(i()){if(window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}),n===3){const S=((C=c==null?void 0:c.email)==null?void 0:C.toLowerCase())||"",E=await V1(r.approvers,S);if(!E.success&&E.error){d(E.error.type,E.error.email,E.error.message);return}E.validatedApprovers&&a("approvers",E.validatedApprovers)}l()}},prevStep:()=>{o(),window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"})},handlePreviewDocument:(C,S)=>{if(S){const E=C.documentId||C.document_id||"";p({fileName:C.originalFileName||C.fileName||"Document",fileType:C.fileType||C.file_type||"application/octet-stream",fileUrl:ho(E),fileSize:Number(C.fileSize||C.file_size||0),documentId:E})}else{const E=URL.createObjectURL(C);p({fileName:C.name,fileType:C.type||"application/octet-stream",fileUrl:E,fileSize:C.size,file:C})}},closePreview:()=>{g!=null&&g.fileUrl&&(g!=null&&g.file)&&URL.revokeObjectURL(g.fileUrl),p(null)}}}const Lm=[{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:ci,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:Le,estimatedTime:"1-2 days",commonApprovers:["Department Head","Manager"],suggestedSLA:2,priority:"medium",fields:{timeline:!0}}];function H1({currentStep:t,totalSteps:s,stepNames:a}){const r=Math.round(t/s*100);return e.jsx("div",{className:"bg-white border-b border-gray-200 px-3 sm:px-6 py-2 sm:py-3 flex-shrink-0","data-testid":"wizard-stepper",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"block sm:hidden","data-testid":"wizard-stepper-mobile",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-green-600 text-white flex items-center justify-center text-xs font-semibold","data-testid":"wizard-stepper-mobile-current-step",children:t}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-900","data-testid":"wizard-stepper-mobile-step-name",children:a[t-1]}),e.jsxs("p",{className:"text-xs text-gray-600","data-testid":"wizard-stepper-mobile-step-info",children:["Step ",t," of ",s]})]})]}),e.jsx("div",{className:"text-right",children:e.jsxs("p",{className:"text-xs font-medium text-green-600","data-testid":"wizard-stepper-mobile-progress",children:[r,"%"]})})]}),e.jsx("div",{className:"w-full bg-gray-200 h-1.5 rounded-full overflow-hidden","data-testid":"wizard-stepper-mobile-progress-bar",children:e.jsx("div",{className:"bg-green-600 h-full transition-all duration-300",style:{width:`${r}%`},"data-testid":"wizard-stepper-mobile-progress-fill"})})]}),e.jsxs("div",{className:"hidden sm:block","data-testid":"wizard-stepper-desktop",children:[e.jsx("div",{className:"flex items-center justify-between mb-2","data-testid":"wizard-stepper-desktop-steps",children:a.map((n,i)=>e.jsxs("div",{className:"flex items-center","data-testid":`wizard-stepper-desktop-step-${i+1}`,children:[e.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center text-xs font-semibold ${i+1<t?"bg-green-600 text-white":i+1===t?"bg-blue-600 text-white":"bg-gray-200 text-gray-600"}`,"data-testid":`wizard-stepper-desktop-step-${i+1}-indicator`,children:i+1<t?e.jsx(jr,{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 W1({currentStep:t,totalSteps:s,isStepValid:a,onPrev:r,onNext:n,onSubmit:i,onSaveDraft:l,submitting:o,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(I,{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(Ys,{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(I,{variant:"outline",onClick:l,size:"sm",className:"sm:size-lg flex-1 sm:flex-none text-xs sm:text-sm",disabled:d||o||c,"data-testid":"wizard-footer-save-draft-button",children:c?e.jsxs(e.Fragment,{children:[e.jsx(Qe,{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(I,{onClick:i,disabled:!a||d||o||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:o?e.jsxs(e.Fragment,{children:[e.jsx(Qe,{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(Nu,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),"Submit"]})}):e.jsxs(I,{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(rs,{className:"h-3 w-3 sm:h-4 sm:w-4 ml-1 sm:ml-2"})]})]})]})})}const Om=t=>{switch(t){case"high":return e.jsx(ta,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(Bt,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(da,{className:"w-4 h-4 text-green-600"});default:return e.jsx(Bt,{className:"w-4 h-4 text-gray-600"})}};function G1({templates:t,selectedTemplate:s,onSelectTemplate:a}){return e.jsxs(as.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(as.div,{whileHover:{scale:1.03},whileTap:{scale:.98},transition:{type:"spring",stiffness:300,damping:20},"data-testid":`template-card-${r.id}`,children:e.jsxs(te,{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(me,{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(as.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(jr,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsx(he,{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(ie,{variant:"secondary",className:"text-xs","data-testid":`template-card-${r.id}-category`,children:r.category}),Om(r.priority)]})]})]}),e.jsxs(se,{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(Vt,{}),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(Ze,{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(Mt,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[r.commonApprovers.length," approvers"]})]})]})]})]})},r.id))}),e.jsx(vi,{children:s&&e.jsx(as.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(te,{className:"bg-gradient-to-br from-blue-50 to-indigo-50 border-2 border-blue-200",children:[e.jsx(me,{children:e.jsxs(he,{className:"flex items-center gap-2 text-blue-900","data-testid":"template-details-title",children:[e.jsx(Nr,{className:"w-5 h-5"}),s.name," - Template Details"]})}),e.jsxs(se,{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(re,{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(re,{className:"text-blue-900 font-semibold",children:"Priority Level"}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[Om(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(re,{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(re,{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(ie,{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 K1({className:t,...s}){return e.jsx(Pg,{"data-slot":"radio-group",className:we("grid gap-3",t),...s})}function $m({className:t,...s}){return e.jsx(Ig,{"data-slot":"radio-group-item",className:we("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(Eg,{"data-slot":"radio-group-indicator",className:"relative flex items-center justify-center",children:e.jsx(Ff,{className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}function Y1({formData:t,selectedTemplate:s,updateFormData:a}){return e.jsxs(as.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(Le,{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(re,{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(Re,{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(re,{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(yi,{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(re,{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(K1,{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($m,{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(to,{className:"w-4 h-4 text-red-600"}),e.jsx(re,{htmlFor:"express",className:"font-medium text-red-900 cursor-pointer",children:"Express"}),e.jsx(ie,{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($m,{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(Ze,{className:"w-4 h-4 text-blue-600"}),e.jsx(re,{htmlFor:"standard",className:"font-medium text-blue-900 cursor-pointer",children:"Standard"}),e.jsx(ie,{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(re,{htmlFor:"amount",className:"text-base font-semibold",children:"Budget Amount"}),e.jsx(Re,{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(re,{className:"text-base font-semibold",children:"Currency"}),e.jsxs(Ue,{value:t.currency,onValueChange:r=>a("currency",r),"data-testid":"basic-information-currency-select",children:[e.jsx(ze,{className:"h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm",children:e.jsx(Ve,{})}),e.jsxs(He,{children:[e.jsx(Y,{value:"USD",children:"USD ($)"}),e.jsx(Y,{value:"EUR",children:"EUR (€)"}),e.jsx(Y,{value:"GBP",children:"GBP (£)"}),e.jsx(Y,{value:"INR",children:"INR (₹)"})]})]})]})]}),(s==null?void 0:s.fields.vendor)&&e.jsxs("div",{"data-testid":"basic-information-vendor-field",children:[e.jsx(re,{htmlFor:"vendor",className:"text-base font-semibold",children:"Vendor/Supplier"}),e.jsx(Re,{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(re,{htmlFor:"costCenter",className:"text-base font-semibold",children:"Cost Center"}),e.jsx(Re,{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(re,{htmlFor:"project",className:"text-base font-semibold",children:"Related Project"}),e.jsx(Re,{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 Z1(){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),g=((m=(await Zs(u,d)).data)==null?void 0:m.data)||[];s(g)}catch(u){console.error("User search failed:",u),s([])}finally{r(!1)}},300)},clearSearch:()=>{n.current&&clearTimeout(n.current),s([]),r(!1)},ensureUser:async c=>{try{return await Ks({userId:c.userId,email:c.email,displayName:c.displayName,firstName:c.firstName,lastName:c.lastName,department:c.department,phone:c.phone,mobilePhone:c.mobilePhone,designation:c.designation,jobTitle:c.jobTitle,manager:c.manager,employeeId:c.employeeId,employeeNumber:c.employeeNumber,secondEmail:c.secondEmail,location:c.location})}catch(d){throw console.error("Failed to ensure user exists:",d),d}}}}function Kp(){const[t,s]=x.useState({}),[a,r]=x.useState({}),n=x.useRef({});return{userSearchResults:t,userSearchLoading:a,searchUsersForIndex:async(o,c,d=10)=>{if(n.current[o]&&clearTimeout(n.current[o]),!c||!c.startsWith("@")||c.length<2){s(m=>({...m,[o]:[]})),r(m=>({...m,[o]:!1}));return}r(m=>({...m,[o]:!0})),n.current[o]=setTimeout(async()=>{var m;try{const u=c.slice(1),g=((m=(await Zs(u,d)).data)==null?void 0:m.data)||[];s(p=>({...p,[o]:g}))}catch(u){console.error(`User search failed for index ${o}:`,u),s(h=>({...h,[o]:[]}))}finally{r(u=>({...u,[o]:!1}))}},300)},clearSearchForIndex:o=>{n.current[o]&&clearTimeout(n.current[o]),s(c=>({...c,[o]:[]})),r(c=>({...c,[o]:!1}))}}}function X1({formData:t,updateFormData:s,onValidationError:a}){var d;const{userSearchResults:r,userSearchLoading:n,searchUsersForIndex:i,clearSearchForIndex:l}=Kp();x.useEffect(()=>{const m=t.approverCount||1,u=t.approvers||[];if(u.length<m){const h=[...u];for(let g=u.length;g<m;g++)h[g]||(h[g]={email:"",name:"",level:g+1,tat:""});s("approvers",h)}else u.length>m&&s("approvers",u.slice(0,m))},[t.approverCount,s]);const o=(m,u)=>{var y,b,j,v,w;const h=[...t.approvers],p=((y=h[m])==null?void 0:y.email)!==u;if(h[m]={...h[m],email:u,level:m+1,userId:p||(b=h[m])==null?void 0:b.userId,name:p||(j=h[m])==null?void 0:j.name,department:p||(v=h[m])==null?void 0:v.department,avatar:p||(w=h[m])==null?void 0:w.avatar},s("approvers",h),!u||!u.startsWith("@")||u.length<2){l(m);return}i(m,u,10)},c=async(m,u)=>{var h,g;try{if((h=t.approvers)==null?void 0:h.some((v,w)=>{var N,C;return w!==m&&(v.userId===u.userId||((N=v.email)==null?void 0:N.toLowerCase())===((C=u.email)==null?void 0:C.toLowerCase()))})){a({type:"error",email:u.email,message:"This user is already added as an approver in another level."});return}if((g=t.spectators)==null?void 0:g.some(v=>{var w,N;return v.userId===u.userId||((w=v.email)==null?void 0:w.toLowerCase())===((N=u.email)==null?void 0:N.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 b=await Ks({userId:u.userId,email:u.email,displayName:u.displayName,firstName:u.firstName,lastName:u.lastName,department:u.department,phone:u.phone,mobilePhone:u.mobilePhone,designation:u.designation,jobTitle:u.jobTitle,manager:u.manager,employeeId:u.employeeId,employeeNumber:u.employeeNumber,secondEmail:u.secondEmail,location:u.location}),j=[...t.approvers];j[m]={...j[m],email:u.email,name:u.displayName||[u.firstName,u.lastName].filter(Boolean).join(" "),userId:b.userId,level:m+1},s("approvers",j),l(m)}catch(p){console.error("Failed to ensure user exists:",p),a({type:"error",email:u.email,message:"Failed to validate user. Please try again."})}};return e.jsxs(as.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(Mt,{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(te,{"data-testid":"approval-workflow-config-card",children:[e.jsxs(me,{children:[e.jsxs(he,{className:"flex items-center gap-2","data-testid":"approval-workflow-config-title",children:[e.jsx(Da,{className:"w-5 h-5"}),"Approval Configuration"]}),e.jsx(De,{children:"Configure how many approvers you need and define the approval sequence."})]}),e.jsx(se,{className:"space-y-6",children:e.jsxs("div",{"data-testid":"approval-workflow-count-field",children:[e.jsx(re,{className:"text-base font-semibold mb-4 block",children:"Number of Approvers *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(I,{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(_f,{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(I,{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(Ls,{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(te,{"data-testid":"approval-workflow-hierarchy-card",children:[e.jsxs(me,{children:[e.jsxs(he,{className:"flex items-center gap-2","data-testid":"approval-workflow-hierarchy-title",children:[e.jsx(cs,{className:"w-5 h-5"}),"Approval Hierarchy *"]}),e.jsxs(De,{children:["Define the approval sequence. Each approver will review the request in order from Level 1 to Level ",t.approverCount||1,"."]})]}),e.jsxs(se,{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(Pt,{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(ie,{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,b;const h=u+1,g=h===(t.approverCount||1),p=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 ${p.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 ${p.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]}),g&&e.jsx(ie,{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(re,{htmlFor:`approver-${h}`,className:"text-sm font-medium",children:"Email Address *"}),p.email&&p.userId&&e.jsxs(ie,{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(Re,{id:`approver-${h}`,type:"email",placeholder:"approver@royalenfield.com",value:p.email||"",onChange:j=>o(u,j.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:(b=r[u])==null?void 0:b.map(j=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>c(u,j),"data-testid":`approval-workflow-approver-${h}-search-result-${j.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:j.displayName||j.email}),e.jsx("div",{className:"text-xs text-gray-600",children:j.email})]},j.userId))})})]})]}),e.jsxs("div",{"data-testid":`approval-workflow-approver-${h}-tat-field`,children:[e.jsx(re,{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(Re,{id:`tat-${h}`,type:"number",placeholder:p.tatType==="days"?"7":"24",min:"1",max:p.tatType==="days"?"30":"720",value:p.tat||"",onChange:j=>{const v=[...t.approvers];v[u]={...v[u],tat:parseInt(j.target.value)||"",level:h,tatType:p.tatType||"hours"},s("approvers",v)},className:"h-10 border-2 border-gray-300 focus:border-blue-500 flex-1","data-testid":`approval-workflow-approver-${h}-tat-input`}),e.jsxs(Ue,{value:p.tatType||"hours",onValueChange:j=>{const v=[...t.approvers];v[u]={...v[u],tatType:j,level:h,tat:""},s("approvers",v)},"data-testid":`approval-workflow-approver-${h}-tat-type-select`,children:[e.jsx(ze,{className:"w-20 h-10 border-2 border-gray-300",children:e.jsx(Ve,{})}),e.jsxs(He,{children:[e.jsx(Y,{value:"hours",children:"Hours"}),e.jsx(Y,{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(Nr,{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(Ze,{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((g,p)=>{const y=Number(p.tat||0);return(p.tatType||"hours")==="days"?g+y:g+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),p=(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:[p," ",p===1?"hour":"hours"]})]})},u):null})}),(()=>{var h;const m=((h=t.approvers)==null?void 0:h.reduce((g,p)=>{const y=Number(p.tat||0);return(p.tatType||"hours")==="days"?g+y*24:g+y},0))||0,u=Math.ceil(m/8);return m===0?null:e.jsxs("div",{className:"bg-white/80 p-3 rounded border border-emerald-200",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-center",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-lg font-bold text-emerald-800",children:[m,"h"]}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Total Hours"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-lg font-bold text-emerald-800",children:u}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Working Days*"})]})]}),e.jsx("p",{className:"text-xs text-emerald-600 mt-2 text-center",children:"*Based on 8-hour working days"})]})})()]})]})]})})]})]})]})}function J1({formData:t,updateFormData:s,onValidationError:a,initiatorEmail:r}){const[n,i]=x.useState(""),{searchResults:l,searchLoading:o,searchUsersDebounced:c,clearSearch:d,ensureUser:m}=Z1(),u=p=>{if(i(p),!p||!p.startsWith("@")||p.length<2){d();return}c(p,10)},h=async p=>{var y,b;if(p){if(p.email.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:p.email,message:"You cannot add yourself as a spectator."});return}const j=t.spectators.some(w=>{var N,C;return w.userId===p.userId||((N=w.email)==null?void 0:N.toLowerCase())===((C=p.email)==null?void 0:C.toLowerCase())}),v=(y=t.approvers)==null?void 0:y.some(w=>{var N,C;return w.userId===p.userId||((N=w.email)==null?void 0:N.toLowerCase())===((C=p.email)==null?void 0:C.toLowerCase())});if(j){a({type:"error",email:p.email,message:"This user is already added as a spectator."});return}if(v){a({type:"error",email:p.email,message:"This user is already added as an approver. A user cannot be both an approver and a spectator."});return}try{const w=await m(p),N={id:w.userId,userId:w.userId,name:w.displayName||p.email.split("@")[0],email:w.email,avatar:(w.displayName||w.email).substring(0,2).toUpperCase(),role:"Spectator",department:w.department||"",level:1,canClose:!1},C=[...t.spectators,N];s("spectators",C),i(""),d()}catch{a({type:"error",email:p.email,message:"Failed to validate user. Please try again."})}}else if(n&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)){if(n.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:n,message:"You cannot add yourself as a spectator."});return}const j=t.spectators.some(w=>{var N;return((N=w.email)==null?void 0:N.toLowerCase())===n.toLowerCase()}),v=(b=t.approvers)==null?void 0:b.some(w=>{var N;return((N=w.email)==null?void 0:N.toLowerCase())===n.toLowerCase()});if(j){a({type:"error",email:n,message:"This user is already added as a spectator."});return}if(v){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}}},g=p=>{const y=t.spectators.filter(b=>b.id!==p);s("spectators",y)};return e.jsxs(as.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(bt,{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(te,{"data-testid":"participants-spectators-card",children:[e.jsxs(me,{children:[e.jsxs(he,{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(bt,{className:"w-4 h-4"}),"Spectators"]}),e.jsx(ie,{variant:"outline",className:"text-xs","data-testid":"participants-spectators-count",children:t.spectators.length})]}),e.jsx(De,{children:"Users who can view and comment but cannot approve"})]}),e.jsxs(se,{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(Re,{placeholder:"Use @ sign to add a user",value:n,onChange:p=>u(p.target.value),onKeyPress:async p=>{p.key==="Enter"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)&&(p.preventDefault(),await h())},className:"text-sm w-full","data-testid":"participants-spectators-email-input"}),(o||l.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:o?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:l.map(p=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>h(p),"data-testid":`participants-spectators-search-result-${p.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:p.displayName||p.email}),e.jsx("div",{className:"text-xs text-gray-600",children:p.email})]},p.userId))})})]}),e.jsx(I,{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(Nr,{className:"w-3 h-3 flex-shrink-0"}),e.jsxs("span",{children:["Use ",e.jsx("span",{className:"font-mono bg-blue-100 px-1 rounded",children:"@"})," sign to search users, or type email directly (will be validated against organization directory)"]})]})]}),e.jsx("div",{className:"space-y-2 max-h-40 overflow-y-auto","data-testid":"participants-spectators-list",children:t.spectators.map(p=>e.jsxs("div",{className:"flex items-center justify-between p-2 bg-teal-50 rounded-lg","data-testid":`participants-spectator-${p.id}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qt,{className:"h-6 w-6",children:e.jsx(qt,{className:"bg-teal-600 text-white text-xs",children:p.avatar})}),e.jsx("span",{className:"text-sm font-medium",children:p.name})]}),e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>g(p.id),"data-testid":`participants-spectator-${p.id}-remove`,children:e.jsx(pt,{className:"h-3 w-3"})})]},p.id))})]})]})})})]})}function Q1({documentPolicy:t,isEditing:s,documents:a,existingDocuments:r,documentsToDelete:n,onDocumentsChange:i,onExistingDocumentsChange:l,onDocumentsToDeleteChange:o,onPreviewDocument:c,onDocumentErrors:d,fileInputRef:m}){const u=y=>{const b=Array.from(y.target.files||[]);if(b.length===0)return;const j=t.maxFileSizeMB*1024*1024,v=[],w=[];b.forEach(N=>{if(N.size>j){v.push({fileName:N.name,reason:`File size exceeds the maximum allowed size of ${t.maxFileSizeMB}MB. Current size: ${(N.size/1048576).toFixed(2)}MB`});return}const C=N.name.toLowerCase(),S=C.substring(C.lastIndexOf(".")+1);if(!t.allowedFileTypes.includes(S)){v.push({fileName:N.name,reason:`File type "${S}" is not allowed. Allowed types: ${t.allowedFileTypes.join(", ")}`});return}w.push(N)}),w.length>0&&i([...a,...w]),v.length>0&&d&&d(v),y.target&&(y.target.value="")},h=y=>{const b=a.filter((j,v)=>v!==y);i(b)},g=y=>{o([...n,y])},p=(y,b=!1)=>{if(b){const j=(y.fileType||y.file_type||"").toLowerCase(),v=(y.originalFileName||y.fileName||"").toLowerCase();return j.includes("image")||j.includes("pdf")||v.endsWith(".jpg")||v.endsWith(".jpeg")||v.endsWith(".png")||v.endsWith(".gif")||v.endsWith(".pdf")}else{const j=(y.type||"").toLowerCase(),v=(y.name||"").toLowerCase();return j.includes("image")||j.includes("pdf")||v.endsWith(".jpg")||v.endsWith(".jpeg")||v.endsWith(".png")||v.endsWith(".gif")||v.endsWith(".pdf")}};return e.jsxs(as.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(Rs,{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(te,{"data-testid":"documents-upload-card",children:[e.jsxs(me,{children:[e.jsxs(he,{className:"flex items-center gap-2","data-testid":"documents-upload-title",children:[e.jsx(Le,{className:"w-5 h-5"}),"File Upload"]}),e.jsxs(De,{children:["Attach supporting documents. Max ",t.maxFileSizeMB,"MB per file. Allowed types: ",t.allowedFileTypes.join(", ")]})]}),e.jsx(se,{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(Rs,{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(I,{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(Ls,{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(te,{"data-testid":"documents-existing-card",children:[e.jsx(me,{children:e.jsxs(he,{className:"flex items-center justify-between","data-testid":"documents-existing-title",children:[e.jsx("span",{children:"Existing Documents"}),e.jsxs(ie,{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(se,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-existing-list",children:r.map(y=>{const b=y.documentId||y.document_id||"";return n.includes(b)?null:e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border bg-gray-50","data-testid":`documents-existing-${b}`,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(Le,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:y.originalFileName||y.fileName||"Document"}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsx("span",{children:y.fileSize?(Number(y.fileSize)/(1024*1024)).toFixed(2)+" MB":"Unknown size"})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[p(y,!0)&&e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>c(y,!0),"data-testid":`documents-existing-${b}-preview`,children:e.jsx(bt,{className:"h-4 w-4"})}),e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>g(b),"data-testid":`documents-existing-${b}-delete`,children:e.jsx(pt,{className:"h-4 w-4 text-red-600"})})]})]},b)})})})]}),a.length>0&&e.jsxs(te,{"data-testid":"documents-new-card",children:[e.jsx(me,{children:e.jsxs(he,{className:"flex items-center justify-between","data-testid":"documents-new-title",children:[e.jsx("span",{children:"New Files to Upload"}),e.jsxs(ie,{variant:"secondary","data-testid":"documents-new-count",children:[a.length," file",a.length!==1?"s":""]})]})}),e.jsx(se,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-new-list",children:a.map((y,b)=>e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-lg border","data-testid":`documents-new-${b}`,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(Le,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:y.name}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsxs("span",{children:[(y.size/(1024*1024)).toFixed(2)," MB"]})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[p(y,!1)&&e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>c(y,!1),"data-testid":`documents-new-${b}-preview`,children:e.jsx(bt,{className:"h-4 w-4"})}),e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>h(b),"data-testid":`documents-new-${b}-remove`,children:e.jsx(pt,{className:"h-4 w-4"})})]})]},b))})})]})]})]})}const q1=t=>{switch(t){case"high":return e.jsx(ta,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(Bt,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(da,{className:"w-4 h-4 text-green-600"});default:return e.jsx(Bt,{className:"w-4 h-4 text-gray-600"})}};function e2({formData:t,selectedTemplate:s}){return e.jsxs(as.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(te,{className:"border-2 border-green-200 bg-green-50/50","data-testid":"review-submit-overview-card",children:[e.jsx(me,{children:e.jsxs(he,{className:"flex items-center gap-2 text-green-900","data-testid":"review-submit-overview-title",children:[e.jsx(Nu,{className:"w-5 h-5"}),"Request Overview"]})}),e.jsxs(se,{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(re,{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(ie,{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(re,{className:"text-green-900 font-semibold",children:"Priority"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[q1(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(re,{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(re,{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(te,{"data-testid":"review-submit-basic-info-card",children:[e.jsx(me,{children:e.jsxs(he,{className:"flex items-center gap-2","data-testid":"review-submit-basic-info-title",children:[e.jsx(Le,{className:"w-5 h-5"}),"Basic Information"]})}),e.jsxs(se,{className:"space-y-4",children:[e.jsxs("div",{"data-testid":"review-submit-basic-info-description",children:[e.jsx(re,{className:"font-semibold",children:"Description"}),e.jsx("div",{className:"mt-1 p-3 bg-gray-50 rounded-lg border",children:e.jsx(Ws,{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(Pa,{className:"w-4 h-4 text-blue-600"}),e.jsx(re,{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(te,{className:"border-2 border-orange-200 bg-orange-50/50","data-testid":"review-submit-approval-card",children:[e.jsxs(me,{children:[e.jsxs(he,{className:"flex items-center gap-2 text-orange-900","data-testid":"review-submit-approval-title",children:[e.jsx(Mt,{className:"w-5 h-5"}),"Approval Workflow"]}),e.jsx(De,{className:"text-orange-700",children:"Sequential approval hierarchy with TAT (Turn Around Time) for each level"})]}),e.jsx(se,{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),l=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 ${l!=null&&l.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(ie,{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:(l==null?void 0:l.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:l!=null&&l.tat?`${l.tat} ${l.tatType==="days"?"day":"hour"}${l.tat!==1?"s":""}`:"Not set"})]})]})]})]})},n)})})})]}),e.jsxs(te,{"data-testid":"review-submit-participants-card",children:[e.jsx(me,{children:e.jsxs(he,{className:"flex items-center gap-2","data-testid":"review-submit-participants-title",children:[e.jsx(bt,{className:"w-5 h-5"}),"Participants & Access Control"]})}),e.jsx(se,{className:"space-y-4",children:t.spectators.length>0&&e.jsxs("div",{"data-testid":"review-submit-participants-spectators",children:[e.jsxs(re,{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(ie,{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(te,{"data-testid":"review-submit-documents-card",children:[e.jsxs(me,{children:[e.jsxs(he,{className:"flex items-center gap-2","data-testid":"review-submit-documents-title",children:[e.jsx(Rs,{className:"w-5 h-5"}),"Documents & Attachments"]}),e.jsxs(De,{children:[t.documents.length," document",t.documents.length!==1?"s":""," attached to this request"]})]}),e.jsx(se,{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(Le,{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(te,{className:"border-2 border-blue-200 bg-blue-50/50","data-testid":"review-submit-confirmation-card",children:e.jsx(se,{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 t2({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(I,{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(Ys,{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 s2({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(vi,{mode:"wait",children:t})})})}function a2({modal:t,onClose:s}){return e.jsx(ot,{open:t.open,onOpenChange:a=>!a&&s(),"data-testid":"create-request-validation-modal",children:e.jsxs(nt,{className:"sm:max-w-md",children:[e.jsxs(ct,{children:[e.jsxs(it,{className:"flex items-center gap-2","data-testid":"validation-modal-title",children:[t.type==="self-assign"&&e.jsxs(e.Fragment,{children:[e.jsx(We,{className:"w-5 h-5 text-amber-600"}),"Cannot Add Yourself"]}),t.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsx(We,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}),t.type==="error"&&e.jsxs(e.Fragment,{children:[e.jsx(We,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})]}),e.jsx(_t,{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(ci,{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(At,{children:e.jsx(I,{onClick:s,className:"w-full sm:w-auto","data-testid":"validation-modal-ok-button",children:t.type==="not-found"?"Fix Email":"OK"})})]})})}function r2({modal:t,documentPolicy:s,onClose:a}){return e.jsx(ot,{open:t.open,onOpenChange:r=>!r&&a(),"data-testid":"create-request-document-error-modal",children:e.jsxs(nt,{className:"sm:max-w-lg",children:[e.jsxs(ct,{children:[e.jsxs(it,{className:"flex items-center gap-2","data-testid":"document-error-modal-title",children:[e.jsx(We,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(_t,{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(At,{children:e.jsx(I,{onClick:a,className:"w-full sm:w-auto","data-testid":"document-error-modal-ok-button",children:"OK"})})]})})}function Bm({onBack:t,onSubmit:s,requestId:a,isEditMode:r=!1}){const n=ir(),i=_a(),l=n.requestId||a||"",o=r&&!!l,{user:c}=Kt(),{formData:d,updateFormData:m,selectedTemplate:u,setSelectedTemplate:h,loadingDraft:g,systemPolicy:p,documentPolicy:y,existingDocuments:b,setExistingDocuments:j}=A1(o,l,Lm),{currentStep:v,totalSteps:w,stepNames:N,isStepValid:C,nextStep:S,prevStep:E}=T1(o,u,d),[P,R]=x.useState([]),[f,T]=x.useState([]),F=x.useRef(null),{validationModal:K,policyViolationModal:B,documentErrorModal:U,openValidationModal:D,closeValidationModal:A,closePolicyViolationModal:k,openDocumentErrorModal:M,closeDocumentErrorModal:O}=k1(),{submitting:L,savingDraft:Z,handleSubmit:z,handleSaveDraft:$}=F1({formData:d,selectedTemplate:u,documents:P,documentsToDelete:f,user:c,isEditing:o,editRequestId:l,onSubmit:s}),{showTemplateModal:W,setShowTemplateModal:_,previewDocument:G,selectTemplate:H,handleTemplateSelection:V,nextStep:ee,prevStep:oe,handlePreviewDocument:pe,closePreview:Pe}=z1({selectedTemplate:u,setSelectedTemplate:h,updateFormData:m,formData:d,currentStep:v,isStepValid:C,wizardNextStep:S,wizardPrevStep:E,user:c,openValidationModal:D,onSubmit:s}),Se=x.useCallback(()=>{v===1||v===3||v===4?t?t():window.history.length>1?window.history.back():i("/dashboard",{replace:!0}):oe()},[v,t,i,oe]),ne=x.useRef(!0),de=x.useRef(!1);x.useEffect(()=>{ne.current&&d.documents&&d.documents.length>0&&!de.current&&(R(d.documents),de.current=!0),ne.current=!1},[d.documents]);const le=x.useRef(!1),fe=x.useRef(P);x.useEffect(()=>{if(le.current){le.current=!1,fe.current=P;return}fe.current!==P&&(m("documents",P),fe.current=P)},[P]);const st=()=>{switch(v){case 1:return e.jsx(G1,{templates:Lm,selectedTemplate:u,onSelectTemplate:H});case 2:return e.jsx(Y1,{formData:d,selectedTemplate:u,updateFormData:m});case 3:return e.jsx(X1,{formData:d,updateFormData:m,onValidationError:ae=>D(ae.type,ae.email,ae.message)});case 4:return e.jsx(J1,{formData:d,updateFormData:m,onValidationError:ae=>D(ae.type,ae.email,ae.message),initiatorEmail:(c==null?void 0:c.email)||""});case 5:return e.jsx(Q1,{documentPolicy:y,isEditing:o,documents:P,existingDocuments:b,documentsToDelete:f,onDocumentsChange:R,onExistingDocumentsChange:j,onDocumentsToDeleteChange:T,onPreviewDocument:pe,onDocumentErrors:ae=>M(ae),fileInputRef:F});case 6:return e.jsx(e2,{formData:d,selectedTemplate:u});default:return null}};return g?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(t2,{isEditing:o,currentStep:v,totalSteps:w,stepNames:N,onBack:Se}),e.jsx(H1,{currentStep:v,totalSteps:w,stepNames:N}),e.jsx(s2,{children:st()}),e.jsx(W1,{currentStep:v,totalSteps:w,isStepValid:C(),onPrev:oe,onNext:ee,onSubmit:z,onSaveDraft:$,submitting:L,savingDraft:Z,loadingDraft:g,isEditing:o}),e.jsx(b1,{open:W,onClose:()=>_(!1),onSelectTemplate:V}),G&&e.jsx(Zo,{fileName:G.fileName,fileType:G.fileType,fileUrl:G.fileUrl,fileSize:G.fileSize,open:!!G,onClose:Pe,onDownload:async()=>{if(G.file){const ae=document.createElement("a");ae.href=G.fileUrl,ae.download=G.fileName,document.body.appendChild(ae),ae.click(),document.body.removeChild(ae)}else G.documentId&&await nr(G.documentId)},attachmentId:G.documentId}),e.jsx(a2,{modal:K,onClose:A}),e.jsx(r2,{modal:U,documentPolicy:y,onClose:O}),e.jsx(zp,{open:B.open,onClose:k,violations:B.violations,policyDetails:{maxApprovalLevels:p.maxApprovalLevels,maxParticipants:p.maxParticipants,allowSpectators:p.allowSpectators,maxSpectators:p.maxSpectators}})]})}function wn({className:t,...s}){return e.jsx(Mg,{"data-slot":"tabs",className:we("flex flex-col gap-2",t),...s})}function Cn({className:t,...s}){return e.jsx(Fg,{"data-slot":"tabs-list",className:we("bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-xl p-[3px] flex",t),...s})}function Ct({className:t,...s}){return e.jsx(_g,{"data-slot":"tabs-trigger",className:we("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 St({className:t,...s}){return e.jsx(Lg,{"data-slot":"tabs-content",className:we("flex-1 outline-none",t),...s})}function Yp(t,s,a,r){const[n,i]=x.useState([]),[l,o]=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 b=await ws.getWorkflowDetails(t);(y=b==null?void 0:b.workflow)!=null&&y.requestId&&m&&(u=b.workflow.requestId)}catch(b){console.error("[useRequestSocket] Failed to resolve UUID:",b)}if(!m)return;const h=fr();if(!h){console.error("[useRequestSocket] Socket not available");return}const g=r==null?void 0:r.userId,p=()=>{wl(h,u,g)};return h.connected?p():h.on("connect",p),()=>{m&&(h.off("connect",p),Yu(h,u))}})(),()=>{m=!1}},[t,r]),x.useEffect(()=>{!t||!s||(async()=>{try{const m=await xr(t),u=s.auditTrail||[],h=[...m,...u];h.sort((g,p)=>{const y=new Date(g.createdAt||g.created_at||g.timestamp||0).getTime(),b=new Date(p.createdAt||p.created_at||p.timestamp||0).getTime();return y-b}),i(h)}catch(m){console.error("[useRequestSocket] Failed to fetch and merge messages:",m)}})()},[t,s]),x.useEffect(()=>{if(!t)return;const m=fr();if(!m)return;const u=g=>{a!=="worknotes"&&o(p=>p+1),(async()=>{try{const p=await xr(t),y=(s==null?void 0:s.auditTrail)||[],b=[...p,...y].sort((j,v)=>{const w=new Date(j.createdAt||j.created_at||j.timestamp||0).getTime(),N=new Date(v.createdAt||v.created_at||v.timestamp||0).getTime();return w-N});i(b)}catch(p){console.error("[useRequestSocket] Failed to refresh messages:",p)}})()},h=g=>{const p=g.type==="breach"?"⏰":g.type==="threshold2"?"⚠️":"⏳";(async()=>{try{const y=await ws.getWorkflowDetails(t);y&&(Array.isArray(y.tatAlerts)&&y.tatAlerts,"Notification"in window&&Notification.permission==="granted"&&new Notification(`${p} TAT Alert`,{body:g.message,icon:"/favicon.ico",tag:`tat-${g.requestId}-${g.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"&&o(0)},[a]),{mergedMessages:n,unreadWorkNotes:l,workNoteAttachments:c,setWorkNoteAttachments:d}}async function en(t,s,a="SUPPORTING"){var l;const r=new FormData;r.append("file",t),r.append("requestId",s),r.append("category",a);const n=await ye.post("/documents",r,{headers:{"Content-Type":"multipart/form-data"}}),i=((l=n.data)==null?void 0:l.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}}function Zp(t,s){const[a,r]=x.useState(!1),[n,i]=x.useState(null),[l,o]=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 p=await ar("DOCUMENT_POLICY"),y={};p.forEach(w=>{y[w.configKey]=w.configValue});const b=parseInt(y.MAX_FILE_SIZE_MB||"10"),v=(y.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(w=>w.trim().toLowerCase());o({maxFileSizeMB:b,allowedFileTypes:v})}catch(p){console.error("Failed to load document policy:",p)}})()},[]);const m=g=>{const p=l.maxFileSizeMB*1024*1024;if(g.size>p)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${l.maxFileSizeMB}MB. Current size: ${(g.size/(1024*1024)).toFixed(2)}MB`};const y=g.name.toLowerCase(),b=y.substring(y.lastIndexOf(".")+1);return l.allowedFileTypes.includes(b)?{valid:!0}:{valid:!1,reason:`File type "${b}" is not allowed. Allowed types: ${l.allowedFileTypes.join(", ")}`}},u=async g=>{var v,w;const p=g.target.files;if(!p||p.length===0)return;const y=Array.from(p),b=[],j=[];if(y.forEach(N=>{const C=m(N);C.valid?j.push(N):b.push({fileName:N.name,reason:C.reason||"Unknown validation error"})}),b.length>0&&d({show:!0,errors:b}),j.length===0){g.target&&(g.target.value="");return}r(!0);try{const N=j[0],C=t==null?void 0:t.requestId;if(!C){q.error("Request ID not found");return}N&&await en(N,C,"SUPPORTING"),await s(),j.length<y.length?q.warning(`${j.length} of ${y.length} file(s) were uploaded. ${b.length} file(s) were rejected.`):q.success("Document uploaded successfully")}catch(N){console.error("[useDocumentUpload] Upload error:",N),q.error(((w=(v=N==null?void 0:N.response)==null?void 0:v.data)==null?void 0:w.error)||"Failed to upload document")}finally{r(!1),g.target&&(g.target.value="")}};return{uploadingDocument:a,handleDocumentUpload:u,triggerFileInput:()=>{const g=document.createElement("input");g.type="file",g.accept=l.allowedFileTypes.map(p=>`.${p}`).join(","),g.onchange=u,g.click()},previewDocument:n,setPreviewDocument:i,documentPolicy:l,documentError:c,setDocumentError:d}}function Xp(t,s,a,r,n,i,l){const[o,c]=x.useState(""),[d,m]=x.useState(!1),[u,h]=x.useState(!1),[g,p]=x.useState(!1),y=async()=>{try{const{getConclusion:v}=await Bn(async()=>{const{getConclusion:N}=await import("./conclusionApi-DFZpYv7A.js");return{getConclusion:N}},__vite__mapDeps([0,1,2,3,4,5,6,7])),w=await v(t.requestId||s);w&&w.aiGeneratedRemark&&(c(w.finalRemark||w.aiGeneratedRemark),p(!!w.aiGeneratedRemark))}catch{}},b=async()=>{try{m(!0);const{generateConclusion:v}=await Bn(async()=>{const{generateConclusion:N}=await import("./conclusionApi-DFZpYv7A.js");return{generateConclusion:N}},__vite__mapDeps([0,1,2,3,4,5,6,7])),w=await v(t.requestId||s);c(w.aiGeneratedRemark),p(!0)}catch(v){console.error("[useConclusionRemark] AI generation failed:",v),c(""),p(!1)}finally{m(!1)}},j=async()=>{var w,N;const v=o.replace(/<[^>]*>/g,"").trim();if(!v){i==null||i({success:!1,title:"Validation Error",message:"Conclusion remark cannot be empty"}),l==null||l(!0);return}if(v.length>2e3){i==null||i({success:!1,title:"Validation Error",message:"Conclusion remark exceeds 2000 characters limit"}),l==null||l(!0);return}try{h(!0);const{finalizeConclusion:C}=await Bn(async()=>{const{finalizeConclusion:S}=await import("./conclusionApi-DFZpYv7A.js");return{finalizeConclusion:S}},__vite__mapDeps([0,1,2,3,4,5,6,7]));await C(t.requestId||s,o),i==null||i({success:!0,title:"Request Closed with Successful Completion",message:"The request has been finalized and moved to Closed Requests."}),l==null||l(!0),await r(),setTimeout(()=>{n?(n(),setTimeout(()=>{window.location.hash="#/closed-requests"},100)):window.location.hash="#/closed-requests"},2e3)}catch(C){i==null||i({success:!1,title:"Error",message:((N=(w=C.response)==null?void 0:w.data)==null?void 0:N.error)||"Failed to finalize conclusion"}),l==null||l(!0)}finally{h(!1)}};return x.useEffect(()=>{((t==null?void 0:t.status)==="approved"||(t==null?void 0:t.status)==="rejected")&&a&&!o&&y()},[t==null?void 0:t.status,a]),{conclusionRemark:o,setConclusionRemark:c,conclusionLoading:d,conclusionSubmitting:u,aiGenerated:g,handleGenerateConclusion:b,handleFinalizeConclusion:j}}function Jp(t,s,a){const[r,n]=x.useState(!1),[i,l]=x.useState(!1),[o,c]=x.useState(!1),[d,m]=x.useState(!1),[u,h]=x.useState(!1),[g,p]=x.useState(!1),[y,b]=x.useState(null),[j,v]=x.useState(null);return{showApproveModal:r,setShowApproveModal:n,showRejectModal:i,setShowRejectModal:l,showAddApproverModal:o,setShowAddApproverModal:c,showAddSpectatorModal:d,setShowAddSpectatorModal:m,showSkipApproverModal:u,setShowSkipApproverModal:h,showActionStatusModal:g,setShowActionStatusModal:p,skipApproverData:y,setSkipApproverData:b,actionStatus:j,setActionStatus:v,handleApproveConfirm:async P=>{var f,T;const R=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!R){alert("Approval level not found");return}await Jr(t,R,P||""),await new Promise(F=>setTimeout(F,500)),await a(),(f=window==null?void 0:window.closeModal)==null||f.call(window),(T=window==null?void 0:window.toast)==null||T.call(window,"Approved successfully")},handleRejectConfirm:async P=>{var f,T;if(!(P!=null&&P.trim())){alert("Comments & remarks are required");return}const R=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!R){alert("Approval level not found");return}await Qr(t,R,P.trim(),P.trim()),await a(),(f=window==null?void 0:window.closeModal)==null||f.call(window),(T=window==null?void 0:window.toast)==null||T.call(window,"Rejected successfully")},handleAddApprover:async(P,R,f)=>{var T,F;try{await th(t,P,R,f),await a(),c(!1),v==null||v({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${f} with ${R}h TAT`}),p==null||p(!0)}catch(K){throw v==null||v({success:!1,title:"Failed to Add Approver",message:((F=(T=K==null?void 0:K.response)==null?void 0:T.data)==null?void 0:F.error)||"Failed to add approver. Please try again."}),p==null||p(!0),K}},handleSkipApprover:async P=>{var R,f;if(y)try{await Yb(t,y.levelId,P),await a(),h(!1),b(null),v==null||v({success:!0,title:"Approver Skipped",message:"Approver skipped successfully. The workflow has moved to the next level."}),p==null||p(!0)}catch(T){throw v==null||v({success:!1,title:"Failed to Skip Approver",message:((f=(R=T==null?void 0:T.response)==null?void 0:R.data)==null?void 0:f.error)||"Failed to skip approver. Please try again."}),p==null||p(!0),T}},handleAddSpectator:async P=>{var R,f;try{await sh(t,P),await a(),m(!1),v==null||v({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),p==null||p(!0)}catch(T){throw v==null||v({success:!1,title:"Failed to Add Spectator",message:((f=(R=T==null?void 0:T.response)==null?void 0:R.data)==null?void 0:f.error)||"Failed to add spectator. Please try again."}),p==null||p(!0),T}}}}const n2=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 Um({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(Le,{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 ",es(t.uploadedAt)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&n2(t.fileType)&&s&&e.jsx(I,{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(bt,{className:"w-4 h-4"})}),a&&e.jsx(I,{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(Nt,{className:"w-4 h-4"})})]})]})}function i2({request:t,workNoteAttachments:s,uploadingDocument:a,documentPolicy:r,triggerFileInput:n,setPreviewDocument:i,downloadDocument:l}){return e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[e.jsxs(te,{children:[e.jsx(me,{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(he,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Le,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Documents"]}),e.jsx(De,{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(I,{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(Rs,{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(se,{children:t.documents&&t.documents.length>0?e.jsx("div",{className:"space-y-3",children:t.documents.map((o,c)=>e.jsx(Um,{document:o,onPreview:d=>i(d),onDownload:l,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(te,{children:[e.jsxs(me,{children:[e.jsxs(he,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Os,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"Work Note Attachments"]}),e.jsx(De,{className:"text-xs sm:text-sm",children:"Files shared in work notes discussions"})]}),e.jsx(se,{children:s&&s.length>0?e.jsx("div",{className:"space-y-3",children:s.map((o,c)=>e.jsx(Um,{document:{documentId:o.attachmentId||"",name:o.name,fileType:o.type||"",size:o.size?`${(o.size/1024).toFixed(1)} KB`:"Unknown size",sizeBytes:o.size,uploadedBy:o.uploadedBy,uploadedAt:o.uploadedAt},onPreview:d=>i(d),onDownload:async d=>{const{downloadWorkNoteAttachment:m}=require("@/services/workflowApi");await m(d)},testId:"worknote-attachment"},o.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"})})]})]})}const l2=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"}}},o2=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}}},c2=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(xt,{className:"w-5 h-5 text-red-600"});case"comment":return e.jsx(Os,{className:"w-5 h-5 text-blue-600"});case"status_change":case"updated":return e.jsx(ns,{className:"w-5 h-5 text-orange-600"});case"assignment":return e.jsx(di,{className:"w-5 h-5 text-purple-600"});case"created":return e.jsx(Le,{className:"w-5 h-5 text-blue-600"});case"reminder":return e.jsx(Ze,{className:"w-5 h-5 text-yellow-600"});case"document_added":return e.jsx(ii,{className:"w-5 h-5 text-indigo-600"});case"sla_warning":return e.jsx(hs,{className:"w-5 h-5 text-amber-600"});default:return e.jsx(ts,{className:"w-5 h-5 text-gray-600"})}};function d2({request:t}){return e.jsxs(te,{children:[e.jsxs(me,{children:[e.jsxs(he,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(ts,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Activity Timeline"]}),e.jsx(De,{className:"text-xs sm:text-sm",children:"Complete audit trail of all request activities"})]}),e.jsx(se,{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:c2(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:es(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(ts,{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 Qp({open:t,onClose:s,success:a,title:r,message:n}){return e.jsx(ot,{open:t,onOpenChange:s,children:e.jsxs(nt,{className:"sm:max-w-md",children:[e.jsx(ct,{children:e.jsxs(it,{className:"flex items-center gap-2",children:[a?e.jsx(Ce,{className:"w-5 h-5 text-green-600"}):e.jsx(We,{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(xt,{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(At,{children:e.jsx(I,{onClick:s,className:`w-full ${a?"bg-green-600 hover:bg-green-700":"bg-gray-600 hover:bg-gray-700"}`,children:"OK"})})]})})}function qp({open:t,onClose:s,onConfirm:a,existingParticipants:r=[]}){const[n,i]=x.useState(""),[l,o]=x.useState(!1),[c,d]=x.useState([]),[m,u]=x.useState(!1),[h,g]=x.useState(null),p=x.useRef(null),y=x.useRef(null),[b,j]=x.useState({open:!1,type:"error",email:"",message:""}),[v,w]=x.useState({open:!1,violations:[]}),[N,C]=x.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20});x.useEffect(()=>{t&&(async()=>{var T;try{const F=await ar("WORKFLOW_SHARING"),K=await ar("TAT_SETTINGS"),B=[...F,...K],U={};B.forEach(D=>{U[D.configKey]=D.configValue}),C({maxApprovalLevels:parseInt(U.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(U.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((T=U.ALLOW_ADD_SPECTATOR)==null?void 0:T.toLowerCase())==="true",maxSpectators:parseInt(U.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(F){console.error("Failed to load system policy:",F)}})()},[t]);const S=async()=>{var A,k;const f=n.trim().toLowerCase();if(!f){j({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(f)){j({open:!0,type:"error",email:f,message:"Please enter a valid email address"});return}const F=r.find(M=>(M.email||"").toLowerCase()===f);if(F){const M=((A=F.participantType)==null?void 0:A.toUpperCase())||"PARTICIPANT",O=F.name||f;if(M==="INITIATOR"){j({open:!0,type:"error",email:f,message:`${O} is the request initiator and cannot be added as a spectator.`});return}else if(M==="APPROVER"){j({open:!0,type:"error",email:f,message:`${O} is already an approver on this request and cannot be added as a spectator.`});return}else if(M==="SPECTATOR"){j({open:!0,type:"error",email:f,message:`${O} is already a spectator on this request.`});return}else{j({open:!0,type:"error",email:f,message:`${O} is already a participant on this request.`});return}}const K=[];N.allowSpectators||K.push({type:"Spectators Not Allowed",message:"Adding spectators is not allowed by system policy."});const U=r.filter(M=>(M.participantType||"").toUpperCase()==="SPECTATOR").length;U>=N.maxSpectators&&K.push({type:"Maximum Spectators Exceeded",message:"This request has reached the maximum number of spectators allowed.",currentValue:U,maxValue:N.maxSpectators});const D=r.length+1;if(D>N.maxParticipants&&K.push({type:"Maximum Participants Exceeded",message:"Adding this spectator would exceed the maximum participants limit.",currentValue:D,maxValue:N.maxParticipants}),K.length>0){w({open:!0,violations:K});return}if(!h||h.email.toLowerCase()!==f)try{const O=((k=(await Zs(f,1)).data)==null?void 0:k.data)||[];if(O.length===0){j({open:!0,type:"not-found",email:f,message:""});return}const L=O[0];await Ks({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(M){console.error("Failed to validate spectator:",M),j({open:!0,type:"error",email:f,message:"Failed to validate user. Please try again."});return}try{o(!0),await a(f),i(""),g(null),s()}catch(M){console.error("Failed to add spectator:",M)}finally{o(!1)}},E=()=>{l||(i(""),g(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(()=>()=>{p.current&&clearTimeout(p.current)},[]);const P=f=>{if(i(f),h&&h.email.toLowerCase()!==f.toLowerCase()&&g(null),p.current&&clearTimeout(p.current),!f||!f.startsWith("@")||f.length<2){d([]),u(!1);return}u(!0),p.current=setTimeout(async()=>{var T;try{const F=f.slice(1),B=((T=(await Zs(F,10)).data)==null?void 0:T.data)||[];d(B)}catch(F){console.error("Search failed:",F),d([])}finally{u(!1)}},300)},R=async f=>{try{await Ks({userId:f.userId,email:f.email,displayName:f.displayName,firstName:f.firstName,lastName:f.lastName,department:f.department,phone:f.phone,mobilePhone:f.mobilePhone,designation:f.designation,jobTitle:f.jobTitle,manager:f.manager,employeeId:f.employeeId,employeeNumber:f.employeeNumber,secondEmail:f.secondEmail,location:f.location}),i(f.email),g(f),d([]),u(!1)}catch(T){console.error("Failed to ensure user exists:",T),j({open:!0,type:"error",email:f.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(ot,{open:t,onOpenChange:E,children:[e.jsxs(nt,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:E,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:l,children:[e.jsx(pt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(ct,{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(bt,{className:"w-5 h-5 text-purple-600"})}),e.jsx(it,{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(mi,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Re,{type:"text",placeholder:"@username or user@example.com",value:n,onChange:f=>P(f.target.value),className:"pl-10 h-11 border-gray-300",disabled:l,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(f=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>R(f),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Qt,{className:"h-8 w-8",children:e.jsx(qt,{className:"bg-purple-100 text-purple-800 text-xs font-semibold",children:(f.displayName||f.email).split(" ").map(T=>T[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:f.displayName||[f.firstName,f.lastName].filter(Boolean).join(" ")||f.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:f.email}),f.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:f.designation})]})]})},f.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(I,{type:"button",variant:"outline",onClick:E,className:"flex-1 h-11 border-gray-300",disabled:l,children:"Cancel"}),e.jsxs(I,{type:"button",onClick:S,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:l||!n.trim(),children:[e.jsx(bt,{className:"w-4 h-4 mr-2"}),l?"Adding...":"Add Spectator"]})]})]}),e.jsx(ot,{open:b.open,onOpenChange:f=>j(T=>({...T,open:f})),children:e.jsxs(nt,{className:"sm:max-w-md",children:[e.jsxs(ct,{children:[e.jsx(it,{className:"flex items-center gap-2",children:b.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(We,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(We,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(_t,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[b.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:b.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(ci,{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."]})})]}),b.type==="error"&&e.jsxs(e.Fragment,{children:[b.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:b.email}),"."]}),b.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:b.message})})]})]})})]}),e.jsx(At,{children:e.jsx(I,{onClick:()=>j(f=>({...f,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(zp,{open:v.open,onClose:()=>w({open:!1,violations:[]}),violations:v.violations,policyDetails:{maxApprovalLevels:N.maxApprovalLevels,maxParticipants:N.maxParticipants,allowSpectators:N.allowSpectators,maxSpectators:N.maxSpectators}})]})}function ex({open:t,onClose:s,onConfirm:a,existingParticipants:r=[],currentLevels:n=[]}){const[i,l]=x.useState(""),[o,c]=x.useState(24),[d,m]=x.useState(null),[u,h]=x.useState(!1),[g,p]=x.useState([]),[y,b]=x.useState(!1),[j,v]=x.useState(null),w=x.useRef(null),N=x.useRef(null),[C,S]=x.useState({open:!1,type:"error",email:"",message:""}),E=n.filter(D=>D&&(D.status==="approved"||D.status==="rejected"||D.status==="skipped")),P=Math.max(1,E.length+1),R=Math.max(1,n.length+1),f=R>=P?Array.from({length:R-P+1},(D,A)=>P+A):[P];x.useEffect(()=>{f.length>0&&d===null&&m(f[0]||null)},[f.length,d]);const T=async()=>{var M,O;const D=i.trim().toLowerCase();if(!D){S({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(D)){S({open:!0,type:"error",email:D,message:"Please enter a valid email address"});return}if(!o||o<=0){S({open:!0,type:"error",email:"",message:"Please enter valid TAT hours (minimum 1 hour)"});return}if(o>720){S({open:!0,type:"error",email:"",message:"TAT hours cannot exceed 720 hours (30 days)"});return}if(!d){S({open:!0,type:"error",email:"",message:"Please select an approval level"});return}if(d<P){S({open:!0,type:"error",email:"",message:`Cannot add approver at level ${d}. Minimum allowed level is ${P} (after completed levels)`});return}const k=r.find(L=>(L.email||"").toLowerCase()===D);if(k){const L=((M=k.participantType)==null?void 0:M.toUpperCase())||"PARTICIPANT",Z=k.name||D;if(L==="INITIATOR"){S({open:!0,type:"error",email:D,message:`${Z} is the request initiator and cannot be added as an approver.`});return}else if(L==="APPROVER"){S({open:!0,type:"error",email:D,message:`${Z} is already an approver on this request.`});return}else if(L==="SPECTATOR"){S({open:!0,type:"error",email:D,message:`${Z} is currently a spectator on this request and cannot be added as an approver. Please remove them as spectator first.`});return}else{S({open:!0,type:"error",email:D,message:`${Z} is already a participant on this request.`});return}}if(!j||j.email.toLowerCase()!==D)try{const Z=((O=(await Zs(D,1)).data)==null?void 0:O.data)||[];if(Z.length===0){S({open:!0,type:"not-found",email:D,message:""});return}const z=Z[0];await Ks({userId:z.userId,email:z.email,displayName:z.displayName,firstName:z.firstName,lastName:z.lastName,department:z.department,phone:z.phone,mobilePhone:z.mobilePhone,designation:z.designation,jobTitle:z.jobTitle,manager:z.manager,employeeId:z.employeeId,employeeNumber:z.employeeNumber,secondEmail:z.secondEmail,location:z.location})}catch(L){console.error("Failed to validate approver:",L),S({open:!0,type:"error",email:D,message:"Failed to validate user. Please try again."});return}try{h(!0),await a(D,o,d),l(""),c(24),m(null),v(null),s()}catch(L){console.error("Failed to add approver:",L)}finally{h(!1)}},F=()=>{u||(l(""),c(24),m(null),v(null),p([]),b(!1),s())},K=D=>{const A=D.toLowerCase();return A==="approved"?e.jsx(Ce,{className:"w-4 h-4 text-green-600"}):A==="rejected"?e.jsx(xt,{className:"w-4 h-4 text-red-600"}):A==="skipped"?e.jsx(We,{className:"w-4 h-4 text-orange-600"}):A==="in-review"||A==="pending"?e.jsx(Ze,{className:"w-4 h-4 text-blue-600"}):e.jsx(Ze,{className:"w-4 h-4 text-gray-400"})};x.useEffect(()=>{g.length>0&&N.current&&N.current.scrollTo({top:N.current.scrollHeight,behavior:"smooth"})},[g.length]),x.useEffect(()=>()=>{w.current&&clearTimeout(w.current)},[]);const B=D=>{if(l(D),j&&j.email.toLowerCase()!==D.toLowerCase()&&v(null),w.current&&clearTimeout(w.current),!D||!D.startsWith("@")||D.length<2){p([]),b(!1);return}b(!0),w.current=setTimeout(async()=>{var A;try{const k=D.slice(1),O=((A=(await Zs(k,10)).data)==null?void 0:A.data)||[];p(O)}catch(k){console.error("Search failed:",k),p([])}finally{b(!1)}},300)},U=async D=>{try{await Ks({userId:D.userId,email:D.email,displayName:D.displayName,firstName:D.firstName,lastName:D.lastName,department:D.department,phone:D.phone,mobilePhone:D.mobilePhone,designation:D.designation,jobTitle:D.jobTitle,manager:D.manager,employeeId:D.employeeId,employeeNumber:D.employeeNumber,secondEmail:D.secondEmail,location:D.location}),l(D.email),v(D),p([]),b(!1)}catch(A){console.error("Failed to ensure user exists:",A),S({open:!0,type:"error",email:D.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(ot,{open:t,onOpenChange:F,children:[e.jsxs(nt,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:F,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(pt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(ct,{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(Mt,{className:"w-5 h-5 text-blue-600"})}),e.jsx(it,{className:"text-xl font-bold text-gray-900",children:"Add Approver"})]})}),e.jsxs("div",{ref:N,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(re,{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(D=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-md ${D.status==="approved"?"bg-green-100 border border-green-200":D.status==="rejected"?"bg-red-100 border border-red-200":D.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:D.levelNumber}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:D.approverName}),e.jsxs("p",{className:"text-xs text-gray-500",children:[D.tatHours,"h TAT"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[K(D.status),e.jsx(ie,{variant:"outline",className:`text-xs ${D.status==="approved"?"bg-green-50 text-green-700 border-green-300":D.status==="rejected"?"bg-red-50 text-red-700 border-red-300":D.status==="skipped"?"bg-orange-50 text-orange-700 border-orange-300":"bg-blue-50 text-blue-700 border-blue-300"}`,children:D.status})]})]},D.levelNumber))}),e.jsxs("p",{className:"text-xs text-gray-500",children:["ℹ️ New approver can only be added at level ",P," or higher (after completed levels)"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-medium text-gray-700",children:"Approval Level *"}),e.jsxs(Ue,{value:(d==null?void 0:d.toString())||"",onValueChange:D=>m(Number(D)),disabled:u,children:[e.jsx(ze,{className:"h-11 border-gray-300",children:e.jsx(Ve,{placeholder:"Select level"})}),e.jsx(He,{children:f.map(D=>e.jsx(Y,{value:D.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cs,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Level ",D]}),D<=n.length&&e.jsxs("span",{className:"text-xs text-gray-500",children:["(will shift existing Level ",D,")"]})]})},D))})]}),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(re,{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(Re,{type:"number",min:"1",max:"720",value:o,onChange:D=>c(Number(D.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(Ze,{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(mi,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Re,{type:"text",placeholder:"@username or user@example.com",value:i,onChange:D=>B(D.target.value),className:"pl-10 h-11 border-gray-300",disabled:u,autoFocus:!0}),(y||g.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..."}):g.length>0?e.jsx("ul",{className:"divide-y",children:g.map(D=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>U(D),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Qt,{className:"h-8 w-8",children:e.jsx(qt,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:(D.displayName||D.email).split(" ").map(A=>A[0]).join("").slice(0,2).toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:D.displayName||[D.firstName,D.lastName].filter(Boolean).join(" ")||D.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:D.email}),D.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:D.designation})]})]})},D.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(I,{type:"button",variant:"outline",onClick:F,className:"flex-1 h-11 border-gray-300",disabled:u,children:"Cancel"}),e.jsxs(I,{type:"button",onClick:T,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:u||!i.trim()||!d||!o,children:[e.jsx(Mt,{className:"w-4 h-4 mr-2"}),u?"Adding...":`Add at Level ${d||"?"}`]})]})]}),e.jsx(ot,{open:C.open,onOpenChange:D=>S(A=>({...A,open:D})),children:e.jsxs(nt,{className:"sm:max-w-md",children:[e.jsxs(ct,{children:[e.jsx(it,{className:"flex items-center gap-2",children:C.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(We,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(We,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(_t,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[C.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:C.email})," was not found in the organization directory."]}),e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3 space-y-2",children:[e.jsx("p",{className:"text-sm text-red-800 font-semibold",children:"Please verify:"}),e.jsxs("ul",{className:"text-sm text-red-700 space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"Email address is spelled correctly"}),e.jsx("li",{children:"User exists in Okta/SSO system"}),e.jsx("li",{children:"User has an active account"})]})]}),e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-blue-800 flex items-center gap-1",children:[e.jsx(ci,{className:"w-4 h-4"}),e.jsx("strong",{children:"Tip:"})," Use ",e.jsx("span",{className:"font-mono bg-blue-100 px-1 rounded",children:"@"})," sign to search users from the directory."]})})]}),C.type==="error"&&e.jsxs(e.Fragment,{children:[C.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:C.email}),"."]}),C.message&&e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-3",children:e.jsx("p",{className:"text-sm text-gray-700",children:C.message})})]})]})})]}),e.jsx(At,{children:e.jsx(I,{onClick:()=>S(D=>({...D,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const m2=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"}},u2=t=>{switch(t){case"online":return"Online";case"away":return"Away";case"offline":return"Offline";default:return"Unknown"}},h2=t=>t.replace(/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,(s,a,r,n)=>{const i=r+s.length,l=n[i];return!l||/\s|[.,!?;:]|@/.test(l)?'<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 />"),p2=t=>t<1024?t+" B":t<1024*1024?(t/1024).toFixed(1)+" KB":(t/(1024*1024)).toFixed(1)+" MB",Vm=({type:t})=>{const s="w-4 h-4",a=t.toLowerCase();return a.includes("pdf")?e.jsx(Le,{className:`${s} text-red-600`}):a.includes("excel")||a.includes("spreadsheet")||a.includes("xlsx")?e.jsx($f,{className:`${s} text-green-600`}):a.includes("powerpoint")||a.includes("presentation")||a.includes("pptx")?e.jsx(Le,{className:`${s} text-orange-600`}):a.includes("word")||a.includes("document")||a.includes("docx")?e.jsx(Le,{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($n,{className:`${s} text-purple-600`}):e.jsx(ii,{className:`${s} text-gray-600`})};function tx({requestId:t,messages:s,onSend:a,skipSocketJoin:r=!1,requestTitle:n,onAttachmentsExtracted:i,isInitiator:l=!1,isSpectator:o=!1,currentLevels:c=[],onAddApprover:d}){const m=ir(),u=t||m.requestId||"",[h,g]=x.useState(""),[p,y]=x.useState(""),[b,j]=x.useState(!1),[v,w]=x.useState([]),[N,C]=x.useState(!1),[S,E]=x.useState([]),[P,R]=x.useState(null),[f,T]=x.useState(null),[F,K]=x.useState(!1),[B,U]=x.useState(!1),[D,A]=x.useState(!1),[k,M]=x.useState({success:!0,title:"",message:""}),O=x.useRef(null),L=x.useRef(null),Z=x.useRef(null),z=x.useRef(!1),[$,W]=x.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[_,G]=x.useState({open:!1,errors:[]}),H=x.useMemo(()=>({id:u,title:n||"Request Details"}),[u,n]),[V,ee]=x.useState([]),oe=V.filter(Q=>Q.status==="online"),pe=v.filter(Q=>Q.content.toLowerCase().includes(p.toLowerCase())||Q.user.name.toLowerCase().includes(p.toLowerCase())),Pe=x.useMemo(()=>o!==void 0?o:!P||V.length===0?!1:V.some(Q=>{const ge=Q.userId||Q.user_id,X=(Q.role||"").toString().toUpperCase(),Ae=(Q.participantType||Q.participant_type||"").toString().toUpperCase();return ge===P&&(X==="SPECTATOR"||Ae==="SPECTATOR")}),[o,P,V]);x.useEffect(()=>{},[V]),x.useEffect(()=>{!u||!P||s||(async()=>{try{const Q=await xr(u),ge=Array.isArray(Q)?Q.map(X=>{const Ae=X.userId||X.user_id;return{id:X.noteId||X.id||String(Math.random()),user:{name:X.userName||"User",avatar:(X.userName||"U").slice(0,2).toUpperCase(),role:X.userRole||"Participant"},content:X.message||"",timestamp:X.createdAt||new Date().toISOString(),isCurrentUser:Ae===P,attachments:Array.isArray(X.attachments)?X.attachments.map(Te=>({attachmentId:Te.attachmentId||Te.attachment_id,name:Te.fileName||Te.file_name||Te.name,fileName:Te.fileName||Te.file_name||Te.name,url:Te.storageUrl||Te.storage_url||Te.url||"#",type:Te.fileType||Te.file_type||Te.type||"file",fileType:Te.fileType||Te.file_type||Te.type||"file",fileSize:Te.fileSize||Te.file_size})):void 0}}):[];w(ge)}catch(Q){console.error("[WorkNoteChat] Failed to load messages:",Q)}})()},[u,P,s]);const Se=x.useMemo(()=>{const Q=[];return v.forEach(ge=>{ge.attachments&&ge.attachments.length>0&&ge.attachments.forEach(X=>{Q.push({attachmentId:X.attachmentId||X.attachment_id,name:X.fileName||X.file_name||X.name||"Untitled",fileName:X.fileName||X.file_name||X.name||"Untitled",size:X.fileSize||X.file_size,type:X.fileType||X.file_type||X.type||"file",uploadedBy:ge.user.name,uploadedAt:ge.timestamp,url:X.storageUrl||X.storage_url||X.url||"#"})})}),Q},[v]);x.useEffect(()=>{i&&Se.length>=0&&i(Se)},[Se,i]);const ne=x.useMemo(()=>V.map(Q=>({email:(Q.email||"").toLowerCase(),participantType:Q.role==="Initiator"?"INITIATOR":Q.role==="Approver"?"APPROVER":Q.role==="Spectator"?"SPECTATOR":"PARTICIPANT",name:Q.name})),[V]),de=Q=>{if(!Q)return"Participant";switch(Q.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return Q.charAt(0).toUpperCase()+Q.slice(1).toLowerCase()}},le=()=>{var Q;(Q=O.current)==null||Q.scrollIntoView({behavior:"smooth"})};x.useEffect(()=>{le()},[v]);const fe=Q=>{switch(Q.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return Q.charAt(0).toUpperCase()+Q.slice(1).toLowerCase()}};x.useEffect(()=>{z.current||u&&(async()=>{try{const Q=await Ts(u),ge=Array.isArray(Q==null?void 0:Q.participants)?Q.participants:[];if(ge.length===0)return;const X=ge.map(ke=>{const Ge=ke.participantType||ke.participant_type||"participant",Fe=ke.userId||ke.user_id||"";return{name:ke.userName||ke.user_name||ke.user_email||ke.userEmail||"User",avatar:(ke.userName||ke.user_name||ke.user_email||"U").toString().split(" ").map(Xe=>Xe[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:fe(Ge.toString()),status:"offline",email:ke.userEmail||ke.user_email||"",permissions:["read","write","mention"],userId:Fe}});z.current=!0,ee(X);let Ae=0;const Te=3,$e=()=>{Z.current&&Z.current.connected?(Z.current.emit("request:online-users",{requestId:u}),Ae++,Ae<Te&&setTimeout($e,500)):(Ae++,Ae<Te&&setTimeout($e,200))};setTimeout($e,100)}catch(Q){console.error("[WorkNoteChat] ❌ Failed to load participants:",Q)}})()},[u]),x.useEffect(()=>()=>{u&&(z.current=!1)},[u]),x.useEffect(()=>{const Q=localStorage.getItem("userData");if(Q)try{const ge=JSON.parse(Q),X=(ge==null?void 0:ge.id)||(ge==null?void 0:ge.userId)||(ge==null?void 0:ge.user_id)||null;R(X)}catch(ge){console.error("[WorkNoteChat] Failed to parse userData:",ge)}},[]),x.useEffect(()=>{(async()=>{try{const ge=await ar("DOCUMENT_POLICY"),X={};ge.forEach(ke=>{X[ke.configKey]=ke.configValue});const Ae=parseInt(X.MAX_FILE_SIZE_MB||"10"),$e=(X.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(ke=>ke.trim().toLowerCase());W({maxFileSizeMB:Ae,allowedFileTypes:$e})}catch(ge){console.error("Failed to load document policy:",ge)}})()},[]),x.useEffect(()=>{if(!P)return;let Q=u;return(async()=>{var ge;try{const X=await Ts(u);(ge=X==null?void 0:X.workflow)!=null&&ge.requestId&&(Q=X.workflow.requestId)}catch{}try{const X=fr();r?ee(et=>et.map(ht=>ht.userId===P?{...ht,status:"online"}:ht)):(wl(X,Q,P),ee(et=>et.map(ht=>ht.userId===P?{...ht,status:"online"}:ht)));const Ae=et=>{const Je=(et==null?void 0:et.note)||et;if(!Je)return;const ht=Je.noteId||Je.id;w(zt=>{if(zt.some(ft=>ft.id===ht))return zt;const Dt=Je.userName||Je.user_name||"User",Us=Je.userRole||Je.user_role,Xs=de(Us),ua=Je.userId||Je.user_id,ha={id:ht||String(Date.now()),user:{name:Dt,avatar:Dt.split(" ").map(ft=>ft[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Xs},content:Je.message||"",timestamp:Je.createdAt||new Date().toISOString(),isCurrentUser:ua===P,attachments:Array.isArray(Je.attachments)?Je.attachments.map(ft=>({attachmentId:ft.attachmentId||ft.attachment_id,name:ft.fileName||ft.file_name||ft.name,fileName:ft.fileName||ft.file_name||ft.name,url:ft.storageUrl||ft.storage_url||ft.url||"#",type:ft.fileType||ft.file_type||ft.type||"file",fileType:ft.fileType||ft.file_type||ft.type||"file",fileSize:ft.fileSize||ft.file_size})):void 0};return[...zt,ha]})},Te=et=>{ee(Je=>Je.length===0||!Je.find(Dt=>Dt.userId===et.userId)?Je:Je.map(Dt=>Dt.userId===et.userId?{...Dt,status:"online"}:Dt))},$e=et=>{et.userId!==P&&ee(Je=>Je.length===0||!Je.find(Dt=>Dt.userId===et.userId)?Je:Je.map(Dt=>Dt.userId===et.userId?{...Dt,status:"offline"}:Dt))},ke=et=>{ee(Je=>Je.length===0?Je:Je.map(zt=>{const Dt=zt.userId||"";if(Dt===P)return{...zt,status:"online"};const Xs=et.userIds.includes(Dt);return{...zt,status:Xs?"online":"offline"}}))},Ge=()=>{ee(et=>et.map(ht=>ht.userId===P?{...ht,status:"online"}:ht)),r||wl(X,Q,P),z.current&&(X.emit("request:online-users",{requestId:Q}),setTimeout(()=>X.emit("request:online-users",{requestId:Q}),300),setTimeout(()=>X.emit("request:online-users",{requestId:Q}),800))},Fe=et=>{console.error("[WorkNoteChat] ❌ Socket error:",et)},Xe=et=>{console.warn("[WorkNoteChat] ⚠️ Socket disconnected:",et),ee(Je=>Je.map(ht=>ht.userId===P?ht:{...ht,status:"offline"}))},ls=et=>{et.includes("presence")||et.includes("worknote")||et.includes("request")};X.on("connect",Ge),X.on("disconnect",Xe),X.on("error",Fe),X.on("worknote:new",Ae),X.on("presence:join",Te),X.on("presence:leave",$e),X.on("presence:online",ke),X.onAny(ls),Z.current=X,X.connected&&z.current&&(X.emit("request:online-users",{requestId:Q}),setTimeout(()=>{X.emit("request:online-users",{requestId:Q})},300),setTimeout(()=>{X.emit("request:online-users",{requestId:Q})},800),setTimeout(()=>{X.emit("request:online-users",{requestId:Q})},1500));const Lt=()=>{X.off("connect",Ge),X.off("disconnect",Xe),X.off("error",Fe),X.off("worknote:new",Ae),X.off("presence:join",Te),X.off("presence:leave",$e),X.off("presence:online",ke),X.offAny(ls),r||Yu(X,Q),Z.current=null};window.__wn_cleanup=Lt}catch{}})(),()=>{var ge;try{(ge=window.__wn_cleanup)==null||ge.call(window)}catch{}}},[u,P,r]);const st=async()=>{if(h.trim()||S.length>0){const Q=is(h),ge=Q.map(Te=>{const $e=V.find(ke=>ke.name.toLowerCase().includes(Te.toLowerCase()));return $e==null?void 0:$e.userId}).filter(Boolean),X=S.map(Te=>({name:Te.name,url:URL.createObjectURL(Te),type:Te.type.split("/")[1]||"file"})),Ae={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:Q,isHighPriority:h.includes("!important")||h.includes("urgent"),attachments:X.length>0?X:void 0,isCurrentUser:!0};if(a)try{await a(h,S)}catch{}else try{await eh(u,{message:h,mentions:ge},S);const Te=await xr(u),$e=Array.isArray(Te)?Te.map(ke=>{const Ge=ke.userId||ke.user_id;return{id:ke.noteId||ke.id||String(Math.random()),user:{name:ke.userName||"User",avatar:(ke.userName||"U").slice(0,2).toUpperCase(),role:ke.userRole||"Participant"},content:ke.message||"",timestamp:ke.createdAt||new Date().toISOString(),isCurrentUser:Ge===P,attachments:Array.isArray(ke.attachments)?ke.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}}):[];w($e)}catch{w(Te=>[...Te,Ae])}g(""),E([])}};x.useEffect(()=>{if(s&&Array.isArray(s))try{const ge=s.filter(X=>(X.type||"").toLowerCase()!=="sla_warning").map(X=>{var Te;if(X.type||X.activityType||X.isSystem)return{id:X.id||`activity-${X.timestamp||Date.now()}-${Math.random()}`,user:{name:"System",avatar:"SY",role:"System"},content:X.details||X.action||X.content||"",timestamp:X.timestamp||X.createdAt||X.created_at||new Date().toISOString(),isSystem:!0,isCurrentUser:!1};{const $e=X.userName||X.user_name||((Te=X.user)==null?void 0:Te.name)||"User",ke=X.userRole||X.user_role,Ge=de(ke),Fe=X.userId||X.user_id;return{id:X.noteId||X.note_id||X.id||String(Math.random()),user:{name:$e,avatar:$e.split(" ").map(Xe=>Xe[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ge},content:X.message||X.content||"",timestamp:X.createdAt||X.created_at||X.timestamp||new Date().toISOString(),isSystem:!1,attachments:Array.isArray(X.attachments)?X.attachments.map(Xe=>({attachmentId:Xe.attachmentId||Xe.attachment_id,name:Xe.fileName||Xe.file_name||Xe.name,fileName:Xe.fileName||Xe.file_name||Xe.name,url:Xe.storageUrl||Xe.storage_url||Xe.url||"#",type:Xe.fileType||Xe.file_type||Xe.type||"file",fileType:Xe.fileType||Xe.file_type||Xe.type||"file",fileSize:Xe.fileSize||Xe.file_size})):void 0,isCurrentUser:Fe===P}}}).sort((X,Ae)=>new Date(X.timestamp).getTime()-new Date(Ae.timestamp).getTime());w(ge)}catch(Q){console.error("[WorkNoteChat] Error mapping messages:",Q)}else(async()=>{try{const Q=await xr(u),ge=Array.isArray(Q)?Q.map(X=>{const Ae=X.userName||X.user_name||"User",Te=X.userRole||X.user_role,$e=de(Te),ke=X.userId||X.user_id;return{id:X.noteId||X.note_id||X.id||String(Math.random()),user:{name:Ae,avatar:Ae.split(" ").map(Ge=>Ge[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:$e},content:X.message||"",timestamp:X.createdAt||X.created_at||new Date().toISOString(),attachments:Array.isArray(X.attachments)?X.attachments.map(Ge=>({attachmentId:Ge.attachmentId||Ge.attachment_id,name:Ge.fileName||Ge.file_name||Ge.name,fileName:Ge.fileName||Ge.file_name||Ge.name,url:Ge.storageUrl||Ge.storage_url||Ge.url||"#",type:Ge.fileType||Ge.file_type||Ge.type||"file",fileType:Ge.fileType||Ge.file_type||Ge.type||"file",fileSize:Ge.fileSize||Ge.file_size})):void 0,isCurrentUser:ke===P}}):[];w(ge)}catch(Q){console.error("[WorkNoteChat] Error loading work notes:",Q)}})()},[s,u,V]);const ae=Q=>{const ge=$.maxFileSizeMB*1024*1024;if(Q.size>ge)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${$.maxFileSizeMB}MB. Current size: ${(Q.size/(1024*1024)).toFixed(2)}MB`};const X=Q.name.toLowerCase(),Ae=X.substring(X.lastIndexOf(".")+1);return $.allowedFileTypes.includes(Ae)?{valid:!0}:{valid:!1,reason:`File type "${Ae}" is not allowed. Allowed types: ${$.allowedFileTypes.join(", ")}`}},je=Q=>{if(!Q.target.files||Q.target.files.length===0)return;const ge=Array.from(Q.target.files),X=[],Ae=[];ge.forEach(Te=>{const $e=ae(Te);$e.valid?Ae.push(Te):X.push({fileName:Te.name,reason:$e.reason||"Unknown validation error"})}),X.length>0&&G({open:!0,errors:X}),Ae.length>0&&(E(Te=>[...Te,...Ae]),Ae.length<ge.length?q.warning(`${Ae.length} of ${ge.length} file(s) were added. ${X.length} file(s) were rejected.`):q.success(`${Ae.length} file(s) added successfully`)),Q.target&&(Q.target.value="")},gt=Q=>{E(ge=>ge.filter((X,Ae)=>Ae!==Q)),L.current&&(L.current.value="")},be=Q=>{g(ge=>ge+Q),j(!1)},Oe=()=>{var Q;(Q=L.current)==null||Q.click()},ut=async Q=>{var ge,X;try{await sh(u,Q);const Ae=await Ts(u),Te=Array.isArray(Ae==null?void 0:Ae.participants)?Ae.participants:[];if(Te.length){const $e=Te.map(ke=>{const Ge=ke.participantType||ke.participant_type||"participant",Fe=ke.userId||ke.user_id||"",Xe=ke.userName||ke.user_name||ke.userEmail||ke.user_email||"User",ls=ke.userEmail||ke.user_email||"",Lt=Xe.split(" ").map(et=>et[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:Xe,avatar:Lt,role:fe(Ge),status:"offline",email:ls,lastSeen:void 0,permissions:["read"],userId:Fe}});ee($e),Z.current&&Z.current.connected&&Z.current.emit("request:online-users",{requestId:u})}K(!1),M({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),A(!0)}catch(Ae){throw console.error("Failed to add spectator:",Ae),M({success:!1,title:"Failed to Add Spectator",message:((X=(ge=Ae==null?void 0:Ae.response)==null?void 0:ge.data)==null?void 0:X.error)||"Failed to add spectator. Please try again."}),A(!0),Ae}},wt=async(Q,ge,X)=>{var Ae,Te;if(d)await d(Q,ge,X),U(!1);else try{await th(u,Q,ge,X);const $e=await Ts(u),ke=Array.isArray($e==null?void 0:$e.participants)?$e.participants:[];if(ke.length){const Ge=ke.map(Fe=>{const Xe=Fe.participantType||Fe.participant_type||"participant",ls=Fe.userId||Fe.user_id||"",Lt=Fe.userName||Fe.user_name||Fe.userEmail||Fe.user_email||"User",et=Fe.userEmail||Fe.user_email||"",Je=Lt.split(" ").map(ht=>ht[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:Lt,avatar:Je,role:fe(Xe),status:"offline",email:et,lastSeen:void 0,permissions:["read"],userId:ls}});ee(Ge),Z.current&&Z.current.connected&&Z.current.emit("request:online-users",{requestId:u})}U(!1),M({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${X} with ${ge}h TAT`}),A(!0)}catch($e){throw console.error("Failed to add approver:",$e),M({success:!1,title:"Failed to Add Approver",message:((Te=(Ae=$e==null?void 0:$e.response)==null?void 0:Ae.data)==null?void 0:Te.error)||"Failed to add approver. Please try again."}),A(!0),$e}},dt=["😊","😂","🤣","😁","😃","😄","😅","😆","😉","😌","😍","🥰","😘","😗","😙","😚","🙂","🤗","🤩","🤔","🤨","😐","😑","😶","🙄","😏","😒","🙃","😬","🤐","😴","😪","😵","🤯","🤪","😜","😝","😛","🤤","😋","😎","🤓","🧐","😕","😟","🙁","☹️","😮","😯","😲","😳","🥺","😦","😧","😨","😰","😥","😢","😭","😱","😖","😣","😞","😓","😩","😫","🥱","😤","😡","😠","🤬","😈","👿","💀","☠️","💩","🤡","👹","👺","👻","👋","🤚","🖐️","✋","🖖","👌","🤌","🤏","✌️","🤞","🤟","🤘","🤙","👈","👉","👆","🖕","👇","☝️","👍","👎","✊","👊","🤛","🤜","👏","🙌","👐","🤲","🤝","🙏","💪","🦾","🦿","🦵","🦶","👂","🦻","👃","🧠","❤️","🧡","💛","💚","💙","💜","🖤","🤍","🤎","💔","❣️","💕","💞","💓","💗","💖","💘","💝","💟","❤️🔥","💼","📊","📈","📉","💻","⌨️","🖥️","🖨️","🖱️","💾","💿","📱","☎️","📞","📟","📠","📧","✉️","📨","📩","📮","📪","📫","📬","📭","📄","📃","📑","📝","✏️","✒️","🖊️","🖋️","📏","📐","📌","📍","🗂️","📁","📂","✅","✔️","☑️","🎯","🎖️","🏆","🥇","🥈","🥉","⭐","🌟","✨","💫","🔥","💥","⚡","💯","🎉","🎊","🎈","⚠️","🚫","❌","⛔","🚷","🚯","🚱","🚳","🔞","📵","❗","❓","❕","❔","‼️","⁉️","💢","💬","💭","🗯️","⏰","⏱️","⏲️","⏳","⌛","📅","📆","🗓️","📇","🕐","🕑","🕒","🕓","🕔","🕕","🕖","🕗","🕘","🕙","🕚","🚀","🎯","🎲","🎰","🧩","🔍","🔎","🔑","🗝️","🔒","🔓","🔐","🔏","🔔","🔕","📣","📢","💡","🔦","🏮","➕","➖","✖️","➗","♾️","‼️","⁉️","❓","❔","❕","🔄","🔃","🔂","▶️","⏸️","⏯️","⏹️","⏺️","⏭️","⏮️","⏩","⏪","⏫","⏬","◀️","🔼","🔽","➡️","⬅️","⬆️","⬇️","↗️","↘️","↙️","↖️","↕️","↔️","↪️","↩️","⤴️"],is=Q=>{const ge=/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,X=[];let Ae;for(;(Ae=ge.exec(Q))!==null;)if(Ae[1]){const Te=Ae.index+Ae[0].length,$e=Q.slice(Te),ke=Q[Te];($e.startsWith("@")||!ke||/\s|[.,!?;:]|@/.test(ke))&&X.push(Ae[1].trim())}return X},Bs=Q=>{Q.key==="Enter"&&!Q.shiftKey&&(Q.preventDefault(),st())},ma=(Q,ge)=>{w(X=>X.map(Ae=>{if(Ae.id===Q){const Te=Ae.reactions||[],$e=Te.find(ke=>ke.emoji===ge);if($e)if($e.users.includes("You")){if($e.users=$e.users.filter(ke=>ke!=="You"),$e.users.length===0)return{...Ae,reactions:Te.filter(ke=>ke.emoji!==ge)}}else $e.users.push("You");else Te.push({emoji:ge,users:["You"]});return{...Ae,reactions:Te}}return Ae}))};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(Os,{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:H.title}),e.jsx(ie,{variant:"outline",className:"text-xs shrink-0",children:t})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:e.jsxs("div",{className:"flex -space-x-2",children:[oe.slice(0,3).map((Q,ge)=>e.jsx(Qt,{className:"h-8 w-8 ring-2 ring-white shadow-sm",children:e.jsx(qt,{className:"bg-blue-500 text-white text-xs font-semibold",children:Q.avatar})},ge)),oe.length>3&&e.jsxs("div",{className:"h-8 w-8 rounded-full bg-gray-100 ring-2 ring-white flex items-center justify-center text-xs font-medium text-gray-600",children:["+",oe.length-3]})]})}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>C(!N),className:"lg:hidden",children:e.jsx(Mt,{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($s,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Re,{placeholder:"Search messages...",value:p,onChange:Q=>y(Q.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:[pe.map(Q=>{const ge=Q.isCurrentUser||!1;return e.jsxs("div",{className:`flex gap-2 sm:gap-3 lg:gap-4 ${Q.isSystem?"justify-center":ge?"justify-end":""}`,children:[!Q.isSystem&&!ge&&e.jsx(Qt,{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(qt,{className:`text-white font-semibold text-xs sm:text-sm ${Q.user.role==="Initiator"?"bg-green-600":Q.user.role==="Current User"?"bg-blue-500":Q.user.role==="System"?"bg-gray-500":"bg-slate-600"}`,children:Q.user.avatar})}),e.jsx("div",{className:`${ge?"max-w-[70%]":"flex-1"} min-w-0 ${Q.isSystem?"text-center max-w-xs sm:max-w-md mx-auto":""}`,children:Q.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(ts,{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:Q.content}),e.jsx("span",{className:"text-xs text-gray-500 hidden sm:inline",children:es(Q.timestamp)})]}):e.jsxs("div",{children:[e.jsxs("div",{className:`flex items-center gap-2 sm:gap-3 mb-1 sm:mb-2 flex-wrap ${ge?"justify-end":""}`,children:[e.jsxs("span",{className:"font-semibold text-gray-900 text-sm sm:text-base truncate",children:[Q.user.name," ",ge&&e.jsx("span",{className:"text-xs text-gray-500 font-normal",children:"(you)"})]}),e.jsx(ie,{variant:"outline",className:"text-xs flex-shrink-0",children:Q.user.role}),e.jsxs("span",{className:"text-xs text-gray-500 flex items-center gap-1 flex-shrink-0",children:[e.jsx(Ze,{className:"w-3 h-3"}),es(Q.timestamp)]}),Q.isHighPriority&&e.jsxs(ie,{variant:"destructive",className:"text-xs flex-shrink-0",children:[e.jsx(Lf,{className:"w-3 h-3 mr-1"}),"Priority"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 sm:p-4 shadow-sm ${ge?"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:h2(Q.content)}}),Q.attachments&&Q.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:Q.attachments.map((X,Ae)=>{const Te=X.fileSize||X.file_size,$e=X.fileName||X.file_name||X.name,ke=X.fileType||X.file_type||X.type||"",Ge=X.attachmentId||X.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(Vm,{type:ke})}),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:$e}),Te&&e.jsx("p",{className:"text-xs text-gray-500",children:p2(Te)})]}),Ge&&(()=>{const Fe=(ke||"").toLowerCase();return Fe.includes("image")||Fe.includes("pdf")||Fe.includes("jpg")||Fe.includes("jpeg")||Fe.includes("png")||Fe.includes("gif")})()&&e.jsx(I,{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:Fe=>{Fe.preventDefault(),Fe.stopPropagation();const Xe=Qb(Ge);T({fileName:$e,fileType:ke,fileUrl:Xe,fileSize:Te,attachmentId:Ge})},title:"Preview file",children:e.jsx(bt,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),e.jsx(I,{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 Fe=>{if(Fe.preventDefault(),Fe.stopPropagation(),!Ge){q.error("Cannot download: Attachment ID missing");return}try{await yd(Ge)}catch{q.error("Failed to download file")}},title:"Download file",children:e.jsx(Nt,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]},Ae)})})}),Q.reactions&&Q.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:[Q.reactions.map((X,Ae)=>e.jsxs("button",{onClick:()=>ma(Q.id,X.emoji),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs sm:text-sm transition-colors flex-shrink-0 ${X.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:X.emoji}),e.jsx("span",{className:"text-xs font-medium",children:X.users.length})]},Ae)),e.jsx(I,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-7 sm:w-7 p-0 flex-shrink-0",onClick:()=>j(!b),children:e.jsx(Ls,{className:"w-2 h-2 sm:w-3 sm:h-3"})})]})]})]})}),!Q.isSystem&&ge&&e.jsx(Qt,{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(qt,{className:"bg-blue-500 text-white font-semibold text-xs sm:text-sm",children:Q.user.avatar})})]},Q.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:je,className:"hidden",multiple:!0,accept:$.allowedFileTypes.map(Q=>`.${Q}`).join(",")}),S.length>0&&e.jsx("div",{className:"mb-3 space-y-2 max-h-32 overflow-y-auto pr-2",children:S.map((Q,ge)=>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(Vm,{type:Q.type.split("/")[1]||"file"})}),e.jsx("span",{className:"text-sm text-gray-700 flex-1 truncate min-w-0",children:Q.name}),e.jsxs("span",{className:"text-xs text-gray-500 flex-shrink-0",children:[(Q.size/1024).toFixed(1)," KB"]}),e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>gt(ge),className:"h-6 w-6 p-0 hover:bg-red-100 flex-shrink-0",children:e.jsx(pt,{className:"h-3 w-3 text-red-600"})})]},ge))}),e.jsxs("div",{className:"relative mb-2",children:[(()=>{const Q=h.lastIndexOf("@"),ge=Q>=0;if(!ge)return null;const X=h.slice(Q+1),Ae=X.trim(),Te=X.endsWith(" "),$e=Ae.length>0,ke=Ae.includes(" ")&&!Te,Ge=Te&&$e;if(!(ge&&X.length<=20&&!ke&&!Ge))return null;const Xe=Ae.toLowerCase(),ls=V.filter(Lt=>Lt.userId===P?!1:Xe?Lt.name.toLowerCase().includes(Xe):!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((Lt,et)=>e.jsxs("button",{type:"button",onClick:Je=>{Je.preventDefault(),Je.stopPropagation();const ht=h.lastIndexOf("@"),zt=h.slice(0,ht);g(zt+"@"+Lt.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(Qt,{className:"h-10 w-10",children:e.jsx(qt,{className:`text-white text-sm font-semibold ${Lt.role==="Initiator"?"bg-green-600":Lt.role==="Approver"?"bg-purple-600":"bg-blue-500"}`,children:Lt.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:Lt.name}),e.jsx("p",{className:"text-xs text-gray-600",children:Lt.role})]})]},et)):e.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:Xe?`No participants found matching "${Xe}"`:"No other participants available"})})]})})(),e.jsx(ps,{placeholder:"Type your message... Use @username to mention someone",value:h,onChange:Q=>g(Q.target.value),onKeyPress:Bs,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}),b&&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(I,{variant:"ghost",size:"sm",onClick:()=>j(!1),className:"h-6 w-6 p-0",children:e.jsx(pt,{className:"h-3 w-3"})})]}),e.jsx("div",{className:"grid grid-cols-8 sm:grid-cols-10 gap-1",children:dt.map((Q,ge)=>e.jsx("button",{onClick:()=>be(Q),className:"text-xl sm:text-2xl hover:bg-gray-100 rounded p-1 transition-colors flex items-center justify-center",title:Q,children:Q},ge))})]})]}),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(I,{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:Oe,title:"Attach file",children:e.jsx(ii,{className:"h-4 w-4"})}),e.jsx(I,{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:()=>j(!b),title:"Add emoji",children:e.jsx(Of,{className:"h-4 w-4"})}),e.jsx(I,{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:()=>g(Q=>Q+"@"),title:"Mention someone",children:e.jsx(mi,{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(I,{onClick:st,disabled:!h.trim()&&S.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(wu,{className:"h-4 w-4 sm:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Send"})]})]})]})]})})]}),N&&e.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 z-40 lg:hidden",onClick:()=>C(!1)}),e.jsxs("div",{className:`
|
||
w-72 sm:w-80 bg-white border-l border-gray-200 flex flex-col
|
||
lg:relative lg:translate-x-0 lg:shadow-none
|
||
${N?"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(I,{variant:"ghost",size:"sm",onClick:()=>C(!1),className:"lg:hidden h-8 w-8 p-0",children:e.jsx(pt,{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((Q,ge)=>{const X=Q.userId===P;return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Qt,{className:"h-9 w-9 sm:h-10 sm:w-10",children:e.jsx(qt,{className:`text-white font-semibold text-sm ${Q.role==="Initiator"?"bg-green-600":X?"bg-blue-500":"bg-slate-600"}`,children:Q.avatar})}),e.jsx("div",{className:`absolute -bottom-1 -right-1 w-3 h-3 rounded-full border-2 border-white ${m2(Q.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:[Q.name," ",X&&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:Q.role}),e.jsx("span",{className:"text-xs text-gray-400",children:"•"}),e.jsx("p",{className:"text-xs text-gray-500",children:u2(Q.status)})]}),Q.lastSeen&&Q.status==="offline"&&e.jsx("p",{className:"text-xs text-gray-400",children:Q.lastSeen})]})]},ge)})})]}),!Pe&&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:[l&&e.jsxs(I,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>U(!0),children:[e.jsx(di,{className:"h-4 w-4"}),"Add Approver"]}),e.jsxs(I,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>K(!0),children:[e.jsx(bt,{className:"h-4 w-4"}),"Add Spectator"]})]})]})]})]}),f&&e.jsx(Zo,{fileName:f.fileName,fileType:f.fileType,fileUrl:f.fileUrl,fileSize:f.fileSize,attachmentId:f.attachmentId,onDownload:yd,open:!!f,onClose:()=>T(null)}),!Pe&&e.jsx(qp,{open:F,onClose:()=>K(!1),onConfirm:ut,requestIdDisplay:u,requestTitle:H.title,existingParticipants:ne}),!Pe&&l&&e.jsx(ex,{open:B,onClose:()=>U(!1),onConfirm:wt,requestIdDisplay:u,requestTitle:H.title,existingParticipants:ne,currentLevels:c}),e.jsx(ot,{open:_.open,onOpenChange:Q=>G(ge=>({...ge,open:Q})),children:e.jsxs(nt,{className:"sm:max-w-lg",children:[e.jsxs(ct,{children:[e.jsxs(it,{className:"flex items-center gap-2",children:[e.jsx(We,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(_t,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-gray-700",children:"The following file(s) could not be uploaded due to policy violations:"}),e.jsx("div",{className:"space-y-2 max-h-60 overflow-y-auto",children:_.errors.map((Q,ge)=>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:Q.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:Q.reason})]},ge))}),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: ",$.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",$.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(At,{children:e.jsx(I,{onClick:()=>G({open:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(Qp,{open:D,onClose:()=>A(!1),success:k.success,title:k.title,message:k.message})]})}function x2({requestId:t,requestTitle:s,mergedMessages:a,setWorkNoteAttachments:r,isInitiator:n,isSpectator:i,currentLevels:l,onAddApprover:o}){return e.jsx("div",{className:"h-[calc(100vh-300px)] min-h-[600px]",children:e.jsx(tx,{requestId:t,requestTitle:s,skipSocketJoin:!0,messages:a,onAttachmentsExtracted:r,isInitiator:n,isSpectator:i,currentLevels:l,onAddApprover:o})})}function g2({summary:t,loading:s,onShare:a,isInitiator:r}){const n=o=>{const c=o.toLowerCase();return c==="approved"?e.jsx(Ce,{className:"h-4 w-4 text-green-600"}):c==="rejected"?e.jsx(xt,{className:"h-4 w-4 text-red-600"}):c==="pending"||c==="in progress"?e.jsx(Ze,{className:"h-4 w-4 text-orange-600"}):e.jsx(Le,{className:"h-4 w-4 text-gray-600"})},i=o=>{const c=o.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"},l=(o,c)=>o&&o.trim()&&o.trim().toUpperCase()!=="N/A"?o: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(Qe,{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(I,{variant:"outline",size:"sm",onClick:a,className:"flex items-center gap-2",children:[e.jsx(vr,{className:"w-4 h-4"}),e.jsx("span",{children:"Share"})]}):e.jsxs(ie,{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(Ws,{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:l(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:Ie(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((o,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:o.levelName||`Approver ${o.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:o.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:l(o.designation,o.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(o.status),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:o.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:Ie(new Date(o.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:o.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:l(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(ie,{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(Ws,{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(Le,{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 f2({sla:t,requestStatus:s,isPaused:a=!1,testId:r="sla-progress"}){if(!(t&&(t.percentageUsed!==void 0||t.elapsedHours!==void 0))||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(on,{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(xt,{className:"h-4 w-4 text-red-600"}):e.jsx(Ze,{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 i=t.percentageUsed!==void 0?t.percentageUsed:0,l=t.status||"on_track",c=a?{badge:"bg-gray-500 text-white",progress:"bg-gray-500",text:"text-gray-600",icon:"text-gray-500"}:i>=100?{badge:"bg-red-600 text-white animate-pulse",progress:"bg-red-600",text:"text-red-600",icon:"text-blue-600"}:i>=75?{badge:"bg-orange-500 text-white",progress:"bg-orange-500",text:"text-orange-600",icon:"text-blue-600"}:i>=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"},d=l==="on_track"||l==="normal"?"normal":l;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(on,{className:`h-4 w-4 ${c.icon}`}):e.jsx(Ze,{className:`h-4 w-4 ${c.icon}`}),e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:a?"SLA Progress (Paused)":"SLA Progress"})]}),e.jsxs(ie,{className:`text-xs ${c.badge}`,"data-testid":`${r}-badge`,children:[i,"% elapsed ",a&&"(frozen)"]})]}),e.jsx(Qs,{value:i,className:"h-3 mb-2",indicatorClassName:c.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:[It(t.elapsedHours||0)," elapsed"]}),e.jsxs("span",{className:`font-semibold ${d==="breached"||d==="critical"?c.text:"text-gray-700"}`,"data-testid":`${r}-remaining`,children:[It(t.remainingHours||0)," remaining"]})]}),t.deadline&&e.jsxs("p",{className:"text-xs text-gray-500","data-testid":`${r}-deadline`,children:["Due: ",qs(t.deadline,!0)," • ",i,"% elapsed"]}),d==="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(hs,{className:"h-3.5 w-3.5"}),"Approaching Deadline"]}),d==="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(Zn,{className:"h-3.5 w-3.5"}),"URGENT - Deadline Passed"]})]})}function y2({request:t,refreshing:s,onBack:a,onRefresh:r,onShareSummary:n,isInitiator:i,slaData:l,isPaused:o=!1}){var m;const c=l2((t==null?void 0:t.priority)||"standard"),d=o2((t==null?void 0:t.status)||"pending");return e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border border-gray-300 mb-4 sm:mb-6","data-testid":"request-detail-header",children:[e.jsxs("div",{className:"p-3 sm:p-4 md:p-6 border-b border-gray-300",children:[e.jsxs("div",{className:"flex items-start sm:items-center justify-between gap-2 sm:gap-4",children:[e.jsxs("div",{className:"flex items-start sm:items-center gap-2 sm:gap-4 min-w-0 flex-1",children:[e.jsx(I,{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(Ys,{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(Le,{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(ie,{className:`${c.color} rounded-full px-2 sm:px-3 text-xs capitalize shrink-0`,variant:"outline","data-testid":"priority-badge",children:c.label}),e.jsx(ie,{className:`${d.color} rounded-full px-2 sm:px-3 text-xs capitalize shrink-0`,variant:"outline","data-testid":"status-badge",children:d.label}),(()=>{const u=(t==null?void 0:t.workflowType)||(t==null?void 0:t.workflow_type),h=(t==null?void 0:t.templateType)||(t==null?void 0:t.template_type),g=u==="CLAIM_MANAGEMENT"||h==="claim-management",p=g?"Claim Management":"Custom",y=g?"bg-blue-100 !text-blue-700 border-blue-200":"bg-purple-100 !text-purple-600 border-purple-200";return e.jsx(ie,{className:`${y} rounded-full px-2 sm:px-3 text-xs shrink-0`,variant:"outline","data-testid":"template-type-badge",children:p})})()]})]})]})]}),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(I,{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(vr,{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(I,{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(ns,{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})})]}),l!==void 0&&e.jsx("div",{className:`px-3 sm:px-4 md:px-6 py-3 sm:py-4 border-b border-gray-200 ${o?"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(f2,{sla:l,requestStatus:t.status,isPaused:o,testId:"request-sla"})})]})}async function Xo(t){return(await ye.get(`/summaries/${t}`)).data.data}async function b2(t,s){return(await ye.post(`/summaries/${t}/share`,{userIds:s})).data.data}async function v2(t={}){var n,i;const{page:s=1,limit:a=20}=t,r=await ye.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 sx(t){await ye.patch(`/summaries/shared/${t}/view`)}async function ax(t){var s;try{return(await ye.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 j2(t){return(await ye.get(`/summaries/${t}/recipients`)).data.data||[]}function N2({activityInfo:t,className:s,createdAt:a,updatedAt:r}){if(!t)return console.warn("[ActivityInformationCard] activityInfo is missing"),e.jsx(te,{className:s,children:e.jsx(se,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Activity information not available"})})});const n=l=>{const o=typeof l=="string"?parseFloat(l):l;return isNaN(o)?"N/A":`₹${o.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`},i=l=>{if(!l)return"N/A";try{return Ie(new Date(l),"MMM d, yyyy")}catch{return l}};return e.jsxs(te,{className:s,children:[e.jsx(me,{children:e.jsxs(he,{className:"flex items-center gap-2 text-base",children:[e.jsx(mt,{className:"w-5 h-5 text-blue-600"}),"Activity Information"]})}),e.jsxs(se,{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(so,{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:i(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(Pa,{className:"w-4 h-4 text-green-600"}),t.estimatedBudget?n(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(us,{className:"w-4 h-4 text-blue-600"}),n(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:[i(t.period.startDate)," - ",i(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((l,o)=>e.jsxs("div",{className:"flex justify-between items-center text-sm",children:[e.jsx("span",{className:"text-gray-700",children:l.description}),e.jsx("span",{className:"font-medium text-gray-900",children:n(l.amount)})]},o)),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:n(t.closedExpensesBreakdown.reduce((l,o)=>l+o.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("div",{className:"mt-2 bg-gray-50 p-3 rounded-lg border border-gray-200",children:e.jsx(Ws,{content:t.description||"",className:"text-sm"})})]}),(a||r)&&e.jsxs("div",{className:"grid grid-cols-2 gap-4 pt-4 border-t border-gray-300",children:[a&&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:es(a)})]}),r&&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:es(r)})]})]})]})]})}function w2({dealerInfo:t,className:s}){return t?!t.dealerCode&&!t.dealerName?(console.warn("[DealerInformationCard] Dealer info missing essential fields:",t),e.jsx(te,{className:s,children:e.jsx(se,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Dealer information incomplete"})})})):e.jsxs(te,{className:s,children:[e.jsx(me,{children:e.jsxs(he,{className:"flex items-center gap-2 text-base",children:[e.jsx(ui,{className:"w-5 h-5 text-purple-600"}),"Dealer Information"]})}),e.jsxs(se,{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(va,{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(li,{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(so,{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(te,{className:s,children:e.jsx(se,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Dealer information not available"})})}))}function C2({ioDetails:t,dmsDetails:s,claimAmount:a,estimatedBudgetBreakdown:r,closedExpensesBreakdown:n,visibility:i,onEditClaimAmount:l,className:o}){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 Ie(new Date(h),"MMM d, yyyy, h:mm a")}catch{return h||""}},m=h=>!h||h.length===0?0:h.reduce((g,p)=>g+(p.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(te,{className:`bg-gradient-to-br from-blue-50 to-purple-50 border-2 border-blue-200 ${o}`,children:[e.jsxs(me,{children:[e.jsxs(he,{className:"text-base flex items-center gap-2",children:[e.jsx(ts,{className:"w-4 h-4 text-blue-600"}),"Process Details"]}),e.jsx(De,{children:"Workflow reference numbers"})]}),e.jsxs(se,{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(us,{className:"w-4 h-4 text-blue-600"}),e.jsx(re,{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(ts,{className:"w-4 h-4 text-purple-600"}),e.jsx(re,{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(Pa,{className:"w-4 h-4 text-green-600"}),e.jsx(re,{className:"text-xs font-semibold text-green-900 uppercase tracking-wide",children:"Claim Amount"})]}),i.canEditClaimAmount&&l&&e.jsxs(I,{variant:"outline",size:"sm",onClick:l,className:"h-7 px-2 text-xs border-green-300 hover:bg-green-50",children:[e.jsx(Cu,{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(us,{className:"w-4 h-4 text-amber-600"}),e.jsx(re,{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,g)=>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)})]},g)),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(us,{className:"w-4 h-4 text-indigo-600"}),e.jsx(re,{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,g)=>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)})]},g)),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 S2({proposalDetails:t,className:s}){const r=t.estimatedBudgetTotal!==void 0&&t.estimatedBudgetTotal!==null?t.estimatedBudgetTotal:t.costBreakup&&t.costBreakup.length>0?t.costBreakup.reduce((c,d)=>{const m=d.amount||0;return c+(Number.isNaN(m)?0:m)},0):0,n=o=>o==null||Number.isNaN(o)?"₹0.00":`₹${o.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,i=o=>{if(!o)return"";try{return Ie(new Date(o),"MMM d, yyyy, h:mm a")}catch{return o||""}},l=o=>{if(!o)return"-";try{return Ie(new Date(o),"MMM d, yyyy")}catch{return o||"-"}};return e.jsxs(te,{className:s,children:[e.jsxs(me,{children:[e.jsxs(he,{className:"flex items-center gap-2 text-base",children:[e.jsx(us,{className:"w-5 h-5 text-green-600"}),"Proposal Details"]}),t.submittedOn&&e.jsxs(De,{children:["Submitted on ",i(t.submittedOn)]})]}),e.jsxs(se,{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((o,c)=>e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 text-sm text-gray-900",children:o.description}),e.jsx("td",{className:"px-4 py-3 text-sm text-gray-900 text-right font-medium",children:n(o.amount)})]},c)),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:n(r)})]})]})]})})]}),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(mt,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{className:"text-sm font-medium text-gray-900",children:["Expected completion by: ",l(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 A2({initiatorInfo:t,className:s}){const a=r=>r.split(" ").map(n=>n[0]).join("").toUpperCase().slice(0,2);return e.jsxs(te,{className:s,children:[e.jsx(me,{children:e.jsx(he,{className:"text-base",children:"Request Initiator"})}),e.jsx(se,{children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(Qt,{className:"h-14 w-14 ring-2 ring-white shadow-md",children:e.jsx(qt,{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(va,{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(li,{className:"w-4 h-4"}),e.jsx("span",{children:t.phone})]})]})]})]})})]})}function Si(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 rx(t,s){var a,r;try{if(!Si(t))return null;const n=t.claimDetails||{},i=t.proposalDetails||{},l=t.completionDetails||{},o=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,g=n.periodEndDate||n.period_end_date,p=n.activityName||n.activity_name||"",y=n.activityType||n.activity_type||"",b=n.location||"";console.debug("[claimDataMapper] Mapped activity fields:",{activityName:p,activityType:y,location:b,hasActivityName:!!p,hasActivityType:!!y,hasLocation:!!b});const j=c.proposalEstimatedBudget||c.proposal_estimated_budget||c.initialEstimatedBudget||c.initial_estimated_budget||n.estimatedBudget||n.estimated_budget,v=(c==null?void 0:c.closedExpenses)||(c==null?void 0:c.closed_expenses)||(l==null?void 0:l.totalClosedExpenses)||(l==null?void 0:l.total_closed_expenses)||(n==null?void 0:n.closedExpenses)||(n==null?void 0:n.closed_expenses),w=v!=null?Number(v):void 0,N=Array.isArray(u)&&u.length>0?u.map(F=>({description:F.description||F.itemDescription||"",amount:Number(F.amount)||0})):(l==null?void 0:l.closedExpenses)||(l==null?void 0:l.closed_expenses)||(l==null?void 0:l.closedExpensesBreakdown)||[],C={activityName:p,activityType:y,requestedDate:n.activityDate||n.activity_date||t.createdAt,location:b,period:h&&g?{startDate:h,endDate:g}:void 0,estimatedBudget:j,closedExpenses:w,closedExpensesBreakdown:N,description:t.description||""},S={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)||""};(!S.dealerCode||!S.dealerName)&&console.warn("[claimDataMapper] Dealer information is missing from claimDetails:",{hasClaimDetails:!!n,dealerCode:S.dealerCode,dealerName:S.dealerName,rawClaimDetails:n,availableKeys:n?Object.keys(n):[]});const E=(i==null?void 0:i.expectedCompletionDate)||(i==null?void 0:i.expected_completion_date),P=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:E,expectedCompletionDays:i.expectedCompletionDays||i.expected_completion_days,timelineForClosure:E,dealerComments:i.dealerComments||i.dealer_comments,submittedOn:i.submittedAt||i.submitted_at||i.submittedOn}:void 0,R={ioNumber:o.ioNumber||o.io_number||n.ioNumber||n.io_number,ioRemark:o.ioRemark||o.io_remark||"",availableBalance:o.ioAvailableBalance||o.io_available_balance||n.ioAvailableBalance||n.io_available_balance,blockedAmount:o.ioBlockedAmount||o.io_blocked_amount||n.ioBlockedAmount||n.io_blocked_amount,remainingBalance:o.ioRemainingBalance||o.io_remaining_balance||n.ioRemainingBalance||n.io_remaining_balance,organizedBy:((a=o.organizer)==null?void 0:a.displayName)||((r=o.organizer)==null?void 0:r.name)||o.organizedBy||"",organizedAt:o.organizedAt||o.organized_at||""},f={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},T={estimated:C.estimatedBudget||0,closed:C.closedExpenses||0};return{activityInfo:C,dealerInfo:S,proposalDetails:P,ioDetails:Object.keys(R).some(F=>R[F])?R:void 0,dmsDetails:Object.keys(f).some(F=>f[F])?f:void 0,claimAmount:T}}catch(n){return console.error("[claimDataMapper] Error mapping claim data:",n),null}}function nx(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 l=t.approvalLevels||[];return l.find(d=>{var m;return d.levelNumber===3&&(d.approverId===s||((m=d.approver)==null?void 0:m.userId)===s)})?"DEPARTMENT_LEAD":l.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 ix(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 T2({request:t,isInitiator:s,isSpectator:a,currentApprovalLevel:r,onAddApprover:n,onAddSpectator:i,onApprove:l,onReject:o,onPause:c,onResume:d,onRetrigger:m,summaryId:u,refreshTrigger:h,pausedByUserId:g,currentUserId:p,apiRequest:y,onEditClaimAmount:b}){var D,A,k,M,O;const{user:j}=Kt(),[v,w]=x.useState([]),[N,C]=x.useState(!1),[S,E]=x.useState(!1),P=(t==null?void 0:t.status)==="closed",R=((D=t==null?void 0:t.pauseInfo)==null?void 0:D.isPaused)||!1,f=g||((k=(A=t==null?void 0:t.pauseInfo)==null?void 0:A.pausedBy)==null?void 0:k.userId),T=p||(j==null?void 0:j.userId)||"",F=!R&&!P&&(r||s),K=R&&d&&(r||s),B=R&&s&&f&&f!==T&&m;x.useEffect(()=>{if(!R||!r||!(t!=null&&t.requestId)){E(!1);return}(async()=>{var Z;try{const W=(((Z=(await ka.list({page:1,limit:50,unreadOnly:!0})).data)==null?void 0:Z.notifications)||[]).some(_=>_.requestId===t.requestId&&_.notificationType==="pause_retrigger_request");E(W)}catch(z){console.error("Failed to check retrigger notifications:",z),E(!1)}})()},[R,r,t==null?void 0:t.requestId,h]),x.useEffect(()=>{(async()=>{if(!P||!u||!s){w([]);return}try{C(!0);const Z=await j2(u);w(Z)}catch(Z){console.error("Failed to fetch shared recipients:",Z),w([])}finally{C(!1)}})()},[P,u,s,h]);const U=x.useMemo(()=>{if(!y||!Si(y))return null;const L=rx(y);if(!L)return null;const Z=nx(y,T),z=ix(Z);return{claimRequest:L,visibility:z}},[y,T]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[!a&&t.status!=="closed"&&e.jsxs(te,{"data-testid":"quick-actions-card",children:[e.jsx(me,{className:"pb-2",children:e.jsx(he,{className:"text-sm sm:text-base",children:"Quick Actions"})}),e.jsxs(se,{className:"space-y-2",children:[s&&t.status!=="closed"&&e.jsxs(I,{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(di,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Add Approver"]}),t.status!=="closed"&&e.jsxs(I,{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(bt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Add Spectator"]}),F&&c&&e.jsxs(I,{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(Ra,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Pause Workflow"]}),K&&e.jsxs(I,{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(Yn,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Resume Workflow"]}),B&&e.jsxs(I,{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(We,{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&&!R&&e.jsxs(e.Fragment,{children:[e.jsxs(I,{className:"w-full bg-green-600 hover:bg-green-700 text-white h-9 sm:h-10 text-xs sm:text-sm",onClick:l,"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(I,{variant:"destructive",className:"w-full h-9 sm:h-10 text-xs sm:text-sm",onClick:o,"data-testid":"reject-request-button",children:[e.jsx(xt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Reject Request"]})]}),R&&e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-3 text-center",children:f===T?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:[S&&e.jsx(We,{className:"w-3.5 h-3.5"}),S?"Initiator has requested you to resume":"You paused this workflow"]}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:S?"Please review and resume if appropriate":'Click "Resume Workflow" to continue'})]}):r&&f!==T&&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:[e.jsx(We,{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&&f!==T?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&&f&&f!==T?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:B?'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(te,{"data-testid":"spectators-card",children:[e.jsx(me,{className:"pb-2",children:e.jsx(he,{className:"text-sm sm:text-base",children:"Spectators"})}),e.jsx(se,{className:"space-y-3",children:t.spectators&&t.spectators.length>0?t.spectators.map((L,Z)=>e.jsxs("div",{className:"flex items-center gap-3","data-testid":`spectator-${Z}`,children:[e.jsx(Qt,{className:"h-8 w-8",children:e.jsx(qt,{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})]})]},Z)):e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"No spectators added"})})})]}),P&&s&&e.jsxs(te,{"data-testid":"shared-recipients-card",children:[e.jsx(me,{className:"pb-2",children:e.jsxs(he,{className:"text-sm sm:text-base flex items-center gap-2",children:[e.jsx(vr,{className:"w-4 h-4"}),"Summary Shared With"]})}),e.jsx(se,{className:"space-y-3",children:N?e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Loading..."})}):v.length>0?v.map((L,Z)=>{const z=(L.displayName||"NA").split(" ").map($=>$[0]).join("").slice(0,2).toUpperCase();return e.jsxs("div",{className:"flex items-center gap-3","data-testid":`shared-recipient-${Z}`,children:[e.jsx(Qt,{className:"h-8 w-8",children:e.jsx(qt,{className:"bg-green-100 text-green-800 text-xs font-semibold",children:z})}),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||Z)}):e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Summary not shared yet"})})})]}),U&&e.jsx(C2,{ioDetails:U.claimRequest.ioDetails,dmsDetails:U.claimRequest.dmsDetails,claimAmount:{amount:U.claimRequest.claimAmount.closed||U.claimRequest.claimAmount.estimated||0},estimatedBudgetBreakdown:(M=U.claimRequest.proposalDetails)==null?void 0:M.costBreakup,closedExpensesBreakdown:(O=U.claimRequest.activityInfo)==null?void 0:O.closedExpensesBreakdown,visibility:U.visibility,onEditClaimAmount:b})]})}function k2({open:t,onClose:s,onConfirm:a,defaultDescription:r="",title:n="Approve Request",requestIdDisplay:i,requestTitle:l}){const[o,c]=x.useState(r),[d,m]=x.useState(!1),u=(o==null?void 0:o.length)||0,h=x.useMemo(()=>o.slice(0,500),[o]),g=async()=>{try{m(!0),await a(h),s()}finally{m(!1)}};return e.jsx(ot,{open:t,onOpenChange:p=>!p&&s(),children:e.jsxs(nt,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(ct,{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(it,{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:l||"—"})]}),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(ie,{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(ps,{value:h,onChange:p=>c(p.target.value),rows:5,placeholder:"Enter your approval comments and any conditions or notes...",className:"border-gray-300"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsx("span",{children:"Comments are required and will be visible to all participants"}),e.jsxs("span",{children:[Math.min(u,500),"/500"]})]})]}),e.jsxs("div",{className:"mt-4 border rounded-lg p-3 bg-green-50 border-green-200 text-green-900 flex items-start gap-2",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx(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(At,{className:"mt-4",children:[e.jsx(I,{variant:"outline",onClick:s,disabled:d,children:"Cancel"}),e.jsxs(I,{onClick:g,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 D2({open:t,onClose:s,onConfirm:a,defaultDescription:r="",title:n="Reject Request",requestIdDisplay:i,requestTitle:l}){const[o,c]=x.useState(r),[d,m]=x.useState(!1),u=(o==null?void 0:o.length)||0,h=x.useMemo(()=>o.slice(0,500),[o]),g=async()=>{if(!h.trim()){alert("Comments & remarks are required");return}try{m(!0),await a(h),s()}finally{m(!1)}};return e.jsx(ot,{open:t,onOpenChange:p=>!p&&s(),children:e.jsxs(nt,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(ct,{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(xt,{className:"w-7 h-7 text-red-600"})}),e.jsxs("div",{children:[e.jsx(it,{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:l||"—"})]}),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(ie,{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(ps,{value:h,onChange:p=>c(p.target.value),rows:5,placeholder:"Enter detailed reasons for rejection and any suggestions for improvement...",className:"border-gray-300"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsx("span",{children:"Comments are required and will be visible to all participants"}),e.jsxs("span",{children:[Math.min(u,500),"/500"]})]})]}),e.jsxs("div",{className:"mt-4 border rounded-lg p-3 bg-red-50 border-red-200 text-red-900 flex items-start gap-2",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx(We,{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(At,{className:"mt-4",children:[e.jsx(I,{variant:"outline",onClick:s,disabled:d,children:"Cancel"}),e.jsxs(I,{variant:"destructive",onClick:g,disabled:d,children:[e.jsx(xt,{className:"w-4 h-4 mr-2"}),d?"Rejecting...":"Reject Request"]})]})]})})}function R2({open:t,onClose:s,onConfirm:a,approverName:r,levelNumber:n,requestIdDisplay:i,requestTitle:l}){const[o,c]=x.useState(""),[d,m]=x.useState(!1),u=async()=>{if(o.trim())try{m(!0),await a(o.trim()),c(""),s()}catch(g){console.error("Failed to skip approver:",g)}finally{m(!1)}},h=()=>{d||(c(""),s())};return e.jsx(ot,{open:t,onOpenChange:h,children:e.jsxs(nt,{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(pt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(ct,{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(We,{className:"w-5 h-5 text-orange-600"})}),e.jsx(it,{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(We,{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||l)&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{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]}),l&&e.jsxs("p",{className:"text-sm text-gray-700",children:[e.jsx("span",{className:"font-medium",children:"Title:"})," ",l]})]})]}),(r||n)&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{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(re,{htmlFor:"skip-reason",className:"text-sm font-semibold text-gray-700",children:"Reason for Skipping *"}),e.jsx(ps,{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:o,onChange:g=>c(g.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(I,{type:"button",variant:"outline",onClick:h,className:"flex-1 h-11 border-gray-300",disabled:d,children:"Cancel"}),e.jsxs(I,{type:"button",onClick:u,className:"flex-1 h-11 bg-orange-600 hover:bg-orange-700 text-white",disabled:d||!o.trim(),children:[e.jsx(We,{className:"w-4 h-4 mr-2"}),d?"Skipping...":"Skip Approver"]})]})]})})}function P2({showApproveModal:t,showRejectModal:s,showAddApproverModal:a,showAddSpectatorModal:r,showSkipApproverModal:n,showActionStatusModal:i,previewDocument:l,documentError:o,request:c,skipApproverData:d,actionStatus:m,existingParticipants:u,currentLevels:h,setShowApproveModal:g,setShowRejectModal:p,setShowAddApproverModal:y,setShowAddSpectatorModal:b,setShowSkipApproverModal:j,setShowActionStatusModal:v,setPreviewDocument:w,setDocumentError:N,setSkipApproverData:C,setActionStatus:S,handleApproveConfirm:E,handleRejectConfirm:P,handleAddApprover:R,handleAddSpectator:f,handleSkipApprover:T,downloadDocument:F,documentPolicy:K}){return e.jsxs(e.Fragment,{children:[e.jsx(k2,{open:t,onClose:()=>g(!1),onConfirm:E,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(D2,{open:s,onClose:()=>p(!1),onConfirm:P,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(ex,{open:a,onClose:()=>y(!1),onConfirm:R,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:u,currentLevels:h}),e.jsx(qp,{open:r,onClose:()=>b(!1),onConfirm:f,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:u}),e.jsx(R2,{open:n,onClose:()=>{j(!1),C(null)},onConfirm:T,approverName:d==null?void 0:d.approverName,levelNumber:d==null?void 0:d.levelNumber,requestIdDisplay:c.id,requestTitle:c.title}),l&&e.jsx(Zo,{fileName:l.fileName,fileType:l.fileType,fileUrl:ho(l.documentId),fileSize:l.fileSize,attachmentId:l.documentId,onDownload:F,open:!!l,onClose:()=>w(null)}),m&&e.jsx(Qp,{open:i,onClose:()=>{v(!1),S(null)},success:m.success,title:m.title,message:m.message}),e.jsx(ot,{open:o.show,onOpenChange:B=>N(U=>({...U,show:B})),children:e.jsxs(nt,{className:"sm:max-w-lg",children:[e.jsxs(ct,{children:[e.jsxs(it,{className:"flex items-center gap-2",children:[e.jsx(We,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(_t,{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:o.errors.map((B,U)=>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:B.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:B.reason})]},U))}),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: ",K.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",K.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(At,{children:e.jsx(I,{onClick:()=>N({show:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const lx={DocumentsTab:i2,ActivityTab:d2,WorkNotesTab:x2,SummaryTab:g2,RequestDetailHeader:y2,QuickActionsSidebar:T2,RequestDetailModals:P2};function Jo({className:t,...s}){return e.jsx(Og,{"data-slot":"checkbox",className:we("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($g,{"data-slot":"checkbox-indicator",className:"flex items-center justify-center text-current transition-none",children:e.jsx(jr,{className:"size-3.5"})})})}function ox({isOpen:t,onClose:s,summaryId:a,requestTitle:r,onSuccess:n}){const[i,l]=x.useState(""),[o,c]=x.useState([]),[d,m]=x.useState(new Set),[u,h]=x.useState(!1),[g,p]=x.useState(!1);x.useEffect(()=>{if(!t){c([]);return}if(!i||!i.startsWith("@")||i.length<2){c([]),h(!1);return}const v=setTimeout(async()=>{var w;try{h(!0);const N=i.slice(1),C=await Zs(N,10),S=((w=C==null?void 0:C.data)==null?void 0:w.data)||(C==null?void 0:C.data)||[];c(Array.isArray(S)?S:[])}catch(N){console.error("Failed to search users:",N),q.error("Failed to search users")}finally{h(!1)}},300);return()=>clearTimeout(v)},[i,t]);const y=v=>{m(w=>{const N=new Set(w);return N.has(v)?N.delete(v):N.add(v),N})},b=async()=>{var v,w;if(d.size===0){q.error("Please select at least one user to share with");return}try{p(!0),await b2(a,Array.from(d)),q.success(`Summary shared with ${d.size} user(s)`),m(new Set),l(""),c([]),n==null||n(),s()}catch(N){console.error("Failed to share summary:",N),q.error(((w=(v=N==null?void 0:N.response)==null?void 0:v.data)==null?void 0:w.message)||"Failed to share summary")}finally{p(!1)}},j=()=>{m(new Set),l(""),c([]),s()};return e.jsx(ot,{open:t,onOpenChange:j,children:e.jsxs(nt,{className:"sm:max-w-[500px]",children:[e.jsx(ct,{children:e.jsx(it,{children:"Share Summary"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{children:[e.jsx(re,{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(re,{htmlFor:"user-search",className:"text-sm font-medium text-gray-700",children:"Search Users"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx($s,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(Re,{id:"user-search",placeholder:"Type @ to search users...",value:i,onChange:v=>l(v.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(Qe,{className:"h-5 w-5 animate-spin text-blue-600"})}),!u&&o.length>0&&e.jsx("div",{className:"border rounded-lg max-h-[300px] overflow-y-auto",children:o.map(v=>{const w=d.has(v.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(v.userId),children:[e.jsx("div",{onClick:N=>N.stopPropagation(),onMouseDown:N=>N.stopPropagation(),className:"flex items-center",children:e.jsx(Jo,{checked:w,onCheckedChange:()=>y(v.userId)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"h-4 w-4 text-gray-400 flex-shrink-0"}),e.jsx("p",{className:"text-sm font-medium text-gray-900 truncate",children:v.displayName||v.email})]}),(v.designation||v.department)&&e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:v.designation||v.department}),e.jsx("p",{className:"text-xs text-gray-400 truncate",children:v.email})]})]},v.userId)})}),!u&&i&&i.startsWith("@")&&o.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(v=>{const w=o.find(N=>N.userId===v);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:(w==null?void 0:w.displayName)||(w==null?void 0:w.email)||v}),e.jsx("button",{onClick:()=>y(v),className:"ml-1 hover:text-red-600",children:e.jsx(pt,{className:"h-3 w-3"})})]},v)})})]})]}),e.jsxs(At,{children:[e.jsx(I,{variant:"outline",onClick:j,disabled:g,children:"Cancel"}),e.jsx(I,{onClick:b,disabled:g||d.size===0,children:g?e.jsxs(e.Fragment,{children:[e.jsx(Qe,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):`Share with ${d.size} user(s)`})]})]})})}function cx({isOpen:t,onClose:s,requestId:a,levelId:r,onSuccess:n}){const[i,l]=x.useState(""),[o,c]=x.useState(""),[d,m]=x.useState(!1),u=()=>Ot().add(1,"month").format("YYYY-MM-DD"),h=()=>Ot().add(1,"month").format("YYYY-MM-DD"),g=()=>Ot().add(1,"day").format("YYYY-MM-DD");x.useEffect(()=>{t&&!o&&c(u())},[t]);const p=async()=>{var w,N,C,S;if(!i.trim()){q.error("Please provide a reason for pausing");return}if(!o){q.error("Please select a resume date");return}const b=Ot(o),j=Ot().add(1,"month"),v=Ot().add(1,"day");if(b.isAfter(j)){q.error("Resume date cannot be more than 1 month from now");return}if(b.isBefore(v,"day")){q.error("Resume date must be at least 1 day from now");return}try{m(!0),await Zb(a,r,i.trim(),b.toDate()),q.success("Workflow paused successfully"),n&&await n(),l(""),c(u()),s()}catch(E){console.error("Failed to pause workflow:",E),q.error(((N=(w=E==null?void 0:E.response)==null?void 0:w.data)==null?void 0:N.error)||((S=(C=E==null?void 0:E.response)==null?void 0:C.data)==null?void 0:S.message)||"Failed to pause workflow")}finally{m(!1)}},y=()=>{d||(l(""),c(u()),s())};return e.jsx(ot,{open:t,onOpenChange:y,children:e.jsxs(nt,{className:"sm:max-w-[500px]",children:[e.jsx(ct,{children:e.jsxs(it,{className:"flex items-center gap-2",children:[e.jsx(Ra,{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(re,{htmlFor:"pause-reason",className:"text-sm font-medium",children:["Reason for Pausing ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ps,{id:"pause-reason",value:i,onChange:b=>l(b.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(re,{htmlFor:"resume-date",className:"text-sm font-medium",children:["Resume Date ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Re,{id:"resume-date",type:"date",value:o,onChange:b=>c(b.target.value),min:g(),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(At,{children:[e.jsx(I,{variant:"outline",onClick:y,disabled:d,children:"Cancel"}),e.jsx(I,{onClick:p,disabled:d||!i.trim()||!o,className:"bg-orange-600 hover:bg-orange-700 text-white",children:d?e.jsxs(e.Fragment,{children:[e.jsx(Qe,{className:"w-4 h-4 mr-2 animate-spin"}),"Pausing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ra,{className:"w-4 h-4 mr-2"}),"Pause Workflow"]})})]})]})})}function dx({isOpen:t,onClose:s,requestId:a,onSuccess:r}){const[n,i]=x.useState(""),[l,o]=x.useState(!1),c=async()=>{var m,u,h,g;try{o(!0),await Xb(a,n.trim()||void 0),q.success("Workflow resumed successfully"),r&&await r(),i(""),s()}catch(p){console.error("Failed to resume workflow:",p),q.error(((u=(m=p==null?void 0:p.response)==null?void 0:m.data)==null?void 0:u.error)||((g=(h=p==null?void 0:p.response)==null?void 0:h.data)==null?void 0:g.message)||"Failed to resume workflow")}finally{o(!1)}},d=()=>{l||(i(""),s())};return e.jsx(ot,{open:t,onOpenChange:d,children:e.jsxs(nt,{className:"sm:max-w-[500px]",children:[e.jsx(ct,{children:e.jsxs(it,{className:"flex items-center gap-2",children:[e.jsx(Yn,{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(re,{htmlFor:"resume-notes",className:"text-sm font-medium",children:"Notes (Optional)"}),e.jsx(ps,{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:l}),e.jsxs("p",{className:"text-xs text-gray-500",children:[n.length," / 1000 characters"]})]})]}),e.jsxs(At,{children:[e.jsx(I,{variant:"outline",onClick:d,disabled:l,children:"Cancel"}),e.jsx(I,{onClick:c,disabled:l,className:"bg-green-600 hover:bg-green-700 text-white",children:l?e.jsxs(e.Fragment,{children:[e.jsx(Qe,{className:"w-4 h-4 mr-2 animate-spin"}),"Resuming..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Yn,{className:"w-4 h-4 mr-2"}),"Resume Workflow"]})})]})]})})}function mx({isOpen:t,onClose:s,requestId:a,approverName:r,onSuccess:n}){const[i,l]=x.useState(!1),o=async()=>{var c,d,m,u;try{l(!0),await Jb(a),q.success("Retrigger request sent to approver"),n&&await n(),s()}catch(h){console.error("Failed to retrigger pause:",h),q.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{l(!1)}};return e.jsx(ot,{open:t,onOpenChange:s,children:e.jsxs(nt,{className:"sm:max-w-[450px]",children:[e.jsx(ct,{children:e.jsxs(it,{className:"flex items-center gap-2",children:[e.jsx(We,{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(At,{children:[e.jsx(I,{variant:"outline",onClick:s,disabled:i,children:"Cancel"}),e.jsx(I,{onClick:o,disabled:i,className:"bg-orange-600 hover:bg-orange-700 text-white",children:i?e.jsxs(e.Fragment,{children:[e.jsx(Qe,{className:"w-4 h-4 mr-2 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(We,{className:"w-4 h-4 mr-2"}),"Send Request"]})})]})]})})}const{DocumentsTab:I2,ActivityTab:E2,WorkNotesTab:M2,SummaryTab:F2,RequestDetailHeader:_2,QuickActionsSidebar:L2,RequestDetailModals:O2}=lx;let $2=class 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("Custom 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(hs,{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(I,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(I,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}};function B2({requestId:t,onBack:s,dynamicRequests:a=[]}){var ua,ha,ft,Oa,$a,Ba,Ua,Va;const n=ir().requestId||t||"",l=new URLSearchParams(window.location.search).get("tab")||"overview",[o,c]=x.useState(l),[d,m]=x.useState(!1),[u,h]=x.useState(null),[g,p]=x.useState(null),[y,b]=x.useState(!1),[j,v]=x.useState(0),[w,N]=x.useState(!1),[C,S]=x.useState(!1),[E,P]=x.useState(!1),{user:R}=Kt(),{request:f,apiRequest:T,loading:F,refreshing:K,refreshDetails:B,currentApprovalLevel:U,isSpectator:D,isInitiator:A,existingParticipants:k,accessDenied:M}=po(n,a,R),{mergedMessages:O,unreadWorkNotes:L,workNoteAttachments:Z,setWorkNoteAttachments:z}=Yp(n,T,o,R),{uploadingDocument:$,triggerFileInput:W,previewDocument:_,setPreviewDocument:G,documentPolicy:H,documentError:V,setDocumentError:ee}=Zp(T,B),{showApproveModal:oe,setShowApproveModal:pe,showRejectModal:Pe,setShowRejectModal:Se,showAddApproverModal:ne,setShowAddApproverModal:de,showAddSpectatorModal:le,setShowAddSpectatorModal:fe,showSkipApproverModal:st,setShowSkipApproverModal:ae,showActionStatusModal:je,setShowActionStatusModal:gt,skipApproverData:be,setSkipApproverData:Oe,actionStatus:ut,setActionStatus:wt,handleApproveConfirm:dt,handleRejectConfirm:is,handleAddApprover:Bs,handleSkipApprover:ma,handleAddSpectator:Q}=Jp(n,U,B),{conclusionRemark:ge,setConclusionRemark:X,conclusionLoading:Ae,conclusionSubmitting:Te,aiGenerated:$e,handleGenerateConclusion:ke,handleFinalizeConclusion:Ge}=Xp(f,n,A,B,s,wt,gt);x.useEffect(()=>{const Cs=new URLSearchParams(window.location.search).get("tab");Cs&&c(Cs)},[n]);const Fe=()=>{B()},Xe=()=>{N(!0)},ls=()=>{S(!0)},Lt=async()=>{await B()},et=()=>{P(!0)},Je=async()=>{await B()},ht=async()=>{await B()},zt=async()=>{if(!(T!=null&&T.requestId)){q.error("Request ID not found");return}if(!u){q.error("Summary not available. Please ensure the request is closed and the summary has been generated.");return}m(!0)},Dt=((f==null?void 0:f.status)==="approved"||(f==null?void 0:f.status)==="rejected")&&A,Us=(f==null?void 0:f.status)==="closed"||(f==null?void 0:f.status)==="approved"&&!A||(f==null?void 0:f.status)==="rejected"&&!A;x.useEffect(()=>{(async()=>{if(!Us||!(T!=null&&T.requestId)){p(null),h(null);return}try{b(!0);const Cs=await ax(T.requestId);if(Cs!=null&&Cs.summaryId){h(Cs.summaryId);try{const wa=await Xo(Cs.summaryId);p(wa)}catch(wa){console.error("Failed to fetch summary details:",wa),p(null),h(null)}}else p(null),h(null)}catch{p(null),h(null)}finally{b(!1)}})()},[Us,T==null?void 0:T.requestId]);const Xs=((f==null?void 0:f.approvalFlow)||[]).filter(ss=>ss&&typeof ss.step=="number").map(ss=>({levelNumber:ss.step||0,approverName:ss.approver||"Unknown",status:ss.status||"pending",tatHours:ss.tatHours||24}));return F&&!f&&!T?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(ns,{className:"w-12 h-12 text-blue-600 animate-spin mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading custom request details..."})]})}):M!=null&&M.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(Su,{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:M.message}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsxs(I,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(Ys,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(I,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})}):f?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"min-h-screen bg-gray-50","data-testid":"custom-request-detail-page",children:e.jsxs("div",{className:"max-w-7xl mx-auto",children:[e.jsx(_2,{request:f,refreshing:K,onBack:s||(()=>window.history.back()),onRefresh:Fe,onShareSummary:zt,isInitiator:A,slaData:((ua=f==null?void 0:f.summary)==null?void 0:ua.sla)||(f==null?void 0:f.sla)||null,isPaused:((ha=f==null?void 0:f.pauseInfo)==null?void 0:ha.isPaused)||!1}),e.jsxs(wn,{value:o,onValueChange:c,className:"w-full","data-testid":"custom-request-detail-tabs",children:[e.jsx("div",{className:"mb-4 sm:mb-6",children:e.jsxs(Cn,{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(Ct,{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(Au,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Overview"})]}),Us&&g&&e.jsxs(Ct,{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(ao,{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(Ct,{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(da,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Workflow"})]}),e.jsxs(Ct,{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(Le,{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(Ct,{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(ts,{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(Ct,{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(Os,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Work Notes"}),L>0&&e.jsx(ie,{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:L>9?"9+":L})]})]})}),e.jsxs("div",{className:o==="worknotes"?"":"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs("div",{className:o==="worknotes"?"":"lg:col-span-2",children:[e.jsx(St,{value:"overview",className:"mt-0","data-testid":"overview-tab-content",children:e.jsx(Mv,{request:f,isInitiator:A,needsClosure:Dt,conclusionRemark:ge,setConclusionRemark:X,conclusionLoading:Ae,conclusionSubmitting:Te,aiGenerated:$e,handleGenerateConclusion:ke,handleFinalizeConclusion:Ge,onPause:Xe,onResume:ls,onRetrigger:et,currentUserIsApprover:!!U,pausedByUserId:(Oa=(ft=f==null?void 0:f.pauseInfo)==null?void 0:ft.pausedBy)==null?void 0:Oa.userId,currentUserId:R==null?void 0:R.userId})}),Us&&e.jsx(St,{value:"summary",className:"mt-0","data-testid":"summary-tab-content",children:e.jsx(F2,{summary:g,loading:y,onShare:zt,isInitiator:A})}),e.jsx(St,{value:"workflow",className:"mt-0",children:e.jsx(Ov,{request:f,user:R,isInitiator:A,onSkipApprover:ss=>{if(!ss.levelId){alert("Level ID not available");return}Oe(ss),ae(!0)},onRefresh:B})}),e.jsx(St,{value:"documents",className:"mt-0",children:e.jsx(I2,{request:f,workNoteAttachments:Z,uploadingDocument:$,documentPolicy:H,triggerFileInput:W,setPreviewDocument:G,downloadDocument:nr})}),e.jsx(St,{value:"activity",className:"mt-0",children:e.jsx(E2,{request:f})}),e.jsx(St,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:o!=="worknotes",children:e.jsx(M2,{requestId:n,requestTitle:f.title,mergedMessages:O,setWorkNoteAttachments:z,isInitiator:A,isSpectator:D,currentLevels:Xs,onAddApprover:Bs})})]}),o!=="worknotes"&&e.jsx(L2,{request:f,isInitiator:A,isSpectator:D,currentApprovalLevel:U,onAddApprover:()=>de(!0),onAddSpectator:()=>fe(!0),onApprove:()=>pe(!0),onReject:()=>Se(!0),onPause:Xe,onResume:ls,onRetrigger:et,summaryId:u,refreshTrigger:j,pausedByUserId:(Ba=($a=f==null?void 0:f.pauseInfo)==null?void 0:$a.pausedBy)==null?void 0:Ba.userId,currentUserId:R==null?void 0:R.userId,apiRequest:T})]})]})]})}),d&&u&&e.jsx(ox,{isOpen:d,onClose:()=>m(!1),summaryId:u,requestTitle:(f==null?void 0:f.title)||"N/A",onSuccess:()=>{B(),v(ss=>ss+1)}}),w&&(T==null?void 0:T.requestId)&&e.jsx(cx,{isOpen:w,onClose:()=>N(!1),requestId:T.requestId,levelId:(U==null?void 0:U.levelId)||null,onSuccess:Je}),C&&(T==null?void 0:T.requestId)&&e.jsx(dx,{isOpen:C,onClose:()=>S(!1),requestId:T.requestId,onSuccess:Lt}),E&&(T==null?void 0:T.requestId)&&e.jsx(mx,{isOpen:E,onClose:()=>P(!1),requestId:T.requestId,approverName:(Va=(Ua=f==null?void 0:f.pauseInfo)==null?void 0:Ua.pausedBy)==null?void 0:Va.name,onSuccess:ht}),e.jsx(O2,{showApproveModal:oe,showRejectModal:Pe,showAddApproverModal:ne,showAddSpectatorModal:le,showSkipApproverModal:st,showActionStatusModal:je,previewDocument:_,documentError:V,request:f,skipApproverData:be,actionStatus:ut,existingParticipants:k,currentLevels:Xs,setShowApproveModal:pe,setShowRejectModal:Se,setShowAddApproverModal:de,setShowAddSpectatorModal:fe,setShowSkipApproverModal:ae,setShowActionStatusModal:gt,setPreviewDocument:G,setDocumentError:ee,setSkipApproverData:Oe,setActionStatus:wt,handleApproveConfirm:dt,handleRejectConfirm:is,handleAddApprover:Bs,handleAddSpectator:Q,handleSkipApprover:ma,downloadDocument:nr,documentPolicy:H})]}):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(Le,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-3",children:"Custom Request Not Found"}),e.jsx("p",{className:"text-gray-600 mb-6",children:"The custom 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(I,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(Ys,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(I,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})})}function U2(t){return e.jsx($2,{children:e.jsx(B2,{...t})})}function V2({request:t,apiRequest:s,currentUserId:a,isInitiator:r,onEditClaimAmount:n,className:i="",needsClosure:l=!1,conclusionRemark:o="",setConclusionRemark:c,conclusionLoading:d=!1,conclusionSubmitting:m=!1,aiGenerated:u=!1,handleGenerateConclusion:h,handleFinalizeConclusion:g}){var v,w,N,C,S,E,P,R,f,T,F,K,B,U,D;if(!Si(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 p=rx(s);if(!p)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:p.activityInfo,dealerInfo:p.dealerInfo,hasProposalDetails:!!p.proposalDetails,closedExpenses:(v=p.activityInfo)==null?void 0:v.closedExpenses,closedExpensesBreakdown:(w=p.activityInfo)==null?void 0:w.closedExpensesBreakdown,hasDealerCode:!!((N=p.dealerInfo)!=null&&N.dealerCode),hasDealerName:!!((C=p.dealerInfo)!=null&&C.dealerName)});const y=nx(s,a),b=ix(y);console.debug("[ClaimManagementOverviewTab] User role and visibility:",{userRole:y,visibility:b,currentUserId:a,showDealerInfo:b.showDealerInfo,dealerInfoPresent:!!((S=p.dealerInfo)!=null&&S.dealerCode||(E=p.dealerInfo)!=null&&E.dealerName)});const j={name:((P=s.initiator)==null?void 0:P.name)||((R=s.initiator)==null?void 0:R.displayName)||((f=s.initiator)==null?void 0:f.email)||"Unknown",role:((T=s.initiator)==null?void 0:T.role)||((F=s.initiator)==null?void 0:F.designation)||"Initiator",department:((K=s.initiator)==null?void 0:K.department)||s.department||"",email:((B=s.initiator)==null?void 0:B.email)||"N/A",phone:((U=s.initiator)==null?void 0:U.phone)||((D=s.initiator)==null?void 0:D.mobile)};return console.debug("[ClaimManagementOverviewTab] Closure setup check:",{needsClosure:l,requestStatus:s==null?void 0:s.status,requestStatusLower:((s==null?void 0:s.status)||"").toLowerCase(),hasConclusionRemark:!!o,conclusionRemarkLength:(o==null?void 0:o.length)||0,conclusionLoading:d,conclusionSubmitting:m,aiGenerated:u,hasHandleGenerate:!!h,hasHandleFinalize:!!g,hasSetConclusion:!!c}),e.jsxs("div",{className:`space-y-6 ${i}`,children:[e.jsx(N2,{activityInfo:p.activityInfo,createdAt:s==null?void 0:s.createdAt,updatedAt:s==null?void 0:s.updatedAt}),e.jsx(w2,{dealerInfo:p.dealerInfo}),b.showProposalDetails&&p.proposalDetails&&e.jsx(S2,{proposalDetails:p.proposalDetails}),e.jsx(A2,{initiatorInfo:j}),(s==null?void 0:s.status)==="closed"&&(s==null?void 0:s.conclusionRemark)&&e.jsxs(te,{children:[e.jsxs(me,{children:[e.jsxs(he,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ce,{className:"w-5 h-5 text-gray-600"}),"Conclusion Remark"]}),e.jsx(De,{className:"mt-1 text-xs sm:text-sm",children:"Final summary of this closed request"})]}),e.jsxs(se,{className:"pt-4",children:[e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-4",children:e.jsx(Ws,{content:s.conclusionRemark||"",className:"text-sm"})}),s.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 ",es(s.closureDate)]}),e.jsxs("span",{children:["By ",j.name]})]})]})]}),l&&e.jsxs(te,{"data-testid":"conclusion-remark-card",children:[e.jsx(me,{className:`bg-gradient-to-r border-b ${((s==null?void 0:s.status)||"").toLowerCase()==="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(he,{className:`flex items-center gap-2 text-base sm:text-lg ${((s==null?void 0:s.status)||"").toLowerCase()==="rejected"?"text-red-700":"text-green-700"}`,children:[e.jsx(Ce,{className:`w-5 h-5 ${((s==null?void 0:s.status)||"").toLowerCase()==="rejected"?"text-red-600":"text-green-600"}`}),"Conclusion Remark - Final Step"]}),e.jsx(De,{className:"mt-1 text-xs sm:text-sm",children:((s==null?void 0:s.status)||"").toLowerCase()==="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."})]}),h&&e.jsxs(I,{variant:"outline",size:"sm",onClick:h,disabled:d,className:"gap-2 shrink-0","data-testid":"generate-ai-conclusion-button",children:[e.jsx(ns,{className:`w-3.5 h-3.5 ${d?"animate-spin":""}`}),u?"Regenerate":"Generate with AI"]})]})}),e.jsx(se,{className:"pt-4",children:d?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(Qe,{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"}),u&&e.jsx("span",{className:"text-xs text-blue-600","data-testid":"ai-generated-label",children:"✓ System-generated suggestion (editable)"})]}),c&&e.jsx(yi,{value:o,onChange:A=>c(A),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:[o?o.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"})]})]}),g&&e.jsx("div",{className:"flex gap-3 justify-end pt-3 border-t",children:e.jsx(I,{onClick:g,disabled:m||!o.trim(),className:"bg-green-600 hover:bg-green-700 text-white","data-testid":"finalize-close-button",children:m?e.jsxs(e.Fragment,{children:[e.jsx(Qe,{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 z2({isOpen:t,onClose:s,onApprove:a,onReject:r,requestTitle:n="Request",requestDescription:i="",requestId:l,levelName:o="Approval Level",approverName:c="Approver"}){const[d,m]=x.useState(""),[u,h]=x.useState(!1),[g,p]=x.useState(null),y=async()=>{if(!d.trim()){q.error("Please provide approval comments");return}try{h(!0),p("approve"),await a(d),j(),s()}catch(w){console.error("Failed to approve request:",w),q.error("Failed to approve request. Please try again.")}finally{h(!1),p(null)}},b=async()=>{if(!d.trim()){q.error("Please provide rejection reason");return}try{h(!0),p("reject"),await r(d),j(),s()}catch(w){console.error("Failed to reject request:",w),q.error("Failed to reject request. Please try again.")}finally{h(!1),p(null)}},j=()=>{m(""),p(null)},v=()=>{u||(j(),s())};return t?e.jsx(ot,{open:t,onOpenChange:v,children:e.jsxs(nt,{className:"dealer-proposal-modal overflow-hidden flex flex-col max-w-3xl",children:[e.jsxs(ct,{className:"flex-shrink-0 pb-3 lg:pb-4 px-6 pt-4 lg:pt-6 border-b",children:[e.jsxs(it,{className:"flex items-center gap-2 text-lg lg:text-xl",children:[e.jsx(Ce,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"}),"Review Request"]}),e.jsxs(_t,{className:"text-xs lg:text-sm",children:[o,": Review request details and make a decision"]}),e.jsx("div",{className:"space-y-1 mt-2 text-xs text-gray-600",children:e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Request ID:"})," ",l||"N/A"]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Approver:"})," ",c]})]})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto overflow-x-hidden py-3 lg:py-4 px-6",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("h3",{className:"font-semibold text-sm lg:text-base flex items-center gap-2",children:[e.jsx(Le,{className:"w-4 h-4 text-blue-600"}),"Request Title"]})}),e.jsx("div",{className:"border rounded-lg p-2.5 lg:p-3 bg-gray-50",children:e.jsx("p",{className:"text-sm lg:text-base font-medium text-gray-900",children:n})})]}),i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("h3",{className:"font-semibold text-sm lg:text-base flex items-center gap-2",children:[e.jsx(Os,{className:"w-4 h-4 text-blue-600"}),"Request Description"]})}),e.jsx("div",{className:"border rounded-lg p-2.5 lg:p-3 bg-gray-50 max-h-[200px] overflow-y-auto",children:e.jsx(Ws,{content:i,className:"text-xs lg:text-sm text-gray-700"})})]}),e.jsxs("div",{className:"space-y-2 border-t pt-3 lg:pt-3",children:[e.jsx("h3",{className:"font-semibold text-sm lg:text-base",children:"Your Decision & Comments"}),e.jsx(ps,{placeholder:"Provide your evaluation comments, approval conditions, or rejection reasons...",value:d,onChange:w=>m(w.target.value),className:"min-h-[80px] lg:min-h-[90px] text-xs lg:text-sm"}),e.jsxs("p",{className:"text-xs text-gray-500",children:[d.length," characters"]})]}),!d.trim()&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-2 flex items-start gap-2",children:[e.jsx(xt,{className:"w-3.5 h-3.5 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-xs text-amber-800",children:"Please provide comments before making a decision. Comments are required and will be visible to all participants."})]})]})}),e.jsxs(At,{className:"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end px-6 pb-6 pt-3 lg:pt-4 flex-shrink-0 border-t bg-gray-50",children:[e.jsx(I,{variant:"outline",onClick:v,disabled:u,className:"border-2",children:"Cancel"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(I,{onClick:b,disabled:!d.trim()||u,variant:"destructive",className:"bg-red-600 hover:bg-red-700",children:u&&g==="reject"?"Rejecting...":e.jsxs(e.Fragment,{children:[e.jsx(xt,{className:"w-4 h-4 mr-2"}),"Reject"]})}),e.jsx(I,{onClick:y,disabled:!d.trim()||u,className:"bg-green-600 hover:bg-green-700 text-white",children:u&&g==="approve"?"Approving...":e.jsxs(e.Fragment,{children:[e.jsx(Ce,{className:"w-4 h-4 mr-2"}),"Approve"]})})]})]})]})}):null}function H2({isOpen:t,onClose:s,onDownload:a,onSendToDealer:r,creditNoteData:n,dealerInfo:i,activityName:l,requestNumber:o,requestId:c,dueDate:d}){const[m,u]=x.useState(!1),[h,g]=x.useState(!1),p=(n==null?void 0:n.creditNoteNumber)&&(n==null?void 0:n.creditNoteNumber)!=="",y=(n==null?void 0:n.creditNoteNumber)||"",b=n!=null&&n.creditNoteDate?es(n.creditNoteDate,{includeTime:!1,format:"short"}):"",j=(n==null?void 0:n.creditNoteAmount)||0,v=(n==null?void 0:n.status)||"PENDING",w=(i==null?void 0:i.dealerName)||"Jaipur Royal Enfield",N=(i==null?void 0:i.dealerCode)||"RE-JP-009",C=l||"Activity",S=o||"RE-REQ-2024-CM-101",E=d?es(d,{includeTime:!1,format:"short"}):"Jan 4, 2026",P=async()=>{if(a)try{u(!0),await a(),q.success("Credit note downloaded successfully")}catch(T){console.error("Failed to download credit note:",T),q.error("Failed to download credit note. Please try again.")}finally{u(!1)}else q.info("Credit note will be automatically saved to Documents tab")},R=async()=>{if(r)try{g(!0),await r(),q.success("Credit note sent to dealer successfully"),s()}catch(T){console.error("Failed to send credit note to dealer:",T),q.error("Failed to send credit note. Please try again.")}finally{g(!1)}else q.info("Email notification will be sent to dealer with credit note attachment")},f=T=>`₹${T.toLocaleString("en-IN",{minimumFractionDigits:0,maximumFractionDigits:0})}`;return e.jsx(ot,{open:t,onOpenChange:s,children:e.jsxs(nt,{className:"sm:max-w-lg lg:max-w-[1000px] max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ct,{children:[e.jsxs(it,{className:"font-semibold flex items-center gap-2 text-2xl",children:[e.jsx(us,{className:"w-6 h-6 text-[--re-green]"}),"Credit Note from SAP"]}),e.jsx(_t,{className:"text-base",children:"Review and send credit note to dealer"})]}),e.jsxs("div",{className:"space-y-5 py-4",children:[p?e.jsxs(e.Fragment,{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(ie,{className:"bg-green-600 text-white px-4 py-2 text-base",children:[e.jsx(Ce,{className:"w-4 h-4 mr-2"}),v==="APPROVED"?"Approved":v==="ISSUED"?"Issued":v==="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(re,{className:"font-medium text-xs text-gray-600 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(Bf,{className:"w-3 h-3"}),"Credit Note Number"]}),e.jsx("p",{className:"font-bold text-gray-900 mt-1 text-lg",children:y})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-green-100",children:[e.jsxs(re,{className:"font-medium text-xs text-gray-600 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(mt,{className:"w-3 h-3"}),"Issue Date"]}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:b})]})]})]}),e.jsxs("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-5",children:[e.jsxs(re,{className:"font-medium text-xs text-gray-600 uppercase tracking-wider flex items-center gap-1 mb-3",children:[e.jsx(Pa,{className:"w-4 h-4"}),"Credit Note Amount"]}),e.jsx("p",{className:"text-4xl font-bold text-blue-700",children:f(j)})]})]}):e.jsx("div",{className:"bg-gray-50 border-2 border-gray-300 rounded-lg p-8 text-center",children:e.jsxs("div",{className:"flex flex-col items-center justify-center space-y-4",children:[e.jsx("div",{className:"w-16 h-16 bg-gray-200 rounded-full flex items-center justify-center",children:e.jsx(us,{className:"w-8 h-8 text-gray-400"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-700 mb-2",children:"No Credit Note Available"}),e.jsx("p",{className:"text-sm text-gray-500",children:"Credit note has not been generated yet. Please wait for the credit note to be generated from DMS."})]})]})}),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(ui,{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(re,{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:w})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(re,{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:N})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(re,{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:C})]})]})]}),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(Le,{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(re,{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:S})]}),e.jsxs("div",{children:[e.jsx(re,{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:E})]})]})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start gap-3",children:[e.jsx(Le,{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(At,{className:"flex-col-reverse gap-2 sm:flex-row flex items-center justify-between sm:justify-between",children:[e.jsx(I,{variant:"outline",onClick:s,disabled:m||h,className:"border-2",children:"Close"}),e.jsx("div",{className:"flex gap-2",children:p&&e.jsxs(e.Fragment,{children:[e.jsxs(I,{variant:"outline",onClick:P,disabled:m||h,className:"border-blue-600 text-blue-600 hover:bg-blue-50",children:[e.jsx(Nt,{className:"w-4 h-4 mr-2"}),m?"Downloading...":"Download"]}),e.jsxs(I,{onClick:R,disabled:m||h,className:"bg-green-600 hover:bg-green-700 text-white shadow-md",children:[e.jsx(wu,{className:"w-4 h-4 mr-2"}),h?"Sending...":"Send to Dealer"]})]})})]})]})})}function W2({isOpen:t,onClose:s,onSubmit:a,dealerName:r="Jaipur Royal Enfield",activityName:n="Activity",requestId:i}){var Pe,Se;const[l,o]=x.useState(""),[c,d]=x.useState(""),[m,u]=x.useState([]),[h,g]=x.useState([]),[p,y]=x.useState([]),[b,j]=x.useState([]),[v,w]=x.useState(null),[N,C]=x.useState(""),[S,E]=x.useState(!1),[P,R]=x.useState(null),f=x.useRef(null),T=x.useRef(null),F=x.useRef(null),K=x.useRef(null),B=ne=>{const de=ne.type.toLowerCase(),le=ne.name.toLowerCase();return de.includes("image")||de.includes("pdf")||le.endsWith(".pdf")||le.endsWith(".jpg")||le.endsWith(".jpeg")||le.endsWith(".png")||le.endsWith(".gif")||le.endsWith(".webp")};x.useEffect(()=>()=>{P!=null&&P.url&&URL.revokeObjectURL(P.url)},[P]);const U=ne=>{if(!B(ne)){q.error("Preview is only available for images and PDF files");return}P!=null&&P.url&&URL.revokeObjectURL(P.url);const de=URL.createObjectURL(ne);R({file:ne,url:de})},D=ne=>{const de=URL.createObjectURL(ne),le=document.createElement("a");le.href=de,le.download=ne.name,document.body.appendChild(le),le.click(),document.body.removeChild(le),URL.revokeObjectURL(de)},A=x.useMemo(()=>m.reduce((ne,de)=>ne+(de.amount||0),0),[m]),k=x.useMemo(()=>{const ne=l!=="",de=h.length>0,le=p.length>0,fe=N.trim().length>0;return ne&&de&&le&&fe},[l,h,p,N]),M=new Date().toISOString().split("T")[0],O=()=>{u([...m,{id:Date.now().toString(),description:"",amount:0}])},L=(ne,de,le)=>{u(m.map(fe=>fe.id===ne?{...fe,[de]:le}:fe))},Z=ne=>{u(m.filter(de=>de.id!==ne))},z=ne=>{const de=Array.from(ne.target.files||[]);if(de.length>0){const le=[".pdf",".doc",".docx",".zip",".rar"];if(de.filter(st=>!le.some(ae=>st.name.toLowerCase().endsWith(ae))).length>0){q.error("Please upload PDF, DOC, DOCX, ZIP, or RAR files only");return}g([...h,...de])}},$=ne=>{g(h.filter((de,le)=>le!==ne))},W=ne=>{const de=Array.from(ne.target.files||[]);if(de.length>0){if(de.filter(fe=>!fe.type.startsWith("image/")).length>0){q.error("Please upload image files only (JPG, PNG, etc.)");return}y([...p,...de])}},_=ne=>{y(p.filter((de,le)=>le!==ne))},G=ne=>{const de=Array.from(ne.target.files||[]);if(de.length>0){const le=[".pdf",".jpg",".jpeg",".png"];if(de.filter(st=>!le.some(ae=>st.name.toLowerCase().endsWith(ae))).length>0){q.error("Please upload PDF, JPG, or PNG files only");return}j([...b,...de])}},H=ne=>{j(b.filter((de,le)=>le!==ne))},V=ne=>{var le,fe;const de=(le=ne.target.files)==null?void 0:le[0];if(de){const st=[".pdf",".xlsx",".xls",".csv"],ae="."+((fe=de.name.split(".").pop())==null?void 0:fe.toLowerCase());if(!st.includes(ae)){q.error("Please upload PDF, Excel, or CSV files only");return}w(de)}},ee=async()=>{if(!k){q.error("Please fill all required fields");return}const ne=m.filter(de=>de.description.trim()!==""&&de.amount>0);try{E(!0),await a({activityCompletionDate:l,numberOfParticipants:c?parseInt(c):void 0,closedExpenses:ne,totalClosedExpenses:A,completionDocuments:h,activityPhotos:p,invoicesReceipts:b.length>0?b:void 0,attendanceSheet:v||void 0,completionDescription:N}),oe(),s()}catch(de){console.error("Failed to submit completion documents:",de),q.error("Failed to submit completion documents. Please try again.")}finally{E(!1)}},oe=()=>{P!=null&&P.url&&URL.revokeObjectURL(P.url),R(null),o(""),d(""),u([]),g([]),y([]),j([]),w(null),C(""),f.current&&(f.current.value=""),T.current&&(T.current.value=""),F.current&&(F.current.value=""),K.current&&(K.current.value="")},pe=()=>{S||(oe(),s())};return e.jsxs(ot,{open:t,onOpenChange:pe,children:[e.jsxs(nt,{className:"dealer-completion-documents-modal overflow-hidden flex flex-col",children:[e.jsxs(ct,{className:"px-6 pt-6 pb-3 flex-shrink-0",children:[e.jsxs(it,{className:"font-semibold flex items-center gap-2 text-xl sm:text-2xl",children:[e.jsx(Rs,{className:"w-5 h-5 sm:w-6 sm:h-6 text-[--re-green]"}),"Activity Completion Documents"]}),e.jsx(_t,{className:"text-sm sm:text-base",children:"Step 5: Upload completion proof and final documents"}),e.jsxs("div",{className:"space-y-1 mt-2 text-xs sm: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.jsx("div",{className:"flex-1 overflow-y-auto overflow-x-hidden px-6 py-3",children:e.jsxs("div",{className:"space-y-5 sm:space-y-6 max-w-4xl mx-auto",children:[e.jsxs("div",{className:"space-y-1.5 sm:space-y-2",children:[e.jsxs(re,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",htmlFor:"completionDate",children:[e.jsx(mt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Activity Completion Date *"]}),e.jsx(Re,{type:"date",id:"completionDate",max:M,value:l,onChange:ne=>o(ne.target.value),onClick:ne=>{ne.currentTarget.showPicker&&ne.currentTarget.showPicker()},className:"w-full max-w-[280px] text-left pr-10 cursor-pointer"})]}),e.jsxs("div",{className:"space-y-3 sm: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-base sm:text-lg",children:"Closed Expenses"}),e.jsx(ie,{className:"bg-secondary text-secondary-foreground text-xs",children:"Optional"})]}),e.jsxs(I,{type:"button",onClick:O,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white",size:"sm",children:[e.jsx(Ls,{className:"w-4 h-4 mr-1"}),"Add Expense"]})]}),e.jsxs("div",{className:"space-y-2 sm:space-y-3",children:[m.map(ne=>e.jsxs("div",{className:"flex gap-2 items-start",children:[e.jsx("div",{className:"flex-1",children:e.jsx(Re,{placeholder:"Item name (e.g., Venue rental, Refreshments, Printing)",value:ne.description,onChange:de=>L(ne.id,"description",de.target.value),className:"text-sm"})}),e.jsx("div",{className:"w-32 sm:w-40",children:e.jsx(Re,{type:"number",placeholder:"Amount",min:"0",step:"0.01",value:ne.amount||"",onChange:de=>L(ne.id,"amount",parseFloat(de.target.value)||0),className:"text-sm"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"mt-0.5 hover:bg-red-100 hover:text-red-700 h-9 w-9 p-0",onClick:()=>Z(ne.id),children:e.jsx(pt,{className:"w-4 h-4"})})]},ne.id)),m.length===0&&e.jsx("p",{className:"text-xs sm:text-sm text-gray-500 italic",children:'No expenses added. Click "Add Expense" to add expense items.'}),m.length>0&&A>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 text-sm sm:text-base",children:"Total Closed Expenses:"}),e.jsxs("span",{className:"font-semibold text-base sm:text-lg",children:["₹",A.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})})]})]}),e.jsxs("div",{className:"space-y-3 sm:space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-base sm:text-lg",children:"Completion Evidence"}),e.jsx(ie,{variant:"outline",className:"text-xs border-red-500 text-red-700 bg-red-50 font-medium",children:"Required"})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6",children:[e.jsxs("div",{children:[e.jsxs(re,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",children:[e.jsx(Le,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Completion Documents *"]}),e.jsx("p",{className:"text-xs sm: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 rounded-lg p-3 sm:p-4 transition-all duration-200 ${h.length>0?"border-green-500 bg-green-50 hover:border-green-600":"border-gray-300 hover:border-blue-500 bg-white"}`,children:[e.jsx("input",{ref:f,type:"file",multiple:!0,accept:".pdf,.doc,.docx,.zip,.rar",className:"hidden",id:"completionDocs",onChange:z}),e.jsx("label",{htmlFor:"completionDocs",className:"cursor-pointer flex flex-col items-center gap-2",children:h.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Fs,{className:"w-8 h-8 text-green-600"}),e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsxs("span",{className:"text-sm font-semibold text-green-700",children:[h.length," document",h.length!==1?"s":""," selected"]}),e.jsx("span",{className:"text-xs text-green-600",children:"Click to add more documents"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Rs,{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.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("p",{className:"text-xs font-medium text-gray-600 mb-1",children:["Selected Documents (",h.length,"):"]}),h.map((ne,de)=>e.jsxs("div",{className:"flex items-start justify-between bg-gradient-to-r from-green-50 to-emerald-50 border border-green-200 p-2 sm:p-3 rounded-lg text-xs sm:text-sm shadow-sm hover:shadow-md transition-shadow w-full",children:[e.jsxs("div",{className:"flex items-start gap-2 flex-1 min-w-0 pr-2",children:[e.jsx(Le,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-green-600 flex-shrink-0 mt-0.5"}),e.jsx("span",{className:"text-gray-800 font-medium break-words break-all",children:ne.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[B(ne)&&e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>U(ne),title:"Preview file",children:e.jsx(bt,{className:"w-3.5 h-3.5"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>D(ne),title:"Download file",children:e.jsx(Nt,{className:"w-3.5 h-3.5"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>$(de),title:"Remove document",children:e.jsx(pt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},de))]})]}),e.jsxs("div",{children:[e.jsxs(re,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",children:[e.jsx($n,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Activity Photos *"]}),e.jsx("p",{className:"text-xs sm: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 rounded-lg p-3 sm:p-4 transition-all duration-200 ${p.length>0?"border-green-500 bg-green-50 hover:border-green-600":"border-gray-300 hover:border-blue-500 bg-white"}`,children:[e.jsx("input",{ref:T,type:"file",multiple:!0,accept:"image/*",className:"hidden",id:"completionPhotos",onChange:W}),e.jsx("label",{htmlFor:"completionPhotos",className:"cursor-pointer flex flex-col items-center gap-2",children:p.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Fs,{className:"w-8 h-8 text-green-600"}),e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsxs("span",{className:"text-sm font-semibold text-green-700",children:[p.length," photo",p.length!==1?"s":""," selected"]}),e.jsx("span",{className:"text-xs text-green-600",children:"Click to add more photos"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx($n,{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)"})]})})]}),p.length>0&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("p",{className:"text-xs font-medium text-gray-600 mb-1",children:["Selected Photos (",p.length,"):"]}),p.map((ne,de)=>e.jsxs("div",{className:"flex items-start justify-between bg-gradient-to-r from-green-50 to-emerald-50 border border-green-200 p-2 sm:p-3 rounded-lg text-xs sm:text-sm shadow-sm hover:shadow-md transition-shadow w-full",children:[e.jsxs("div",{className:"flex items-start gap-2 flex-1 min-w-0 pr-2",children:[e.jsx($n,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-green-600 flex-shrink-0 mt-0.5"}),e.jsx("span",{className:"text-gray-800 font-medium break-words break-all",children:ne.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[B(ne)&&e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>U(ne),title:"Preview photo",children:e.jsx(bt,{className:"w-3.5 h-3.5"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>D(ne),title:"Download photo",children:e.jsx(Nt,{className:"w-3.5 h-3.5"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>_(de),title:"Remove photo",children:e.jsx(pt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},de))]})]})]})]}),e.jsxs("div",{className:"space-y-3 sm:space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-base sm:text-lg",children:"Supporting Documents"}),e.jsx(ie,{className:"bg-secondary text-secondary-foreground text-xs",children:"Optional"})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6",children:[e.jsxs("div",{children:[e.jsxs(re,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",children:[e.jsx(us,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Invoices / Receipts"]}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 mb-2",children:"Upload invoices and receipts for expenses incurred"}),e.jsxs("div",{className:`border-2 border-dashed rounded-lg p-3 sm:p-4 transition-all duration-200 ${b.length>0?"border-blue-500 bg-blue-50 hover:border-blue-600":"border-gray-300 hover:border-blue-500 bg-white"}`,children:[e.jsx("input",{ref:F,type:"file",multiple:!0,accept:".pdf,.jpg,.jpeg,.png",className:"hidden",id:"invoiceReceipts",onChange:G}),e.jsx("label",{htmlFor:"invoiceReceipts",className:"cursor-pointer flex flex-col items-center gap-2",children:b.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Fs,{className:"w-8 h-8 text-blue-600"}),e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsxs("span",{className:"text-sm font-semibold text-blue-700",children:[b.length," document",b.length!==1?"s":""," selected"]}),e.jsx("span",{className:"text-xs text-blue-600",children:"Click to add more documents"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(us,{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)"})]})})]}),b.length>0&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("p",{className:"text-xs font-medium text-gray-600 mb-1",children:["Selected Documents (",b.length,"):"]}),b.map((ne,de)=>e.jsxs("div",{className:"flex items-start justify-between bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 p-2 sm:p-3 rounded-lg text-xs sm:text-sm shadow-sm hover:shadow-md transition-shadow w-full",children:[e.jsxs("div",{className:"flex items-start gap-2 flex-1 min-w-0 pr-2",children:[e.jsx(us,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-blue-600 flex-shrink-0 mt-0.5"}),e.jsx("span",{className:"text-gray-800 font-medium break-words break-all",children:ne.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[B(ne)&&e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>U(ne),title:"Preview file",children:e.jsx(bt,{className:"w-3.5 h-3.5"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>D(ne),title:"Download file",children:e.jsx(Nt,{className:"w-3.5 h-3.5"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>H(de),title:"Remove document",children:e.jsx(pt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},de))]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-sm sm:text-base font-semibold",children:"Attendance Sheet / Participant List"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 mb-2",children:"Upload attendance records or participant lists (if applicable)"}),e.jsxs("div",{className:`border-2 border-dashed rounded-lg p-3 sm:p-4 transition-all duration-200 ${v?"border-blue-500 bg-blue-50 hover:border-blue-600":"border-gray-300 hover:border-blue-500 bg-white"}`,children:[e.jsx("input",{ref:K,type:"file",accept:".pdf,.xlsx,.xls,.csv",className:"hidden",id:"attendanceDoc",onChange:V}),e.jsx("label",{htmlFor:"attendanceDoc",className:"cursor-pointer flex flex-col items-center gap-2",children:v?e.jsxs(e.Fragment,{children:[e.jsx(Fs,{className:"w-8 h-8 text-blue-600"}),e.jsxs("div",{className:"flex flex-col items-center gap-1 w-full max-w-full px-2",children:[e.jsx("span",{className:"text-sm font-semibold text-blue-700 break-words text-center w-full max-w-full",children:v.name}),e.jsx("span",{className:"text-xs text-blue-600",children:"Document selected"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Rs,{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)"})]})})]}),v&&e.jsxs("div",{className:"mt-3",children:[e.jsx("p",{className:"text-xs font-medium text-gray-600 mb-2",children:"Selected Document:"}),e.jsxs("div",{className:"flex items-start justify-between bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 p-2 sm:p-3 rounded-lg text-xs sm:text-sm shadow-sm hover:shadow-md transition-shadow w-full",children:[e.jsxs("div",{className:"flex items-start gap-2 flex-1 min-w-0 pr-2",children:[e.jsx(Le,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-blue-600 flex-shrink-0 mt-0.5"}),e.jsx("span",{className:"text-gray-800 font-medium break-words break-all",children:v.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[B(v)&&e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>U(v),title:"Preview file",children:e.jsx(bt,{className:"w-3.5 h-3.5"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>D(v),title:"Download file",children:e.jsx(Nt,{className:"w-3.5 h-3.5"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>{w(null),K.current&&(K.current.value="")},title:"Remove document",children:e.jsx(pt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})]})]})]})]}),e.jsxs("div",{className:"space-y-1.5 sm:space-y-2 max-w-3xl",children:[e.jsx(re,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",htmlFor:"completionDescription",children:"Brief Description of Completion *"}),e.jsx(ps,{id:"completionDescription",placeholder:"Provide a brief description of the completed activity, including key highlights, outcomes, challenges faced, and any relevant observations...",value:N,onChange:ne=>C(ne.target.value),className:"min-h-[100px] sm:min-h-[120px] text-sm"}),e.jsxs("p",{className:"text-xs text-gray-500",children:[N.length," characters"]})]}),!k&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-3 sm:p-4 flex items-start gap-2 sm:gap-3",children:[e.jsx(We,{className:"w-4 h-4 sm:w-5 sm:h-5 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-xs sm: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(At,{className:"flex flex-col-reverse sm:flex-row sm:justify-end gap-2 px-6 pt-3 pb-6 border-t flex-shrink-0",children:[e.jsx(I,{variant:"outline",onClick:pe,disabled:S,className:"border-2",children:"Cancel"}),e.jsx(I,{onClick:ee,disabled:S||!k,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white disabled:bg-gray-300 disabled:text-gray-500",children:S?"Submitting...":"Submit Documents"})]})]}),P&&e.jsx(ot,{open:!!P,onOpenChange:()=>{P!=null&&P.url&&URL.revokeObjectURL(P.url),R(null)},children:e.jsx(nt,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(ct,{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(bt,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(it,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:P.file.name}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[P.file.type||"Unknown type"," • ",(P.file.size/1024).toFixed(1)," KB"]})]})]}),e.jsx("div",{className:"flex items-center gap-2 flex-wrap mr-2",children:e.jsxs(I,{variant:"outline",size:"sm",onClick:()=>D(P.file),className:"gap-2 h-9",children:[e.jsx(Nt,{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:(Pe=P.file.type)!=null&&Pe.includes("image")?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("img",{src:P.url,alt:P.file.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"},className:"rounded-lg shadow-lg"})}):(Se=P.file.type)!=null&&Se.includes("pdf")||P.file.name.toLowerCase().endsWith(".pdf")?e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("iframe",{src:P.url,className:"w-full h-full rounded-lg border-0",title:P.file.name,style:{minHeight:"70vh",height:"100%"}})}):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(bt,{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."}),e.jsxs(I,{onClick:()=>D(P.file),className:"gap-2",children:[e.jsx(Nt,{className:"h-4 w-4"}),"Download ",P.file.name]})]})})]})})})]})}function G2({isOpen:t,onClose:s,onSubmit:a,dealerName:r="Jaipur Royal Enfield",activityName:n="Activity",requestId:i}){var W,_;const[l,o]=x.useState(null),[c,d]=x.useState([{id:"1",description:"",amount:0}]),[m,u]=x.useState("date"),[h,g]=x.useState(""),[p,y]=x.useState(""),[b,j]=x.useState([]),[v,w]=x.useState(""),[N,C]=x.useState(!1),[S,E]=x.useState(null),P=x.useRef(null),R=x.useRef(null),f=G=>{const H=G.type.toLowerCase(),V=G.name.toLowerCase();return H.includes("image")||H.includes("pdf")||V.endsWith(".pdf")||V.endsWith(".jpg")||V.endsWith(".jpeg")||V.endsWith(".png")||V.endsWith(".gif")||V.endsWith(".webp")};x.useEffect(()=>()=>{S!=null&&S.url&&URL.revokeObjectURL(S.url)},[S]);const T=G=>{if(!f(G)){q.error("Preview is only available for images and PDF files");return}S!=null&&S.url&&URL.revokeObjectURL(S.url);const H=URL.createObjectURL(G);E({file:G,url:H})},F=G=>{const H=URL.createObjectURL(G),V=document.createElement("a");V.href=H,V.download=G.name,document.body.appendChild(V),V.click(),document.body.removeChild(V),URL.revokeObjectURL(H)},K=x.useMemo(()=>c.reduce((G,H)=>G+(H.amount||0),0),[c]),B=x.useMemo(()=>{const G=l!==null,H=c.length>0&&c.every(oe=>oe.description.trim()!==""&&oe.amount>0),V=m==="date"?h!=="":p!==""&&parseInt(p)>0,ee=v.trim().length>0;return G&&H&&V&&ee},[l,c,m,h,p,v]),U=G=>{var V,ee;const H=(V=G.target.files)==null?void 0:V[0];if(H){const oe=[".pdf",".doc",".docx"],pe="."+((ee=H.name.split(".").pop())==null?void 0:ee.toLowerCase());if(!oe.includes(pe)){q.error("Please upload a PDF, DOC, or DOCX file");return}o(H)}},D=G=>{const H=Array.from(G.target.files||[]);j(V=>[...V,...H])},A=()=>{d(G=>[...G,{id:Date.now().toString(),description:"",amount:0}])},k=G=>{c.length>1&&d(H=>H.filter(V=>V.id!==G))},M=(G,H,V)=>{d(ee=>ee.map(oe=>oe.id===G?{...oe,[H]:H==="amount"?parseFloat(V.toString())||0:V}:oe))},O=G=>{j(H=>H.filter((V,ee)=>ee!==G))},L=async()=>{if(!B){q.error("Please fill all required fields");return}let G=h||"";if(m==="days"&&p){const H=parseInt(p),V=new Date;V.setDate(V.getDate()+H),G=V.toISOString().split("T")[0]}try{C(!0),await a({proposalDocument:l,costBreakup:c.filter(H=>H.description.trim()!==""&&H.amount>0),expectedCompletionDate:G,otherDocuments:b,dealerComments:v}),Z(),s()}catch(H){console.error("Failed to submit proposal:",H),q.error("Failed to submit proposal. Please try again.")}finally{C(!1)}},Z=()=>{S!=null&&S.url&&URL.revokeObjectURL(S.url),E(null),o(null),d([{id:"1",description:"",amount:0}]),u("date"),g(""),y(""),j([]),w(""),P.current&&(P.current.value=""),R.current&&(R.current.value="")},z=()=>{N||(Z(),s())},$=new Date().toISOString().split("T")[0];return e.jsxs(ot,{open:t,onOpenChange:z,children:[e.jsxs(nt,{className:"dealer-proposal-modal overflow-hidden flex flex-col",children:[e.jsxs(ct,{className:"flex-shrink-0 pb-3 lg:pb-4",children:[e.jsxs(it,{className:"flex items-center gap-2 text-xl lg:text-2xl",children:[e.jsx(Rs,{className:"w-5 h-5 lg:w-6 lg:h-6 text-[--re-green]"}),"Dealer Proposal Submission"]}),e.jsx(_t,{className:"text-sm lg:text-base",children:"Step 1: Upload proposal and planning details"}),e.jsxs("div",{className:"space-y-1 mt-2 text-xs lg:text-sm text-gray-600",children:[e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1",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-1",children:"Please upload proposal document, provide cost breakdown, timeline, and detailed comments."})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto overflow-x-hidden py-3 lg:py-4",children:e.jsxs("div",{className:"space-y-4 lg:space-y-0 lg:grid lg:grid-cols-2 lg:gap-6 lg:items-start lg:content-start",children:[e.jsxs("div",{className:"space-y-4 lg:space-y-4 flex flex-col",children:[e.jsxs("div",{className:"space-y-2 lg:space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-base lg:text-lg",children:"Proposal Document"}),e.jsx(ie,{variant:"outline",className:"text-xs border-red-500 text-red-700 bg-red-50 font-medium",children:"Required"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-sm lg:text-base font-semibold flex items-center gap-2",children:"Proposal Document *"}),e.jsx("p",{className:"text-xs lg:text-sm text-gray-600 mb-2",children:"Detailed proposal with activity details and requested information"}),e.jsxs("div",{className:`border-2 border-dashed rounded-lg p-3 lg:p-4 transition-all duration-200 ${l?"border-green-500 bg-green-50 hover:border-green-600":"border-gray-300 hover:border-blue-500 bg-white"}`,children:[e.jsx("input",{ref:P,type:"file",accept:".pdf,.doc,.docx",className:"hidden",id:"proposalDoc",onChange:U}),e.jsx("label",{htmlFor:"proposalDoc",className:"cursor-pointer flex flex-col items-center gap-2",children:l?e.jsxs("div",{className:"flex flex-col items-center gap-2 w-full",children:[e.jsx(Fs,{className:"w-8 h-8 text-green-600"}),e.jsxs("div",{className:"flex flex-col items-center gap-1 w-full max-w-full px-2",children:[e.jsx("span",{className:"text-sm font-semibold text-green-700 break-words text-center w-full max-w-full",children:l.name}),e.jsx("span",{className:"text-xs text-green-600 mb-2",children:"Document selected"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[f(l)&&e.jsxs(I,{type:"button",variant:"outline",size:"sm",onClick:()=>T(l),className:"h-8 text-xs",children:[e.jsx(bt,{className:"w-3.5 h-3.5 mr-1"}),"Preview"]}),e.jsxs(I,{type:"button",variant:"outline",size:"sm",onClick:()=>F(l),className:"h-8 text-xs",children:[e.jsx(Nt,{className:"w-3.5 h-3.5 mr-1"}),"Download"]})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Rs,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600",children:"Click to upload proposal (PDF, DOC, DOCX)"})]})})]})]})]}),e.jsxs("div",{className:"space-y-2 lg:space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-base lg:text-lg",children:"Other Supporting Documents"}),e.jsx(ie,{variant:"outline",className:"text-xs border-gray-300 text-gray-600 bg-gray-50 font-medium",children:"Optional"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"flex items-center gap-2 text-sm lg:text-base font-semibold",children:"Additional Documents"}),e.jsx("p",{className:"text-xs lg:text-sm text-gray-600 mb-2",children:"Any other supporting documents (invoices, receipts, photos, etc.)"}),e.jsxs("div",{className:`border-2 border-dashed rounded-lg p-3 lg:p-4 transition-all duration-200 ${b.length>0?"border-blue-500 bg-blue-50 hover:border-blue-600":"border-gray-300 hover:border-blue-500 bg-white"}`,children:[e.jsx("input",{ref:R,type:"file",multiple:!0,className:"hidden",id:"otherDocs",onChange:D}),e.jsx("label",{htmlFor:"otherDocs",className:"cursor-pointer flex flex-col items-center gap-2",children:b.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Fs,{className:"w-8 h-8 text-blue-600"}),e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsxs("span",{className:"text-sm font-semibold text-blue-700",children:[b.length," document",b.length!==1?"s":""," selected"]}),e.jsx("span",{className:"text-xs text-blue-600",children:"Click to add more documents"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Rs,{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)"})]})})]}),b.length>0&&e.jsxs("div",{className:"mt-2 lg:mt-3 space-y-2 max-h-[150px] lg:max-h-[140px] overflow-y-auto",children:[e.jsxs("p",{className:"text-xs font-medium text-gray-600 mb-1",children:["Selected Documents (",b.length,"):"]}),b.map((G,H)=>e.jsxs("div",{className:"flex items-start justify-between bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 p-2 lg:p-3 rounded-lg text-xs lg:text-sm shadow-sm hover:shadow-md transition-shadow w-full",children:[e.jsxs("div",{className:"flex items-start gap-2 flex-1 min-w-0 pr-2",children:[e.jsx(Le,{className:"w-4 h-4 text-blue-600 flex-shrink-0 mt-0.5"}),e.jsx("span",{className:"text-gray-800 font-medium break-words break-all",children:G.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[f(G)&&e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>T(G),title:"Preview file",children:e.jsx(bt,{className:"w-3.5 h-3.5"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>F(G),title:"Download file",children:e.jsx(Nt,{className:"w-3.5 h-3.5"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>O(H),title:"Remove document",children:e.jsx(pt,{className:"w-4 h-4"})})]})]},H))]})]})]})]}),e.jsxs("div",{className:"space-y-4 lg:space-y-4 flex flex-col",children:[e.jsxs("div",{className:"space-y-2 lg:space-y-2",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-base lg:text-lg",children:"Cost Breakup"}),e.jsx(ie,{variant:"outline",className:"text-xs border-red-500 text-red-700 bg-red-50 font-medium",children:"Required"})]}),e.jsxs(I,{type:"button",onClick:A,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white",size:"sm",children:[e.jsx(Ls,{className:"w-3 h-3 lg:w-4 lg:h-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Add Item"}),e.jsx("span",{className:"sm:hidden",children:"Add"})]})]}),e.jsx("div",{className:"space-y-2 lg:space-y-2 max-h-[200px] lg:max-h-[180px] overflow-y-auto",children:c.map(G=>e.jsxs("div",{className:"flex gap-2 items-start w-full",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(Re,{placeholder:"Item description (e.g., Banner printing, Event setup)",value:G.description,onChange:H=>M(G.id,"description",H.target.value),className:"w-full"})}),e.jsx("div",{className:"w-32 lg:w-36 flex-shrink-0",children:e.jsx(Re,{type:"number",placeholder:"Amount",min:"0",step:"0.01",value:G.amount||"",onChange:H=>M(G.id,"amount",H.target.value),className:"w-full"})}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",className:"mt-0.5 hover:bg-red-100 hover:text-red-700 flex-shrink-0",onClick:()=>k(G.id),disabled:c.length===1,children:e.jsx(pt,{className:"w-4 h-4"})})]},G.id))}),e.jsx("div",{className:"border-2 border-gray-300 rounded-lg p-3 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(yl,{className:"w-4 h-4 lg:w-5 lg:h-5 text-gray-700"}),e.jsx("span",{className:"font-semibold text-sm lg:text-base text-gray-900",children:"Estimated Budget"})]}),e.jsxs("div",{className:"text-xl lg:text-2xl font-bold text-gray-900",children:["₹",K.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})})]}),e.jsxs("div",{className:"space-y-2 lg:space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-base lg:text-lg",children:"Timeline for Closure"}),e.jsx(ie,{variant:"outline",className:"text-xs border-red-500 text-red-700 bg-red-50 font-medium",children:"Required"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(I,{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(mt,{className:"w-4 h-4 mr-1"}),"Specific Date"]}),e.jsx(I,{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",{className:"w-full",children:[e.jsx(re,{className:"text-xs lg:text-sm font-medium mb-1.5 lg:mb-2 block",children:"Expected Completion Date"}),e.jsx(Re,{type:"date",min:$,value:h,onChange:G=>g(G.target.value),onClick:G=>{G.currentTarget.showPicker&&G.currentTarget.showPicker()},className:"h-9 lg:h-10 w-full text-left pr-10 cursor-pointer"})]}):e.jsxs("div",{className:"w-full",children:[e.jsx(re,{className:"text-xs lg:text-sm font-medium mb-1.5 lg:mb-2 block",children:"Number of Days"}),e.jsx(Re,{type:"number",placeholder:"Enter number of days",min:"1",value:p,onChange:G=>y(G.target.value),className:"h-9 lg:h-10 w-full"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"dealerComments",className:"text-sm lg:text-base font-semibold flex items-center gap-2",children:"Dealer Comments / Details *"}),e.jsx(ps,{id:"dealerComments",placeholder:"Provide detailed comments about this claim request, including any special considerations, execution details, or additional information...",value:v,onChange:G=>w(G.target.value),className:"min-h-[80px] lg:min-h-[100px] text-sm w-full"}),e.jsxs("p",{className:"text-xs text-gray-500",children:[v.length," characters"]})]})]}),!B&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-3 lg:p-4 flex items-start gap-2 lg:gap-3 lg:col-span-2",children:[e.jsx(We,{className:"w-4 h-4 lg:w-5 lg:h-5 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-xs lg: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(At,{className:"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end flex-shrink-0 pt-3 lg:pt-4 border-t",children:[e.jsx(I,{variant:"outline",onClick:z,disabled:N,className:"border-2",children:"Cancel"}),e.jsx(I,{onClick:L,disabled:!B||N,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white disabled:bg-gray-300 disabled:text-gray-500",children:N?"Submitting...":"Submit Documents"})]})]}),S&&e.jsx(ot,{open:!!S,onOpenChange:()=>{S!=null&&S.url&&URL.revokeObjectURL(S.url),E(null)},children:e.jsx(nt,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(ct,{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(bt,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(it,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:S.file.name}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[S.file.type||"Unknown type"," • ",(S.file.size/1024).toFixed(1)," KB"]})]})]}),e.jsx("div",{className:"flex items-center gap-2 flex-wrap mr-2",children:e.jsxs(I,{variant:"outline",size:"sm",onClick:()=>F(S.file),className:"gap-2 h-9",children:[e.jsx(Nt,{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:(W=S.file.type)!=null&&W.includes("image")?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("img",{src:S.url,alt:S.file.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"},className:"rounded-lg shadow-lg"})}):(_=S.file.type)!=null&&_.includes("pdf")||S.file.name.toLowerCase().endsWith(".pdf")?e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("iframe",{src:S.url,className:"w-full h-full rounded-lg border-0",title:S.file.name,style:{minHeight:"70vh",height:"100%"}})}):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(bt,{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."}),e.jsxs(I,{onClick:()=>F(S.file),className:"gap-2",children:[e.jsx(Nt,{className:"h-4 w-4"}),"Download ",S.file.name]})]})})]})})})]})}function K2({isOpen:t,onClose:s,onApprove:a,onReject:r,requestTitle:n,requestId:i,preFilledIONumber:l,preFilledIORemark:o,preFilledBlockedAmount:c,preFilledRemainingBalance:d}){const[m,u]=x.useState("approve"),[h,g]=x.useState(""),[p,y]=x.useState(""),[b,j]=x.useState(!1),v=l||"";x.useEffect(()=>{t&&(g(o||""),y(""),u("approve"))},[t,o]);const w=h.length,N=p.length,C=300,S=500,E=x.useMemo(()=>(m==="reject"||v.trim().length>0&&h.trim().length>0)&&p.trim().length>0,[m,v,h,p]),P=async()=>{if(!E){if(m==="approve"){if(!v.trim()){q.error("IO number is required. Please block amount from IO tab first.");return}if(!h.trim()){q.error("Please enter IO remark");return}}if(!p.trim()){q.error("Please provide comments");return}return}try{j(!0),m==="approve"?await a({ioNumber:v.trim(),ioRemark:h.trim(),comments:p.trim()}):await r(p.trim()),R(),s()}catch(T){console.error(`Failed to ${m} request:`,T),q.error(`Failed to ${m} request. Please try again.`)}finally{j(!1)}},R=()=>{u("approve"),g(""),y("")},f=()=>{b||(R(),s())};return e.jsx(ot,{open:t,onOpenChange:f,children:e.jsxs(nt,{className:"dept-lead-io-modal overflow-hidden flex flex-col",children:[e.jsxs(ct,{className:"flex-shrink-0 px-6 pt-6 pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 lg:gap-3 mb-2",children:[e.jsx("div",{className:"p-1.5 lg:p-2 rounded-lg bg-green-100",children:e.jsx(Ce,{className:"w-5 h-5 lg:w-6 lg:h-6 text-green-600"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(it,{className:"font-semibold text-lg lg:text-xl",children:"Approve and Organise IO"}),e.jsx(_t,{className:"text-xs lg:text-sm mt-1",children:"Review IO details and provide your approval comments"})]})]}),e.jsxs("div",{className:"space-y-2 lg:space-y-3 p-3 lg: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-sm lg:text-base text-gray-900",children:"Workflow Step:"}),e.jsx(ie,{variant:"outline",className:"font-mono text-xs",children:"Step 3"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-sm lg:text-base text-gray-900",children:"Title:"}),e.jsx("p",{className:"text-xs lg:text-sm text-gray-700 mt-1",children:n||"—"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-sm lg:text-base text-gray-900",children:"Action:"}),e.jsxs(ie,{className:"bg-green-100 text-green-800 border-green-200 text-xs",children:[e.jsx(Ce,{className:"w-3 h-3 mr-1"}),"APPROVE"]})]})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto overflow-x-hidden py-3 lg:py-4 px-6",children:e.jsxs("div",{className:"space-y-3 lg:space-y-4",children:[e.jsxs("div",{className:"flex gap-2 p-1 bg-gray-100 rounded-lg",children:[e.jsxs(I,{type:"button",onClick:()=>u("approve"),className:`flex-1 text-sm lg:text-base ${m==="approve"?"bg-green-600 text-white shadow-sm":"text-gray-700 hover:bg-gray-200"}`,variant:m==="approve"?"default":"ghost",children:[e.jsx(Ce,{className:"w-4 h-4 mr-1"}),"Approve"]}),e.jsxs(I,{type:"button",onClick:()=>u("reject"),className:`flex-1 text-sm lg:text-base ${m==="reject"?"bg-red-600 text-white shadow-sm":"text-gray-700 hover:bg-gray-200"}`,variant:m==="reject"?"destructive":"ghost",children:[e.jsx(xt,{className:"w-4 h-4 mr-1"}),"Reject"]})]}),e.jsxs("div",{className:"space-y-3 lg:space-y-0 lg:grid lg:grid-cols-2 lg:gap-6",children:[m==="approve"&&e.jsxs("div",{className:"p-3 lg:p-4 bg-blue-50 border border-blue-200 rounded-lg space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(us,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"}),e.jsx("h4",{className:"font-semibold text-sm lg:text-base text-blue-900",children:"IO Organisation Details"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(re,{htmlFor:"ioNumber",className:"text-xs lg:text-sm font-semibold text-gray-900 flex items-center gap-2",children:["IO Number ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Re,{id:"ioNumber",value:v||"—",disabled:!0,readOnly:!0,className:"bg-gray-100 h-8 lg:h-9 cursor-not-allowed text-xs lg:text-sm"}),!v&&e.jsx("p",{className:"text-xs text-red-600 mt-1",children:"⚠️ IO number not found. Please block amount from IO tab first."}),v&&e.jsx("p",{className:"text-xs text-blue-600 mt-1",children:"✓ Loaded from IO table"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[c!==void 0&&c>0&&e.jsx("div",{className:"p-2 bg-green-50 border border-green-200 rounded",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-xs font-semibold text-gray-700",children:"Blocked Amount:"}),e.jsxs("span",{className:"text-xs lg:text-sm font-bold text-green-700 mt-1",children:["₹",c.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})}),d!=null&&e.jsx("div",{className:"p-2 bg-blue-50 border border-blue-200 rounded",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-xs font-semibold text-gray-700",children:"Remaining Balance:"}),e.jsxs("span",{className:"text-xs lg:text-sm font-bold text-blue-700 mt-1",children:["₹",d.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(re,{htmlFor:"ioRemark",className:"text-xs lg: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(ps,{id:"ioRemark",placeholder:"Enter remarks about IO organization",value:h||"—",disabled:!0,readOnly:!0,rows:3,className:"bg-gray-100 text-xs lg:text-sm min-h-[80px] lg:min-h-[100px] resize-none cursor-not-allowed"}),e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[o?e.jsx("span",{className:"text-blue-600",children:"✓ Loaded from IO tab"}):e.jsx("span",{className:"text-red-600",children:"⚠️ IO remark not found. Please add remark in IO tab first."}),e.jsxs("span",{className:"text-gray-600",children:[w,"/",C]})]})]})]}),e.jsxs("div",{className:`space-y-1.5 ${m==="approve"?"":"lg:col-span-2"}`,children:[e.jsxs(re,{htmlFor:"comment",className:"text-xs lg: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(ps,{id:"comment",placeholder:m==="approve"?"Enter your approval comments and any conditions or notes...":"Enter detailed reasons for rejection...",value:p,onChange:T=>{const F=T.target.value;F.length<=S&&y(F)},rows:4,className:"text-xs lg:text-sm min-h-[80px] lg:min-h-[100px] 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(hs,{className:"w-3 h-3"}),"Required and visible to all"]}),e.jsxs("span",{children:[N,"/",S]})]})]})]})]})}),e.jsxs(At,{className:"flex-shrink-0 flex flex-col-reverse sm:flex-row sm:justify-end gap-2 px-6 pb-6 pt-3 border-t",children:[e.jsx(I,{variant:"outline",onClick:f,disabled:b,className:"text-sm lg:text-base",children:"Cancel"}),e.jsx(I,{onClick:P,disabled:!E||b,className:`text-sm lg:text-base ${m==="approve"?"bg-green-600 hover:bg-green-700":"bg-red-600 hover:bg-red-700"} text-white`,children:b?`${m==="approve"?"Approving":"Rejecting"}...`:e.jsxs(e.Fragment,{children:[e.jsx(Ce,{className:"w-4 h-4 mr-2"}),m==="approve"?"Approve Request":"Reject Request"]})})]})]})})}function Y2({isOpen:t,onClose:s,onPush:a,completionDetails:r,ioDetails:n,requestTitle:i,requestNumber:l}){const[o,c]=x.useState(""),[d,m]=x.useState(!1),u=o.length,h=500,g=x.useMemo(()=>r!=null&&r.totalClosedExpenses?r.totalClosedExpenses:r!=null&&r.closedExpenses&&Array.isArray(r.closedExpenses)?r.closedExpenses.reduce((w,N)=>{const C=typeof N=="object"&&N.amount||0;return w+(Number(C)||0)},0):0,[r]),p=w=>{if(!w)return"—";try{return new Date(w).toLocaleDateString("en-IN",{year:"numeric",month:"long",day:"numeric"})}catch{return w}},y=w=>`₹${w.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,b=async()=>{if(!o.trim()){q.error("Please provide comments before pushing to DMS");return}try{m(!0),await a(o.trim()),j(),s()}catch(w){console.error("Failed to push to DMS:",w),q.error("Failed to push to DMS. Please try again.")}finally{m(!1)}},j=()=>{c("")},v=()=>{d||(j(),s())};return e.jsx(ot,{open:t,onOpenChange:v,children:e.jsxs(nt,{className:"dms-push-modal overflow-hidden flex flex-col",children:[e.jsxs(ct,{className:"px-6 pt-6 pb-3 flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 mb-2",children:[e.jsx("div",{className:"p-1.5 sm:p-2 rounded-lg bg-indigo-100",children:e.jsx(ts,{className:"w-4 h-4 sm:w-5 sm:h-5 sm:w-6 sm:h-6 text-indigo-600"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(it,{className:"font-semibold text-lg sm:text-xl",children:"Push to DMS - Verification"}),e.jsx(_t,{className:"text-xs sm:text-sm mt-1",children:"Review completion details and expenses before pushing to DMS for e-invoice generation"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4 p-3 sm:p-4 bg-gray-50 rounded-lg border",children:[e.jsxs("div",{className:"flex items-center justify-between sm:flex-col sm:items-start sm:gap-1",children:[e.jsx("span",{className:"font-medium text-xs sm:text-sm text-gray-600",children:"Workflow Step:"}),e.jsx(ie,{variant:"outline",className:"font-mono text-xs",children:"Requestor Claim Approval"})]}),l&&e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"font-medium text-xs sm:text-sm text-gray-600",children:"Request Number:"}),e.jsx("p",{className:"text-gray-700 font-mono text-xs sm:text-sm",children:l})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"font-medium text-xs sm:text-sm text-gray-600",children:"Title:"}),e.jsx("p",{className:"text-gray-700 text-xs sm:text-sm line-clamp-2",children:i||"—"})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:flex-col sm:items-start sm:gap-1",children:[e.jsx("span",{className:"font-medium text-xs sm:text-sm text-gray-600",children:"Action:"}),e.jsxs(ie,{className:"bg-indigo-100 text-indigo-800 border-indigo-200 text-xs",children:[e.jsx(ts,{className:"w-3 h-3 mr-1"}),"PUSH TO DMS"]})]})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto overflow-x-hidden px-6 py-3",children:e.jsxs("div",{className:"space-y-3 sm:space-y-4 max-w-7xl mx-auto",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6",children:[r&&e.jsxs(te,{children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs(he,{className:"flex items-center gap-2 text-base sm:text-lg",children:[e.jsx(Fs,{className:"w-4 h-4 sm:w-5 sm:h-5 text-green-600"}),"Completion Details"]}),e.jsx(De,{className:"text-xs sm:text-sm",children:"Review activity completion information"})]}),e.jsxs(se,{className:"space-y-2 sm:space-y-3",children:[r.activityCompletionDate&&e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1 py-1.5 sm:py-2 border-b",children:[e.jsx("span",{className:"text-xs sm:text-sm text-gray-600",children:"Activity Completion Date:"}),e.jsx("span",{className:"text-xs sm:text-sm font-semibold text-gray-900",children:p(r.activityCompletionDate)})]}),r.numberOfParticipants!==void 0&&e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1 py-1.5 sm:py-2 border-b",children:[e.jsx("span",{className:"text-xs sm:text-sm text-gray-600",children:"Number of Participants:"}),e.jsx("span",{className:"text-xs sm:text-sm font-semibold text-gray-900",children:r.numberOfParticipants})]}),r.completionDescription&&e.jsxs("div",{className:"pt-2",children:[e.jsx("p",{className:"text-xs text-gray-600 mb-1",children:"Completion Description:"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-900 line-clamp-3",children:r.completionDescription})]})]})]}),n&&n.ioNumber&&e.jsxs(te,{children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs(he,{className:"flex items-center gap-2 text-base sm:text-lg",children:[e.jsx(us,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"IO Details"]}),e.jsx(De,{className:"text-xs sm:text-sm",children:"Internal Order information for budget reference"})]}),e.jsxs(se,{className:"space-y-2 sm:space-y-3",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1 py-1.5 sm:py-2 border-b",children:[e.jsx("span",{className:"text-xs sm:text-sm text-gray-600",children:"IO Number:"}),e.jsx("span",{className:"text-xs sm:text-sm font-semibold text-gray-900 font-mono",children:n.ioNumber})]}),n.blockedAmount!==void 0&&n.blockedAmount>0&&e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1 py-1.5 sm:py-2 border-b",children:[e.jsx("span",{className:"text-xs sm:text-sm text-gray-600",children:"Blocked Amount:"}),e.jsx("span",{className:"text-xs sm:text-sm font-bold text-green-700",children:y(n.blockedAmount)})]}),n.remainingBalance!==void 0&&n.remainingBalance!==null&&e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1 py-1.5 sm:py-2",children:[e.jsx("span",{className:"text-xs sm:text-sm text-gray-600",children:"Remaining Balance:"}),e.jsx("span",{className:"text-xs sm:text-sm font-semibold text-gray-900",children:y(n.remainingBalance)})]})]})]}),(r==null?void 0:r.closedExpenses)&&r.closedExpenses.length>0&&e.jsxs(te,{children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs(he,{className:"flex items-center gap-2 text-base sm:text-lg",children:[e.jsx(Pa,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Expense Breakdown"]}),e.jsx(De,{className:"text-xs sm:text-sm",children:"Review closed expenses before pushing to DMS"})]}),e.jsxs(se,{children:[e.jsx("div",{className:"space-y-1.5 sm:space-y-2 max-h-[200px] overflow-y-auto",children:r.closedExpenses.map((w,N)=>e.jsxs("div",{className:"flex items-center justify-between py-1.5 sm:py-2 px-2 sm:px-3 bg-gray-50 rounded border",children:[e.jsx("div",{className:"flex-1 min-w-0 pr-2",children:e.jsx("p",{className:"text-xs sm:text-sm font-medium text-gray-900 truncate",children:w.description||`Expense ${N+1}`})}),e.jsx("div",{className:"ml-2 flex-shrink-0",children:e.jsx("p",{className:"text-xs sm:text-sm font-semibold text-gray-900",children:y(typeof w=="object"&&w.amount||0)})})]},N))}),e.jsxs("div",{className:"flex items-center justify-between py-2 sm:py-3 px-2 sm:px-3 bg-blue-50 rounded border-2 border-blue-200 mt-2 sm:mt-3",children:[e.jsx("span",{className:"text-xs sm:text-sm font-semibold text-gray-900",children:"Total:"}),e.jsx("span",{className:"text-sm sm:text-base font-bold text-blue-700",children:y(g)})]})]})]})]}),e.jsx("div",{className:"p-2.5 sm:p-3 bg-yellow-50 border border-yellow-200 rounded-lg",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(hs,{className:"w-4 h-4 sm:w-5 sm:h-5 text-yellow-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs sm:text-sm font-semibold text-yellow-900",children:"Please verify all details before pushing to DMS"}),e.jsx("p",{className:"text-xs text-yellow-700 mt-1",children:"Once pushed, the system will automatically generate an e-invoice and log it as an activity."})]})]})}),e.jsxs("div",{className:"space-y-1.5 max-w-2xl",children:[e.jsxs(re,{htmlFor:"comment",className:"text-xs sm: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(ps,{id:"comment",placeholder:"Enter your comments about pushing to DMS (e.g., verified expenses, ready for invoice generation)...",value:o,onChange:w=>{const N=w.target.value;N.length<=h&&c(N)},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(hs,{className:"w-3 h-3"}),"Required and visible to all"]}),e.jsxs("span",{children:[u,"/",h]})]})]})]})}),e.jsxs(At,{className:"flex flex-col-reverse sm:flex-row sm:justify-end gap-2 px-6 pt-3 pb-6 border-t flex-shrink-0",children:[e.jsx(I,{variant:"outline",onClick:v,disabled:d,children:"Cancel"}),e.jsx(I,{onClick:b,disabled:!o.trim()||d,className:"bg-indigo-600 hover:bg-indigo-700 text-white",children:d?"Pushing to DMS...":e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"w-4 h-4 mr-2"}),"Push to DMS"]})})]})]})})}function Z2({isOpen:t,onClose:s,stepNumber:a,stepName:r,requestNumber:n="RE-REQ-2024-CM-101",recipientEmail:i="system@royalenfield.com",subject:l,emailBody:o}){const c=`System Notification: Activity Created - ${n}`,d=l||c,m=`System Notification
|
||
|
||
Activity has been automatically created for claim ${n}.
|
||
|
||
All stakeholders have been notified.
|
||
|
||
This is an automated message.`,u=o||m;return e.jsx(ot,{open:t,onOpenChange:s,children:e.jsxs(nt,{className:"sm:max-w-2xl lg:max-w-[1000px] max-w-2xl",children:[e.jsx(ct,{children:e.jsx("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-full bg-blue-100 flex items-center justify-center",children:e.jsx(va,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(it,{className:"text-lg leading-none font-semibold",children:"Email Notification Template"}),e.jsxs(_t,{className:"text-sm",children:["Step ",a,": ",r]})]})]})})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"bg-gradient-to-r from-blue-50 to-purple-50 rounded-lg p-4 border border-blue-200",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Pt,{className:"w-4 h-4 text-gray-600 mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-xs text-gray-600",children:"To:"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:i})]})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(va,{className:"w-4 h-4 text-gray-600 mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-xs text-gray-600",children:"Subject:"}),e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:d})]})]})]})}),e.jsx("div",{className:"bg-white rounded-lg border border-gray-200 p-6",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-3 border-b border-gray-200",children:[e.jsx(ui,{className:"w-5 h-5 text-purple-600"}),e.jsx("span",{className:"font-semibold text-gray-900",children:"Royal Enfield"})]}),e.jsx("div",{className:"prose prose-sm max-w-none",children:e.jsx("pre",{className:"whitespace-pre-wrap font-sans text-sm text-gray-700 leading-relaxed bg-transparent p-0 border-0",children:u})}),e.jsx("div",{className:"pt-3 border-t border-gray-200",children:e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:[e.jsx(mt,{className:"w-3 h-3"}),e.jsx("span",{children:"Automated email • Royal Enfield Claims Portal"})]})})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ie,{className:"bg-blue-50 text-blue-700 border-blue-200",children:["Step ",a]}),e.jsx(ie,{className:"bg-purple-50 text-purple-700 border-purple-200",children:"Auto-triggered"})]})]}),e.jsx("div",{className:"flex justify-end gap-2 pt-2",children:e.jsxs(I,{variant:"outline",onClick:s,className:"h-9",children:[e.jsx(pt,{className:"w-4 h-4 mr-2"}),"Close"]})})]})})}function X2({isOpen:t,onClose:s,onApprove:a,onReject:r,proposalData:n,dealerName:i="Dealer",activityName:l="Activity",requestId:o}){var f,T;const[c,d]=x.useState(""),[m,u]=x.useState(!1),[h,g]=x.useState(null),[p,y]=x.useState(null),[b,j]=x.useState(!1),v=x.useMemo(()=>{if(!(n!=null&&n.costBreakup))return 0;const F=Array.isArray(n.costBreakup)?n.costBreakup:typeof n.costBreakup=="string"?JSON.parse(n.costBreakup):[];return Array.isArray(F)?F.reduce((K,B)=>{const U=typeof B=="object"&&B.amount||0;return K+(Number(U)||0)},0):0},[n]),w=F=>{if(!F)return"—";try{return new Date(F).toLocaleDateString("en-IN",{year:"numeric",month:"long",day:"numeric"})}catch{return F}},N=F=>{if(!F.name)return!1;const K=F.name.toLowerCase();return K.endsWith(".pdf")||K.endsWith(".jpg")||K.endsWith(".jpeg")||K.endsWith(".png")||K.endsWith(".gif")||K.endsWith(".webp")},C=async F=>{if(!F.id){q.error("Document preview not available - document ID missing");return}j(!0);try{const K=ho(F.id),B=F.name.toLowerCase(),U=B.endsWith(".pdf"),D=B.match(/\.(jpg|jpeg|png|gif|webp)$/i),A=!0,k=A?null:localStorage.getItem("accessToken"),O=await fetch(K,{headers:{Accept:U?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!O.ok)throw new Error(`Failed to load file: ${O.status} ${O.statusText}`);const L=await O.blob();if(L.size===0)throw new Error("File is empty or could not be loaded");const Z=window.URL.createObjectURL(L);y({name:F.name,url:Z,type:L.type||(U?"application/pdf":D?"image":void 0),size:L.size})}catch(K){console.error("Failed to load document preview:",K),q.error("Failed to load document preview")}finally{j(!1)}};x.useEffect(()=>()=>{p!=null&&p.url&&p.url.startsWith("blob:")&&window.URL.revokeObjectURL(p.url)},[p]);const S=async()=>{if(!c.trim()){q.error("Please provide approval comments");return}try{u(!0),g("approve"),await a(c),P(),s()}catch(F){console.error("Failed to approve proposal:",F),q.error("Failed to approve proposal. Please try again.")}finally{u(!1),g(null)}},E=async()=>{if(!c.trim()){q.error("Please provide rejection reason");return}try{u(!0),g("reject"),await r(c),P(),s()}catch(F){console.error("Failed to reject proposal:",F),q.error("Failed to reject proposal. Please try again.")}finally{u(!1),g(null)}},P=()=>{d(""),g(null)},R=()=>{m||(P(),s())};return t?e.jsxs(ot,{open:t,onOpenChange:R,children:[e.jsxs(nt,{className:"dealer-proposal-modal overflow-hidden flex flex-col",children:[e.jsxs(ct,{className:"flex-shrink-0 pb-3 lg:pb-4 px-6 pt-4 lg:pt-6 border-b",children:[e.jsxs(it,{className:"flex items-center gap-2 text-lg lg:text-xl",children:[e.jsx(Ce,{className:"w-4 h-4 lg:w-5 lg:h-5 text-green-600"}),"Requestor Evaluation & Confirmation"]}),e.jsx(_t,{className:"text-xs lg:text-sm",children:"Step 2: Review dealer proposal and make a decision"}),e.jsxs("div",{className:"space-y-1 mt-2 text-xs text-gray-600",children:[e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Dealer:"})," ",i]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Activity:"})," ",l]})]}),e.jsxs("div",{className:"mt-1 text-amber-600 font-medium",children:["Decision: ",e.jsx("strong",{children:"Confirms?"})," (YES → Continue to Dept Lead / NO → Request is cancelled)"]})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto overflow-x-hidden py-3 lg:py-4 px-6",children:e.jsxs("div",{className:"space-y-4 lg:space-y-0 lg:grid lg:grid-cols-2 lg:gap-6 lg:items-start lg:content-start",children:[e.jsxs("div",{className:"space-y-4 lg:space-y-4 flex flex-col",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("h3",{className:"font-semibold text-sm lg:text-base flex items-center gap-2",children:[e.jsx(Le,{className:"w-4 h-4 text-blue-600"}),"Proposal Document"]})}),n!=null&&n.proposalDocument?e.jsxs("div",{className:"border rounded-lg p-2.5 lg:p-3 bg-gray-50 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 lg:gap-3 min-w-0 flex-1",children:[e.jsx(Le,{className:"w-5 h-5 lg:w-6 lg:h-6 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium text-xs lg:text-sm text-gray-900 truncate",title:n.proposalDocument.name,children:n.proposalDocument.name}),(n==null?void 0:n.submittedAt)&&e.jsxs("p",{className:"text-xs text-gray-500 truncate",children:["Submitted on ",w(n.submittedAt)]})]})]}),e.jsx("div",{className:"flex items-center gap-2 flex-shrink-0",children:n.proposalDocument.id&&e.jsxs(e.Fragment,{children:[N(n.proposalDocument)&&e.jsx("button",{type:"button",onClick:()=>C(n.proposalDocument),disabled:b,className:"p-2 hover:bg-gray-200 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Preview document",children:b?e.jsx(Qe,{className:"w-5 h-5 text-blue-600 animate-spin"}):e.jsx(bt,{className:"w-5 h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{var F;try{(F=n.proposalDocument)!=null&&F.id&&await nr(n.proposalDocument.id)}catch(K){console.error("Failed to download document:",K),q.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(Nt,{className:"w-5 h-5 text-gray-600"})})]})})]}):e.jsx("p",{className:"text-xs text-gray-500 italic",children:"No proposal document available"})]}),(n==null?void 0:n.otherDocuments)&&n.otherDocuments.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("h3",{className:"font-semibold text-sm lg:text-base flex items-center gap-2",children:[e.jsx(Le,{className:"w-4 h-4 text-gray-600"}),"Other Supporting Documents"]}),e.jsxs(ie,{variant:"secondary",className:"text-xs",children:[n.otherDocuments.length," file(s)"]})]}),e.jsx("div",{className:"space-y-2 max-h-[150px] lg:max-h-[140px] overflow-y-auto",children:n.otherDocuments.map((F,K)=>e.jsxs("div",{className:"border rounded-lg p-2 lg:p-3 bg-gray-50 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 lg:gap-3 min-w-0 flex-1",children:[e.jsx(Le,{className:"w-4 h-4 lg:w-5 lg:h-5 text-gray-600 flex-shrink-0"}),e.jsx("p",{className:"text-xs lg:text-sm font-medium text-gray-900 truncate",title:F.name,children:F.name})]}),F.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[N(F)&&e.jsx("button",{type:"button",onClick:()=>C(F),disabled:b,className:"p-2 hover:bg-gray-200 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Preview document",children:b?e.jsx(Qe,{className:"w-5 h-5 text-blue-600 animate-spin"}):e.jsx(bt,{className:"w-5 h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{try{F.id&&await nr(F.id)}catch(B){console.error("Failed to download document:",B),q.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(Nt,{className:"w-5 h-5 text-gray-600"})})]})]},K))})]})]}),e.jsxs("div",{className:"space-y-4 lg:space-y-4 flex flex-col",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("h3",{className:"font-semibold text-sm lg:text-base flex items-center gap-2",children:[e.jsx(yl,{className:"w-4 h-4 text-green-600"}),"Cost Breakup"]})}),(()=>{const F=n!=null&&n.costBreakup?Array.isArray(n.costBreakup)?n.costBreakup:typeof n.costBreakup=="string"?JSON.parse(n.costBreakup):[]:[];return F&&Array.isArray(F)&&F.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"border rounded-lg overflow-hidden max-h-[200px] lg:max-h-[180px] overflow-y-auto",children:[e.jsx("div",{className:"bg-gray-50 px-3 lg:px-4 py-2 border-b sticky top-0",children:e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-xs lg: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:F.map((K,B)=>e.jsxs("div",{className:"px-3 lg:px-4 py-2 lg:py-3 grid grid-cols-2 gap-4",children:[e.jsx("div",{className:"text-xs lg:text-sm text-gray-700",children:(K==null?void 0:K.description)||"N/A"}),e.jsxs("div",{className:"text-xs lg:text-sm font-semibold text-gray-900 text-right",children:["₹",(Number(K==null?void 0:K.amount)||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]},(K==null?void 0:K.id)||(K==null?void 0:K.description)||B))})]}),e.jsx("div",{className:"border-2 border-[--re-green] rounded-lg p-2.5 lg:p-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yl,{className:"w-4 h-4 text-[--re-green]"}),e.jsx("span",{className:"font-semibold text-xs lg:text-sm text-gray-700",children:"Total Estimated Budget"})]}),e.jsxs("div",{className:"text-lg lg:text-xl font-bold text-[--re-green]",children:["₹",v.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})})]}):e.jsx("p",{className:"text-xs text-gray-500 italic",children:"No cost breakdown available"})})()]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("h3",{className:"font-semibold text-sm lg:text-base flex items-center gap-2",children:[e.jsx(mt,{className:"w-4 h-4 text-purple-600"}),"Expected Completion Date"]})}),e.jsx("div",{className:"border rounded-lg p-2.5 lg:p-3 bg-gray-50",children:e.jsx("p",{className:"text-sm lg:text-base font-semibold text-gray-900",children:n!=null&&n.expectedCompletionDate?w(n.expectedCompletionDate):"Not specified"})})]})]}),e.jsx("div",{className:"space-y-2 border-t pt-3 lg:pt-3 lg:col-span-2 mt-2",children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4 lg:gap-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("h3",{className:"font-semibold text-sm lg:text-base flex items-center gap-2",children:[e.jsx(Os,{className:"w-4 h-4 text-blue-600"}),"Dealer Comments"]})}),e.jsx("div",{className:"border rounded-lg p-2.5 lg:p-3 bg-gray-50 max-h-[150px] lg:max-h-[140px] overflow-y-auto",children:e.jsx("p",{className:"text-xs text-gray-700 whitespace-pre-wrap",children:(n==null?void 0:n.dealerComments)||"No comments provided"})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"font-semibold text-sm lg:text-base",children:"Your Decision & Comments"}),e.jsx(ps,{placeholder:"Provide your evaluation comments, approval conditions, or rejection reasons...",value:c,onChange:F=>d(F.target.value),className:"min-h-[150px] lg:min-h-[140px] text-xs lg:text-sm w-full"}),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-2 flex items-start gap-2 lg:col-span-2",children:[e.jsx(xt,{className:"w-3.5 h-3.5 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-xs text-amber-800",children:"Please provide comments before making a decision. Comments are required and will be visible to all participants."})]})]})}),e.jsxs(At,{className:"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end px-6 pb-6 pt-3 lg:pt-4 flex-shrink-0 border-t bg-gray-50",children:[e.jsx(I,{variant:"outline",onClick:R,disabled:m,className:"border-2",children:"Cancel"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(I,{onClick:E,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(xt,{className:"w-4 h-4 mr-2"}),"Reject (Cancel Request)"]})}),e.jsx(I,{onClick:S,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)"]})})]})]})]}),p&&e.jsx(ot,{open:!!p,onOpenChange:()=>y(null),children:e.jsx(nt,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(ct,{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(bt,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(it,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:p.name}),p.type&&e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[p.type," ",p.size&&`• ${(p.size/1024).toFixed(1)} KB`]})]})]}),e.jsx("div",{className:"flex items-center gap-2 flex-wrap mr-2",children:e.jsxs(I,{variant:"outline",size:"sm",onClick:()=>{const F=document.createElement("a");F.href=p.url,F.download=p.name,F.click()},className:"gap-2 h-9",children:[e.jsx(Nt,{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:b?e.jsx("div",{className:"flex items-center justify-center h-full min-h-[70vh]",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Qe,{className:"w-8 h-8 animate-spin text-blue-600 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Loading preview..."})]})}):p.name.toLowerCase().endsWith(".pdf")||(f=p.type)!=null&&f.includes("pdf")?e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("iframe",{src:p.url,className:"w-full h-full rounded-lg border-0",title:p.name,style:{minHeight:"70vh",height:"100%"}})}):p.name.match(/\.(jpg|jpeg|png|gif|webp)$/i)||(T=p.type)!=null&&T.includes("image")?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("img",{src:p.url,alt:p.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"},className:"rounded-lg shadow-lg"})}):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(bt,{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."}),e.jsxs(I,{onClick:()=>{const F=document.createElement("a");F.href=p.url,F.download=p.name,F.click()},className:"gap-2",children:[e.jsx(Nt,{className:"h-4 w-4"}),"Download ",p.name]})]})})]})})})]}):null}async function J2(t){var s;try{const a=await ye.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 Q2(t){var s;try{const a=await ye.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 q2(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 ye.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 eS(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 ye.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 tS(t,s){var a;try{const r=await ye.get(`/dealer-claims/${t}/io/validate`,{params:{ioNumber:s}});return((a=r.data)==null?void 0:a.data)||r.data}catch(r){throw console.error("[DealerClaimAPI] Error validating IO:",r),r}}async function Wl(t,s){var a;try{const r={ioNumber:s.ioNumber,ioRemark:s.ioRemark||""};s.ioAvailableBalance!==void 0&&(r.availableBalance=s.ioAvailableBalance),s.ioBlockedAmount!==void 0&&(r.blockedAmount=s.ioBlockedAmount),s.ioRemainingBalance!==void 0&&(r.remainingBalance=s.ioRemainingBalance);const n=await ye.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 sS(t,s){var a;try{const r=await ye.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}}async function aS(t){var s;try{const a=await ye.post(`/dealer-claims/${t}/credit-note/send`);return((s=a.data)==null?void 0:s.data)||a.data}catch(a){throw console.error("[DealerClaimAPI] Error sending credit note to dealer:",a),a}}const _n=t=>{if(!t)return"";try{return es(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}}},rS=t=>{switch(t){case"approved":return e.jsx(Ce,{className:"w-5 h-5 text-green-600"});case"pending":return e.jsx(Ze,{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(Ze,{className:"w-5 h-5 text-gray-400"})}},nS=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"}},iS=(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",lS=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 oS({request:t,user:s,isInitiator:a,onSkipApprover:r,onRefresh:n}){var ma,Q,ge,X,Ae,Te,$e,ke,Ge,Fe,Xe,ls,Lt,et,Je,ht,zt,Dt,Us,Xs,ua,ha,ft,Oa,$a,Ba,Ua,Va,ss,Cs,wa,kn,Dr,za,Rr,Pr,Ir,Er,Mr,Fr,_r,Lr,Or,$r,rt,ds,sa,aa,Dn,Br,Ur,Vr,zr,Hr,dc,mc,uc,hc,pc,xc,gc,fc,yc,bc,vc,jc,Nc,wc,Cc,Sc,Ac,Tc,kc,Dc,Rc,Pc,Ic,Ec,Mc,Fc,_c,Lc,Oc,$c,Bc,Uc,Vc,zc,Hc,Wc,Gc,Kc,Yc,Zc,Xc;const[i,l]=x.useState(!1),[o,c]=x.useState(!1),[d,m]=x.useState(!1),[u,h]=x.useState(!1),[g,p]=x.useState(!1),[y,b]=x.useState(!1),[j,v]=x.useState(!1),[w,N]=x.useState(null),[C,S]=x.useState(!1),[E,P]=x.useState(null),[R,f]=x.useState([]),[T,F]=x.useState(0);x.useEffect(()=>{(async()=>{if(t!=null&&t.id||t!=null&&t.requestId){const Ee=t.id||t.requestId;try{const xe=await Ts(Ee),ce=(xe==null?void 0:xe.approvalLevels)||(xe==null?void 0:xe.approvals)||[];if(ce&&ce.length>0){const ve=ce.map(ue=>{var _e;return{step:ue.levelNumber||ue.level_number||0,levelNumber:ue.levelNumber||ue.level_number||0,levelName:ue.levelName||ue.level_name,approver:ue.approverName||ue.approver_name||"",approverEmail:(ue.approverEmail||ue.approver_email||"").toLowerCase(),status:((_e=ue.status)==null?void 0:_e.toLowerCase())||"waiting",tatHours:ue.tatHours||ue.tat_hours||24,elapsedHours:ue.elapsedHours||ue.elapsed_hours,approvedAt:ue.actionDate||ue.action_date,comment:ue.comments||ue.comment,levelId:ue.levelId||ue.level_id}}).sort((ue,_e)=>(ue.levelNumber||0)-(_e.levelNumber||0));f(ue=>ue.length!==ve.length||ue.some((qe,Me)=>{const vt=ve[Me];return!vt||qe.levelNumber!==vt.levelNumber||qe.levelName!==vt.levelName||qe.approverEmail!==vt.approverEmail||qe.status!==vt.status})?ve:ue)}else f([])}catch(xe){console.warn("Failed to load approval flows from API:",xe),t!=null&&t.approvalFlow&&t.approvalFlow.length>0&&f(t.approvalFlow)}}else t!=null&&t.approvalFlow&&t.approvalFlow.length>0&&f(t.approvalFlow)})()},[t==null?void 0:t.id,t==null?void 0:t.requestId,t==null?void 0:t.totalLevels,T]),x.useEffect(()=>{if(t!=null&&t.id||t!=null&&t.requestId){const J=t.id||t.requestId;(async()=>{try{const xe=await Ts(J),ce=(xe==null?void 0:xe.approvalLevels)||(xe==null?void 0:xe.approvals)||[];if(ce&&ce.length>0){const ve=ce.map(ue=>{var _e;return{step:ue.levelNumber||ue.level_number||0,levelNumber:ue.levelNumber||ue.level_number||0,levelName:ue.levelName||ue.level_name,approver:ue.approverName||ue.approver_name||"",approverEmail:(ue.approverEmail||ue.approver_email||"").toLowerCase(),status:((_e=ue.status)==null?void 0:_e.toLowerCase())||"waiting",tatHours:ue.tatHours||ue.tat_hours||24,elapsedHours:ue.elapsedHours||ue.elapsed_hours,approvedAt:ue.actionDate||ue.action_date,comment:ue.comments||ue.comment,levelId:ue.levelId||ue.level_id}}).sort((ue,_e)=>(ue.levelNumber||0)-(_e.levelNumber||0));f(ve)}}catch(xe){console.warn("Failed to load approval flows from API:",xe)}})()}},[t==null?void 0:t.currentStep,t==null?void 0:t.totalLevels]);const K=async()=>{F(J=>J+1),await new Promise(J=>setTimeout(J,500)),n==null||n()},B=(J,Ee,xe)=>{if(Ee&&Ee.trim())return Ee.toLowerCase().includes("additional approver"),Ee;const ce={1:"Dealer - Proposal Submission",2:"Requestor Evaluation & Confirmation",3:"Department Lead Approval",4:"Activity Creation",5:"Dealer - Completion Documents",6:"Requestor - Claim Approval",7:"E-Invoice Generation",8:"Credit Note from SAP"};return ce[J]?ce[J]:xe&&xe!=="Unknown"&&xe!=="System"?`Additional Approver - ${xe}`:`Additional Approver - Step ${J}`},U=(J,Ee,xe)=>{if(Ee&&Ee.toLowerCase().includes("additional approver"))return xe&&xe!=="Unknown"&&xe!=="System"?`${xe} will review and approve this request as an additional approver.`:"Additional approver will review and approve this request.";if(Ee&&Ee.trim()){const ue=Ee.toLowerCase();if(ue.includes("dealer")&&ue.includes("proposal"))return"Dealer submits the proposal for the activity with comments including proposal document with requested details, cost break-up, timeline for closure, and other requests";if(ue.includes("requestor")&&(ue.includes("evaluation")||ue.includes("confirmation")))return"Requestor evaluates the request and confirms with comments. Decision point: Confirms? (YES → Continue to Dept Lead / NO → Request is cancelled)";if(ue.includes("department lead"))return"Department Lead approval. Decision point: Approved? (YES → Budget is blocked in the respective IO for the activity / NO → More clarification required → Request is cancelled)";if(ue.includes("activity creation"))return"Activity is created. Activity confirmation email is auto-triggered to dealer / requestor / Lead. IO confirmation to be made.";if(ue.includes("dealer")&&(ue.includes("completion")||ue.includes("documents")))return"Dealer submits the necessary documents upon completion of the activity including document attachments (Zip Folder) and brief description";if(ue.includes("requestor")&&(ue.includes("claim")||ue.includes("approval")))return"Requestor approves the claim in full or can modify the amount. If more information is required, can request additional details from dealer.";if(ue.includes("e-invoice")||ue.includes("invoice generation"))return"E-invoice will be generated through DMS.";if(ue.includes("credit note")||ue.includes("sap"))return"Got credit note from SAP. Review and send to dealer to complete the claim management process."}const ve={1:"Dealer submits the proposal for the activity with comments including proposal document with requested details, cost break-up, timeline for closure, and other requests",2:"Requestor evaluates the request and confirms with comments. Decision point: Confirms? (YES → Continue to Dept Lead / NO → Request is cancelled)",3:"Department Lead approval. Decision point: Approved? (YES → Budget is blocked in the respective IO for the activity / NO → More clarification required → Request is cancelled)",4:"Activity is created. Activity confirmation email is auto-triggered to dealer / requestor / Lead. IO confirmation to be made.",5:"Dealer submits the necessary documents upon completion of the activity including document attachments (Zip Folder) and brief description",6:"Requestor approves the claim in full or can modify the amount. If more information is required, can request additional details from dealer.",7:"E-invoice will be generated through DMS.",8:"Got credit note from SAP. Review and send to dealer to complete the claim management process."};return ve[J]?ve[J]:xe&&xe!=="Unknown"&&xe!=="System"?`${xe} will review and approve this request.`:`Step ${J} approval required.`},D=R.map((J,Ee)=>{var pa,Ps,Ne,xs;const xe=J.levelNumber||J.level_number||J.step||Ee+1,ce=J.levelName||J.level_name,ve=(pa=t==null?void 0:t.approvals)==null?void 0:pa.find(Be=>Be.levelId===J.levelId);let ue;if(ce&&ce.toLowerCase().includes("department lead")||xe===3){const Be=(t==null?void 0:t.internalOrder)||(t==null?void 0:t.internal_order);if(Be!=null&&Be.ioNumber||Be!=null&&Be.io_number){const gs=Be.ioRemark||Be.io_remark||Be.IORemark||Be.IO_Remark||(Be==null?void 0:Be.ioRemark)||(Be==null?void 0:Be.io_remark)||"";ue={ioNumber:Be.ioNumber||Be.io_number||"",ioRemark:gs&&typeof gs=="string"&&gs.trim()?gs.trim():"N/A",blockedAmount:Be.ioBlockedAmount||Be.io_blocked_amount||0,availableBalance:Be.ioAvailableBalance||Be.io_available_balance||0,remainingBalance:Be.ioRemainingBalance||Be.io_remaining_balance||0,organizedBy:((Ps=Be.organizer)==null?void 0:Ps.displayName)||((Ne=Be.organizer)==null?void 0:Ne.name)||Be.organizedBy||J.approver||"N/A",organizedAt:Be.organizedAt||Be.organized_at||J.approvedAt||(t==null?void 0:t.updatedAt)||""}}}let qe;xe===6&&(ve!=null&&ve.dmsDetails?qe={dmsNumber:ve.dmsDetails.dmsNumber||"",dmsRemarks:ve.dmsDetails.dmsRemarks||"",pushedBy:ve.dmsDetails.pushedBy||J.approver,pushedAt:ve.dmsDetails.pushedAt||J.approvedAt||""}:t!=null&&t.dmsNumber&&(qe={dmsNumber:t.dmsNumber||"",dmsRemarks:t.dmsRemarks||((xs=t.dmsDetails)==null?void 0:xs.dmsRemarks)||"",pushedBy:J.approver,pushedAt:J.approvedAt||t.updatedAt||""}));let vt=(J.status||(ve==null?void 0:ve.status)||"waiting").toLowerCase();if((vt==="in-review"||vt==="in_review"||vt==="in review")&&(vt="in_progress"),ve!=null&&ve.status){const Be=ve.status.toLowerCase();Be==="approved"?vt="approved":Be==="rejected"?vt="rejected":(Be==="pending"||Be==="in_progress"||Be==="in-progress")&&(vt="in_progress")}const Ca=vt==="waiting"?0:J.elapsedHours||0,Tt=J.approver||J.approverName||"Unknown";return{step:xe,title:B(xe,ce,Tt),approver:Tt,description:U(xe,ce,Tt)||J.description||"",tatHours:J.tatHours||24,status:vt,comment:J.comment||(ve==null?void 0:ve.comment),approvedAt:J.approvedAt||(ve==null?void 0:ve.timestamp),elapsedHours:Ca,ioDetails:ue,dmsDetails:qe,einvoiceUrl:xe===7?ve==null?void 0:ve.einvoiceUrl:void 0,emailTemplateUrl:(ve==null?void 0:ve.emailTemplateUrl)||void 0}}),A=(t==null?void 0:t.currentLevel)||(t==null?void 0:t.current_level)||(t==null?void 0:t.currentStep),k=D.find(J=>J.step===A),M=k&&(k.status==="pending"||k.status==="in_progress")?k:D.find(J=>{var xe;const Ee=((xe=J.status)==null?void 0:xe.toLowerCase())||"";return Ee==="pending"||Ee==="in_progress"||Ee==="in-review"||Ee==="in_review"}),O=M?M.step:A||(t==null?void 0:t.currentStep)||1,L=((ma=s==null?void 0:s.email)==null?void 0:ma.toLowerCase())||"",Z=((Q=t==null?void 0:t.dealerEmail)==null?void 0:Q.toLowerCase())||((X=(ge=t==null?void 0:t.dealer)==null?void 0:ge.email)==null?void 0:X.toLowerCase())||((Te=(Ae=t==null?void 0:t.claimDetails)==null?void 0:Ae.dealerEmail)==null?void 0:Te.toLowerCase())||((ke=($e=t==null?void 0:t.claimDetails)==null?void 0:$e.dealer_email)==null?void 0:ke.toLowerCase())||"",z=Z&&L===Z,$=R.find(J=>(J.step||J.levelNumber||J.level_number)===O),W=(($==null?void 0:$.approverEmail)||"").toLowerCase(),_=W&&L===W,G=((Fe=(Ge=t==null?void 0:t.initiator)==null?void 0:Ge.email)==null?void 0:Fe.toLowerCase())||((Xe=t==null?void 0:t.initiatorEmail)==null?void 0:Xe.toLowerCase())||"",H=R.find(J=>{const Ee=(J.approverEmail||"").toLowerCase(),xe=(J.levelName||"").toLowerCase();return G&&Ee===G||xe.includes("requestor evaluation")||xe.includes("requestor")&&xe.includes("confirmation")}),V=H&&(H.step||H.levelNumber||H.level_number)||2,ee=H||R.find(J=>(J.step||J.levelNumber||J.level_number)===2),oe=((ee==null?void 0:ee.approverEmail)||"").toLowerCase(),pe=oe&&L===oe,Pe=R.find(J=>(J.step||J.levelNumber||J.level_number)===1),Se=((Pe==null?void 0:Pe.approverEmail)||"").toLowerCase(),ne=Se&&L===Se,de=R.find(J=>(J.levelName||"").toLowerCase().includes("department lead")),le=((de==null?void 0:de.approverEmail)||"").toLowerCase(),fe=le&&L===le,st=async J=>{var Ee,xe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ce=t.id||t.requestId;J.proposalDocument&&await en(J.proposalDocument,ce,"APPROVAL");for(const ue of J.otherDocuments)await en(ue,ce,"SUPPORTING");const ve=J.costBreakup.reduce((ue,_e)=>ue+_e.amount,0);await q2(ce,{proposalDocument:J.proposalDocument||void 0,costBreakup:J.costBreakup.map(ue=>({description:ue.description,amount:ue.amount})),totalEstimatedBudget:ve,expectedCompletionDate:J.expectedCompletionDate,dealerComments:J.dealerComments}),q.success("Proposal submitted successfully"),K()}catch(ce){console.error("Failed to submit proposal:",ce);const ve=((xe=(Ee=ce==null?void 0:ce.response)==null?void 0:Ee.data)==null?void 0:xe.message)||(ce==null?void 0:ce.message)||"Failed to submit proposal. Please try again.";throw q.error(ve),ce}},ae=async J=>{var Ee,xe,ce,ve,ue;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const _e=t.id||t.requestId,qe=await Ts(_e),Me=(qe==null?void 0:qe.approvalLevels)||(qe==null?void 0:qe.approvals)||[],vt=((xe=(Ee=t==null?void 0:t.initiator)==null?void 0:Ee.email)==null?void 0:xe.toLowerCase())||((ce=t==null?void 0:t.initiatorEmail)==null?void 0:ce.toLowerCase())||"",Ht=Me.find(Tt=>{const pa=(Tt.approverEmail||Tt.approver_email||"").toLowerCase(),Ps=(Tt.levelName||Tt.level_name||"").toLowerCase(),Ne=Tt.levelNumber||Tt.level_number;return vt&&pa===vt||Ps.includes("requestor evaluation")||Ps.includes("requestor")&&Ps.includes("confirmation")||Ne===V})||Me.find(Tt=>(Tt.levelNumber||Tt.level_number)===2);if(!(Ht!=null&&Ht.levelId)&&!(Ht!=null&&Ht.level_id))throw new Error("Initiator approval level not found");const Ca=Ht.levelId||Ht.level_id;await Jr(_e,Ca,J),q.success("Proposal approved successfully"),K()}catch(_e){console.error("Failed to approve proposal:",_e);const qe=((ue=(ve=_e==null?void 0:_e.response)==null?void 0:ve.data)==null?void 0:ue.message)||(_e==null?void 0:_e.message)||"Failed to approve proposal. Please try again.";throw q.error(qe),_e}},je=async J=>{var Ee,xe,ce,ve,ue;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const _e=t.id||t.requestId,qe=await Ts(_e),Me=(qe==null?void 0:qe.approvalLevels)||(qe==null?void 0:qe.approvals)||[],vt=((xe=(Ee=t==null?void 0:t.initiator)==null?void 0:Ee.email)==null?void 0:xe.toLowerCase())||((ce=t==null?void 0:t.initiatorEmail)==null?void 0:ce.toLowerCase())||"",Ht=Me.find(Tt=>{const pa=(Tt.approverEmail||Tt.approver_email||"").toLowerCase(),Ps=(Tt.levelName||Tt.level_name||"").toLowerCase(),Ne=Tt.levelNumber||Tt.level_number;return vt&&pa===vt||Ps.includes("requestor evaluation")||Ps.includes("requestor")&&Ps.includes("confirmation")||Ne===V})||Me.find(Tt=>(Tt.levelNumber||Tt.level_number)===2);if(!(Ht!=null&&Ht.levelId)&&!(Ht!=null&&Ht.level_id))throw new Error("Initiator approval level not found");const Ca=Ht.levelId||Ht.level_id;await Qr(_e,Ca,"Proposal rejected by requestor",J),q.success("Proposal rejected. Request has been cancelled."),K()}catch(_e){console.error("Failed to reject proposal:",_e);const qe=((ue=(ve=_e==null?void 0:_e.response)==null?void 0:ve.data)==null?void 0:ue.message)||(_e==null?void 0:_e.message)||"Failed to reject proposal. Please try again.";throw q.error(qe),_e}},gt=async J=>{var Ee,xe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ce=t.id||t.requestId,ve=await Ts(ce),ue=(ve==null?void 0:ve.approvalLevels)||(ve==null?void 0:ve.approvals)||[],_e=ue.find(Me=>(Me.levelName||Me.level_name||"").toLowerCase().includes("department lead"))||ue.find(Me=>(Me.levelNumber||Me.level_number)===3);if(!(_e!=null&&_e.levelId)&&!(_e!=null&&_e.level_id))throw new Error("Department Lead approval level not found");const qe=_e.levelId||_e.level_id;await Wl(ce,{ioNumber:J.ioNumber,ioRemark:J.ioRemark}),await Jr(ce,qe,J.comments),q.success("Request approved and IO organized successfully"),K()}catch(ce){console.error("Failed to approve and organize IO:",ce);const ve=((xe=(Ee=ce==null?void 0:ce.response)==null?void 0:Ee.data)==null?void 0:xe.message)||(ce==null?void 0:ce.message)||"Failed to approve request. Please try again.";throw q.error(ve),ce}},be=async J=>{var Ee,xe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ce=t.id||t.requestId,ve=J.closedExpenses.map(ue=>({description:ue.description,amount:ue.amount}));if(await eS(ce,{activityCompletionDate:J.activityCompletionDate,numberOfParticipants:J.numberOfParticipants,closedExpenses:ve,totalClosedExpenses:J.totalClosedExpenses,completionDocuments:J.completionDocuments,activityPhotos:J.activityPhotos}),J.invoicesReceipts&&J.invoicesReceipts.length>0)for(const ue of J.invoicesReceipts)await en(ue,ce,"SUPPORTING");J.attendanceSheet&&await en(J.attendanceSheet,ce,"SUPPORTING"),q.success("Completion documents submitted successfully"),K()}catch(ce){console.error("Failed to submit completion documents:",ce);const ve=((xe=(Ee=ce==null?void 0:ce.response)==null?void 0:Ee.data)==null?void 0:xe.message)||(ce==null?void 0:ce.message)||"Failed to submit completion documents. Please try again.";throw q.error(ve),ce}},Oe=async J=>{var Ee,xe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ce=t.id||t.requestId,ve=new Date().toISOString().slice(0,10);await sS(ce,{eInvoiceDate:ve}),q.success("Pushed to DMS successfully. E-invoice will be generated automatically."),K()}catch(ce){console.error("[DealerClaimWorkflowTab] Error pushing to DMS:",ce);const ve=((xe=(Ee=ce==null?void 0:ce.response)==null?void 0:Ee.data)==null?void 0:xe.message)||(ce==null?void 0:ce.message)||"Failed to push to DMS. Please try again.";throw q.error(ve),ce}},ut=async J=>{var Ee,xe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ce=t.id||t.requestId,ve=await Ts(ce),ue=(ve==null?void 0:ve.approvalLevels)||(ve==null?void 0:ve.approvals)||[],_e=ue.find(Me=>(Me.levelName||Me.level_name||"").toLowerCase().includes("department lead"))||ue.find(Me=>(Me.levelNumber||Me.level_number)===3);if(!(_e!=null&&_e.levelId)&&!(_e!=null&&_e.level_id))throw new Error("Department Lead approval level not found");const qe=_e.levelId||_e.level_id;await Qr(ce,qe,"Dept Lead rejected - More clarification required",J),q.success("Request rejected. Request has been cancelled."),K()}catch(ce){console.error("Failed to reject request:",ce);const ve=((xe=(Ee=ce==null?void 0:ce.response)==null?void 0:Ee.data)==null?void 0:xe.message)||(ce==null?void 0:ce.message)||"Failed to reject request. Please try again.";throw q.error(ve),ce}},[wt,dt]=x.useState(null);x.useEffect(()=>{if(!t){dt(null);return}(async()=>{try{const Ee=t.id||t.requestId;if(!Ee){dt(null);return}const xe=await Ts(Ee),ce=(xe==null?void 0:xe.documents)||[],ve=t.proposalDetails||(xe==null?void 0:xe.proposalDetails)||{},ue=ce.find(Me=>Me.category==="APPROVAL"||Me.type==="proposal"||Me.documentCategory==="APPROVAL"),_e=ce.filter(Me=>Me.category==="SUPPORTING"||Me.type==="supporting"||Me.documentCategory==="SUPPORTING");let qe=ve.costBreakup||[];if(typeof qe=="string")try{qe=JSON.parse(qe)}catch(Me){console.warn("Failed to parse costBreakup JSON:",Me),qe=[]}Array.isArray(qe)||(qe=[]),dt({proposalDocument:ue?{name:ue.fileName||ue.file_name||ue.name,id:ue.documentId||ue.document_id||ue.id}:void 0,costBreakup:qe,expectedCompletionDate:ve.expectedCompletionDate||"",otherDocuments:_e.map(Me=>({name:Me.fileName||Me.file_name||Me.name,id:Me.documentId||Me.document_id||Me.id})),dealerComments:ve.dealerComments||"",submittedAt:ve.submittedAt})}catch(Ee){console.warn("Failed to load proposal data:",Ee);const xe=t.proposalDetails||{};let ce=xe.costBreakup||[];if(typeof ce=="string")try{ce=JSON.parse(ce)}catch(ve){console.warn("Failed to parse costBreakup JSON:",ve),ce=[]}Array.isArray(ce)||(ce=[]),dt({proposalDocument:void 0,costBreakup:ce,expectedCompletionDate:xe.expectedCompletionDate||"",otherDocuments:[],dealerComments:xe.dealerComments||"",submittedAt:xe.submittedAt})}})()},[t]);const is=((ls=t==null?void 0:t.claimDetails)==null?void 0:ls.dealerName)||((Lt=t==null?void 0:t.dealerInfo)==null?void 0:Lt.name)||"Dealer",Bs=((et=t==null?void 0:t.claimDetails)==null?void 0:et.activityName)||((Je=t==null?void 0:t.activityInfo)==null?void 0:Je.activityName)||(t==null?void 0:t.title)||"Activity";return e.jsxs(e.Fragment,{children:[e.jsxs(te,{children:[e.jsx(me,{children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsxs(he,{className:"flex items-center gap-2",children:[e.jsx(da,{className:"w-5 h-5 text-purple-600"}),"Claim Management Workflow"]}),e.jsx(De,{className:"mt-2",children:"Approval process for dealer claim management"})]})})}),e.jsx(se,{children:e.jsx("div",{className:"space-y-4",children:D.map((J,Ee)=>{var Ht,Ca,Tt,pa,Ps;const xe=((Ht=J.status)==null?void 0:Ht.toLowerCase())||"",ce=xe==="pending"||xe==="in_progress",ve=J.step===O,ue=ce&&ve,_e=J.status==="approved",qe=R.find(Ne=>(Ne.step||Ne.levelNumber||Ne.level_number)===J.step),Me=qe!=null&&qe.levelId?(Ca=t==null?void 0:t.approvals)==null?void 0:Ca.find(Ne=>Ne.levelId===qe.levelId||Ne.level_id===qe.levelId):null,vt=(Me==null?void 0:Me.status)==="PAUSED"||((Tt=t==null?void 0:t.pauseInfo)==null?void 0:Tt.isPaused)&&(((pa=t==null?void 0:t.pauseInfo)==null?void 0:pa.levelId)===(Me==null?void 0:Me.levelId)||((Ps=t==null?void 0:t.pauseInfo)==null?void 0:Ps.level_id)===(Me==null?void 0:Me.levelId));return e.jsx("div",{className:`relative p-5 rounded-lg border-2 transition-all ${iS(J.status,ue)}`,children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:`p-3 rounded-xl ${lS(J.status)}`,children:rS(J.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.jsx("h4",{className:"font-semibold text-gray-900",children:J.title}),e.jsx(ie,{className:nS(J.status),children:J.status.toLowerCase()}),J.emailTemplateUrl&&J.status==="approved"&&e.jsx(I,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-blue-100",title:"View email template",onClick:()=>{N({stepNumber:J.step,stepName:J.title}),v(!0)},children:e.jsx(va,{className:"w-3.5 h-3.5 text-blue-600"})}),J.step===7&&J.einvoiceUrl&&_e&&e.jsx(I,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-green-100",title:"Download E-Invoice",onClick:()=>window.open(J.einvoiceUrl,"_blank"),children:e.jsx(Nt,{className:"w-3.5 h-3.5 text-green-600"})})]}),e.jsx("p",{className:"text-sm text-gray-600",children:J.approver}),e.jsx("p",{className:"text-sm text-gray-500 mt-2 italic",children:J.description})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:["TAT: ",It(J.tatHours)]}),J.elapsedHours&&(ue||_e)&&e.jsxs("p",{className:"text-xs text-gray-600 font-medium",children:["Elapsed: ",It(J.elapsedHours)]})]})]}),J.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:J.comment})}),ue&&(Me==null?void 0:Me.sla)&&e.jsxs("div",{className:"mt-3 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:Me.sla.deadline?qs(Me.sla.deadline,!0):"Not set"})]}),e.jsxs("div",{className:`border rounded-lg p-3 ${vt?"bg-gray-100 border-gray-300":(Me.sla.percentageUsed||0)>=100?"bg-red-50 border-red-200":(Me.sla.percentageUsed||0)>=75?"bg-orange-50 border-orange-200":(Me.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(Ze,{className:"w-4 h-4"}),"Current Approver - Time Tracking ",vt&&"(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:Me.sla.elapsedText||"0 hours"})]}),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:[Me.sla.elapsedText||"0 hours"," / ",It(J.tatHours)," allocated"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[(()=>{const Ne=Me.sla.percentageUsed||0,xs=()=>vt?"bg-gray-500":Ne>=100?"bg-red-600":Ne>=75?"bg-orange-500":Ne>=50?"bg-amber-500":"bg-green-600",Be=()=>vt?"text-gray-600":Ne>=100?"text-red-600":Ne>=75?"text-orange-600":Ne>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(Qs,{value:Ne,className:"h-3",indicatorClassName:xs()}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:`text-xs font-semibold ${Be()}`,children:["Progress: ",Math.min(100,Ne),"% of TAT used"]}),e.jsxs("span",{className:"text-xs font-medium text-gray-700",children:[Me.sla.remainingText||"0 hours"," remaining"]})]})]})})(),Me.sla.status==="breached"&&e.jsxs("p",{className:"text-xs font-semibold text-center text-red-600 flex items-center justify-center gap-1.5",children:[e.jsx(Zn,{className:"w-4 h-4"}),"Deadline Breached"]}),Me.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(hs,{className:"w-4 h-4"}),"Approaching Deadline"]})]})]})]}),(()=>{const Ne=J.levelName||J.level_name;return(Ne&&Ne.toLowerCase().includes("department lead")||J.title&&J.title.toLowerCase().includes("department lead"))&&J.status==="approved"&&J.ioDetails&&J.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(us,{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:J.ioDetails.ioNumber})]}),J.ioDetails.blockedAmount!==void 0&&J.ioDetails.blockedAmount>0&&e.jsxs("div",{className:"flex items-center justify-between pt-1.5 border-t border-blue-100",children:[e.jsx("span",{className:"text-xs text-gray-600",children:"Blocked Amount:"}),e.jsxs("span",{className:"text-sm font-bold text-green-700",children:["₹",J.ioDetails.blockedAmount.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),J.ioDetails.remainingBalance!==void 0&&J.ioDetails.remainingBalance!==null&&e.jsxs("div",{className:"flex items-center justify-between pt-1.5 border-t border-blue-100",children:[e.jsx("span",{className:"text-xs text-gray-600",children:"Remaining Balance:"}),e.jsxs("span",{className:"text-sm font-semibold text-blue-700",children:["₹",J.ioDetails.remainingBalance.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),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:J.ioDetails.ioRemark||"N/A"})]}),e.jsxs("div",{className:"pt-1.5 border-t border-blue-100 text-xs text-gray-500",children:["Organised by ",J.ioDetails.organizedBy||J.approver||"N/A"," on"," ",J.ioDetails.organizedAt?_n(J.ioDetails.organizedAt):J.approvedAt?_n(J.approvedAt):"N/A"]})]})]})})(),J.step===6&&J.dmsDetails&&J.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(ts,{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:J.dmsDetails.dmsNumber})]}),J.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:J.dmsDetails.dmsRemarks})]}),J.dmsDetails.pushedAt&&e.jsxs("div",{className:"pt-1.5 border-t border-purple-100 text-xs text-gray-500",children:["Pushed by ",J.dmsDetails.pushedBy," on"," ",_n(J.dmsDetails.pushedAt)]})]})]}),(()=>{const Ne=R.find(yt=>(yt.step||yt.levelNumber||yt.level_number)===J.step),xs=((Ne==null?void 0:Ne.approverEmail)||"").toLowerCase(),Be=xs&&L===xs,gs=J.step===1||(Ne==null?void 0:Ne.levelName)&&Ne.levelName.toLowerCase().includes("dealer");return ue&&(Be||gs&&z)})()&&e.jsxs("div",{className:"mt-4 flex gap-2",children:[J.step===1&&(z||ne)&&e.jsxs(I,{className:"bg-purple-600 hover:bg-purple-700",onClick:()=>{l(!0)},children:[e.jsx(Rs,{className:"w-4 h-4 mr-2"}),"Submit Proposal"]}),J.step===V&&(a||pe)&&e.jsxs(I,{className:"bg-blue-600 hover:bg-blue-700",onClick:()=>{c(!0)},children:[e.jsx(Ce,{className:"w-4 h-4 mr-2"}),"Review Request"]}),(()=>{const Ne=R.find(Et=>(Et.levelName||"").toLowerCase().includes("department lead"));if(!(Ne&&J.step===(Ne.step||Ne.levelNumber||Ne.level_number)))return null;const Be=((Ne==null?void 0:Ne.approverEmail)||"").toLowerCase();if(!(Be&&L===Be||fe||_))return null;const at=(t==null?void 0:t.internalOrder)||(t==null?void 0:t.internal_order),yt=(at==null?void 0:at.ioNumber)||(at==null?void 0:at.io_number)||(t==null?void 0:t.ioNumber)||"",Yt=yt&&yt.trim()!=="";return e.jsxs("div",{className:"space-y-1",children:[e.jsxs(I,{className:"bg-green-600 hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>{m(!0)},disabled:!Yt,children:[e.jsx(Ce,{className:"w-4 h-4 mr-2"}),"Approve and Organise IO"]}),!Yt&&e.jsx("p",{className:"text-xs text-amber-600",children:"Please add an IO number in the IO tab before approving this step."})]})})(),(()=>{const Ne=R.find(yt=>(yt.step||yt.levelNumber||yt.level_number)===J.step),xs=((Ne==null?void 0:Ne.approverEmail)||"").toLowerCase(),Be=z&&xs===Z,gs=((Ne==null?void 0:Ne.levelName)||J.title||"").toLowerCase(),at=gs.includes("dealer completion")||gs.includes("completion documents");return Be&&at})()&&e.jsxs(I,{className:"bg-purple-600 hover:bg-purple-700",onClick:()=>{h(!0)},children:[e.jsx(Rs,{className:"w-4 h-4 mr-2"}),"Upload Completion Docs"]}),(()=>{const Ne=R.find(at=>{const yt=(at.levelName||"").toLowerCase();return yt.includes("requestor claim")||yt.includes("requestor - claim")});if(!(Ne&&J.step===(Ne.step||Ne.levelNumber||Ne.level_number)))return null;const Be=((Ne==null?void 0:Ne.approverEmail)||"").toLowerCase();return a||Be&&L===Be?e.jsxs(I,{className:"bg-indigo-600 hover:bg-indigo-700",onClick:()=>{p(!0)},children:[e.jsx(ts,{className:"w-4 h-4 mr-2"}),"Push to DMS"]}):null})(),J.step===8&&(()=>{var yt;const Ne=R.find(Yt=>(Yt.step||Yt.levelNumber||Yt.level_number)===8),xs=((Ne==null?void 0:Ne.approverEmail)||"").toLowerCase(),Be=xs&&L===xs,gs=((yt=s==null?void 0:s.role)==null?void 0:yt.toUpperCase())||"";return Be||(gs==="FINANCE"||gs==="ADMIN")})()&&e.jsxs(I,{className:"bg-green-600 hover:bg-green-700",onClick:()=>{b(!0)},children:[e.jsx(us,{className:"w-4 h-4 mr-2"}),"View & Send Credit Note"]}),(()=>{const Ne=R.find(at=>(at.step||at.levelNumber||at.level_number)===J.step),Be=((Ne==null?void 0:Ne.levelName)||J.title||"").toLowerCase().includes("additional approver"),gs=J.step===1||J.step===V||(()=>{const at=R.find(yt=>(yt.levelName||"").toLowerCase().includes("department lead"));return at&&J.step===(at.step||at.levelNumber||at.level_number)})()||(()=>{const at=R.find(Ti=>(Ti.step||Ti.levelNumber||Ti.level_number)===J.step),yt=((at==null?void 0:at.approverEmail)||"").toLowerCase(),Yt=z&&yt===Z,Et=((at==null?void 0:at.levelName)||J.title||"").toLowerCase(),xa=Et.includes("dealer completion")||Et.includes("completion documents");return Yt&&xa})()||(()=>{const at=R.find(yt=>{const Yt=(yt.levelName||"").toLowerCase();return Yt.includes("requestor claim")||Yt.includes("requestor - claim")});return at&&J.step===(at.step||at.levelNumber||at.level_number)})()||J.step===8;if(Be||!gs){const at=(Ne==null?void 0:Ne.levelId)||(Ne==null?void 0:Ne.level_id);if(at){const yt=(Ne==null?void 0:Ne.levelName)||(Ne==null?void 0:Ne.level_name)||J.title||"Approval Level",Yt=(Ne==null?void 0:Ne.approverName)||(Ne==null?void 0:Ne.approver_name)||J.approver||"Approver";return e.jsxs(I,{className:"bg-blue-600 hover:bg-blue-700",onClick:()=>{P({levelId:at,levelName:yt,approverName:Yt}),S(!0)},children:[e.jsx(Ce,{className:"w-4 h-4 mr-2"}),"Review Request"]})}return e.jsxs(e.Fragment,{children:[e.jsxs(I,{className:"bg-green-600 hover:bg-green-700",onClick:async()=>{var yt,Yt;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Et=t.id||t.requestId;if(!at){q.error("Approval level not found");return}await Jr(Et,at,""),q.success("Request approved successfully"),K()}catch(Et){console.error("Failed to approve:",Et);const xa=((Yt=(yt=Et==null?void 0:Et.response)==null?void 0:yt.data)==null?void 0:Yt.message)||(Et==null?void 0:Et.message)||"Failed to approve request. Please try again.";q.error(xa)}},children:[e.jsx(Ce,{className:"w-4 h-4 mr-2"}),"Approve"]}),e.jsxs(I,{variant:"destructive",onClick:async()=>{var yt,Yt;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Et=t.id||t.requestId;if(!at){q.error("Approval level not found");return}const xa=prompt("Please provide a reason for rejection:");if(xa===null)return;await Qr(Et,at,"Request rejected",xa),q.success("Request rejected successfully"),K()}catch(Et){console.error("Failed to reject:",Et);const xa=((Yt=(yt=Et==null?void 0:Et.response)==null?void 0:yt.data)==null?void 0:Yt.message)||(Et==null?void 0:Et.message)||"Failed to reject request. Please try again.";q.error(xa)}},children:[e.jsx(xt,{className:"w-4 h-4 mr-2"}),"Reject"]})]})}return null})()]}),J.approvedAt&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Approved on ",_n(J.approvedAt)]})]})]})},Ee)})})})]}),e.jsx(G2,{isOpen:i,onClose:()=>l(!1),onSubmit:st,dealerName:is,activityName:Bs,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId)}),e.jsx(X2,{isOpen:o,onClose:()=>{c(!1)},onApprove:ae,onReject:je,proposalData:wt,dealerName:is,activityName:Bs,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId)}),e.jsx(K2,{isOpen:d,onClose:()=>m(!1),onApprove:gt,onReject:ut,requestTitle:t==null?void 0:t.title,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),preFilledIONumber:((ht=t==null?void 0:t.internalOrder)==null?void 0:ht.ioNumber)||((zt=t==null?void 0:t.internalOrder)==null?void 0:zt.io_number)||((Dt=t==null?void 0:t.internal_order)==null?void 0:Dt.ioNumber)||((Us=t==null?void 0:t.internal_order)==null?void 0:Us.io_number)||void 0,preFilledIORemark:((Xs=t==null?void 0:t.internalOrder)==null?void 0:Xs.ioRemark)||((ua=t==null?void 0:t.internalOrder)==null?void 0:ua.io_remark)||((ha=t==null?void 0:t.internal_order)==null?void 0:ha.ioRemark)||((ft=t==null?void 0:t.internal_order)==null?void 0:ft.io_remark)||void 0,preFilledBlockedAmount:((Oa=t==null?void 0:t.internalOrder)==null?void 0:Oa.ioBlockedAmount)||(($a=t==null?void 0:t.internalOrder)==null?void 0:$a.io_blocked_amount)||((Ba=t==null?void 0:t.internal_order)==null?void 0:Ba.ioBlockedAmount)||((Ua=t==null?void 0:t.internal_order)==null?void 0:Ua.io_blocked_amount)||void 0,preFilledRemainingBalance:((Va=t==null?void 0:t.internalOrder)==null?void 0:Va.ioRemainingBalance)||((ss=t==null?void 0:t.internalOrder)==null?void 0:ss.io_remaining_balance)||((Cs=t==null?void 0:t.internal_order)==null?void 0:Cs.ioRemainingBalance)||((wa=t==null?void 0:t.internal_order)==null?void 0:wa.io_remaining_balance)||void 0}),e.jsx(W2,{isOpen:u,onClose:()=>h(!1),onSubmit:be,dealerName:is,activityName:Bs,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId)}),e.jsx(Y2,{isOpen:g,onClose:()=>p(!1),onPush:Oe,completionDetails:{activityCompletionDate:((kn=t==null?void 0:t.completionDetails)==null?void 0:kn.activityCompletionDate)||((Dr=t==null?void 0:t.completionDetails)==null?void 0:Dr.activity_completion_date),numberOfParticipants:((za=t==null?void 0:t.completionDetails)==null?void 0:za.numberOfParticipants)||((Rr=t==null?void 0:t.completionDetails)==null?void 0:Rr.number_of_participants),closedExpenses:(t==null?void 0:t.completionExpenses)||(t==null?void 0:t.completion_expenses)||((Pr=t==null?void 0:t.completionDetails)==null?void 0:Pr.closedExpenses)||((Ir=t==null?void 0:t.completionDetails)==null?void 0:Ir.closed_expenses),totalClosedExpenses:((Er=t==null?void 0:t.budgetTracking)==null?void 0:Er.closedExpenses)||((Mr=t==null?void 0:t.budgetTracking)==null?void 0:Mr.closed_expenses)||((Fr=t==null?void 0:t.completionDetails)==null?void 0:Fr.totalClosedExpenses)||((_r=t==null?void 0:t.completionDetails)==null?void 0:_r.total_closed_expenses),completionDescription:((Lr=t==null?void 0:t.completionDetails)==null?void 0:Lr.completionDescription)||((Or=t==null?void 0:t.completionDetails)==null?void 0:Or.completion_description)},ioDetails:{ioNumber:(($r=t==null?void 0:t.internalOrder)==null?void 0:$r.ioNumber)||((rt=t==null?void 0:t.internalOrder)==null?void 0:rt.io_number)||((ds=t==null?void 0:t.internal_order)==null?void 0:ds.ioNumber)||((sa=t==null?void 0:t.internal_order)==null?void 0:sa.io_number),blockedAmount:((aa=t==null?void 0:t.internalOrder)==null?void 0:aa.ioBlockedAmount)||((Dn=t==null?void 0:t.internalOrder)==null?void 0:Dn.io_blocked_amount)||((Br=t==null?void 0:t.internal_order)==null?void 0:Br.ioBlockedAmount)||((Ur=t==null?void 0:t.internal_order)==null?void 0:Ur.io_blocked_amount),availableBalance:((Vr=t==null?void 0:t.internalOrder)==null?void 0:Vr.ioAvailableBalance)||((zr=t==null?void 0:t.internalOrder)==null?void 0:zr.io_available_balance)||((Hr=t==null?void 0:t.internal_order)==null?void 0:Hr.ioAvailableBalance)||((dc=t==null?void 0:t.internal_order)==null?void 0:dc.io_available_balance),remainingBalance:((mc=t==null?void 0:t.internalOrder)==null?void 0:mc.ioRemainingBalance)||((uc=t==null?void 0:t.internalOrder)==null?void 0:uc.io_remaining_balance)||((hc=t==null?void 0:t.internal_order)==null?void 0:hc.ioRemainingBalance)||((pc=t==null?void 0:t.internal_order)==null?void 0:pc.io_remaining_balance)},requestTitle:t==null?void 0:t.title,requestNumber:(t==null?void 0:t.requestNumber)||(t==null?void 0:t.request_number)||(t==null?void 0:t.id)}),e.jsx(H2,{isOpen:y,onClose:()=>b(!1),onDownload:async()=>{q.info("Download functionality will be implemented")},onSendToDealer:async()=>{var J,Ee;try{const xe=(t==null?void 0:t.requestId)||(t==null?void 0:t.id);if(!xe){q.error("Request ID not found");return}await aS(xe),q.success("Credit note sent to dealer successfully. Step 8 has been approved."),n&&n()}catch(xe){console.error("Failed to send credit note to dealer:",xe);const ce=((Ee=(J=xe==null?void 0:xe.response)==null?void 0:J.data)==null?void 0:Ee.message)||(xe==null?void 0:xe.message)||"Failed to send credit note to dealer";q.error(ce)}},creditNoteData:{creditNoteNumber:((xc=t==null?void 0:t.creditNote)==null?void 0:xc.creditNoteNumber)||((gc=t==null?void 0:t.creditNote)==null?void 0:gc.credit_note_number)||((yc=(fc=t==null?void 0:t.claimDetails)==null?void 0:fc.creditNote)==null?void 0:yc.creditNoteNumber)||((bc=t==null?void 0:t.claimDetails)==null?void 0:bc.creditNoteNumber)||((vc=t==null?void 0:t.claimDetails)==null?void 0:vc.credit_note_number),creditNoteDate:((jc=t==null?void 0:t.creditNote)==null?void 0:jc.creditNoteDate)||((Nc=t==null?void 0:t.creditNote)==null?void 0:Nc.credit_note_date)||((Cc=(wc=t==null?void 0:t.claimDetails)==null?void 0:wc.creditNote)==null?void 0:Cc.creditNoteDate)||((Sc=t==null?void 0:t.claimDetails)==null?void 0:Sc.creditNoteDate)||((Ac=t==null?void 0:t.claimDetails)==null?void 0:Ac.credit_note_date),creditNoteAmount:(Tc=t==null?void 0:t.creditNote)!=null&&Tc.creditNoteAmount?Number((kc=t==null?void 0:t.creditNote)==null?void 0:kc.creditNoteAmount):(Dc=t==null?void 0:t.creditNote)!=null&&Dc.credit_note_amount?Number((Rc=t==null?void 0:t.creditNote)==null?void 0:Rc.credit_note_amount):(Ic=(Pc=t==null?void 0:t.claimDetails)==null?void 0:Pc.creditNote)!=null&&Ic.creditNoteAmount?Number((Mc=(Ec=t==null?void 0:t.claimDetails)==null?void 0:Ec.creditNote)==null?void 0:Mc.creditNoteAmount):(Fc=t==null?void 0:t.claimDetails)!=null&&Fc.creditNoteAmount?Number((_c=t==null?void 0:t.claimDetails)==null?void 0:_c.creditNoteAmount):(Lc=t==null?void 0:t.claimDetails)!=null&&Lc.credit_note_amount?Number((Oc=t==null?void 0:t.claimDetails)==null?void 0:Oc.credit_note_amount):void 0,status:(($c=t==null?void 0:t.creditNote)==null?void 0:$c.status)||((Uc=(Bc=t==null?void 0:t.claimDetails)==null?void 0:Bc.creditNote)==null?void 0:Uc.status)||((Vc=t==null?void 0:t.creditNote)!=null&&Vc.creditNoteNumber?"CONFIRMED":"PENDING")},dealerInfo:{dealerName:((zc=t==null?void 0:t.claimDetails)==null?void 0:zc.dealerName)||((Hc=t==null?void 0:t.claimDetails)==null?void 0:Hc.dealer_name),dealerCode:((Wc=t==null?void 0:t.claimDetails)==null?void 0:Wc.dealerCode)||((Gc=t==null?void 0:t.claimDetails)==null?void 0:Gc.dealer_code),dealerEmail:((Kc=t==null?void 0:t.claimDetails)==null?void 0:Kc.dealerEmail)||((Yc=t==null?void 0:t.claimDetails)==null?void 0:Yc.dealer_email)},activityName:((Zc=t==null?void 0:t.claimDetails)==null?void 0:Zc.activityName)||((Xc=t==null?void 0:t.claimDetails)==null?void 0:Xc.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}),e.jsx(Z2,{isOpen:j,onClose:()=>{v(!1),N(null)},stepNumber:(w==null?void 0:w.stepNumber)||4,stepName:(w==null?void 0:w.stepName)||"Activity Creation",requestNumber:(t==null?void 0:t.requestNumber)||(t==null?void 0:t.id)||(t==null?void 0:t.request_number),recipientEmail:"system@royalenfield.com"}),E&&e.jsx(z2,{isOpen:C,onClose:()=>{S(!1),P(null)},onApprove:async J=>{var Ee,xe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ce=t.id||t.requestId,ve=E.levelId;if(!ve){q.error("Approval level not found");return}await Jr(ce,ve,J),q.success("Request approved successfully"),K(),S(!1),P(null)}catch(ce){console.error("Failed to approve:",ce);const ve=((xe=(Ee=ce==null?void 0:ce.response)==null?void 0:Ee.data)==null?void 0:xe.message)||(ce==null?void 0:ce.message)||"Failed to approve request. Please try again.";throw q.error(ve),ce}},onReject:async J=>{var Ee,xe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ce=t.id||t.requestId,ve=E.levelId;if(!ve){q.error("Approval level not found");return}await Qr(ce,ve,"Request rejected",J),q.success("Request rejected successfully"),K(),S(!1),P(null)}catch(ce){console.error("Failed to reject:",ce);const ve=((xe=(Ee=ce==null?void 0:ce.response)==null?void 0:Ee.data)==null?void 0:xe.message)||(ce==null?void 0:ce.message)||"Failed to reject request. Please try again.";throw q.error(ve),ce}},requestTitle:(t==null?void 0:t.title)||"Request",requestDescription:(t==null?void 0:t.description)||"",requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),levelName:E.levelName,approverName:E.approverName})]})}function cS({request:t,apiRequest:s,onRefresh:a}){const{user:r}=Kt(),n=(s==null?void 0:s.requestId)||(t==null?void 0:t.requestId),i=(s==null?void 0:s.internalOrder)||(s==null?void 0:s.internal_order)||null,l=(i==null?void 0:i.ioNumber)||(i==null?void 0:i.io_number)||(t==null?void 0:t.ioNumber)||"",o=(i==null?void 0:i.ioRemark)||(i==null?void 0:i.io_remark)||"",c=(i==null?void 0:i.ioBlockedAmount)||(i==null?void 0:i.io_blocked_amount)||0,d=(i==null?void 0:i.ioAvailableBalance)||(i==null?void 0:i.io_available_balance)||0,m=(i==null?void 0:i.ioRemainingBalance)||(i==null?void 0:i.io_remaining_balance)||0,u=(i==null?void 0:i.sapDocumentNumber)||(i==null?void 0:i.sap_document_number)||"",h=(i==null?void 0:i.organizer)||null,[g,p]=x.useState(l),[y,b]=x.useState(o),[j,v]=x.useState(!1),[w,N]=x.useState(null),[C,S]=x.useState(""),[E,P]=x.useState(null),[R,f]=x.useState(!1),T=300,F=y.length;x.useEffect(()=>{if(i&&l){const D=Number(d)||0,A=(h==null?void 0:h.displayName)||(h==null?void 0:h.display_name)||(h==null?void 0:h.name)||(h!=null&&h.firstName&&(h!=null&&h.lastName)?`${h.firstName} ${h.lastName}`.trim():null)||(h==null?void 0:h.email)||"Unknown User";if(p(l),b(o),c>0){const k=Number(c)||0,M=Number(m)||0,O=D-k;console.log("[IOTab] Loading existing IO block:",{availableBeforeBlock:D,blockedAmount:k,expectedRemaining:O,backendRemaining:M}),Math.abs(M-O)>.01&&console.warn("[IOTab] ⚠️ Remaining balance calculation issue detected!",{availableBalance:D,blockedAmount:k,expectedRemaining:O,backendRemaining:M,difference:M-O}),P({ioNumber:l,blockedAmount:k,availableBalance:D,remainingBalance:M,blockedDate:i.organizedAt||i.organized_at||new Date().toISOString(),blockedBy:A,sapDocumentNumber:u,ioRemark:o,status:i.status==="BLOCKED"?"blocked":i.status==="RELEASED"?"released":"blocked"}),D>0&&N(D)}}},[i,l,o,c,d,m,u,h]);const K=async()=>{var D,A;if(!g.trim()){q.error("Please enter an IO number");return}if(!n){q.error("Request ID not found");return}v(!0);try{const k=await tS(n,g.trim());k.isValid&&k.availableBalance>0?(N(k.availableBalance),S(String(k.availableBalance)),q.success(`IO fetched from SAP. Available balance: ₹${k.availableBalance.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`)):(q.error("Invalid IO number or no available balance found"),N(null),S(""))}catch(k){console.error("Failed to fetch IO budget:",k);const M=((A=(D=k==null?void 0:k.response)==null?void 0:D.data)==null?void 0:A.message)||(k==null?void 0:k.message)||"Failed to validate IO number or fetch budget from SAP";q.error(M),N(null)}finally{v(!1)}},B=async()=>{var D,A;if(!g.trim()){q.error("Please enter an IO number");return}if(!y.trim()){q.error("Please enter an IO remark");return}if(!n){q.error("Request ID not found");return}f(!0);try{const k={ioNumber:g.trim(),ioRemark:y.trim()};await Wl(n,k),q.success("IO details saved successfully"),a==null||a()}catch(k){console.error("Failed to save IO details:",k);const M=((A=(D=k==null?void 0:k.response)==null?void 0:D.data)==null?void 0:A.message)||(k==null?void 0:k.message)||"Failed to save IO details";q.error(M)}finally{f(!1)}},U=async()=>{var k,M;if(!g.trim()||w===null){q.error("Please fetch IO amount first");return}if(!y.trim()){q.error("Please enter IO remark before blocking the amount");return}if(!n){q.error("Request ID not found");return}const D=parseFloat(C);if(!C||isNaN(D)||D<=0){q.error("Please enter a valid amount to block");return}const A=Math.round(D*100)/100;if(A>w){q.error("Amount to block exceeds available IO budget");return}console.log("[IOTab] Blocking budget:",{ioNumber:g.trim(),originalInput:C,parsedAmount:D,roundedAmount:A,fetchedAmount:w,calculatedRemaining:w-A}),f(!0);try{const O={ioNumber:g.trim(),ioRemark:y.trim(),ioAvailableBalance:w,ioBlockedAmount:A,ioRemainingBalance:w-A};console.log("[IOTab] Sending to backend:",O),await Wl(n,O);const L=await Q2(n),Z=(L==null?void 0:L.internalOrder)||(L==null?void 0:L.internal_order);if(Z){const z=Number(Z.ioBlockedAmount||Z.io_blocked_amount||A),$=Number(Z.ioRemainingBalance||Z.io_remaining_balance||0),W=w-z;console.log("[IOTab] Blocking result:",{sentAmount:A,savedBlockedAmount:z,availableBalance:w,expectedRemaining:W,backendRemaining:$,difference:z-A,remainingDifference:w-$}),Math.abs(z-A)>.01&&console.warn("[IOTab] ⚠️ Amount mismatch! Sent:",A,"Saved:",z),Math.abs($-W)>.01&&console.warn("[IOTab] ⚠️ Remaining balance calculation issue detected!",{availableBalance:w,blockedAmount:z,expectedRemaining:W,backendRemaining:$,difference:$-W});const _=r,G=(_==null?void 0:_.displayName)||(_==null?void 0:_.display_name)||(_==null?void 0:_.name)||(_!=null&&_.firstName&&(_!=null&&_.lastName)?`${_.firstName} ${_.lastName}`.trim():null)||(_==null?void 0:_.email)||"Current User",H=Z.ioRemark||Z.io_remark||y.trim(),V={ioNumber:Z.ioNumber||Z.io_number||g,blockedAmount:z,availableBalance:w,remainingBalance:$,blockedDate:Z.organizedAt||Z.organized_at||new Date().toISOString(),blockedBy:G,sapDocumentNumber:Z.sapDocumentNumber||Z.sap_document_number||"",ioRemark:H,status:"blocked"};P(V),S(""),q.success("IO budget blocked successfully in SAP"),a==null||a()}else q.error("IO blocked but failed to fetch updated details"),a==null||a()}catch(O){console.error("Failed to block IO budget:",O);const L=((M=(k=O==null?void 0:O.response)==null?void 0:k.data)==null?void 0:M.message)||(O==null?void 0:O.message)||"Failed to block IO budget in SAP";q.error(L)}finally{f(!1)}};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(te,{children:[e.jsxs(me,{children:[e.jsxs(he,{className:"flex items-center gap-2",children:[e.jsx(Pa,{className:"w-5 h-5 text-[#2d4a3e]"}),"IO Budget Management"]}),e.jsx(De,{children:"Enter IO number to fetch available budget from SAP"})]}),e.jsxs(se,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(re,{htmlFor:"ioNumber",children:"IO Number *"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Re,{id:"ioNumber",placeholder:"Enter IO number (e.g., IO-2024-12345)",value:g,onChange:D=>p(D.target.value),disabled:j||!!E,className:"flex-1"}),e.jsxs(I,{onClick:K,disabled:!g.trim()||j||!!E,className:"bg-[#2d4a3e] hover:bg-[#1f3329]",children:[e.jsx(Nt,{className:"w-4 h-4 mr-2"}),j?"Fetching...":"Fetch Amount"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"ioRemark",className:"text-sm font-medium text-gray-900",children:["IO Remark ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ps,{id:"ioRemark",placeholder:"Enter remarks about IO organization (required before blocking amount)",value:y,onChange:D=>{const A=D.target.value;A.length<=T&&b(A)},rows:3,disabled:!!E,className:`bg-white text-sm min-h-[80px] resize-none ${w!==null&&!y.trim()&&!E?"border-red-300 focus:border-red-500 focus:ring-red-500":""}`,required:!0}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("div",{children:w!==null&&!y.trim()&&!E&&e.jsx("p",{className:"text-xs text-red-600",children:"IO remark is mandatory before blocking the amount"})}),e.jsx("div",{className:"text-xs text-gray-600",children:e.jsxs("span",{children:[F,"/",T]})})]})]}),!w&&!E&&g.trim()&&e.jsx(I,{onClick:B,disabled:R||!g.trim()||!y.trim(),variant:"outline",className:"w-full border-[#2d4a3e] text-[#2d4a3e] hover:bg-[#2d4a3e] hover:text-white",children:R?"Saving...":"Save IO Details"}),w!==null&&!E&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"bg-green-50 border-2 border-green-200 rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-600 uppercase tracking-wide mb-1",children:"Available Amount"}),e.jsxs("p",{className:"text-2xl font-bold text-green-700",children:["₹",w.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),e.jsx(Ce,{className:"w-8 h-8 text-green-600"})]}),e.jsxs("div",{className:"mt-3 pt-3 border-t border-green-200",children:[e.jsxs("p",{className:"text-xs text-gray-600",children:[e.jsx("strong",{children:"IO Number:"})," ",g]}),e.jsxs("p",{className:"text-xs text-gray-600 mt-1",children:[e.jsx("strong",{children:"Fetched from:"})," SAP System"]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(re,{htmlFor:"blockAmount",children:"Amount to Block *"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-500",children:"₹"}),e.jsx(Re,{type:"number",id:"blockAmount",placeholder:"Enter amount to block",min:"0",step:"0.01",value:C,onChange:D=>S(D.target.value),className:"pl-8"})]})]}),e.jsxs(I,{onClick:U,disabled:R||!C||parseFloat(C)<=0||parseFloat(C)>w||!y.trim(),className:"w-full bg-[#2d4a3e] hover:bg-[#1f3329]",children:[e.jsx(Bt,{className:"w-4 h-4 mr-2"}),R?"Blocking in SAP...":"Block IO in SAP"]}),!y.trim()&&e.jsx("p",{className:"text-xs text-red-600 mt-1",children:"Please enter IO remark before blocking the amount"})]})]})]}),e.jsxs(te,{children:[e.jsxs(me,{children:[e.jsxs(he,{className:"flex items-center gap-2",children:[e.jsx(Ce,{className:"w-5 h-5 text-green-600"}),"IO Blocked Details"]}),e.jsx(De,{children:"Details of IO blocked in SAP system"})]}),e.jsx(se,{children:E?e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"bg-green-50 border-2 border-green-500 rounded-lg p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ce,{className:"w-6 h-6 text-green-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-green-900",children:"IO Blocked Successfully"}),e.jsx("p",{className:"text-sm text-green-700 mt-1",children:"Budget has been reserved in SAP system"})]})]})}),e.jsxs("div",{className:"border rounded-lg divide-y",children:[e.jsxs("div",{className:"p-4",children:[e.jsx("p",{className:"text-xs text-gray-500 uppercase tracking-wide mb-1",children:"IO Number"}),e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:E.ioNumber})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("p",{className:"text-xs text-gray-500 uppercase tracking-wide mb-1",children:"SAP Document Number"}),e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:E.sapDocumentNumber||"N/A"})]}),E.ioRemark&&e.jsxs("div",{className:"p-4",children:[e.jsx("p",{className:"text-xs text-gray-500 uppercase tracking-wide mb-1",children:"IO Remark"}),e.jsx("p",{className:"text-sm font-medium text-gray-900 whitespace-pre-wrap",children:E.ioRemark})]}),e.jsxs("div",{className:"p-4 bg-green-50",children:[e.jsx("p",{className:"text-xs text-gray-500 uppercase tracking-wide mb-1",children:"Blocked Amount"}),e.jsxs("p",{className:"text-xl font-bold text-green-700",children:["₹",E.blockedAmount.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("p",{className:"text-xs text-gray-500 uppercase tracking-wide mb-1",children:"Available Amount (Before Block)"}),e.jsxs("p",{className:"text-sm font-medium text-gray-900",children:["₹",E.availableBalance.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),e.jsxs("div",{className:"p-4 bg-blue-50",children:[e.jsx("p",{className:"text-xs text-gray-500 uppercase tracking-wide mb-1",children:"Remaining Amount (After Block)"}),e.jsxs("p",{className:"text-sm font-bold text-blue-700",children:["₹",E.remainingBalance.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("p",{className:"text-xs text-gray-500 uppercase tracking-wide mb-1",children:"Blocked By"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:E.blockedBy})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("p",{className:"text-xs text-gray-500 uppercase tracking-wide mb-1",children:"Blocked At"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:new Date(E.blockedDate).toLocaleString("en-IN",{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",hour12:!0})})]}),e.jsxs("div",{className:"p-4 bg-gray-50",children:[e.jsx("p",{className:"text-xs text-gray-500 uppercase tracking-wide mb-1",children:"Status"}),e.jsxs(ie,{className:"bg-green-100 text-green-800 border-green-200",children:[e.jsx(Ce,{className:"w-3 h-3 mr-1"}),"Blocked"]})]})]})]}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Pa,{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"})]})})]})]})}var Ye=function(){return Ye=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},Ye.apply(this,arguments)};function dS(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 ux(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 Sn(t){return t.mode==="multiple"}function An(t){return t.mode==="range"}function Ai(t){return t.mode==="single"}var mS={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 uS(t,s){return Ie(t,"LLLL y",s)}function hS(t,s){return Ie(t,"d",s)}function pS(t,s){return Ie(t,"LLLL",s)}function xS(t){return"".concat(t)}function gS(t,s){return Ie(t,"cccccc",s)}function fS(t,s){return Ie(t,"yyyy",s)}var yS=Object.freeze({__proto__:null,formatCaption:uS,formatDay:hS,formatMonthCaption:pS,formatWeekNumber:xS,formatWeekdayName:gS,formatYearCaption:fS}),bS=function(t,s,a){return Ie(t,"do MMMM (EEEE)",a)},vS=function(){return"Month: "},jS=function(){return"Go to next month"},NS=function(){return"Go to previous month"},wS=function(t,s){return Ie(t,"cccc",s)},CS=function(t){return"Week n. ".concat(t)},SS=function(){return"Year: "},AS=Object.freeze({__proto__:null,labelDay:bS,labelMonthDropdown:vS,labelNext:jS,labelPrevious:NS,labelWeekNumber:CS,labelWeekday:wS,labelYearDropdown:SS});function TS(){var t="buttons",s=mS,a=ef,r={},n={},i=1,l={},o=new Date;return{captionLayout:t,classNames:s,formatters:yS,labels:AS,locale:a,modifiersClassNames:r,modifiers:n,numberOfMonths:i,styles:l,today:o,mode:"default"}}function kS(t){var s=t.fromYear,a=t.toYear,r=t.fromMonth,n=t.toMonth,i=t.fromDate,l=t.toDate;return r?i=_s(r):s&&(i=new Date(s,0,1)),n?l=Xl(n):a&&(l=new Date(a,11,31)),{fromDate:i?Qc(i):void 0,toDate:l?Qc(l):void 0}}var hx=x.createContext(void 0);function DS(t){var s,a=t.initialProps,r=TS(),n=kS(a),i=n.fromDate,l=n.toDate,o=(s=a.captionLayout)!==null&&s!==void 0?s:r.captionLayout;o!=="buttons"&&(!i||!l)&&(o="buttons");var c;(Ai(a)||Sn(a)||An(a))&&(c=a.onSelect);var d=Ye(Ye(Ye({},r),a),{captionLayout:o,classNames:Ye(Ye({},r.classNames),a.classNames),components:Ye({},a.components),formatters:Ye(Ye({},r.formatters),a.formatters),fromDate:i,labels:Ye(Ye({},r.labels),a.labels),mode:a.mode||r.mode,modifiers:Ye(Ye({},r.modifiers),a.modifiers),modifiersClassNames:Ye(Ye({},r.modifiersClassNames),a.modifiersClassNames),onSelect:c,styles:Ye(Ye({},r.styles),a.styles),toDate:l});return e.jsx(hx.Provider,{value:d,children:t.children})}function kt(){var t=x.useContext(hx);if(!t)throw new Error("useDayPicker must be used within a DayPickerProvider.");return t}function px(t){var s=kt(),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 RS(t){return e.jsx("svg",Ye({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 xx(t){var s,a,r=t.onChange,n=t.value,i=t.children,l=t.caption,o=t.className,c=t.style,d=kt(),m=(a=(s=d.components)===null||s===void 0?void 0:s.IconDropdown)!==null&&a!==void 0?a:RS;return e.jsxs("div",{className:o,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:[l,e.jsx(m,{className:d.classNames.dropdown_icon,style:d.styles.dropdown_icon})]})]})}function PS(t){var s,a=kt(),r=a.fromDate,n=a.toDate,i=a.styles,l=a.locale,o=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(lf(r,n))for(var h=_s(r),g=r.getMonth();g<=n.getMonth();g++)u.push(Pi(h,g));else for(var h=_s(new Date),g=0;g<=11;g++)u.push(Pi(h,g));var p=function(b){var j=Number(b.target.value),v=Pi(_s(t.displayMonth),j);t.onChange(v)},y=(s=d==null?void 0:d.Dropdown)!==null&&s!==void 0?s:xx;return e.jsx(y,{name:"months","aria-label":m(),className:c.dropdown_month,style:i.dropdown_month,onChange:p,value:t.displayMonth.getMonth(),caption:o(t.displayMonth,{locale:l}),children:u.map(function(b){return e.jsx("option",{value:b.getMonth(),children:o(b,{locale:l})},b.getMonth())})})}function IS(t){var s,a=t.displayMonth,r=kt(),n=r.fromDate,i=r.toDate,l=r.locale,o=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 g=n.getFullYear(),p=i.getFullYear(),y=g;y<=p;y++)h.push(qc(of(new Date),y));var b=function(v){var w=qc(_s(a),Number(v.target.value));t.onChange(w)},j=(s=d==null?void 0:d.Dropdown)!==null&&s!==void 0?s:xx;return e.jsx(j,{name:"years","aria-label":u(),className:c.dropdown_year,style:o.dropdown_year,onChange:b,value:a.getFullYear(),caption:m(a,{locale:l}),children:h.map(function(v){return e.jsx("option",{value:v.getFullYear(),children:m(v,{locale:l})},v.getFullYear())})})}function ES(t,s){var a=x.useState(t),r=a[0],n=a[1],i=s===void 0?r:s;return[i,n]}function MS(t){var s=t.month,a=t.defaultMonth,r=t.today,n=s||a||r||new Date,i=t.toDate,l=t.fromDate,o=t.numberOfMonths,c=o===void 0?1:o;if(i&&ln(i,n)<0){var d=-1*(c-1);n=ca(i,d)}return l&&ln(n,l)<0&&(n=l),_s(n)}function FS(){var t=kt(),s=MS(t),a=ES(s,t.month),r=a[0],n=a[1],i=function(l){var o;if(!t.disableNavigation){var c=_s(l);n(c),(o=t.onMonthChange)===null||o===void 0||o.call(t,c)}};return[r,i]}function _S(t,s){for(var a=s.reverseMonths,r=s.numberOfMonths,n=_s(t),i=_s(ca(n,r)),l=ln(i,n),o=[],c=0;c<l;c++){var d=ca(n,c);o.push(d)}return a&&(o=o.reverse()),o}function LS(t,s){if(!s.disableNavigation){var a=s.toDate,r=s.pagedNavigation,n=s.numberOfMonths,i=n===void 0?1:n,l=r?i:1,o=_s(t);if(!a)return ca(o,l);var c=ln(a,t);if(!(c<i))return ca(o,l)}}function OS(t,s){if(!s.disableNavigation){var a=s.fromDate,r=s.pagedNavigation,n=s.numberOfMonths,i=n===void 0?1:n,l=r?i:1,o=_s(t);if(!a)return ca(o,-l);var c=ln(o,a);if(!(c<=0))return ca(o,-l)}}var gx=x.createContext(void 0);function $S(t){var s=kt(),a=FS(),r=a[0],n=a[1],i=_S(r,s),l=LS(r,s),o=OS(r,s),c=function(u){return i.some(function(h){return Jl(u,h)})},d=function(u,h){c(u)||(h&&hu(u,h)?n(ca(u,1+s.numberOfMonths*-1)):n(u))},m={currentMonth:r,displayMonths:i,goToMonth:n,goToDate:d,previousMonth:o,nextMonth:l,isDateDisplayed:c};return e.jsx(gx.Provider,{value:m,children:t.children})}function Tn(){var t=x.useContext(gx);if(!t)throw new Error("useNavigation must be used within a NavigationProvider");return t}function zm(t){var s,a=kt(),r=a.classNames,n=a.styles,i=a.components,l=Tn().goToMonth,o=function(m){l(ca(m,t.displayIndex?-t.displayIndex:0))},c=(s=i==null?void 0:i.CaptionLabel)!==null&&s!==void 0?s:px,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(PS,{onChange:o,displayMonth:t.displayMonth}),e.jsx(IS,{onChange:o,displayMonth:t.displayMonth})]})}function BS(t){return e.jsx("svg",Ye({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 US(t){return e.jsx("svg",Ye({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 si=x.forwardRef(function(t,s){var a=kt(),r=a.classNames,n=a.styles,i=[r.button_reset,r.button];t.className&&i.push(t.className);var l=i.join(" "),o=Ye(Ye({},n.button_reset),n.button);return t.style&&Object.assign(o,t.style),e.jsx("button",Ye({},t,{ref:s,type:"button",className:l,style:o}))});function VS(t){var s,a,r=kt(),n=r.dir,i=r.locale,l=r.classNames,o=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}),g=[l.nav_button,l.nav_button_previous].join(" "),p=m(t.nextMonth,{locale:i}),y=[l.nav_button,l.nav_button_next].join(" "),b=(s=u==null?void 0:u.IconRight)!==null&&s!==void 0?s:US,j=(a=u==null?void 0:u.IconLeft)!==null&&a!==void 0?a:BS;return e.jsxs("div",{className:l.nav,style:o.nav,children:[!t.hidePrevious&&e.jsx(si,{name:"previous-month","aria-label":h,className:g,style:o.nav_button_previous,disabled:!t.previousMonth,onClick:t.onPreviousClick,children:n==="rtl"?e.jsx(b,{className:l.nav_icon,style:o.nav_icon}):e.jsx(j,{className:l.nav_icon,style:o.nav_icon})}),!t.hideNext&&e.jsx(si,{name:"next-month","aria-label":p,className:y,style:o.nav_button_next,disabled:!t.nextMonth,onClick:t.onNextClick,children:n==="rtl"?e.jsx(j,{className:l.nav_icon,style:o.nav_icon}):e.jsx(b,{className:l.nav_icon,style:o.nav_icon})})]})}function Hm(t){var s=kt().numberOfMonths,a=Tn(),r=a.previousMonth,n=a.nextMonth,i=a.goToMonth,l=a.displayMonths,o=l.findIndex(function(p){return Jl(t.displayMonth,p)}),c=o===0,d=o===l.length-1,m=s>1&&(c||!d),u=s>1&&(d||!c),h=function(){r&&i(r)},g=function(){n&&i(n)};return e.jsx(VS,{displayMonth:t.displayMonth,hideNext:m,hidePrevious:u,nextMonth:n,previousMonth:r,onPreviousClick:h,onNextClick:g})}function zS(t){var s,a=kt(),r=a.classNames,n=a.disableNavigation,i=a.styles,l=a.captionLayout,o=a.components,c=(s=o==null?void 0:o.CaptionLabel)!==null&&s!==void 0?s:px,d;return n?d=e.jsx(c,{id:t.id,displayMonth:t.displayMonth}):l==="dropdown"?d=e.jsx(zm,{displayMonth:t.displayMonth,id:t.id}):l==="dropdown-buttons"?d=e.jsxs(e.Fragment,{children:[e.jsx(zm,{displayMonth:t.displayMonth,displayIndex:t.displayIndex,id:t.id}),e.jsx(Hm,{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(Hm,{displayMonth:t.displayMonth,id:t.id})]}),e.jsx("div",{className:r.caption,style:i.caption,children:d})}function HS(t){var s=kt(),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 WS(t,s,a){for(var r=a?Ql(new Date):ql(new Date,{locale:t,weekStartsOn:s}),n=[],i=0;i<7;i++){var l=Is(r,i);n.push(l)}return n}function GS(){var t=kt(),s=t.classNames,a=t.styles,r=t.showWeekNumber,n=t.locale,i=t.weekStartsOn,l=t.ISOWeek,o=t.formatters.formatWeekdayName,c=t.labels.labelWeekday,d=WS(n,i,l);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:o(m,{locale:n})},u)})]})}function KS(){var t,s=kt(),a=s.classNames,r=s.styles,n=s.components,i=(t=n==null?void 0:n.HeadRow)!==null&&t!==void 0?t:GS;return e.jsx("thead",{style:r.head,className:a.head,children:e.jsx(i,{})})}function YS(t){var s=kt(),a=s.locale,r=s.formatters.formatDay;return e.jsx(e.Fragment,{children:r(t.date,{locale:a})})}var Qo=x.createContext(void 0);function ZS(t){if(!Sn(t.initialProps)){var s={selected:void 0,modifiers:{disabled:[]}};return e.jsx(Qo.Provider,{value:s,children:t.children})}return e.jsx(XS,{initialProps:t.initialProps,children:t.children})}function XS(t){var s=t.initialProps,a=t.children,r=s.selected,n=s.min,i=s.max,l=function(d,m,u){var h,g;(h=s.onDayClick)===null||h===void 0||h.call(s,d,m,u);var p=!!(m.selected&&n&&(r==null?void 0:r.length)===n);if(!p){var y=!!(!m.selected&&i&&(r==null?void 0:r.length)===i);if(!y){var b=r?ux([],r):[];if(m.selected){var j=b.findIndex(function(v){return ks(d,v)});b.splice(j,1)}else b.push(d);(g=s.onSelect)===null||g===void 0||g.call(s,b,d,m,u)}}},o={disabled:[]};r&&o.disabled.push(function(d){var m=i&&r.length>i-1,u=r.some(function(h){return ks(h,d)});return!!(m&&!u)});var c={selected:r,onDayClick:l,modifiers:o};return e.jsx(Qo.Provider,{value:c,children:a})}function qo(){var t=x.useContext(Qo);if(!t)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return t}function JS(t,s){var a=s||{},r=a.from,n=a.to;return r&&n?ks(n,t)&&ks(r,t)?void 0:ks(n,t)?{from:n,to:void 0}:ks(r,t)?void 0:fl(r,t)?{from:t,to:n}:{from:r,to:t}:n?fl(t,n)?{from:n,to:t}:{from:t,to:n}:r?hu(t,r)?{from:t,to:r}:{from:r,to:t}:{from:t,to:void 0}}var ec=x.createContext(void 0);function QS(t){if(!An(t.initialProps)){var s={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(ec.Provider,{value:s,children:t.children})}return e.jsx(qS,{initialProps:t.initialProps,children:t.children})}function qS(t){var s=t.initialProps,a=t.children,r=s.selected,n=r||{},i=n.from,l=n.to,o=s.min,c=s.max,d=function(g,p,y){var b,j;(b=s.onDayClick)===null||b===void 0||b.call(s,g,p,y);var v=JS(g,r);(j=s.onSelect)===null||j===void 0||j.call(s,v,g,p,y)},m={range_start:[],range_end:[],range_middle:[],disabled:[]};if(i?(m.range_start=[i],l?(m.range_end=[l],ks(i,l)||(m.range_middle=[{after:i,before:l}])):m.range_end=[i]):l&&(m.range_start=[l],m.range_end=[l]),o&&(i&&!l&&m.disabled.push({after:Ri(i,o-1),before:Is(i,o-1)}),i&&l&&m.disabled.push({after:i,before:Is(i,o-1)}),!i&&l&&m.disabled.push({after:Ri(l,o-1),before:Is(l,o-1)})),c){if(i&&!l&&(m.disabled.push({before:Is(i,-c+1)}),m.disabled.push({after:Is(i,c-1)})),i&&l){var u=ba(l,i)+1,h=c-u;m.disabled.push({before:Ri(i,h)}),m.disabled.push({after:Is(l,h)})}!i&&l&&(m.disabled.push({before:Is(l,-c+1)}),m.disabled.push({after:Is(l,c-1)}))}return e.jsx(ec.Provider,{value:{selected:r,onDayClick:d,modifiers:m},children:a})}function tc(){var t=x.useContext(ec);if(!t)throw new Error("useSelectRange must be used within a SelectRangeProvider");return t}function Gn(t){return Array.isArray(t)?ux([],t):t!==void 0?[t]:[]}function eA(t){var s={};return Object.entries(t).forEach(function(a){var r=a[0],n=a[1];s[r]=Gn(n)}),s}var ea;(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"})(ea||(ea={}));var tA=ea.Selected,ya=ea.Disabled,sA=ea.Hidden,aA=ea.Today,nl=ea.RangeEnd,il=ea.RangeMiddle,ll=ea.RangeStart,rA=ea.Outside;function nA(t,s,a){var r,n=(r={},r[tA]=Gn(t.selected),r[ya]=Gn(t.disabled),r[sA]=Gn(t.hidden),r[aA]=[t.today],r[nl]=[],r[il]=[],r[ll]=[],r[rA]=[],r);return t.fromDate&&n[ya].push({before:t.fromDate}),t.toDate&&n[ya].push({after:t.toDate}),Sn(t)?n[ya]=n[ya].concat(s.modifiers[ya]):An(t)&&(n[ya]=n[ya].concat(a.modifiers[ya]),n[ll]=a.modifiers[ll],n[il]=a.modifiers[il],n[nl]=a.modifiers[nl]),n}var fx=x.createContext(void 0);function iA(t){var s=kt(),a=qo(),r=tc(),n=nA(s,a,r),i=eA(s.modifiers),l=Ye(Ye({},n),i);return e.jsx(fx.Provider,{value:l,children:t.children})}function yx(){var t=x.useContext(fx);if(!t)throw new Error("useModifiers must be used within a ModifiersProvider");return t}function lA(t){return!!(t&&typeof t=="object"&&"before"in t&&"after"in t)}function oA(t){return!!(t&&typeof t=="object"&&"from"in t)}function cA(t){return!!(t&&typeof t=="object"&&"after"in t)}function dA(t){return!!(t&&typeof t=="object"&&"before"in t)}function mA(t){return!!(t&&typeof t=="object"&&"dayOfWeek"in t)}function uA(t,s){var a,r=s.from,n=s.to;if(r&&n){var i=ba(n,r)<0;i&&(a=[n,r],r=a[0],n=a[1]);var l=ba(t,r)>=0&&ba(n,t)>=0;return l}return n?ks(n,t):r?ks(r,t):!1}function hA(t){return gu(t)}function pA(t){return Array.isArray(t)&&t.every(gu)}function xA(t,s){return s.some(function(a){if(typeof a=="boolean")return a;if(hA(a))return ks(t,a);if(pA(a))return a.includes(t);if(oA(a))return uA(t,a);if(mA(a))return a.dayOfWeek.includes(t.getDay());if(lA(a)){var r=ba(a.before,t),n=ba(a.after,t),i=r>0,l=n<0,o=fl(a.before,a.after);return o?l&&i:i||l}return cA(a)?ba(t,a.after)>0:dA(a)?ba(a.before,t)>0:typeof a=="function"?a(t):!1})}function sc(t,s,a){var r=Object.keys(s).reduce(function(i,l){var o=s[l];return xA(t,o)&&i.push(l),i},[]),n={};return r.forEach(function(i){return n[i]=!0}),a&&!Jl(t,a)&&(n.outside=!0),n}function gA(t,s){for(var a=_s(t[0]),r=Xl(t[t.length-1]),n,i,l=a;l<=r;){var o=sc(l,s),c=!o.disabled&&!o.hidden;if(!c){l=Is(l,1);continue}if(o.selected)return l;o.today&&!i&&(i=l),n||(n=l),l=Is(l,1)}return i||n}var fA=365;function bx(t,s){var a=s.moveBy,r=s.direction,n=s.context,i=s.modifiers,l=s.retry,o=l===void 0?{count:0,lastFocused:t}:l,c=n.weekStartsOn,d=n.fromDate,m=n.toDate,u=n.locale,h={day:Is,week:gl,month:ca,year:af,startOfWeek:function(b){return n.ISOWeek?Ql(b):ql(b,{locale:u,weekStartsOn:c})},endOfWeek:function(b){return n.ISOWeek?pu(b):xu(b,{locale:u,weekStartsOn:c})}},g=h[a](t,r==="after"?1:-1);r==="before"&&d?g=rf([d,g]):r==="after"&&m&&(g=nf([m,g]));var p=!0;if(i){var y=sc(g,i);p=!y.disabled&&!y.hidden}return p?g:o.count>fA?o.lastFocused:bx(g,{moveBy:a,direction:r,context:n,modifiers:i,retry:Ye(Ye({},o),{count:o.count+1})})}var vx=x.createContext(void 0);function yA(t){var s=Tn(),a=yx(),r=x.useState(),n=r[0],i=r[1],l=x.useState(),o=l[0],c=l[1],d=gA(s.displayMonths,a),m=n??(o&&s.isDateDisplayed(o))?o:d,u=function(){c(n),i(void 0)},h=function(b){i(b)},g=kt(),p=function(b,j){if(n){var v=bx(n,{moveBy:b,direction:j,context:g,modifiers:a});ks(n,v)||(s.goToDate(v,n),h(v))}},y={focusedDay:n,focusTarget:m,blur:u,focus:h,focusDayAfter:function(){return p("day","after")},focusDayBefore:function(){return p("day","before")},focusWeekAfter:function(){return p("week","after")},focusWeekBefore:function(){return p("week","before")},focusMonthBefore:function(){return p("month","before")},focusMonthAfter:function(){return p("month","after")},focusYearBefore:function(){return p("year","before")},focusYearAfter:function(){return p("year","after")},focusStartOfWeek:function(){return p("startOfWeek","before")},focusEndOfWeek:function(){return p("endOfWeek","after")}};return e.jsx(vx.Provider,{value:y,children:t.children})}function ac(){var t=x.useContext(vx);if(!t)throw new Error("useFocusContext must be used within a FocusProvider");return t}function bA(t,s){var a=yx(),r=sc(t,a,s);return r}var rc=x.createContext(void 0);function vA(t){if(!Ai(t.initialProps)){var s={selected:void 0};return e.jsx(rc.Provider,{value:s,children:t.children})}return e.jsx(jA,{initialProps:t.initialProps,children:t.children})}function jA(t){var s=t.initialProps,a=t.children,r=function(i,l,o){var c,d,m;if((c=s.onDayClick)===null||c===void 0||c.call(s,i,l,o),l.selected&&!s.required){(d=s.onSelect)===null||d===void 0||d.call(s,void 0,i,l,o);return}(m=s.onSelect)===null||m===void 0||m.call(s,i,i,l,o)},n={selected:s.selected,onDayClick:r};return e.jsx(rc.Provider,{value:n,children:a})}function jx(){var t=x.useContext(rc);if(!t)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return t}function NA(t,s){var a=kt(),r=jx(),n=qo(),i=tc(),l=ac(),o=l.focusDayAfter,c=l.focusDayBefore,d=l.focusWeekAfter,m=l.focusWeekBefore,u=l.blur,h=l.focus,g=l.focusMonthBefore,p=l.focusMonthAfter,y=l.focusYearBefore,b=l.focusYearAfter,j=l.focusStartOfWeek,v=l.focusEndOfWeek,w=function(A){var k,M,O,L;Ai(a)?(k=r.onDayClick)===null||k===void 0||k.call(r,t,s,A):Sn(a)?(M=n.onDayClick)===null||M===void 0||M.call(n,t,s,A):An(a)?(O=i.onDayClick)===null||O===void 0||O.call(i,t,s,A):(L=a.onDayClick)===null||L===void 0||L.call(a,t,s,A)},N=function(A){var k;h(t),(k=a.onDayFocus)===null||k===void 0||k.call(a,t,s,A)},C=function(A){var k;u(),(k=a.onDayBlur)===null||k===void 0||k.call(a,t,s,A)},S=function(A){var k;(k=a.onDayMouseEnter)===null||k===void 0||k.call(a,t,s,A)},E=function(A){var k;(k=a.onDayMouseLeave)===null||k===void 0||k.call(a,t,s,A)},P=function(A){var k;(k=a.onDayPointerEnter)===null||k===void 0||k.call(a,t,s,A)},R=function(A){var k;(k=a.onDayPointerLeave)===null||k===void 0||k.call(a,t,s,A)},f=function(A){var k;(k=a.onDayTouchCancel)===null||k===void 0||k.call(a,t,s,A)},T=function(A){var k;(k=a.onDayTouchEnd)===null||k===void 0||k.call(a,t,s,A)},F=function(A){var k;(k=a.onDayTouchMove)===null||k===void 0||k.call(a,t,s,A)},K=function(A){var k;(k=a.onDayTouchStart)===null||k===void 0||k.call(a,t,s,A)},B=function(A){var k;(k=a.onDayKeyUp)===null||k===void 0||k.call(a,t,s,A)},U=function(A){var k;switch(A.key){case"ArrowLeft":A.preventDefault(),A.stopPropagation(),a.dir==="rtl"?o():c();break;case"ArrowRight":A.preventDefault(),A.stopPropagation(),a.dir==="rtl"?c():o();break;case"ArrowDown":A.preventDefault(),A.stopPropagation(),d();break;case"ArrowUp":A.preventDefault(),A.stopPropagation(),m();break;case"PageUp":A.preventDefault(),A.stopPropagation(),A.shiftKey?y():g();break;case"PageDown":A.preventDefault(),A.stopPropagation(),A.shiftKey?b():p();break;case"Home":A.preventDefault(),A.stopPropagation(),j();break;case"End":A.preventDefault(),A.stopPropagation(),v();break}(k=a.onDayKeyDown)===null||k===void 0||k.call(a,t,s,A)},D={onClick:w,onFocus:N,onBlur:C,onKeyDown:U,onKeyUp:B,onMouseEnter:S,onMouseLeave:E,onPointerEnter:P,onPointerLeave:R,onTouchCancel:f,onTouchEnd:T,onTouchMove:F,onTouchStart:K};return D}function wA(){var t=kt(),s=jx(),a=qo(),r=tc(),n=Ai(t)?s.selected:Sn(t)?a.selected:An(t)?r.selected:void 0;return n}function CA(t){return Object.values(ea).includes(t)}function SA(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(CA(r)){var i=t.classNames["day_".concat(r)];i&&a.push(i)}}),a}function AA(t,s){var a=Ye({},t.styles.day);return Object.keys(s).forEach(function(r){var n;a=Ye(Ye({},a),(n=t.modifiersStyles)===null||n===void 0?void 0:n[r])}),a}function TA(t,s,a){var r,n,i,l=kt(),o=ac(),c=bA(t,s),d=NA(t,c),m=wA(),u=!!(l.onDayClick||l.mode!=="default");x.useEffect(function(){var S;c.outside||o.focusedDay&&u&&ks(o.focusedDay,t)&&((S=a.current)===null||S===void 0||S.focus())},[o.focusedDay,t,a,u,c.outside]);var h=SA(l,c).join(" "),g=AA(l,c),p=!!(c.outside&&!l.showOutsideDays||c.hidden),y=(i=(n=l.components)===null||n===void 0?void 0:n.DayContent)!==null&&i!==void 0?i:YS,b=e.jsx(y,{date:t,displayMonth:s,activeModifiers:c}),j={style:g,className:h,children:b,role:"gridcell"},v=o.focusTarget&&ks(o.focusTarget,t)&&!c.outside,w=o.focusedDay&&ks(o.focusedDay,t),N=Ye(Ye(Ye({},j),(r={disabled:c.disabled,role:"gridcell"},r["aria-selected"]=c.selected,r.tabIndex=w||v?0:-1,r)),d),C={isButton:u,isHidden:p,activeModifiers:c,selectedDays:m,buttonProps:N,divProps:j};return C}function kA(t){var s=x.useRef(null),a=TA(t.date,t.displayMonth,s);return a.isHidden?e.jsx("div",{role:"gridcell"}):a.isButton?e.jsx(si,Ye({name:"day",ref:s},a.buttonProps)):e.jsx("div",Ye({},a.divProps))}function DA(t){var s=t.number,a=t.dates,r=kt(),n=r.onWeekNumberClick,i=r.styles,l=r.classNames,o=r.locale,c=r.labels.labelWeekNumber,d=r.formatters.formatWeekNumber,m=d(Number(s),{locale:o});if(!n)return e.jsx("span",{className:l.weeknumber,style:i.weeknumber,children:m});var u=c(Number(s),{locale:o}),h=function(g){n(s,a,g)};return e.jsx(si,{name:"week-number","aria-label":u,className:l.weeknumber,style:i.weeknumber,onClick:h,children:m})}function RA(t){var s,a,r=kt(),n=r.styles,i=r.classNames,l=r.showWeekNumber,o=r.components,c=(s=o==null?void 0:o.Day)!==null&&s!==void 0?s:kA,d=(a=o==null?void 0:o.WeekNumber)!==null&&a!==void 0?a:DA,m;return l&&(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})},sf(u))})]})}function Wm(t,s,a){for(var r=a!=null&&a.ISOWeek?pu(s):xu(s,a),n=a!=null&&a.ISOWeek?Ql(t):ql(t,a),i=ba(r,n),l=[],o=0;o<=i;o++)l.push(Is(n,o));var c=l.reduce(function(d,m){var u=a!=null&&a.ISOWeek?cf(m):df(m,a),h=d.find(function(g){return g.weekNumber===u});return h?(h.dates.push(m),d):(d.push({weekNumber:u,dates:[m]}),d)},[]);return c}function PA(t,s){var a=Wm(_s(t),Xl(t),s);if(s!=null&&s.useFixedWeeks){var r=tf(t,s);if(r<6){var n=a[a.length-1],i=n.dates[n.dates.length-1],l=gl(i,6-r),o=Wm(gl(i,1),l,s);a.push.apply(a,o)}}return a}function IA(t){var s,a,r,n=kt(),i=n.locale,l=n.classNames,o=n.styles,c=n.hideHead,d=n.fixedWeeks,m=n.components,u=n.weekStartsOn,h=n.firstWeekContainsDate,g=n.ISOWeek,p=PA(t.displayMonth,{useFixedWeeks:!!d,ISOWeek:g,locale:i,weekStartsOn:u,firstWeekContainsDate:h}),y=(s=m==null?void 0:m.Head)!==null&&s!==void 0?s:KS,b=(a=m==null?void 0:m.Row)!==null&&a!==void 0?a:RA,j=(r=m==null?void 0:m.Footer)!==null&&r!==void 0?r:HS;return e.jsxs("table",{id:t.id,className:l.table,style:o.table,role:"grid","aria-labelledby":t["aria-labelledby"],children:[!c&&e.jsx(y,{}),e.jsx("tbody",{className:l.tbody,style:o.tbody,children:p.map(function(v){return e.jsx(b,{displayMonth:t.displayMonth,dates:v.dates,weekNumber:v.weekNumber},v.weekNumber)})}),e.jsx(j,{displayMonth:t.displayMonth})]})}function EA(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var MA=EA()?x.useLayoutEffect:x.useEffect,ol=!1,FA=0;function Gm(){return"react-day-picker-".concat(++FA)}function _A(t){var s,a=t??(ol?Gm():null),r=x.useState(a),n=r[0],i=r[1];return MA(function(){n===null&&i(Gm())},[]),x.useEffect(function(){ol===!1&&(ol=!0)},[]),(s=t??n)!==null&&s!==void 0?s:void 0}function LA(t){var s,a,r=kt(),n=r.dir,i=r.classNames,l=r.styles,o=r.components,c=Tn().displayMonths,d=_A(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=l.month,g=t.displayIndex===0,p=t.displayIndex===c.length-1,y=!g&&!p;n==="rtl"&&(s=[g,p],p=s[0],g=s[1]),g&&(u.push(i.caption_start),h=Ye(Ye({},h),l.caption_start)),p&&(u.push(i.caption_end),h=Ye(Ye({},h),l.caption_end)),y&&(u.push(i.caption_between),h=Ye(Ye({},h),l.caption_between));var b=(a=o==null?void 0:o.Caption)!==null&&a!==void 0?a:zS;return e.jsxs("div",{className:u.join(" "),style:h,children:[e.jsx(b,{id:d,displayMonth:t.displayMonth,displayIndex:t.displayIndex}),e.jsx(IA,{id:m,"aria-labelledby":d,displayMonth:t.displayMonth})]},t.displayIndex)}function OA(t){var s=kt(),a=s.classNames,r=s.styles;return e.jsx("div",{className:a.months,style:r.months,children:t.children})}function $A(t){var s,a,r=t.initialProps,n=kt(),i=ac(),l=Tn(),o=x.useState(!1),c=o[0],d=o[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=Ye(Ye({},n.styles.root),n.style),h=Object.keys(r).filter(function(p){return p.startsWith("data-")}).reduce(function(p,y){var b;return Ye(Ye({},p),(b={},b[y]=r[y],b))},{}),g=(a=(s=r.components)===null||s===void 0?void 0:s.Months)!==null&&a!==void 0?a:OA;return e.jsx("div",Ye({className:m.join(" "),style:u,dir:n.dir,id:n.id,nonce:r.nonce,title:r.title,lang:r.lang},h,{children:e.jsx(g,{children:l.displayMonths.map(function(p,y){return e.jsx(LA,{displayIndex:y,displayMonth:p},y)})})}))}function BA(t){var s=t.children,a=dS(t,["children"]);return e.jsx(DS,{initialProps:a,children:e.jsx($S,{children:e.jsx(vA,{initialProps:a,children:e.jsx(ZS,{initialProps:a,children:e.jsx(QS,{initialProps:a,children:e.jsx(iA,{children:e.jsx(yA,{children:s})})})})})})})}function UA(t){return e.jsx(BA,Ye({},t,{children:e.jsx($A,{initialProps:t})}))}function cl({className:t,classNames:s,showOutsideDays:a=!0,...r}){return e.jsx(UA,{showOutsideDays:a,className:we("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:we(cn({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:we("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:we(cn({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(Tu,{className:we("size-4",n),...i}),IconRight:({className:n,...i})=>e.jsx(ro,{className:we("size-4",n),...i})},...r})}async function VA(t,s=10){var a;try{const r={limit:s};t&&(r.q=t);const n=await ye.get("/dealers",{params:r});return((a=n.data)==null?void 0:a.data)||n.data||[]}catch(r){throw console.error("[DealerAPI] Error fetching dealers:",r),r}}async function zA(t){var s,a,r;try{const n=await ye.get(`/dealers/verify/${t}`);return((s=n.data)==null?void 0:s.data)||n.data}catch(n){const i=((r=(a=n.response)==null?void 0:a.data)==null?void 0:r.message)||n.message||"Dealer verification failed";throw console.error("[DealerAPI] Error verifying dealer login:",i),new Error(i)}}const As=[{level:1,name:"Dealer Proposal Submission",description:"Dealer submits proposal documents",defaultTat:72,isAuto:!1,approverType:"dealer"},{level:2,name:"Requestor Evaluation",description:"Initiator evaluates dealer proposal",defaultTat:48,isAuto:!1,approverType:"initiator"},{level:3,name:"Department Lead Approval",description:"Department lead approves and blocks IO budget",defaultTat:72,isAuto:!1,approverType:"manual"},{level:4,name:"Dealer Completion Documents",description:"Dealer submits completion documents",defaultTat:120,isAuto:!1,approverType:"dealer"},{level:5,name:"Requestor Claim Approval",description:"Initiator approves completion",defaultTat:48,isAuto:!1,approverType:"initiator"}];function HA({formData:t,updateFormData:s,onValidationError:a,currentUserEmail:r="",currentUserId:n="",currentUserName:i="",onValidate:l}){const{userSearchResults:o,userSearchLoading:c,searchUsersForIndex:d,clearSearchForIndex:m}=Kp(),[u,h]=x.useState(!1),[g,p]=x.useState(""),[y,b]=x.useState(24),[j,v]=x.useState("hours"),[w,N]=x.useState(3),[C,S]=x.useState([]),[E,P]=x.useState(!1),[R,f]=x.useState(null),T=x.useRef(null),F=()=>{const $=t.approvers||[],W=[];return As.forEach(_=>{if(_.isAuto||_.approverType==="dealer"||_.approverType==="initiator")return;const G=$.find(H=>H.level===_.level);(!G||!G.email||!G.userId||!G.tat)&&W.push(`${_.name}`)}),{isValid:W.length===0,missingSteps:W}};x.useEffect(()=>{if(l){const $=F();l($.isValid)}},[t.approvers]),x.useEffect(()=>{const $=t.approvers||[];if($.length>0){const W=[],_=$.filter(H=>H.isAdditional);As.forEach(H=>{const V=$.find(ee=>ee.originalStepLevel===H.level||!ee.originalStepLevel&&!ee.isAdditional&&ee.level===H.level);if(V)W.push(V);else if(H.isAuto){const ee=H.level===8?"finance@royalenfield.com":"system@royalenfield.com",oe=H.level===8?"System/Finance":"System";W.push({email:ee,name:oe,level:H.level,tat:H.defaultTat,tatType:"hours",originalStepLevel:H.level})}else H.approverType==="dealer"?W.push({email:t.dealerEmail||"",name:t.dealerName||"",level:H.level,tat:H.defaultTat,tatType:"hours",originalStepLevel:H.level}):H.approverType==="initiator"?W.push({email:r||"",name:i||r||"User",userId:n,level:H.level,tat:H.defaultTat,tatType:"hours",originalStepLevel:H.level}):W.push({email:"",name:"",level:H.level,tat:H.defaultTat,tatType:"hours",originalStepLevel:H.level})}),_.forEach(H=>{W.push(H)}),W.sort((H,V)=>H.level-V.level),JSON.stringify($.map(H=>({level:H.level,originalStepLevel:H.originalStepLevel})))!==JSON.stringify(W.map(H=>({level:H.level,originalStepLevel:H.originalStepLevel})))&&s("approvers",W)}else{const W=[];As.forEach(_=>{_.isAuto||(_.approverType==="dealer"?W.push({email:t.dealerEmail||"",name:t.dealerName||"",level:_.level,tat:_.defaultTat,tatType:"hours",originalStepLevel:_.level}):_.approverType==="initiator"?W.push({email:r||"",name:i||r||"User",userId:n,level:_.level,tat:_.defaultTat,tatType:"hours",originalStepLevel:_.level}):W.push({email:"",name:"",level:_.level,tat:_.defaultTat,tatType:"hours",originalStepLevel:_.level}))}),s("approvers",W)}},[t.dealerEmail,t.dealerName,r,n,i]);const K=($,W)=>{const _=[...t.approvers||[]],G=_.findIndex(H=>H.originalStepLevel===$||!H.originalStepLevel&&H.level===$&&!H.isAdditional);if(G===-1){const H=As.find(V=>V.level===$);_.push({email:W,name:"",level:$,tat:(H==null?void 0:H.defaultTat)||48,tatType:"hours",originalStepLevel:$})}else{const H=_[G];if(H){const V=H.email;_[G]={...H,email:W,name:W!==V?"":H.name,userId:W!==V?void 0:H.userId}}}if(s("approvers",_),!W||!W.startsWith("@")||W.length<2){m($-1);return}d($-1,W,10)},B=async($,W)=>{var _,G;try{const H=As.find(Se=>Se.level===$);if(H&&!H.isAuto&&H.approverType!=="initiator"&&((_=W.email)==null?void 0:_.toLowerCase())===(r==null?void 0:r.toLowerCase())){q.error(`You cannot assign yourself as ${H.name} approver.`),a&&a({type:"self-assign",email:W.email,message:`You cannot assign yourself as ${H.name} approver.`});return}if((t.approvers||[]).some(Se=>{var ne,de;return Se.level!==$&&(Se.userId===W.userId||((ne=Se.email)==null?void 0:ne.toLowerCase())===((de=W.email)==null?void 0:de.toLowerCase()))})){q.error("This user is already assigned to another step."),a&&a({type:"error",email:W.email,message:"This user is already assigned to another step."});return}const oe=await Ks({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}),pe=[...t.approvers||[]],Pe=pe.findIndex(Se=>Se.originalStepLevel===$||!Se.originalStepLevel&&Se.level===$&&!Se.isAdditional);if(Pe===-1){const Se=As.find(ne=>ne.level===$);pe.push({email:W.email,name:W.displayName||[W.firstName,W.lastName].filter(Boolean).join(" "),userId:oe.userId,level:$,tat:(Se==null?void 0:Se.defaultTat)||48,tatType:"hours",originalStepLevel:$})}else{const Se=pe[Pe];Se&&(pe[Pe]={...Se,email:W.email,name:W.displayName||[W.firstName,W.lastName].filter(Boolean).join(" "),userId:oe.userId,originalStepLevel:Se.originalStepLevel||$})}s("approvers",pe),m($-1),q.success(`Approver for ${(G=As.find(Se=>Se.level===$))==null?void 0:G.name} selected successfully.`)}catch(H){console.error("Failed to ensure user exists:",H),q.error("Failed to validate user. Please try again."),a&&a({type:"error",email:W.email,message:"Failed to validate user. Please try again."})}},U=($,W)=>{const _=[...t.approvers||[]],G=_.findIndex(H=>H.originalStepLevel===$||!H.originalStepLevel&&H.level===$&&!H.isAdditional);if(G!==-1){const H=_[G];H&&(_[G]={...H,tat:W},s("approvers",_))}},D=($,W)=>{const _=[...t.approvers||[]],G=_.findIndex(H=>H.originalStepLevel===$||!H.originalStepLevel&&H.level===$&&!H.isAdditional);if(G!==-1){const H=_[G];H&&(_[G]={...H,tatType:W,tat:""},s("approvers",_))}},A=$=>{if(p($),R&&R.email.toLowerCase()!==$.toLowerCase()&&f(null),T.current&&clearTimeout(T.current),!$||!$.startsWith("@")||$.length<2){S([]),P(!1);return}P(!0),T.current=setTimeout(async()=>{var W;try{const _=$.slice(1),H=((W=(await Zs(_,10)).data)==null?void 0:W.data)||[];S(H)}catch(_){console.error("Search failed:",_),S([])}finally{P(!1)}},300)},k=async $=>{try{await Ks({userId:$.userId,email:$.email,displayName:$.displayName,firstName:$.firstName,lastName:$.lastName,department:$.department,phone:$.phone,mobilePhone:$.mobilePhone,designation:$.designation,jobTitle:$.jobTitle,manager:$.manager,employeeId:$.employeeId,employeeNumber:$.employeeNumber,secondEmail:$.secondEmail,location:$.location}),p($.email),f($),S([]),P(!1)}catch(W){console.error("Failed to ensure user exists:",W),q.error("Failed to verify user. Please try again.")}},M=async()=>{var ne;const $=g.trim().toLowerCase();if(!$){q.error("Please enter an email address");return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test($)){q.error("Please enter a valid email address");return}const _=typeof y=="string"?Number(y):y;if(!_||_<=0||isNaN(_)){q.error("Please enter valid TAT (minimum 1)");return}const G=j==="days"?30:720;if((j==="days"?_*24:_)>720){q.error(`TAT cannot exceed ${G} ${j==="days"?"days":"hours"}`);return}const V=As.find(de=>de.name==="Requestor Claim Approval");if(V&&w>=V.level){q.error('Additional approvers cannot be added after "Requestor Claim Approval" as it is considered final.');return}if($===(r==null?void 0:r.toLowerCase())){q.error("You cannot add yourself as an additional approver.");return}const ee=t.approvers||[];if(ee.some(de=>{var le;return de.userId&&(R==null?void 0:R.userId)&&de.userId===R.userId||((le=de.email)==null?void 0:le.toLowerCase())===$})){q.error("This user is already assigned as an approver.");return}const pe=ee.find(de=>de.originalStepLevel===w||!de.originalStepLevel&&!de.isAdditional&&de.level===w),Se=(pe?pe.level:w)+1;if(!R||R.email.toLowerCase()!==$)try{const le=((ne=(await Zs($,1)).data)==null?void 0:ne.data)||[];if(le.length===0){q.error("User not found in organization directory. Please use @ to search for users.");return}const fe=le[0];await Ks({userId:fe.userId,email:fe.email,displayName:fe.displayName,firstName:fe.firstName,lastName:fe.lastName,department:fe.department,phone:fe.phone,mobilePhone:fe.mobilePhone,designation:fe.designation,jobTitle:fe.jobTitle,manager:fe.manager,employeeId:fe.employeeId,employeeNumber:fe.employeeNumber,secondEmail:fe.secondEmail,location:fe.location});const st={email:fe.email,name:fe.displayName||[fe.firstName,fe.lastName].filter(Boolean).join(" "),userId:fe.userId,level:Se,tat:typeof y=="string"?Number(y):y,tatType:j,isAdditional:!0,insertAfterLevel:w,stepName:`Additional Approver - ${fe.displayName||fe.email}`},ae=ee.map(je=>je.level>=Se?{...je,level:je.level+1}:je);ae.push(st),ae.sort((je,gt)=>je.level-gt.level),s("approvers",ae),q.success("Additional approver added and subsequent steps shifted")}catch(de){console.error("Failed to validate approver:",de),q.error("Failed to validate user. Please try again.");return}else{const de={email:R.email,name:R.displayName||[R.firstName,R.lastName].filter(Boolean).join(" "),userId:R.userId,level:Se,tat:y,tatType:j,isAdditional:!0,insertAfterLevel:w,stepName:`Additional Approver - ${R.displayName||R.email}`},le=ee.map(fe=>fe.level>=Se?{...fe,level:fe.level+1}:fe);le.push(de),le.sort((fe,st)=>fe.level-st.level),s("approvers",le),q.success("Additional approver added and subsequent steps shifted")}p(""),b(24),v("hours"),N(3),f(null),S([]),h(!1)},O=$=>{const W=[...t.approvers||[]];if(!W.find(V=>V.level===$))return;const H=W.filter(V=>V.level!==$).map(V=>V.level>$&&!V.isAdditional?{...V,level:V.level-1}:V);H.sort((V,ee)=>V.level-ee.level),s("approvers",H),q.success("Additional approver removed and subsequent steps shifted back")},L=()=>[...t.approvers||[]].sort((W,_)=>W.level-_.level),Z=t.approvers||[],z=L();return e.jsxs(as.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-purple-500 to-indigo-600 rounded-2xl flex items-center justify-center mx-auto mb-4",children:e.jsx(Mt,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Approver Selection"}),e.jsx("p",{className:"text-gray-600",children:"Assign approvers for workflow steps with TAT (Turn Around Time)"})]}),e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsx(te,{className:"border-2 border-blue-200 bg-blue-50",children:e.jsxs(me,{children:[e.jsxs(he,{className:"flex items-center gap-2 text-blue-900",children:[e.jsx(Nr,{className:"w-5 h-5"}),"Workflow Steps Information"]}),e.jsx(De,{className:"text-blue-700",children:'Some steps are pre-filled (Dealer, Initiator, System). You need to assign approvers for "Department Lead Approval" only. Additional approvers cannot be added after "Requestor Claim Approval" as it is considered final.'})]})}),e.jsxs(te,{className:"border-2",children:[e.jsxs(me,{children:[e.jsxs(he,{className:"flex items-center gap-2",children:[e.jsx(cs,{className:"w-5 h-5"}),"Approval Hierarchy"]}),e.jsx(De,{children:'Define approvers and TAT for each step. Some steps are pre-filled (Dealer, Initiator, System). Only "Department Lead Approval" requires manual assignment.'})]}),e.jsxs(se,{className:"space-y-2 pt-4",children:[e.jsx("div",{className:"mb-4 flex justify-end",children:e.jsxs(I,{type:"button",variant:"outline",onClick:()=>h(!0),className:"flex items-center gap-2",children:[e.jsx(Ls,{className:"w-4 h-4"}),"Add Additional Approver"]})}),e.jsx("div",{className:"p-3 rounded-lg border-2 border-blue-200 bg-blue-50",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 bg-blue-600 rounded-full flex items-center justify-center flex-shrink-0",children:e.jsx(Pt,{className:"w-4 h-4 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 text-sm",children:"Request Initiator"}),e.jsx(ie,{variant:"secondary",className:"text-xs",children:"YOU"})]}),e.jsx("p",{className:"text-xs text-blue-700",children:"Creates and submits the request"})]})]})}),(()=>{const $=z.filter(_=>_.isAdditional&&_.insertAfterLevel===0);let W=$.length;return As.filter(_=>!_.isAuto).map((_,G,H)=>{var ne,de;const V=Z.find(le=>le.originalStepLevel===_.level||!le.originalStepLevel&&le.level===_.level&&!le.isAdditional)||{email:"",name:"",level:_.level,tat:_.defaultTat,tatType:"hours",originalStepLevel:_.level},ee=G===H.length-1,oe=_.isAuto||_.approverType==="dealer"||_.approverType==="initiator",pe=!_.isAuto,Pe=z.filter(le=>le.isAdditional&&le.insertAfterLevel===_.level).sort((le,fe)=>le.level-fe.level),Se=W+1;return W++,W+=Pe.length,e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"w-px h-3 bg-gray-300"})}),G===0&&$.map((le,fe)=>{const st=fe+1;return e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"w-px h-3 bg-gray-300"})}),e.jsx("div",{className:"p-3 rounded-lg border-2 border-purple-200 bg-purple-50",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 bg-purple-600",children:e.jsx("span",{className:"text-white font-semibold text-sm",children:st})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-gray-900 text-sm",children:"Additional Approver"}),e.jsx(ie,{variant:"outline",className:"text-xs bg-purple-50 text-purple-700 border-purple-300",children:"ADDITIONAL"}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",onClick:()=>O(le.level),className:"h-6 w-6 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",children:e.jsx(pt,{className:"w-3 h-3"})})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:le.name||le.email}),e.jsxs("div",{className:"text-xs text-gray-500",children:[e.jsxs("div",{children:["Email: ",le.email]}),e.jsxs("div",{children:["TAT: ",le.tat," ",le.tatType]})]})]})]})})]},`additional-${le.level}`)}),e.jsx("div",{className:`p-3 rounded-lg border-2 transition-all ${V.email&&V.userId?"border-green-200 bg-green-50":oe?"border-blue-200 bg-blue-50":"border-gray-200 bg-gray-50"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${V.email&&V.userId?"bg-green-600":oe?"bg-blue-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold text-sm",children:Se})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-gray-900 text-sm",children:_.name}),ee&&e.jsx(ie,{variant:"destructive",className:"text-xs",children:"FINAL"}),oe&&e.jsx(ie,{variant:"outline",className:"text-xs",children:"PRE-FILLED"})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:_.description}),pe&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsxs(re,{htmlFor:`approver-${_.level}`,className:"text-xs font-medium",children:["Email Address ",!oe&&"*"]}),V.email&&V.userId&&e.jsxs(ie,{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(Re,{id:`approver-${_.level}`,type:"text",placeholder:oe?V.email:"@approver@royalenfield.com",value:V.email||"",onChange:le=>{const fe=le.target.value;oe||K(_.level,fe)},disabled:oe||_.isAuto,className:"h-9 border-2 border-gray-300 focus:border-blue-500 mt-1 w-full text-sm"}),!oe&&!_.isAuto&&(c[_.level-1]||(((ne=o[_.level-1])==null?void 0:ne.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:c[_.level-1]?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:(de=o[_.level-1])==null?void 0:de.map(le=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>B(_.level,le),children:[e.jsx("div",{className:"font-medium text-gray-900",children:le.displayName||le.email}),e.jsx("div",{className:"text-xs text-gray-600",children:le.email}),le.department&&e.jsx("div",{className:"text-xs text-gray-500",children:le.department})]},le.userId))})})]}),V.name&&e.jsxs("p",{className:"text-xs text-green-600 mt-1",children:["Selected: ",e.jsx("span",{className:"font-semibold",children:V.name})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:`tat-${_.level}`,className:"text-xs font-medium",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Re,{id:`tat-${_.level}`,type:"number",placeholder:V.tatType==="days"?"7":"24",min:"1",max:V.tatType==="days"?"30":"720",value:V.tat||"",onChange:le=>U(_.level,parseInt(le.target.value)||""),disabled:_.isAuto,className:"h-9 border-2 border-gray-300 focus:border-blue-500 flex-1 text-sm"}),e.jsxs(Ue,{value:V.tatType||"hours",onValueChange:le=>D(_.level,le),disabled:_.isAuto,children:[e.jsx(ze,{className:"w-20 h-9 border-2 border-gray-300 text-sm",children:e.jsx(Ve,{})}),e.jsxs(He,{children:[e.jsx(Y,{value:"hours",children:"Hours"}),e.jsx(Y,{value:"days",children:"Days"})]})]})]})]})]})]})]})}),Pe.map((le,fe)=>{const st=Se+fe+1;return e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"w-px h-3 bg-gray-300"})}),e.jsx("div",{className:"p-3 rounded-lg border-2 border-purple-200 bg-purple-50",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 bg-purple-600",children:e.jsx("span",{className:"text-white font-semibold text-sm",children:st})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-gray-900 text-sm",children:le.stepName||"Additional Approver"}),e.jsx(ie,{variant:"outline",className:"text-xs bg-purple-50 text-purple-700 border-purple-300",children:"ADDITIONAL"}),le.email&&le.userId&&e.jsxs(ie,{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.jsx(I,{type:"button",variant:"ghost",size:"sm",onClick:()=>O(le.level),className:"h-6 w-6 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",children:e.jsx(pt,{className:"w-3 h-3"})})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:le.name||le.email||"No approver assigned"}),le.email&&e.jsxs("div",{className:"text-xs text-gray-500 space-y-1",children:[e.jsxs("div",{children:["Email: ",le.email]}),le.tat&&e.jsxs("div",{children:["TAT: ",le.tat," ",le.tatType]})]})]})]})})]},`additional-${le.level}`)})]},_.level)})})()]})]}),e.jsxs(te,{className:"border-2",children:[e.jsx(me,{children:e.jsxs(he,{className:"flex items-center gap-2",children:[e.jsx(Ze,{className:"w-5 h-5"}),"TAT Summary"]})}),e.jsx(se,{children:e.jsx("div",{className:"space-y-3",children:z.map($=>{const W=$.originalStepLevel?As.find(V=>V.level===$.originalStepLevel):As.find(V=>V.level===$.level&&!$.isAdditional);if(W!=null&&W.isAuto)return null;const _=Number($.tat||0),H=($.tatType||"hours")==="days"?_*24:_;if(!_)return null;if($.isAdditional){const V=As.find(ee=>ee.level===$.insertAfterLevel);return e.jsxs("div",{className:"flex items-center justify-between p-2 bg-purple-50 rounded border border-purple-200",children:[e.jsx("span",{className:"text-sm font-medium",children:$.stepName||`Additional Approver (after "${(V==null?void 0:V.name)||"Unknown"}")`}),e.jsxs("span",{className:"text-sm text-gray-600",children:[H," hours"]})]},$.level)}return e.jsxs("div",{className:"flex items-center justify-between p-2 bg-gray-50 rounded",children:[e.jsx("span",{className:"text-sm font-medium",children:(W==null?void 0:W.name)||"Unknown"}),e.jsxs("span",{className:"text-sm text-gray-600",children:[H," hours"]})]},$.level)})})})]})]}),e.jsx(ot,{open:u,onOpenChange:h,children:e.jsxs(nt,{className:"sm:max-w-md",children:[e.jsxs(ct,{children:[e.jsxs(it,{className:"flex items-center gap-2",children:[e.jsx(Ls,{className:"w-5 h-5 text-blue-600"}),"Add Additional Approver"]}),e.jsx(_t,{children:'Add an additional approver between workflow steps. The approver will be inserted after the selected step. Additional approvers cannot be added after "Requestor Claim Approval".'})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-medium",children:"Insert After Step *"}),e.jsxs(Ue,{value:w.toString(),onValueChange:$=>N(Number($)),children:[e.jsx(ze,{className:"h-11 border-gray-300",children:e.jsx(Ve,{placeholder:"Select step"})}),e.jsx(He,{children:As.filter($=>{if($.isAuto)return!1;const W=As.find(_=>_.name==="Requestor Claim Approval");return!(W&&$.level>=W.level)}).map($=>e.jsx(Y,{value:$.level.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cs,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:$.name})]})},$.level))})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"The new approver will be inserted after the selected step."}),e.jsx("p",{className:"text-xs text-amber-600 font-medium",children:'⚠️ Additional approvers cannot be added after "Requestor Claim Approval" as it is considered final.'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-medium",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Re,{type:"number",min:"1",max:j==="days"?"30":"720",value:y,onChange:$=>{const W=$.target.value;if(W==="")b("");else{const _=Number(W);!isNaN(_)&&_>=0&&b(_)}},onBlur:$=>{const W=$.target.value;(!W||W===""||Number(W)<=0)&&b(24)},className:"h-11 border-gray-300 flex-1",placeholder:"24"}),e.jsxs(Ue,{value:j,onValueChange:$=>v($),children:[e.jsx(ze,{className:"w-24 h-11 border-gray-300",children:e.jsx(Ve,{})}),e.jsxs(He,{children:[e.jsx(Y,{value:"hours",children:"Hours"}),e.jsx(Y,{value:"days",children:"Days"})]})]})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Maximum time for this approver to respond (1-",j==="days"?"30 days":"720 hours",")"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-medium",children:"Email Address *"}),e.jsxs("div",{className:"relative",children:[e.jsx(mi,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Re,{type:"text",placeholder:"@username or user@example.com",value:g,onChange:$=>A($.target.value),className:"pl-10 h-11 border-gray-300",autoFocus:!0}),(E||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:E?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($=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>k($),children:e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:$.displayName||[$.firstName,$.lastName].filter(Boolean).join(" ")||$.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:$.email}),$.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:$.designation})]})})},$.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(At,{children:[e.jsx(I,{type:"button",variant:"outline",onClick:()=>{h(!1),p(""),b(24),v("hours"),N(3),f(null),S([])},className:"flex-1",children:"Cancel"}),e.jsxs(I,{type:"button",onClick:M,className:"flex-1 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:!g.trim()||!y,children:[e.jsx(Ls,{className:"w-4 h-4 mr-2"}),"Add Approver"]})]})]})})]})}const dl=[{level:1,name:"Dealer Proposal Submission",description:"Dealer submits proposal documents",defaultTat:72,isAuto:!1,approverType:"dealer"},{level:2,name:"Requestor Evaluation",description:"Initiator evaluates dealer proposal",defaultTat:48,isAuto:!1,approverType:"initiator"},{level:3,name:"Department Lead Approval",description:"Department lead approves and blocks IO budget",defaultTat:72,isAuto:!1,approverType:"manual"},{level:4,name:"Activity Creation",description:"System auto-processes activity creation",defaultTat:1,isAuto:!0,approverType:"system"},{level:5,name:"Dealer Completion Documents",description:"Dealer submits completion documents",defaultTat:120,isAuto:!1,approverType:"dealer"},{level:6,name:"Requestor Claim Approval",description:"Initiator approves completion",defaultTat:48,isAuto:!1,approverType:"initiator"},{level:7,name:"E-Invoice Generation",description:"System generates e-invoice via DMS",defaultTat:1,isAuto:!0,approverType:"system"},{level:8,name:"Credit Note Confirmation",description:"System/Finance processes credit note confirmation",defaultTat:48,isAuto:!0,approverType:"system"}],WA=["Riders Mania Claims","Marketing Cost – Bike to Vendor","Media Bike Service","ARAI Motorcycle Liquidation","ARAI Certification – STA Approval CNR","Procurement of Spares/Apparel/GMA for Events","Fuel for Media Bike Used for Event","Motorcycle Buyback and Goodwill Support","Liquidation of Used Motorcycle","Motorcycle Registration CNR (Owned or Gifted by RE)","Legal Claims Reimbursement","Service Camp Claims","Corporate Claims – Institutional Sales PDI"],ml=["Claim Details","Approver Selection","Review & Submit"];function GA({onBack:t,onSubmit:s}){const{user:a}=Kt(),[r,n]=x.useState(1),[i,l]=x.useState(!1),[o,c]=x.useState([]),[d,m]=x.useState(!1),[u,h]=x.useState(""),g=x.useRef(null),[p,y]=x.useState({activityName:"",activityType:"",dealerCode:"",dealerName:"",dealerEmail:"",dealerPhone:"",dealerAddress:"",activityDate:void 0,location:"",requestDescription:"",periodStartDate:void 0,periodEndDate:void 0,estimatedBudget:"",approvers:[]}),b=ml.length,j=R=>{if(h(R),g.current&&clearTimeout(g.current),!R||R.trim().length<2){c([]),m(!1);return}m(!0),g.current=setTimeout(async()=>{try{const f=await VA(R,10);c(f)}catch(f){console.error("Error searching dealers:",f),c([])}finally{m(!1)}},300)},v=(R,f)=>{y(T=>{const F={...T,[R]:f};if(R==="periodStartDate")f&&F.periodEndDate&&f>F.periodEndDate&&(F.periodEndDate=void 0,q.error("End date must be on or after the start date. End date has been cleared."));else if(R==="periodEndDate"&&f&&F.periodStartDate&&f<F.periodStartDate)return q.error("End date must be on or after the start date."),T;return F})},w=()=>{switch(r){case 1:return p.activityName&&p.activityType&&p.dealerCode&&p.dealerName&&p.activityDate&&p.location&&p.requestDescription;case 2:const f=(p.approvers||[]).find(T=>T.originalStepLevel===3||!T.originalStepLevel&&T.level===3&&!T.isAdditional);return(f==null?void 0:f.email)&&(f==null?void 0:f.userId)&&(f==null?void 0:f.tat);case 3:return!0;default:return!1}},N=()=>{if(r<b){if(!w()){if(r===2){const f=(p.approvers||[]).find(F=>F.originalStepLevel===3||!F.originalStepLevel&&F.level===3&&!F.isAdditional),T=[];(!(f!=null&&f.email)||!(f!=null&&f.userId)||!(f!=null&&f.tat))&&T.push("Department Lead Approval"),T.length>0?q.error(`Please add missing approvers: ${T.join(", ")}`):q.error("Please complete all required approver selections (email, user verification, and TAT) before proceeding.")}else q.error("Please complete all required fields before proceeding.");return}n(r+1)}},C=()=>{r>1&&n(r-1)},S=async R=>{l(!0);try{const f=await zA(R.dealerCode);if(!f.isLoggedIn){q.error(`Dealer "${f.dealerName||f.displayName}" (${f.dealerCode}) has not logged in to the system. Please ask them to log in first.`,{duration:5e3}),h(""),c([]),v("dealerCode",""),v("dealerName",""),v("dealerEmail",""),v("dealerPhone",""),v("dealerAddress",""),l(!1);return}v("dealerCode",f.dealerCode),v("dealerName",f.dealerName||f.displayName),v("dealerEmail",f.email||""),v("dealerPhone",f.phone||""),v("dealerAddress",""),h(f.dealerName||f.displayName),c([]),q.success(`Dealer "${f.dealerName||f.displayName}" verified and logged in`)}catch(f){const T=f.message||"Failed to verify dealer login";q.error(T,{duration:5e3}),h(""),c([]),v("dealerCode",""),v("dealerName",""),v("dealerEmail",""),v("dealerPhone",""),v("dealerAddress","")}finally{l(!1)}},E=()=>{const f=[...p.approvers||[]].sort((U,D)=>U.level-D.level),T=new Map,F=[];if(f.forEach(U=>{T.has(U.level)?F.push(U.level):T.set(U.level,U)}),F.length>0){q.error(`Duplicate approver levels detected: ${F.join(", ")}. Please refresh and try again.`),console.error("Duplicate levels found:",F,f);return}const K=f.map(U=>{const D={email:U.email,name:U.name,userId:U.userId,level:U.level,tat:U.tat,tatType:U.tatType};return U.isAdditional&&U.stepName&&(D.stepName=U.stepName,D.isAdditional=!0),U.originalStepLevel&&(D.originalStepLevel=U.originalStepLevel),D}),B={...p,templateType:"claim-management",submittedAt:new Date().toISOString(),status:"pending",currentStep:"initiator-review",approvers:K};s&&s(B)},P=()=>{switch(r){case 1:return e.jsxs(as.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(us,{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(re,{htmlFor:"activityName",className:"text-base font-semibold",children:"Activity Name *"}),e.jsx(Re,{id:"activityName",placeholder:"e.g., Himalayan Adventure Fest 2024",value:p.activityName,onChange:R=>v("activityName",R.target.value),className:"mt-2 h-12"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"activityType",className:"text-base font-semibold",children:"Activity Type *"}),e.jsxs(Ue,{value:p.activityType,onValueChange:R=>v("activityType",R),children:[e.jsx(ze,{className:"mt-2 !h-12 data-[size=default]:!h-12",id:"activityType",children:e.jsx(Ve,{placeholder:"Select activity type"})}),e.jsx(He,{children:WA.map(R=>e.jsx(Y,{value:R,children:R},R))})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-base font-semibold",children:"Dealer Code / Dealer Name *"}),e.jsx("div",{className:"mt-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(Re,{placeholder:"Type dealer code, name, or email to search...",value:p.dealerCode?`${p.dealerName} (${p.dealerCode})`:u,onChange:R=>{p.dealerCode?(v("dealerCode",""),v("dealerName",""),v("dealerEmail",""),v("dealerPhone",""),v("dealerAddress",""),h(R.target.value)):j(R.target.value)},onFocus:()=>{u&&u.length>=2&&j(u)},className:"h-12 border-2 border-gray-300 focus:border-blue-500",disabled:i}),p.dealerCode&&e.jsx("div",{className:"absolute right-3 top-1/2 -translate-y-1/2",children:e.jsxs(ie,{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"]})}),(d||o.length>0)&&!p.dealerCode&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg",children:d?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(R=>e.jsx("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>S(R),children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-gray-900",children:R.dealerName||R.displayName}),e.jsxs("div",{className:"text-xs text-gray-600",children:[e.jsx("span",{className:"font-mono",children:R.dealerCode}),R.email&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1",children:"•"}),e.jsx("span",{children:R.email})]})]}),R.city&&R.state&&e.jsxs("div",{className:"text-xs text-gray-500",children:[R.city,", ",R.state]})]}),e.jsx("div",{className:"ml-2 flex-shrink-0",children:R.isLoggedIn?e.jsx(Ce,{className:"w-4 h-4 text-green-600"}):e.jsx(xt,{className:"w-4 h-4 text-red-500"})})]})},R.dealerId))})})]})}),e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-xs text-gray-500",children:[e.jsx("span",{children:"Status:"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ce,{className:"w-3 h-3 text-green-600"}),e.jsx("span",{children:"Logged in"})]}),e.jsx("span",{className:"mx-1",children:"•"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(xt,{className:"w-3 h-3 text-red-500"}),e.jsx("span",{children:"Not logged in"})]})]}),p.dealerCode&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsxs("p",{className:"text-sm text-gray-600",children:["Selected: ",e.jsx("span",{className:"font-semibold",children:p.dealerName})," (",p.dealerCode,")"]}),p.dealerEmail&&e.jsxs("p",{className:"text-xs text-gray-500",children:["Email: ",p.dealerEmail]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-base font-semibold",children:"Date *"}),e.jsxs(ra,{children:[e.jsx(na,{asChild:!0,children:e.jsxs(I,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12 pl-3",children:[e.jsx(mt,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:p.activityDate?Ie(p.activityDate,"PPP"):"Select date"})]})}),e.jsx(ia,{className:"w-auto p-0",align:"start",children:e.jsx(cl,{mode:"single",selected:p.activityDate,onSelect:R=>v("activityDate",R),initialFocus:!0})})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"location",className:"text-base font-semibold",children:"Location *"}),e.jsx(Re,{id:"location",placeholder:"e.g., Mumbai, Maharashtra",value:p.location,onChange:R=>v("location",R.target.value),className:"mt-2 h-12"})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"requestDescription",className:"text-base font-semibold",children:"Request in Detail - Brief Requirement *"}),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(yi,{value:p.requestDescription||"",onChange:R=>v("requestDescription",R),placeholder:"Provide comprehensive details about your claim requirement 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"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(re,{className:"text-base font-semibold",children:"Period (If Any)"}),e.jsx(ie,{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(re,{className:"text-sm text-gray-600",children:"Start Date"}),e.jsxs(ra,{children:[e.jsx(na,{asChild:!0,children:e.jsxs(I,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12 pl-3",children:[e.jsx(mt,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:p.periodStartDate?Ie(p.periodStartDate,"PPP"):"Start date"})]})}),e.jsx(ia,{className:"w-auto p-0",align:"start",children:e.jsx(cl,{mode:"single",selected:p.periodStartDate,onSelect:R=>v("periodStartDate",R),initialFocus:!0,toDate:p.periodEndDate||void 0})})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-sm text-gray-600",children:"End Date"}),e.jsxs(ra,{children:[e.jsx(na,{asChild:!0,children:e.jsxs(I,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12 pl-3",disabled:!p.periodStartDate,children:[e.jsx(mt,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:p.periodEndDate?Ie(p.periodEndDate,"PPP"):"End date"})]})}),e.jsx(ia,{className:"w-auto p-0",align:"start",children:e.jsx(cl,{mode:"single",selected:p.periodEndDate,onSelect:R=>v("periodEndDate",R),initialFocus:!0,fromDate:p.periodStartDate||void 0})})]}),!p.periodStartDate&&e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Please select start date first"})]})]}),(p.periodStartDate||p.periodEndDate)&&e.jsx("div",{className:"mt-2",children:p.periodStartDate&&p.periodEndDate?e.jsxs("p",{className:"text-xs text-gray-600",children:["Period: ",Ie(p.periodStartDate,"MMM dd, yyyy")," - ",Ie(p.periodEndDate,"MMM dd, yyyy")]}):e.jsx("p",{className:"text-xs text-gray-500",children:p.periodStartDate?"Please select end date for the period":"Please select start date first"})})]})]})]});case 2:return e.jsx(HA,{formData:p,updateFormData:v,currentUserEmail:(a==null?void 0:a.email)||"",currentUserId:(a==null?void 0:a.userId)||"",currentUserName:(a==null?void 0:a.displayName)||(a==null?void 0:a.name)||(a!=null&&a.firstName&&(a!=null&&a.lastName)?`${a.firstName} ${a.lastName}`.trim():(a==null?void 0:a.email)||"User")});case 3:return e.jsxs(as.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(te,{className:"border-2",children:[e.jsx(me,{className:"bg-gradient-to-br from-blue-50 to-indigo-50",children:e.jsxs(he,{className:"flex items-center gap-2",children:[e.jsx(us,{className:"w-5 h-5 text-blue-600"}),"Activity Information"]})}),e.jsx(se,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:p.activityName})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Type"}),e.jsx(ie,{variant:"secondary",className:"mt-1",children:p.activityType})]})]})})]}),e.jsxs(te,{className:"border-2",children:[e.jsx(me,{className:"bg-gradient-to-br from-green-50 to-emerald-50",children:e.jsxs(he,{className:"flex items-center gap-2",children:[e.jsx(ui,{className:"w-5 h-5 text-green-600"}),"Dealer Information"]})}),e.jsx(se,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(re,{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:p.dealerCode})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:p.dealerName})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Email"}),e.jsx("p",{className:"text-gray-900 mt-1",children:p.dealerEmail})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Phone"}),e.jsx("p",{className:"text-gray-900 mt-1",children:p.dealerPhone})]}),p.dealerAddress&&e.jsxs("div",{className:"col-span-2",children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Address"}),e.jsx("p",{className:"text-gray-900 mt-1",children:p.dealerAddress})]})]})})]}),e.jsxs(te,{className:"border-2",children:[e.jsx(me,{className:"bg-gradient-to-br from-purple-50 to-indigo-50",children:e.jsxs(he,{className:"flex items-center gap-2",children:[e.jsx(Mt,{className:"w-5 h-5 text-purple-600"}),"Selected Approvers"]})}),e.jsx(se,{className:"pt-6 space-y-4",children:e.jsx("div",{className:"space-y-3",children:[...p.approvers||[]].filter(f=>{var T,F;return!((T=f.email)!=null&&T.includes("system@"))&&!((F=f.email)!=null&&F.includes("finance@"))}).sort((f,T)=>f.level-T.level).map(f=>{const T=Number(f.tat||0),K=(f.tatType||"hours")==="days"?T*24:T;let B="Unknown",U="";if(f.isAdditional){B=f.stepName||"Additional Approver";const D=dl.find(A=>A.level===f.insertAfterLevel);U=f.stepName||`Additional Approver (after "${(D==null?void 0:D.name)||"Unknown"}")`}else{const D=f.originalStepLevel?dl.find(A=>A.level===f.originalStepLevel):dl.find(A=>A.level===f.level&&!A.isAuto);B=(D==null?void 0:D.name)||"Unknown",U=B}return e.jsx("div",{className:`p-3 rounded-lg border ${f.isAdditional?"bg-purple-50 border-purple-200":"bg-gray-50 border-gray-200"}`,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:U}),f.isAdditional&&e.jsx(ie,{variant:"outline",className:"text-xs bg-purple-100 text-purple-700 border-purple-300",children:"ADDITIONAL"})]}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:f.name||f.email||"Not selected"}),f.email&&e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:f.email})]}),e.jsxs("div",{className:"text-right ml-4",children:[e.jsxs("p",{className:"text-sm font-semibold text-gray-900",children:[K," hours"]}),e.jsx("p",{className:"text-xs text-gray-500",children:"TAT"})]})]})},`${f.level}-${f.email}`)})})})]}),e.jsxs(te,{className:"border-2",children:[e.jsx(me,{className:"bg-gradient-to-br from-purple-50 to-pink-50",children:e.jsxs(he,{className:"flex items-center gap-2",children:[e.jsx(mt,{className:"w-5 h-5 text-purple-600"}),"Date & Location"]})}),e.jsx(se,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:p.activityDate?Ie(p.activityDate,"PPP"):"N/A"})]}),e.jsxs("div",{children:[e.jsx(re,{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(so,{className:"w-4 h-4 text-gray-500"}),e.jsx("p",{className:"font-semibold text-gray-900",children:p.location})]})]}),p.estimatedBudget&&e.jsxs("div",{className:"col-span-2",children:[e.jsx(re,{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:p.estimatedBudget})]})]})})]}),e.jsxs(te,{className:"border-2",children:[e.jsx(me,{className:"bg-gradient-to-br from-orange-50 to-amber-50",children:e.jsxs(he,{className:"flex items-center gap-2",children:[e.jsx(Le,{className:"w-5 h-5 text-orange-600"}),"Request Details"]})}),e.jsx(se,{className:"pt-6 space-y-4",children:e.jsxs("div",{children:[e.jsx(re,{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(Ws,{content:p.requestDescription||"",className:"text-sm"})})]})})]}),(p.periodStartDate||p.periodEndDate)&&e.jsxs(te,{className:"border-2",children:[e.jsx(me,{className:"bg-gradient-to-br from-cyan-50 to-blue-50",children:e.jsxs(he,{className:"flex items-center gap-2",children:[e.jsx(Ze,{className:"w-5 h-5 text-cyan-600"}),"Period"]})}),e.jsx(se,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Start Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:p.periodStartDate?Ie(p.periodStartDate,"PPP"):"Not specified"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"End Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:p.periodEndDate?Ie(p.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(Nr,{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(I,{variant:"ghost",onClick:t,className:"mb-3 sm:mb-4 gap-2 text-sm sm:text-base",children:[e.jsx(Ys,{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(ie,{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 ",r," of ",b,": ",e.jsx("span",{className:"hidden sm:inline",children:ml[r-1]})]})]})}),e.jsxs("div",{className:"mt-4 sm:mt-6",children:[e.jsx(Qs,{value:r/b*100,className:"h-2"}),e.jsx("div",{className:"flex justify-between mt-2 px-1",children:ml.map((R,f)=>e.jsx("span",{className:`text-xs sm:text-sm ${f+1<=r?"text-blue-600 font-medium":"text-gray-400"}`,children:f+1},f))})]})]}),e.jsx(te,{className:"mb-6 sm:mb-8",children:e.jsx(se,{className:"p-4 sm:p-6 lg:p-8",children:e.jsx(vi,{mode:"wait",children:P()})})}),e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between gap-3 sm:gap-0 pb-4 sm:pb-0",children:[e.jsxs(I,{variant:"outline",onClick:C,disabled:r===1,className:"gap-2 w-full sm:w-auto order-2 sm:order-1",children:[e.jsx(Ys,{className:"w-4 h-4"}),"Previous"]}),r<b?e.jsxs(I,{onClick:N,className:`gap-2 w-full sm:w-auto order-1 sm:order-2 ${w()?"":"opacity-50 cursor-pointer hover:opacity-60"}`,children:["Next",e.jsx(rs,{className:"w-4 h-4"})]}):e.jsxs(I,{onClick:E,disabled:!w(),className:"gap-2 bg-green-600 hover:bg-green-700 w-full sm:w-auto order-1 sm:order-2",children:[e.jsx(jr,{className:"w-4 h-4"}),"Submit Claim Request"]})]})]})})}const{DocumentsTab:KA,ActivityTab:YA,WorkNotesTab:ZA,SummaryTab:XA,RequestDetailHeader:JA,QuickActionsSidebar:QA,RequestDetailModals:qA}=lx;let eT=class 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("Dealer Claim 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(hs,{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(I,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(I,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}};function tT({requestId:t,onBack:s,dynamicRequests:a=[]}){var Pr,Ir,Er,Mr,Fr,_r,Lr,Or,$r;const n=ir().requestId||t||"",l=new URLSearchParams(window.location.search).get("tab")||"overview",[o,c]=x.useState(l),[d,m]=x.useState(!1),[u,h]=x.useState(null),[g,p]=x.useState(null),[y,b]=x.useState(!1),[j,v]=x.useState(0),[w,N]=x.useState(!1),[C,S]=x.useState(!1),[E,P]=x.useState(!1),{user:R}=Kt(),{request:f,apiRequest:T,loading:F,refreshing:K,refreshDetails:B,currentApprovalLevel:U,isSpectator:D,isInitiator:A,existingParticipants:k,accessDenied:M}=po(n,a,R),O=(R==null?void 0:R.userId)||"",L=((Pr=R==null?void 0:R.email)==null?void 0:Pr.toLowerCase())||"",Z=(T==null?void 0:T.approvalFlow)||[],z=(T==null?void 0:T.approvals)||[],$=Z.find(rt=>(rt.levelName||rt.level_name||"").toLowerCase().includes("department lead"))||z.find(rt=>(rt.levelName||rt.level_name||"").toLowerCase().includes("department lead"))||Z.find(rt=>(rt.step||rt.levelNumber||rt.level_number)===3)||z.find(rt=>(rt.levelNumber||rt.level_number)===3),W=($==null?void 0:$.approverId)||($==null?void 0:$.approver_id)||((Ir=$==null?void 0:$.approver)==null?void 0:Ir.userId),_=(($==null?void 0:$.approverEmail)||($==null?void 0:$.approver_email)||((Er=$==null?void 0:$.approver)==null?void 0:Er.email)||"").toLowerCase().trim(),H=W&&W===O||_&&L&&_===L,{mergedMessages:V,unreadWorkNotes:ee,workNoteAttachments:oe,setWorkNoteAttachments:pe}=Yp(n,T,o,R),{uploadingDocument:Pe,triggerFileInput:Se,previewDocument:ne,setPreviewDocument:de,documentPolicy:le,documentError:fe,setDocumentError:st}=Zp(T,B),[ae,je]=x.useState(null),gt=ae||U,{showApproveModal:be,setShowApproveModal:Oe,showRejectModal:ut,setShowRejectModal:wt,showAddApproverModal:dt,setShowAddApproverModal:is,showAddSpectatorModal:Bs,setShowAddSpectatorModal:ma,showSkipApproverModal:Q,setShowSkipApproverModal:ge,showActionStatusModal:X,setShowActionStatusModal:Ae,skipApproverData:Te,setSkipApproverData:$e,actionStatus:ke,setActionStatus:Ge,handleApproveConfirm:Fe,handleRejectConfirm:Xe,handleAddApprover:ls,handleSkipApprover:Lt,handleAddSpectator:et}=Jp(n,gt,B),Je=async rt=>{await Fe(rt),je(null)},ht=async rt=>{await Xe(rt),je(null)},zt=((f==null?void 0:f.status)||(T==null?void 0:T.status)||"").toLowerCase(),Dt=(zt==="approved"||zt==="rejected")&&A;console.debug("[DealerClaimRequestDetail] Closure check:",{requestStatus:zt,requestStatusRaw:f==null?void 0:f.status,apiRequestStatusRaw:T==null?void 0:T.status,isInitiator:A,needsClosure:Dt});const{conclusionRemark:Us,setConclusionRemark:Xs,conclusionLoading:ua,conclusionSubmitting:ha,aiGenerated:ft,handleGenerateConclusion:Oa,handleFinalizeConclusion:$a}=Xp(f,n,A,B,s,Ge,Ae);x.useEffect(()=>{const ds=new URLSearchParams(window.location.search).get("tab");ds&&c(ds)},[n]);const Ba=()=>{B()},Ua=()=>{N(!0)},Va=()=>{S(!0)},ss=async()=>{await B()},Cs=()=>{P(!0)},wa=async()=>{await B()},kn=async()=>{await B()},Dr=async()=>{if(!(T!=null&&T.requestId)){q.error("Request ID not found");return}if(!u){q.error("Summary not available. Please ensure the request is closed and the summary has been generated.");return}m(!0)},za=(f==null?void 0:f.status)==="closed"||(f==null?void 0:f.status)==="approved"&&!A||(f==null?void 0:f.status)==="rejected"&&!A;x.useEffect(()=>{(async()=>{if(!za||!(T!=null&&T.requestId)){p(null),h(null);return}try{b(!0);const ds=await ax(T.requestId);if(ds!=null&&ds.summaryId){h(ds.summaryId);try{const sa=await Xo(ds.summaryId);p(sa)}catch(sa){console.error("Failed to fetch summary details:",sa),p(null),h(null)}}else p(null),h(null)}catch{p(null),h(null)}finally{b(!1)}})()},[za,T==null?void 0:T.requestId]),x.useEffect(()=>{if(!O||!(T!=null&&T.requestId))return;const rt=fr();if(!rt)return;Zu(rt,O);const ds=sa=>{var Ur,Vr,zr,Hr;const aa=sa==null?void 0:sa.notification;if(!aa)return;const Dn=aa.requestId||aa.request_id,Br=((Ur=aa.metadata)==null?void 0:Ur.requestNumber)||((Vr=aa.metadata)==null?void 0:Vr.request_number);Dn!==T.requestId&&Br!==n&&Br!==T.requestNumber||((zr=aa.metadata)!=null&&zr.creditNoteNumber||(Hr=aa.metadata)!=null&&Hr.credit_note_number)&&B()};return rt.on("notification:new",ds),()=>{rt.off("notification:new",ds)}},[O,T==null?void 0:T.requestId,n,B]);const Rr=((f==null?void 0:f.approvalFlow)||[]).filter(rt=>rt&&typeof rt.step=="number").map(rt=>({levelNumber:rt.step||0,approverName:rt.approver||"Unknown",status:rt.status||"pending",tatHours:rt.tatHours||24}));return F&&!f&&!T?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(ns,{className:"w-12 h-12 text-blue-600 animate-spin mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading dealer claim request details..."})]})}):M!=null&&M.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(Su,{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:M.message}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsxs(I,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(Ys,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(I,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})}):f?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"min-h-screen bg-gray-50","data-testid":"dealer-claim-request-detail-page",children:e.jsxs("div",{className:"max-w-7xl mx-auto",children:[e.jsx(JA,{request:f,refreshing:K,onBack:s||(()=>window.history.back()),onRefresh:Ba,onShareSummary:Dr,isInitiator:A,slaData:((Mr=f==null?void 0:f.summary)==null?void 0:Mr.sla)||(f==null?void 0:f.sla)||null,isPaused:((Fr=f==null?void 0:f.pauseInfo)==null?void 0:Fr.isPaused)||!1}),e.jsxs(wn,{value:o,onValueChange:c,className:"w-full","data-testid":"dealer-claim-request-detail-tabs",children:[e.jsx("div",{className:"mb-4 sm:mb-6",children:e.jsxs(Cn,{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(Ct,{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(Au,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Overview"})]}),za&&g&&e.jsxs(Ct,{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(ao,{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(Ct,{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(da,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Workflow"})]}),H&&e.jsxs(Ct,{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(Pa,{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(Ct,{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(Le,{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(Ct,{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(ts,{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(Ct,{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(Os,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Work Notes"}),ee>0&&e.jsx(ie,{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:ee>9?"9+":ee})]})]})}),e.jsxs("div",{className:o==="worknotes"?"":"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs("div",{className:o==="worknotes"?"":"lg:col-span-2",children:[e.jsx(St,{value:"overview",className:"mt-0","data-testid":"overview-tab-content",children:e.jsx(V2,{request:f,apiRequest:T,currentUserId:O,isInitiator:A,needsClosure:Dt,conclusionRemark:Us,setConclusionRemark:Xs,conclusionLoading:ua,conclusionSubmitting:ha,aiGenerated:ft,handleGenerateConclusion:Oa,handleFinalizeConclusion:$a})}),za&&e.jsx(St,{value:"summary",className:"mt-0","data-testid":"summary-tab-content",children:e.jsx(XA,{summary:g,loading:y,onShare:Dr,isInitiator:A})}),e.jsx(St,{value:"workflow",className:"mt-0",children:e.jsx(oS,{request:f,user:R,isInitiator:A,onSkipApprover:rt=>{if(!rt.levelId){alert("Level ID not available");return}$e(rt),ge(!0)},onRefresh:B})}),H&&e.jsx(St,{value:"io",className:"mt-0",children:e.jsx(cS,{request:f,apiRequest:T,onRefresh:B})}),e.jsx(St,{value:"documents",className:"mt-0",children:e.jsx(KA,{request:f,workNoteAttachments:oe,uploadingDocument:Pe,documentPolicy:le,triggerFileInput:Se,setPreviewDocument:de,downloadDocument:nr})}),e.jsx(St,{value:"activity",className:"mt-0",children:e.jsx(YA,{request:f})}),e.jsx(St,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:o!=="worknotes",children:e.jsx(ZA,{requestId:n,requestTitle:f.title,mergedMessages:V,setWorkNoteAttachments:pe,isInitiator:A,isSpectator:D,currentLevels:Rr,onAddApprover:ls})})]}),o!=="worknotes"&&e.jsx(QA,{request:f,isInitiator:A,isSpectator:D,currentApprovalLevel:Si(T)?null:U,onAddApprover:()=>is(!0),onAddSpectator:()=>ma(!0),onApprove:()=>Oe(!0),onReject:()=>wt(!0),onPause:Ua,onResume:Va,onRetrigger:Cs,summaryId:u,refreshTrigger:j,pausedByUserId:(Lr=(_r=f==null?void 0:f.pauseInfo)==null?void 0:_r.pausedBy)==null?void 0:Lr.userId,currentUserId:O,apiRequest:T})]})]})]})}),d&&u&&e.jsx(ox,{isOpen:d,onClose:()=>m(!1),summaryId:u,requestTitle:(f==null?void 0:f.title)||"N/A",onSuccess:()=>{B(),v(rt=>rt+1)}}),w&&(T==null?void 0:T.requestId)&&e.jsx(cx,{isOpen:w,onClose:()=>N(!1),requestId:T.requestId,levelId:(U==null?void 0:U.levelId)||null,onSuccess:wa}),C&&(T==null?void 0:T.requestId)&&e.jsx(dx,{isOpen:C,onClose:()=>S(!1),requestId:T.requestId,onSuccess:ss}),E&&(T==null?void 0:T.requestId)&&e.jsx(mx,{isOpen:E,onClose:()=>P(!1),requestId:T.requestId,approverName:($r=(Or=f==null?void 0:f.pauseInfo)==null?void 0:Or.pausedBy)==null?void 0:$r.name,onSuccess:kn}),e.jsx(qA,{showApproveModal:be,showRejectModal:ut,showAddApproverModal:dt,showAddSpectatorModal:Bs,showSkipApproverModal:Q,showActionStatusModal:X,previewDocument:ne,documentError:fe,request:f,skipApproverData:Te,actionStatus:ke,existingParticipants:k,currentLevels:Rr,setShowApproveModal:Oe,setShowRejectModal:wt,setShowAddApproverModal:is,setShowAddSpectatorModal:ma,setShowSkipApproverModal:ge,setShowActionStatusModal:Ae,setPreviewDocument:de,setDocumentError:st,setSkipApproverData:$e,setActionStatus:Ge,handleApproveConfirm:Je,handleRejectConfirm:ht,handleAddApprover:ls,handleAddSpectator:et,handleSkipApprover:Lt,downloadDocument:nr,documentPolicy:le})]}):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(Le,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-3",children:"Dealer Claim Request Not Found"}),e.jsx("p",{className:"text-gray-600 mb-6",children:"The dealer claim 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(I,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(Ys,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(I,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})})}function sT(t){return e.jsx(eT,{children:e.jsx(tT,{...t})})}function aT(t){switch(t){case"DEALER_CLAIM":return sT;case"CUSTOM":default:return U2}}class rT 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 Router 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(hs,{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(I,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(I,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}}function nT({requestId:t,onBack:s,dynamicRequests:a=[]}){const n=ir().requestId||t||"",{user:i}=Kt(),{apiRequest:l,loading:o}=po(n,a,i);if(o&&!l)return 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(ns,{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..."})]})});const c=Rv(l),d=aT(c);return e.jsx(d,{requestId:t,onBack:s,dynamicRequests:a})}function iT(t){return e.jsx(rT,{children:e.jsx(nT,{...t})})}function lT({onViewSummary:t}){const s=_a(),[a,r]=x.useState([]),[n,i]=x.useState(!0),[l,o]=x.useState(""),[c,d]=x.useState(1),[m,u]=x.useState(1),[h,g]=x.useState(0),p=10,y=x.useCallback(async(w=1)=>{try{i(!0);const N=await v2({page:w,limit:p});r(N.data||[]),u(N.pagination.totalPages||1),g(N.pagination.total||0),d(N.pagination.page||1)}catch(N){console.error("Failed to fetch shared summaries:",N),q.error("Failed to load shared summaries")}finally{i(!1)}},[]);x.useEffect(()=>{y(1)},[y]);const b=async w=>{try{await sx(w),r(N=>N.map(C=>C.sharedSummaryId===w?{...C,isRead:!0,viewedAt:new Date().toISOString()}:C)),t?t(w):s(`/shared-summaries/${w}`)}catch(N){console.error("Failed to mark as viewed:",N),t?t(w):s(`/shared-summaries/${w}`)}},j=w=>{w>=1&&w<=m&&y(w)},v=a.filter(w=>{var C,S,E,P;if(!l)return!0;const N=l.toLowerCase();return((C=w.title)==null?void 0:C.toLowerCase().includes(N))||((S=w.requestNumber)==null?void 0:S.toLowerCase().includes(N))||((E=w.initiatorName)==null?void 0:E.toLowerCase().includes(N))||((P=w.sharedByName)==null?void 0:P.toLowerCase().includes(N))});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($s,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(Re,{placeholder:"Search by title, request number, or user...",value:l,onChange:w=>o(w.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(Qe,{className:"h-8 w-8 animate-spin text-blue-600"})}),!n&&v.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(Le,{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:l?"No summaries match your search.":"You haven't received any shared summaries yet."})]}),!n&&v.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid gap-3 sm:gap-4 mb-4 sm:mb-6",children:v.map(w=>e.jsx("div",{className:`bg-white rounded-lg shadow-sm border-2 transition-all cursor-pointer hover:shadow-md ${w.isRead?"border-gray-200":"border-blue-300 bg-blue-50"}`,onClick:()=>b(w.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:[w.isRead?e.jsx(Uf,{className:"h-4 w-4 text-gray-400 flex-shrink-0"}):e.jsx(bt,{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:w.title}),!w.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:w.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(Pt,{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:w.initiatorName})]})]}),e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(Pt,{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:w.sharedByName})]})]}),e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(mt,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Shared: ",Ie(new Date(w.sharedAt),"MMM dd, yyyy HH:mm")]})]}),w.viewedAt&&e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(bt,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Viewed: ",Ie(new Date(w.viewedAt),"MMM dd, yyyy HH:mm")]})]})]})]}),e.jsx(I,{variant:"outline",size:"sm",className:"w-full sm:w-auto flex-shrink-0",onClick:N=>{N.stopPropagation(),b(w.sharedSummaryId)},children:"View"})]})})},w.sharedSummaryId))}),m>1&&e.jsxs("div",{className:"flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-3 sm:gap-4 bg-white rounded-lg shadow-sm border border-gray-200 p-3 sm:p-4",children:[e.jsxs("div",{className:"text-xs sm:text-sm text-gray-600 text-center sm:text-left",children:["Showing ",(c-1)*p+1," to ",Math.min(c*p,h)," of ",h," summaries"]}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.jsx(I,{variant:"outline",size:"sm",onClick:()=>j(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(I,{variant:"outline",size:"sm",onClick:()=>j(c+1),disabled:c===m,className:"text-xs sm:text-sm",children:"Next"})]})]})]})]})})}function oT(){const{sharedSummaryId:t}=ir(),s=_a(),[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 sx(t)}catch(g){console.warn("Failed to mark as viewed:",g)}const h=await Xo(t);r(h)}catch(h){console.error("Failed to fetch summary details:",h),q.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 l=d=>{const m=d.toLowerCase();return m==="approved"?e.jsx(Ce,{className:"h-4 w-4 text-green-600"}):m==="rejected"?e.jsx(xt,{className:"h-4 w-4 text-red-600"}):m==="pending"||m==="in progress"?e.jsx(Ze,{className:"h-4 w-4 text-orange-600"}):e.jsx(Le,{className:"h-4 w-4 text-gray-600"})},o=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(Qe,{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(I,{variant:"ghost",size:"sm",onClick:()=>s("/shared-summaries"),className:"mb-4",children:[e.jsx(Ys,{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(ie,{className:o(a.workflow.status),children:[l(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(Ws,{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:Ie(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:[l(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:Ie(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(ie,{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(Ws,{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(Le,{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(I,{onClick:()=>s("/shared-summaries"),children:"Go Back"})]})})}function cT(){const{requestId:t}=ir(),s=_a(),a=i=>{s(`/${i}`)},r=()=>{s("/new-request")},n=()=>{s("/login")};return e.jsx(fs,{currentPage:"work-notes",onNavigate:a,onNewRequest:r,onLogout:n,children:e.jsx("div",{className:"h-full w-full overflow-hidden",children:e.jsx(tx,{requestId:t||""})})})}function Nx({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(ie,{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 Es({label:t,value:s,icon:a,iconColor:r,gradient:n,textColor:i,valueColor:l,testId:o="stats-card",onClick:c}){return e.jsx(te,{className:`${n} border transition-shadow ${c?"cursor-pointer hover:shadow-lg":"hover:shadow-md"}`,"data-testid":o,onClick:c,children:e.jsx(se,{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":`${o}-label`,children:t}),e.jsx("p",{className:`text-xl sm:text-2xl font-bold ${l}`,"data-testid":`${o}-value`,children:s})]}),e.jsx(a,{className:`w-6 h-6 sm:w-8 sm:h-8 ${r}`,"data-testid":`${o}-icon`})]})})})}function dT({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(Es,{label:"Total",value:t.total,icon:Le,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(Es,{label:"Pending",value:t.pending,icon:Ze,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(Es,{label:"Paused",value:t.paused,icon:Ra,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(Es,{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(Es,{label:"Rejected",value:t.rejected,icon:xt,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(Es,{label:"Draft",value:t.draft,icon:hi,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(Es,{label:"Closed",value:t.closed,icon:pi,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 mT({searchTerm:t,statusFilter:s,priorityFilter:a,templateTypeFilter:r,onSearchChange:n,onStatusChange:i,onPriorityChange:l,onTemplateTypeChange:o}){return e.jsx(te,{className:"border-gray-200","data-testid":"my-requests-filters",children:e.jsx(se,{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($s,{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(Re,{placeholder:"Search requests by title, description, or ID...",value:t,onChange:c=>n(c.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(Ue,{value:s,onValueChange:i,children:[e.jsx(ze,{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(Ve,{placeholder:"Status"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"all",children:"All Status"}),e.jsx(Y,{value:"draft",children:"Draft"}),e.jsx(Y,{value:"pending",children:"Pending"}),e.jsx(Y,{value:"paused",children:"Paused"}),e.jsx(Y,{value:"approved",children:"Approved"}),e.jsx(Y,{value:"rejected",children:"Rejected"}),e.jsx(Y,{value:"closed",children:"Closed"})]})]}),e.jsxs(Ue,{value:a,onValueChange:l,children:[e.jsx(ze,{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(Ve,{placeholder:"Priority"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"all",children:"All Priority"}),e.jsx(Y,{value:"express",children:"Express"}),e.jsx(Y,{value:"standard",children:"Standard"})]})]}),e.jsxs(Ue,{value:r,onValueChange:o,children:[e.jsx(ze,{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":"template-type-filter",children:e.jsx(Ve,{placeholder:"Template Type"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"all",children:"All Templates"}),e.jsx(Y,{value:"CUSTOM",children:"Custom"}),e.jsx(Y,{value:"DEALER CLAIM",children:"Dealer Claim"})]})]})]})]})})})}function uT(t){switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:ta,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Bt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Bt,iconColor:"text-gray-600"}}}function hT(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:xt,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:Ze,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:hi,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:We,iconColor:"text-gray-600"}}}const pT=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 xT({request:t,index:s,onViewRequest:a}){var o;const r=hT(t.status),n=uT(t.priority),i=r.icon,l=n.icon;return e.jsx(as.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:s*.1},children:e.jsx(te,{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(se,{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(ie,{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})]}),(((o=t.pauseInfo)==null?void 0:o.isPaused)||t.isPaused)&&e.jsxs(ie,{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(Ra,{className:"w-3 h-3 mr-1"}),"Paused"]}),e.jsxs(ie,{variant:"outline",className:`${n.color} border font-medium text-xs capitalize shrink-0`,"data-testid":"priority-badge",children:[e.jsx(l,{className:"w-3 h-3 mr-1"}),t.priority]}),(()=>{const c=(t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"",d=(c==null?void 0:c.toUpperCase())||"";let m="Custom",u="bg-purple-100 !text-purple-600 border-purple-200";return d==="DEALER CLAIM"?(m="Dealer Claim",u="bg-blue-100 !text-blue-700 border-blue-200"):d==="TEMPLATE"&&(m="Template"),e.jsx(ie,{variant:"outline",className:`${u} font-medium text-xs shrink-0`,"data-testid":"template-type-badge",children:m})})()]}),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:pT(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:"})," ",qs(t.submittedDate)]})]})]}),e.jsx(rs,{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(Pt,{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(da,{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(Ze,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{"data-testid":"submitted-timestamp",children:["Submitted: ",qs(t.submittedDate)]})]})]})]})})})})}function gT({requests:t,loading:s,searchTerm:a,statusFilter:r,priorityFilter:n,onViewRequest:i}){if(s)return e.jsx(te,{"data-testid":"loading-state",children:e.jsx(se,{className:"p-6 text-sm text-gray-600",children:"Loading your requests…"})});if(t.length===0){const l=a||r!=="all"||n!=="all";return e.jsx(te,{"data-testid":"empty-state",children:e.jsxs(se,{className:"p-12 text-center",children:[e.jsx(Le,{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:l?"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((l,o)=>e.jsx(xT,{request:l,index:o,onViewRequest:i},l.id))})}function fT(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||t.template_type,workflowType:t.workflowType||t.workflow_type,templateName:t.templateName||t.template_name}}function wx(t){return Array.isArray(t)?t.map(fT):[]}function yT({itemsPerPage:t=10}={}){const[s,a]=x.useState([]),[r,n]=x.useState(!1),[i,l]=x.useState(!1),[o,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 ws.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,templateType:u==null?void 0:u.templateType}),g=Array.isArray(h==null?void 0:h.data)?h.data:[],p=wx(g);a(p),l(!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([]),l(!0)}finally{n(!1)}},[t]);return{requests:s,loading:r,hasFetchedFromApi:i,pagination:o,fetchMyRequests:d}}const bT={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",currentPage:1},Cx=wr({name:"myRequests",initialState:bT,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},setTemplateTypeFilter:(t,s)=>{t.templateTypeFilter=s.payload,t.currentPage=1},setCurrentPage:(t,s)=>{t.currentPage=s.payload},clearFilters:t=>{t.searchTerm="",t.statusFilter="all",t.priorityFilter="all",t.templateTypeFilter="all",t.currentPage=1}}}),{setSearchTerm:vT,setStatusFilter:jT,setPriorityFilter:NT,setTemplateTypeFilter:wT,setCurrentPage:CT,clearFilters:ST}=Cx.actions;function AT({onFiltersChange:t,debounceMs:s=500}={}){const a=yn(),r=x.useRef(null),n=x.useRef(!0),{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:c,currentPage:d}=Sr(j=>j.myRequests),m=x.useCallback(j=>a(vT(j)),[a]),u=x.useCallback(j=>a(jT(j)),[a]),h=x.useCallback(j=>a(NT(j)),[a]),g=x.useCallback(j=>a(wT(j)),[a]),p=x.useCallback(j=>a(CT(j)),[a]),y=x.useCallback(()=>({search:i,status:l,priority:o,templateType:c}),[i,l,o,c]);x.useEffect(()=>{if(n.current){n.current=!1;return}r.current&&clearTimeout(r.current);const j=setTimeout(()=>{t&&t(y())},i?s:0);return r.current=j,()=>{r.current&&clearTimeout(r.current)}},[i,l,o,c,t,y,s]);const b=x.useCallback(()=>{a(ST())},[a]);return{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:c,currentPage:d,setSearchTerm:m,setStatusFilter:u,setPriorityFilter:h,setTemplateTypeFilter:g,setCurrentPage:p,getFilters:y,resetFilters:b}}function TT({onViewRequest:t,dynamicRequests:s=[]}){const{user:a}=Kt(),r=yT({itemsPerPage:10}),n=x.useRef(r.fetchMyRequests);n.current=r.fetchMyRequests;const i=AT(),l=x.useRef({searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,templateTypeFilter:i.templateTypeFilter}),o=x.useRef(!1);x.useEffect(()=>{const j=i.currentPage||1;n.current(j,{search:i.searchTerm||void 0,status:i.statusFilter!=="all"?i.statusFilter:void 0,priority:i.priorityFilter!=="all"?i.priorityFilter:void 0,templateType:i.templateTypeFilter!=="all"?i.templateTypeFilter:void 0}),o.current=!0},[]),x.useEffect(()=>{if(!o.current)return;const j=l.current;if(!(j.searchTerm!==i.searchTerm||j.statusFilter!==i.statusFilter||j.priorityFilter!==i.priorityFilter||j.templateTypeFilter!==i.templateTypeFilter))return;const w=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,templateType:i.templateTypeFilter!=="all"?i.templateTypeFilter:void 0}),l.current={searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,templateTypeFilter:i.templateTypeFilter}},i.searchTerm!==j.searchTerm?500:0);return()=>clearTimeout(w)},[i.searchTerm,i.statusFilter,i.priorityFilter,i.templateTypeFilter]);const[c,d]=x.useState(null),[m,u]=x.useState(!1),h=x.useCallback(async()=>{if(a!=null&&a.userId)try{u(!0);const j=await jt.getRequestStats("all",void 0,void 0,void 0,i.priorityFilter!=="all"?i.priorityFilter:void 0,i.templateTypeFilter!=="all"?i.templateTypeFilter:void 0,void 0,a.userId,void 0,void 0,i.searchTerm||void 0,void 0,!0);d({total:j.totalRequests||0,pending:j.openRequests||0,paused:j.pausedRequests||0,approved:j.approvedRequests||0,rejected:j.rejectedRequests||0,draft:j.draftRequests||0,closed:j.closedRequests||0})}catch(j){console.error("Failed to fetch backend stats:",j),d(null)}finally{u(!1)}},[a==null?void 0:a.userId,i.searchTerm,i.priorityFilter,i.templateTypeFilter]);x.useEffect(()=>{const j=setTimeout(()=>{h()},i.searchTerm?500:0);return()=>clearTimeout(j)},[i.searchTerm,i.priorityFilter,i.templateTypeFilter,h]);const g=wx(s),p=r.hasFetchedFromApi?r.requests:g,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]),b=x.useCallback(j=>{j>=1&&j<=r.pagination.totalPages&&(i.setCurrentPage(j),r.fetchMyRequests(j,{search:i.searchTerm||void 0,status:i.statusFilter!=="all"?i.statusFilter:void 0,priority:i.priorityFilter!=="all"?i.priorityFilter:void 0,templateType:i.templateTypeFilter!=="all"?i.templateTypeFilter: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(Nx,{icon:Le,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(dT,{stats:y,onStatusFilter:j=>{i.setStatusFilter(j)}}),e.jsx(mT,{searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,templateTypeFilter:i.templateTypeFilter,onSearchChange:i.setSearchTerm,onStatusChange:i.setStatusFilter,onPriorityChange:i.setPriorityFilter,onTemplateTypeChange:i.setTemplateTypeFilter}),e.jsx(gT,{requests:p,loading:r.loading,searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,onViewRequest:t}),e.jsx(lr,{currentPage:i.currentPage||r.pagination.currentPage,totalPages:r.pagination.totalPages,totalRecords:r.pagination.totalRecords,itemsPerPage:r.pagination.itemsPerPage,onPageChange:b,loading:r.loading,itemLabel:"requests",testIdPrefix:"my-requests-pagination"})]})}function Sx({isOrgLevel:t,isAdmin:s,loading:a,exporting:r,onExport:n}){const i=()=>"All Requests",l=()=>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(Nx,{icon:Le,title:i(),description:l(),testId:"requests-header"}),e.jsx(ie,{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(I,{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(ns,{className:"w-4 h-4 mr-2 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Nt,{className:"w-4 h-4 mr-2"}),"Export"]})})]})}function Ax({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(Es,{label:"Total",value:t.total,icon:Le,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(Es,{label:"Pending",value:t.pending,icon:Ze,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(Es,{label:"Paused",value:t.paused,icon:Ra,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(Es,{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(Es,{label:"Rejected",value:t.rejected,icon:xt,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(Es,{label:"Closed",value:t.closed,icon:pi,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 kT=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:ta,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Bt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Bt,iconColor:"text-gray-600"}}},DT=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:xt,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:Ze,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:hi,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:We,iconColor:"text-gray-600"}}},RT=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 PT({request:t,index:s,onViewRequest:a}){var o;const r=DT(t.status),n=kT(t.priority),i=r.icon,l=n.icon;return e.jsx(as.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:s*.1},children:e.jsx(te,{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(se,{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(ie,{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})]}),(((o=t.pauseInfo)==null?void 0:o.isPaused)||t.isPaused)&&e.jsxs(ie,{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(Ra,{className:"w-3 h-3 mr-1"}),"Paused"]}),e.jsxs(ie,{variant:"outline",className:`${n.color} border font-medium text-xs capitalize shrink-0`,"data-testid":"priority-badge",children:[e.jsx(l,{className:"w-3 h-3 mr-1"}),t.priority]}),(()=>{const c=(t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"",d=(c==null?void 0:c.toUpperCase())||"";let m="Custom",u="bg-purple-100 !text-purple-600 border-purple-200";return d==="DEALER CLAIM"?(m="Dealer Claim",u="bg-blue-100 !text-blue-700 border-blue-200"):d==="TEMPLATE"&&(m="Template"),e.jsx(ie,{variant:"outline",className:`${u} font-medium text-xs shrink-0`,"data-testid":"template-type-badge",children:m})})(),t.department&&e.jsx(ie,{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:RT(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:"})," ",qs(t.submittedDate)]})]})]}),e.jsx(rs,{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(Pt,{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(da,{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(Ze,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{"data-testid":"submitted-timestamp",children:["Submitted: ",qs(t.submittedDate)]})]})]})]})})})})}function Tx({requests:t,loading:s,hasActiveFilters:a,onViewRequest:r}){return s?e.jsx(te,{"data-testid":"loading-state",children:e.jsx(se,{className:"p-6 text-sm text-gray-600",children:"Loading requests…"})}):t.length===0?e.jsx(te,{"data-testid":"empty-state",children:e.jsxs(se,{className:"p-12 text-center",children:[e.jsx(Le,{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(PT,{request:n,index:i,onViewRequest:r},n.id))})}const IT={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",slaComplianceFilter:"all",departmentFilter:"all",initiatorFilter:"all",approverFilter:"all",approverFilterType:"current",dateRange:"all",customStartDate:void 0,customEndDate:void 0,showCustomDatePicker:!1,currentPage:1},kx=wr({name:"requests",initialState:IT,reducers:{setSearchTerm:(t,s)=>{t.searchTerm=s.payload},setStatusFilter:(t,s)=>{t.statusFilter=s.payload},setPriorityFilter:(t,s)=>{t.priorityFilter=s.payload},setTemplateTypeFilter:(t,s)=>{t.templateTypeFilter=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.templateTypeFilter="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:ET,setStatusFilter:MT,setPriorityFilter:FT,setTemplateTypeFilter:_T,setSlaComplianceFilter:LT,setDepartmentFilter:OT,setInitiatorFilter:$T,setApproverFilter:BT,setApproverFilterType:UT,setDateRange:Km,setCustomStartDate:ul,setCustomEndDate:hl,setShowCustomDatePicker:Ln,setCurrentPage:VT,clearFilters:zT}=kx.actions;function Dx(){const t=yn(),{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,slaComplianceFilter:i,departmentFilter:l,initiatorFilter:o,approverFilter:c,approverFilterType:d,dateRange:m,customStartDate:u,customEndDate:h,showCustomDatePicker:g,currentPage:p}=Sr(k=>k.requests),y=x.useCallback(k=>t(ET(k)),[t]),b=x.useCallback(k=>t(MT(k)),[t]),j=x.useCallback(k=>t(FT(k)),[t]),v=x.useCallback(k=>t(_T(k)),[t]),w=x.useCallback(k=>t(LT(k)),[t]),N=x.useCallback(k=>t(OT(k)),[t]),C=x.useCallback(k=>t($T(k)),[t]),S=x.useCallback(k=>t(BT(k)),[t]),E=x.useCallback(k=>t(UT(k)),[t]),P=x.useCallback(k=>t(Km(k)),[t]),R=x.useCallback(k=>t(ul(k)),[t]),f=x.useCallback(k=>t(hl(k)),[t]),T=x.useCallback(k=>t(Ln(k)),[t]),F=x.useCallback(k=>t(VT(k)),[t]),K=x.useCallback(()=>({search:s||void 0,status:a!=="all"?a:void 0,priority:r!=="all"?r:void 0,templateType:n!=="all"?n:void 0,slaCompliance:i!=="all"?i:void 0,department:l!=="all"?l:void 0,initiator:o!=="all"?o:void 0,approver:c!=="all"?c:void 0,approverType:c!=="all"?d:void 0,dateRange:m,startDate:u,endDate:h}),[s,a,r,n,i,l,o,c,d,m,u,h]),B=x.useCallback(()=>{t(zT())},[t]),U=x.useCallback(k=>{const M=k;t(Km(M)),M!=="custom"?(t(ul(void 0)),t(hl(void 0)),t(Ln(!1))):t(Ln(!0))},[t]),D=x.useCallback(()=>{u&&h&&(u>h&&(t(ul(h)),t(hl(u))),t(Ln(!1)))},[u,h,t]);return{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,slaComplianceFilter:i,departmentFilter:l,initiatorFilter:o,approverFilter:c,approverFilterType:d,dateRange:m,customStartDate:u,customEndDate:h,showCustomDatePicker:g,currentPage:p,hasActiveFilters:!!(s||a!=="all"||r!=="all"||n!=="all"||i!=="all"||l!=="all"||o!=="all"||c!=="all"||m!=="all"||u||h),setSearchTerm:y,setStatusFilter:b,setPriorityFilter:j,setTemplateTypeFilter:v,setSlaComplianceFilter:w,setDepartmentFilter:N,setInitiatorFilter:C,setApproverFilter:S,setApproverFilterType:E,setDateRange:P,setCustomStartDate:R,setCustomEndDate:f,setShowCustomDatePicker:T,setCurrentPage:F,getFilters:K,clearFilters:B,handleDateRangeChange:U,handleApplyCustomDate:D}}function ai({allUsers:t,filterValue:s,onFilterChange:a}){const[r,n]=x.useState(""),[i,l]=x.useState([]),[o,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(b=>b.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){l([]),c(!1);return}u.current=setTimeout(()=>{const b=y.toLowerCase().trim(),j=t.filter(v=>{const w=(v.email||"").toLowerCase(),N=(v.displayName||"").toLowerCase();return w.includes(b)||N.includes(b)});l(j.slice(0,10)),c(j.length>0)},300)},[t]),g=x.useCallback(y=>{m(y),a(y.userId),n(y.displayName||y.email),c(!1),l([])},[a]),p=x.useCallback(()=>{m(null),a("all"),n(""),c(!1),l([])},[a]);return{searchQuery:r,searchResults:i,showResults:o,selectedUser:d,handleSearch:h,handleSelect:g,handleClear:p,setShowResults:c}}function HT(t){var d,m,u,h,g,p,y;const s=t.submittedAt||t.submitted_at||t.createdAt||t.created_at,a=(t.priority||"").toString().toLowerCase(),r=(t.status||"").toString().toUpperCase();let n="—",i="—";const l=t.currentApprover||t.current_approver||t.currentApproverData;if(l)n=l.name||l.approverName||l.displayName||l.email||l.approverEmail||"—";else if(t.approvals&&Array.isArray(t.approvals)&&t.approvals.length>0){const b=t.approvals.find(j=>{const v=(j.status||"").toString().toUpperCase();return v==="PENDING"||v==="IN_PROGRESS"});if(b)n=b.approverName||((d=b.approver)==null?void 0:d.name)||((m=b.approver)==null?void 0:m.displayName)||b.approverEmail||((u=b.approver)==null?void 0:u.email)||"—";else{const v=[...t.approvals].sort((w,N)=>{const C=w.levelNumber||w.level_number||0;return(N.levelNumber||N.level_number||0)-C})[0];v&&(n=v.approverName||((h=v.approver)==null?void 0:h.name)||((g=v.approver)==null?void 0:g.displayName)||v.approverEmail||((p=v.approver)==null?void 0:p.email)||"—")}}const o=t.currentLevel||t.current_level||t.currentLevelNumber||t.current_level_number,c=t.totalLevels||t.total_levels||t.totalLevelsCount||t.total_levels_count;if(o&&c)i=`${o} of ${c}`;else if(t.approvals&&Array.isArray(t.approvals)&&t.approvals.length>0){const b=t.approvals.find(j=>{const v=(j.status||"").toString().toUpperCase();return v==="PENDING"||v==="IN_PROGRESS"});if(b){const j=b.levelNumber||b.level_number||0,v=c||t.approvals.length;i=`${j} of ${v}`}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||t.template_type,workflowType:t.workflowType||t.workflow_type,templateName:t.templateName||t.template_name}}function Rx(t){return Array.isArray(t)?t.map(HT):[]}function WT(t,s,a,r,n,i){if(t.length>0){const l=t.length,o=t.filter(g=>{const p=(g.status||"").toString().toUpperCase();return p==="PENDING"||p==="IN_PROGRESS"}).length,c=t.filter(g=>(g.status||"").toString().toUpperCase()==="APPROVED").length,d=t.filter(g=>(g.status||"").toString().toUpperCase()==="REJECTED").length,m=t.filter(g=>(g.status||"").toString().toUpperCase()==="DRAFT").length,u=t.filter(g=>(g.status||"").toString().toUpperCase()==="CLOSED").length,h=t.filter(g=>(g.status||"").toString().toUpperCase()==="PAUSED").length;return{total:l,pending:o,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(o=>o.status==="pending"||o.status==="in-progress").length,paused:i.filter(o=>o.status==="paused").length,approved:i.filter(o=>o.status==="approved").length,rejected:i.filter(o=>o.status==="rejected").length,draft:i.filter(o=>o.status==="draft").length,closed:i.filter(o=>o.status==="closed").length}}var Px={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(ri,function(){return function(a,r){r.prototype.isSameOrBefore=function(n,i){return this.isSame(n,i)||this.isBefore(n,i)}}})})(Px);var GT=Px.exports;const Ix=ni(GT);var Ex={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(ri,function(){return function(a,r){r.prototype.isSameOrAfter=function(n,i){return this.isSame(n,i)||this.isAfter(n,i)}}})})(Ex);var KT=Ex.exports;const Mx=ni(KT);Ot.extend(Mx);Ot.extend(Ix);function YT(t,s){let a=[...t];if(s.search){const r=s.search.toLowerCase();a=a.filter(n=>{var i,l,o,c;return((i=n.title)==null?void 0:i.toLowerCase().includes(r))||((l=n.description)==null?void 0:l.toLowerCase().includes(r))||((o=n.requestNumber)==null?void 0:o.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 l;const n=(r.status||"").toString().toUpperCase(),i=((l=r.pauseInfo)==null?void 0:l.isPaused)||r.isPaused||!1;return(n==="PENDING"||n==="IN_PROGRESS")&&!i});else if(s.status.toLowerCase()==="paused")a=a.filter(r=>{var l;const n=(r.status||"").toString().toUpperCase(),i=((l=r.pauseInfo)==null?void 0:l.isPaused)||r.isPaused||!1;return n==="PAUSED"||i});else{const r=s.status.toUpperCase().replace("-","_");a=a.filter(n=>{var o;const i=(n.status||"").toString().toUpperCase(),l=((o=n.pauseInfo)==null?void 0:o.isPaused)||n.isPaused||!1;return r==="IN_PROGRESS"||r==="IN-PROGRESS"?i==="IN_PROGRESS"&&!l:i===r&&!l})}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,l;return(r.initiatorId||r.initiator_id||((i=r.initiator)==null?void 0:i.userId)||((l=r.initiator)==null?void 0:l.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 l,o,c,d,m,u;return(((l=n.currentApprover)==null?void 0:l.userId)||((o=n.currentApprover)==null?void 0:o.user_id)||((d=(c=n.approvals)==null?void 0:c.find(h=>{const g=(h.status||"").toString().toUpperCase();return g==="IN_PROGRESS"||g==="PENDING"}))==null?void 0:d.approverId)||((u=(m=n.approvals)==null?void 0:m.find(h=>{const g=(h.status||"").toString().toUpperCase();return g==="IN_PROGRESS"||g==="PENDING"}))==null?void 0:u.approver_id)||n.currentApproverId||n.current_approver_id)===s.approver}):a=a.filter(n=>{var l,o;const i=[];return(l=n.currentApprover)!=null&&l.userId&&i.push(n.currentApprover.userId),(o=n.currentApprover)!=null&&o.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,g,p,y,b,j,v,w;const n=s.slaCompliance||"";if(n.toLowerCase()==="compliant"){const N=(r.status||"").toString().toUpperCase();if(!(N==="APPROVED"||N==="REJECTED"||N==="CLOSED"))return!1;const S=((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)||((g=(h=r.summary)==null?void 0:h.sla)==null?void 0:g.status);return S?S!=="breached"&&S.toLowerCase()!=="breached":!0}const i=((p=r.currentLevelSLA)==null?void 0:p.status)||((b=(y=r.currentApprover)==null?void 0:y.sla)==null?void 0:b.status)||((j=r.sla)==null?void 0:j.status)||((w=(v=r.summary)==null?void 0:v.sla)==null?void 0:w.status);if(!i)return n==="on-track"||n==="on_track";const o={"on-track":"on_track",on_track:"on_track",approaching:"approaching",critical:"critical",breached:"breached"}[n.toLowerCase()]||n.toLowerCase();return i===o||i.toLowerCase()===o})),s.dateRange){let r=null,n=null;if(s.dateRange==="custom"&&s.startDate&&s.endDate)r=Ot(s.startDate).startOf("day").toDate(),n=Ot(s.endDate).endOf("day").toDate();else{const i=Ot();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 l=i.submittedAt||i.submission_date||i.submitted_at;if(!l){const m=i.createdAt||i.created_at||i.created_date;if(!m)return!1;const u=Ot(m).startOf("day").toDate(),h=Ot(r).startOf("day").toDate(),g=Ot(n).endOf("day").toDate();return u>=h&&u<=g}const o=Ot(l).startOf("day").toDate(),c=Ot(r).startOf("day").toDate(),d=Ot(n).endOf("day").toDate();return o>=c&&o<=d}))}return a}Ot.extend(Ix);Ot.extend(Mx);function ZT(t){if(!t)return"N/A";try{const s=typeof t=="string"?new Date(t):t;return Ie(s,"yyyy-MM-dd HH:mm:ss")}catch{return"N/A"}}async function Fx(t,s){const a=YT(t,s),r=[["Request Number","Title","Status","Priority","Initiator","Department","Current Approver","Approval Level","Submitted Date","Description"].join(",")];a.forEach(c=>{var v,w,N,C,S;const d=(c.status||"").toString().toLowerCase().replace("_","-"),m=(c.priority||"").toString().toLowerCase(),u=((v=c.initiator)==null?void 0:v.displayName)||((w=c.initiator)==null?void 0:w.email)||c.initiatorName||"N/A",h=c.department||((N=c.initiator)==null?void 0:N.department)||"N/A",g=((C=c.currentApprover)==null?void 0:C.displayName)||((S=c.currentApprover)==null?void 0:S.email)||c.currentApproverName||"N/A",p=c.currentApproverLevel||c.approvalLevel||c.currentLevel||"N/A",y=ZT(c.submittedAt||c.createdAt||c.submitted_at||c.created_at),b=(c.description||"").replace(/"/g,'""').replace(/\n/g," ").replace(/\r/g,""),j=[c.requestNumber||c.request_number||"",`"${(c.title||"").replace(/"/g,'""')}"`,d,m,`"${u.replace(/"/g,'""')}"`,`"${h.replace(/"/g,'""')}"`,`"${g.replace(/"/g,'""')}"`,p,y,`"${b}"`];r.push(j.join(","))});const n=r.join(`
|
||
`),i=new Blob([n],{type:"text/csv;charset=utf-8;"}),l=document.createElement("a"),o=URL.createObjectURL(i);l.setAttribute("href",o),l.setAttribute("download",`requests-export-${new Date().toISOString().split("T")[0]}.csv`),l.style.visibility="hidden",document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(o)}async function XT({page:t,itemsPerPage:s,filters:a,isOrgLevel:r}){var n,i,l,o;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.templateType&&a.templateType!=="all"&&(c.templateType=a.templateType),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 ws.listWorkflows({page:t,limit:s,...c});let m=[];Array.isArray(d==null?void 0:d.data)?m=d.data:Array.isArray(d)&&(m=d);const u=m.filter(p=>(p.status||"").toString().toUpperCase()!=="DRAFT"),h=(d==null?void 0:d.pagination)||{page:t,limit:s,total:u.length,totalPages:1};return{data:u,allData:[],filteredData:u,pagination:{page:h.page,limit:h.limit||s,total:h.total||u.length,totalPages:h.totalPages||1}}}else{const c={};a!=null&&a.search&&(c.search=a.search),a!=null&&a.status&&a.status!=="all"&&(c.status=a.status),a!=null&&a.priority&&a.priority!=="all"&&(c.priority=a.priority),a!=null&&a.templateType&&a.templateType!=="all"&&(c.templateType=a.templateType),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=(l=a.startDate)==null?void 0:l.toISOString()),a!=null&&a.endDate&&(c.endDate=(o=a.endDate)==null?void 0:o.toISOString());const d=await ws.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(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:h}}}async function JT(t){const a=[];let r=1,n=!0;const i=100;for(;n&&r<=i;){const l=t?await ws.listWorkflows({page:r,limit:100}):await ws.listParticipantRequests({page:r,limit:100});let o=[];if(Array.isArray(l==null?void 0:l.data)?o=l.data:Array.isArray(l)&&(o=l),o.length>0){const c=o.filter(d=>(d.status||"").toString().toUpperCase()!=="DRAFT");a.push(...c),r++,l!=null&&l.pagination?n=r<=l.pagination.totalPages:n=o.length===100}else n=!1}return a}function QT({onViewRequest:t}){const{user:s}=Kt(),a=Sr(z=>z.dashboard.viewAsUser),r=x.useMemo(()=>xi(s),[s]),n=x.useMemo(()=>r&&!a,[r,a]),i=Dx(),[l,o]=x.useState([]),[c,d]=x.useState(!1),[m,u]=x.useState(!1),[h,g]=x.useState(null),[p,y]=x.useState([]),[b,j]=x.useState(!1),[v,w]=x.useState([]),[N,C]=x.useState(1),[S,E]=x.useState(0),[P]=x.useState(10),R=ai({allUsers:v,filterValue:i.initiatorFilter,onFilterChange:i.setInitiatorFilter}),f=ai({allUsers:v,filterValue:i.approverFilter,onFilterChange:i.setApproverFilter}),T=x.useCallback(async(z,$,W,_)=>{try{const G=_==null?void 0:_.slaCompliance;if(G&&G!=="all"&&G!=="breached"&&G!=="compliant"){const V={};_!=null&&_.search&&(V.search=_.search),_!=null&&_.priority&&_.priority!=="all"&&(V.priority=_.priority),_!=null&&_.department&&_.department!=="all"&&(V.department=_.department),_!=null&&_.initiator&&_.initiator!=="all"&&(V.initiator=_.initiator),_!=null&&_.approver&&_.approver!=="all"&&(V.approver=_.approver,V.approverType=_.approverType||"current"),V.slaCompliance=G,z&&(V.dateRange=z),$&&(V.startDate=$.toISOString()),W&&(V.endDate=W.toISOString());const ee=n?await ws.listWorkflows({page:1,limit:1e3,...V}):await ws.listParticipantRequests({page:1,limit:1e3,...V}),oe=Array.isArray(ee==null?void 0:ee.data)?ee.data:[],pe=oe.length,Pe=oe.filter(le=>{const fe=(le.status||"").toString().toUpperCase();return fe==="PENDING"||fe==="IN_PROGRESS"}).length,Se=oe.filter(le=>(le.status||"").toString().toUpperCase()==="APPROVED").length,ne=oe.filter(le=>(le.status||"").toString().toUpperCase()==="REJECTED").length,de=oe.filter(le=>(le.status||"").toString().toUpperCase()==="CLOSED").length;g({total:pe,pending:Pe,paused:0,approved:Se,rejected:ne,draft:0,closed:de})}else{const V=await jt.getRequestStats(z,$?$.toISOString():void 0,W?W.toISOString():void 0,void 0,_==null?void 0:_.priority,void 0,_==null?void 0:_.department,_==null?void 0:_.initiator,_==null?void 0:_.approver,_==null?void 0:_.approverType,_==null?void 0:_.search,_==null?void 0:_.slaCompliance,!n);g({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(G){console.error("Failed to fetch backend stats:",G)}finally{}},[n]),F=x.useCallback(async()=>{try{j(!0);const z=await jt.getDepartments();y(z)}catch{}finally{j(!1)}},[]),K=x.useCallback(async()=>{try{const $=(await Ms.getAllUsers()).map(W=>({userId:W.userId,email:W.email,displayName:W.displayName||W.email}));w($)}catch(z){console.error("Failed to fetch users:",z)}},[]),B=x.useRef(i),U=x.useRef(T);x.useEffect(()=>{B.current=i,U.current=T},[i,T]);const D=x.useCallback(async(z=1)=>{try{z===1&&(d(!0),o([]));const $=B.current.getFilters(),W=await XT({page:z,itemsPerPage:P,filters:$,isOrgLevel:n});o(W.data),i.setCurrentPage(W.pagination.page),C(W.pagination.totalPages),E(W.pagination.total)}catch{o([])}finally{d(!1)}},[P,n]),A=x.useCallback(async()=>{try{u(!0);const z=await JT(n);await Fx(z,i.getFilters())}catch(z){console.error("Failed to export requests:",z),alert("Failed to export requests. Please try again.")}finally{u(!1)}},[n,i]);x.useEffect(()=>{F(),K()},[F,K]),x.useEffect(()=>{const z=setTimeout(()=>{const $={priority:i.priorityFilter!=="all"?i.priorityFilter:void 0,templateType:i.templateTypeFilter!=="all"?i.templateTypeFilter: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},W=i.dateRange||"all";U.current(W,i.customStartDate,i.customEndDate,$)},i.searchTerm?500:0);return()=>clearTimeout(z)},[n,i.dateRange,i.customStartDate,i.customEndDate,i.priorityFilter,i.templateTypeFilter,i.departmentFilter,i.initiatorFilter,i.approverFilter,i.approverFilterType,i.searchTerm,i.slaComplianceFilter]);const k=x.useRef({searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,templateTypeFilter:i.templateTypeFilter,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}),M=x.useRef(!1);x.useEffect(()=>{const z=i.currentPage||1;D(z),M.current=!0},[]),x.useEffect(()=>{if(!M.current)return;const z=k.current;if(!(z.searchTerm!==i.searchTerm||z.statusFilter!==i.statusFilter||z.priorityFilter!==i.priorityFilter||z.templateTypeFilter!==i.templateTypeFilter||z.slaComplianceFilter!==i.slaComplianceFilter||z.departmentFilter!==i.departmentFilter||z.initiatorFilter!==i.initiatorFilter||z.approverFilter!==i.approverFilter||z.approverFilterType!==i.approverFilterType||z.dateRange!==i.dateRange||z.customStartDate!==i.customStartDate||z.customEndDate!==i.customEndDate||z.isOrgLevel!==n))return;const W=setTimeout(()=>{i.setCurrentPage(1),D(1),k.current={searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,templateTypeFilter:i.templateTypeFilter,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!==z.searchTerm?500:0);return()=>clearTimeout(W)},[n,i.searchTerm,i.statusFilter,i.priorityFilter,i.templateTypeFilter,i.slaComplianceFilter,i.departmentFilter,i.initiatorFilter,i.approverFilter,i.approverFilterType,i.dateRange,i.customStartDate,i.customEndDate]);const O=x.useCallback(z=>{z>=1&&z<=N&&(i.setCurrentPage(z),D(z))},[N,D,i]),L=x.useMemo(()=>Rx(l),[l]),Z=x.useMemo(()=>h?{total:h.total||0,pending:h.pending||0,paused:h.paused||0,approved:h.approved||0,rejected:h.rejected||0,draft:h.draft||0,closed:h.closed||0}:WT([],n,h,!1,S,L),[n,h,S,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(Sx,{isOrgLevel:n,isAdmin:r,loading:c,exporting:m,onExport:A}),e.jsx(Ax,{stats:Z,onStatusFilter:z=>{i.setStatusFilter(z)}}),e.jsx(te,{className:"border-gray-200 shadow-md","data-testid":"requests-filters",children:e.jsx(se,{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(gn,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),i.hasActiveFilters&&e.jsx(ie,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),i.hasActiveFilters&&e.jsxs(I,{variant:"ghost",size:"sm",onClick:i.clearFilters,className:"gap-2",children:[e.jsx(ns,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Vt,{}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 lg:grid-cols-6 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative md:col-span-3 lg:col-span-1",children:[e.jsx($s,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Re,{placeholder:"Search requests...",value:i.searchTerm,onChange:z=>i.setSearchTerm(z.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(Ue,{value:i.statusFilter,onValueChange:i.setStatusFilter,children:[e.jsx(ze,{className:"h-10","data-testid":"status-filter",children:e.jsx(Ve,{placeholder:"All Status"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"all",children:"All Status"}),e.jsx(Y,{value:"pending",children:"Pending"}),e.jsx(Y,{value:"paused",children:"Paused"}),e.jsx(Y,{value:"approved",children:"Approved"}),e.jsx(Y,{value:"rejected",children:"Rejected"}),e.jsx(Y,{value:"closed",children:"Closed"})]})]}),e.jsxs(Ue,{value:i.priorityFilter,onValueChange:i.setPriorityFilter,children:[e.jsx(ze,{className:"h-10","data-testid":"priority-filter",children:e.jsx(Ve,{placeholder:"All Priority"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"all",children:"All Priority"}),e.jsx(Y,{value:"express",children:"Express"}),e.jsx(Y,{value:"standard",children:"Standard"})]})]}),e.jsxs(Ue,{value:i.templateTypeFilter,onValueChange:i.setTemplateTypeFilter,children:[e.jsx(ze,{className:"h-10","data-testid":"template-type-filter",children:e.jsx(Ve,{placeholder:"All Templates"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"all",children:"All Templates"}),e.jsx(Y,{value:"CUSTOM",children:"Custom"}),e.jsx(Y,{value:"DEALER CLAIM",children:"Dealer Claim"})]})]}),e.jsxs(Ue,{value:i.departmentFilter,onValueChange:i.setDepartmentFilter,disabled:b||p.length===0,children:[e.jsx(ze,{className:"h-10","data-testid":"department-filter",children:e.jsx(Ve,{placeholder:b?"Loading...":"All Departments"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"all",children:"All Departments"}),p.map(z=>e.jsx(Y,{value:z,children:z},z))]})]}),e.jsxs(Ue,{value:i.slaComplianceFilter,onValueChange:i.setSlaComplianceFilter,children:[e.jsx(ze,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(Ve,{placeholder:"All SLA Status"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"all",children:"All SLA Status"}),e.jsx(Y,{value:"compliant",children:"Compliant"}),e.jsx(Y,{value:"on-track",children:"On Track"}),e.jsx(Y,{value:"approaching",children:"Approaching"}),e.jsx(Y,{value:"critical",children:"Critical"}),e.jsx(Y,{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(re,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:R.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:R.selectedUser.displayName||R.selectedUser.email}),e.jsx(I,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:R.handleClear,children:e.jsx(pt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Re,{placeholder:"Search initiator...",value:R.searchQuery,onChange:z=>R.handleSearch(z.target.value),onFocus:()=>{R.searchResults.length>0&&R.setShowResults(!0)},onBlur:()=>setTimeout(()=>R.setShowResults(!1),200),className:"h-10","data-testid":"initiator-search-input"}),R.showResults&&R.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:R.searchResults.map(z=>e.jsx("button",{type:"button",onClick:()=>R.handleSelect(z),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:z.displayName||z.email}),z.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:z.email})]})},z.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(re,{className:"text-sm font-medium text-gray-700",children:"Approver"}),i.approverFilter!=="all"&&e.jsxs(Ue,{value:i.approverFilterType,onValueChange:z=>i.setApproverFilterType(z),children:[e.jsx(ze,{className:"h-7 w-32 text-xs",children:e.jsx(Ve,{})}),e.jsxs(He,{children:[e.jsx(Y,{value:"current",children:"Current Only"}),e.jsx(Y,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:f.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:f.selectedUser.displayName||f.selectedUser.email}),e.jsx(I,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:f.handleClear,children:e.jsx(pt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Re,{placeholder:"Search approver...",value:f.searchQuery,onChange:z=>f.handleSearch(z.target.value),onFocus:()=>{f.searchResults.length>0&&f.setShowResults(!0)},onBlur:()=>setTimeout(()=>f.setShowResults(!1),200),className:"h-10","data-testid":"approver-search-input"}),f.showResults&&f.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:f.searchResults.map(z=>e.jsx("button",{type:"button",onClick:()=>f.handleSelect(z),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:z.displayName||z.email}),z.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:z.email})]})},z.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(mt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ue,{value:i.dateRange,onValueChange:i.handleDateRangeChange,children:[e.jsx(ze,{className:"w-[160px] h-10",children:e.jsx(Ve,{placeholder:"Date Range"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"all",children:"All Time"}),e.jsx(Y,{value:"today",children:"Today"}),e.jsx(Y,{value:"week",children:"This Week"}),e.jsx(Y,{value:"month",children:"This Month"}),e.jsx(Y,{value:"last7days",children:"Last 7 Days"}),e.jsx(Y,{value:"last30days",children:"Last 30 Days"}),e.jsx(Y,{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(I,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(mt,{className:"w-4 h-4"}),i.customStartDate&&i.customEndDate?`${Ie(i.customStartDate,"MMM d, yyyy")} - ${Ie(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(re,{htmlFor:"start-date",children:"Start Date"}),e.jsx(Re,{id:"start-date",type:"date",value:i.customStartDate?Ie(i.customStartDate,"yyyy-MM-dd"):"",onChange:z=>{const $=z.target.value?new Date(z.target.value):void 0;$?(i.setCustomStartDate($),i.customEndDate&&$>i.customEndDate&&i.setCustomEndDate($)):i.setCustomStartDate(void 0)},max:Ie(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"end-date",children:"End Date"}),e.jsx(Re,{id:"end-date",type:"date",value:i.customEndDate?Ie(i.customEndDate,"yyyy-MM-dd"):"",onChange:z=>{const $=z.target.value?new Date(z.target.value):void 0;$?(i.setCustomEndDate($),i.customStartDate&&$<i.customStartDate&&i.setCustomStartDate($)):i.setCustomEndDate(void 0)},min:i.customStartDate?Ie(i.customStartDate,"yyyy-MM-dd"):void 0,max:Ie(new Date,"yyyy-MM-dd"),className:"w-full"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(I,{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(I,{size:"sm",variant:"outline",onClick:()=>{i.setShowCustomDatePicker(!1),i.setCustomStartDate(void 0),i.setCustomEndDate(void 0),i.setDateRange("month")},children:"Cancel"})]})]})})]})]})]})})}),e.jsx(Tx,{requests:L,loading:c,hasActiveFilters:i.hasActiveFilters,onViewRequest:t}),e.jsx(lr,{currentPage:i.currentPage||1,totalPages:N,totalRecords:S,itemsPerPage:P,onPageChange:O,loading:c,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}async function qT({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.templateType&&a.templateType!=="all"&&(r.templateType=a.templateType),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 ws.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 l=i.filter(c=>(c.status||"").toString().toUpperCase()!=="DRAFT"),o=(n==null?void 0:n.pagination)||{page:t,limit:s,total:l.length,totalPages:1};return{data:l,allData:[],filteredData:l,pagination:{page:o.page,limit:o.limit||s,total:o.total||l.length,totalPages:o.totalPages||1}}}const Ym=100;async function ek(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.templateType&&t.templateType!=="all"&&(i.templateType=t.templateType),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 l=await ws.listParticipantRequests({page:r,limit:Ym,...i});let o=[];if(Array.isArray(l==null?void 0:l.data)?o=l.data:Array.isArray(l)&&(o=l),o.length===0)a=!1;else{const c=o.filter(d=>(d.status||"").toString().toUpperCase()!=="DRAFT");s.push(...c),r++,l!=null&&l.pagination?a=r<=l.pagination.totalPages:a=o.length===Ym}}return s}function tk({onViewRequest:t}){const s=Dx(),[a,r]=x.useState([]),[n,i]=x.useState(!1),[l,o]=x.useState(!1),[c,d]=x.useState(null),[m,u]=x.useState([]),[h,g]=x.useState(!1),[p,y]=x.useState([]),[b,j]=x.useState(1),[v,w]=x.useState(0),[N]=x.useState(10),C=ai({allUsers:p,filterValue:s.initiatorFilter,onFilterChange:s.setInitiatorFilter}),S=ai({allUsers:p,filterValue:s.approverFilter,onFilterChange:s.setApproverFilter}),E=x.useCallback(async(M,O,L,Z)=>{try{const z=await jt.getRequestStats(M,O?O.toISOString():void 0,L?L.toISOString():void 0,void 0,Z==null?void 0:Z.priority,Z==null?void 0:Z.templateType,Z==null?void 0:Z.department,Z==null?void 0:Z.initiator,Z==null?void 0:Z.approver,Z==null?void 0:Z.approverType,Z==null?void 0:Z.search,Z==null?void 0:Z.slaCompliance,!0);d({total:z.totalRequests||0,pending:z.openRequests||0,paused:z.pausedRequests||0,approved:z.approvedRequests||0,rejected:z.rejectedRequests||0,draft:z.draftRequests||0,closed:z.closedRequests||0})}catch(z){console.error("Failed to fetch backend stats:",z)}},[]),P=x.useCallback(async()=>{try{g(!0);const M=await jt.getDepartments();u(M)}catch{}finally{g(!1)}},[]),R=x.useCallback(async()=>{try{const O=(await Ms.getAllUsers()).map(L=>({userId:L.userId,email:L.email,displayName:L.displayName||L.email}));y(O)}catch(M){console.error("Failed to fetch users:",M)}},[]),f=x.useRef(s),T=x.useRef(E);x.useEffect(()=>{f.current=s,T.current=E},[s,E]);const F=x.useCallback(async(M=1)=>{try{M===1&&(i(!0),r([]));const O=f.current.getFilters(),L=await qT({page:M,itemsPerPage:N,filters:O});r(L.data),s.setCurrentPage(L.pagination.page),j(L.pagination.totalPages),w(L.pagination.total)}catch{r([])}finally{i(!1)}},[N]),K=x.useCallback(async()=>{try{o(!0);const M=await ek(s.getFilters());await Fx(M,s.getFilters())}catch(M){console.error("Failed to export requests:",M),alert("Failed to export requests. Please try again.")}finally{o(!1)}},[s]);x.useEffect(()=>{P(),R()},[P,R]),x.useEffect(()=>{const M=setTimeout(()=>{const O={priority:s.priorityFilter!=="all"?s.priorityFilter:void 0,templateType:s.templateTypeFilter!=="all"?s.templateTypeFilter: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==="all"?"all":s.dateRange||"month";T.current(L,s.customStartDate,s.customEndDate,O)},s.searchTerm?500:0);return()=>clearTimeout(M)},[s.searchTerm,s.priorityFilter,s.slaComplianceFilter,s.departmentFilter,s.initiatorFilter,s.approverFilter,s.approverFilterType,s.dateRange,s.customStartDate,s.customEndDate,s.templateTypeFilter]);const B=x.useRef({searchTerm:s.searchTerm,statusFilter:s.statusFilter,priorityFilter:s.priorityFilter,templateTypeFilter:s.templateTypeFilter,slaComplianceFilter:s.slaComplianceFilter,departmentFilter:s.departmentFilter,initiatorFilter:s.initiatorFilter,approverFilter:s.approverFilter,approverFilterType:s.approverFilterType,dateRange:s.dateRange,customStartDate:s.customStartDate,customEndDate:s.customEndDate}),U=x.useRef(!1);x.useEffect(()=>{const M=s.currentPage||1;F(M),U.current=!0},[]),x.useEffect(()=>{if(!U.current)return;const M=B.current;if(!(M.searchTerm!==s.searchTerm||M.statusFilter!==s.statusFilter||M.priorityFilter!==s.priorityFilter||M.templateTypeFilter!==s.templateTypeFilter||M.slaComplianceFilter!==s.slaComplianceFilter||M.departmentFilter!==s.departmentFilter||M.initiatorFilter!==s.initiatorFilter||M.approverFilter!==s.approverFilter||M.approverFilterType!==s.approverFilterType||M.dateRange!==s.dateRange||M.customStartDate!==s.customStartDate||M.customEndDate!==s.customEndDate))return;const L=setTimeout(()=>{s.setCurrentPage(1),F(1),B.current={searchTerm:s.searchTerm,statusFilter:s.statusFilter,priorityFilter:s.priorityFilter,templateTypeFilter:s.templateTypeFilter,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!==M.searchTerm?500:0);return()=>clearTimeout(L)},[s.searchTerm,s.statusFilter,s.priorityFilter,s.templateTypeFilter,s.slaComplianceFilter,s.departmentFilter,s.initiatorFilter,s.approverFilter,s.approverFilterType,s.dateRange,s.customStartDate,s.customEndDate]);const D=x.useCallback(M=>{M>=1&&M<=b&&(s.setCurrentPage(M),F(M))},[b,F,s]),A=x.useMemo(()=>Rx(a),[a]),k=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 M=A.filter($=>{const W=($.status||"").toString().toLowerCase();return W==="pending"||W==="in-progress"}).length,O=A.filter($=>($.status||"").toString().toLowerCase()==="paused").length,L=A.filter($=>($.status||"").toString().toLowerCase()==="approved").length,Z=A.filter($=>($.status||"").toString().toLowerCase()==="rejected").length,z=A.filter($=>($.status||"").toString().toLowerCase()==="closed").length;return{total:v>0?v:A.length,pending:M,paused:O,approved:L,rejected:Z,draft:0,closed:z}},[c,v,A]);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(Sx,{isOrgLevel:!1,isAdmin:!1,loading:n,exporting:l,onExport:K}),e.jsx(Ax,{stats:k,onStatusFilter:M=>{s.setStatusFilter(M)}}),e.jsx(te,{className:"border-gray-200 shadow-md","data-testid":"requests-filters",children:e.jsx(se,{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(gn,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),s.hasActiveFilters&&e.jsx(ie,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),s.hasActiveFilters&&e.jsxs(I,{variant:"ghost",size:"sm",onClick:s.clearFilters,className:"gap-2",children:[e.jsx(ns,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Vt,{}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 lg:grid-cols-6 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative md:col-span-3 lg:col-span-1",children:[e.jsx($s,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Re,{placeholder:"Search requests...",value:s.searchTerm,onChange:M=>s.setSearchTerm(M.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(Ue,{value:s.statusFilter,onValueChange:s.setStatusFilter,children:[e.jsx(ze,{className:"h-10","data-testid":"status-filter",children:e.jsx(Ve,{placeholder:"All Status"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"all",children:"All Status"}),e.jsx(Y,{value:"pending",children:"Pending"}),e.jsx(Y,{value:"paused",children:"Paused"}),e.jsx(Y,{value:"approved",children:"Approved"}),e.jsx(Y,{value:"rejected",children:"Rejected"}),e.jsx(Y,{value:"closed",children:"Closed"})]})]}),e.jsxs(Ue,{value:s.priorityFilter,onValueChange:s.setPriorityFilter,children:[e.jsx(ze,{className:"h-10","data-testid":"priority-filter",children:e.jsx(Ve,{placeholder:"All Priority"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"all",children:"All Priority"}),e.jsx(Y,{value:"express",children:"Express"}),e.jsx(Y,{value:"standard",children:"Standard"})]})]}),e.jsxs(Ue,{value:s.templateTypeFilter,onValueChange:s.setTemplateTypeFilter,children:[e.jsx(ze,{className:"h-10","data-testid":"template-type-filter",children:e.jsx(Ve,{placeholder:"All Templates"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"all",children:"All Templates"}),e.jsx(Y,{value:"CUSTOM",children:"Custom"}),e.jsx(Y,{value:"DEALER CLAIM",children:"Dealer Claim"})]})]}),e.jsxs(Ue,{value:s.departmentFilter,onValueChange:s.setDepartmentFilter,disabled:h||m.length===0,children:[e.jsx(ze,{className:"h-10","data-testid":"department-filter",children:e.jsx(Ve,{placeholder:h?"Loading...":"All Departments"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"all",children:"All Departments"}),m.map(M=>e.jsx(Y,{value:M,children:M},M))]})]}),e.jsxs(Ue,{value:s.slaComplianceFilter,onValueChange:s.setSlaComplianceFilter,children:[e.jsx(ze,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(Ve,{placeholder:"All SLA Status"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"all",children:"All SLA Status"}),e.jsx(Y,{value:"compliant",children:"Compliant"}),e.jsx(Y,{value:"on-track",children:"On Track"}),e.jsx(Y,{value:"approaching",children:"Approaching"}),e.jsx(Y,{value:"critical",children:"Critical"}),e.jsx(Y,{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(re,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:C.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:C.selectedUser.displayName||C.selectedUser.email}),e.jsx(I,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:C.handleClear,children:e.jsx(pt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Re,{placeholder:"Search initiator...",value:C.searchQuery,onChange:M=>C.handleSearch(M.target.value),onFocus:()=>{C.searchResults.length>0&&C.setShowResults(!0)},onBlur:()=>setTimeout(()=>C.setShowResults(!1),200),className:"h-10","data-testid":"initiator-search-input"}),C.showResults&&C.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:C.searchResults.map(M=>e.jsx("button",{type:"button",onClick:()=>C.handleSelect(M),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:M.displayName||M.email}),M.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:M.email})]})},M.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(re,{className:"text-sm font-medium text-gray-700",children:"Approver"}),s.approverFilter!=="all"&&e.jsxs(Ue,{value:s.approverFilterType,onValueChange:M=>s.setApproverFilterType(M),children:[e.jsx(ze,{className:"h-7 w-32 text-xs",children:e.jsx(Ve,{})}),e.jsxs(He,{children:[e.jsx(Y,{value:"current",children:"Current Only"}),e.jsx(Y,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:S.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:S.selectedUser.displayName||S.selectedUser.email}),e.jsx(I,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:S.handleClear,children:e.jsx(pt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Re,{placeholder:"Search approver...",value:S.searchQuery,onChange:M=>S.handleSearch(M.target.value),onFocus:()=>{S.searchResults.length>0&&S.setShowResults(!0)},onBlur:()=>setTimeout(()=>S.setShowResults(!1),200),className:"h-10","data-testid":"approver-search-input"}),S.showResults&&S.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:S.searchResults.map(M=>e.jsx("button",{type:"button",onClick:()=>S.handleSelect(M),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:M.displayName||M.email}),M.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:M.email})]})},M.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(mt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ue,{value:s.dateRange,onValueChange:s.handleDateRangeChange,children:[e.jsx(ze,{className:"w-[160px] h-10",children:e.jsx(Ve,{placeholder:"Date Range"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"all",children:"All Time"}),e.jsx(Y,{value:"today",children:"Today"}),e.jsx(Y,{value:"week",children:"This Week"}),e.jsx(Y,{value:"month",children:"This Month"}),e.jsx(Y,{value:"last7days",children:"Last 7 Days"}),e.jsx(Y,{value:"last30days",children:"Last 30 Days"}),e.jsx(Y,{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(I,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(mt,{className:"w-4 h-4"}),s.customStartDate&&s.customEndDate?`${Ie(s.customStartDate,"MMM d, yyyy")} - ${Ie(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(re,{htmlFor:"start-date",children:"Start Date"}),e.jsx(Re,{id:"start-date",type:"date",value:s.customStartDate?Ie(s.customStartDate,"yyyy-MM-dd"):"",onChange:M=>{const O=M.target.value?new Date(M.target.value):void 0;O?(s.setCustomStartDate(O),s.customEndDate&&O>s.customEndDate&&s.setCustomEndDate(O)):s.setCustomStartDate(void 0)},max:Ie(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"end-date",children:"End Date"}),e.jsx(Re,{id:"end-date",type:"date",value:s.customEndDate?Ie(s.customEndDate,"yyyy-MM-dd"):"",onChange:M=>{const O=M.target.value?new Date(M.target.value):void 0;O?(s.setCustomEndDate(O),s.customStartDate&&O<s.customStartDate&&s.setCustomStartDate(O)):s.setCustomEndDate(void 0)},min:s.customStartDate?Ie(s.customStartDate,"yyyy-MM-dd"):void 0,max:Ie(new Date,"yyyy-MM-dd"),className:"w-full"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(I,{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(I,{size:"sm",variant:"outline",onClick:()=>{s.setShowCustomDatePicker(!1),s.setCustomStartDate(void 0),s.setCustomEndDate(void 0),s.setDateRange("month")},children:"Cancel"})]})]})})]})]})]})})}),e.jsx(Tx,{requests:A,loading:n,hasActiveFilters:s.hasActiveFilters,onViewRequest:t}),e.jsx(lr,{currentPage:s.currentPage||1,totalPages:b,totalRecords:v,itemsPerPage:N,onPageChange:D,loading:n,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}function sk(){const t=_a();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(te,{children:e.jsxs(se,{className:"p-8 text-center",children:[e.jsx(We,{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(I,{onClick:()=>t(-1),className:"mt-4","data-testid":"back-button",children:[e.jsx(Ys,{className:"w-4 h-4 mr-2"}),"Back"]})]})})})})}function ak({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(Mt,{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(I,{variant:"outline",size:"sm",onClick:a,disabled:s,className:"gap-2","data-testid":"refresh-button",children:[e.jsx(ns,{className:`w-4 h-4 ${s?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:"Refresh"})]})]})}function rk({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(te,{children:[e.jsx(me,{className:"pb-3",children:e.jsx(he,{className:"text-sm font-medium text-gray-600",children:"TAT Compliance"})}),e.jsxs(se,{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(Bt,{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(Qs,{value:s,className:"mt-2 h-2"})]})]}),e.jsxs(te,{children:[e.jsx(me,{className:"pb-3",children:e.jsx(he,{className:"text-sm font-medium text-gray-600",children:"Total Approved"})}),e.jsxs(se,{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(te,{children:[e.jsx(me,{className:"pb-3",children:e.jsx(he,{className:"text-sm font-medium text-gray-600",children:"Avg Response Time"})}),e.jsxs(se,{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(no,{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(te,{children:[e.jsx(me,{className:"pb-3",children:e.jsx(he,{className:"text-sm font-medium text-gray-600",children:"Pending Actions"})}),e.jsxs(se,{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(Ze,{className:"w-5 h-5 text-orange-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Awaiting approval"})]})]})]})}function nk({approverName:t,approverStats:s,dateRange:a="all",customStartDate:r,customEndDate:n}){return e.jsxs(te,{"data-testid":"approver-actions-stats",children:[e.jsxs(me,{children:[e.jsx(he,{children:"Approver's Actions"}),e.jsxs(De,{children:["Statistics for all requests by ",t," ",a&&a!=="all"?wb(a,r,n,""):"(all time)"]})]}),e.jsxs(se,{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(Mt,{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(xt,{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(Ze,{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(pi,{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(Le,{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(Bt,{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(Vf,{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(We,{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(ku,{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 ik({searchTerm:t,statusFilter:s,priorityFilter:a,slaComplianceFilter:r,dateRange:n,customStartDate:i,customEndDate:l,showCustomDatePicker:o,tempCustomStartDate:c,tempCustomEndDate:d,onSearchChange:m,onStatusChange:u,onPriorityChange:h,onSlaComplianceChange:g,onDateRangeChange:p,onShowCustomDatePickerChange:y,onTempStartDateChange:b,onTempEndDateChange:j,onApplyCustomDate:v,onClearFilters:w}){return e.jsxs(te,{"data-testid":"approver-performance-filters",children:[e.jsx(me,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{children:"Filters"}),e.jsx(I,{variant:"ghost",size:"sm",onClick:w,className:"text-xs","data-testid":"clear-filters-button",children:"Clear All"})]})}),e.jsx(se,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-6 gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx($s,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(Re,{placeholder:"Search requests...",value:t,onChange:N=>m(N.target.value),className:"pl-10","data-testid":"search-input"})]}),e.jsxs(Ue,{value:s,onValueChange:u,children:[e.jsx(ze,{"data-testid":"status-filter",children:e.jsx(Ve,{placeholder:"Status"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"all",children:"All Status"}),e.jsx(Y,{value:"pending",children:"Pending"}),e.jsx(Y,{value:"approved",children:"Approved"}),e.jsx(Y,{value:"rejected",children:"Rejected"}),e.jsx(Y,{value:"closed",children:"Closed"})]})]}),e.jsxs(Ue,{value:a,onValueChange:h,children:[e.jsx(ze,{"data-testid":"priority-filter",children:e.jsx(Ve,{placeholder:"Priority"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"all",children:"All Priority"}),e.jsx(Y,{value:"express",children:"Express"}),e.jsx(Y,{value:"standard",children:"Standard"})]})]}),e.jsxs(Ue,{value:r,onValueChange:g,children:[e.jsx(ze,{"data-testid":"sla-compliance-filter",children:e.jsx(Ve,{placeholder:"SLA Compliance"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"all",children:"All SLA"}),e.jsx(Y,{value:"compliant",children:"Compliant"}),e.jsx(Y,{value:"on-track",children:"On Track"}),e.jsx(Y,{value:"approaching",children:"Approaching"}),e.jsx(Y,{value:"critical",children:"Critical"}),e.jsx(Y,{value:"breached",children:"Breached"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ue,{value:n,onValueChange:p,children:[e.jsx(ze,{className:"flex-1","data-testid":"date-range-filter",children:e.jsx(Ve,{placeholder:"Date Range"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"all",children:"All Time"}),e.jsx(Y,{value:"today",children:"Today"}),e.jsx(Y,{value:"week",children:"This Week"}),e.jsx(Y,{value:"month",children:"This Month"}),e.jsx(Y,{value:"last7days",children:"Last 7 Days"}),e.jsx(Y,{value:"last30days",children:"Last 30 Days"}),e.jsx(Y,{value:"custom",children:"Custom Range"})]})]}),n==="custom"&&e.jsxs(ra,{open:o,onOpenChange:y,children:[e.jsx(na,{asChild:!0,children:e.jsxs(I,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(mt,{className:"w-4 h-4"}),c&&d?`${Ie(c,"MMM d")} - ${Ie(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(re,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(Re,{id:"start-date",type:"date",value:c?Ie(c,"yyyy-MM-dd"):"",onChange:N=>{const C=N.target.value?new Date(N.target.value):void 0;C?(b(C),d&&C>d&&j(C)):b(void 0)},max:Ie(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(Re,{id:"end-date",type:"date",value:d?Ie(d,"yyyy-MM-dd"):"",onChange:N=>{const C=N.target.value?new Date(N.target.value):void 0;C?(j(C),c&&C<c&&b(C)):j(void 0)},min:c?Ie(c,"yyyy-MM-dd"):void 0,max:Ie(new Date,"yyyy-MM-dd"),className:"w-full"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(I,{size:"sm",onClick:v,disabled:!c||!d,className:"flex-1 bg-re-green hover:bg-re-green/90","data-testid":"apply-date-button",children:"Apply"}),e.jsx(I,{size:"sm",variant:"outline",onClick:()=>{y(!1),b(i),j(l),(!i||!l)&&p("all")},"data-testid":"cancel-date-button",children:"Cancel"})]})]})})]})]})]})})]})}const lk=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:da,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Bt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Bt,iconColor:"text-gray-600"}}},ok=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:xt,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:Ze,iconColor:"text-yellow-600"};case"in-progress":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Ze,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:Le,iconColor:"text-gray-600"}}},ck=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 dk(t){if(!t)return"N/A";try{return Ie(new Date(t),"MMM d, yyyy")}catch{return"N/A"}}function mk(t){if(!t)return"N/A";try{return Ie(new Date(t),"MMM d, yyyy HH:mm")}catch{return"N/A"}}function uk({requests:t,loading:s,approverName:a,currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:l,onPageChange:o}){const c=_a();return e.jsxs(te,{"data-testid":"approver-performance-request-list",children:[e.jsxs(me,{children:[e.jsx(he,{children:"Request Details"}),e.jsxs(De,{children:["All requests handled by ",a," with applied filters"]})]}),e.jsxs(se,{children:[s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"loading-state",children:[e.jsx(ns,{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(Le,{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=lk(d.priority),u=ok(d.status),h=ck(d.slaStatus||""),g=m.icon,p=u.icon;return e.jsx(te,{className:"hover:shadow-md transition-shadow cursor-pointer",onClick:()=>{const{navigateToRequest:y}=require("@/utils/requestNavigation");y({requestId:d.requestId,requestTitle:d.title,status:d.status,request:d,navigate:c})},"data-testid":`request-card-${d.requestId}`,children:e.jsx(se,{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(ie,{className:m.color,"data-testid":"priority-badge",children:[e.jsx(g,{className:`w-3 h-3 mr-1 ${m.iconColor}`}),d.priority]}),e.jsxs(ie,{className:u.color,"data-testid":"status-badge",children:[e.jsx(p,{className:`w-3 h-3 mr-1 ${u.iconColor}`}),d.status]}),d.approvalStatus&&e.jsx(ie,{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(xt,{className:"w-3 h-3 mr-1"}),"Rejected"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-3 h-3 mr-1"}),"Pending"]})}),d.slaStatus&&e.jsx(ie,{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(Pt,{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(Ze,{className:"w-3 h-3"}),"Submitted: ",dk(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: ",mk(d.approvalActionDate)]}),e.jsxs("span",{className:"flex items-center gap-1","data-testid":"approval-level",children:[e.jsx(Bt,{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(no,{className:"w-3 h-3"}),It(d.levelElapsedHours)," / ",It(d.levelTatHours||0)," TAT"]})]})]}),e.jsx(I,{variant:"ghost",size:"sm",onClick:y=>{y.stopPropagation();const{navigateToRequest:b}=require("@/utils/requestNavigation");b({requestId:d.requestId,requestTitle:d.title,status:d.status,request:d,navigate:c})},"data-testid":"view-request-button",children:e.jsx(rs,{className:"w-4 h-4"})})]})})},d.requestId)})}),n>0&&e.jsx("div",{className:"mt-6","data-testid":"pagination-container",children:e.jsx(lr,{currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:l,onPageChange:o,itemLabel:"requests",testIdPrefix:"approver-performance"})})]})]})}function hk(){const[t]=Pu(),[s,a]=x.useState(""),[r,n]=x.useState(t.get("status")||"all"),[i,l]=x.useState(t.get("priority")||"all"),[o,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),[g,p]=x.useState(t.get("endDate")?new Date(t.get("endDate")):void 0),[y,b]=x.useState(!1),[j,v]=x.useState(void 0),[w,N]=x.useState(void 0),C=x.useCallback(()=>{a(""),n("all"),l("all"),c("all"),m("all"),h(void 0),p(void 0),v(void 0),N(void 0),b(!1)},[]),S=x.useCallback(P=>{const R=P;m(R),R!=="custom"?(h(void 0),p(void 0),v(void 0),N(void 0),b(!1)):(v(u),N(g),b(!0))},[u,g]),E=x.useCallback(()=>{if(j&&w){if(j>w){const P=j;h(w),p(P),v(w),N(P)}else h(j),p(w);b(!1)}},[j,w]);return{searchTerm:s,statusFilter:r,priorityFilter:i,slaComplianceFilter:o,dateRange:d,customStartDate:u,customEndDate:g,showCustomDatePicker:y,tempCustomStartDate:j,tempCustomEndDate:w,setSearchTerm:a,setStatusFilter:n,setPriorityFilter:l,setSlaComplianceFilter:c,setDateRange:m,setCustomStartDate:h,setCustomEndDate:p,setShowCustomDatePicker:b,setTempCustomStartDate:v,setTempCustomEndDate:N,clearFilters:C,handleDateRangeChange:S,handleApplyCustomDate:E}}function pk({approverId:t,dateRange:s,customStartDate:a,customEndDate:r,statusFilter:n,priorityFilter:i,slaComplianceFilter:l,searchTerm:o,itemsPerPage:c}){const[d,m]=x.useState([]),[u,h]=x.useState(null),[g,p]=x.useState([]),[y,b]=x.useState(!0),[j,v]=x.useState(!1),[w,N]=x.useState(1),[C,S]=x.useState(1),[E,P]=x.useState(0),R=x.useRef(!0),f=x.useCallback(async()=>{if(t)try{const B=s==="all"?void 0:s,U=await jt.getSingleApproverStats(t,B,a,r,i!=="all"?i:void 0,l!=="all"?l:void 0);h(U)}catch(B){console.error("[ApproverPerformance] Failed to fetch approver stats:",B),h(null)}},[t,s,a,r,i,l]),T=x.useCallback(async(B=1)=>{if(!t){b(!1);return}try{b(!0);const U=await jt.getRequestsByApprover(t,B,c,s==="all"?void 0:s,a,r,n!=="all"?n:void 0,i!=="all"?i:void 0,l!=="all"?l:void 0,o||void 0);m(U.requests),P(U.pagination.totalRecords),S(U.pagination.totalPages),N(U.pagination.currentPage),p(U.requests)}catch(U){console.error("Failed to fetch requests:",U)}finally{b(!1),v(!1)}},[t,s,a,r,n,i,l,o,c]);x.useEffect(()=>{R.current&&(R.current=!1,f(),T(1))},[]),x.useEffect(()=>{R.current||f()},[s,a,r,i,l]),x.useEffect(()=>{R.current||T(1)},[s,a,r,n,i,l,o]);const F=x.useCallback(()=>{v(!0),f(),T(1)},[f,T]),K=x.useCallback(B=>{T(B)},[T]);return{requests:d,approverStats:u,allFilteredRequests:g,loading:y,refreshing:j,currentPage:w,totalPages:C,totalRecords:E,handleRefresh:F,handlePageChange:K}}const Zm=10;function xk(){const[t]=Pu(),s=t.get("approverId")||"",a=t.get("approverName")||"Unknown Approver",r=hk(),n=pk({approverId:s,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,slaComplianceFilter:r.slaComplianceFilter,searchTerm:r.searchTerm,itemsPerPage:Zm});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(ak,{approverName:a,refreshing:n.refreshing,onRefresh:n.handleRefresh}),n.approverStats&&e.jsx(rk,{approverStats:n.approverStats}),n.approverStats&&e.jsx(nk,{approverName:a,approverStats:n.approverStats,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate}),e.jsx(ik,{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(uk,{requests:n.requests,loading:n.loading,approverName:a,currentPage:n.currentPage,totalPages:n.totalPages,totalRecords:n.totalRecords,itemsPerPage:Zm,onPageChange:n.handlePageChange})]}):e.jsx(sk,{})}function gk(){const{user:t}=Kt(),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(te,{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(se,{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(Qt,{className:"h-24 w-24 ring-4 ring-white/20 shadow-xl",children:[e.jsx(fi,{src:(t==null?void 0:t.picture)||""}),e.jsx(qt,{className:"bg-yellow-400 text-slate-900 text-2xl font-bold",children:s()})]}),Ka(t)&&e.jsx("div",{className:"absolute -bottom-2 -right-2 bg-yellow-400 rounded-full p-1.5 shadow-lg",children:e.jsx(cs,{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:[Ka(t)&&e.jsxs(ie,{className:"bg-yellow-400 text-slate-900 hover:bg-yellow-400 font-semibold",children:[e.jsx(cs,{className:"w-3 h-3 mr-1"}),"Administrator"]}),Wr(t)&&e.jsxs(ie,{className:"bg-blue-400 text-slate-900 hover:bg-blue-400 font-semibold",children:[e.jsx(Mt,{className:"w-3 h-3 mr-1"}),"Management"]}),(t==null?void 0:t.employeeId)&&e.jsxs(ie,{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(te,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(me,{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(Pt,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(he,{className:"text-lg text-gray-900",children:"Personal Information"}),e.jsx(De,{className:"text-gray-600",children:"Your personal details"})]})]})}),e.jsx(se,{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(va,{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(Pt,{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(Pt,{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(Pt,{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(li,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"Phone"}),e.jsx("p",{className:"text-base text-gray-900",children:t.phone})]})]})]})})]}),e.jsxs(te,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(me,{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(td,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsx(he,{className:"text-lg text-gray-900",children:"Professional Information"}),e.jsx(De,{className:"text-gray-600",children:"Work-related details"})]})]})}),e.jsx(se,{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(Pt,{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(eo,{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(td,{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(cs,{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(ie,{variant:Ka(t)||Wr(t)?"default":"secondary",className:Ka(t)?"bg-yellow-400 text-slate-900":Wr(t)?"bg-blue-400 text-slate-900":"",children:Ka(t)?"Administrator":Wr(t)?"Management":"User"}),(Ka(t)||Wr(t))&&e.jsx(Ce,{className:"w-4 h-4 text-green-600"})]})]})]})]})})]})]}),e.jsxs(te,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(me,{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(mt,{className:"h-5 w-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(he,{className:"text-lg text-gray-900",children:"Account Status"}),e.jsx(De,{className:"text-gray-600",children:"Account information and activity"})]})]})}),e.jsx(se,{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(ie,{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 On="BBb78N3tSTEw6mPbBmvEDX2bhYEDKPc_zffL-vxPV8FBSmR1qSpy9gdV8zt-WFF-q2NPpVmL4BhbUzLSHVAPjcI",fk="https://re-workflow-nt-dev.siplsolutions.com/";function pl(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 yk(){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 bk(t){if(On.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:pl(On)})}else try{s=await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:pl(On)})}catch(l){console.warn("[Push] Initial subscription failed, attempting to clear and retry...");try{const o=await t.pushManager.getSubscription();o&&await o.unsubscribe().catch(()=>{}),s=await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:pl(On)})}catch(o){const c=(l==null?void 0:l.message)||(o==null?void 0:o.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 l=(i==null?void 0:i.message)||"Unknown error";throw l.includes("push service error")||l.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."):l.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: ${l}`)}const a=s.toJSON(),r=!0,n=null;try{const i={"Content-Type":"application/json"},l=await fetch(`${fk}/api/v1/workflows/notifications/subscribe`,{method:"POST",headers:i,credentials:"include",body:JSON.stringify(a)});if(!l.ok){const c=await l.json().catch(()=>({error:"Unknown error"}));throw new Error((c==null?void 0:c.error)||(c==null?void 0:c.message)||`Server error: ${l.status}`)}const o=await l.json();if(!o.success)throw new Error(o.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 vk(){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 yk()}catch(a){throw new Error(`Service worker registration failed: ${(a==null?void 0:a.message)||"Unknown error"}`)}try{await bk(s)}catch(a){throw a}}function Gl({className:t,defaultValue:s,value:a,min:r=0,max:n=100,...i}){const l=x.useMemo(()=>Array.isArray(a)?a:Array.isArray(s)?s:[r,n],[a,s,r,n]);return e.jsxs(Bg,{"data-slot":"slider",defaultValue:s,value:a,min:r,max:n,className:we("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(Ug,{"data-slot":"slider-track",className:we("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(Vg,{"data-slot":"slider-range",className:we("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full")})}),Array.from({length:l.length},(o,c)=>e.jsx(zg,{"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 jk({onConfigUpdate:t}){const[s,a]=x.useState([]),[r,n]=x.useState(!0),[i,l]=x.useState(null),[o,c]=x.useState(null),[d,m]=x.useState({}),[u,h]=x.useState(null);x.useEffect(()=>{g()},[]);const g=async()=>{var f,T;try{n(!0),c(null);const F=await Ci();a(F)}catch(F){c(((T=(f=F.response)==null?void 0:f.data)==null?void 0:T.error)||"Failed to load configurations")}finally{n(!1)}},p=async f=>{var T,F;try{l(f.configKey),c(null);const K=d[f.configKey]??f.configValue;if(f.validationRules){const B=parseFloat(K);if(f.valueType==="NUMBER"){if(f.validationRules.min!==void 0&&B<f.validationRules.min)throw new Error(`Value must be at least ${f.validationRules.min}`);if(f.validationRules.max!==void 0&&B>f.validationRules.max)throw new Error(`Value must be at most ${f.validationRules.max}`)}}await bs(f.configKey,K),a(B=>B.map(U=>U.configKey===f.configKey?{...U,configValue:K}:U)),m(B=>{const U={...B};return delete U[f.configKey],U}),h(`${f.displayName} updated successfully`),setTimeout(()=>h(null),3e3),t&&t()}catch(K){c(K.message||((F=(T=K.response)==null?void 0:T.data)==null?void 0:F.error)||"Failed to save configuration")}finally{l(null)}},y=async f=>{var T,F;if(confirm(`Reset "${f.displayName}" to default value?`))try{l(f.configKey),c(null),await v1(f.configKey),a(K=>K.map(B=>B.configKey===f.configKey?{...B,configValue:B.defaultValue||""}:B)),m(K=>{const B={...K};return delete B[f.configKey],B}),h(`${f.displayName} reset to default`),setTimeout(()=>h(null),3e3)}catch(K){c(((F=(T=K.response)==null?void 0:T.data)==null?void 0:F.error)||"Failed to reset configuration")}finally{l(null)}},b=(f,T)=>{m(F=>({...F,[f]:T}))},j=f=>d[f.configKey]??f.configValue,v=f=>d[f.configKey]!==void 0&&d[f.configKey]!==f.configValue,w=f=>{var K,B,U,D;const T=j(f),F=i===f.configKey;if(!f.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:f.configValue}),e.jsxs("p",{className:"text-xs text-slate-500 mt-1.5 flex items-center gap-1",children:[e.jsx(We,{className:"w-3 h-3"}),"This setting cannot be modified"]})]});switch(f.uiComponent||f.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 ${T==="true"?"bg-green-500":"bg-slate-400"}`}),e.jsx("span",{className:`text-sm font-medium ${T==="true"?"text-green-700":"text-slate-600"}`,children:T==="true"?"Enabled":"Disabled"})]}),e.jsx(Ns,{checked:T==="true",onCheckedChange:O=>b(f.configKey,O?"true":"false"),disabled:F})]});case"slider":const A=parseInt(T)||0,k=((K=f.validationRules)==null?void 0:K.min)||0,M=((B=f.validationRules)==null?void 0:B.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:[A,"%"]}),e.jsxs("span",{className:"text-xs text-slate-500 bg-slate-100 px-2 py-1 rounded-sm border border-slate-200",children:["Range: ",k,"-",M]})]}),e.jsx(Gl,{value:[A],min:k,max:M,step:1,onValueChange:([O])=>{O!==void 0&&b(f.configKey,O.toString())},disabled:F,className:"w-full"})]});case"number":return e.jsx(Re,{type:"number",value:T,onChange:O=>b(f.configKey,O.target.value),disabled:F,min:(U=f.validationRules)==null?void 0:U.min,max:(D=f.validationRules)==null?void 0:D.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(Re,{type:"text",value:T,onChange:O=>b(f.configKey,O.target.value),disabled:F,className:"font-mono border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 rounded-md transition-all shadow-sm"})}},N=f=>{switch(f){case"TAT_SETTINGS":return e.jsx(Ze,{className:"w-5 h-5"});case"DOCUMENT_POLICY":return e.jsx(Le,{className:"w-5 h-5"});case"NOTIFICATION_RULES":return e.jsx(vs,{className:"w-5 h-5"});case"AI_CONFIGURATION":return e.jsx(oi,{className:"w-5 h-5"});case"WORKFLOW_SHARING":return e.jsx(vr,{className:"w-5 h-5"});default:return e.jsx(Da,{className:"w-5 h-5"})}},C=["DASHBOARD_LAYOUT"],S=["ALLOW_EXTERNAL_SHARING","NOTIFICATION_BATCH_DELAY_MS","AI_REMARK_MAX_CHARACTERS"],E=s.filter(f=>!C.includes(f.configCategory)&&!S.includes(f.configKey)),P=E.reduce((f,T)=>(f[T.configCategory]||(f[T.configCategory]=[]),f[T.configCategory].push(T),f),{});if(Object.keys(P).forEach(f=>{const T=P[f];T&&T.sort((F,K)=>F.sortOrder-K.sortOrder)}),r)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Qe,{className:"w-8 h-8 animate-spin text-gray-400"})});if(E.length===0)return e.jsx(te,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(se,{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(Da,{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 R=Object.keys(P);return e.jsxs("div",{className:"space-y-6",children:[u&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-green-50 to-emerald-50 border border-green-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-green-500 rounded-md",children:e.jsx(Ce,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-green-900",children:u})]}),o&&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(We,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:o}),e.jsx(I,{size:"sm",variant:"ghost",onClick:()=>c(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsxs(wn,{defaultValue:R[0],className:"w-full",children:[e.jsx(Cn,{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:R.map(f=>e.jsx(Ct,{value:f,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:f.replace(/_/g," ")})},f))}),R.map(f=>{var T,F,K;return e.jsx(St,{value:f,className:"space-y-4 mt-6",children:e.jsxs(te,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(me,{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:N(f)})}),e.jsxs("div",{children:[e.jsx(he,{className:"text-lg font-semibold text-slate-900",children:f.replace(/_/g," ")}),e.jsxs(De,{className:"text-sm",children:[((T=P[f])==null?void 0:T.length)||0," setting",(((F=P[f])==null?void 0:F.length)||0)!==1?"s":""," available"]})]})]})}),e.jsx(se,{className:"space-y-6",children:(K=P[f])==null?void 0:K.map(B=>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(re,{className:"text-sm font-semibold text-slate-900",children:B.displayName}),v(B)&&e.jsx(ie,{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"}),B.requiresRestart&&e.jsx(ie,{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"})]}),B.description&&e.jsx("p",{className:"text-xs text-slate-600 mt-1 leading-relaxed",children:B.description}),B.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:B.defaultValue})]})]})}),w(B),B.isEditable&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(I,{size:"sm",onClick:()=>p(B),disabled:!v(B)||i===B.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===B.configKey?e.jsxs(e.Fragment,{children:[e.jsx(Qe,{className:"w-4 h-4 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Fa,{className:"w-4 h-4"}),"Save Changes"]})}),B.defaultValue&&e.jsxs(I,{size:"sm",variant:"outline",onClick:()=>y(B),disabled:i===B.configKey,className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(zf,{className:"w-4 h-4"}),"Reset to Default"]})]})]},B.configKey))})]})},f)})]})]})}function Nk(){const[t,s]=x.useState([]),[a,r]=x.useState(!0),[n,i]=x.useState(new Date().getFullYear()),[l,o]=x.useState(!1),[c,d]=x.useState(null),[m,u]=x.useState(null),[h,g]=x.useState(null),[p,y]=x.useState({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1});x.useEffect(()=>{b()},[n]);const b=async()=>{var f,T;try{r(!0),u(null);const F=await j1(n);s(F)}catch(F){u(((T=(f=F.response)==null?void 0:f.data)==null?void 0:T.error)||"Failed to load holidays")}finally{r(!1)}},j=()=>{y({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1}),d(null),o(!0)},v=f=>{y({holidayDate:f.holidayDate,holidayName:f.holidayName,description:f.description||"",holidayType:f.holidayType,isRecurring:f.isRecurring}),d(f),o(!0)},w=()=>{if(c)return;const f=new Date;return f.setDate(f.getDate()+1),f.toISOString().split("T")[0]},N=async()=>{var f,T;try{if(u(null),!p.holidayDate||!p.holidayName){u("Holiday date and name are required");return}c?(await w1(c.holidayId,p),g("Holiday updated successfully")):(await N1(p),g("Holiday created successfully")),await b(),o(!1),setTimeout(()=>g(null),3e3)}catch(F){u(((T=(f=F.response)==null?void 0:f.data)==null?void 0:T.error)||"Failed to save holiday")}},C=async f=>{var T,F;if(confirm(`Delete "${f.holidayName}"?`))try{u(null),await C1(f.holidayId),g("Holiday deleted successfully"),await b(),setTimeout(()=>g(null),3e3)}catch(K){u(((F=(T=K.response)==null?void 0:T.data)==null?void 0:F.error)||"Failed to delete holiday")}},S=f=>{switch(f){case"NATIONAL":return"bg-gradient-to-r from-red-50 to-rose-50 text-red-800 border-red-300";case"REGIONAL":return"bg-gradient-to-r from-blue-50 to-cyan-50 text-blue-800 border-blue-300";case"ORGANIZATIONAL":return"bg-gradient-to-r from-purple-50 to-violet-50 text-purple-800 border-purple-300";case"OPTIONAL":return"bg-gradient-to-r from-slate-50 to-gray-50 text-slate-700 border-slate-300"}},E=Array.from({length:5},(f,T)=>new Date().getFullYear()-1+T),P=t.reduce((f,T)=>{const F=new Date(T.holidayDate).toLocaleString("default",{month:"long"});return f[F]||(f[F]=[]),f[F].push(T),f},{}),R=Object.keys(P).sort((f,T)=>{const F=new Date(Date.parse(f+" 1, 2000")).getMonth(),K=new Date(Date.parse(T+" 1, 2000")).getMonth();return F-K});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(We,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:m}),e.jsx(I,{size:"sm",variant:"ghost",onClick:()=>u(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsx(te,{className:"shadow-lg border-0 rounded-md",children:e.jsx(me,{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(mt,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(he,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Holiday Calendar"}),e.jsx(De,{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(Ue,{value:n.toString(),onValueChange:f=>i(parseInt(f)),children:[e.jsx(ze,{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(Ve,{})}),e.jsx(He,{className:"rounded-md",children:E.map(f=>e.jsx(Y,{value:f.toString(),children:f},f))})]}),e.jsxs(I,{onClick:j,className:"gap-2 bg-re-green hover:bg-re-green/90 text-white shadow-sm flex-1 sm:flex-initial",children:[e.jsx(Ls,{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(Qe,{className:"w-8 h-8 animate-spin text-gray-400"})}):t.length===0?e.jsx(te,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(se,{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(mt,{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(I,{onClick:j,variant:"outline",className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(Ls,{className:"w-4 h-4"}),"Add First Holiday"]})]})}):e.jsx("div",{className:"space-y-4 sm:space-y-6",children:R.map(f=>{var T,F,K;return e.jsxs(te,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(me,{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(he,{className:"text-base sm:text-lg font-semibold text-slate-900",children:[f," ",n]}),e.jsxs(De,{className:"text-xs sm:text-sm",children:[((T=P[f])==null?void 0:T.length)||0," holiday",(((F=P[f])==null?void 0:F.length)||0)!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-blue-50 rounded-md",children:e.jsx(mt,{className:"w-4 h-4 text-blue-600"})})]})}),e.jsx(se,{className:"space-y-3 pt-4",children:(K=P[f])==null?void 0:K.map(B=>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:B.holidayName}),e.jsx(ie,{variant:"outline",className:`${S(B.holidayType)} text-[10px] sm:text-xs font-medium shadow-sm`,children:B.holidayType}),B.isRecurring&&e.jsx(ie,{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:nh(B.holidayDate)}),B.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-1.5 line-clamp-2",children:B.description})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-2 self-end sm:self-auto",children:[e.jsxs(I,{size:"sm",variant:"ghost",onClick:()=>v(B),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(Cu,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]}),e.jsxs(I,{size:"sm",variant:"ghost",onClick:()=>C(B),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(io,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Delete"})]})]})]},B.holidayId))})]},f)})}),e.jsx(ot,{open:l,onOpenChange:o,children:e.jsxs(nt,{className:"sm:max-w-[550px] max-h-[90vh] rounded-lg flex flex-col p-0",children:[e.jsx(ct,{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(mt,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(it,{className:"text-xl font-semibold text-slate-900",children:c?"Edit Holiday":"Add New Holiday"}),e.jsx(_t,{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(re,{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(Re,{id:"date",type:"date",value:p.holidayDate,onChange:f=>y({...p,holidayDate:f.target.value}),min:w(),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(re,{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(Re,{id:"name",placeholder:"e.g., Diwali, Republic Day, Christmas",value:p.holidayName,onChange:f=>y({...p,holidayName:f.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(re,{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(Re,{id:"description",placeholder:"Add additional details about this holiday...",value:p.description,onChange:f=>y({...p,description:f.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(re,{htmlFor:"type",className:"text-sm font-semibold text-slate-900",children:"Holiday Type"}),e.jsxs(Ue,{value:p.holidayType,onValueChange:f=>y({...p,holidayType:f}),children:[e.jsx(ze,{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(Ve,{})}),e.jsxs(He,{className:"rounded-lg",children:[e.jsx(Y,{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(Y,{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(Y,{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(Y,{value:"OPTIONAL",className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-slate-500"}),e.jsx("span",{children:"Optional"})]})})]})]}),e.jsx("p",{className:"text-xs text-slate-500",children:"Select the category of this holiday"})]}),e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-gradient-to-br from-slate-50 to-slate-100/50 border-2 border-slate-200 rounded-lg hover:border-slate-300 hover:bg-slate-100 transition-all cursor-pointer group",onClick:()=>y({...p,isRecurring:!p.isRecurring}),children:[e.jsx("input",{type:"checkbox",id:"recurring",checked:p.isRecurring,onChange:f=>y({...p,isRecurring:f.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(re,{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(At,{className:"gap-3 pt-4 border-t border-slate-100 px-6 pb-6 flex-shrink-0",children:[e.jsx(I,{variant:"outline",onClick:()=>o(!1),className:"h-11 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:"Cancel"}),e.jsxs(I,{onClick:N,disabled:!p.holidayDate||!p.holidayName,className:"h-11 bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx(mt,{className:"w-4 h-4 mr-2"}),c?"Update Holiday":"Add Holiday"]})]})]})})]})}function wk(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function Ck(){const[t,s]=x.useState(""),[a,r]=x.useState([]),[n,i]=x.useState(!1),[l,o]=x.useState(null),[c,d]=x.useState("USER"),[m,u]=x.useState(!1),[h,g]=x.useState(null),[p,y]=x.useState([]),[b,j]=x.useState(!1),[v,w]=x.useState({admins:0,management:0,users:0}),[N,C]=x.useState("ELEVATED"),[S,E]=x.useState(1),[P,R]=x.useState(1),[f,T]=x.useState(0),F=10,K=x.useRef(null),B=x.useRef(null),U=x.useCallback(wk(async _=>{var G,H,V;if(!_||!_.startsWith("@")||_.length<2){r([]),i(!1);return}i(!0);try{const ee=_.slice(1),pe=((G=(await Ms.searchUsers(ee,20)).data)==null?void 0:G.data)||[];r(pe)}catch(ee){console.error("Search failed:",ee),g({type:"error",text:((V=(H=ee.response)==null?void 0:H.data)==null?void 0:V.message)||"Failed to search users"})}finally{i(!1)}},300),[]),D=_=>{const G=_.target.value;s(G),U(G)},A=async _=>{o(_),s(_.email),r([]);const G=p.find(H=>H.email.toLowerCase()===_.email.toLowerCase()||H.userId===_.userId);if(G&&G.role)d(G.role);else try{const V=(await Ms.getAllUsers()).find(ee=>ee.email&&ee.email.toLowerCase()===_.email.toLowerCase()||ee.userId&&ee.userId===_.userId);V&&V.role?d(V.role):d("USER")}catch(H){console.error("Failed to check user role:",H),d("USER")}},k=async()=>{var _,G;if(!l||!c){g({type:"error",text:"Please select a user and role"});return}u(!0),g(null);try{await Ms.assignRole(l.email,c),g({type:"success",text:`Successfully assigned ${c} role to ${l.displayName||l.email}`}),o(null),s(""),d("USER"),await M(),await O()}catch(H){console.error("Role assignment failed:",H),g({type:"error",text:((G=(_=H.response)==null?void 0:_.data)==null?void 0:G.error)||"Failed to assign role"})}finally{u(!1)}},M=async(_=S)=>{var G,H,V,ee,oe,pe;j(!0);try{const Pe=await Ms.getUsersByRole(N,_,F),Se=((H=(G=Pe.data)==null?void 0:G.data)==null?void 0:H.users)||[],ne=(ee=(V=Pe.data)==null?void 0:V.data)==null?void 0:ee.pagination,de=(pe=(oe=Pe.data)==null?void 0:oe.data)==null?void 0:pe.summary;y(Se),ne&&(E(ne.currentPage),R(ne.totalPages),T(ne.totalUsers)),de&&w({admins:de.ADMIN||0,management:de.MANAGEMENT||0,users:de.USER||0})}catch(Pe){console.error("Failed to fetch users:",Pe)}finally{j(!1)}},O=async()=>{var _,G,H,V,ee,oe;try{const pe=await Ms.getRoleStatistics(),Pe=((G=(_=pe.data)==null?void 0:_.data)==null?void 0:G.statistics)||((H=pe.data)==null?void 0:H.statistics)||[];w({admins:parseInt(((V=Pe.find(Se=>Se.role==="ADMIN"))==null?void 0:V.count)||"0"),management:parseInt(((ee=Pe.find(Se=>Se.role==="MANAGEMENT"))==null?void 0:ee.count)||"0"),users:parseInt(((oe=Pe.find(Se=>Se.role==="USER"))==null?void 0:oe.count)||"0")})}catch(pe){console.error("Failed to fetch statistics:",pe)}};x.useEffect(()=>{M(1),O()},[N]);const L=_=>{C(_),E(1)},Z=_=>{M(_)},z=_=>{C(_),E(1),requestAnimationFrame(()=>{const G=B.current;G&&G.scrollIntoView({behavior:"smooth",block:"start"})})};x.useEffect(()=>{const _=G=>{K.current&&!K.current.contains(G.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",_),()=>{document.removeEventListener("mousedown",_)}},[a]);const $=_=>{switch(_){case"ADMIN":return"bg-yellow-400 text-slate-800";case"MANAGEMENT":return"bg-blue-400 text-slate-800";default:return"bg-gray-400 text-slate-800"}},W=_=>{switch(_){case"ADMIN":return e.jsx(or,{className:"w-5 h-5 text-slate-800"});case"MANAGEMENT":return e.jsx(Mt,{className:"w-5 h-5 text-slate-800"});default:return e.jsx(Pt,{className:"w-5 h-5 text-slate-800"})}};return e.jsxs(te,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(me,{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(Hf,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(he,{className:"text-lg font-semibold text-gray-900",children:"User Role Management"}),e.jsx(De,{className:"text-sm text-gray-600",children:"Search for users, assign roles, and manage user permissions across the system"})]})]})}),e.jsxs(se,{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(te,{className:`border-2 bg-gradient-to-br from-yellow-50 to-yellow-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${N==="ADMIN"?"border-yellow-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"admin-count-card",onClick:()=>z("ADMIN"),children:e.jsx(se,{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:v.admins}),e.jsx("p",{className:"text-xs text-yellow-700 mt-1 font-semibold",children:N==="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(or,{className:"w-6 h-6 text-slate-800"})})]})})}),e.jsx(te,{className:`border-2 bg-gradient-to-br from-blue-50 to-blue-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${N==="MANAGEMENT"?"border-blue-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"management-count-card",onClick:()=>z("MANAGEMENT"),children:e.jsx(se,{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:v.management}),e.jsx("p",{className:"text-xs text-blue-700 mt-1 font-semibold",children:N==="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(Mt,{className:"w-6 h-6 text-slate-800"})})]})})}),e.jsx(te,{className:`border-2 bg-gradient-to-br from-gray-50 to-gray-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${N==="USER"?"border-gray-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"user-count-card",onClick:()=>z("USER"),children:e.jsx(se,{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:v.users}),e.jsx("p",{className:"text-xs text-gray-700 mt-1 font-semibold",children:N==="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(Pt,{className:"w-6 h-6 text-slate-800"})})]})})})]}),e.jsx(Vt,{}),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:K,children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Search User"}),e.jsxs("div",{className:"relative",children:[e.jsx($s,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none"}),e.jsx(Re,{type:"text",placeholder:"Type @ to search users...",value:t,onChange:D,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(Qe,{className:"absolute right-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-re-green animate-spin"})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Start with @ to search users (e.g., @john)"}),a.length>0&&e.jsxs("div",{className:"border border-purple-200 rounded-lg shadow-lg bg-white max-h-60 overflow-y-auto",children:[e.jsx("div",{className:"sticky top-0 bg-purple-50 px-4 py-2 border-b border-purple-100",children:e.jsxs("p",{className:"text-xs font-semibold text-purple-700",children:[a.length," user",a.length>1?"s":""," found"]})}),e.jsx("div",{className:"p-2",children:a.map(_=>e.jsxs("button",{onClick:()=>A(_),className:"w-full text-left p-2 hover:bg-purple-50 rounded-lg transition-colors mb-1 last:mb-0","data-testid":`user-result-${_.email}`,children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:_.displayName||_.email}),e.jsx("p",{className:"text-xs text-gray-600",children:_.email}),_.department&&e.jsxs("p",{className:"text-xs text-gray-500",children:[_.department,_.designation?` • ${_.designation}`:""]})]},_.userId))})]})]}),l&&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:(l.displayName||l.email).charAt(0).toUpperCase()}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-slate-900",children:l.displayName||l.email}),e.jsx("p",{className:"text-sm text-slate-600",children:l.email}),l.department&&e.jsxs("p",{className:"text-xs text-slate-500 mt-1",children:[l.department,l.designation?` • ${l.designation}`:""]})]})]}),e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{o(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(Ue,{value:c,onValueChange:_=>d(_),children:[e.jsx(ze,{className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20","data-testid":"role-select",children:e.jsx(Ve,{placeholder:"Select role"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"w-4 h-4 text-gray-600"}),e.jsx("span",{children:"User - Regular access"})]})}),e.jsx(Y,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mt,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Management - Read all data"})]})}),e.jsx(Y,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(or,{className:"w-4 h-4 text-yellow-600"}),e.jsx("span",{children:"Administrator - Full access"})]})})]})]})]}),e.jsx(I,{onClick:k,disabled:!l||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(Qe,{className:"w-4 h-4 mr-2 animate-spin"}),"Assigning Role..."]}):e.jsxs(e.Fragment,{children:[e.jsx(cs,{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(We,{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(Vt,{}),e.jsxs("div",{ref:B,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 (",f," ",N!=="ALL"&&N!=="ELEVATED"?N.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(Ue,{value:N,onValueChange:L,children:[e.jsx(ze,{className:"w-[200px] h-10 border rounded-lg border-gray-300",children:e.jsx(Ve,{placeholder:"Filter by role"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"ELEVATED",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cs,{className:"w-4 h-4 text-purple-600"}),e.jsxs("span",{children:["Elevated (",v.admins+v.management,")"]})]})}),e.jsx(Y,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(or,{className:"w-4 h-4 text-yellow-600"}),e.jsxs("span",{children:["Admins (",v.admins,")"]})]})}),e.jsx(Y,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mt,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Management (",v.management,")"]})]})}),e.jsx(Y,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["Users (",v.users,")"]})]})}),e.jsx(Y,{value:"ALL",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mt,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["All Users (",v.admins+v.management+v.users,")"]})]})})]})]})})]}),e.jsx("div",{className:"pt-2",children:b?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsx(Qe,{className:"w-6 h-6 animate-spin text-purple-500 mb-2"}),e.jsx("p",{className:"text-sm text-gray-500",children:"Loading users..."})]}):p.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-gray-100 flex items-center justify-center mx-auto mb-3",children:e.jsx(Mt,{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:N==="ELEVATED"?"Assign ADMIN or MANAGEMENT roles to see users here":"No users match the selected filter"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-2","data-testid":"users-list",children:p.map(_=>e.jsx("div",{className:"border border-gray-200 hover:border-re-green hover:shadow-sm transition-all rounded-lg bg-white p-4","data-testid":`user-${_.email}`,children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx("div",{className:`w-10 h-10 rounded-lg ${$(_.role)} flex items-center justify-center shadow-sm`,children:W(_.role)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-semibold text-gray-900 truncate",children:_.displayName}),e.jsx("p",{className:"text-sm text-gray-600 truncate",children:_.email}),_.department&&e.jsxs("p",{className:"text-xs text-gray-500 mt-1 truncate",children:[_.department,_.designation?` • ${_.designation}`:""]})]})]}),e.jsx(ie,{className:`${$(_.role)} shrink-0`,"data-testid":`role-badge-${_.role}`,children:_.role})]})},_.userId))}),P>1&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("div",{className:"text-sm text-gray-600",children:["Showing ",(S-1)*F+1," to ",Math.min(S*F,f)," of ",f," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(I,{variant:"outline",size:"sm",onClick:()=>Z(S-1),disabled:S===1,"data-testid":"prev-page-button",children:"Previous"}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,P)},(_,G)=>{let H;return P<=5||S<=3?H=G+1:S>=P-2?H=P-4+G:H=S-2+G,e.jsx(I,{variant:S===H?"default":"outline",size:"sm",onClick:()=>Z(H),className:`w-9 h-9 p-0 ${S===H?"bg-re-green hover:bg-re-green/90 text-white":""}`,"data-testid":`page-${H}-button`,children:H},H)})}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>Z(S+1),disabled:S===P,"data-testid":"next-page-button",children:"Next"})]})]})]})})]})]})]})}function Sk({open:t,onClose:s,success:a,message:r}){return e.jsx(ot,{open:t,onOpenChange:s,children:e.jsxs(nt,{className:"sm:max-w-md",children:[e.jsxs(ct,{children:[e.jsxs(it,{className:"flex items-center gap-2",children:[e.jsx(vs,{className:"w-5 h-5 text-blue-600"}),"Push Notifications"]}),e.jsx(_t,{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(xt,{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(At,{children:e.jsx(I,{onClick:s,className:"w-full",children:a?"Done":"Close"})})]})})}const Ak=async()=>(await ye.get("/user/preferences/notifications")).data.data,Tk=async t=>(await ye.put("/user/preferences/notifications",t)).data.data;function kk({open:t,onClose:s}){const[a,r]=x.useState({emailNotificationsEnabled:!0,pushNotificationsEnabled:!0,inAppNotificationsEnabled:!0}),[n,i]=x.useState(!0),[l,o]=x.useState(null),[c,d]=x.useState(null),[m,u]=x.useState(null);x.useEffect(()=>{t&&h()},[t]);const h=async()=>{var p,y;try{i(!0),u(null);const b=await Ak();r(b)}catch(b){console.error("[NotificationPreferences] Failed to load preferences:",b),u(((y=(p=b.response)==null?void 0:p.data)==null?void 0:y.message)||"Failed to load notification preferences")}finally{i(!1)}},g=async(p,y)=>{var b,j;try{o(p),u(null),d(null);const v={[p]:y},w=await Tk(v);r(w),d(`${p==="emailNotificationsEnabled"?"Email":p==="pushNotificationsEnabled"?"Push":"In-App"} notifications ${y?"enabled":"disabled"}`),setTimeout(()=>d(null),3e3)}catch(v){console.error("[NotificationPreferences] Failed to update preference:",v),u(((j=(b=v.response)==null?void 0:b.data)==null?void 0:j.message)||"Failed to update notification preference"),h()}finally{o(null)}};return e.jsx(ot,{open:t,onOpenChange:s,children:e.jsxs(nt,{className:"sm:max-w-[600px] max-h-[85vh] overflow-y-auto",children:[e.jsx(ct,{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(Da,{className:"h-6 w-6 text-white"})}),e.jsxs("div",{children:[e.jsx(it,{className:"text-xl font-semibold",children:"Notification Preferences"}),e.jsx(_t,{className:"text-sm",children:"Customize how you receive notifications for workflow updates"})]})]})}),e.jsx(Vt,{className:"my-4"}),n?e.jsx("div",{className:"p-12 flex items-center justify-center",children:e.jsx(Qe,{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(We,{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(va,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(re,{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:[l==="emailNotificationsEnabled"&&e.jsx(Qe,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(Ns,{id:"email-notifications-modal",checked:a.emailNotificationsEnabled,onCheckedChange:p=>g("emailNotificationsEnabled",p),disabled:l==="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(vs,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(re,{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:[l==="pushNotificationsEnabled"&&e.jsx(Qe,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(Ns,{id:"push-notifications-modal",checked:a.pushNotificationsEnabled,onCheckedChange:p=>g("pushNotificationsEnabled",p),disabled:l==="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(Os,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(re,{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:[l==="inAppNotificationsEnabled"&&e.jsx(Qe,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(Ns,{id:"inapp-notifications-modal",checked:a.inAppNotificationsEnabled,onCheckedChange:p=>g("inAppNotificationsEnabled",p),disabled:l==="inAppNotificationsEnabled"})]})]})}),e.jsx(Vt,{}),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 Dk(){const{user:t}=Kt(),s=Ka(t),[a,r]=x.useState(!1),[n,i]=x.useState(!1),[l,o]=x.useState(),[c,d]=x.useState(!1),[m,u]=x.useState(!1),[h,g]=x.useState(!1),[p,y]=x.useState(!0);x.useEffect(()=>{b()},[]);const b=async()=>{try{y(!0);const v=await Fy();g(v.length>0)}catch(v){console.error("Failed to check subscription status:",v),g(!1)}finally{y(!1)}},j=async()=>{d(!0),r(!1);try{if(!("Notification"in window)){i(!1),o("Notifications are not supported in this browser. Please use a modern browser like Chrome, Firefox, or Edge."),r(!0),d(!1);return}let v=Notification.permission;if(v==="denied"){i(!1),o(`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(v==="default"&&(v=await Notification.requestPermission(),v==="denied")){i(!1),o(`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(v!=="granted"){i(!1),o("Notification permission is required to enable push notifications. Please grant permission and try again."),r(!0),d(!1);return}await vk(),i(!0),o("Push notifications have been successfully enabled! You will now receive notifications for workflow updates, approvals, and TAT alerts."),r(!0),await b()}catch(v){console.error("[Settings] Error enabling notifications:",v),i(!1);const w=(v==null?void 0:v.message)||"Unknown error occurred";o(w.includes("permission")?"Notification permission was denied. Please enable notifications in your browser settings and try again.":w.includes("Service worker")?"Service worker registration failed. Please refresh the page and try again.":w.includes("token")?"Authentication required. Please log in again and try enabling notifications.":`Unable to enable push notifications: ${w}`),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(te,{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(se,{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(Da,{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(wn,{defaultValue:"user",className:"w-full",children:[e.jsxs(Cn,{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(Ct,{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(Da,{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(Ct,{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(cs,{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(Ct,{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(Du,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Configuration"}),e.jsx("span",{className:"sm:hidden",children:"Config"})]}),e.jsxs(Ct,{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(mt,{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(St,{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(te,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(me,{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(vs,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(he,{className:"text-lg font-semibold text-gray-900",children:"Browser Push Setup"}),e.jsx(De,{className:"text-sm text-gray-600",children:"Register this browser for push notifications"})]})]})}),e.jsx(se,{children:e.jsxs("div",{className:"space-y-4",children:[p?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(I,{onClick:j,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(vs,{className:`w-4 h-4 mr-2 ${c?"animate-pulse":""}`}),c?"Registering...":h?"Already Registered":"Register Browser for Push"]})]})})]}),e.jsxs(te,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(me,{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(on,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(he,{className:"text-lg font-semibold text-gray-900",children:"Security"}),e.jsx(De,{className:"text-sm text-gray-600",children:"Password and security settings"})]})]})}),e.jsx(se,{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(te,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(me,{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(sd,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(he,{className:"text-lg font-semibold text-gray-900",children:"Appearance"}),e.jsx(De,{className:"text-sm text-gray-600",children:"Theme and display preferences"})]})]})}),e.jsx(se,{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(te,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(me,{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(cs,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(he,{className:"text-lg font-semibold text-gray-900",children:"Preferences"}),e.jsx(De,{className:"text-sm text-gray-600",children:"Notification and application preferences"})]})]})}),e.jsx(se,{children:e.jsxs(I,{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(cs,{className:"w-4 h-4 mr-2"}),"Manage Preferences"]})})]})]})}),e.jsx(St,{value:"roles",className:"mt-0",children:e.jsx(Ck,{})}),e.jsx(St,{value:"system",className:"mt-0",children:e.jsx(jk,{})}),e.jsx(St,{value:"holidays",className:"mt-0",children:e.jsx(Nk,{})})]})]}):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(te,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(me,{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(vs,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(he,{className:"text-lg font-semibold text-gray-900",children:"Browser Push Setup"}),e.jsx(De,{className:"text-sm text-gray-600",children:"Register this browser for push notifications"})]})]})}),e.jsx(se,{children:e.jsxs("div",{className:"space-y-4",children:[p?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(I,{onClick:j,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(vs,{className:`w-4 h-4 mr-2 ${c?"animate-pulse":""}`}),c?"Registering...":h?"Already Registered":"Register Browser for Push"]})]})})]}),e.jsxs(te,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(me,{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(on,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(he,{className:"text-lg font-semibold text-gray-900",children:"Security"}),e.jsx(De,{className:"text-sm text-gray-600",children:"Password and security settings"})]})]})}),e.jsx(se,{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(te,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(me,{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(sd,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(he,{className:"text-lg font-semibold text-gray-900",children:"Appearance"}),e.jsx(De,{className:"text-sm text-gray-600",children:"Theme and display preferences"})]})]})}),e.jsx(se,{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(te,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(me,{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(cs,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(he,{className:"text-lg font-semibold text-gray-900",children:"Preferences"}),e.jsx(De,{className:"text-sm text-gray-600",children:"Notification and application preferences"})]})]})}),e.jsx(se,{children:e.jsxs(I,{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(cs,{className:"w-4 h-4 mr-2"}),"Manage Preferences"]})})]})]})})]}),e.jsx(Sk,{open:a,onClose:()=>r(!1),success:n,message:l}),e.jsx(kk,{open:m,onClose:()=>u(!1)})]})}function Rk({onNavigate:t}){const[s,a]=x.useState([]),[r,n]=x.useState(!0),[i,l]=x.useState(1),[o,c]=x.useState(1),[d,m]=x.useState(0),[u,h]=x.useState("all"),[g,p]=x.useState(!1),y=20,b=async(R=i,f=u==="unread")=>{var T,F;try{n(R===1);const K=await ka.list({page:R,limit:y,unreadOnly:f}),B=((T=K.data)==null?void 0:T.notifications)||[],U=((F=K.data)==null?void 0:F.total)||0;a(B),m(U),c(Math.ceil(U/y))}catch(K){console.error("[Notifications] Failed to fetch:",K)}finally{n(!1),p(!1)}};x.useEffect(()=>{b(1,u==="unread")},[u]);const j=async R=>{var f;try{if(R.isRead||(await ka.markAsRead(R.notificationId),a(T=>T.map(F=>F.notificationId===R.notificationId?{...F,isRead:!0}:F))),R.actionUrl&&t){const T=(f=R.metadata)==null?void 0:f.requestNumber;if(T){let F=`request/${T}`;(R.notificationType==="mention"||R.notificationType==="comment"||R.notificationType==="worknote")&&(F+="?tab=worknotes"),t(F)}}}catch(T){console.error("[Notifications] Error handling notification click:",T)}},v=async()=>{try{p(!0),await ka.markAllAsRead(),await b(i,u==="unread")}catch(R){console.error("[Notifications] Error marking all as read:",R),p(!1)}},w=async R=>{try{await ka.delete(R),a(f=>f.filter(T=>T.notificationId!==R)),m(f=>f-1)}catch(f){console.error("[Notifications] Error deleting notification:",f)}},N=()=>{p(!0),b(i,u==="unread")},C=R=>{R<1||R>o||(l(R),b(R,u==="unread"))},S=R=>{const f="w-6 h-6";switch(R){case"mention":case"comment":return e.jsx(Os,{className:`${f} text-blue-600`});case"worknote":return e.jsx(Le,{className:`${f} text-purple-600`});case"assignment":return e.jsx(di,{className:`${f} text-indigo-600`});case"approval":return e.jsx(Ce,{className:`${f} text-green-600`});case"rejection":return e.jsx(xt,{className:`${f} text-red-600`});case"tat_alert":return e.jsx(Ze,{className:`${f} text-orange-600`});case"tat_breach":return e.jsx(We,{className:`${f} text-red-600`});case"tat_breach_initiator":return e.jsx(hs,{className:`${f} text-amber-600`});default:return e.jsx(vs,{className:`${f} text-gray-600`})}},E=R=>{switch(R==null?void 0:R.toUpperCase()){case"URGENT":return"bg-red-100 text-red-800 border-red-200";case"HIGH":return"bg-orange-100 text-orange-800 border-orange-200";case"MEDIUM":return"bg-blue-100 text-blue-800 border-blue-200";default:return"bg-gray-100 text-gray-800 border-gray-200"}},P=s.filter(R=>!R.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(vs,{className:"w-8 h-8 text-blue-600"}),"Notifications"]}),e.jsxs("p",{className:"text-gray-600 mt-1",children:[d," total notification",d!==1?"s":"",P>0&&` • ${P} unread`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(I,{variant:"outline",size:"sm",onClick:N,disabled:g,className:"gap-2",children:[e.jsx(ns,{className:`w-4 h-4 ${g?"animate-spin":""}`}),"Refresh"]}),P>0&&e.jsxs(I,{variant:"outline",size:"sm",onClick:v,disabled:g,className:"gap-2",children:[e.jsx(Wf,{className:"w-4 h-4"}),"Mark All Read"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(I,{variant:u==="all"?"default":"outline",size:"sm",onClick:()=>{h("all"),l(1)},children:"All Notifications"}),e.jsxs(I,{variant:u==="unread"?"default":"outline",size:"sm",onClick:()=>{h("unread"),l(1)},children:["Unread",P>0&&e.jsx(ie,{className:"ml-2 bg-red-500 text-white",children:P})]})]}),e.jsxs(te,{children:[e.jsxs(me,{children:[e.jsx(he,{children:"Recent Activity"}),e.jsx(De,{children:"Stay updated with all your workflow activities and mentions"})]}),e.jsx(se,{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(vs,{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(R=>{var f;return e.jsx("div",{className:`p-4 rounded-lg border transition-all cursor-pointer hover:shadow-md ${R.isRead?"bg-white border-gray-200 hover:bg-gray-50":"bg-blue-50 border-blue-200 hover:bg-blue-100"}`,onClick:()=>j(R),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"shrink-0 mt-0.5",children:S(R.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 ${R.isRead?"font-semibold":"font-bold"} text-gray-900`,children:R.title}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[R.priority&&R.priority!=="LOW"&&e.jsx(ie,{variant:"outline",className:`text-xs ${E(R.priority)}`,children:R.priority}),!R.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:R.message}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:[uu(new Date(R.createdAt),{addSuffix:!0}),((f=R.metadata)==null?void 0:f.requestNumber)&&e.jsxs("span",{className:"ml-2",children:["• ",R.metadata.requestNumber]})]}),e.jsx(I,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-600",onClick:T=>{T.stopPropagation(),w(R.notificationId)},children:e.jsx(io,{className:"w-3.5 h-3.5"})})]})]})]})},R.notificationId)})})})]}),!r&&o>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(I,{variant:"outline",size:"sm",onClick:()=>C(i-1),disabled:i===1,children:[e.jsx(Tu,{className:"w-4 h-4"}),"Previous"]}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,o)},(R,f)=>{let T;return o<=5||i<=3?T=f+1:i>=o-2?T=o-4+f:T=i-2+f,e.jsx(I,{variant:i===T?"default":"outline",size:"sm",className:"w-9 h-9 p-0",onClick:()=>C(T),children:T},T)})}),e.jsxs(I,{variant:"outline",size:"sm",onClick:()=>C(i+1),disabled:i===o,children:["Next",e.jsx(ro,{className:"w-4 h-4"})]})]})]})]})}function Pk({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(I,{variant:"outline",onClick:t,className:"inline-flex items-center gap-2","data-testid":"back-button",children:[e.jsx(Ys,{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(Le,{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 nc({dateRange:t,customStartDate:s,customEndDate:a,showCustomDatePicker:r,tempCustomStartDate:n,tempCustomEndDate:i,onDateRangeChange:l,onShowCustomDatePickerChange:o,onStartDateChange:c,onEndDateChange:d,onApply:m,onCancel:u,testIdPrefix:h="date-filter"}){const g=s&&a?`${Ie(s,"MMM d, yyyy")} - ${Ie(a,"MMM d, yyyy")}`:"Select dates";return e.jsxs("div",{className:"flex items-center gap-2","data-testid":`${h}-container`,children:[e.jsx(mt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ue,{value:t,onValueChange:l,"data-testid":`${h}-select`,children:[e.jsx(ze,{className:"w-[160px]",children:e.jsx(Ve,{placeholder:"Date Range"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"today",children:"Today"}),e.jsx(Y,{value:"week",children:"This Week"}),e.jsx(Y,{value:"month",children:"This Month"}),e.jsx(Y,{value:"custom",children:"Custom Range"})]})]}),t==="custom"&&e.jsxs(ra,{open:r,onOpenChange:o,children:[e.jsx(na,{asChild:!0,children:e.jsxs(I,{variant:"outline",size:"sm",className:"gap-2","data-testid":`${h}-custom-trigger`,children:[e.jsx(mt,{className:"w-4 h-4"}),g]})}),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(re,{htmlFor:`${h}-start-date`,className:"text-sm font-medium",children:"Start Date"}),e.jsx(Re,{id:`${h}-start-date`,type:"date",value:n?Ie(n,"yyyy-MM-dd"):"",onChange:p=>{const y=p.target.value?new Date(p.target.value):void 0;c(y)},max:Ie(new Date,"yyyy-MM-dd"),className:"w-full","data-testid":`${h}-start-input`})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:`${h}-end-date`,className:"text-sm font-medium",children:"End Date"}),e.jsx(Re,{id:`${h}-end-date`,type:"date",value:i?Ie(i,"yyyy-MM-dd"):"",onChange:p=>{const y=p.target.value?new Date(p.target.value):void 0;d(y)},min:n?Ie(n,"yyyy-MM-dd"):void 0,max:Ie(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(I,{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(I,{size:"sm",variant:"outline",onClick:u,"data-testid":`${h}-cancel-button`,children:"Cancel"})]})]})})]})]})}function Ik(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 _x(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 Lx(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 Ek(t){return t>=20?"bg-red-600":t>=10?"bg-orange-500":"bg-amber-500"}function Mk({lifecycleRequests:t,loading:s,loadingPage:a,error:r,pagination:n,dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,exporting:u,onDateRangeChange:h,onShowCustomDatePickerChange:g,onStartDateChange:p,onEndDateChange:y,onApplyCustomDate:b,onCancelCustomDate:j,onPageChange:v,onExport:w,onViewRequest:N}){return e.jsxs(te,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"request-lifecycle-report",children:[e.jsxs(me,{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(ts,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(he,{className:"text-lg text-gray-900",children:"Request Lifecycle Report"}),e.jsx(De,{className:"text-gray-600",children:"End-to-end workflow status including all approval levels, approvers, dates, and TAT compliance"})]})]}),e.jsxs(I,{variant:"outline",size:"sm",className:"gap-2",onClick:w,disabled:u,"data-testid":"export-lifecycle-button",children:[e.jsx(Nt,{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(nc,{dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,onDateRangeChange:h,onShowCustomDatePickerChange:g,onStartDateChange:p,onEndDateChange:y,onApply:b,onCancel:j,testIdPrefix:"lifecycle"})})]}),e.jsxs(se,{children:[s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"lifecycle-loading",children:[e.jsx(Qe,{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(We,{className:"w-5 h-5 mr-2"}),e.jsx("span",{className:"text-sm",children:r})]}):t.length===0?e.jsx("div",{className:"text-center py-12 text-gray-500","data-testid":"lifecycle-empty",children:e.jsx("p",{className:"text-sm",children:"No lifecycle data available"})}):e.jsx("div",{className:"space-y-4",children:t.map(C=>e.jsx("div",{className:"border rounded-xl overflow-hidden","data-testid":`lifecycle-request-${C.id}`,children:e.jsx("div",{className:"p-4 bg-gradient-to-r from-gray-50 to-white hover:bg-gray-100 cursor-pointer transition-all",onClick:()=>N(C.requestId||C.id),children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"flex items-center gap-4",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("button",{onClick:S=>{S.stopPropagation(),N(C.requestId||C.id)},className:"font-semibold text-sm text-blue-600 hover:text-blue-800 hover:underline cursor-pointer transition-colors","data-testid":`lifecycle-request-link-${C.id}`,children:C.id}),e.jsx(ie,{className:_x(C.priority),"data-testid":`lifecycle-priority-${C.id}`,children:C.priority}),e.jsx(ie,{className:Lx(C.status),"data-testid":`lifecycle-status-${C.id}`,children:C.status})]}),e.jsx("p",{className:"text-sm text-gray-700",children:C.title}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["Initiated by ",e.jsx("span",{className:"font-medium",children:C.initiator})," on ",C.initDate]}),C.currentStage&&!C.currentStage.includes("Level")&&e.jsxs("p",{className:"text-xs text-gray-400 mt-0.5",children:["Stage: ",C.currentStage]})]})}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Current Stage"}),e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:C.currentStage}),e.jsxs("p",{className:"text-xs text-gray-400 mt-0.5",children:["(Level ",C.currentLevel,"/",C.totalLevels,")"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-xs text-gray-500",children:"Overall TAT"}),e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:C.overallTAT}),C.breachCount>0&&e.jsxs("p",{className:"text-xs text-red-500 mt-0.5",children:[C.breachCount," breach",C.breachCount>1?"es":""]})]}),e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>N(C.requestId||C.id),className:"gap-1.5","data-testid":`lifecycle-view-button-${C.id}`,children:e.jsx(ro,{className:"w-4 h-4"})})]})]})})},C.id))}),n.totalPages>1&&e.jsxs("div",{className:"flex items-center justify-between p-4 border-t relative","data-testid":"lifecycle-pagination",children:[a&&e.jsx("div",{className:"absolute inset-0 bg-white/80 flex items-center justify-center z-10 rounded-b-lg",children:e.jsx(Qe,{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(I,{variant:"outline",size:"sm",onClick:()=>v(n.page-1),disabled:n.page<=1||a,"data-testid":"lifecycle-pagination-prev",children:"Previous"}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>v(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"lifecycle-pagination-next",children:"Next"})]})]})]})]})}function ic({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:we("w-full caption-bottom text-sm",t),...s})})}function lc({className:t,...s}){return e.jsx("thead",{"data-slot":"table-header",className:we("[&_tr]:border-b",t),...s})}function oc({className:t,...s}){return e.jsx("tbody",{"data-slot":"table-body",className:we("[&_tr:last-child]:border-0",t),...s})}function rr({className:t,...s}){return e.jsx("tr",{"data-slot":"table-row",className:we("hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",t),...s})}function Jt({className:t,...s}){return e.jsx("th",{"data-slot":"table-head",className:we("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 Gt({className:t,...s}){return e.jsx("td",{"data-slot":"table-cell",className:we("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",t),...s})}function Fk({activityLog:t,loading:s,loadingPage:a,error:r,pagination:n,dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,filterCategory:u,filterSeverity:h,exporting:g,onDateRangeChange:p,onShowCustomDatePickerChange:y,onStartDateChange:b,onEndDateChange:j,onApplyCustomDate:v,onCancelCustomDate:w,onCategoryChange:N,onSeverityChange:C,onClearFilters:S,onPageChange:E,onExport:P,onViewRequest:R}){const f=u!=="all"||h!=="all"||i!=="month"||l||o;return e.jsxs(te,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"user-activity-log-report",children:[e.jsxs(me,{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(Gf,{className:"h-5 w-5 text-indigo-600"})}),e.jsxs("div",{children:[e.jsx(he,{className:"text-lg text-gray-900",children:"User Activity Log Report"}),e.jsx(De,{className:"text-gray-600",children:"Consolidated user actions and activity history"})]})]}),e.jsxs(I,{variant:"outline",size:"sm",className:"gap-2",onClick:P,disabled:g,"data-testid":"export-activity-button",children:[e.jsx(Nt,{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(nc,{dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,onDateRangeChange:p,onShowCustomDatePickerChange:y,onStartDateChange:b,onEndDateChange:j,onApply:v,onCancel:w,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(Ue,{value:u,onValueChange:N,"data-testid":"activity-category-filter",children:[e.jsx(ze,{className:"w-40",children:e.jsx(Ve,{placeholder:"All Categories"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"all",children:"All Categories"}),e.jsx(Y,{value:"WORKFLOW",children:"Workflow"}),e.jsx(Y,{value:"COLLABORATION",children:"Collaboration"}),e.jsx(Y,{value:"DOCUMENT",children:"Document"}),e.jsx(Y,{value:"AUTHENTICATION",children:"Authentication"}),e.jsx(Y,{value:"SYSTEM",children:"System"}),e.jsx(Y,{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(Ue,{value:h,onValueChange:C,"data-testid":"activity-severity-filter",children:[e.jsx(ze,{className:"w-40",children:e.jsx(Ve,{placeholder:"All Severities"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"all",children:"All Severities"}),e.jsx(Y,{value:"INFO",children:"Info"}),e.jsx(Y,{value:"WARNING",children:"Warning"}),e.jsx(Y,{value:"ERROR",children:"Error"}),e.jsx(Y,{value:"CRITICAL",children:"Critical"})]})]})]}),f&&e.jsx(I,{variant:"ghost",size:"sm",onClick:S,className:"text-xs","data-testid":"activity-clear-filters",children:"Clear Filters"})]})]}),e.jsx(se,{children:s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"activity-loading",children:[e.jsx(Qe,{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(We,{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(ic,{children:[e.jsx(lc,{children:e.jsxs(rr,{className:"bg-gray-50",children:[e.jsx(Jt,{className:"font-semibold",children:"Timestamp"}),e.jsx(Jt,{className:"font-semibold",children:"User"}),e.jsx(Jt,{className:"font-semibold",children:"Action"}),e.jsx(Jt,{className:"font-semibold",children:"Details"}),e.jsx(Jt,{className:"font-semibold",children:"IP Address"}),e.jsx(Jt,{className:"font-semibold",children:"Request ID"})]})}),e.jsx(oc,{children:t.map((T,F)=>e.jsxs(rr,{className:"hover:bg-gray-50","data-testid":`activity-row-${F}`,children:[e.jsx(Gt,{className:"text-xs font-medium",children:T.timestamp}),e.jsx(Gt,{className:"text-sm",children:T.user}),e.jsx(Gt,{children:e.jsx(ie,{className:Ik(T.action),"data-testid":`activity-action-${F}`,children:T.action})}),e.jsx(Gt,{className:"text-sm text-gray-600",children:T.details}),e.jsx(Gt,{className:"text-xs font-mono text-gray-500",children:T.ip&&T.ip!=="N/A"?e.jsx("span",{title:T.userAgent||"",children:T.ip}):e.jsx("span",{className:"text-gray-400 italic",title:"IP address not yet captured",children:"N/A"})}),e.jsx(Gt,{children:T.requestId!=="-"&&T.requestId!=="System Login"?e.jsx("button",{onClick:()=>{const K=T.requestId;K&&R(K)},className:"hover:underline","data-testid":`activity-request-link-${F}`,children:e.jsx(ie,{variant:"outline",className:"text-xs cursor-pointer hover:bg-blue-50 hover:border-blue-300 transition-colors",children:T.requestId})}):e.jsx("span",{className:"text-xs text-gray-400",children:"-"})})]},F))})]}),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(Qe,{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(I,{variant:"outline",size:"sm",onClick:()=>E(n.page-1),disabled:n.page<=1||a,"data-testid":"activity-pagination-prev",children:"Previous"}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>E(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"activity-pagination-next",children:"Next"})]})]})]})})]})}function _k({agingWorkflows:t,loading:s,loadingPage:a,error:r,pagination:n,threshold:i,thresholdError:l,dateRange:o,customStartDate:c,customEndDate:d,showCustomDatePicker:m,tempCustomStartDate:u,tempCustomEndDate:h,searchQuery:g,exporting:p,onThresholdChange:y,onThresholdBlur:b,onDateRangeChange:j,onShowCustomDatePickerChange:v,onStartDateChange:w,onEndDateChange:N,onApplyCustomDate:C,onCancelCustomDate:S,onSearchChange:E,onPageChange:P,onExport:R,onViewRequest:f}){return e.jsxs(te,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"workflow-aging-report",children:[e.jsxs(me,{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(no,{className:"h-5 w-5 text-amber-600"})}),e.jsxs("div",{children:[e.jsx(he,{className:"text-lg text-gray-900",children:"Workflow Aging Report"}),e.jsx(De,{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(Re,{type:"number",min:"1",value:i,onChange:T=>y(T.target.value),onBlur:b,className:`w-24 ${l?"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"})]}),l&&e.jsx("span",{className:"text-xs text-red-600",children:l})]})]}),e.jsxs(ie,{variant:"outline",className:"font-semibold","data-testid":"aging-total-badge",children:[n.totalRecords," workflows"]}),e.jsxs(I,{variant:"outline",size:"sm",className:"gap-2",onClick:R,disabled:p,"data-testid":"export-aging-button",children:[e.jsx(Nt,{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(nc,{dateRange:o,customStartDate:c,customEndDate:d,showCustomDatePicker:m,tempCustomStartDate:u,tempCustomEndDate:h,onDateRangeChange:j,onShowCustomDatePickerChange:v,onStartDateChange:w,onEndDateChange:N,onApply:C,onCancel:S,testIdPrefix:"aging"}),e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx($s,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(Re,{placeholder:"Search by Request ID, Title, or Initiator...",value:g,onChange:T=>E(T.target.value),className:"pl-10","data-testid":"aging-search-input"})]})]})]}),e.jsx(se,{children:s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"aging-loading",children:[e.jsx(Qe,{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(We,{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(ic,{children:[e.jsx(lc,{children:e.jsxs(rr,{className:"bg-gray-50",children:[e.jsx(Jt,{className:"font-semibold",children:"Request ID"}),e.jsx(Jt,{className:"font-semibold",children:"Title"}),e.jsx(Jt,{className:"font-semibold",children:"Initiator"}),e.jsx(Jt,{className:"font-semibold",children:"Start Date"}),e.jsx(Jt,{className:"font-semibold",children:"Days Open"}),e.jsx(Jt,{className:"font-semibold",children:"Current Stage"}),e.jsx(Jt,{className:"font-semibold",children:"Assigned To"}),e.jsx(Jt,{className:"font-semibold",children:"Priority"}),e.jsx(Jt,{className:"font-semibold",children:"Status"})]})}),e.jsx(oc,{children:t.map(T=>e.jsxs(rr,{className:"hover:bg-gray-50","data-testid":`aging-workflow-${T.id}`,children:[e.jsx(Gt,{className:"font-medium text-sm",children:e.jsx("button",{onClick:()=>f(T.requestId||T.id),className:"text-blue-600 hover:text-blue-800 hover:underline cursor-pointer transition-colors","data-testid":`aging-request-link-${T.id}`,children:T.id})}),e.jsx(Gt,{className:"text-sm",children:T.title}),e.jsx(Gt,{className:"text-sm",children:T.initiator}),e.jsx(Gt,{className:"text-sm text-gray-600",children:T.startDate}),e.jsx(Gt,{children:e.jsxs(ie,{className:`${Ek(T.daysOpen)} text-white border-transparent`,"data-testid":`aging-days-${T.id}`,children:[T.daysOpen," days",e.jsx("span",{className:"ml-1 text-xs opacity-75",children:"(business)"})]})}),e.jsx(Gt,{className:"text-sm",children:T.currentStage}),e.jsx(Gt,{className:"text-sm",children:T.assignedTo&&T.assignedTo!=="N/A"?T.assignedTo:e.jsx("span",{className:"text-gray-400 italic",title:"Assigned approver not available",children:"N/A"})}),e.jsx(Gt,{children:e.jsx(ie,{className:_x(T.priority),"data-testid":`aging-priority-${T.id}`,children:T.priority})}),e.jsx(Gt,{children:e.jsx(ie,{className:Lx(T.status),"data-testid":`aging-status-${T.id}`,children:T.status})})]},T.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(Qe,{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(I,{variant:"outline",size:"sm",onClick:()=>P(n.page-1),disabled:n.page<=1||a,"data-testid":"aging-pagination-prev",children:"Previous"}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>P(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"aging-pagination-next",children:"Next"})]})]})]})})]})}function xl(t="month"){const[s,a]=x.useState(t),[r,n]=x.useState(void 0),[i,l]=x.useState(void 0),[o,c]=x.useState(!1),[d,m]=x.useState(void 0),[u,h]=x.useState(void 0),g=x.useCallback(N=>{const C=N;a(C),C!=="custom"?(n(void 0),l(void 0),m(void 0),h(void 0),c(!1)):(m(r),h(i),c(!0))},[r,i]),p=x.useCallback(()=>{if(d&&u){if(d>u){const N=d;n(u),l(N),m(u),h(N)}else n(d),l(u);c(!1)}},[d,u]),y=x.useCallback(()=>{c(!1),m(r),h(i),(!r||!i)&&(n(void 0),l(void 0),a("month"))},[r,i]),b=x.useCallback(N=>{N?(m(N),u&&N>u&&h(N)):m(void 0)},[u]),j=x.useCallback(N=>{N?(h(N),d&&N<d&&m(N)):h(void 0)},[d]),v=x.useCallback(()=>r&&i?`${Ie(r,"MMM d, yyyy")} - ${Ie(i,"MMM d, yyyy")}`:"Select dates",[r,i]),w=x.useCallback(()=>{a("month"),n(void 0),l(void 0),c(!1),m(void 0),h(void 0)},[]);return{dateRange:s,customStartDate:r,customEndDate:i,showCustomDatePicker:o,tempCustomStartDate:d,tempCustomEndDate:u,setShowCustomDatePicker:c,handleDateRangeChange:g,handleApplyCustomDate:p,handleCancelCustomDate:y,handleStartDateChange:b,handleEndDateChange:j,getDisplayDateRange:v,reset:w}}function Lk(t){if(!t&&t!==0)return"N/A";const s=8;if(t<s)return It(t);const a=Math.floor(t/s),r=t%s;return r>0?`${a}d ${It(r)}`:`${a}d`}function Ox(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 Xa(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"),l=String(s.getMinutes()).padStart(2,"0");return`${a}-${r}-${n} ${i}:${l}`}catch{return t}}function $x(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 Ok=10;function $k({dateRange:t,customStartDate:s,customEndDate:a}){const[r,n]=x.useState([]),[i,l]=x.useState(!0),[o,c]=x.useState(!1),[d,m]=x.useState(null),[u,h]=x.useState({page:1,totalPages:1,totalRecords:0}),g=x.useRef(!0),p=x.useCallback(async(y=1)=>{const b=y===1&&g.current;try{b?l(!0):c(!0),m(null);const j=await jt.getLifecycleReport(y,Ok,t,s,a),v=j.lifecycleData.map(w=>{const N=Lk(w.overallTATHours);return{id:w.requestNumber,requestId:w.requestId,title:w.title,priority:w.priority||"medium",status:w.status,initiator:w.initiatorName||"Unknown",initDate:Ox(w.submissionDate),currentStage:w.currentStageName||`Level ${w.currentLevel}`,overallTAT:N,currentLevel:w.currentLevel,totalLevels:w.totalLevels,breachCount:w.breachCount||0}});n(v),h({page:j.pagination.currentPage,totalPages:j.pagination.totalPages,totalRecords:j.pagination.totalRecords})}catch(j){console.error("Failed to fetch lifecycle data:",j),m((j==null?void 0:j.message)||"Failed to load lifecycle data")}finally{b?l(!1):c(!1)}b&&(g.current=!1)},[t,s,a]);return x.useEffect(()=>{t==="custom"&&(!s||!a)||p(1)},[t,s,a]),{lifecycleRequests:r,loading:i,loadingPage:o,error:d,pagination:u,fetchData:p}}const Bk=20;function Uk({dateRange:t,customStartDate:s,customEndDate:a,filterCategory:r,filterSeverity:n}){const[i,l]=x.useState([]),[o,c]=x.useState(!0),[d,m]=x.useState(!1),[u,h]=x.useState(null),[g,p]=x.useState({page:1,totalPages:1,totalRecords:0}),y=x.useRef(!0),b=x.useCallback(async(j=1)=>{const v=j===1&&y.current;try{v?c(!0):m(!0),h(null);const w=await jt.getActivityLogReport(j,Bk,t,void 0,void 0,r&&r!=="all"?r:void 0,n&&n!=="all"?n:void 0,s,a),N=w.activities.map(C=>{const S=$x(C.type||"",C.details),E=(C.type||"").toLowerCase()==="login"||C.requestId==="00000000-0000-0000-0000-000000000001"||C.requestId==="SYSTEM_LOGIN",P=E?C.details||"User login":C.requestTitle||C.requestNumber||C.details||"N/A";return{timestamp:C.timestamp?Ox(C.timestamp):"N/A",user:C.userName||"Unknown",action:S,details:P,ip:C.ipAddress||"N/A",userAgent:C.userAgent||null,requestId:E?"System Login":C.requestNumber||C.requestId||"-",userId:C.userId}});l(N),p({page:w.pagination.currentPage,totalPages:w.pagination.totalPages,totalRecords:w.pagination.totalRecords})}catch(w){console.error("Failed to fetch activity data:",w),h((w==null?void 0:w.message)||"Failed to load activity data")}finally{v?c(!1):m(!1)}v&&(y.current=!1)},[r,n,t,s,a]);return x.useEffect(()=>{t==="custom"&&(!s||!a)||b(1)},[r,n,t,s,a]),{activityLog:i,loading:o,loadingPage:d,error:u,pagination:g,fetchData:b}}const Vk=20;function zk({threshold:t,dateRange:s,customStartDate:a,customEndDate:r,searchQuery:n=""}){const[i,l]=x.useState([]),[o,c]=x.useState(!0),[d,m]=x.useState(!1),[u,h]=x.useState(null),[g,p]=x.useState({page:1,totalPages:1,totalRecords:0}),y=x.useRef(!0),b=x.useCallback(async(v=1)=>{const w=v===1&&y.current;try{w?c(!0):m(!0),h(null);const N=parseInt(t,10);if(isNaN(N)||N<1){h("Please enter a valid threshold (minimum 1 day)");return}const C=await jt.getWorkflowAgingReport(N,v,Vk,s,a,r),S=C.agingData.map(E=>({id:E.requestNumber||E.requestId,requestId:E.requestId,title:E.title,initiator:E.initiatorName||"Unknown",startDate:E.submissionDate?new Date(E.submissionDate).toLocaleDateString():"N/A",daysOpen:E.daysOpen,currentStage:E.currentStageName||`Level ${E.currentLevel}`,assignedTo:E.currentApproverName||"N/A",priority:E.priority||"medium",status:E.status||"pending"}));l(S),p({page:C.pagination.currentPage,totalPages:C.pagination.totalPages,totalRecords:C.pagination.totalRecords})}catch(N){console.error("Failed to fetch aging data:",N),h((N==null?void 0:N.message)||"Failed to load aging data")}finally{w?c(!1):m(!1)}w&&(y.current=!1)},[t,s,a,r]),j=x.useMemo(()=>i.filter(v=>{var N,C,S;if(!n)return!0;const w=n.toLowerCase();return((N=v.id)==null?void 0:N.toLowerCase().includes(w))||((C=v.title)==null?void 0:C.toLowerCase().includes(w))||((S=v.initiator)==null?void 0:S.toLowerCase().includes(w))}),[i,n]);return x.useEffect(()=>{s==="custom"&&(!a||!r)||b(1)},[t,s,a,r]),{agingWorkflows:j,loading:o,loadingPage:d,error:u,pagination:g,fetchData:b}}function Hk(t="7"){const[s,a]=x.useState(t),[r,n]=x.useState(null),i=x.useCallback(o=>{if(o===""){a(""),n(null);return}const c=parseInt(o,10);isNaN(c)||c<1?(n("Minimum threshold is 1 day"),a(o)):(n(null),a(o))},[]),l=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:l}}async function Wk(t,s,a){const r=await jt.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 l=await Ts(i.requestId||i.requestNumber),o=i.submissionDate?Xa(i.submissionDate):"N/A",c=i.closureDate?Xa(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),g=(l==null?void 0:l.approvals)||[];if(g.length===0){const p=[i.requestNumber||"",`"${(i.title||"").replace(/"/g,'""')}"`,i.priority||"medium",i.status||"",`"${(i.initiatorName||"Unknown").replace(/"/g,'""')}"`,o,c,u.toString(),h.toString(),d.toString(),m,(i.breachCount||0).toString(),"N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A"];n.push(p.join(","))}else g.forEach(p=>{const y=p.levelStartTime?Xa(p.levelStartTime):"N/A",b=p.levelEndTime||p.completedAt?Xa(p.levelEndTime||p.completedAt):"N/A",j=p.tatHours||0,v=p.tatDays||(j>0?(j/8).toFixed(2):"0");let w="N/A",N="N/A",C="N/A",S="N/A";if(p.levelStartTime){const P=new Date(p.levelStartTime);if(N=(((p.levelEndTime||p.completedAt?new Date(p.levelEndTime||p.completedAt):new Date).getTime()-P.getTime())/(1e3*60*60)).toFixed(2),j>0){const T=parseFloat(N);C=Math.max(0,j-T).toFixed(2),S=(T/j*100).toFixed(2),p.status==="APPROVED"||p.status==="REJECTED"?w=T<=j?"Compliant":"Breached":p.status==="IN_PROGRESS"||p.status==="PENDING"?w=T<=j?"On Track":"At Risk":w="N/A"}}const E=[i.requestNumber||"",`"${(i.title||"").replace(/"/g,'""')}"`,i.priority||"medium",i.status||"",`"${(i.initiatorName||"Unknown").replace(/"/g,'""')}"`,o,c,(i.totalLevels||0).toString(),(i.currentLevel||0).toString(),d.toString(),m,(i.breachCount||0).toString(),(p.levelNumber||"").toString(),`"${(p.levelName||`Level ${p.levelNumber}`).replace(/"/g,'""')}"`,`"${(p.approverName||"N/A").replace(/"/g,'""')}"`,`"${(p.approverEmail||"N/A").replace(/"/g,'""')}"`,p.status||"PENDING",y,b,j.toString(),v.toString(),w,N,C,S];n.push(E.join(","))})}catch(l){console.error(`Failed to fetch details for request ${i.requestNumber}:`,l);const o=i.submissionDate?Xa(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,'""')}"`,o,"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(","))}cc(n,`lifecycle-report-end-to-end-${new Date().toISOString().split("T")[0]}.csv`)}async function Gk(t,s,a,r,n){const i=await jt.getActivityLogReport(1,1e4,t,void 0,void 0,r&&r!=="all"?r:void 0,n&&n!=="all"?n:void 0,s,a),l=[["Timestamp","User","Action","Details","IP Address","User Agent","Request ID"].join(",")];i.activities.forEach(o=>{const c=$x(o.type||"",o.details),m=[o.timestamp?Xa(o.timestamp):"N/A",`"${(o.userName||"Unknown").replace(/"/g,'""')}"`,`"${c.replace(/"/g,'""')}"`,`"${(o.requestTitle||o.requestNumber||o.details||"N/A").replace(/"/g,'""')}"`,o.ipAddress||"N/A",`"${(o.userAgent||"").replace(/"/g,'""')}"`,o.requestNumber||o.requestId||"-"];l.push(m.join(","))}),cc(l,`activity-log-report-${new Date().toISOString().split("T")[0]}.csv`)}async function Kk(t,s,a,r){const n=await jt.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(l=>{const o=l.submissionDate?Xa(l.submissionDate):"N/A",c=[l.requestNumber||l.requestId||"",`"${(l.title||"").replace(/"/g,'""')}"`,`"${(l.initiatorName||"Unknown").replace(/"/g,'""')}"`,o,(l.daysOpen||0).toString(),`"${(l.currentStageName||`Level ${l.currentLevel}`).replace(/"/g,'""')}"`,`"${(l.currentApproverName||"N/A").replace(/"/g,'""')}"`,l.priority||"medium",l.status||"pending"];i.push(c.join(","))}),cc(i,`workflow-aging-report-${new Date().toISOString().split("T")[0]}.csv`)}function cc(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 Yk(){const[t,s]=x.useState(!1),[a,r]=x.useState(!1),[n,i]=x.useState(!1),l=x.useCallback(async(d,m,u)=>{try{s(!0),await Wk(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)}},[]),o=x.useCallback(async(d,m,u,h,g)=>{try{r(!0),await Gk(d,m,u,h,g)}catch(p){console.error("Failed to export activity data:",p),alert("Failed to export activity data. Please try again.")}finally{r(!1)}},[]),c=x.useCallback(async(d,m,u,h)=>{try{i(!0),await Kk(d,m,u,h)}catch(g){console.error("Failed to export aging data:",g),alert("Failed to export aging data. Please try again.")}finally{i(!1)}},[]);return{exportingLifecycle:t,exportingActivity:a,exportingAging:n,handleExportLifecycle:l,handleExportActivity:o,handleExportAging:c}}function Zk({onBack:t}){const s=_a(),[a,r]=x.useState(""),[n,i]=x.useState("all"),[l,o]=x.useState("all"),c=xl("month"),d=xl("month"),m=xl("month"),u=Hk("7"),h=$k({dateRange:c.dateRange,customStartDate:c.customStartDate,customEndDate:c.customEndDate}),g=Uk({dateRange:d.dateRange,customStartDate:d.customStartDate,customEndDate:d.customEndDate,filterCategory:n,filterSeverity:l}),p=zk({threshold:u.threshold,dateRange:m.dateRange,customStartDate:m.customStartDate,customEndDate:m.customEndDate,searchQuery:a}),y=Yk(),b=x.useCallback(()=>{t?t():s("/dashboard")},[t,s]),j=x.useCallback(S=>{const{navigateToRequest:E}=require("@/utils/requestNavigation");E({requestId:S,navigate:s})},[s]),v=x.useCallback(()=>{y.handleExportLifecycle(c.dateRange,c.customStartDate,c.customEndDate)},[y,c]),w=x.useCallback(()=>{y.handleExportActivity(d.dateRange,d.customStartDate,d.customEndDate,n,l)},[y,d,n,l]),N=x.useCallback(()=>{const S=parseInt(u.threshold,10);!isNaN(S)&&S>=1&&y.handleExportAging(S,m.dateRange,m.customStartDate,m.customEndDate)},[y,u.threshold,m]),C=x.useCallback(()=>{i("all"),o("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(Pk,{onBack:b}),e.jsx(Mk,{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:v,onViewRequest:j}),e.jsx(Fk,{activityLog:g.activityLog,loading:g.loading,loadingPage:g.loadingPage,error:g.error,pagination:g.pagination,dateRange:d.dateRange,customStartDate:d.customStartDate,customEndDate:d.customEndDate,showCustomDatePicker:d.showCustomDatePicker,tempCustomStartDate:d.tempCustomStartDate,tempCustomEndDate:d.tempCustomEndDate,filterCategory:n,filterSeverity:l,exporting:y.exportingActivity,onDateRangeChange:d.handleDateRangeChange,onShowCustomDatePickerChange:d.setShowCustomDatePicker,onStartDateChange:d.handleStartDateChange,onEndDateChange:d.handleEndDateChange,onApplyCustomDate:d.handleApplyCustomDate,onCancelCustomDate:d.handleCancelCustomDate,onCategoryChange:i,onSeverityChange:o,onClearFilters:C,onPageChange:g.fetchData,onExport:w,onViewRequest:j}),e.jsx(_k,{agingWorkflows:p.agingWorkflows,loading:p.loading,loadingPage:p.loadingPage,error:p.error,pagination:p.pagination,threshold:u.threshold,thresholdError:u.thresholdError,dateRange:m.dateRange,customStartDate:m.customStartDate,customEndDate:m.customEndDate,showCustomDatePicker:m.showCustomDatePicker,tempCustomStartDate:m.tempCustomStartDate,tempCustomEndDate:m.tempCustomEndDate,searchQuery:a,exporting:y.exportingAging,onThresholdChange:u.handleThresholdChange,onThresholdBlur:u.handleThresholdBlur,onDateRangeChange:m.handleDateRangeChange,onShowCustomDatePickerChange:m.setShowCustomDatePicker,onStartDateChange:m.handleStartDateChange,onEndDateChange:m.handleEndDateChange,onApplyCustomDate:m.handleApplyCustomDate,onCancelCustomDate:m.handleCancelCustomDate,onSearchChange:r,onPageChange:p.fetchData,onExport:N,onViewRequest:j})]})})}function Xk({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(re,{htmlFor:"default-period",children:"Default Reporting Period"}),e.jsxs(Ue,{value:t,onValueChange:a,children:[e.jsx(ze,{id:"default-period",children:e.jsx(Ve,{})}),e.jsx(He,{children:n.map(i=>e.jsx(Y,{value:i,children:i},i))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"refresh-interval",children:"Auto-Refresh Interval (minutes)"}),e.jsx(Re,{id:"refresh-interval",type:"number",min:"1",max:"60",value:s,onChange:i=>r(parseInt(i.target.value)||5)})]})]})}function Jk({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 Qk=["CSV","Excel","PDF","JSON"];function qk({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(re,{children:"Allowed Export Formats"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:Qk.map(r=>e.jsxs("div",{className:"flex items-center space-x-2 p-2 bg-muted/50 rounded",children:[e.jsx(Jo,{id:`export-${r}`,checked:t.includes(r),onCheckedChange:n=>a(r,n)}),e.jsx(re,{htmlFor:`export-${r}`,className:"text-sm cursor-pointer",children:r})]},r))})]})}function e5({dataRetention:t,onDataRetentionChange:s}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"data-retention",children:"Historical Data Retention (months)"}),e.jsx(Re,{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 t5(){const[t,s]=x.useState({defaultPeriod:"This Month",refreshInterval:5,autoRefresh:!0,realTimeUpdates:!0,dataExport:!0,exportFormats:["CSV","Excel","PDF"],dataRetention:24}),a=()=>{q.success("Analytics configuration saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(te,{children:[e.jsxs(me,{children:[e.jsx(he,{children:"Analytics & Reporting Configuration"}),e.jsx(De,{children:"Configure default reporting periods, auto-refresh, export settings, and data retention"})]}),e.jsxs(se,{className:"space-y-6",children:[e.jsx(Xk,{defaultPeriod:t.defaultPeriod,refreshInterval:t.refreshInterval,onDefaultPeriodChange:n=>r({defaultPeriod:n}),onRefreshIntervalChange:n=>r({refreshInterval:n})}),e.jsx(Vt,{}),e.jsx(Jk,{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(Vt,{}),e.jsx(qk,{exportFormats:t.exportFormats,onExportFormatsChange:n=>r({exportFormats:n})}),e.jsx(e5,{dataRetention:t.dataRetention,onDataRetentionChange:n=>r({dataRetention:n})}),e.jsxs(I,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(Fa,{className:"w-4 h-4 mr-2"}),"Save Analytics Configuration"]})]})]})}const s5=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"}},a5=t=>t.split(" ").map(s=>s[0]).join("").toUpperCase().substring(0,2);function r5({users:t,onEdit:s,onToggleStatus:a,onDelete:r}){return e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(ic,{children:[e.jsx(lc,{children:e.jsxs(rr,{children:[e.jsx(Jt,{children:"User"}),e.jsx(Jt,{children:"Role"}),e.jsx(Jt,{children:"Department"}),e.jsx(Jt,{children:"Status"}),e.jsx(Jt,{className:"text-right",children:"Actions"})]})}),e.jsx(oc,{children:t.length===0?e.jsx(rr,{children:e.jsx(Gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No users found"})}):t.map(n=>e.jsxs(rr,{className:"hover:bg-muted/50",children:[e.jsx(Gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Qt,{className:"size-10",children:e.jsx(qt,{className:"bg-re-green text-white",children:a5(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(Gt,{children:e.jsx(ie,{className:s5(n.role),children:n.role})}),e.jsx(Gt,{children:n.department}),e.jsx(Gt,{children:e.jsxs(ie,{className:"bg-green-100 text-green-800 border-green-200",children:[e.jsx(Fs,{className:"w-3 h-3 mr-1"}),n.status]})}),e.jsx(Gt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>s(n.id),className:"h-8",children:e.jsx(hi,{className:"w-4 h-4"})}),e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>a(n.id),disabled:n.role.toUpperCase()==="ADMIN",className:"h-8",children:e.jsx(Kf,{className:"w-4 h-4"})}),e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>r(n.id),disabled:n.role.toUpperCase()==="ADMIN",className:"h-8 text-destructive hover:text-destructive",children:e.jsx(io,{className:"w-4 h-4"})})]})})]},n.id))})]})})}function n5({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 i5(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function l5(){const[t,s]=x.useState(""),[a,r]=x.useState([]),[n,i]=x.useState(!1),[l,o]=x.useState(null),[c,d]=x.useState("USER"),[m,u]=x.useState(!1),[h,g]=x.useState(!1),[p,y]=x.useState(null),[b,j]=x.useState([]),[v,w]=x.useState(!1),[N,C]=x.useState({admins:0,management:0,users:0,total:0,active:0,inactive:0}),[S,E]=x.useState("ELEVATED"),[P,R]=x.useState(1),[f,T]=x.useState(1),[F,K]=x.useState(0),B=10,U=x.useRef(null),D=x.useCallback(i5(async V=>{var ee,oe,pe;if(!V||!V.startsWith("@")||V.length<2){r([]),i(!1);return}i(!0);try{const Pe=V.slice(1),ne=((ee=(await Ms.searchUsers(Pe,20)).data)==null?void 0:ee.data)||[];r(ne)}catch(Pe){console.error("Search failed:",Pe),y({type:"error",text:((pe=(oe=Pe.response)==null?void 0:oe.data)==null?void 0:pe.message)||"Failed to search users"})}finally{i(!1)}},300),[]),A=V=>{const ee=V.target.value;s(ee),D(ee)},k=async V=>{var ee,oe;try{const pe=b.find(de=>de.email.toLowerCase()===V.toLowerCase());if(pe)return pe.role;const ne=(((oe=(ee=(await Ms.getUsersByRole("ALL",1,1e3)).data)==null?void 0:ee.data)==null?void 0:oe.users)||[]).find(de=>{var le;return((le=de.email)==null?void 0:le.toLowerCase())===V.toLowerCase()});return ne&&ne.role?ne.role:null}catch(pe){return console.error("Failed to fetch user role:",pe),null}},M=async V=>{o(V),s(V.email),r([]),g(!0);try{const ee=await k(V.email);d(ee||"USER")}catch(ee){console.error("Failed to fetch user role:",ee),d("USER")}finally{g(!1)}},O=async()=>{var V,ee;if(!l||!c){y({type:"error",text:"Please select a user and role"});return}u(!0),y(null);try{await Ms.assignRole(l.email,c),y({type:"success",text:`Successfully assigned ${c} role to ${l.displayName||l.email}`}),o(null),s(""),d("USER"),await L(),await Z(),q.success("Role assigned successfully")}catch(oe){console.error("Role assignment failed:",oe);const pe=((ee=(V=oe.response)==null?void 0:V.data)==null?void 0:ee.error)||"Failed to assign role";y({type:"error",text:pe}),q.error(pe)}finally{u(!1)}},L=async(V=P)=>{var ee,oe,pe,Pe,Se,ne;w(!0);try{const de=await Ms.getUsersByRole(S,V,B),le=((oe=(ee=de.data)==null?void 0:ee.data)==null?void 0:oe.users)||[],fe=(Pe=(pe=de.data)==null?void 0:pe.data)==null?void 0:Pe.pagination,st=(ne=(Se=de.data)==null?void 0:Se.data)==null?void 0:ne.summary;j(le.map(ae=>({userId:ae.userId,email:ae.email,displayName:ae.displayName||ae.email,role:ae.role||"USER",department:ae.department,designation:ae.designation,isActive:ae.isActive!==!1}))),fe&&(R(fe.currentPage),T(fe.totalPages),K(fe.totalUsers)),st&&C(ae=>({...ae,admins:st.ADMIN||0,management:st.MANAGEMENT||0,users:st.USER||0,total:(st.ADMIN||0)+(st.MANAGEMENT||0)+(st.USER||0)}))}catch(de){console.error("Failed to fetch users:",de),q.error("Failed to load users")}finally{w(!1)}},Z=async()=>{var V,ee,oe,pe,Pe,Se;try{const ne=await Ms.getRoleStatistics(),de=((ee=(V=ne.data)==null?void 0:V.data)==null?void 0:ee.statistics)||((oe=ne.data)==null?void 0:oe.statistics)||[],le={admins:parseInt(((pe=de.find(fe=>fe.role==="ADMIN"))==null?void 0:pe.count)||"0"),management:parseInt(((Pe=de.find(fe=>fe.role==="MANAGEMENT"))==null?void 0:Pe.count)||"0"),users:parseInt(((Se=de.find(fe=>fe.role==="USER"))==null?void 0:Se.count)||"0")};C(fe=>({...fe,...le,total:le.admins+le.management+le.users,active:fe.active||le.admins+le.management+le.users,inactive:fe.inactive||0}))}catch(ne){console.error("Failed to fetch statistics:",ne)}};x.useEffect(()=>{L(1),Z()},[S]);const z=V=>{E(V),R(1)},$=V=>{L(V)},W=async(V,ee)=>{var oe,pe;try{await Ms.updateUserRole(V,ee),q.success("User role updated successfully"),await L(),await Z()}catch(Pe){console.error("Failed to update user role:",Pe),q.error(((pe=(oe=Pe.response)==null?void 0:oe.data)==null?void 0:pe.error)||"Failed to update user role")}},_=async V=>{b.find(oe=>oe.userId===V)&&q.info("User status toggle functionality coming soon")},G=async V=>{const ee=b.find(oe=>oe.userId===V);if(ee){if(ee.role==="ADMIN"){q.error("Cannot delete admin user");return}q.info("User deletion functionality coming soon")}};x.useEffect(()=>{const V=ee=>{U.current&&!U.current.contains(ee.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",V),()=>{document.removeEventListener("mousedown",V)}},[a]);const H={total:N.total,active:N.active,inactive:N.inactive,admins:N.admins};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(n5,{stats:H}),e.jsxs(te,{children:[e.jsx(me,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Assign User Role"}),e.jsx(De,{children:"Search for a user in Okta and assign them a role"})]}),e.jsx(I,{onClick:O,disabled:!l||m,className:"bg-re-green hover:bg-re-green/90",children:m?e.jsxs(e.Fragment,{children:[e.jsx(Qe,{className:"w-4 h-4 mr-2 animate-spin"}),"Assigning..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ls,{className:"w-4 h-4 mr-2"}),"Assign Role"]})})]})}),e.jsxs(se,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",ref:U,children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:"relative flex-1",children:[e.jsx($s,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(Re,{type:"text",placeholder:"Type @ to search users...",value:t,onChange:A,className:"pl-10 border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),n&&e.jsx(Qe,{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:()=>M(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))})]})]}),l&&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:(l.displayName||l.email).charAt(0).toUpperCase()}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-gray-900",children:l.displayName||l.email}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l.email}),l.department&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[l.department,l.designation?` • ${l.designation}`:""]}),h&&e.jsxs("p",{className:"text-xs text-re-green mt-1 flex items-center gap-1",children:[e.jsx(Qe,{className:"w-3 h-3 animate-spin"}),"Checking current role..."]})]})]}),e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{o(null),s(""),d("USER"),g(!1)},children:"Clear"})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Select Role"}),e.jsxs(Ue,{value:c,onValueChange:V=>d(V),disabled:h,children:[e.jsx(ze,{className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Ve,{placeholder:h?"Loading current role...":"Select role"})}),e.jsxs(He,{className:"rounded-lg",children:[e.jsx(Y,{value:"USER",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"w-4 h-4 text-gray-600"}),e.jsx("span",{children:"User - Regular access"})]})}),e.jsx(Y,{value:"MANAGEMENT",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mt,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Management - Read all data"})]})}),e.jsx(Y,{value:"ADMIN",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(or,{className:"w-4 h-4 text-yellow-600"}),e.jsx("span",{children:"Administrator - Full access"})]})})]})]})]}),p&&e.jsx("div",{className:`border-2 rounded-lg p-4 ${p.type==="success"?"border-green-200 bg-green-50":"border-red-200 bg-red-50"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[p.type==="success"?e.jsx(Ce,{className:"w-5 h-5 text-green-600 shrink-0 mt-0.5"}):e.jsx(We,{className:"w-5 h-5 text-red-600 shrink-0 mt-0.5"}),e.jsx("p",{className:`text-sm ${p.type==="success"?"text-green-800":"text-red-800"}`,children:p.text})]})})]})]}),e.jsxs(te,{children:[e.jsx(me,{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(he,{className:"flex items-center gap-2",children:[e.jsx(Mt,{className:"w-5 h-5 text-re-green"}),"User Management"]}),e.jsxs(De,{children:["View and manage user accounts and roles (",F," ",S!=="ALL"&&S!=="ELEVATED"?S.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(Ue,{value:S,onValueChange:z,children:[e.jsx(ze,{className:"w-[200px] border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Ve,{placeholder:"Filter by role"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"ELEVATED",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cs,{className:"w-4 h-4 text-purple-600"}),e.jsxs("span",{children:["Elevated (",N.admins+N.management,")"]})]})}),e.jsx(Y,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(or,{className:"w-4 h-4 text-yellow-600"}),e.jsxs("span",{children:["Admins (",N.admins,")"]})]})}),e.jsx(Y,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mt,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Management (",N.management,")"]})]})}),e.jsx(Y,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["Users (",N.users,")"]})]})}),e.jsx(Y,{value:"ALL",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mt,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["All Users (",N.admins+N.management+N.users,")"]})]})})]})]})})]})}),e.jsx(se,{className:"pt-6",children:v?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsx(Qe,{className:"w-6 h-6 animate-spin text-re-green mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading users..."})]}):b.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(Mt,{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:S==="ELEVATED"?"Assign ADMIN or MANAGEMENT roles to see users here":"No users match the selected filter"})]}):e.jsxs(e.Fragment,{children:[e.jsx(r5,{users:b.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 ee=b.find(oe=>oe.userId===V);if(ee){const oe=ee.role==="USER"?"MANAGEMENT":ee.role==="MANAGEMENT"?"ADMIN":"USER";W(V,oe)}},onToggleStatus:_,onDelete:G}),f>1&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t mt-4",children:[e.jsxs("div",{className:"text-sm text-gray-600",children:["Showing ",(P-1)*B+1," to ",Math.min(P*B,F)," of ",F," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(I,{variant:"outline",size:"sm",onClick:()=>$(P-1),disabled:P===1,children:"Previous"}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,f)},(V,ee)=>{let oe;return f<=5||P<=3?oe=ee+1:P>=f-2?oe=f-4+ee:oe=P-2+ee,e.jsx(I,{variant:P===oe?"default":"outline",size:"sm",onClick:()=>$(oe),className:`w-9 h-9 p-0 ${P===oe?"bg-re-green hover:bg-re-green/90":""}`,children:oe},oe)})}),e.jsx(I,{variant:"outline",size:"sm",onClick:()=>$(P+1),disabled:P===f,children:"Next"})]})]})]})})]})]})}function o5({expressHours:t,standardHours:s,onExpressChange:a,onStandardChange:r}){return e.jsxs(te,{className:"border-0 shadow-sm",children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(to,{className:"w-5 h-5 text-re-green"}),e.jsx(he,{className:"text-base font-semibold",children:"Priority TAT Settings"})]}),e.jsx(De,{className:"text-sm",children:"Set default turnaround time in hours for each priority level"})]}),e.jsx(se,{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(re,{htmlFor:"tat-express",className:"text-sm font-medium",children:"Express Priority (hours)"}),e.jsx(Re,{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(Ze,{className:"w-3 h-3"}),"Critical/Emergency requests (24/7, includes weekends)"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"tat-standard",className:"text-sm font-medium",children:"Standard Priority (hours)"}),e.jsx(Re,{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(Ze,{className:"w-3 h-3"}),"Regular priority requests (working hours only, excludes weekends & holidays)"]})]})]})})]})}function c5({reminderThreshold1:t,reminderThreshold2:s,onReminderThreshold1Change:a,onReminderThreshold2Change:r}){return e.jsxs(te,{className:"border-0 shadow-sm",children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vs,{className:"w-5 h-5 text-re-green"}),e.jsx(he,{className:"text-base font-semibold",children:"Auto-Reminder & Escalation"})]}),e.jsx(De,{className:"text-sm",children:"Configure automatic reminder thresholds based on TAT percentage"})]}),e.jsx(se,{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(re,{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(Gl,{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(vs,{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(re,{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(Gl,{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(hs,{className:"w-3 h-3"}),"Send escalation warning when ",s,"% of TAT elapsed"]})]})]})})]})}const Zr=[{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 d5({workStartHour:t,workEndHour:s,workStartDay:a,workEndDay:r,onWorkStartHourChange:n,onWorkEndHourChange:i,onWorkStartDayChange:l,onWorkEndDayChange:o}){var c,d,m;return e.jsxs(te,{className:"border-0 shadow-sm",children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mt,{className:"w-5 h-5 text-re-green"}),e.jsx(he,{className:"text-base font-semibold",children:"Working Hours Configuration"})]}),e.jsx(De,{className:"text-sm",children:"Define your organization's working hours and days for TAT calculations"})]}),e.jsxs(se,{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(re,{htmlFor:"work-start-hour",className:"text-sm font-medium",children:"Working Day Start Hour"}),e.jsx(Re,{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(Ze,{className:"w-3 h-3"}),"24-hour format (0-23). Default: 9 AM"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"work-end-hour",className:"text-sm font-medium",children:"Working Day End Hour"}),e.jsx(Re,{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(Ze,{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(re,{htmlFor:"work-start-day",className:"text-sm font-medium",children:"Working Week Start Day"}),e.jsxs(Ue,{value:a.toString(),onValueChange:u=>l(parseInt(u)),children:[e.jsx(ze,{id:"work-start-day",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Ve,{placeholder:"Select start day"})}),e.jsx(He,{children:Zr.map(u=>e.jsx(Y,{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(re,{htmlFor:"work-end-day",className:"text-sm font-medium",children:"Working Week End Day"}),e.jsxs(Ue,{value:r.toString(),onValueChange:u=>o(parseInt(u)),children:[e.jsx(ze,{id:"work-end-day",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Ve,{placeholder:"Select end day"})}),e.jsx(He,{children:Zr.map(u=>e.jsx(Y,{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=Zr.find(u=>u.value===a))==null?void 0:c.label} only`:` ${(d=Zr.find(u=>u.value===a))==null?void 0:d.label} to ${(m=Zr.find(u=>u.value===r))==null?void 0:m.label}`]})})]})]})}function m5(){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(()=>{l()},[]);const l=async()=>{try{s(!0);const d=await Ci("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),q.error("Failed to load TAT configurations")}finally{s(!1)}},o=async()=>{var d,m;try{r(!0),await Promise.all([bs("DEFAULT_TAT_EXPRESS_HOURS",n.expressHours.toString()),bs("DEFAULT_TAT_STANDARD_HOURS",n.standardHours.toString()),bs("TAT_REMINDER_THRESHOLD_1",n.reminderThreshold1.toString()),bs("TAT_REMINDER_THRESHOLD_2",n.reminderThreshold2.toString()),bs("WORK_START_HOUR",n.workStartHour.toString()),bs("WORK_END_HOUR",n.workEndHour.toString()),bs("WORK_START_DAY",n.workStartDay.toString()),bs("WORK_END_DAY",n.workEndDay.toString())]),q.success("TAT configuration saved successfully"),await l()}catch(u){console.error("Failed to save TAT configuration:",u),q.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(te,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(se,{className:"p-12 text-center",children:[e.jsx(Qe,{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(te,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(me,{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(Ze,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(he,{className:"text-lg font-semibold text-gray-900",children:"Turn Around Time (TAT) Configuration"}),e.jsx(De,{className:"text-sm text-gray-600",children:"Set default TAT hours per priority level, working hours, and configure auto-escalation thresholds"})]})]})}),e.jsxs(se,{className:"space-y-6",children:[e.jsx(o5,{expressHours:n.expressHours,standardHours:n.standardHours,onExpressChange:d=>c({expressHours:d}),onStandardChange:d=>c({standardHours:d})}),e.jsx(Vt,{}),e.jsx(d5,{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(Vt,{}),e.jsx(c5,{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(I,{onClick:o,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(Qe,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Fa,{className:"w-4 h-4 mr-2"}),"Save TAT Settings"]})})})]})]})}function u5({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 h5({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(re,{htmlFor:"notification-frequency",children:"Notification Frequency"}),e.jsxs(Ue,{value:t,onValueChange:a,children:[e.jsx(ze,{id:"notification-frequency",children:e.jsx(Ve,{placeholder:"Select frequency"})}),e.jsxs(He,{children:[e.jsx(Y,{value:"Immediate",children:"Immediate"}),e.jsx(Y,{value:"Hourly",children:"Hourly"}),e.jsx(Y,{value:"Daily",children:"Daily"}),e.jsx(Y,{value:"Weekly",children:"Weekly"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"reminder-frequency",children:"Reminder Frequency (hours)"}),e.jsx(Re,{id:"reminder-frequency",type:"number",min:"1",max:"168",value:s,onChange:n=>r(parseInt(n.target.value)||12)})]})]})}function p5({emailTemplate:t,onEmailTemplateChange:s}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"email-template",children:"Email Template Message"}),e.jsx(ps,{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 x5(){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=()=>{q.success("Notification configuration saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(te,{children:[e.jsxs(me,{children:[e.jsx(he,{children:"Notification Configuration"}),e.jsx(De,{children:"Configure notification channels, frequency, and message templates"})]}),e.jsxs(se,{className:"space-y-6",children:[e.jsx(u5,{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(Vt,{}),e.jsx(h5,{notificationFrequency:t.notificationFrequency,reminderFrequency:t.reminderFrequency,onNotificationFrequencyChange:n=>r({notificationFrequency:n}),onReminderFrequencyChange:n=>r({reminderFrequency:n})}),e.jsx(p5,{emailTemplate:t.emailTemplate,onEmailTemplateChange:n=>r({emailTemplate:n})}),e.jsxs(I,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(Fa,{className:"w-4 h-4 mr-2"}),"Save Notification Settings"]})]})]})}function g5({maxFileSizeMB:t,retentionDays:s,onMaxFileSizeChange:a,onRetentionDaysChange:r}){const n=Math.round(s/365*10)/10;return e.jsxs(te,{className:"border-0 shadow-sm",children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rs,{className:"w-5 h-5 text-re-green"}),e.jsx(he,{className:"text-base font-semibold",children:"Upload & Retention Settings"})]}),e.jsx(De,{className:"text-sm",children:"Configure file size limits and document retention period"})]}),e.jsx(se,{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(re,{htmlFor:"max-upload",className:"text-sm font-medium",children:"Maximum Upload Size (MB)"}),e.jsx(Re,{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(Rs,{className:"w-3 h-3"}),"Maximum allowed file size for document uploads"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"retention",className:"text-sm font-medium",children:"Retention Period (Days)"}),e.jsx(Re,{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(pi,{className:"w-3 h-3"}),"Days to retain documents after workflow closure (",n," years)"]})]})]})})]})}const f5=[{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 y5({allowedFileTypes:t,onAllowedFileTypesChange:s}){const a=t.split(",").map(l=>l.trim().toLowerCase()),r=(l,o)=>{const c=new Set(a);o?l.forEach(d=>c.add(d)):l.forEach(d=>c.delete(d)),s(Array.from(c).join(","))},n=l=>l.some(o=>a.includes(o)),i=l=>{s(l)};return e.jsxs(te,{className:"border-0 shadow-sm",children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ao,{className:"w-5 h-5 text-re-green"}),e.jsx(he,{className:"text-base font-semibold",children:"Allowed File Types"})]}),e.jsx(De,{className:"text-sm",children:"Select which file types are allowed for upload"})]}),e.jsxs(se,{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:f5.map(l=>{const o=n(l.extensions);return e.jsxs("div",{onClick:()=>r(l.extensions,!o),className:`flex items-center justify-between p-3 rounded-md border-2 cursor-pointer transition-all ${o?"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 ${o?"bg-re-green border-re-green":"bg-white border-gray-300"}`,children:o&&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 ${o?"text-re-green":"text-gray-600"}`,children:l.label})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:l.extensions.join(", ")})]},l.label)})}),e.jsxs("div",{className:"space-y-2 pt-2",children:[e.jsx(re,{htmlFor:"file-types-manual",className:"text-sm font-medium",children:"File Extensions (comma-separated)"}),e.jsx(Re,{id:"file-types-manual",type:"text",value:t,onChange:l=>i(l.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 b5(){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(()=>{l()},[]);const l=async()=>{try{s(!0);const d=await Ci("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),q.error("Failed to load document configurations")}finally{s(!1)}},o=async()=>{var d,m;try{r(!0),await Promise.all([bs("MAX_FILE_SIZE_MB",n.maxFileSizeMB.toString()),bs("DOCUMENT_RETENTION_DAYS",n.retentionDays.toString()),bs("ALLOWED_FILE_TYPES",n.allowedFileTypes)]),q.success("Document policy saved successfully"),await l()}catch(u){console.error("Failed to save document configuration:",u),q.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(te,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(se,{className:"p-12 text-center",children:[e.jsx(Qe,{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(te,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(me,{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(Le,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(he,{className:"text-lg font-semibold text-gray-900",children:"Document Upload Policy"}),e.jsx(De,{className:"text-sm text-gray-600",children:"Configure file upload limits, allowed types, and retention policies"})]})]})}),e.jsxs(se,{className:"space-y-6",children:[e.jsx(g5,{maxFileSizeMB:n.maxFileSizeMB,retentionDays:n.retentionDays,onMaxFileSizeChange:d=>c({maxFileSizeMB:d}),onRetentionDaysChange:d=>c({retentionDays:d})}),e.jsx(Vt,{}),e.jsx(y5,{allowedFileTypes:n.allowedFileTypes,onAllowedFileTypesChange:d=>c({allowedFileTypes:d})}),e.jsx("div",{className:"flex justify-end pt-4",children:e.jsx(I,{onClick:o,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(Qe,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Fa,{className:"w-4 h-4 mr-2"}),"Save Document Policy"]})})})]})]})}function v5(){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 j5=["Total Requests","Open Requests","Approved Requests","Rejected Requests","My Pending Actions","TAT Compliance","Delayed Workflows","Average Cycle Time"],N5=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 w5({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(ie,{className:N5(t),children:[t," Dashboard"]})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-2 ml-4",children:j5.map(r=>e.jsxs("div",{className:"flex items-center space-x-2 p-2 bg-muted/50 rounded",children:[e.jsx(Jo,{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 C5(){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=()=>{q.success("Dashboard layout saved successfully")},r=(i,l,o)=>{s(c=>({...c,[i]:{...c[i],[l]:o}}))},n=["Initiator","Approver","Spectator"];return e.jsxs(te,{children:[e.jsxs(me,{children:[e.jsx(he,{children:"Dashboard Layout Configuration"}),e.jsx(De,{children:"Control which KPI cards are visible for each user role"})]}),e.jsxs(se,{className:"space-y-4",children:[e.jsx(v5,{}),e.jsx("div",{className:"space-y-6",children:n.map(i=>e.jsx(w5,{role:i,kpis:t[i]||{},onKPIToggle:(l,o)=>r(i,l,o)},i))}),e.jsxs(I,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(Fa,{className:"w-4 h-4 mr-2"}),"Save Dashboard Layout"]})]})]})}function S5({aiEnabled:t,onAiEnabledChange:s}){return e.jsxs(te,{className:"border-0 shadow-sm",children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ru,{className:"w-5 h-5 text-re-green"}),e.jsx(he,{className:"text-base font-semibold",children:"Vertex AI Gemini Configuration"})]}),e.jsx(De,{className:"text-sm",children:"Configure AI features. Model and region are configured via environment variables."})]}),e.jsx(se,{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:s})]})})]})}function A5({aiRemarkGeneration:t,onRemarkGenerationChange:s}){return e.jsxs(te,{className:"border-0 shadow-sm",children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oi,{className:"w-5 h-5 text-re-green"}),e.jsx(he,{className:"text-base font-semibold",children:"AI Features"})]}),e.jsx(De,{className:"text-sm",children:"Enable/disable specific AI-powered features"})]}),e.jsx(se,{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 T5({maxRemarkChars:t,onMaxRemarkCharsChange:s}){return e.jsxs(te,{className:"border-0 shadow-sm",children:[e.jsxs(me,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Du,{className:"w-5 h-5 text-re-green"}),e.jsx(he,{className:"text-base font-semibold",children:"AI Parameters"})]}),e.jsx(De,{className:"text-sm",children:"Configure AI generation parameters"})]}),e.jsx(se,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"max-remark-chars",className:"text-sm font-medium",children:"Maximum Remark Length"}),e.jsx(Re,{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 k5(){const[t,s]=x.useState(!0),[a,r]=x.useState(!1),[n,i]=x.useState({aiEnabled:!0,aiRemarkGeneration:!0,maxRemarkChars:2e3});x.useEffect(()=>{l()},[]);const l=async()=>{try{s(!0);const d=await Ci("AI_CONFIGURATION"),m={};d.forEach(u=>{m[u.configKey]=u.configValue}),i({aiEnabled:m.AI_ENABLED==="true",aiRemarkGeneration:m.AI_REMARK_GENERATION_ENABLED==="true",maxRemarkChars:parseInt(m.AI_MAX_REMARK_LENGTH||"2000")})}catch(d){console.error("Failed to load AI configurations:",d),q.error("Failed to load AI configurations")}finally{s(!1)}},o=async()=>{var d,m;try{r(!0),await Promise.all([bs("AI_ENABLED",n.aiEnabled.toString()),bs("AI_REMARK_GENERATION_ENABLED",n.aiRemarkGeneration.toString()),bs("AI_MAX_REMARK_LENGTH",n.maxRemarkChars.toString())]),q.success("AI configuration saved successfully"),await l()}catch(u){console.error("Failed to save AI configuration:",u),q.error(((m=(d=u.response)==null?void 0:d.data)==null?void 0:m.error)||"Failed to save AI configuration")}finally{r(!1)}},c=d=>{i(m=>({...m,...d}))};return t?e.jsx(te,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(se,{className:"p-12 text-center",children:[e.jsx(Qe,{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(te,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(me,{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(oi,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(he,{className:"text-lg font-semibold text-gray-900",children:"AI Features Configuration"}),e.jsx(De,{className:"text-sm text-gray-600",children:"Configure Vertex AI Gemini settings and enable/disable AI-powered features"})]})]})}),e.jsxs(se,{className:"space-y-6",children:[e.jsx(S5,{aiEnabled:n.aiEnabled,onAiEnabledChange:d=>c({aiEnabled:d})}),e.jsx(Vt,{}),e.jsx(A5,{aiRemarkGeneration:n.aiRemarkGeneration,onRemarkGenerationChange:d=>c({aiRemarkGeneration:d})}),e.jsx(Vt,{}),e.jsx(T5,{maxRemarkChars:n.maxRemarkChars,onMaxRemarkCharsChange:d=>c({maxRemarkChars:d})}),e.jsx("div",{className:"flex justify-end pt-4",children:e.jsx(I,{onClick:o,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(Qe,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Fa,{className:"w-4 h-4 mr-2"}),"Save AI Configuration"]})})})]})]})}const Xm=["Admin Only","Initiator Only","Approver Only","Initiator & Approver","Admin & Initiator","Admin & Approver","All Roles"];function D5({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(re,{htmlFor:"spectator-permission",children:"Spectator Addition Permission"}),e.jsxs(Ue,{value:t,onValueChange:a,children:[e.jsx(ze,{id:"spectator-permission",children:e.jsx(Ve,{placeholder:"Select permission"})}),e.jsx(He,{children:Xm.map(n=>e.jsx(Y,{value:n,children:n},n))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"link-sharing-permission",children:"Link Sharing Permission"}),e.jsxs(Ue,{value:s,onValueChange:r,children:[e.jsx(ze,{id:"link-sharing-permission",children:e.jsx(Ve,{placeholder:"Select permission"})}),e.jsx(He,{children:Xm.map(n=>e.jsx(Y,{value:n,children:n},n))})]})]})]})}function R5({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 P5(){const[t,s]=x.useState({spectatorPermission:"Initiator & Approver",linkSharingPermission:"Admin & Initiator",requirePassword:!0,allowExternalSharing:!1}),a=()=>{q.success("Sharing policy saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(te,{children:[e.jsxs(me,{children:[e.jsx(he,{children:"Workflow Sharing Policy"}),e.jsx(De,{children:"Control who can add spectators and share workflow links"})]}),e.jsxs(se,{className:"space-y-6",children:[e.jsx(D5,{spectatorPermission:t.spectatorPermission,linkSharingPermission:t.linkSharingPermission,onSpectatorPermissionChange:n=>r({spectatorPermission:n}),onLinkSharingPermissionChange:n=>r({linkSharingPermission:n})}),e.jsx(Vt,{}),e.jsx(R5,{requirePassword:t.requirePassword,allowExternalSharing:t.allowExternalSharing,onRequirePasswordChange:n=>r({requirePassword:n}),onAllowExternalSharingChange:n=>r({allowExternalSharing:n})}),e.jsxs(I,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(Fa,{className:"w-4 h-4 mr-2"}),"Save Sharing Policy"]})]})]})}function I5(){const{user:t}=Kt(),[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"}]}],l=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),o=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(cs,{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(ie,{className:"bg-re-green/10 text-re-green border-re-green/20 px-4 py-2",children:[e.jsx(cs,{className:"w-4 h-4 mr-2"}),"Administrator: ",(t==null?void 0:t.displayName)||"Admin User"]})]}),e.jsx(Vt,{}),e.jsxs(wn,{value:r,onValueChange:n,className:"flex flex-col gap-2 space-y-4",children:[e.jsxs(Cn,{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(Ct,{value:"kpi",className:"flex items-center gap-2",children:[e.jsx(ku,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"KPI Config"})]}),e.jsxs(Ct,{value:"analytics",className:"flex items-center gap-2",children:[e.jsx(da,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Analytics"})]}),e.jsxs(Ct,{value:"users",className:"flex items-center gap-2",children:[e.jsx(Mt,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Users"})]}),e.jsxs(Ct,{value:"tat",className:"flex items-center gap-2",children:[e.jsx(Ze,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"TAT"})]}),e.jsxs(Ct,{value:"notifications",className:"flex items-center gap-2",children:[e.jsx(vs,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Notify"})]}),e.jsxs(Ct,{value:"documents",className:"flex items-center gap-2",children:[e.jsx(Le,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Docs"})]}),e.jsxs(Ct,{value:"dashboard",className:"flex items-center gap-2",children:[e.jsx(Yf,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Dashboard"})]}),e.jsxs(Ct,{value:"ai",className:"flex items-center gap-2",children:[e.jsx(Ru,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"AI"})]}),e.jsxs(Ct,{value:"sharing",className:"flex items-center gap-2",children:[e.jsx(vr,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Sharing"})]})]}),e.jsx(St,{value:"kpi",className:"flex-1 outline-none space-y-4",children:e.jsxs(te,{children:[e.jsx(me,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(he,{children:"KPI Configuration"}),e.jsx(De,{children:"Configure which KPIs are enabled, visible to specific roles, and set alert thresholds"})]}),e.jsxs(ie,{className:"bg-blue-50 text-blue-700",children:[o," / ",o," KPIs Active"]})]})}),e.jsxs(se,{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($s,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(Re,{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))}),l.map(d=>e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ts,{className:"w-5 h-5 text-re-green"}),e.jsx("h3",{className:"font-semibold",children:d.name}),e.jsxs(ie,{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(ie,{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(Zf,{className:"w-3 h-3"}):e.jsx(Xf,{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(ie,{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(We,{className:"w-3 h-3"}),e.jsx("span",{className:"font-medium",children:"Threshold Breached!"})]})]})]})]})})},m.id))})]},d.name))]})]})}),e.jsx(St,{value:"analytics",className:"flex-1 outline-none space-y-4",children:e.jsx(t5,{})}),e.jsx(St,{value:"users",className:"flex-1 outline-none space-y-4",children:e.jsx(l5,{})}),e.jsx(St,{value:"tat",className:"flex-1 outline-none space-y-4",children:e.jsx(m5,{})}),e.jsx(St,{value:"notifications",className:"flex-1 outline-none space-y-4",children:e.jsx(x5,{})}),e.jsx(St,{value:"documents",className:"flex-1 outline-none space-y-4",children:e.jsx(b5,{})}),e.jsx(St,{value:"dashboard",className:"flex-1 outline-none space-y-4",children:e.jsx(C5,{})}),e.jsx(St,{value:"ai",className:"flex-1 outline-none space-y-4",children:e.jsx(k5,{})}),e.jsx(St,{value:"sharing",className:"flex-1 outline-none space-y-4",children:e.jsx(P5,{})})]})]})}function E5({isOpen:t,onClose:s,action:a,requestId:r,requestTitle:n,onSubmit:i}){const[l,o]=x.useState(""),[c,d]=x.useState(!1),m=async()=>{if(!(!l.trim()||l.length>500)){d(!0);try{await i(a,l.trim()),o(""),s()}catch(y){console.error("Error submitting approval action:",y)}finally{d(!1)}}},u=()=>{o(""),s()},g=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:xt,iconColor:"text-red-600",buttonColor:"bg-red-600 hover:bg-red-700",badgeColor:"bg-red-100 text-red-800 border-red-200",placeholder:"Enter detailed reasons for rejection and any suggestions for improvement..."},p=g.icon;return e.jsx(ot,{open:t,onOpenChange:u,children:e.jsxs(nt,{className:"max-w-2xl bg-white",children:[e.jsxs(ct,{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:`p-2 rounded-lg ${a==="approve"?"bg-green-100":"bg-red-100"}`,children:e.jsx(p,{className:`w-6 h-6 ${g.iconColor}`})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(it,{className:"text-xl",children:g.title}),e.jsx(_t,{className:"mt-1",children:g.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(ie,{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(ie,{className:g.badgeColor,variant:"outline",children:[e.jsx(p,{className:"w-3 h-3 mr-1"}),a==="approve"?"APPROVE":"REJECT"]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"comment",className:"text-sm font-semibold text-gray-900",children:"Comments & Remarks *"}),e.jsx(ps,{id:"comment",placeholder:g.placeholder,value:l,onChange:y=>o(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(hs,{className:"w-3 h-3"}),"Comments are required and will be visible to all participants"]}),e.jsxs("span",{children:[l.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(hs,{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(At,{className:"gap-2",children:[e.jsx(I,{variant:"outline",onClick:u,disabled:c,children:"Cancel"}),e.jsx(I,{onClick:m,disabled:!l.trim()||c||l.length>500,className:g.buttonColor,children:c?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin mr-2"}),"Processing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(p,{className:"w-4 h-4 mr-2"}),a==="approve"?"Approve Request":"Reject Request"]})})]})]})})}var M5=(t,s,a,r,n,i,l,o)=>{let c=document.documentElement,d=["light","dark"];function m(g){(Array.isArray(t)?t:[t]).forEach(p=>{let y=p==="class",b=y&&i?n.map(j=>i[j]||j):n;y?(c.classList.remove(...b),c.classList.add(i&&i[g]?i[g]:g)):c.setAttribute(p,g)}),u(g)}function u(g){o&&d.includes(g)&&(c.style.colorScheme=g)}function h(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}if(r)m(r);else try{let g=localStorage.getItem(s)||a,p=l&&g==="system"?h():g;m(p)}catch{}},F5=x.createContext(void 0),_5={setTheme:t=>{},themes:[]},L5=()=>{var t;return(t=x.useContext(F5))!=null?t:_5};x.memo(({forcedTheme:t,storageKey:s,attribute:a,enableSystem:r,enableColorScheme:n,defaultTheme:i,value:l,themes:o,nonce:c,scriptProps:d})=>{let m=JSON.stringify([a,s,i,t,o,l,r,n]).slice(1,-1);return x.createElement("script",{...d,suppressHydrationWarning:!0,nonce:typeof window>"u"?c:"",dangerouslySetInnerHTML:{__html:`(${M5.toString()})(${m})`}})});const O5=({...t})=>{const{theme:s="system"}=L5();return e.jsx(Jf,{theme:s,className:"toaster group",style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)"},...t})};function $5({open:t,onClose:s,onSelect:a,managers:r=[],errorType:n,message:i,isLoading:l=!1}){const o=c=>{a(c)};return e.jsx(ot,{open:t,onOpenChange:s,children:e.jsxs(nt,{className:"sm:max-w-[600px]",children:[e.jsxs(ct,{children:[e.jsx(it,{className:"flex items-center gap-2",children:n==="NO_MANAGER_FOUND"?e.jsxs(e.Fragment,{children:[e.jsx(We,{className:"w-5 h-5 text-amber-500"}),"Manager Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Fs,{className:"w-5 h-5 text-blue-500"}),"Select Your Manager"]})}),e.jsx(_t,{children:n==="NO_MANAGER_FOUND"?e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"text-sm text-gray-600",children:i||"No reporting manager found in the system. Please ensure your manager is correctly configured in your profile."}),e.jsx("p",{className:"text-sm text-gray-500 mt-2",children:"Please contact your administrator to update your manager information, or try again later."})]}):e.jsx("div",{className:"mt-2",children:e.jsx("p",{className:"text-sm text-gray-600",children:i||"Multiple managers were found with the same name. Please select the correct manager from the list below."})})})]}),e.jsx("div",{className:"mt-4",children:n==="NO_MANAGER_FOUND"?e.jsx("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(We,{className:"w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium text-amber-900",children:"Unable to Proceed"}),e.jsx("p",{className:"text-sm text-amber-700 mt-1",children:"We couldn't find your reporting manager in the system. The claim request cannot be created without a valid manager assigned."})]})]})}):e.jsx("div",{className:"space-y-3 max-h-[400px] overflow-y-auto",children:r.map(c=>e.jsx("div",{className:"border rounded-lg p-4 hover:bg-gray-50 transition-colors cursor-pointer",onClick:()=>!l&&o(c.email),children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-3 flex-1",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center flex-shrink-0",children:e.jsx(Pt,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"flex items-center gap-2 mb-1",children:e.jsx("p",{className:"font-medium text-gray-900",children:c.displayName||`${c.firstName||""} ${c.lastName||""}`.trim()||"Unknown"})}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:[e.jsx(va,{className:"w-4 h-4"}),e.jsx("span",{className:"truncate",children:c.email})]}),c.department&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500",children:[e.jsx(eo,{className:"w-4 h-4"}),e.jsx("span",{children:c.department})]})]})]})]}),e.jsx(I,{onClick:d=>{d.stopPropagation(),o(c.email)},disabled:l,className:"flex-shrink-0",size:"sm",children:"Select"})]})},c.userId))})}),e.jsx("div",{className:"flex justify-end gap-3 mt-6",children:n==="NO_MANAGER_FOUND"?e.jsx(I,{onClick:s,variant:"outline",children:"Close"}):e.jsx(e.Fragment,{children:e.jsx(I,{onClick:s,variant:"outline",disabled:l,children:"Cancel"})})})]})})}function B5({onViewRequest:t}){const{user:s}=Kt();return xi(s)?e.jsx(QT,{onViewRequest:t}):e.jsx(tk,{onViewRequest:t})}function U5({onLogout:t}){const s=_a(),[a,r]=x.useState(null),[n,i]=x.useState([]),[l,o]=x.useState(""),[c,d]=x.useState(""),[m,u]=x.useState(!1),[h,g]=x.useState(null);x.useEffect(()=>{const S=localStorage.getItem("dynamicRequests");if(S)try{const E=JSON.parse(S);i(E)}catch(E){console.error("Error parsing dynamic requests:",E)}},[]),x.useEffect(()=>{n.length>0&&localStorage.setItem("dynamicRequests",JSON.stringify(n))},[n]);const p=S=>{if(S==="profile"){s("/profile");return}if(S==="settings"){s("/settings");return}S.startsWith("/")?s(S):s(`/${S}`)},y=async(S,E,P,R)=>{o(S),d(E||"Unknown Request");const{navigateToRequest:f}=await Bn(async()=>{const{navigateToRequest:T}=await import("./requestNavigation-DVuzZmST.js");return{navigateToRequest:T}},__vite__mapDeps([8,1,2,3,4,5,6,7]));f({requestId:S,requestTitle:E,status:P,request:R,navigate:s})},b=()=>{s(-1)},j=()=>{s("/new-request")},v=S=>{var R,f,T,F,K,B,U,D,A,k,M;if(S.templateType){S.templateType==="claim-management"&&s("/claim-management");return}const E=`RE-REQ-2024-${String(Object.keys(lh).length+n.length+1).padStart(3,"0")}`,P={id:E,title:S.title,description:S.description||"",category:S.category||"General",subcategory:S.subcategory||"",status:"pending",priority:S.priority||"standard",amount:S.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:((R=S.approvers)==null?void 0:R.length)||1,currentApprover:((T=(f=S.approvers)==null?void 0:f[0])==null?void 0:T.name)||((B=(K=(F=S.approvers)==null?void 0:F[0])==null?void 0:K.email)==null?void 0:B.split("@")[0])||"Pending Assignment",approverLevel:`1 of ${((U=S.approvers)==null?void 0:U.length)||1}`,template:"custom",initiator:{name:"Current User",role:S.initiatorRole||"Employee",department:S.department||"General",email:"current.user@royalenfield.com",phone:"+91 98765 43290",avatar:"CU"},department:S.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:(S.approvers||[]).filter(O=>O).map((O,L)=>{var $;const Z=(O==null?void 0:O.name)||(($=O==null?void 0:O.email)==null?void 0:$.split("@")[0])||`Approver ${L+1}`,z=(O==null?void 0:O.email)||"";return{step:L+1,approver:`${Z}${z?` (${z})`:""}`,role:(O==null?void 0:O.role)||`Level ${(O==null?void 0:O.level)||L+1} Approver`,status:L===0?"pending":"waiting",tatHours:O!=null&&O.tat?typeof O.tat=="string"?parseInt(O.tat):O.tat:48,elapsedHours:0,assignedAt:L===0?new Date().toISOString():null,comment:null,timestamp:null}}),documents:[],spectators:(S.spectators||[]).filter(O=>O&&(O.name||O.email)).map(O=>{var Z;const L=(O==null?void 0:O.name)||((Z=O==null?void 0:O.email)==null?void 0:Z.split("@")[0])||"Observer";return{name:L,role:(O==null?void 0:O.role)||(O==null?void 0:O.department)||"Observer",avatar:L.split(" ").map(z=>z[0]).join("").toUpperCase().slice(0,2)||"OB"}}),auditTrail:[{type:"created",action:"Request Created",details:`Custom request "${S.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 ${((A=(D=S.approvers)==null?void 0:D[0])==null?void 0:A.name)||((M=(k=S.approvers)==null?void 0:k[0])==null?void 0:M.email)||"first approver"}`,user:"System",timestamp:new Date().toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0})}],tags:S.tags||["custom-request"]};i([...n,P]),s("/my-requests"),q.success("Request Submitted Successfully!",{description:`Your request "${S.title}" (${E}) has been created and sent for approval.`,duration:5e3})},w=(S,E)=>new Promise(P=>{setTimeout(()=>{S==="approve"?q.success("Request Approved",{description:"The request has been approved and forwarded to the next step.",duration:5e3}):q.error("Request Rejected",{description:"The request has been rejected and returned to the initiator.",duration:5e3}),r(null),P(!0)},1e3)}),N=()=>{r(null)},C=async(S,E)=>{var P,R,f,T,F,K,B;try{const U={activityName:S.activityName,activityType:S.activityType,dealerCode:S.dealerCode,dealerName:S.dealerName,dealerEmail:S.dealerEmail||void 0,dealerPhone:S.dealerPhone||void 0,dealerAddress:S.dealerAddress||void 0,activityDate:S.activityDate?new Date(S.activityDate).toISOString():void 0,location:S.location,requestDescription:S.requestDescription,periodStartDate:S.periodStartDate?new Date(S.periodStartDate).toISOString():void 0,periodEndDate:S.periodEndDate?new Date(S.periodEndDate).toISOString():void 0,estimatedBudget:S.estimatedBudget||void 0,approvers:S.approvers||[]},D=await J2(U);if(!D||!D.request)throw new Error("Invalid response from server: Request object not found");const A=D.request;if(!A.requestNumber&&!A.requestId)throw new Error("Invalid response from server: Request identifier not found");u(!1),g(null),q.success("Claim Request Submitted",{description:"Your claim management request has been created successfully."}),A.requestNumber?s(`/request/${A.requestNumber}`):A.requestId?s(`/request/${A.requestId}`):s("/my-requests")}catch(U){console.error("[App] Error creating claim request:",U);const D=(P=U==null?void 0:U.response)==null?void 0:P.data,A=(D==null?void 0:D.code)||((R=D==null?void 0:D.error)==null?void 0:R.code);if(A==="NO_MANAGER_FOUND"){g({errorType:"NO_MANAGER_FOUND",message:(D==null?void 0:D.message)||((f=D==null?void 0:D.error)==null?void 0:f.message)||"No reporting manager found. Please ensure your manager is correctly configured in the system.",pendingClaimData:S}),u(!0);return}if(A==="MULTIPLE_MANAGERS_FOUND"){const M=(D==null?void 0:D.managers)||((T=D==null?void 0:D.error)==null?void 0:T.managers)||[];g({errorType:"MULTIPLE_MANAGERS_FOUND",managers:M,message:(D==null?void 0:D.message)||((F=D==null?void 0:D.error)==null?void 0:F.message)||"Multiple managers found. Please select one.",pendingClaimData:S}),u(!0);return}const k=((B=(K=U==null?void 0:U.response)==null?void 0:K.data)==null?void 0:B.message)||(U==null?void 0:U.message)||"Failed to create claim request";q.error("Failed to Submit Claim Request",{description:k})}};return e.jsxs("div",{className:"min-h-screen h-screen flex flex-col overflow-hidden bg-background",children:[e.jsxs(t0,{children:[e.jsx(Zt,{path:"/login/callback",element:e.jsx(Wu,{})}),e.jsx(Zt,{path:"/",element:e.jsx(fs,{currentPage:"dashboard",onNavigate:p,onNewRequest:j,onLogout:t,children:e.jsx(gd,{onNavigate:p,onNewRequest:j})})}),e.jsx(Zt,{path:"/dashboard",element:e.jsx(fs,{currentPage:"dashboard",onNavigate:p,onNewRequest:j,onLogout:t,children:e.jsx(gd,{onNavigate:p,onNewRequest:j})})}),e.jsx(Zt,{path:"/open-requests",element:e.jsx(fs,{currentPage:"open-requests",onNavigate:p,onNewRequest:j,onLogout:t,children:e.jsx(rv,{onViewRequest:y})})}),e.jsx(Zt,{path:"/closed-requests",element:e.jsx(fs,{currentPage:"closed-requests",onNavigate:p,onNewRequest:j,onLogout:t,children:e.jsx(Tv,{onViewRequest:y})})}),e.jsx(Zt,{path:"/shared-summaries",element:e.jsx(fs,{currentPage:"shared-summaries",onNavigate:p,onNewRequest:j,onLogout:t,children:e.jsx(lT,{})})}),e.jsx(Zt,{path:"/shared-summaries/:sharedSummaryId",element:e.jsx(fs,{currentPage:"shared-summaries",onNavigate:p,onNewRequest:j,onLogout:t,children:e.jsx(oT,{})})}),e.jsx(Zt,{path:"/my-requests",element:e.jsx(fs,{currentPage:"my-requests",onNavigate:p,onNewRequest:j,onLogout:t,children:e.jsx(TT,{onViewRequest:y,dynamicRequests:n})})}),e.jsx(Zt,{path:"/requests",element:e.jsx(fs,{currentPage:"requests",onNavigate:p,onNewRequest:j,onLogout:t,children:e.jsx(B5,{onViewRequest:y})})}),e.jsx(Zt,{path:"/approver-performance",element:e.jsx(fs,{currentPage:"approver-performance",onNavigate:p,onNewRequest:j,onLogout:t,children:e.jsx(xk,{})})}),e.jsx(Zt,{path:"/request/:requestId",element:e.jsx(fs,{currentPage:"request-detail",onNavigate:p,onNewRequest:j,onLogout:t,children:e.jsx(iT,{requestId:"",onBack:b,dynamicRequests:n})})}),e.jsx(Zt,{path:"/work-notes/:requestId",element:e.jsx(cT,{})}),e.jsx(Zt,{path:"/new-request",element:e.jsx(Bm,{onBack:b,onSubmit:v})}),e.jsx(Zt,{path:"/edit-request/:requestId",element:e.jsx(Bm,{onBack:b,onSubmit:v,requestId:void 0,isEditMode:!0})}),e.jsx(Zt,{path:"/claim-management",element:e.jsx(GA,{onBack:b,onSubmit:C})}),e.jsx(Zt,{path:"/profile",element:e.jsx(fs,{currentPage:"profile",onNavigate:p,onNewRequest:j,onLogout:t,children:e.jsx(gk,{})})}),e.jsx(Zt,{path:"/settings",element:e.jsx(fs,{currentPage:"settings",onNavigate:p,onNewRequest:j,onLogout:t,children:e.jsx(Dk,{})})}),e.jsx(Zt,{path:"/notifications",element:e.jsx(fs,{currentPage:"notifications",onNavigate:p,onNewRequest:j,onLogout:t,children:e.jsx(Rk,{onNavigate:p})})}),e.jsx(Zt,{path:"/detailed-reports",element:e.jsx(fs,{currentPage:"detailed-reports",onNavigate:p,onNewRequest:j,onLogout:t,children:e.jsx(Zk,{})})}),e.jsx(Zt,{path:"/admin",element:e.jsx(fs,{currentPage:"admin",onNavigate:p,onNewRequest:j,onLogout:t,children:e.jsx(I5,{})})})]}),e.jsx(O5,{position:"top-right",toastOptions:{style:{background:"var(--card)",color:"var(--card-foreground)",border:"1px solid var(--border)"}}}),e.jsx($5,{open:m,onClose:()=>{u(!1),g(null)},onSelect:async S=>{h!=null&&h.pendingClaimData&&await C(h.pendingClaimData)},managers:h==null?void 0:h.managers,errorType:(h==null?void 0:h.errorType)||"NO_MANAGER_FOUND",message:h==null?void 0:h.message,isLoading:!1}),a&&e.jsx(E5,{isOpen:!!a,onClose:N,action:a,requestId:l,requestTitle:c,onSubmit:w})]})}function V5(t){const{onLogout:s}=t||{};return e.jsx(e0,{children:e.jsx(U5,{onLogout:s})})}function z5(){const{isAuthenticated:t,isLoading:s,error:a,user:r,logout:n}=Kt(),[i,l]=x.useState(!1),o=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)}}};if(x.useEffect(()=>{},[t,s,a,r]),o){const d=typeof window<"u"?new URLSearchParams(window.location.search):null,m=d==null?void 0:d.get("code"),u=d==null?void 0:d.get("error");if(!m&&!u){console.log("🚪 AuthenticatedApp: Logout redirect detected, redirecting to home");const g=new URLSearchParams;return g.set("tanflow_logged_out","true"),g.set("logout",Date.now().toString()),window.location.replace(`/?${g.toString()}`),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:"Redirecting..."})]})})}return(typeof window<"u"?sessionStorage.getItem("auth_provider"):null)==="tanflow"?e.jsx(Ny,{}):e.jsx(Wu,{})}return 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(V5,{onLogout:c}),i&&e.jsx(Cy,{isOpen:i,onClose:()=>l(!1)})]}):e.jsx(jy,{})}const Kn=()=>{try{return!0}catch{return!1}},H5=()=>{if(Kn())return null;try{return localStorage.getItem("token")}catch{return null}},W5={user:null,token:H5(),isAuthenticated:!1,isLoading:!1,error:null},Bx=wr({name:"auth",initialState:W5,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,!Kn())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,!Kn())try{localStorage.removeItem("token")}catch{}},logout:t=>{if(t.isAuthenticated=!1,t.user=null,t.token=null,t.error=null,!Kn())try{localStorage.removeItem("token")}catch{}},clearError:t=>{t.error=null},updateUser:(t,s)=>{t.user=s.payload}}}),{loginStart:n4,loginSuccess:i4,loginFailure:l4,logout:o4,clearError:c4,updateUser:d4}=Bx.actions,G5=qf({reducer:{auth:Bx.reducer,dashboard:Xu.reducer,requests:kx.reducer,myRequests:Cx.reducer,openRequests:Qu.reducer,closedRequests:ih.reducer},middleware:t=>t({serializableCheck:{ignoredActions:["persist/PERSIST"]}}),devTools:!1});bl.createRoot(document.getElementById("root")).render(e.jsx(Xg.StrictMode,{children:e.jsx(j0,{store:G5,children:e.jsx(V0,{children:e.jsx(z5,{})})})}));export{ye as a,t4 as g};
|
||
//# sourceMappingURL=index-B9vDSbbE.js.map
|