Re_Backend/build/assets/index-BCZm9H2Q.js

65 lines
1.3 MiB
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/conclusionApi-Nd172SfW.js","assets/radix-vendor-CYvDqP9X.js","assets/charts-vendor-BVfwAPj-.js","assets/utils-vendor-BTBPSQfW.js","assets/ui-vendor-CX5oLBI_.js","assets/socket-vendor-TjCxX7sJ.js","assets/redux-vendor-tbZCm13o.js","assets/router-vendor-B_rK4TXr.js"])))=>i.map(i=>d[i]);
var t0=Object.defineProperty;var s0=(t,s,a)=>s in t?t0(t,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[s]=a;var Vi=(t,s,a)=>s0(t,typeof s!="symbol"?s+"":s,a);import{j as e,S as ax,R as rx,I as nx,F as ix,a as a0,T as r0,P as n0,C as i0,b as l0,O as lx,c as ox,d as o0,e as c0,f as d0,D as m0,g as u0,A as x0,h as h0,i as p0,k as g0,l as f0,m as b0,n as y0,V as v0,o as j0,p as N0,q as w0,r as C0,s as S0,t as A0,u as T0,v as k0,w as R0,x as D0,y as P0,z as I0,B as E0,E as F0,G as _0,H as L0,J as M0,K as $0,L as O0,M as U0,N as B0,Q as cx,U as dx,W as V0,X as mx,Y as ux,Z as z0,_ as H0,$ as G0,a0 as W0,a1 as Y0,a2 as K0,a3 as X0,a4 as Z0,a5 as J0,a6 as Q0,a7 as q0,a8 as ef,a9 as tf,aa as sf,ab as af}from"./radix-vendor-CYvDqP9X.js";import{a as rf,r as p,c as xx,d as Fr,B as Dl,C as si,X as ai,Y as ri,T as _r,L as ni,e as ya,P as hx,f as px,g as gx,h as nf,i as tm,j as bi,k as yi,b as lf}from"./charts-vendor-BVfwAPj-.js";import{a as lo,f as fx,s as Ys,e as oo,b as sm,c as of,d as wa,g as fn,i as co,h as bx,j as Os,k as Hs,l as zi,m as ka,n as cf,o as Pl,p as df,q as Ge,r as Il,t as mf,u as uf,v as xf,w as hf,x as Hi,y as am,z as pf,A as yx,B as vx,C as mo,D as uo,E as gf,F as ff,G as jx,H as Sr,I as Gi,J as bf,K as yf,L as vf}from"./utils-vendor-BTBPSQfW.js";import{L as jf,S as Ns,C as Ye,a as Ws,b as it,X as ft,H as Nf,c as Nx,U as Gt,F as ke,d as Re,e as Sn,P as gs,f as wf,g as Cf,B as aa,h as Ya,i as Wi,j as xo,k as ho,l as Ra,m as wx,n as vi,o as Cx,p as xt,q as Qa,R as Ut,I as Hr,T as Bt,r as nt,s as fa,t as Sf,A as ls,u as os,M as Ds,v as ji,w as It,x as El,D as At,Z as po,y as ps,z as Af,E as Tf,G as kf,J as Rf,K as Df,N as Pf,O as If,Q as Ef,V as Ff,W as Sx,Y as _f,_ as Lf,$ as Da,a0 as Ni,a1 as Ka,a2 as ii,a3 as rm,a4 as Mn,a5 as li,a6 as Ax,a7 as Ct,a8 as Mf,a9 as K,aa as na,ab as Cs,ac as Tx,ad as Yt,ae as kx,af as bt,ag as $f,ah as Of,ai as Rx,aj as wi,ak as Dx,al as Uf,am as Bf,an as go,ao as Ks,ap as Pa,aq as Ci,ar as Si,as as Es,at as Vf,au as zf,av as Px,aw as Ix,ax as Yn,ay as Ha,az as fo,aA as Ai,aB as oi,aC as Ex,aD as Fx,aE as _x,aF as Ti,aG as ki,aH as Hf,aI as Wa,aJ as Lx,aK as Fl,aL as Gf,aM as Wf,aN as Yf,aO as bo,aP as yo,aQ as vo,aR as Kf,aS as nm,aT as Mx,aU as Xf,aV as Ri,aW as Zf,aX as $n,aY as Jf,aZ as im,a_ as $x,a$ as Qf,b0 as qf,b1 as eb,b2 as tb}from"./ui-vendor-CX5oLBI_.js";import{l as sb}from"./socket-vendor-TjCxX7sJ.js";import{c as Gr,a as ab}from"./redux-vendor-tbZCm13o.js";import{u as Fs,a as Fa,b as Ox,B as rb,R as nb,c as _t,O as ib}from"./router-vendor-B_rK4TXr.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 _l={},lm=rf;_l.createRoot=lm.createRoot,_l.hydrateRoot=lm.hydrateRoot;var Ux={exports:{}},Bx={};var An=p;function lb(t,s){return t===s&&(t!==0||1/t===1/s)||t!==t&&s!==s}var ob=typeof Object.is=="function"?Object.is:lb,cb=An.useSyncExternalStore,db=An.useRef,mb=An.useEffect,ub=An.useMemo,xb=An.useDebugValue;Bx.useSyncExternalStoreWithSelector=function(t,s,a,r,n){var i=db(null);if(i.current===null){var l={hasValue:!1,value:null};i.current=l}else l=i.current;i=ub(function(){function c(u){if(!d){if(d=!0,m=u,u=r(u),n!==void 0&&l.hasValue){var g=l.value;if(n(g,u))return h=g}return h=u}if(g=h,ob(m,u))return g;var b=r(u);return n!==void 0&&n(g,b)?(m=u,g):(m=u,h=b)}var d=!1,m,h,x=a===void 0?null:a;return[function(){return c(s())},x===null?void 0:function(){return c(x())}]},[s,a,r,n]);var o=cb(t,i[0],i[1]);return mb(function(){l.hasValue=!0,l.value=o},[o]),xb(o),o};Ux.exports=Bx;var hb=Ux.exports;function pb(t){t()}function gb(){let t=null,s=null;return{clear(){t=null,s=null},notify(){pb(()=>{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 om={notify(){},get:()=>[]};function fb(t,s){let a,r=om,n=0,i=!1;function l(b){m();const f=r.subscribe(b);let y=!1;return()=>{y||(y=!0,f(),h())}}function o(){r.notify()}function c(){g.onStateChange&&g.onStateChange()}function d(){return i}function m(){n++,a||(a=t.subscribe(c),r=gb())}function h(){n--,a&&n===0&&(a(),a=void 0,r.clear(),r=om)}function x(){i||(i=!0,m())}function u(){i&&(i=!1,h())}const g={addNestedSub:l,notifyNestedSubs:o,handleChangeWrapper:c,isSubscribed:d,trySubscribe:x,tryUnsubscribe:u,getListeners:()=>r};return g}var bb=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",yb=bb(),vb=()=>typeof navigator<"u"&&navigator.product==="ReactNative",jb=vb(),Nb=()=>yb||jb?p.useLayoutEffect:p.useEffect,wb=Nb(),Yi=Symbol.for("react-redux-context"),Ki=typeof globalThis<"u"?globalThis:{};function Cb(){if(!p.createContext)return{};const t=Ki[Yi]??(Ki[Yi]=new Map);let s=t.get(p.createContext);return s||(s=p.createContext(null),t.set(p.createContext,s)),s}var Xa=Cb();function Sb(t){const{children:s,context:a,serverState:r,store:n}=t,i=p.useMemo(()=>{const c=fb(n);return{store:n,subscription:c,getServerState:r?()=>r:void 0}},[n,r]),l=p.useMemo(()=>n.getState(),[n]);wb(()=>{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||Xa;return p.createElement(o.Provider,{value:i},s)}var Ab=Sb;function jo(t=Xa){return function(){return p.useContext(t)}}var Vx=jo();function zx(t=Xa){const s=t===Xa?Vx:jo(t),a=()=>{const{store:r}=s();return r};return Object.assign(a,{withTypes:()=>a}),a}var Tb=zx();function kb(t=Xa){const s=t===Xa?Tb:zx(t),a=()=>s().dispatch;return Object.assign(a,{withTypes:()=>a}),a}var Rb=kb(),Db=(t,s)=>t===s;function Pb(t=Xa){const s=t===Xa?Vx:jo(t),a=(r,n={})=>{const{equalityFn:i=Db}=typeof n=="function"?{equalityFn:n}:n,l=s(),{store:o,subscription:c,getServerState:d}=l;p.useRef(!0);const m=p.useCallback({[r.name](x){return r(x)}}[r.name],[r]),h=hb.useSyncExternalStoreWithSelector(c.addNestedSub,o.getState,d||o.getState,m,i);return p.useDebugValue(h),h};return Object.assign(a,{withTypes:()=>a}),a}var Ib=Pb(),Ll=function(t,s){return Ll=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])},Ll(t,s)};function Eb(t,s){if(typeof s!="function"&&s!==null)throw new TypeError("Class extends value "+String(s)+" is not a constructor or null");Ll(t,s);function a(){this.constructor=t}t.prototype=s===null?Object.create(s):(a.prototype=s.prototype,new a)}var ci=function(){return ci=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},ci.apply(this,arguments)};var mr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function No(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function wo(t,s){return t(s={exports:{}},s.exports),s.exports}var or=wo(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()}});No(or);var Fb=No(wo(function(t,s){var a=mr&&mr.__awaiter||function(m,h,x,u){return new(x||(x=Promise))(function(g,b){function f(C){try{v(u.next(C))}catch(w){b(w)}}function y(C){try{v(u.throw(C))}catch(w){b(w)}}function v(C){C.done?g(C.value):new x(function(w){w(C.value)}).then(f,y)}v((u=u.apply(m,h||[])).next())})},r=mr&&mr.__generator||function(m,h){var x,u,g,b,f={label:0,sent:function(){if(1&g[0])throw g[1];return g[1]},trys:[],ops:[]};return b={next:y(0),throw:y(1),return:y(2)},typeof Symbol=="function"&&(b[Symbol.iterator]=function(){return this}),b;function y(v){return function(C){return function(w){if(x)throw new TypeError("Generator is already executing.");for(;f;)try{if(x=1,u&&(g=2&w[0]?u.return:w[0]?u.throw||((g=u.return)&&g.call(u),0):u.next)&&!(g=g.call(u,w[1])).done)return g;switch(u=0,g&&(w=[2&w[0],g.value]),w[0]){case 0:case 1:g=w;break;case 4:return f.label++,{value:w[1],done:!1};case 5:f.label++,u=w[1],w=[0];continue;case 7:w=f.ops.pop(),f.trys.pop();continue;default:if(g=f.trys,!((g=g.length>0&&g[g.length-1])||w[0]!==6&&w[0]!==2)){f=0;continue}if(w[0]===3&&(!g||w[1]>g[0]&&w[1]<g[3])){f.label=w[1];break}if(w[0]===6&&f.label<g[1]){f.label=g[1],g=w;break}if(g&&f.label<g[2]){f.label=g[2],f.ops.push(w);break}g[2]&&f.ops.pop(),f.trys.pop();continue}w=h.call(m,f)}catch(A){w=[6,A],u=0}finally{x=g=0}if(5&w[0])throw w[1];return{value:w[0]?w[1]:void 0,done:!0}}([v,C])}}},n=mr;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(h){throw new Error("Unsupported")})})},getItem:function(m){return a(n,void 0,void 0,function(){return r(this,function(h){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(h){throw new Error("Unsupported")})})},setItem:function(m,h){return a(n,void 0,void 0,function(){return r(this,function(x){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,h){return window.localStorage.setItem(m,h)}};function o(m){return new Promise(function(h){return setTimeout(h,m)})}function c(m){for(var h="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",x="",u=0;u<m;u++)x+=h[Math.floor(Math.random()*h.length)];return x}var d=function(){function m(h){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=h,m.waiters===void 0&&(m.waiters=[])}return m.prototype.acquireLock=function(h,x){return x===void 0&&(x=5e3),a(this,void 0,void 0,function(){var u,g,b,f,y,v,C;return r(this,function(w){switch(w.label){case 0:u=Date.now()+c(4),g=Date.now()+x,b=i+"-"+h,f=this.storageHandler===void 0?l:this.storageHandler,w.label=1;case 1:return Date.now()<g?[4,o(30)]:[3,8];case 2:return w.sent(),f.getItemSync(b)!==null?[3,5]:(y=this.id+"-"+h+"-"+u,[4,o(Math.floor(25*Math.random()))]);case 3:return w.sent(),f.setItemSync(b,JSON.stringify({id:this.id,iat:u,timeoutKey:y,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,o(30)];case 4:return w.sent(),(v=f.getItemSync(b))!==null&&(C=JSON.parse(v)).id===this.id&&C.iat===u?(this.acquiredIatSet.add(u),this.refreshLockWhileAcquired(b,u),[2,!0]):[3,7];case 5:return m.lockCorrector(this.storageHandler===void 0?l:this.storageHandler),[4,this.waitForSomethingToChange(g)];case 6:w.sent(),w.label=7;case 7:return u=Date.now()+c(4),[3,1];case 8:return[2,!1]}})})},m.prototype.refreshLockWhileAcquired=function(h,x){return a(this,void 0,void 0,function(){var u=this;return r(this,function(g){return setTimeout(function(){return a(u,void 0,void 0,function(){var b,f,y;return r(this,function(v){switch(v.label){case 0:return[4,or.default().lock(x)];case 1:return v.sent(),this.acquiredIatSet.has(x)?(b=this.storageHandler===void 0?l:this.storageHandler,(f=b.getItemSync(h))===null?(or.default().unlock(x),[2]):((y=JSON.parse(f)).timeRefreshed=Date.now(),b.setItemSync(h,JSON.stringify(y)),or.default().unlock(x),this.refreshLockWhileAcquired(h,x),[2])):(or.default().unlock(x),[2])}})})},1e3),[2]})})},m.prototype.waitForSomethingToChange=function(h){return a(this,void 0,void 0,function(){return r(this,function(x){switch(x.label){case 0:return[4,new Promise(function(u){var g=!1,b=Date.now(),f=!1;function y(){if(f||(window.removeEventListener("storage",y),m.removeFromWaiting(y),clearTimeout(v),f=!0),!g){g=!0;var C=50-(Date.now()-b);C>0?setTimeout(u,C):u(null)}}window.addEventListener("storage",y),m.addToWaiting(y);var v=setTimeout(y,Math.max(0,h-Date.now()))})];case 1:return x.sent(),[2]}})})},m.addToWaiting=function(h){this.removeFromWaiting(h),m.waiters!==void 0&&m.waiters.push(h)},m.removeFromWaiting=function(h){m.waiters!==void 0&&(m.waiters=m.waiters.filter(function(x){return x!==h}))},m.notifyWaiters=function(){m.waiters!==void 0&&m.waiters.slice().forEach(function(h){return h()})},m.prototype.releaseLock=function(h){return a(this,void 0,void 0,function(){return r(this,function(x){switch(x.label){case 0:return[4,this.releaseLock__private__(h)];case 1:return[2,x.sent()]}})})},m.prototype.releaseLock__private__=function(h){return a(this,void 0,void 0,function(){var x,u,g,b;return r(this,function(f){switch(f.label){case 0:return x=this.storageHandler===void 0?l:this.storageHandler,u=i+"-"+h,(g=x.getItemSync(u))===null?[2]:(b=JSON.parse(g)).id!==this.id?[3,2]:[4,or.default().lock(b.iat)];case 1:f.sent(),this.acquiredIatSet.delete(b.iat),x.removeItemSync(u),or.default().unlock(b.iat),m.notifyWaiters(),f.label=2;case 2:return[2]}})})},m.lockCorrector=function(h){for(var x=Date.now()-5e3,u=h,g=[],b=0;;){var f=u.keySync(b);if(f===null)break;g.push(f),b++}for(var y=!1,v=0;v<g.length;v++){var C=g[v];if(C.includes(i)){var w=u.getItemSync(C);if(w!==null){var A=JSON.parse(w);(A.timeRefreshed===void 0&&A.timeAcquired<x||A.timeRefreshed!==void 0&&A.timeRefreshed<x)&&(u.removeItemSync(C),y=!0)}}}y&&m.notifyWaiters()},m.waiters=void 0,m}();s.default=d}));new TextEncoder;new TextDecoder;var hr=wo(function(t,s){var a=mr&&mr.__assign||function(){return a=Object.assign||function(c){for(var d,m=1,h=arguments.length;m<h;m++)for(var x in d=arguments[m])Object.prototype.hasOwnProperty.call(d,x)&&(c[x]=d[x]);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(h){if(typeof h.expires=="number"){var x=new Date;x.setMilliseconds(x.getMilliseconds()+864e5*h.expires),h.expires=x}return r("Expires",h.expires?h.expires.toUTCString():"")+r("Domain",h.domain)+r("Path",h.path)+r("Secure",h.secure)+r("SameSite",h.sameSite)}(m)}function i(c){for(var d={},m=c?c.split("; "):[],h=/(%[\dA-F]{2})+/gi,x=0;x<m.length;x++){var u=m[x].split("="),g=u.slice(1).join("=");g.charAt(0)==='"'&&(g=g.slice(1,-1));try{d[u[0].replace(h,decodeURIComponent)]=g.replace(h,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}))}});No(hr),hr.encode,hr.parse,hr.getAll;hr.get;hr.set;hr.remove;var cm;(function(t){t.Code="code",t.ConnectCode="connect_code"})(cm||(cm={}));var dm;(function(t){t.Bearer="Bearer",t.DPoP="DPoP"})(dm||(dm={}));new Fb;var _b={isAuthenticated:!1,isLoading:!0,error:void 0,user:void 0},Ms=function(){throw new Error("You forgot to wrap your component in <Auth0Provider>.")},Lb=ci(ci({},_b),{buildAuthorizeUrl:Ms,buildLogoutUrl:Ms,getAccessTokenSilently:Ms,getAccessTokenWithPopup:Ms,getIdTokenClaims:Ms,loginWithRedirect:Ms,loginWithPopup:Ms,connectAccountWithRedirect:Ms,logout:Ms,handleRedirectCallback:Ms,getDpopNonce:Ms,setDpopNonce:Ms,generateDpopProof:Ms,createFetcher:Ms}),Mb=p.createContext(Lb);(function(t){Eb(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 $b=function(t){return t===void 0&&(t=Mb),p.useContext(t)};const Xi="idToken",Zi="userData",Ob=()=>!0;class st{static setAccessToken(s){}static getAccessToken(){return null}static setRefreshToken(s){}static getRefreshToken(){return null}static setIdToken(s){sessionStorage.setItem(Xi,s)}static getIdToken(){return sessionStorage.getItem(Xi)}static setUserData(s){localStorage.setItem(Zi,JSON.stringify(s))}static getUserData(){const s=localStorage.getItem(Zi);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(Zi),sessionStorage.removeItem(Xi)}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 Ob()}}function Ji(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 Hx="https://reflow-uat.royalenfield.com/api/v1/",ve=lo.create({baseURL:Hx,headers:{"Content-Type":"application/json"},withCredentials:!0});ve.interceptors.request.use(t=>t,t=>Promise.reject(t));ve.interceptors.response.use(t=>t,async t=>{var a,r;const s=t.config;if(t.code==="ERR_NETWORK"||t.code==="ECONNREFUSED"||(a=t.message)!=null&&a.includes("ERR_CONNECTION_REFUSED"),((r=t.response)==null?void 0:r.status)===401&&!s._retry){s._retry=!0;const n=!0;try{const i=st.getRefreshToken(),l=await lo.post(`${Hx}/auth/refresh`,n?{}:{refreshToken:i},{withCredentials:!0}),c=(l.data.data||l.data).accessToken;return ve(s)}catch(i){return st.clearAll(),window.location.href="/",Promise.reject(i)}}return Promise.reject(t)});async function Ub(t,s){var a,r;try{const n=await ve.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&&st.setUserData(l.user),l.idToken&&st.setIdToken(l.idToken),l.accessToken&&l.refreshToken&&(st.setAccessToken(l.accessToken),st.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 Bb(){var r;const t={},a=(await ve.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 ln(){const s=(await ve.get("/auth/me")).data;return s.data||s}async function Vb(){var t,s;try{await ve.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 Ml="https://ssodev.rebridge.co.in/realms/RE",Gx="REFLOW",Co=`${window.location.origin}/login/callback`;function zb(){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=`${Ml}/protocol/openid-connect/auth?client_id=${Gx}&response_type=code&scope=openid&redirect_uri=${encodeURIComponent(Co)}&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 Hb(t,s){var r,n,i;const a="https://reflow-uat.royalenfield.com/api/v1/";try{const l=await lo.post(`${a}/auth/tanflow/token-exchange`,{code:t,redirectUri:Co,state:s},{withCredentials:!0,headers:{"Content-Type":"application/json"}}),o=((r=l.data)==null?void 0:r.data)||l.data;return o.accessToken&&st.setAccessToken(o.accessToken),o.refreshToken&&st.setRefreshToken(o.refreshToken),o.idToken&&st.setIdToken(o.idToken),o.user&&st.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 Gb(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=Co,a=new URL(`${Ml}/protocol/openid-connect/logout`);a.searchParams.set("client_id",Gx),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:`${Ml}/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 Wx=p.createContext(void 0);function Wb({children:t}){const[s,a]=p.useState(!1),[r,n]=p.useState(!0),[i,l]=p.useState(null),[o,c]=p.useState(null),[d,m]=p.useState(!1);p.useEffect(()=>{const v=sessionStorage.getItem("__logout_in_progress__"),C=sessionStorage.getItem("__force_logout__");if(v==="true"||C==="true"){sessionStorage.removeItem("__logout_in_progress__"),sessionStorage.removeItem("__force_logout__"),st.clearAll();try{localStorage.clear(),sessionStorage.clear()}catch(A){console.error("Error clearing storage:",A)}a(!1),l(null),n(!1),c(null);return}const w=new URLSearchParams(window.location.search);if(w.has("logout")||w.has("okta_logged_out")||w.has("tanflow_logged_out")){console.log("🚪 Logout parameter detected in URL, clearing all tokens"),st.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 A=new URLSearchParams;w.has("okta_logged_out")&&A.set("okta_logged_out","true"),w.has("tanflow_logged_out")&&A.set("tanflow_logged_out","true");const N=A.toString()?`/?${A.toString()}`:"/";window.history.replaceState({},document.title,N);return}window.location.pathname==="/login/callback"||window.location.pathname==="/login/tanflow/callback"||(st.getUserData(),d?n(!1):x())},[d]),p.useEffect(()=>{if(!s)return;const v=async()=>{try{await f()}catch(A){console.error("Silent refresh failed:",A)}},C=10*60*1e3,w=setInterval(v,C);return()=>clearInterval(w)},[s]);const h=p.useRef(!1);p.useEffect(()=>{if(h.current||window.location.pathname!=="/login/callback")return;(async()=>{const C=new URLSearchParams(window.location.search);if((C.has("logout")||C.has("tanflow_logged_out")||C.has("okta_logged_out"))&&!C.get("code")){console.log("🚪 Logout redirect detected in callback, redirecting to home");const _=new URLSearchParams;C.has("tanflow_logged_out")&&_.set("tanflow_logged_out","true"),C.has("okta_logged_out")&&_.set("okta_logged_out","true"),C.has("logout")&&_.set("logout",C.get("logout")||Date.now().toString());const T=_.toString()?`/?${_.toString()}`:"/?logout="+Date.now();window.location.replace(T);return}h.current=!0;const w=C.get("code"),A=C.get("error");if(window.history.replaceState({},document.title,"/login/callback"),sessionStorage.getItem("auth_provider")==="tanflow"){h.current=!1;return}if(A){c(new Error(`Authentication error: ${A}`)),n(!1),sessionStorage.removeItem("auth_provider");return}if(!w){n(!1),sessionStorage.removeItem("auth_provider");return}try{n(!0),a(!1),c(null);const _=`${window.location.origin}/login/callback`,T=await Ub(w,_);l(T.user),a(!0),c(null),sessionStorage.removeItem("auth_provider"),window.history.replaceState({},document.title,"/")}catch(_){console.error("❌ Token exchange error in AuthContext:",_),c(_),a(!1),l(null),sessionStorage.removeItem("auth_provider"),h.current=!1}finally{n(!1)}})()},[]);const x=async()=>{var C;if(d){n(!1);return}const v=!0;try{if(n(!0),v){const N=st.getUserData();try{const _=await ln();l(_),st.setUserData(_),a(!0)}catch(_){if(((C=_==null?void 0:_.response)==null?void 0:C.status)===401)try{await f();const T=await ln();l(T),st.setUserData(T),a(!0)}catch{st.clearAll(),a(!1),l(null)}else _!=null&&_.isConnectionError?N?(l(N),a(!0)):(a(!1),l(null)):(st.clearAll(),a(!1),l(null))}return}const w=st.getAccessToken(),A=st.getUserData();if(!w){a(!1),l(null),n(!1);return}if(Ji(w))try{await f();const N=st.getAccessToken();if(N&&!Ji(N)){const _=st.getUserData();if(_)l(_),a(!0);else try{const T=await ln();l(T),st.setUserData(T),a(!0)}catch{st.clearAll(),a(!1),l(null)}}else st.clearAll(),a(!1),l(null)}catch{st.clearAll(),a(!1),l(null)}else if(A)l(A),a(!0);else try{const N=await ln();l(N),st.setUserData(N),a(!0)}catch{st.clearAll(),a(!1),l(null)}}catch(w){console.error("Error checking auth status:",w),c(w),st.clearAll(),a(!1),l(null)}finally{n(!1)}},u=async()=>{try{c(null);const v="https://dev-830839.oktapreview.com",C="0oa2jgzvrpdwx2iqd0h8",w=`${window.location.origin}/login/callback`,A="code",N="openid profile email",_=Math.random().toString(36).substring(7);sessionStorage.setItem("auth_provider","okta");const T=new URLSearchParams(window.location.search),R=T.has("logout")||T.has("okta_logged_out")||T.has("tanflow_logged_out");let j=`${v}/oauth2/default/v1/authorize?client_id=${C}&redirect_uri=${encodeURIComponent(w)}&response_type=${A}&scope=${encodeURIComponent(N)}&state=${_}`;R&&(j+="&prompt=login"),window.location.href=j}catch(v){throw c(v),v}},g=async()=>{try{const v=st.getIdToken(),C=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 Vb(),console.log("🚪 Backend logout API called successfully")}catch(T){console.error("🚪 Logout API error:",T),console.warn("🚪 Backend logout failed - httpOnly cookies may not be cleared")}const w=sessionStorage.getItem("__logout_in_progress__"),A=sessionStorage.getItem("__force_logout__"),N=sessionStorage.getItem("auth_provider");if(st.clearAll(),w&&sessionStorage.setItem("__logout_in_progress__",w),A&&sessionStorage.setItem("__force_logout__",A),v&&st.setIdToken(v),N&&sessionStorage.setItem("auth_provider",N),await new Promise(T=>setTimeout(T,100)),C==="tanflow"&&v){console.log("🚪 Initiating Tanflow logout...");try{Gb(v);return}catch(T){console.error("🚪 Tanflow logout error:",T)}}console.log("🚪 Using OKTA logout flow or fallback"),sessionStorage.removeItem("auth_provider"),v&&st.clearAll();const _=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(_)}catch(v){console.error("🚪 Logout error:",v);try{localStorage.clear(),sessionStorage.clear(),sessionStorage.setItem("__logout_in_progress__","true");const C=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(C)}catch{window.location.replace("/?logout="+Date.now())}}},b=async()=>{{if(s)return"cookie-based-auth";try{return await f(),s?"cookie-based-auth":null}catch{return null}}const v=st.getAccessToken();if(v&&!Ji(v))return v;try{return await f(),st.getAccessToken()}catch{return null}},f=async()=>{try{const C=await Bb();return}catch(C){throw st.clearAll(),a(!1),l(null),C}},y={isAuthenticated:s,isLoading:r,user:i,error:o,login:u,logout:g,getAccessTokenSilently:b,refreshTokenSilently:f};return e.jsx(Wx.Provider,{value:y,children:t})}function Yb({children:t}){return e.jsx(Wb,{children:t})}function Jt(){const t=p.useContext(Wx);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t}function cr(t){return(t==null?void 0:t.role)==="ADMIN"}function tn(t){return(t==null?void 0:t.role)==="MANAGEMENT"}function Di(t){return(t==null?void 0:t.role)==="MANAGEMENT"||(t==null?void 0:t.role)==="ADMIN"}const mm=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,um=xx,So=(t,s)=>a=>{var r;if((s==null?void 0:s.variants)==null)return um(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],h=i==null?void 0:i[d];if(m===null)return null;const x=mm(m)||mm(h);return n[d][x]}),o=a&&Object.entries(a).reduce((d,m)=>{let[h,x]=m;return x===void 0||(d[h]=x),d},{}),c=s==null||(r=s.compoundVariants)===null||r===void 0?void 0:r.reduce((d,m)=>{let{class:h,className:x,...u}=m;return Object.entries(u).every(g=>{let[b,f]=g;return Array.isArray(f)?f.includes({...i,...o}[b]):{...i,...o}[b]===f})?[...d,h,x]:d},[]);return um(t,l,c,a==null?void 0:a.class,a==null?void 0:a.className)},Ao="-",Kb=t=>{const s=Zb(t),{conflictingClassGroups:a,conflictingClassGroupModifiers:r}=t;return{getClassGroupId:l=>{const o=l.split(Ao);return o[0]===""&&o.length!==1&&o.shift(),Yx(o,s)||Xb(l)},getConflictingClassGroupIds:(l,o)=>{const c=a[l]||[];return o&&r[l]?[...c,...r[l]]:c}}},Yx=(t,s)=>{var l;if(t.length===0)return s.classGroupId;const a=t[0],r=s.nextPart.get(a),n=r?Yx(t.slice(1),r):void 0;if(n)return n;if(s.validators.length===0)return;const i=t.join(Ao);return(l=s.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},xm=/^\[(.+)\]$/,Xb=t=>{if(xm.test(t)){const s=xm.exec(t)[1],a=s==null?void 0:s.substring(0,s.indexOf(":"));if(a)return"arbitrary.."+a}},Zb=t=>{const{theme:s,prefix:a}=t,r={nextPart:new Map,validators:[]};return Qb(Object.entries(t.classGroups),a).forEach(([i,l])=>{$l(l,r,i,s)}),r},$l=(t,s,a,r)=>{t.forEach(n=>{if(typeof n=="string"){const i=n===""?s:hm(s,n);i.classGroupId=a;return}if(typeof n=="function"){if(Jb(n)){$l(n(r),s,a,r);return}s.validators.push({validator:n,classGroupId:a});return}Object.entries(n).forEach(([i,l])=>{$l(l,hm(s,i),a,r)})})},hm=(t,s)=>{let a=t;return s.split(Ao).forEach(r=>{a.nextPart.has(r)||a.nextPart.set(r,{nextPart:new Map,validators:[]}),a=a.nextPart.get(r)}),a},Jb=t=>t.isThemeGetter,Qb=(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,qb=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)}}},Kx="!",ey=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,h;for(let f=0;f<o.length;f++){let y=o[f];if(d===0){if(y===n&&(r||o.slice(f,f+i)===s)){c.push(o.slice(m,f)),m=f+i;continue}if(y==="/"){h=f;continue}}y==="["?d++:y==="]"&&d--}const x=c.length===0?o:o.substring(m),u=x.startsWith(Kx),g=u?x.substring(1):x,b=h&&h>m?h-m:void 0;return{modifiers:c,hasImportantModifier:u,baseClassName:g,maybePostfixModifierPosition:b}};return a?o=>a({className:o,parseClassName:l}):l},ty=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},sy=t=>({cache:qb(t.cacheSize),parseClassName:ey(t),...Kb(t)}),ay=/\s+/,ry=(t,s)=>{const{parseClassName:a,getClassGroupId:r,getConflictingClassGroupIds:n}=s,i=[],l=t.trim().split(ay);let o="";for(let c=l.length-1;c>=0;c-=1){const d=l[c],{modifiers:m,hasImportantModifier:h,baseClassName:x,maybePostfixModifierPosition:u}=a(d);let g=!!u,b=r(g?x.substring(0,u):x);if(!b){if(!g){o=d+(o.length>0?" "+o:o);continue}if(b=r(x),!b){o=d+(o.length>0?" "+o:o);continue}g=!1}const f=ty(m).join(":"),y=h?f+Kx:f,v=y+b;if(i.includes(v))continue;i.push(v);const C=n(b,g);for(let w=0;w<C.length;++w){const A=C[w];i.push(y+A)}o=d+(o.length>0?" "+o:o)}return o};function ny(){let t=0,s,a,r="";for(;t<arguments.length;)(s=arguments[t++])&&(a=Xx(s))&&(r&&(r+=" "),r+=a);return r}const Xx=t=>{if(typeof t=="string")return t;let s,a="";for(let r=0;r<t.length;r++)t[r]&&(s=Xx(t[r]))&&(a&&(a+=" "),a+=s);return a};function iy(t,...s){let a,r,n,i=l;function l(c){const d=s.reduce((m,h)=>h(m),t());return a=sy(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=ry(c,a);return n(c,m),m}return function(){return i(ny.apply(null,arguments))}}const Lt=t=>{const s=a=>a[t]||[];return s.isThemeGetter=!0,s},Zx=/^\[(?:([a-z-]+):)?(.+)\]$/i,ly=/^\d+\/\d+$/,oy=new Set(["px","full","screen"]),cy=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,dy=/\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$/,my=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,uy=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,xy=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Sa=t=>Lr(t)||oy.has(t)||ly.test(t),Ba=t=>Wr(t,"length",jy),Lr=t=>!!t&&!Number.isNaN(Number(t)),Qi=t=>Wr(t,"number",Lr),sn=t=>!!t&&Number.isInteger(Number(t)),hy=t=>t.endsWith("%")&&Lr(t.slice(0,-1)),ot=t=>Zx.test(t),Va=t=>cy.test(t),py=new Set(["length","size","percentage"]),gy=t=>Wr(t,py,Jx),fy=t=>Wr(t,"position",Jx),by=new Set(["image","url"]),yy=t=>Wr(t,by,wy),vy=t=>Wr(t,"",Ny),an=()=>!0,Wr=(t,s,a)=>{const r=Zx.exec(t);return r?r[1]?typeof s=="string"?r[1]===s:s.has(r[1]):a(r[2]):!1},jy=t=>dy.test(t)&&!my.test(t),Jx=()=>!1,Ny=t=>uy.test(t),wy=t=>xy.test(t),Cy=()=>{const t=Lt("colors"),s=Lt("spacing"),a=Lt("blur"),r=Lt("brightness"),n=Lt("borderColor"),i=Lt("borderRadius"),l=Lt("borderSpacing"),o=Lt("borderWidth"),c=Lt("contrast"),d=Lt("grayscale"),m=Lt("hueRotate"),h=Lt("invert"),x=Lt("gap"),u=Lt("gradientColorStops"),g=Lt("gradientColorStopPositions"),b=Lt("inset"),f=Lt("margin"),y=Lt("opacity"),v=Lt("padding"),C=Lt("saturate"),w=Lt("scale"),A=Lt("sepia"),N=Lt("skew"),_=Lt("space"),T=Lt("translate"),R=()=>["auto","contain","none"],j=()=>["auto","hidden","clip","visible","scroll"],E=()=>["auto",ot,s],P=()=>[ot,s],B=()=>["",Sa,Ba],k=()=>["auto",Lr,ot],L=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],V=()=>["solid","dashed","dotted","double","none"],D=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],S=()=>["start","end","center","between","around","evenly","stretch"],O=()=>["","0",ot],I=()=>["auto","avoid","all","avoid-page","page","left","right","column"],M=()=>[Lr,ot];return{cacheSize:500,separator:":",theme:{colors:[an],spacing:[Sa,Ba],blur:["none","",Va,ot],brightness:M(),borderColor:[t],borderRadius:["none","","full",Va,ot],borderSpacing:P(),borderWidth:B(),contrast:M(),grayscale:O(),hueRotate:M(),invert:O(),gap:P(),gradientColorStops:[t],gradientColorStopPositions:[hy,Ba],inset:E(),margin:E(),opacity:M(),padding:P(),saturate:M(),scale:M(),sepia:O(),skew:M(),space:P(),translate:P()},classGroups:{aspect:[{aspect:["auto","square","video",ot]}],container:["container"],columns:[{columns:[Va]}],"break-after":[{"break-after":I()}],"break-before":[{"break-before":I()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...L(),ot]}],overflow:[{overflow:j()}],"overflow-x":[{"overflow-x":j()}],"overflow-y":[{"overflow-y":j()}],overscroll:[{overscroll:R()}],"overscroll-x":[{"overscroll-x":R()}],"overscroll-y":[{"overscroll-y":R()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[b]}],"inset-x":[{"inset-x":[b]}],"inset-y":[{"inset-y":[b]}],start:[{start:[b]}],end:[{end:[b]}],top:[{top:[b]}],right:[{right:[b]}],bottom:[{bottom:[b]}],left:[{left:[b]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",sn,ot]}],basis:[{basis:E()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",ot]}],grow:[{grow:O()}],shrink:[{shrink:O()}],order:[{order:["first","last","none",sn,ot]}],"grid-cols":[{"grid-cols":[an]}],"col-start-end":[{col:["auto",{span:["full",sn,ot]},ot]}],"col-start":[{"col-start":k()}],"col-end":[{"col-end":k()}],"grid-rows":[{"grid-rows":[an]}],"row-start-end":[{row:["auto",{span:[sn,ot]},ot]}],"row-start":[{"row-start":k()}],"row-end":[{"row-end":k()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",ot]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",ot]}],gap:[{gap:[x]}],"gap-x":[{"gap-x":[x]}],"gap-y":[{"gap-y":[x]}],"justify-content":[{justify:["normal",...S()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...S(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...S(),"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:[f]}],mx:[{mx:[f]}],my:[{my:[f]}],ms:[{ms:[f]}],me:[{me:[f]}],mt:[{mt:[f]}],mr:[{mr:[f]}],mb:[{mb:[f]}],ml:[{ml:[f]}],"space-x":[{"space-x":[_]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[_]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",ot,s]}],"min-w":[{"min-w":[ot,s,"min","max","fit"]}],"max-w":[{"max-w":[ot,s,"none","full","min","max","fit","prose",{screen:[Va]},Va]}],h:[{h:[ot,s,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[ot,s,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[ot,s,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[ot,s,"auto","min","max","fit"]}],"font-size":[{text:["base",Va,Ba]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Qi]}],"font-family":[{font:[an]}],"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",ot]}],"line-clamp":[{"line-clamp":["none",Lr,Qi]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Sa,ot]}],"list-image":[{"list-image":["none",ot]}],"list-style-type":[{list:["none","disc","decimal",ot]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[t]}],"placeholder-opacity":[{"placeholder-opacity":[y]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[t]}],"text-opacity":[{"text-opacity":[y]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...V(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Sa,Ba]}],"underline-offset":[{"underline-offset":["auto",Sa,ot]}],"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:P()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",ot]}],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",ot]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[y]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...L(),fy]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",gy]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},yy]}],"bg-color":[{bg:[t]}],"gradient-from-pos":[{from:[g]}],"gradient-via-pos":[{via:[g]}],"gradient-to-pos":[{to:[g]}],"gradient-from":[{from:[u]}],"gradient-via":[{via:[u]}],"gradient-to":[{to:[u]}],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":[y]}],"border-style":[{border:[...V(),"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":[y]}],"divide-style":[{divide:V()}],"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:["",...V()]}],"outline-offset":[{"outline-offset":[Sa,ot]}],"outline-w":[{outline:[Sa,Ba]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:B()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[y]}],"ring-offset-w":[{"ring-offset":[Sa,Ba]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",Va,vy]}],"shadow-color":[{shadow:[an]}],opacity:[{opacity:[y]}],"mix-blend":[{"mix-blend":[...D(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":D()}],filter:[{filter:["","none"]}],blur:[{blur:[a]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",Va,ot]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[m]}],invert:[{invert:[h]}],saturate:[{saturate:[C]}],sepia:[{sepia:[A]}],"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":[h]}],"backdrop-opacity":[{"backdrop-opacity":[y]}],"backdrop-saturate":[{"backdrop-saturate":[C]}],"backdrop-sepia":[{"backdrop-sepia":[A]}],"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",ot]}],duration:[{duration:M()}],ease:[{ease:["linear","in","out","in-out",ot]}],delay:[{delay:M()}],animate:[{animate:["none","spin","ping","pulse","bounce",ot]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[w]}],"scale-x":[{"scale-x":[w]}],"scale-y":[{"scale-y":[w]}],rotate:[{rotate:[sn,ot]}],"translate-x":[{"translate-x":[T]}],"translate-y":[{"translate-y":[T]}],"skew-x":[{"skew-x":[N]}],"skew-y":[{"skew-y":[N]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",ot]}],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",ot]}],"caret-color":[{caret:[t]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":P()}],"scroll-mx":[{"scroll-mx":P()}],"scroll-my":[{"scroll-my":P()}],"scroll-ms":[{"scroll-ms":P()}],"scroll-me":[{"scroll-me":P()}],"scroll-mt":[{"scroll-mt":P()}],"scroll-mr":[{"scroll-mr":P()}],"scroll-mb":[{"scroll-mb":P()}],"scroll-ml":[{"scroll-ml":P()}],"scroll-p":[{"scroll-p":P()}],"scroll-px":[{"scroll-px":P()}],"scroll-py":[{"scroll-py":P()}],"scroll-ps":[{"scroll-ps":P()}],"scroll-pe":[{"scroll-pe":P()}],"scroll-pt":[{"scroll-pt":P()}],"scroll-pr":[{"scroll-pr":P()}],"scroll-pb":[{"scroll-pb":P()}],"scroll-pl":[{"scroll-pl":P()}],"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",ot]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[Sa,Ba,Qi]}],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"]}}},Sy=iy(Cy);function Ae(...t){return Sy(xx(t))}const bn=So("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"}}),F=p.forwardRef(({className:t,variant:s,size:a,asChild:r=!1,...n},i)=>{const l=r?ax:"button";return e.jsx(l,{"data-slot":"button",className:Ae(bn({variant:s,size:a,className:t})),ref:i,...n})});F.displayName="Button";function se({className:t,...s}){return e.jsx("div",{"data-slot":"card",className:Ae("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border",t),...s})}function ge({className:t,...s}){return e.jsx("div",{"data-slot":"card-header",className:Ae("@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 fe({className:t,...s}){return e.jsx("h4",{"data-slot":"card-title",className:Ae("leading-none",t),...s})}function Ue({className:t,...s}){return e.jsx("p",{"data-slot":"card-description",className:Ae("text-muted-foreground",t),...s})}function ae({className:t,...s}){return e.jsx("div",{"data-slot":"card-content",className:Ae("px-6 [&:last-child]:pb-6",t),...s})}const Pi="/assets/Re_Logo-By51taPS.png",pm="/assets/landing_page_image-ClTD-4qZ.jpg";function Ay(){const{login:t,isLoading:s,error:a}=Jt(),[r,n]=p.useState(!1),[i,l]=p.useState(!1);p.useEffect(()=>{const d=new Image;d.src=pm,d.onload=()=>{l(!0)},d.complete&&l(!0)},[]);const o=async()=>{localStorage.clear(),sessionStorage.clear();try{await t()}catch(d){console.error("========================================"),console.error("OKTA LOGIN ERROR"),console.error("Error details:",d),console.error("Error message:",d==null?void 0:d.message),console.error("Error stack:",d==null?void 0:d.stack),console.error("========================================")}},c=()=>{localStorage.clear(),sessionStorage.clear(),n(!0);try{zb()}catch(d){console.error("========================================"),console.error("TANFLOW LOGIN ERROR"),console.error("Error details:",d),n(!1)}};return a&&console.error("Auth Error in Auth Component:",{message:a.message,error:a}),e.jsxs("div",{className:"min-h-screen flex items-center justify-center p-4 relative",style:{backgroundImage:i?`url(${pm})`:"none",backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",transition:"background-image 0.3s ease-in-out"},children:[!i&&e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-900 to-slate-800"}),e.jsx("div",{className:"absolute inset-0 bg-black/40"}),e.jsxs(se,{className:"w-full max-w-md shadow-xl relative z-10 bg-black backdrop-blur-sm border-gray-800",children:[e.jsx(ge,{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:Pi,alt:"Royal Enfield Logo",className:"h-10 w-auto max-w-[168px] object-contain mb-2"}),e.jsx("p",{className:"text-xs text-gray-300 text-center truncate",children:"Approval Portal"})]})}),e.jsxs(ae,{className:"space-y-4",children:[a&&e.jsxs("div",{className:"bg-red-900/50 border border-red-700 text-red-200 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(F,{onClick:o,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(jf,{className:"mr-2 h-5 w-5"}),"RE Employee Login"]})}),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-700"})}),e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"bg-gray-900 px-2 text-gray-400",children:"Or"})})]}),e.jsx(F,{onClick:c,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(Ns,{className:"mr-2 h-5 w-5"}),"Dealer Login"]})})]}),e.jsxs("div",{className:"text-center text-sm text-gray-400 mt-4",children:[e.jsx("p",{children:"Secure Single Sign-On"}),e.jsx("p",{className:"text-xs mt-1 text-gray-500",children:"Choose your authentication provider"})]})]})]})]})}function Qx(){const{isAuthenticated:t,isLoading:s,error:a,user:r}=Jt(),[n,i]=p.useState("exchanging");p.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:Pi,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(Ye,{className:"w-16 h-16 text-red-500"})}),e.jsx(Ye,{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(Ws,{className:"w-16 h-16 text-green-500"})}),e.jsx(Ws,{className:"w-16 h-16 text-green-500 relative"})]}):e.jsxs("div",{className:"relative",children:[e.jsx(it,{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 Ty(){const{isAuthenticated:t,isLoading:s,error:a,user:r}=Jt(),[n,i]=p.useState("exchanging"),[l,o]=p.useState(""),c=p.useRef(!1);p.useEffect(()=>{if(a){i("error");return}if(s){const h=new URLSearchParams(window.location.search).get("code");i(h&&!r?"exchanging":r&&!t?"fetching":"exchanging")}else r&&t&&(i("complete"),setTimeout(()=>{window.location.href="/"},1e3))},[t,s,a,r]),p.useEffect(()=>{if(c.current||window.location.pathname!=="/login/callback")return;const m=new URLSearchParams(window.location.search),h=m.get("code"),x=m.get("error");if(!h&&!x){console.log("🚪 Logout redirect detected: no code, no error - redirecting to home immediately"),c.current=!0;const b=new URLSearchParams;b.set("tanflow_logged_out","true"),b.set("logout",Date.now().toString());const f=`/?${b.toString()}`;console.log("🚪 Redirecting to:",f),window.location.replace(f);return}if(sessionStorage.getItem("auth_provider")!=="tanflow")return;(async()=>{c.current=!0;const b=new URLSearchParams(window.location.search),f=b.get("code"),y=b.get("state"),v=b.get("error");if(window.history.replaceState({},document.title,"/login/callback"),v){i("error"),sessionStorage.removeItem("auth_provider"),sessionStorage.removeItem("tanflow_auth_state");return}const C=sessionStorage.getItem("tanflow_auth_state");if(y&&y!==C){i("error"),sessionStorage.removeItem("auth_provider"),sessionStorage.removeItem("tanflow_auth_state");return}if(!f){i("error"),sessionStorage.removeItem("auth_provider"),sessionStorage.removeItem("tanflow_auth_state");return}try{i("exchanging");const w=await Hb(f,y||"");sessionStorage.removeItem("tanflow_auth_state"),i("fetching");const A=w.user||await ln();if(A)st.setUserData(A),i("complete"),setTimeout(()=>{window.history.replaceState({},document.title,"/"),window.location.href="/"},1e3);else throw new Error("User data not received")}catch(w){console.error("Tanflow callback error:",w),i("error"),o(w.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:Pi,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(Ye,{className:"w-16 h-16 text-red-500"})}),e.jsx(Ye,{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(Ws,{className:"w-16 h-16 text-green-500"})}),e.jsx(Ws,{className:"w-16 h-16 text-green-500 relative"})]}):e.jsxs("div",{className:"relative",children:[e.jsx(it,{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 ky=So("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 oe({className:t,variant:s,asChild:a=!1,...r}){const n=a?ax:"span";return e.jsx(n,{"data-slot":"badge",className:Ae(ky({variant:s}),t),...r})}function Ry({isOpen:t,onClose:s}){const{user:a,isAuthenticated:r,isLoading:n,error:i}=$b();return p.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(se,{className:"w-full max-w-2xl max-h-[90vh] overflow-auto",children:[e.jsx(ge,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(fe,{children:"Authentication Debug Information"}),e.jsx(F,{variant:"ghost",size:"icon",onClick:s,children:e.jsx(ft,{className:"h-4 w-4"})})]})}),e.jsxs(ae,{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(oe,{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 ts=p.forwardRef(({className:t,...s},a)=>e.jsx(rx,{ref:a,"data-slot":"avatar",className:Ae("relative flex size-10 shrink-0 overflow-hidden rounded-full",t),...s}));ts.displayName=rx.displayName;const Ii=p.forwardRef(({className:t,...s},a)=>e.jsx(nx,{ref:a,"data-slot":"avatar-image",className:Ae("aspect-square size-full",t),...s}));Ii.displayName=nx.displayName;const ss=p.forwardRef(({className:t,...s},a)=>e.jsx(ix,{ref:a,"data-slot":"avatar-fallback",className:Ae("bg-muted flex size-full items-center justify-center rounded-full",t),...s}));ss.displayName=ix.displayName;function gm({...t}){return e.jsx(a0,{"data-slot":"dropdown-menu",...t})}function fm({...t}){return e.jsx(r0,{"data-slot":"dropdown-menu-trigger",...t})}function bm({className:t,sideOffset:s=4,...a}){return e.jsx(n0,{children:e.jsx(i0,{"data-slot":"dropdown-menu-content",sideOffset:s,className:Ae("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 qi({className:t,inset:s,variant:a="default",...r}){return e.jsx(l0,{"data-slot":"dropdown-menu-item","data-inset":s,"data-variant":a,className:Ae("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 qx({...t}){return e.jsx(c0,{"data-slot":"alert-dialog",...t})}function Dy({...t}){return e.jsx(o0,{"data-slot":"alert-dialog-portal",...t})}const eh=p.forwardRef(({className:t,...s},a)=>e.jsx(lx,{"data-slot":"alert-dialog-overlay",className:Ae("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}));eh.displayName=lx.displayName;const To=p.forwardRef(({className:t,...s},a)=>e.jsxs(Dy,{children:[e.jsx(eh,{}),e.jsx(ox,{"data-slot":"alert-dialog-content",ref:a,className:Ae("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})]}));To.displayName=ox.displayName;function th({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-header",className:Ae("flex flex-col gap-2 text-center sm:text-left",t),...s})}function sh({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-footer",className:Ae("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s})}function ah({className:t,...s}){return e.jsx(d0,{"data-slot":"alert-dialog-title",className:Ae("text-lg font-semibold",t),...s})}function rh({className:t,...s}){return e.jsx(m0,{"data-slot":"alert-dialog-description",className:Ae("text-muted-foreground text-sm",t),...s})}function nh({className:t,...s}){return e.jsx(x0,{className:Ae(bn(),t),...s})}function ih({className:t,...s}){return e.jsx(u0,{className:Ae(bn({variant:"outline"}),t),...s})}const Ga={async list(t){return(await ve.get("/notifications",{params:t})).data},async getUnreadCount(){return(await ve.get("/notifications/unread-count")).data},async markAsRead(t){return(await ve.patch(`/notifications/${t}/read`)).data},async markAllAsRead(){return(await ve.post("/notifications/mark-all-read")).data},async delete(t){return(await ve.delete(`/notifications/${t}`)).data}},Py=async()=>(await ve.get("/notifications/subscriptions")).data.data.subscriptions;let ir=null;function Iy(){return"https://reflow-uat.royalenfield.com"}function Or(t){const s=Iy();return ir||(ir=sb(s,{withCredentials:!0,transports:["websocket","polling"],path:"/socket.io",reconnection:!0,reconnectionDelay:1e3,reconnectionAttempts:5}),ir.on("connect",()=>{}),ir.on("connect_error",a=>{console.error("[Socket] Connection error:",a.message)}),ir.on("disconnect",a=>{}),ir)}function Ol(t,s,a){a?t.emit("join:request",{requestId:s,userId:a}):t.emit("join:request",s)}function lh(t,s){t.emit("leave:request",s)}function oh(t,s){t.emit("join:user",{userId:s})}function vs({children:t,currentPage:s="dashboard",onNavigate:a,onNewRequest:r,onLogout:n}){const[i,l]=p.useState(!1),[o,c]=p.useState(!1),[d,m]=p.useState([]),[h,x]=p.useState(0),[u,g]=p.useState(!1),{user:b}=Jt(),f=p.useMemo(()=>{try{const N=st.getUserData();return(N==null?void 0:N.jobTitle)==="Dealer"}catch(N){return console.error("[PageLayout] Error checking dealer status:",N),!1}},[]),y=()=>{var N,_;try{if(b!=null&&b.displayName&&typeof b.displayName=="string"){const T=b.displayName.split(" ").filter(Boolean);return T.length>=2?`${((N=T[0])==null?void 0:N[0])||""}${((_=T[T.length-1])==null?void 0:_[0])||""}`.toUpperCase():b.displayName.substring(0,2).toUpperCase()}return b!=null&&b.email&&typeof b.email=="string"?b.email.substring(0,2).toUpperCase():"U"}catch(T){return console.error("[PageLayout] Error getting user initials:",T),"U"}},v=p.useMemo(()=>{const N=[{id:"dashboard",label:"Dashboard",icon:Nf},{id:"requests",label:"All Requests",icon:Nx,adminOnly:!1}];return f||N.push({id:"my-requests",label:"My Requests",icon:Gt}),N.push({id:"open-requests",label:"Open Requests",icon:ke},{id:"closed-requests",label:"Closed Requests",icon:Re},{id:"shared-summaries",label:"Shared Summary",icon:Sn}),N},[f]),C=()=>{l(!i)},w=async N=>{var _;try{if(N.isRead||(await Ga.markAsRead(N.notificationId),m(T=>T.map(R=>R.notificationId===N.notificationId?{...R,isRead:!0}:R)),x(T=>Math.max(0,T-1))),N.actionUrl&&a){const T=(_=N.metadata)==null?void 0:_.requestNumber;if(T){let R=`request/${T}`;(N.notificationType==="mention"||N.notificationType==="comment"||N.notificationType==="worknote")&&(R+="?tab=worknotes"),a(R)}}g(!1)}catch(T){console.error("[PageLayout] Error handling notification click:",T)}},A=async()=>{try{await Ga.markAllAsRead(),m(N=>N.map(_=>({..._,isRead:!0}))),x(0)}catch(N){console.error("[PageLayout] Error marking all as read:",N)}};return p.useEffect(()=>{const N=b==null?void 0:b.userId;if(!N)return;let _=!0;(async()=>{var j,E;try{const P=await Ga.list({page:1,limit:4,unreadOnly:!1});if(!_)return;const B=((j=P.data)==null?void 0:j.notifications)||[];m(B),x(((E=P.data)==null?void 0:E.unreadCount)||0)}catch(P){console.error("[PageLayout] Failed to fetch notifications:",P)}})();const R=Or();if(R){oh(R,N);const j=E=>{_&&(m(P=>[E.notification,...P].slice(0,4)),x(P=>P+1))};return R.on("notification:new",j),()=>{_=!1,R.off("notification:new",j)}}return()=>{_=!1}},[b]),p.useEffect(()=>{const N=()=>{window.innerWidth>=768?l(!0):l(!1)};return N(),window.addEventListener("resize",N),()=>window.removeEventListener("resize",N)},[]),e.jsxs("div",{className:"min-h-screen flex w-full bg-background",children:[i&&e.jsx("div",{className:"fixed inset-0 bg-black/50 z-40 md:hidden",onClick:()=>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:Pi,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:v.filter(N=>!N.adminOnly||(b==null?void 0:b.role)==="ADMIN").map(N=>e.jsxs("button",{onClick:()=>{N.id==="admin/templates"?a==null||a("admin/templates"):a==null||a(N.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===N.id?"bg-re-green text-white font-medium":"text-gray-300 hover:bg-gray-900 hover:text-white"}`,children:[e.jsx(N.icon,{className:"w-4 h-4 shrink-0"}),e.jsx("span",{className:"truncate",children:N.label})]},N.id))}),!f&&e.jsx("div",{className:"mt-6 pt-6 border-t border-gray-800 px-3",children:e.jsxs(F,{onClick:r,className:"w-full bg-re-green hover:bg-re-green/90 text-white text-sm font-medium",size:"sm",children:[e.jsx(gs,{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(F,{variant:"ghost",size:"icon",onClick:C,className:"shrink-0 h-10 w-10 sidebar-toggle",children:i?e.jsx(wf,{className:"w-5 h-5 text-gray-600"}):e.jsx(Cf,{className:"w-5 h-5 text-gray-600"})})}),e.jsxs("div",{className:"flex items-center gap-4 shrink-0",children:[!f&&e.jsxs(F,{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(gs,{className:"w-4 h-4"}),"New Request"]}),e.jsxs(gm,{open:u,onOpenChange:g,children:[e.jsx(fm,{asChild:!0,children:e.jsxs(F,{variant:"ghost",size:"icon",className:"relative shrink-0 h-10 w-10",children:[e.jsx(aa,{className:"w-5 h-5"}),h>0&&e.jsx(oe,{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:h>9?"9+":h})]})}),e.jsxs(bm,{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"}),h>0&&e.jsx(F,{variant:"ghost",size:"sm",className:"text-xs text-blue-600 hover:text-blue-700 h-auto p-1",onClick:N=>{N.stopPropagation(),A()},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(aa,{className:"w-12 h-12 text-gray-300 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-gray-500",children:"No notifications yet"})]}):e.jsx("div",{className:"divide-y",children:d.map(N=>e.jsx("div",{className:`p-3 hover:bg-gray-50 cursor-pointer transition-colors ${N.isRead?"":"bg-blue-50"}`,onClick:()=>w(N),children:e.jsxs("div",{className:"flex gap-2",children:[!N.isRead&&e.jsx("div",{className:"w-2 h-2 rounded-full bg-blue-600 mt-1.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`text-sm ${N.isRead?"font-medium":"font-semibold"}`,children:N.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-2",children:N.message}),e.jsx("p",{className:"text-xs text-gray-400 mt-1",children:fx(new Date(N.createdAt),{addSuffix:!0})})]})]})},N.notificationId))})}),d.length>0&&e.jsx("div",{className:"p-2 border-t",children:e.jsx(F,{variant:"ghost",className:"w-full text-sm text-blue-600 hover:text-blue-700",onClick:()=>{g(!1),a==null||a("notifications")},children:"View all notifications"})})]})]}),e.jsxs(gm,{children:[e.jsx(fm,{asChild:!0,children:e.jsxs(ts,{className:"cursor-pointer shrink-0 h-10 w-10",children:[e.jsx(Ii,{src:(b==null?void 0:b.picture)||""}),e.jsx(ss,{className:"bg-re-green text-white text-sm",children:y()})]})}),e.jsxs(bm,{align:"end",children:[e.jsxs(qi,{onClick:()=>a==null?void 0:a("profile"),children:[e.jsx(Gt,{className:"w-4 h-4 mr-2"}),"Profile"]}),e.jsxs(qi,{onClick:()=>a==null?void 0:a("settings"),children:[e.jsx(Ya,{className:"w-4 h-4 mr-2"}),"Settings"]}),e.jsxs(qi,{onClick:()=>c(!0),className:"text-red-600 focus:text-red-600",children:[e.jsx(Wi,{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(qx,{open:o,onOpenChange:c,children:e.jsxs(To,{children:[e.jsxs(th,{children:[e.jsxs(ah,{className:"flex items-center gap-2",children:[e.jsx(Wi,{className:"w-5 h-5 text-red-600"}),"Confirm Logout"]}),e.jsx(rh,{className:"pt-2",children:"Are you sure you want to logout? You will need to sign in again to access your account."})]}),e.jsxs(sh,{children:[e.jsx(ih,{onClick:()=>c(!1),children:"Cancel"}),e.jsxs(nh,{onClick:async()=>{if(c(!1),n)try{await n()}catch(N){console.error("🔴 Error calling onLogout:",N)}else console.error("🔴 ERROR: onLogout is undefined!")},className:"bg-red-600 hover:bg-red-700 text-white focus:ring-red-600",children:[e.jsx(Wi,{className:"w-4 h-4 mr-2"}),"Logout"]})]})]})})]})}const Tn=()=>Rb(),Yr=Ib,Ey=()=>{try{const t=localStorage.getItem("dashboard_viewAsUser");return t?JSON.parse(t):!1}catch{return!1}},Fy={viewAsUser:Ey()},ch=Gr({name:"dashboard",initialState:Fy,reducers:{setViewAsUser:(t,s)=>{t.viewAsUser=s.payload,localStorage.setItem("dashboard_viewAsUser",JSON.stringify(s.payload))}}}),{setViewAsUser:_y}=ch.actions;function Ly(){const[t,s]=p.useState("all"),[a,r]=p.useState(void 0),[n,i]=p.useState(void 0),[l,o]=p.useState(!1),c=p.useCallback(h=>{const x=h;s(x),x!=="custom"?(r(void 0),i(void 0),o(!1)):o(!0)},[]),d=p.useCallback(h=>{if(a&&n){if(a>n){const x=a;r(n),i(x),h(n,x)}else h(a,n);o(!1)}},[a,n]),m=p.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 My(){const[t,s]=p.useState({page:1,totalPages:1,totalRecords:0}),[a,r]=p.useState({page:1,totalPages:1,totalRecords:0}),[n,i]=p.useState({page:1,totalPages:1,totalRecords:0}),[l,o]=p.useState({page:1,totalPages:1,totalRecords:0}),c=p.useCallback((f,y,v)=>{s({page:f,totalPages:y,totalRecords:v})},[]),d=p.useCallback((f,y,v)=>{r({page:f,totalPages:y,totalRecords:v})},[]),m=p.useCallback((f,y,v)=>{i({page:f,totalPages:y,totalRecords:v})},[]),h=p.useCallback((f,y,v)=>{o({page:f,totalPages:y,totalRecords:v})},[]),x=p.useCallback((f,y)=>{f>=1&&f<=t.totalPages&&(s(v=>({...v,page:f})),y(f))},[t.totalPages]),u=p.useCallback((f,y)=>{f>=1&&f<=a.totalPages&&(r(v=>({...v,page:f})),y(f))},[a.totalPages]),g=p.useCallback((f,y)=>{f>=1&&f<=n.totalPages&&(i(v=>({...v,page:f})),y(f))},[n.totalPages]),b=p.useCallback((f,y)=>{f>=1&&f<=l.totalPages&&(o(v=>({...v,page:f})),y(f))},[l.totalPages]);return{activity:t,critical:a,deadlines:n,approver:l,updateActivityPagination:c,updateCriticalPagination:d,updateDeadlinesPagination:m,updateApproverPagination:h,handleActivityPageChange:x,handleCriticalPageChange:u,handleDeadlinesPageChange:g,handleApproverPageChange:b}}class $y{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 ve.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,h,x,u){try{const g={dateRange:s};return s==="custom"&&a&&r&&(g.startDate=a,g.endDate=r),n&&n!=="all"&&(g.status=n),i&&i!=="all"&&(g.priority=i),l&&l!=="all"&&(g.templateType=l),o&&o!=="all"&&(g.department=o),c&&c!=="all"&&(g.initiator=c),d&&d!=="all"&&(g.approver=d),m&&(g.approverType=m),h&&(g.search=h),x&&x!=="all"&&(g.slaCompliance=x),u&&(g.viewAsUser="true"),(await ve.get("/dashboard/stats/requests",{params:g})).data.data}catch(g){throw console.error("Failed to fetch request stats:",g),g}}async getTATEfficiency(s){try{return(await ve.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 ve.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 ve.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 ve.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 ve.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 ve.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 ve.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 ve.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 ve.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 ve.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 ve.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 ve.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 h=await ve.get("/dashboard/reports/activity-log",{params:m});return{activities:h.data.data,pagination:h.data.pagination}}catch(m){throw console.error("Failed to fetch activity log report:",m),m}}async getDepartments(){try{return(await ve.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 ve.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 ve.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 h={approverId:s,page:a,limit:r};n&&(h.dateRange=n),n==="custom"&&i&&l&&(h.startDate=i.toISOString(),h.endDate=l.toISOString()),o&&(h.status=o),c&&(h.priority=c),d&&(h.slaCompliance=d),m&&(h.search=m);const x=await ve.get("/dashboard/requests/by-approver",{params:h});return{requests:x.data.data,pagination:x.data.pagination}}catch(h){throw console.error("Failed to fetch requests by approver:",h),h}}}const Dt=new $y;function Oy({isAdmin:t,viewAsUser:s=!1,userId:a,dateRange:r,customStartDate:n,customEndDate:i,onPaginationUpdate:l}){const[o,c]=p.useState(null),[d,m]=p.useState([]),[h,x]=p.useState([]),[u,g]=p.useState([]),[b,f]=p.useState([]),[y,v]=p.useState([]),[C,w]=p.useState(null),[A,N]=p.useState([]),[_,T]=p.useState(!0),[R,j]=p.useState(!1),E=p.useRef(l);E.current=l;const P=p.useCallback(async(D=!1)=>{try{D?j(!0):T(!0);const S=[Dt.getKPIs(r,n,i,s),Dt.getRecentActivity(1,10,s),Dt.getCriticalRequests(1,10,s),Dt.getUpcomingDeadlines(1,10,s)],O=!t&&a?Dt.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,I=t?[Dt.getDepartmentStats(r,n,i),Dt.getPriorityDistribution(r,n,i),Dt.getAIRemarkUtilization(r,n,i),Dt.getApproverPerformance(r,1,10,n,i)]:[],[M,W,G]=await Promise.all([Promise.all(S),O,Promise.all(I)]),re=M[0],te=M[1],$=M[2],z=M[3];if(!t&&W&&(re.requestVolume=W),c(re),m(te.activities),E.current.activity(te.pagination.currentPage,te.pagination.totalPages,te.pagination.totalRecords),x($.criticalRequests),E.current.critical($.pagination.currentPage,$.pagination.totalPages,$.pagination.totalRecords),v(z.deadlines),E.current.deadlines(z.pagination.currentPage,z.pagination.totalPages,z.pagination.totalRecords),t&&G.length>=4){const H=G[0],je=G[1],le=G[2],ue=G[3];g(H),f(je),w(le),N(ue.performance),E.current.approver(ue.pagination.currentPage,ue.pagination.totalPages,ue.pagination.totalRecords)}else t||(g([]),f([]),w(null),N([]))}catch(S){console.error("Failed to fetch dashboard data:",S)}finally{T(!1),j(!1)}},[t,s,a,r,n,i]),B=p.useCallback(async(D=1)=>{try{const S=await Dt.getRecentActivity(D,10,s);m(S.activities),E.current.activity(S.pagination.currentPage,S.pagination.totalPages,S.pagination.totalRecords)}catch(S){console.error("Failed to fetch recent activities:",S)}},[s]),k=p.useCallback(async(D=1)=>{try{const S=await Dt.getCriticalRequests(D,10,s);x(S.criticalRequests),E.current.critical(S.pagination.currentPage,S.pagination.totalPages,S.pagination.totalRecords)}catch(S){console.error("Failed to fetch critical requests:",S)}},[s]),L=p.useCallback(async(D=1)=>{try{const S=await Dt.getUpcomingDeadlines(D,10,s);v(S.deadlines),E.current.deadlines(S.pagination.currentPage,S.pagination.totalPages,S.pagination.totalRecords)}catch(S){console.error("Failed to fetch upcoming deadlines:",S)}},[s]),V=p.useCallback(async(D=1)=>{try{const S=await Dt.getApproverPerformance(r,D,10,n,i);N(S.performance),E.current.approver(S.pagination.currentPage,S.pagination.totalPages,S.pagination.totalRecords)}catch(S){console.error("Failed to fetch approver performance:",S)}},[r,n,i]);return{kpis:o,recentActivity:d,criticalRequests:h,departmentStats:u,priorityDistribution:b,upcomingDeadlines:y,aiRemarkUtilization:C,approverPerformance:A,loading:_,refreshing:R,fetchDashboardData:P,fetchRecentActivities:B,fetchCriticalRequests:k,fetchUpcomingDeadlines:L,fetchApproverPerformance:V}}const Aa={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 Uy{constructor(){Vi(this,"config",null);Vi(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 ve.get("/config"),r=((s=a.data)==null?void 0:s.data)||a.data;return{...Aa,...r,workingHours:{...Aa.workingHours,...r.workingHours},tat:{...Aa.tat,...r.tat},upload:{...Aa.upload,...r.upload},workflow:{...Aa.workflow,...r.workflow},workNotes:{...Aa.workNotes,...r.workNotes},features:{...Aa.features,...r.features},ui:{...Aa.ui,...r.ui}}}catch(a){return console.error("[ConfigService] ⚠️ Failed to fetch config from server, using defaults:",a),Aa}}async refreshConfig(){return this.config=null,this.loading=null,this.getConfig()}getCachedConfig(){return this.config}isLoaded(){return this.config!==null}}const By=new Uy;let Vy=9,zy=18,Hy=1,Gy=5,ym=!1;async function Wy(){if(!ym)try{const t=await By.getConfig();Vy=t.workingHours.START_HOUR,zy=t.workingHours.END_HOUR,Hy=t.workingHours.START_DAY,Gy=t.workingHours.END_DAY,ym=!0}catch{console.warn("[SLA Tracker] ⚠️ Using default working hours (9 AM - 6 PM)")}}Wy().catch(()=>{});function Mt(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 Yy(t,s,a){const r=[];let n=1,i=!0;const l=100;for(;i&&n<=l;){const x=await Dt.getApproverPerformance(t,n,100,s,a);x.performance&&x.performance.length>0?(r.push(...x.performance),n++,i=n<=x.pagination.totalPages):i=!1}const o=[["Approver Name","Total Approved","TAT Compliance (%)","Avg Response Time","Pending Count"].join(",")];r.forEach(x=>{const u=[`"${(x.approverName||"Unknown").replace(/"/g,'""')}"`,x.totalApproved||0,x.tatCompliancePercent||0,Mt(x.avgResponseHours),x.pendingCount||0];o.push(u.join(","))});const c=o.join(`
`),d=new Blob([c],{type:"text/csv;charset=utf-8;"}),m=document.createElement("a"),h=URL.createObjectURL(d);m.setAttribute("href",h),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(h)}async function Ky(t,s,a){const r=await Dt.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 Xy(){const[t,s]=p.useState(!1),[a,r]=p.useState(!1),n=p.useCallback(async(l,o,c)=>{try{s(!0),await Ky(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=p.useCallback(async(l,o,c)=>{try{r(!0),await Yy(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 mn({className:t,...s}){return e.jsx(h0,{"data-slot":"switch",className:Ae("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(p0,{"data-slot":"switch-thumb",className:Ae("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 ne({className:t,...s}){return e.jsx(g0,{"data-slot":"label",className:Ae("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 Zy({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(se,{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(ae,{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(xo,{className:`w-3 h-3 sm:w-3.5 sm:h-3.5 ${a?"text-gray-300":"text-red-600"}`}),e.jsx(ne,{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(mn,{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(Gt,{className:`w-3 h-3 sm:w-3.5 sm:h-3.5 ${a?"text-red-600":"text-gray-300"}`}),e.jsx(ne,{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(F,{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 Ke({...t}){return e.jsx(f0,{"data-slot":"select",...t})}function Xe({...t}){return e.jsx(v0,{"data-slot":"select-value",...t})}function Ze({className:t,size:s="default",children:a,...r}){return e.jsxs(b0,{"data-slot":"select-trigger","data-size":s,className:Ae("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(y0,{asChild:!0,children:e.jsx(ho,{className:"size-4 opacity-50"})})]})}function Je({className:t,children:s,position:a="popper",...r}){return e.jsx(j0,{children:e.jsxs(N0,{"data-slot":"select-content",className:Ae("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(Jy,{}),e.jsx(w0,{className:Ae("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(Qy,{})]})})}function Y({className:t,children:s,...a}){return e.jsxs(C0,{"data-slot":"select-item",className:Ae("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(S0,{children:e.jsx(Ra,{className:"size-4"})})}),e.jsx(A0,{children:s})]})}function Jy({className:t,...s}){return e.jsx(T0,{"data-slot":"select-scroll-up-button",className:Ae("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(wx,{className:"size-4"})})}function Qy({className:t,...s}){return e.jsx(k0,{"data-slot":"select-scroll-down-button",className:Ae("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(ho,{className:"size-4"})})}function Ps({className:t,orientation:s="horizontal",decorative:a=!0,...r}){return e.jsx(R0,{"data-slot":"separator-root",decorative:a,orientation:s,className:Ae("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 Xs({...t}){return e.jsx(D0,{"data-slot":"popover",...t})}function Zs({...t}){return e.jsx(P0,{"data-slot":"popover-trigger",...t})}function Js({className:t,align:s="center",sideOffset:a=4,...r}){return e.jsx(I0,{children:e.jsx(E0,{"data-slot":"popover-content",align:s,sideOffset:a,className:Ae("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})})}var tt=function(){return tt=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},tt.apply(this,arguments)};function qy(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 dh(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 kn(t){return t.mode==="multiple"}function Rn(t){return t.mode==="range"}function Ei(t){return t.mode==="single"}var ev={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 tv(t,s){return Ge(t,"LLLL y",s)}function sv(t,s){return Ge(t,"d",s)}function av(t,s){return Ge(t,"LLLL",s)}function rv(t){return"".concat(t)}function nv(t,s){return Ge(t,"cccccc",s)}function iv(t,s){return Ge(t,"yyyy",s)}var lv=Object.freeze({__proto__:null,formatCaption:tv,formatDay:sv,formatMonthCaption:av,formatWeekNumber:rv,formatWeekdayName:nv,formatYearCaption:iv}),ov=function(t,s,a){return Ge(t,"do MMMM (EEEE)",a)},cv=function(){return"Month: "},dv=function(){return"Go to next month"},mv=function(){return"Go to previous month"},uv=function(t,s){return Ge(t,"cccc",s)},xv=function(t){return"Week n. ".concat(t)},hv=function(){return"Year: "},pv=Object.freeze({__proto__:null,labelDay:ov,labelMonthDropdown:cv,labelNext:dv,labelPrevious:mv,labelWeekNumber:xv,labelWeekday:uv,labelYearDropdown:hv});function gv(){var t="buttons",s=ev,a=of,r={},n={},i=1,l={},o=new Date;return{captionLayout:t,classNames:s,formatters:lv,labels:pv,locale:a,modifiersClassNames:r,modifiers:n,numberOfMonths:i,styles:l,today:o,mode:"default"}}function fv(t){var s=t.fromYear,a=t.toYear,r=t.fromMonth,n=t.toMonth,i=t.fromDate,l=t.toDate;return r?i=Ys(r):s&&(i=new Date(s,0,1)),n?l=oo(n):a&&(l=new Date(a,11,31)),{fromDate:i?sm(i):void 0,toDate:l?sm(l):void 0}}var mh=p.createContext(void 0);function bv(t){var s,a=t.initialProps,r=gv(),n=fv(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;(Ei(a)||kn(a)||Rn(a))&&(c=a.onSelect);var d=tt(tt(tt({},r),a),{captionLayout:o,classNames:tt(tt({},r.classNames),a.classNames),components:tt({},a.components),formatters:tt(tt({},r.formatters),a.formatters),fromDate:i,labels:tt(tt({},r.labels),a.labels),mode:a.mode||r.mode,modifiers:tt(tt({},r.modifiers),a.modifiers),modifiersClassNames:tt(tt({},r.modifiersClassNames),a.modifiersClassNames),onSelect:c,styles:tt(tt({},r.styles),a.styles),toDate:l});return e.jsx(mh.Provider,{value:d,children:t.children})}function Et(){var t=p.useContext(mh);if(!t)throw new Error("useDayPicker must be used within a DayPickerProvider.");return t}function uh(t){var s=Et(),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 yv(t){return e.jsx("svg",tt({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 xh(t){var s,a,r=t.onChange,n=t.value,i=t.children,l=t.caption,o=t.className,c=t.style,d=Et(),m=(a=(s=d.components)===null||s===void 0?void 0:s.IconDropdown)!==null&&a!==void 0?a:yv;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 vv(t){var s,a=Et(),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 h=[];if(hf(r,n))for(var x=Ys(r),u=r.getMonth();u<=n.getMonth();u++)h.push(Hi(x,u));else for(var x=Ys(new Date),u=0;u<=11;u++)h.push(Hi(x,u));var g=function(f){var y=Number(f.target.value),v=Hi(Ys(t.displayMonth),y);t.onChange(v)},b=(s=d==null?void 0:d.Dropdown)!==null&&s!==void 0?s:xh;return e.jsx(b,{name:"months","aria-label":m(),className:c.dropdown_month,style:i.dropdown_month,onChange:g,value:t.displayMonth.getMonth(),caption:o(t.displayMonth,{locale:l}),children:h.map(function(f){return e.jsx("option",{value:f.getMonth(),children:o(f,{locale:l})},f.getMonth())})})}function jv(t){var s,a=t.displayMonth,r=Et(),n=r.fromDate,i=r.toDate,l=r.locale,o=r.styles,c=r.classNames,d=r.components,m=r.formatters.formatYearCaption,h=r.labels.labelYearDropdown,x=[];if(!n)return e.jsx(e.Fragment,{});if(!i)return e.jsx(e.Fragment,{});for(var u=n.getFullYear(),g=i.getFullYear(),b=u;b<=g;b++)x.push(am(pf(new Date),b));var f=function(v){var C=am(Ys(a),Number(v.target.value));t.onChange(C)},y=(s=d==null?void 0:d.Dropdown)!==null&&s!==void 0?s:xh;return e.jsx(y,{name:"years","aria-label":h(),className:c.dropdown_year,style:o.dropdown_year,onChange:f,value:a.getFullYear(),caption:m(a,{locale:l}),children:x.map(function(v){return e.jsx("option",{value:v.getFullYear(),children:m(v,{locale:l})},v.getFullYear())})})}function Nv(t,s){var a=p.useState(t),r=a[0],n=a[1],i=s===void 0?r:s;return[i,n]}function wv(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&&fn(i,n)<0){var d=-1*(c-1);n=wa(i,d)}return l&&fn(n,l)<0&&(n=l),Ys(n)}function Cv(){var t=Et(),s=wv(t),a=Nv(s,t.month),r=a[0],n=a[1],i=function(l){var o;if(!t.disableNavigation){var c=Ys(l);n(c),(o=t.onMonthChange)===null||o===void 0||o.call(t,c)}};return[r,i]}function Sv(t,s){for(var a=s.reverseMonths,r=s.numberOfMonths,n=Ys(t),i=Ys(wa(n,r)),l=fn(i,n),o=[],c=0;c<l;c++){var d=wa(n,c);o.push(d)}return a&&(o=o.reverse()),o}function Av(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=Ys(t);if(!a)return wa(o,l);var c=fn(a,t);if(!(c<i))return wa(o,l)}}function Tv(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=Ys(t);if(!a)return wa(o,-l);var c=fn(o,a);if(!(c<=0))return wa(o,-l)}}var hh=p.createContext(void 0);function kv(t){var s=Et(),a=Cv(),r=a[0],n=a[1],i=Sv(r,s),l=Av(r,s),o=Tv(r,s),c=function(h){return i.some(function(x){return co(h,x)})},d=function(h,x){c(h)||(x&&bx(h,x)?n(wa(h,1+s.numberOfMonths*-1)):n(h))},m={currentMonth:r,displayMonths:i,goToMonth:n,goToDate:d,previousMonth:o,nextMonth:l,isDateDisplayed:c};return e.jsx(hh.Provider,{value:m,children:t.children})}function Dn(){var t=p.useContext(hh);if(!t)throw new Error("useNavigation must be used within a NavigationProvider");return t}function vm(t){var s,a=Et(),r=a.classNames,n=a.styles,i=a.components,l=Dn().goToMonth,o=function(m){l(wa(m,t.displayIndex?-t.displayIndex:0))},c=(s=i==null?void 0:i.CaptionLabel)!==null&&s!==void 0?s:uh,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(vv,{onChange:o,displayMonth:t.displayMonth}),e.jsx(jv,{onChange:o,displayMonth:t.displayMonth})]})}function Rv(t){return e.jsx("svg",tt({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 Dv(t){return e.jsx("svg",tt({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 di=p.forwardRef(function(t,s){var a=Et(),r=a.classNames,n=a.styles,i=[r.button_reset,r.button];t.className&&i.push(t.className);var l=i.join(" "),o=tt(tt({},n.button_reset),n.button);return t.style&&Object.assign(o,t.style),e.jsx("button",tt({},t,{ref:s,type:"button",className:l,style:o}))});function Pv(t){var s,a,r=Et(),n=r.dir,i=r.locale,l=r.classNames,o=r.styles,c=r.labels,d=c.labelPrevious,m=c.labelNext,h=r.components;if(!t.nextMonth&&!t.previousMonth)return e.jsx(e.Fragment,{});var x=d(t.previousMonth,{locale:i}),u=[l.nav_button,l.nav_button_previous].join(" "),g=m(t.nextMonth,{locale:i}),b=[l.nav_button,l.nav_button_next].join(" "),f=(s=h==null?void 0:h.IconRight)!==null&&s!==void 0?s:Dv,y=(a=h==null?void 0:h.IconLeft)!==null&&a!==void 0?a:Rv;return e.jsxs("div",{className:l.nav,style:o.nav,children:[!t.hidePrevious&&e.jsx(di,{name:"previous-month","aria-label":x,className:u,style:o.nav_button_previous,disabled:!t.previousMonth,onClick:t.onPreviousClick,children:n==="rtl"?e.jsx(f,{className:l.nav_icon,style:o.nav_icon}):e.jsx(y,{className:l.nav_icon,style:o.nav_icon})}),!t.hideNext&&e.jsx(di,{name:"next-month","aria-label":g,className:b,style:o.nav_button_next,disabled:!t.nextMonth,onClick:t.onNextClick,children:n==="rtl"?e.jsx(y,{className:l.nav_icon,style:o.nav_icon}):e.jsx(f,{className:l.nav_icon,style:o.nav_icon})})]})}function jm(t){var s=Et().numberOfMonths,a=Dn(),r=a.previousMonth,n=a.nextMonth,i=a.goToMonth,l=a.displayMonths,o=l.findIndex(function(g){return co(t.displayMonth,g)}),c=o===0,d=o===l.length-1,m=s>1&&(c||!d),h=s>1&&(d||!c),x=function(){r&&i(r)},u=function(){n&&i(n)};return e.jsx(Pv,{displayMonth:t.displayMonth,hideNext:m,hidePrevious:h,nextMonth:n,previousMonth:r,onPreviousClick:x,onNextClick:u})}function Iv(t){var s,a=Et(),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:uh,d;return n?d=e.jsx(c,{id:t.id,displayMonth:t.displayMonth}):l==="dropdown"?d=e.jsx(vm,{displayMonth:t.displayMonth,id:t.id}):l==="dropdown-buttons"?d=e.jsxs(e.Fragment,{children:[e.jsx(vm,{displayMonth:t.displayMonth,displayIndex:t.displayIndex,id:t.id}),e.jsx(jm,{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(jm,{displayMonth:t.displayMonth,id:t.id})]}),e.jsx("div",{className:r.caption,style:i.caption,children:d})}function Ev(t){var s=Et(),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 Fv(t,s,a){for(var r=a?mo(new Date):uo(new Date,{locale:t,weekStartsOn:s}),n=[],i=0;i<7;i++){var l=Hs(r,i);n.push(l)}return n}function _v(){var t=Et(),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=Fv(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,h){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})},h)})]})}function Lv(){var t,s=Et(),a=s.classNames,r=s.styles,n=s.components,i=(t=n==null?void 0:n.HeadRow)!==null&&t!==void 0?t:_v;return e.jsx("thead",{style:r.head,className:a.head,children:e.jsx(i,{})})}function Mv(t){var s=Et(),a=s.locale,r=s.formatters.formatDay;return e.jsx(e.Fragment,{children:r(t.date,{locale:a})})}var ko=p.createContext(void 0);function $v(t){if(!kn(t.initialProps)){var s={selected:void 0,modifiers:{disabled:[]}};return e.jsx(ko.Provider,{value:s,children:t.children})}return e.jsx(Ov,{initialProps:t.initialProps,children:t.children})}function Ov(t){var s=t.initialProps,a=t.children,r=s.selected,n=s.min,i=s.max,l=function(d,m,h){var x,u;(x=s.onDayClick)===null||x===void 0||x.call(s,d,m,h);var g=!!(m.selected&&n&&(r==null?void 0:r.length)===n);if(!g){var b=!!(!m.selected&&i&&(r==null?void 0:r.length)===i);if(!b){var f=r?dh([],r):[];if(m.selected){var y=f.findIndex(function(v){return Os(d,v)});f.splice(y,1)}else f.push(d);(u=s.onSelect)===null||u===void 0||u.call(s,f,d,m,h)}}},o={disabled:[]};r&&o.disabled.push(function(d){var m=i&&r.length>i-1,h=r.some(function(x){return Os(x,d)});return!!(m&&!h)});var c={selected:r,onDayClick:l,modifiers:o};return e.jsx(ko.Provider,{value:c,children:a})}function Ro(){var t=p.useContext(ko);if(!t)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return t}function Uv(t,s){var a=s||{},r=a.from,n=a.to;return r&&n?Os(n,t)&&Os(r,t)?void 0:Os(n,t)?{from:n,to:void 0}:Os(r,t)?void 0:Il(r,t)?{from:t,to:n}:{from:r,to:t}:n?Il(t,n)?{from:n,to:t}:{from:t,to:n}:r?bx(t,r)?{from:t,to:r}:{from:r,to:t}:{from:t,to:void 0}}var Do=p.createContext(void 0);function Bv(t){if(!Rn(t.initialProps)){var s={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(Do.Provider,{value:s,children:t.children})}return e.jsx(Vv,{initialProps:t.initialProps,children:t.children})}function Vv(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(u,g,b){var f,y;(f=s.onDayClick)===null||f===void 0||f.call(s,u,g,b);var v=Uv(u,r);(y=s.onSelect)===null||y===void 0||y.call(s,v,u,g,b)},m={range_start:[],range_end:[],range_middle:[],disabled:[]};if(i?(m.range_start=[i],l?(m.range_end=[l],Os(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:zi(i,o-1),before:Hs(i,o-1)}),i&&l&&m.disabled.push({after:i,before:Hs(i,o-1)}),!i&&l&&m.disabled.push({after:zi(l,o-1),before:Hs(l,o-1)})),c){if(i&&!l&&(m.disabled.push({before:Hs(i,-c+1)}),m.disabled.push({after:Hs(i,c-1)})),i&&l){var h=ka(l,i)+1,x=c-h;m.disabled.push({before:zi(i,x)}),m.disabled.push({after:Hs(l,x)})}!i&&l&&(m.disabled.push({before:Hs(l,-c+1)}),m.disabled.push({after:Hs(l,c-1)}))}return e.jsx(Do.Provider,{value:{selected:r,onDayClick:d,modifiers:m},children:a})}function Po(){var t=p.useContext(Do);if(!t)throw new Error("useSelectRange must be used within a SelectRangeProvider");return t}function Kn(t){return Array.isArray(t)?dh([],t):t!==void 0?[t]:[]}function zv(t){var s={};return Object.entries(t).forEach(function(a){var r=a[0],n=a[1];s[r]=Kn(n)}),s}var pa;(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"})(pa||(pa={}));var Hv=pa.Selected,Ta=pa.Disabled,Gv=pa.Hidden,Wv=pa.Today,el=pa.RangeEnd,tl=pa.RangeMiddle,sl=pa.RangeStart,Yv=pa.Outside;function Kv(t,s,a){var r,n=(r={},r[Hv]=Kn(t.selected),r[Ta]=Kn(t.disabled),r[Gv]=Kn(t.hidden),r[Wv]=[t.today],r[el]=[],r[tl]=[],r[sl]=[],r[Yv]=[],r);return t.fromDate&&n[Ta].push({before:t.fromDate}),t.toDate&&n[Ta].push({after:t.toDate}),kn(t)?n[Ta]=n[Ta].concat(s.modifiers[Ta]):Rn(t)&&(n[Ta]=n[Ta].concat(a.modifiers[Ta]),n[sl]=a.modifiers[sl],n[tl]=a.modifiers[tl],n[el]=a.modifiers[el]),n}var ph=p.createContext(void 0);function Xv(t){var s=Et(),a=Ro(),r=Po(),n=Kv(s,a,r),i=zv(s.modifiers),l=tt(tt({},n),i);return e.jsx(ph.Provider,{value:l,children:t.children})}function gh(){var t=p.useContext(ph);if(!t)throw new Error("useModifiers must be used within a ModifiersProvider");return t}function Zv(t){return!!(t&&typeof t=="object"&&"before"in t&&"after"in t)}function Jv(t){return!!(t&&typeof t=="object"&&"from"in t)}function Qv(t){return!!(t&&typeof t=="object"&&"after"in t)}function qv(t){return!!(t&&typeof t=="object"&&"before"in t)}function ej(t){return!!(t&&typeof t=="object"&&"dayOfWeek"in t)}function tj(t,s){var a,r=s.from,n=s.to;if(r&&n){var i=ka(n,r)<0;i&&(a=[n,r],r=a[0],n=a[1]);var l=ka(t,r)>=0&&ka(n,t)>=0;return l}return n?Os(n,t):r?Os(r,t):!1}function sj(t){return jx(t)}function aj(t){return Array.isArray(t)&&t.every(jx)}function rj(t,s){return s.some(function(a){if(typeof a=="boolean")return a;if(sj(a))return Os(t,a);if(aj(a))return a.includes(t);if(Jv(a))return tj(t,a);if(ej(a))return a.dayOfWeek.includes(t.getDay());if(Zv(a)){var r=ka(a.before,t),n=ka(a.after,t),i=r>0,l=n<0,o=Il(a.before,a.after);return o?l&&i:i||l}return Qv(a)?ka(t,a.after)>0:qv(a)?ka(a.before,t)>0:typeof a=="function"?a(t):!1})}function Io(t,s,a){var r=Object.keys(s).reduce(function(i,l){var o=s[l];return rj(t,o)&&i.push(l),i},[]),n={};return r.forEach(function(i){return n[i]=!0}),a&&!co(t,a)&&(n.outside=!0),n}function nj(t,s){for(var a=Ys(t[0]),r=oo(t[t.length-1]),n,i,l=a;l<=r;){var o=Io(l,s),c=!o.disabled&&!o.hidden;if(!c){l=Hs(l,1);continue}if(o.selected)return l;o.today&&!i&&(i=l),n||(n=l),l=Hs(l,1)}return i||n}var ij=365;function fh(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,h=n.locale,x={day:Hs,week:Pl,month:wa,year:mf,startOfWeek:function(f){return n.ISOWeek?mo(f):uo(f,{locale:h,weekStartsOn:c})},endOfWeek:function(f){return n.ISOWeek?yx(f):vx(f,{locale:h,weekStartsOn:c})}},u=x[a](t,r==="after"?1:-1);r==="before"&&d?u=uf([d,u]):r==="after"&&m&&(u=xf([m,u]));var g=!0;if(i){var b=Io(u,i);g=!b.disabled&&!b.hidden}return g?u:o.count>ij?o.lastFocused:fh(u,{moveBy:a,direction:r,context:n,modifiers:i,retry:tt(tt({},o),{count:o.count+1})})}var bh=p.createContext(void 0);function lj(t){var s=Dn(),a=gh(),r=p.useState(),n=r[0],i=r[1],l=p.useState(),o=l[0],c=l[1],d=nj(s.displayMonths,a),m=n??(o&&s.isDateDisplayed(o))?o:d,h=function(){c(n),i(void 0)},x=function(f){i(f)},u=Et(),g=function(f,y){if(n){var v=fh(n,{moveBy:f,direction:y,context:u,modifiers:a});Os(n,v)||(s.goToDate(v,n),x(v))}},b={focusedDay:n,focusTarget:m,blur:h,focus:x,focusDayAfter:function(){return g("day","after")},focusDayBefore:function(){return g("day","before")},focusWeekAfter:function(){return g("week","after")},focusWeekBefore:function(){return g("week","before")},focusMonthBefore:function(){return g("month","before")},focusMonthAfter:function(){return g("month","after")},focusYearBefore:function(){return g("year","before")},focusYearAfter:function(){return g("year","after")},focusStartOfWeek:function(){return g("startOfWeek","before")},focusEndOfWeek:function(){return g("endOfWeek","after")}};return e.jsx(bh.Provider,{value:b,children:t.children})}function Eo(){var t=p.useContext(bh);if(!t)throw new Error("useFocusContext must be used within a FocusProvider");return t}function oj(t,s){var a=gh(),r=Io(t,a,s);return r}var Fo=p.createContext(void 0);function cj(t){if(!Ei(t.initialProps)){var s={selected:void 0};return e.jsx(Fo.Provider,{value:s,children:t.children})}return e.jsx(dj,{initialProps:t.initialProps,children:t.children})}function dj(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(Fo.Provider,{value:n,children:a})}function yh(){var t=p.useContext(Fo);if(!t)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return t}function mj(t,s){var a=Et(),r=yh(),n=Ro(),i=Po(),l=Eo(),o=l.focusDayAfter,c=l.focusDayBefore,d=l.focusWeekAfter,m=l.focusWeekBefore,h=l.blur,x=l.focus,u=l.focusMonthBefore,g=l.focusMonthAfter,b=l.focusYearBefore,f=l.focusYearAfter,y=l.focusStartOfWeek,v=l.focusEndOfWeek,C=function(D){var S,O,I,M;Ei(a)?(S=r.onDayClick)===null||S===void 0||S.call(r,t,s,D):kn(a)?(O=n.onDayClick)===null||O===void 0||O.call(n,t,s,D):Rn(a)?(I=i.onDayClick)===null||I===void 0||I.call(i,t,s,D):(M=a.onDayClick)===null||M===void 0||M.call(a,t,s,D)},w=function(D){var S;x(t),(S=a.onDayFocus)===null||S===void 0||S.call(a,t,s,D)},A=function(D){var S;h(),(S=a.onDayBlur)===null||S===void 0||S.call(a,t,s,D)},N=function(D){var S;(S=a.onDayMouseEnter)===null||S===void 0||S.call(a,t,s,D)},_=function(D){var S;(S=a.onDayMouseLeave)===null||S===void 0||S.call(a,t,s,D)},T=function(D){var S;(S=a.onDayPointerEnter)===null||S===void 0||S.call(a,t,s,D)},R=function(D){var S;(S=a.onDayPointerLeave)===null||S===void 0||S.call(a,t,s,D)},j=function(D){var S;(S=a.onDayTouchCancel)===null||S===void 0||S.call(a,t,s,D)},E=function(D){var S;(S=a.onDayTouchEnd)===null||S===void 0||S.call(a,t,s,D)},P=function(D){var S;(S=a.onDayTouchMove)===null||S===void 0||S.call(a,t,s,D)},B=function(D){var S;(S=a.onDayTouchStart)===null||S===void 0||S.call(a,t,s,D)},k=function(D){var S;(S=a.onDayKeyUp)===null||S===void 0||S.call(a,t,s,D)},L=function(D){var S;switch(D.key){case"ArrowLeft":D.preventDefault(),D.stopPropagation(),a.dir==="rtl"?o():c();break;case"ArrowRight":D.preventDefault(),D.stopPropagation(),a.dir==="rtl"?c():o();break;case"ArrowDown":D.preventDefault(),D.stopPropagation(),d();break;case"ArrowUp":D.preventDefault(),D.stopPropagation(),m();break;case"PageUp":D.preventDefault(),D.stopPropagation(),D.shiftKey?b():u();break;case"PageDown":D.preventDefault(),D.stopPropagation(),D.shiftKey?f():g();break;case"Home":D.preventDefault(),D.stopPropagation(),y();break;case"End":D.preventDefault(),D.stopPropagation(),v();break}(S=a.onDayKeyDown)===null||S===void 0||S.call(a,t,s,D)},V={onClick:C,onFocus:w,onBlur:A,onKeyDown:L,onKeyUp:k,onMouseEnter:N,onMouseLeave:_,onPointerEnter:T,onPointerLeave:R,onTouchCancel:j,onTouchEnd:E,onTouchMove:P,onTouchStart:B};return V}function uj(){var t=Et(),s=yh(),a=Ro(),r=Po(),n=Ei(t)?s.selected:kn(t)?a.selected:Rn(t)?r.selected:void 0;return n}function xj(t){return Object.values(pa).includes(t)}function hj(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(xj(r)){var i=t.classNames["day_".concat(r)];i&&a.push(i)}}),a}function pj(t,s){var a=tt({},t.styles.day);return Object.keys(s).forEach(function(r){var n;a=tt(tt({},a),(n=t.modifiersStyles)===null||n===void 0?void 0:n[r])}),a}function gj(t,s,a){var r,n,i,l=Et(),o=Eo(),c=oj(t,s),d=mj(t,c),m=uj(),h=!!(l.onDayClick||l.mode!=="default");p.useEffect(function(){var N;c.outside||o.focusedDay&&h&&Os(o.focusedDay,t)&&((N=a.current)===null||N===void 0||N.focus())},[o.focusedDay,t,a,h,c.outside]);var x=hj(l,c).join(" "),u=pj(l,c),g=!!(c.outside&&!l.showOutsideDays||c.hidden),b=(i=(n=l.components)===null||n===void 0?void 0:n.DayContent)!==null&&i!==void 0?i:Mv,f=e.jsx(b,{date:t,displayMonth:s,activeModifiers:c}),y={style:u,className:x,children:f,role:"gridcell"},v=o.focusTarget&&Os(o.focusTarget,t)&&!c.outside,C=o.focusedDay&&Os(o.focusedDay,t),w=tt(tt(tt({},y),(r={disabled:c.disabled,role:"gridcell"},r["aria-selected"]=c.selected,r.tabIndex=C||v?0:-1,r)),d),A={isButton:h,isHidden:g,activeModifiers:c,selectedDays:m,buttonProps:w,divProps:y};return A}function fj(t){var s=p.useRef(null),a=gj(t.date,t.displayMonth,s);return a.isHidden?e.jsx("div",{role:"gridcell"}):a.isButton?e.jsx(di,tt({name:"day",ref:s},a.buttonProps)):e.jsx("div",tt({},a.divProps))}function bj(t){var s=t.number,a=t.dates,r=Et(),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 h=c(Number(s),{locale:o}),x=function(u){n(s,a,u)};return e.jsx(di,{name:"week-number","aria-label":h,className:l.weeknumber,style:i.weeknumber,onClick:x,children:m})}function yj(t){var s,a,r=Et(),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:fj,d=(a=o==null?void 0:o.WeekNumber)!==null&&a!==void 0?a:bj,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(h){return e.jsx("td",{className:i.cell,style:n.cell,role:"presentation",children:e.jsx(c,{displayMonth:t.displayMonth,date:h})},df(h))})]})}function Nm(t,s,a){for(var r=a!=null&&a.ISOWeek?yx(s):vx(s,a),n=a!=null&&a.ISOWeek?mo(t):uo(t,a),i=ka(r,n),l=[],o=0;o<=i;o++)l.push(Hs(n,o));var c=l.reduce(function(d,m){var h=a!=null&&a.ISOWeek?gf(m):ff(m,a),x=d.find(function(u){return u.weekNumber===h});return x?(x.dates.push(m),d):(d.push({weekNumber:h,dates:[m]}),d)},[]);return c}function vj(t,s){var a=Nm(Ys(t),oo(t),s);if(s!=null&&s.useFixedWeeks){var r=cf(t,s);if(r<6){var n=a[a.length-1],i=n.dates[n.dates.length-1],l=Pl(i,6-r),o=Nm(Pl(i,1),l,s);a.push.apply(a,o)}}return a}function jj(t){var s,a,r,n=Et(),i=n.locale,l=n.classNames,o=n.styles,c=n.hideHead,d=n.fixedWeeks,m=n.components,h=n.weekStartsOn,x=n.firstWeekContainsDate,u=n.ISOWeek,g=vj(t.displayMonth,{useFixedWeeks:!!d,ISOWeek:u,locale:i,weekStartsOn:h,firstWeekContainsDate:x}),b=(s=m==null?void 0:m.Head)!==null&&s!==void 0?s:Lv,f=(a=m==null?void 0:m.Row)!==null&&a!==void 0?a:yj,y=(r=m==null?void 0:m.Footer)!==null&&r!==void 0?r:Ev;return e.jsxs("table",{id:t.id,className:l.table,style:o.table,role:"grid","aria-labelledby":t["aria-labelledby"],children:[!c&&e.jsx(b,{}),e.jsx("tbody",{className:l.tbody,style:o.tbody,children:g.map(function(v){return e.jsx(f,{displayMonth:t.displayMonth,dates:v.dates,weekNumber:v.weekNumber},v.weekNumber)})}),e.jsx(y,{displayMonth:t.displayMonth})]})}function Nj(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var wj=Nj()?p.useLayoutEffect:p.useEffect,al=!1,Cj=0;function wm(){return"react-day-picker-".concat(++Cj)}function Sj(t){var s,a=t??(al?wm():null),r=p.useState(a),n=r[0],i=r[1];return wj(function(){n===null&&i(wm())},[]),p.useEffect(function(){al===!1&&(al=!0)},[]),(s=t??n)!==null&&s!==void 0?s:void 0}function Aj(t){var s,a,r=Et(),n=r.dir,i=r.classNames,l=r.styles,o=r.components,c=Dn().displayMonths,d=Sj(r.id?"".concat(r.id,"-").concat(t.displayIndex):void 0),m=r.id?"".concat(r.id,"-grid-").concat(t.displayIndex):void 0,h=[i.month],x=l.month,u=t.displayIndex===0,g=t.displayIndex===c.length-1,b=!u&&!g;n==="rtl"&&(s=[u,g],g=s[0],u=s[1]),u&&(h.push(i.caption_start),x=tt(tt({},x),l.caption_start)),g&&(h.push(i.caption_end),x=tt(tt({},x),l.caption_end)),b&&(h.push(i.caption_between),x=tt(tt({},x),l.caption_between));var f=(a=o==null?void 0:o.Caption)!==null&&a!==void 0?a:Iv;return e.jsxs("div",{className:h.join(" "),style:x,children:[e.jsx(f,{id:d,displayMonth:t.displayMonth,displayIndex:t.displayIndex}),e.jsx(jj,{id:m,"aria-labelledby":d,displayMonth:t.displayMonth})]},t.displayIndex)}function Tj(t){var s=Et(),a=s.classNames,r=s.styles;return e.jsx("div",{className:a.months,style:r.months,children:t.children})}function kj(t){var s,a,r=t.initialProps,n=Et(),i=Eo(),l=Dn(),o=p.useState(!1),c=o[0],d=o[1];p.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 h=tt(tt({},n.styles.root),n.style),x=Object.keys(r).filter(function(g){return g.startsWith("data-")}).reduce(function(g,b){var f;return tt(tt({},g),(f={},f[b]=r[b],f))},{}),u=(a=(s=r.components)===null||s===void 0?void 0:s.Months)!==null&&a!==void 0?a:Tj;return e.jsx("div",tt({className:m.join(" "),style:h,dir:n.dir,id:n.id,nonce:r.nonce,title:r.title,lang:r.lang},x,{children:e.jsx(u,{children:l.displayMonths.map(function(g,b){return e.jsx(Aj,{displayIndex:b,displayMonth:g},b)})})}))}function Rj(t){var s=t.children,a=qy(t,["children"]);return e.jsx(bv,{initialProps:a,children:e.jsx(kv,{children:e.jsx(cj,{initialProps:a,children:e.jsx($v,{initialProps:a,children:e.jsx(Bv,{initialProps:a,children:e.jsx(Xv,{children:e.jsx(lj,{children:s})})})})})})})}function Dj(t){return e.jsx(Rj,tt({},t,{children:e.jsx(kj,{initialProps:t})}))}function Xn({className:t,classNames:s,showOutsideDays:a=!0,...r}){return e.jsx(Dj,{showOutsideDays:a,className:Ae("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:Ae(bn({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:Ae("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:Ae(bn({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(Cx,{className:Ae("size-4",n),...i}),IconRight:({className:n,...i})=>e.jsx(vi,{className:Ae("size-4",n),...i})},...r})}function Us({value:t,onChange:s,minDate:a,maxDate:r,placeholderText:n="dd/mm/yyyy",disabled:i=!1,className:l,wrapperClassName:o,error:c=!1,displayFormat:d="dd/MM/yyyy",id:m}){const[h,x]=p.useState(!1),u=p.useMemo(()=>{if(t){if(t instanceof Date)return Sr(t)?t:void 0;if(typeof t=="string")try{const y=Gi(t,"yyyy-MM-dd",new Date);return Sr(y)?y:void 0}catch{return}}},[t]),g=p.useMemo(()=>{if(a){if(a instanceof Date)return Sr(a)?a:void 0;if(typeof a=="string"){const y=Gi(a,"yyyy-MM-dd",new Date);return Sr(y)?y:void 0}}},[a]),b=p.useMemo(()=>{if(r){if(r instanceof Date)return Sr(r)?r:void 0;if(typeof r=="string"){const y=Gi(r,"yyyy-MM-dd",new Date);return Sr(y)?y:void 0}}},[r]),f=y=>{if(x(!1),!!s){if(!y){s(null);return}s(Ge(y,"yyyy-MM-dd"))}};return e.jsx("div",{className:Ae("relative",o),children:e.jsxs(Xs,{open:h,onOpenChange:x,children:[e.jsx(Zs,{asChild:!0,children:e.jsxs(F,{id:m,disabled:i,variant:"outline",className:Ae("w-full justify-start text-left font-normal",!u&&"text-muted-foreground",c&&"border-destructive ring-destructive/20",l),children:[e.jsx(xt,{className:"mr-2 h-4 w-4"}),u?Ge(u,d):e.jsx("span",{children:n})]})}),e.jsx(Js,{className:"w-auto p-0",align:"start",children:e.jsx(Xn,{mode:"single",selected:u,onSelect:f,disabled:y=>!!(g&&y<g||b&&y>b),initialFocus:!0})})]})})}function Pj({isAdmin:t,dateRange:s,customStartDate:a,customEndDate:r,showCustomDatePicker:n,refreshing:i,onDateRangeChange:l,onCustomStartDateChange:o,onCustomEndDateChange:c,onShowCustomDatePickerChange:d,onApplyCustomDate:m,onResetCustomDates:h,onRefresh:x}){return e.jsx(se,{className:"shadow-md","data-testid":"dashboard-filters-bar",children:e.jsx(ae,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qa,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Filters"}),t&&e.jsx(oe,{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(xt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ke,{value:s,onValueChange:l,"data-testid":"date-range-select",children:[e.jsx(Ze,{className:"w-[140px]",children:e.jsx(Xe,{placeholder:"Select period"})}),e.jsxs(Je,{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(Xs,{open:n,onOpenChange:d,children:[e.jsx(Zs,{asChild:!0,children:e.jsxs(F,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(xt,{className:"w-4 h-4"}),a&&r?`${Ge(a,"MMM d, yyyy")} - ${Ge(r,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Js,{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(ne,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(Us,{value:a||null,onChange:u=>{const g=u?new Date(u):void 0;g?(o(g),r&&g>r&&c(g)):o(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full","data-testid":"start-date-input"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(Us,{value:r||null,onChange:u=>{const g=u?new Date(u):void 0;g?(c(g),a&&g<a&&o(g)):c(void 0)},minDate:a||void 0,maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full","data-testid":"end-date-input"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(F,{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(F,{size:"sm",variant:"outline",onClick:h,"data-testid":"cancel-custom-date",children:"Cancel"})]})]})})]})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ke,{value:s,onValueChange:u=>l(u),"data-testid":"date-range-select-user",children:[e.jsx(Ze,{className:"w-[140px]",children:e.jsx(Xe,{placeholder:"Select period"})}),e.jsxs(Je,{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(Xs,{open:n,onOpenChange:d,children:[e.jsx(Zs,{asChild:!0,children:e.jsxs(F,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(xt,{className:"w-4 h-4"}),a&&r?`${Ge(a,"MMM d, yyyy")} - ${Ge(r,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Js,{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(ne,{htmlFor:"start-date-user",className:"text-sm font-medium",children:"Start Date"}),e.jsx(Us,{value:a||null,onChange:u=>{const g=u?new Date(u):void 0;g?(o(g),r&&g>r&&c(g)):o(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full","data-testid":"start-date-input-user"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"end-date-user",className:"text-sm font-medium",children:"End Date"}),e.jsx(Us,{value:r||null,onChange:u=>{const g=u?new Date(u):void 0;g?(c(g),a&&g<a&&o(g)):c(void 0)},minDate:a||void 0,maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full","data-testid":"end-date-input-user"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(F,{size:"sm",onClick:m,disabled:!a||!r,className:"flex-1 bg-re-green hover:bg-re-green/90","data-testid":"apply-custom-date-user",children:"Apply"}),e.jsx(F,{size:"sm",variant:"outline",onClick:h,"data-testid":"cancel-custom-date-user",children:"Cancel"})]})]})})]})]}),e.jsx(Ps,{orientation:"vertical",className:"h-6 hidden sm:block"}),e.jsxs(F,{variant:"outline",size:"sm",onClick:x,disabled:i,className:"gap-2 min-w-[110px]","data-testid":"refresh-button",children:[e.jsx(Ut,{className:`w-4 h-4 ${i?"animate-spin":""}`}),e.jsx("span",{className:"inline-block w-[60px] text-center",children:i?"Refreshing...":"Refresh"})]})]})]})})})}function pr({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 h=x=>{x.stopPropagation(),d==null||d()};return e.jsxs(se,{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(ge,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(fe,{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:h,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(Hr,{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(ae,{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 hs({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 oa({className:t,value:s,indicatorClassName:a,...r}){return e.jsx(F0,{"data-slot":"progress",className:Ae("bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",t),...r,children:e.jsx(_0,{"data-slot":"progress-indicator",className:Ae("bg-primary h-full w-full flex-1 transition-all",a),style:{transform:`translateX(-${100-(s||0)}%)`}})})}function Ij({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(pr,{title:"Total Requests",value:(t==null?void 0:t.requestVolume.totalRequests)||0,icon:ke,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(hs,{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(hs,{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(hs,{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(hs,{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(hs,{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(pr,{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(oa,{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(hs,{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(hs,{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(pr,{title:"Avg Cycle Time",value:t!=null&&t.tatEfficiency.avgCycleTimeHours?Mt(t.tatEfficiency.avgCycleTimeHours):"0 hours",icon:nt,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(hs,{label:"Express",value:(()=>{const o=s.find(d=>d.priority==="express"),c=o?Number(o.avgCycleTimeHours):0;return c>0?Mt(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(hs,{label:"Standard",value:(()=>{const o=s.find(d=>d.priority==="standard"),c=o?Number(o.avgCycleTimeHours):0;return c>0?Mt(c):"N/A"})(),bgColor:"bg-blue-50",textColor:"text-blue-600",testId:"stat-standard-time",onClick:o=>{o.stopPropagation(),i({...l(),priority:"standard"})}})]})})})]})}function Ej({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 x=new URLSearchParams;x.set("approverId",o),x.set("approverName",c||"My Performance"),x.set("dateRange",a),a==="custom"&&r&&n&&(x.set("startDate",r.toISOString()),x.set("endDate",n.toISOString())),l==null||l(`/approver-performance?${x.toString()}`)},h=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(pr,{title:"My Requests (Submitted)",value:(t==null?void 0:t.requestVolume.totalRequests)||0,icon:ke,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(hs,{label:"Approved",value:(t==null?void 0:t.requestVolume.approvedRequests)||0,bgColor:"bg-green-50",textColor:"text-green-600",testId:"stat-user-approved",onClick:x=>{x.stopPropagation(),i({...d(),status:"approved"})}}),e.jsx(hs,{label:"Pending",value:(t==null?void 0:t.requestVolume.openRequests)||0,bgColor:"bg-orange-50",textColor:"text-orange-600",testId:"stat-user-pending",onClick:x=>{x.stopPropagation(),i({...d(),status:"pending"})}}),e.jsx(hs,{label:"Paused",value:(t==null?void 0:t.requestVolume.pausedRequests)||0,bgColor:"bg-amber-50",textColor:"text-amber-600",testId:"stat-user-paused",onClick:x=>{x.stopPropagation(),i({...d(),status:"paused"})}}),e.jsx(hs,{label:"Rejected",value:(t==null?void 0:t.requestVolume.rejectedRequests)||0,bgColor:"bg-red-50",textColor:"text-red-600",testId:"stat-user-rejected",onClick:x=>{x.stopPropagation(),i({...d(),status:"rejected"})}}),e.jsx(hs,{label:"Closed",value:(t==null?void 0:t.requestVolume.closedRequests)||0,bgColor:"bg-blue-50",textColor:"text-blue-600",testId:"stat-user-closed",onClick:x=>{x.stopPropagation(),i({...d(),status:"closed"})}})]})}),e.jsx(pr,{title:"Awaiting My Approval",value:(t==null?void 0:t.approverLoad.pendingActions)||0,icon:nt,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(hs,{label:"Approved Today",value:(t==null?void 0:t.approverLoad.completedToday)||0,bgColor:"bg-blue-50",textColor:"text-blue-600",testId:"stat-today",onClick:x=>{x.stopPropagation(),i({...d(),targetPage:"open-requests",status:"pending"})}}),e.jsx(hs,{label:"This Week",value:(t==null?void 0:t.approverLoad.completedThisWeek)||0,bgColor:"bg-green-50",textColor:"text-green-600",testId:"stat-week",onClick:x=>{x.stopPropagation(),i({...d(),targetPage:"open-requests",status:"pending"})}})]})}),e.jsx(pr,{title:"Critical Alerts",value:s.length,icon:fa,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(hs,{label:"Breached",value:s.filter(x=>x.breachCount>0).length,bgColor:"bg-orange-50",textColor:"text-red-600",testId:"stat-user-breached",onClick:x=>{x.stopPropagation(),i({...d(),targetPage:"open-requests"})}}),e.jsx(hs,{label:"Warning",value:s.filter(x=>x.breachCount===0).length,bgColor:"bg-yellow-50",textColor:"text-orange-600",testId:"stat-user-warning",onClick:x=>{x.stopPropagation(),i({...d(),targetPage:"open-requests"})}})]})}),e.jsx(pr,{title:"Success Rate",value:`${h.toFixed(0)}%`,icon:Re,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(oa,{value:h,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 Fj=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)))},_j=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 Lj({alert:t,onNavigate:s,testId:a="critical-alert-card"}){const r=Fj(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(Sf,{className:"h-3 w-3 text-red-500 flex-shrink-0","data-testid":`${a}-priority-icon`}),t.breachCount>0&&e.jsx(oe,{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(oe,{variant:"outline",className:"text-xs bg-white border-red-200 text-red-700 font-medium whitespace-nowrap","data-testid":`${a}-remaining-time`,children:_j(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(oa,{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 Mj(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 $j(t){return t.filter(s=>{const a=Number(s.tatPercentageUsed)||0;return(Number(s.remainingHours)||0)>0&&a<100})}function Oj(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 Uj(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 vh(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 Bj({isAdmin:t,breachedRequests:s,pagination:a,onPageChange:r,onNavigate:n}){return e.jsxs(se,{className:"lg:col-span-2 shadow-md hover:shadow-lg transition-shadow flex flex-col overflow-hidden h-full","data-testid":"critical-alerts-section",children:[e.jsx(ge,{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(fa,{className:"h-4 w-4 sm:h-5 sm:w-5 text-red-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-base sm:text-lg text-gray-900",children:"Critical Alerts"}),e.jsx(Ue,{className:"text-xs sm:text-sm text-gray-600",children:t?"Organization-wide":"My requests"})]})]}),e.jsx(oe,{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(ae,{className:`overflow-y-auto flex-1 p-4 ${a.totalPages>1?"max-h-[calc(100%-140px)]":"max-h-[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(Re,{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(Lj,{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(F,{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(ls,{className:"h-3 w-3 rotate-180"})}),vh(a.page,a.totalPages,3).map(i=>e.jsx(F,{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(F,{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(ls,{className:"h-3 w-3"})})]})]})})]})}const Vj=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"}},zj=t=>{const s=new Date,a=new Date(t),r=bf(s,a);if(r<1)return"just now";if(r<60)return`${r} minute${r>1?"s":""} ago`;const n=yf(s,a);if(n<24)return`${n} hour${n>1?"s":""} ago`;const i=vf(s,a);return`${i} day${i>1?"s":""} ago`},Hj=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()},Gj=t=>{const s=t.toLowerCase();return s.includes("approv")?e.jsx(Re,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-green-600"}):s.includes("reject")?e.jsx(os,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-red-600"}):s.includes("comment")?e.jsx(Ds,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-blue-600"}):s.includes("escalat")?e.jsx(fa,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-orange-600"}):s.includes("submit")?e.jsx(ke,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-purple-600"}):s.includes("document")?e.jsx(ji,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-indigo-600"}):e.jsx(It,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-gray-600"})};function Wj({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(ts,{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(Ii,{src:""}),e.jsx(ss,{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:Gj(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(oe,{variant:"outline",className:`text-xs ${Vj(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:Hj(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:zj(t.timestamp)})]})]}),e.jsx(ls,{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 Yj({isAdmin:t,recentActivity:s,pagination:a,refreshing:r,onPageChange:n,onRefresh:i,onNavigate:l,currentUserId:o,currentUserDisplayName:c,currentUserEmail:d}){return e.jsxs(se,{className:"lg:col-span-1 shadow-md hover:shadow-lg transition-shadow flex flex-col overflow-hidden h-full","data-testid":"recent-activity-section",children:[e.jsx(ge,{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(It,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx(fe,{className:"text-base sm:text-lg text-gray-900",children:"Recent Activity"}),e.jsx(Ue,{className:"text-xs sm:text-sm text-gray-600 truncate",children:t?"All workflow updates":"My workflow updates"})]})]}),e.jsxs(F,{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(Ut,{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(ae,{className:`overflow-y-auto flex-1 p-4 ${a.totalPages>1?"max-h-[calc(100%-140px)]":"max-h-[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(It,{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(Wj,{activity:m,currentUserId:o,currentUserDisplayName:c,currentUserEmail:d,onNavigate:h=>l==null?void 0:l(`request/${h}`),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(F,{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(ls,{className:"h-3 w-3 rotate-180"})}),vh(a.page,a.totalPages,3).map(m=>e.jsx(F,{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(F,{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(ls,{className:"h-3 w-3"})})]})]})})]})}function Kj({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(se,{className:"shadow-md hover:shadow-lg transition-shadow flex-1","data-testid":"active-levels-card",children:[e.jsx(ge,{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(It,{className:"h-4 w-4 text-blue-600"})}),e.jsx(fe,{className:"text-sm",children:"Active Levels"})]})}),e.jsx(ae,{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(Ps,{}),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(h=>h.breachCount>0).length})]})]})]})})]}),e.jsxs(se,{className:"shadow-md hover:shadow-lg transition-shadow flex-1","data-testid":"collaboration-card",children:[e.jsx(ge,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-2 bg-indigo-100 rounded-lg",children:e.jsx(Ds,{className:"h-4 w-4 text-indigo-600"})}),e.jsx(fe,{className:"text-sm",children:"Collaboration"})]})}),e.jsx(ae,{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(Ps,{}),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(se,{className:"shadow-md hover:shadow-lg transition-shadow lg:col-span-2","data-testid":"department-stats-card",children:[e.jsx(ge,{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(El,{className:"h-5 w-5 sm:h-6 sm:w-6 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-base sm:text-lg lg:text-xl",children:"Department-wise Workflow Summary"}),e.jsx(Ue,{className:"text-xs sm:text-sm",children:"Workflow distribution across departments"})]})]}),e.jsxs(F,{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(At,{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(ae,{children:e.jsx(Fr,{width:"100%",height:400,children:e.jsxs(Dl,{data:r,children:[e.jsx(si,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(ai,{dataKey:"department",stroke:"#999",tick:h=>{const{x,y:u,payload:g}=h;return e.jsx("g",{transform:`translate(${x},${u})`,children:e.jsx("text",{x:0,y:0,dy:16,textAnchor:"middle",fill:"#999",fontSize:11,className:"cursor-pointer hover:text-blue-600 hover:underline",onClick:()=>{c({...m(),department:g.value})},children:g.value})})}}),e.jsx(ri,{stroke:"#999",tick:{fontSize:11}}),e.jsx(_r,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(ni,{verticalAlign:"bottom",height:36,iconType:"square",wrapperStyle:{fontSize:"12px",paddingTop:"10px"}}),e.jsx(ya,{dataKey:"approved",fill:"#10b981",name:"Approved"}),e.jsx(ya,{dataKey:"inProgress",fill:"#f59e0b",name:"Pending"}),e.jsx(ya,{dataKey:"rejected",fill:"#ef4444",name:"Rejected"})]})})})]})]})}function Xj({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(se,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"user-activity-card",children:[e.jsx(ge,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-2 bg-indigo-100 rounded-lg",children:e.jsx(Ds,{className:"h-4 w-4 text-indigo-600"})}),e.jsx(fe,{className:"text-sm",children:"My Activity"})]})}),e.jsx(ae,{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(se,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"user-response-time-card",children:[e.jsx(ge,{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(nt,{className:"h-4 w-4 text-purple-600"})}),e.jsx(fe,{className:"text-sm",children:"Avg Response Time"})]})}),e.jsx(ae,{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:Mt(t.tatEfficiency.avgCycleTimeHours)})}),e.jsx(Ps,{}),e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["≈ ",t.tatEfficiency.avgCycleTimeDays.toFixed(1)," working days"]})]})})]})]}):null}function Zj({priorityDistribution:t,onNavigate:s}){return t.length===0?null:e.jsxs(se,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"priority-distribution-report",children:[e.jsx(ge,{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(fe,{className:"text-base sm:text-lg lg:text-xl",children:"Priority Distribution Report"}),e.jsx(Ue,{className:"text-xs sm:text-sm",children:"Express vs Standard workflow analysis"})]})]})}),e.jsxs(ae,{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: ",Mt(n)," cycle"]})]},r)})}),e.jsx("div",{className:"flex justify-center",children:e.jsx(Fr,{width:"100%",height:300,children:e.jsxs(hx,{children:[e.jsx(px,{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),h=r+d*Math.sin(-n*c);return e.jsx("text",{x:m,y:h,fill:"#1f2937",textAnchor:m>a?"start":"end",dominantBaseline:"central",className:"text-sm font-semibold pointer-events-none",children:`${l}: ${o}%`})},outerRadius:90,fill:"#8884d8",dataKey:"value",onClick:a=>{a&&a.priority&&s&&s(`requests?priority=${a.priority}`)},className:"cursor-pointer",children:t.map((a,r)=>e.jsx(gx,{fill:a.priority==="express"?"#ef4444":"#3b82f6",className:"cursor-pointer"},`cell-${r}`))}),e.jsx(_r,{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 jr({currentPage:t,totalPages:s,itemsPerPage:a,totalRecords:r,onPageChange:n,loading:i=!1,itemLabel:l="items",testIdPrefix:o="pagination"}){const c=()=>{const h=[];let u=Math.max(1,t-Math.floor(2.5)),g=Math.min(s,u+5-1);g-u<4&&(u=Math.max(1,g-5+1));for(let b=u;b<=g;b++)h.push(b);return h},d=r>0?(t-1)*a+1:0,m=Math.min(t*a,r);return s<=1?e.jsx(se,{className:"shadow-md border-gray-200","data-testid":`${o}-container`,children:e.jsx(ae,{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(se,{className:"shadow-md border-gray-200","data-testid":`${o}-container`,children:e.jsx(ae,{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(F,{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(ls,{className:"h-4 w-4 rotate-180"})}),t>3&&s>5&&e.jsxs(e.Fragment,{children:[e.jsx(F,{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(h=>e.jsx(F,{variant:h===t?"default":"outline",size:"sm",onClick:()=>n(h),className:`h-8 w-8 p-0 ${h===t?"bg-re-green text-white hover:bg-re-green/90":""}`,"data-testid":`${o}-page-${h}`,"aria-current":h===t?"page":void 0,children:h},h)),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(F,{variant:"outline",size:"sm",onClick:()=>n(s),className:"h-8 w-8 p-0","data-testid":`${o}-page-${s}`,children:s})]}),e.jsx(F,{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(ls,{className:"h-4 w-4"})})]})]})})})}function Jj(t,s,a,r="for"){return t==="custom"&&s&&a?`${r} ${Ge(s,"MMM d, yyyy")} - ${Ge(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 Qj(t,s,a){return t==="all"?"All historical data":t==="custom"&&s&&a?`Data from ${Ge(s,"MMM d, yyyy")} to ${Ge(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 qj({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(se,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"tat-breach-report",children:[e.jsx(ge,{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(os,{className:"h-5 w-5 sm:h-6 sm:w-6 text-red-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-base sm:text-lg lg:text-xl",children:"TAT Breach Report"}),e.jsxs(Ue,{className:"text-xs sm:text-sm",children:["Requests that breached TAT - ",Qj(a,r,n)]})]})]}),e.jsxs(oe,{variant:"destructive",className:"text-sm font-medium self-start sm:self-auto",children:[s.totalRecords," ",s.totalRecords===1?"Breach":"Breaches"]})]})}),e.jsxs(ae,{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 h=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 x=new URLSearchParams;x.set("approver",d.approverId),x.set("approverType","current"),x.set("slaCompliance","breached"),a&&x.set("dateRange",a),r&&x.set("startDate",r.toISOString()),n&&x.set("endDate",n.toISOString()),o(`requests?${x.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:Oj(h)})}),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(oe,{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(jr,{currentPage:s.page,totalPages:s.totalPages,totalRecords:s.totalRecords,itemsPerPage:10,onPageChange:i,itemLabel:"critical requests",testIdPrefix:"dashboard-critical-pagination"})})]})]})}function eN({isAdmin:t,upcomingDeadlines:s,pagination:a,onPageChange:r,onNavigate:n}){return s.length===0?null:e.jsxs(se,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"upcoming-deadlines-section",children:[e.jsx(ge,{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(xt,{className:"h-4 w-4 sm:h-5 sm:w-5 text-orange-600"}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-base sm:text-lg",children:"Upcoming Deadlines"}),e.jsx(Ue,{className:"text-xs sm:text-sm",children:t?"Current active levels organization-wide":"Requests awaiting your approval"})]})]})})}),e.jsxs(ae,{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(oe,{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(oe,{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(oa,{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:[Mt(c)," elapsed"]}),e.jsxs("span",{children:[Mt(d)," left"]})]})]})]},l)})}),e.jsx("div",{className:"mt-4",children:e.jsx(jr,{currentPage:a.page,totalPages:a.totalPages,totalRecords:a.totalRecords,itemsPerPage:10,onPageChange:r,itemLabel:"deadlines",testIdPrefix:"dashboard-deadlines-pagination"})})]})]})}function tN({aiRemarkUtilization:t}){return t?e.jsxs(se,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"ai-remark-utilization-report",children:[e.jsx(ge,{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(po,{className:"h-5 w-5 sm:h-6 sm:w-6 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-base sm:text-lg lg:text-xl",children:"AI Remark Utilization Report"}),e.jsx(Ue,{className:"text-xs sm:text-sm",children:"AI-generated remarks usage and edits"})]})]})}),e.jsxs(ae,{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(Fr,{width:"100%",height:250,children:e.jsxs(nf,{data:t.monthlyTrends,children:[e.jsx(si,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(ai,{dataKey:"month",stroke:"#999",tick:{fontSize:11}}),e.jsx(ri,{stroke:"#999",tick:{fontSize:11}}),e.jsx(_r,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(ni,{verticalAlign:"bottom",height:36,iconType:"circle",wrapperStyle:{fontSize:"12px",paddingTop:"10px"}}),e.jsx(tm,{type:"monotone",dataKey:"aiUsage",stroke:"#8b5cf6",strokeWidth:2,name:"AI Usage",dot:{fill:"#8b5cf6",r:4}}),e.jsx(tm,{type:"monotone",dataKey:"manualEdits",stroke:"#ec4899",strokeWidth:2,name:"Manual Edits",dot:{fill:"#ec4899",r:4}})]})})]})]}):null}function sN({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(se,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"approver-performance-report",children:[e.jsx(ge,{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(ps,{className:"h-5 w-5 sm:h-6 sm:w-6 text-yellow-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-base sm:text-lg lg:text-xl",children:"Approver Performance Report"}),e.jsx(Ue,{className:"text-xs sm:text-sm",children:"Response time & TAT compliance tracking"})]})]}),e.jsx(F,{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(Ut,{className:"w-4 h-4 mr-2 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(At,{className:"w-4 h-4 mr-2"}),"Export"]})})]})}),e.jsxs(ae,{children:[e.jsx("div",{className:"space-y-3",children:t.map((m,h)=>{const x=m.tatCompliancePercent;return e.jsxs("div",{className:"border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer",onClick:()=>{const u=new URLSearchParams;u.set("approverId",m.approverId),u.set("approverName",m.approverName),u.set("dateRange",a),a==="custom"&&r&&n&&(u.set("startDate",r.toISOString()),u.set("endDate",n.toISOString())),d==null||d(`/approver-performance?${u.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:h+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 ${Uj(x)} flex-shrink-0`,children:[x,"% 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:Mt(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})})]})]})]},h)})}),e.jsx("div",{className:"mt-4",children:e.jsx(jr,{currentPage:s.page,totalPages:s.totalPages,totalRecords:s.totalRecords,itemsPerPage:10,onPageChange:o,itemLabel:"approvers",testIdPrefix:"dashboard-approver-pagination"})})]})]})}function aN(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 rN(t,s,a,r){const n=[];return r||n.push({label:"New Request",icon:ke,action:()=>s==null?void 0:s(),color:"bg-emerald-600 hover:bg-emerald-700"}),n.push({label:"View Pending",icon:nt,action:()=>a==null?void 0:a("open-requests"),color:"bg-blue-600 hover:bg-blue-700"},{label:"Settings",icon:Ya,action:()=>a==null?void 0:a("settings"),color:"bg-slate-600 hover:bg-slate-700"}),t&&n.splice(n.length-1,0,{label:"Reports",icon:It,action:()=>a==null?void 0:a("detailed-reports"),color:"bg-purple-600 hover:bg-purple-700"}),n}function nN({onNavigate:t,onNewRequest:s}){const{user:a}=Jt(),r=Tn(),n=Yr(ze=>ze.dashboard.viewAsUser),i=p.useMemo(()=>Di(a),[a]),l=i&&!n,o=p.useCallback(ze=>{r(_y(ze))},[r]),c=Ly(),{dateRange:d,customStartDate:m,customEndDate:h,showCustomDatePicker:x,handleDateRangeChange:u,handleApplyCustomDate:g,resetCustomDates:b,setCustomStartDate:f,setCustomEndDate:y,setShowCustomDatePicker:v}=c,C=My(),{activity:w,critical:A,deadlines:N,approver:_,updateActivityPagination:T,updateCriticalPagination:R,updateDeadlinesPagination:j,updateApproverPagination:E,handleActivityPageChange:P,handleCriticalPageChange:B,handleDeadlinesPageChange:k,handleApproverPageChange:L}=C,V=Oy({isAdmin:l,viewAsUser:i&&n,userId:a==null?void 0:a.userId,dateRange:d,customStartDate:m,customEndDate:h,onPaginationUpdate:{activity:T,critical:R,deadlines:j,approver:E}}),{kpis:D,recentActivity:S,criticalRequests:O,departmentStats:I,priorityDistribution:M,upcomingDeadlines:W,aiRemarkUtilization:G,approverPerformance:re,loading:te,refreshing:$,fetchDashboardData:z,fetchRecentActivities:H,fetchCriticalRequests:je,fetchUpcomingDeadlines:le,fetchApproverPerformance:ue}=V,$e=Xy(),{exportingDeptStats:Te,exportingApproverPerformance:Ve,handleExportDepartmentStats:Qe,handleExportApproverPerformance:Fe}=$e,Q=p.useMemo(()=>Mj(O),[O]),pe=p.useMemo(()=>$j(W),[W]),Ce=p.useCallback(()=>{z(!0)},[d,m,h,z]),Oe=p.useCallback(()=>{g(()=>{m&&h&&z(!1)})},[m,h,g,z]),X=p.useCallback(ze=>{P(ze,H)},[P,H]),Z=p.useCallback(ze=>{B(ze,je)},[B,je]),me=p.useCallback(ze=>{k(ze,le)},[k,le]),J=p.useCallback(ze=>{L(ze,()=>ue(ze))},[L,ue]);p.useEffect(()=>{d==="custom"?m&&h&&z(!1):z(!1)},[d,m,h,n]);const be=p.useMemo(()=>{try{const ze=st.getUserData();return(ze==null?void 0:ze.jobTitle)==="Dealer"}catch(ze){return console.error("[Dashboard] Error checking dealer status:",ze),!1}},[]),Be=p.useMemo(()=>rN(i,s,t,be),[i,s,t,be]),Ee=p.useCallback(ze=>{const vt=aN(ze);t==null||t(vt)},[t]);return te?e.jsx("div",{className:"flex items-center justify-center h-screen",children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx(Ut,{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(Zy,{isAdmin:i,effectiveIsAdmin:l,viewAsUser:n,onToggleView:o,quickActions:Be,userDisplayName:a==null?void 0:a.displayName,userEmail:a==null?void 0:a.email}),e.jsx(Pj,{isAdmin:l,dateRange:d,customStartDate:m,customEndDate:h,showCustomDatePicker:x,refreshing:$,onDateRangeChange:u,onCustomStartDateChange:f,onCustomEndDateChange:y,onShowCustomDatePickerChange:v,onApplyCustomDate:Oe,onResetCustomDates:b,onRefresh:Ce}),l?e.jsx(Ij,{kpis:D,priorityDistribution:M,dateRange:d,customStartDate:m,customEndDate:h,onKPIClick:Ee}):e.jsx(Ej,{kpis:D,criticalRequests:O,dateRange:d,customStartDate:m,customEndDate:h,onKPIClick:Ee,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(Bj,{isAdmin:l,breachedRequests:Q,pagination:A,onPageChange:Z,onNavigate:t}),e.jsx(Yj,{isAdmin:l,recentActivity:S,pagination:w,refreshing:$,onPageChange:X,onRefresh:Ce,onNavigate:t,currentUserId:a==null?void 0:a.userId,currentUserDisplayName:a==null?void 0:a.displayName,currentUserEmail:a==null?void 0:a.email})]}),l&&D&&e.jsx(Kj,{kpis:D,upcomingDeadlines:W,criticalRequests:O,departmentStats:I,dateRange:d,customStartDate:m,customEndDate:h,exportingDeptStats:Te,onKPIClick:Ee,onExportDepartmentStats:Qe}),!l&&D&&e.jsx(Xj,{kpis:D}),l&&M.length>0&&e.jsx(Zj,{priorityDistribution:M,onNavigate:t}),l&&Q.length>0&&e.jsx(qj,{breachedRequests:Q,pagination:A,dateRange:d,customStartDate:m,customEndDate:h,onPageChange:Z,onKPIClick:Ee,onNavigate:t}),pe.length>0&&e.jsx(eN,{isAdmin:l,upcomingDeadlines:pe,pagination:N,onPageChange:me,onNavigate:t}),l&&G&&e.jsx(tN,{aiRemarkUtilization:G}),l&&re.length>0&&e.jsx(sN,{approverPerformance:re,pagination:_,dateRange:d,customStartDate:m,customEndDate:h,loading:te,exportingApproverPerformance:Ve,onPageChange:J,onExport:Fe,onNavigate:t})]})}const iN={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",sortBy:"created",sortOrder:"desc",currentPage:1},jh=Gr({name:"openRequests",initialState:iN,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:lN,setStatusFilter:oN,setPriorityFilter:cN,setTemplateTypeFilter:dN,setSortBy:mN,setSortOrder:uN,setCurrentPage:xN,clearFilters:hN}=jh.actions;function pN(){const t=Tn(),{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,sortBy:i,sortOrder:l,currentPage:o}=Yr(y=>y.openRequests),c=p.useCallback(y=>t(lN(y)),[t]),d=p.useCallback(y=>t(oN(y)),[t]),m=p.useCallback(y=>t(cN(y)),[t]),h=p.useCallback(y=>t(dN(y)),[t]),x=p.useCallback(y=>t(mN(y)),[t]),u=p.useCallback(y=>t(uN(y)),[t]),g=p.useCallback(y=>t(xN(y)),[t]),b=p.useCallback(()=>t(hN()),[t]),f=[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:h,setSortBy:x,setSortOrder:u,setCurrentPage:g,clearFilters:b,activeFiltersCount:f}}function rl(){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 gN(t){var o;const s=t.priorityUi.toUpperCase()==="EXPRESS"?"EXPRESS":"STANDARD",a=Array.from({length:t.approverCount||1},(c,d)=>{const m=d,h=t.approvers[m]||{},x=m+1,u=h.tat??"";let g=0;typeof u=="number"&&(g=h.tatType==="days"?u*24:u);const b=h.email||"",f=h.name&&h.name.trim()||b.split("@")[0]||`Approver ${x}`;return{levelNumber:x,levelName:`Level ${x}`,approverId:rl(),approverEmail:b,approverName:f,tatHours:g>0?g:24,isFinalApprover:x===(t.approverCount||1)}}),r=[...(t.spectators||[]).map(c=>({userId:rl(),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:rl(),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,isDraft:t.isDraft},i=await ve.post("/workflows",n),l=((o=i.data)==null?void 0:o.data)||i.data;return{id:l.id||l.workflowId||""}}async function _o(t,s,a="SUPPORTING"){var o;const r={templateType:t.templateType,title:t.title,description:t.description,priority:t.priorityUi.toUpperCase()==="EXPRESS"?"EXPRESS":"STANDARD",isDraft:t.isDraft,approvers:Array.from({length:t.approverCount||1},(c,d)=>{const m=t.approvers[d]||{},h=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:h,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 ve.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 fN(t={}){var b;const{page:s=1,limit:a=20,search:r,status:n,priority:i,templateType:l,department:o,initiator:c,approver:d,slaCompliance:m,dateRange:h,startDate:x,endDate:u}=t,g=await ve.get("/workflows",{params:{page:s,limit:a,search:r,status:n,priority:i,templateType:l,department:o,initiator:c,approver:d,slaCompliance:m,dateRange:h,startDate:x,endDate:u}});return((b=g.data)==null?void 0:b.data)||g.data}async function bN(t={}){var f,y,v,C,w;const{page:s=1,limit:a=20,search:r,status:n,priority:i,templateType:l,department:o,initiator:c,approver:d,approverType:m,slaCompliance:h,dateRange:x,startDate:u,endDate:g}=t,b=await ve.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:h,dateRange:x,startDate:u,endDate:g}});return{data:((y=(f=b.data)==null?void 0:f.data)==null?void 0:y.data)||((v=b.data)==null?void 0:v.data)||[],pagination:((w=(C=b.data)==null?void 0:C.data)==null?void 0:w.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function yN(t={}){var g,b,f,y,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:h,endDate:x}=t,u=await ve.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:h,endDate:x}});return{data:((b=(g=u.data)==null?void 0:g.data)==null?void 0:b.data)||((f=u.data)==null?void 0:f.data)||[],pagination:((v=(y=u.data)==null?void 0:y.data)==null?void 0:v.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function vN(t={}){var u,g,b,f,y;const{page:s=1,limit:a=20,search:r,status:n,priority:i,templateType:l,department:o,slaCompliance:c,dateRange:d,startDate:m,endDate:h}=t,x=await ve.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:h}});return{data:((g=(u=x.data)==null?void 0:u.data)==null?void 0:g.data)||((b=x.data)==null?void 0:b.data)||[],pagination:((y=(f=x.data)==null?void 0:f.data)==null?void 0:y.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function jN(t={}){var m,h,x,u,g;const{page:s=1,limit:a=20,search:r,status:n,priority:i,templateType:l,sortBy:o,sortOrder:c}=t,d=await ve.get("/workflows/open-for-me",{params:{page:s,limit:a,search:r,status:n,priority:i,templateType:l,sortBy:o,sortOrder:c}});return{data:((h=(m=d.data)==null?void 0:m.data)==null?void 0:h.data)||((x=d.data)==null?void 0:x.data)||[],pagination:((g=(u=d.data)==null?void 0:u.data)==null?void 0:g.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function NN(t={}){var m,h,x,u,g;const{page:s=1,limit:a=20,search:r,status:n,priority:i,templateType:l,sortBy:o,sortOrder:c}=t,d=await ve.get("/workflows/closed-by-me",{params:{page:s,limit:a,search:r,status:n,priority:i,templateType:l,sortBy:o,sortOrder:c}});return{data:((h=(m=d.data)==null?void 0:m.data)==null?void 0:h.data)||((x=d.data)==null?void 0:x.data)||[],pagination:((g=(u=d.data)==null?void 0:u.data)==null?void 0:g.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Ts(t,s){var r;const a=await ve.get(`/workflows/${t}/details`);return((r=a.data)==null?void 0:r.data)||a.data}async function Mr(t){var a;const s=await ve.get(`/workflows/${t}/work-notes`);return((a=s.data)==null?void 0:a.data)||s.data}async function Nh(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 ve.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 wh(t,s,a,r){var i;const n=await ve.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 wN(t,s,a){var n;const r=await ve.post(`/workflows/${t}/approvals/${s}/skip`,{reason:a});return((n=r.data)==null?void 0:n.data)||r.data}async function Ch(t,s){var r;const a=await ve.post(`/workflows/${t}/participants/spectator`,{email:s});return((r=a.data)==null?void 0:r.data)||a.data}async function CN(t,s,a,r){var i;const n=await ve.post(`/workflows/${t}/pause`,{levelId:s,reason:a,resumeDate:r.toISOString()});return((i=n.data)==null?void 0:i.data)||n.data}async function SN(t,s){var r;const a=await ve.post(`/workflows/${t}/resume`,{notes:s});return((r=a.data)==null?void 0:r.data)||a.data}async function AN(t){var a;const s=await ve.post(`/workflows/${t}/pause/retrigger`);return((a=s.data)==null?void 0:a.data)||s.data}async function Cm(t){var a;const s=await ve.get(`/workflows/${t}/pause`);return((a=s.data)==null?void 0:a.data)||s.data}function TN(t){return`https://reflow-uat.royalenfield.com/api/v1/workflows/work-notes/attachments/${t}/preview`}function Kr(t){return`https://reflow-uat.royalenfield.com/api/v1/workflows/documents/${t}/preview`}function Sh(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 ws(t){const a=`https://reflow-uat.royalenfield.com/api/v1/workflows/documents/${t}/download`,r=!0;try{const i=await fetch(a,{credentials:"include"});if(!i.ok){const h=await i.text();throw new Error(`Download failed: ${i.status} - ${h}`)}const l=await i.blob(),o=window.URL.createObjectURL(l),c=i.headers.get("Content-Disposition"),d=Sh(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 Sm(t){const a=`https://reflow-uat.royalenfield.com/api/v1/workflows/work-notes/attachments/${t}/download`,r=!0;try{const i=await fetch(a,{credentials:"include"});if(!i.ok){const h=await i.text();throw new Error(`Download failed: ${i.status} - ${h}`)}const l=await i.blob(),o=window.URL.createObjectURL(l),c=i.headers.get("Content-Disposition"),d=Sh(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 Is={createWorkflowFromForm:gN,createWorkflowMultipart:_o,listWorkflows:fN,listParticipantRequests:bN,listMyWorkflows:yN,listMyInitiatedWorkflows:vN,listOpenForMe:jN,listClosedByMe:NN,submitWorkflow:Ah,getWorkflowDetails:Ts,getWorkNotes:Mr,createWorkNoteMultipart:Nh,handleInitiatorAction:Th};async function Ah(t){var a;const s=await ve.patch(`/workflows/${t}/submit`);return((a=s.data)==null?void 0:a.data)||s.data}async function kN(t,s){var r;const a=await ve.put(`/workflows/${t}`,s);return((r=a.data)==null?void 0:r.data)||a.data}async function RN(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 ve.put(`/workflows/${t}/multipart`,i,{headers:{"Content-Type":"multipart/form-data"}});return((o=l.data)==null?void 0:o.data)||l.data}async function on(t,s,a){var n;const r=await ve.patch(`/workflows/${t}/approvals/${s}/approve`,{action:"APPROVE",comments:a||""});return((n=r.data)==null?void 0:n.data)||r.data}async function Tr(t,s,a,r){var i;const n=await ve.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 DN(t,s){const a=await ve.put(`/tat/breach-reason/${t}`,{breachReason:s});if(!a.data.success)throw new Error(a.data.error||"Failed to update breach reason")}async function Th(t,s,a){var n;const r=await ve.post(`/workflows/${t}/initiator-action`,{action:s,...a});return((n=r.data)==null?void 0:n.data)||r.data}async function PN(t){var a;return((a=(await ve.get(`/workflows/${t}/history`)).data)==null?void 0:a.data)||[]}function as(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 kh(t){return as(t,{includeTime:!1,format:"short"})}function ga(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"),h=o>=12?"PM":"AM";return`${r} ${i} ${l}, ${c}:${d}:${m} ${h}`}return`${r} ${i} ${l}`}catch(a){return console.error("Error formatting date:",a),String(t)}}function IN(t){return t?t.jobTitle==="Dealer"||t.jobTitle==="DEALER":!1}function Lo(t){return IN(t)?"DEALER":"STANDARD"}function va(t){if(!t)return"";let s=t.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,"");return s=s.replace(/\s+on\w+\s*=\s*(?:'[^']*'|"[^"]*"|[^\s>]+)/gi,""),s=s.replace(/(href|src)\s*=\s*(?:'javascript:[^']*'|"javascript:[^"]*"|javascript:[^\s>]+)/gi,'$1="#"'),s=s.replace(/<style[^>]*>[\s\S]*?<\/style>/gi,""),s=s.replace(/<(meta|link|iframe|object|embed|applet)[^>]*>/gi,""),s=s.replace(/<a[^>]*>([\s\S]*?)<\/a>/gi,"$1"),s}const On=[{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 Pn({value:t,onChange:s,placeholder:a="Enter text...",className:r,minHeight:n="120px",...i}){const l=p.useRef(null),[o,c]=p.useState(!1),[d,m]=p.useState(new Set),[h,x]=p.useState(!1),[u,g]=p.useState(null),[b,f]=p.useState("#FFEB3B"),[y,v]=p.useState(!1),[C,w]=p.useState(null),[A,N]=p.useState("#000000");p.useEffect(()=>{l.current&&l.current.innerHTML!==t&&l.current.innerHTML!==t&&(l.current.innerHTML=va(t||""))},[t]);const _=p.useCallback(D=>(D=D.replace(/<!--[\s\S]*?-->/g,""),D=D.replace(/<style[^>]*>[\s\S]*?<\/style>/gi,""),D=D.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,""),D=D.replace(/<meta[^>]*>/gi,""),D=D.replace(/\s*class="Mso[^"]*"/gi,""),D=D.replace(/\s*class="mso[^"]*"/gi,""),D=D.replace(/\s*style="[^"]*mso-[^"]*"/gi,""),D=D.replace(/\s*style="[^"]*font-family:[^"]*"/gi,""),D=D.replace(/\s*xmlns[^=]*="[^"]*"/gi,""),D=D.replace(/<\/?o:p[^>]*>/gi,""),D=D.replace(/<v:[^>]*>[\s\S]*?<\/v:[^>]*>/gi,""),D=D.replace(/<v:[^>]*\/>/gi,""),D=D.replace(/<p[^>]*>\s*<\/p>/gi,""),D=D.replace(/<div[^>]*>\s*<\/div>/gi,""),D=D.replace(/\s+/g," "),D=D.trim(),D),[]),T=p.useCallback(D=>{D.preventDefault();const S=D.clipboardData;let O=S.getData("text/html")||S.getData("text/plain");if((O.includes("<!--")||O.includes("<style")||O.includes("MsoNormal"))&&(O=_(O)),!l.current)return;const I=window.getSelection();if(!I||I.rangeCount===0)return;const M=I.getRangeAt(0);M.deleteContents();const W=document.createElement("div");W.innerHTML=O;const G=document.createDocumentFragment();Array.from(W.childNodes).forEach(re=>{if(re.nodeType===Node.ELEMENT_NODE){const te=re;if(te.tagName==="UL"||te.tagName==="OL"){const $=te.cloneNode(!0);$.removeAttribute("style"),$.removeAttribute("class"),$.querySelectorAll("li").forEach(z=>{z.removeAttribute("style"),z.removeAttribute("class");const H=z.textContent||"";H.trim()&&(z.textContent=H.trim())}),G.appendChild($)}else if(te.tagName==="TABLE"){const $=te.cloneNode(!0);$.removeAttribute("style"),$.removeAttribute("class"),$.querySelectorAll("td, th").forEach(H=>{H.removeAttribute("style"),H.removeAttribute("class")});const z=document.createElement("div");z.className="table-wrapper",z.appendChild($),G.appendChild(z)}else if(te.tagName==="P"||te.tagName==="DIV"){const $=document.createElement("p"),H=te.innerHTML.replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<!--[\s\S]*?-->/g,"");$.innerHTML=H,$.removeAttribute("style"),$.removeAttribute("class"),G.appendChild($)}else if(te.tagName==="BR")G.appendChild(te.cloneNode(!0));else{const $=te.textContent||"";if($.trim()){const z=document.createElement("p");z.textContent=$.trim(),G.appendChild(z)}}}else if(re.nodeType===Node.TEXT_NODE){const te=re.textContent||"";if(te.trim()){const $=document.createElement("p");$.textContent=te.trim(),G.appendChild($)}}}),G.childNodes.length===0&&S.getData("text/plain").split(`
`).forEach($=>{if($.trim()){const z=document.createElement("p");z.textContent=$.trim(),G.appendChild(z)}else G.appendChild(document.createElement("br"))}),M.insertNode(G),M.collapse(!1),I.removeAllRanges(),I.addRange(M),l.current&&s(va(l.current.innerHTML))},[s,_]),R=p.useCallback(()=>{if(!l.current||!o)return;const D=new Set,S=window.getSelection();if(S&&S.rangeCount>0){const I=S.getRangeAt(0).commonAncestorContainer;let M=null;for(I.nodeType===Node.TEXT_NODE?M=I.parentElement:M=I;M&&M!==l.current;){const W=M.tagName.toLowerCase();(W==="strong"||W==="b")&&D.add("bold"),(W==="em"||W==="i")&&D.add("italic"),W==="u"&&D.add("underline"),W==="h1"&&D.add("h1"),W==="h2"&&D.add("h2"),W==="h3"&&D.add("h3"),W==="ul"&&D.add("ul"),W==="ol"&&D.add("ol");const G=window.getComputedStyle(M);G.textAlign==="center"&&D.add("center"),G.textAlign==="right"&&D.add("right"),G.textAlign==="left"&&D.add("left");const re=H=>{if(H.startsWith("#"))return H.toUpperCase();const je=H.match(/\d+/g);if(!je||je.length<3)return null;const le=je[0],ue=je[1],$e=je[2];if(!le||!ue||!$e)return null;const Te=parseInt(le).toString(16).padStart(2,"0"),Ve=parseInt(ue).toString(16).padStart(2,"0"),Qe=parseInt($e).toString(16).padStart(2,"0");return`#${Te}${Ve}${Qe}`.toUpperCase()},te=G.backgroundColor;if(te&&te!=="rgba(0, 0, 0, 0)"&&te!=="transparent"&&te!=="rgb(255, 255, 255)"&&te!=="#ffffff"&&te!=="#FFFFFF"){D.add("highlight");const H=re(te);if(H){const je=On.find(le=>le.value==="transparent"?!1:le.value.toUpperCase()===H);g(je?je.value:H)}}else D.has("highlight")||g(null);const $=G.color,z=re($);if($&&z&&$!=="rgba(0, 0, 0, 0)"&&z!=="#000000"){D.add("textColor");const H=On.find(je=>je.value==="transparent"?!1:je.value.toUpperCase()===z);w(H?H.value:z)}else D.has("textColor")||w(z==="#000000"||!z?"#000000":null);M=M.parentElement}}m(D)},[o]),j=p.useCallback((D,S)=>{if(!l.current)return;o||l.current.focus();const O=window.getSelection();if(!O||O.rangeCount===0){l.current.focus();return}document.execCommand(D,!1,S),l.current&&s(va(l.current.innerHTML)),setTimeout(R,10)},[o,s,R]),E=p.useCallback(D=>{if(!l.current)return;o||l.current.focus();const S=window.getSelection();if(!S||S.rangeCount===0){l.current.focus();return}let O=!1;if(S.rangeCount>0){const W=S.getRangeAt(0).commonAncestorContainer;let G=null;for(W.nodeType===Node.TEXT_NODE?G=W.parentElement:G=W;G&&G!==l.current;){const te=window.getComputedStyle(G).backgroundColor;if(te&&te!=="rgba(0, 0, 0, 0)"&&te!=="transparent"&&te!=="rgb(255, 255, 255)"&&te!=="#ffffff"&&te!=="#FFFFFF"){const z=(H=>{if(H.startsWith("#"))return H.toUpperCase();const je=H.match(/\d+/g);if(!je||je.length<3)return null;const le=je[0],ue=je[1],$e=je[2];if(!le||!ue||!$e)return null;const Te=parseInt(le).toString(16).padStart(2,"0"),Ve=parseInt(ue).toString(16).padStart(2,"0"),Qe=parseInt($e).toString(16).padStart(2,"0");return`#${Te}${Ve}${Qe}`.toUpperCase()})(te);if(z&&z===D.toUpperCase()){O=!0;break}}G=G.parentElement}}if(D==="transparent"||O){const M=S.getRangeAt(0);if(M.collapsed)document.execCommand("removeFormat",!1);else{const W=M.extractContents(),G=document.createDocumentFragment(),re=te=>{if(te.nodeType===Node.TEXT_NODE)return te.cloneNode(!0);if(te.nodeType===Node.ELEMENT_NODE){const $=te,z=document.createElement($.tagName.toLowerCase());return Array.from($.attributes).forEach(H=>{H.name!=="style"&&H.name!=="class"&&z.setAttribute(H.name,H.value)}),Array.from($.childNodes).forEach(H=>{const je=re(H);je&&z.appendChild(je)}),$.style.backgroundColor&&(z.style.backgroundColor=""),z}return null};Array.from(W.childNodes).forEach(te=>{const $=re(te);$&&G.appendChild($)}),M.insertNode(G),document.execCommand("removeFormat",!1)}g(null),f("#FFEB3B")}else if(S.rangeCount>0&&!S.getRangeAt(0).collapsed)document.execCommand("backColor",!1,D),g(D),D!=="transparent"&&/^#[0-9A-Fa-f]{6}$/i.test(D)&&f(D);else return;const I=window.getSelection();I&&I.removeAllRanges(),l.current&&s(va(l.current.innerHTML)),x(!1),setTimeout(()=>{l.current&&l.current.focus(),R()},50)},[o,s,R]),P=p.useCallback(D=>{if(!l.current)return;o||l.current.focus();const S=window.getSelection();if(!S||S.rangeCount===0){l.current.focus();return}let O=!1;if(S.rangeCount>0){const M=S.getRangeAt(0).commonAncestorContainer;let W=null;for(M.nodeType===Node.TEXT_NODE?W=M.parentElement:W=M;W&&W!==l.current;){const re=window.getComputedStyle(W).color;if(re){const $=(z=>{if(z.startsWith("#"))return z.toUpperCase();const H=z.match(/\d+/g);if(!H||H.length<3)return null;const je=H[0],le=H[1],ue=H[2];if(!je||!le||!ue)return null;const $e=parseInt(je).toString(16).padStart(2,"0"),Te=parseInt(le).toString(16).padStart(2,"0"),Ve=parseInt(ue).toString(16).padStart(2,"0");return`#${$e}${Te}${Ve}`.toUpperCase()})(re);if(D==="#000000"){if($==="#000000"||!$){O=!0;break}}else if($&&$===D.toUpperCase()){O=!0;break}}W=W.parentElement}}if(D==="transparent"||D==="default"||O){if(D==="#000000"&&O){v(!1);return}document.execCommand("removeFormat",!1),w(null),N("#000000")}else document.execCommand("foreColor",!1,D),w(D),D!=="transparent"&&/^#[0-9A-Fa-f]{6}$/i.test(D)&&N(D);l.current&&s(va(l.current.innerHTML)),v(!1),setTimeout(R,10)},[o,s,R]),B=p.useCallback(()=>{l.current&&s(va(l.current.innerHTML)),R()},[s,R]),k=p.useCallback(D=>{if(D.ctrlKey&&D.key==="b"){D.preventDefault(),j("bold");return}if(D.ctrlKey&&D.key==="i"){D.preventDefault(),j("italic");return}if(D.ctrlKey&&D.key==="u"){D.preventDefault(),j("underline");return}},[j]),L=p.useCallback(()=>{c(!0)},[]),V=p.useCallback(()=>{c(!1),l.current&&s(va(l.current.innerHTML))},[s]);return p.useEffect(()=>{if(!o)return;const D=()=>{R()};return document.addEventListener("selectionchange",D),()=>{document.removeEventListener("selectionchange",D)}},[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(F,{type:"button",variant:"ghost",size:"sm",className:Ae("h-7 w-7 p-0",d.has("bold")&&"bg-blue-100 text-blue-700"),onClick:()=>j("bold"),title:"Bold (Ctrl+B)",children:e.jsx(Af,{className:"h-4 w-4"})}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:Ae("h-7 w-7 p-0",d.has("italic")&&"bg-blue-100 text-blue-700"),onClick:()=>j("italic"),title:"Italic (Ctrl+I)",children:e.jsx(Tf,{className:"h-4 w-4"})}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:Ae("h-7 w-7 p-0",d.has("underline")&&"bg-blue-100 text-blue-700"),onClick:()=>j("underline"),title:"Underline (Ctrl+U)",children:e.jsx(kf,{className:"h-4 w-4"})}),e.jsxs(Xs,{open:h,onOpenChange:x,children:[e.jsx(Zs,{asChild:!0,children:e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:Ae("h-7 w-7 p-0",d.has("highlight")&&"bg-blue-100 text-blue-700"),title:"Text Highlight",children:e.jsx(Rf,{className:"h-4 w-4"})})}),e.jsx(Js,{className:"w-auto p-2",align:"start",onPointerDownOutside:D=>{D.target.closest("[data-popover-content]")&&D.preventDefault()},children:e.jsxs("div",{className:"space-y-2 relative",onClick:D=>D.stopPropagation(),children:[e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:"absolute top-0 right-0 h-6 w-6 p-0 hover:bg-gray-100",onClick:D=>{D.stopPropagation(),x(!1)},title:"Close",children:e.jsx(ft,{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:On.map(D=>{const S=u===D.value,O=D.value==="transparent";return e.jsxs("button",{type:"button",onClick:I=>{I.preventDefault(),I.stopPropagation(),E(S&&!O?"transparent":D.value)},className:Ae("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md relative",D.class,S&&"ring-2 ring-blue-600 ring-offset-1 border-blue-600",O&&"border-gray-400 bg-white",!O&&!S&&"border-gray-300"),title:S&&!O?`${D.name} (Click to remove)`:D.name,style:O?{}:{backgroundColor:D.value},children:[O&&e.jsx("span",{className:"text-[10px] text-gray-600 font-bold",children:"×"}),S&&!O&&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"})})]},D.value)})}),u&&u!=="transparent"&&e.jsx("div",{className:"mb-2",children:e.jsx(F,{type:"button",variant:"outline",size:"sm",className:"w-full h-7 text-xs",onClick:D=>{D.stopPropagation(),E("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:u&&u!=="transparent"?u:b,onChange:D=>{const S=D.target.value;f(S);const O=window.getSelection();O&&O.rangeCount>0&&!O.getRangeAt(0).collapsed&&E(S)},className:"w-8 h-8 rounded border border-gray-300 cursor-pointer",title:"Pick a custom color"}),e.jsx("input",{type:"text",value:u&&u!=="transparent"?u:b,onChange:D=>{D.stopPropagation();const S=D.target.value;f(S)},onKeyDown:D=>{if(D.stopPropagation(),D.key==="Enter"){D.preventDefault();const S=D.currentTarget.value.trim();/^#[0-9A-Fa-f]{6}$/i.test(S)&&E(S)}},onPaste:D=>{D.stopPropagation();const S=D.clipboardData.getData("text").trim();D.preventDefault(),setTimeout(()=>{if(/^#[0-9A-Fa-f]{6}$/i.test(S)){f(S);const O=window.getSelection();O&&O.rangeCount>0&&!O.getRangeAt(0).collapsed&&E(S)}else{const O=S.match(/^([0-9A-Fa-f]{6})$/);if(O){const I=`#${O[1]}`;f(I);const M=window.getSelection();M&&M.rangeCount>0&&!M.getRangeAt(0).collapsed&&E(I)}}},0)},onClick:D=>{D.stopPropagation()},onFocus:D=>{D.stopPropagation(),D.target.select()},onBlur:D=>{const S=D.target.value.trim();if(/^#[0-9A-Fa-f]{6}$/i.test(S)){const O=window.getSelection();O&&O.rangeCount>0&&!O.getRangeAt(0).collapsed&&E(S)}else f(S===""?u||"#FFEB3B":S)},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(F,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>{const D=b.trim();/^#[0-9A-Fa-f]{6}$/i.test(D)?E(D):f(u||"#FFEB3B")},title:"Apply custom color",children:"Apply"})]})]})]})})]}),e.jsxs(Xs,{open:y,onOpenChange:v,children:[e.jsx(Zs,{asChild:!0,children:e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:Ae("h-7 w-7 p-0",d.has("textColor")&&"bg-blue-100 text-blue-700"),title:"Text Color",children:e.jsx(Df,{className:"h-4 w-4"})})}),e.jsx(Js,{className:"w-auto p-2",align:"start",onPointerDownOutside:D=>{D.target.closest("[data-popover-content]")&&D.preventDefault()},children:e.jsxs("div",{className:"space-y-2 relative",onClick:D=>D.stopPropagation(),children:[e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:"absolute top-0 right-0 h-6 w-6 p-0 hover:bg-gray-100",onClick:D=>{D.stopPropagation(),v(!1)},title:"Close",children:e.jsx(ft,{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:D=>{D.preventDefault(),D.stopPropagation(),C==="#000000"||!C&&!d.has("textColor")||P("#000000")},className:Ae("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md flex items-center justify-center bg-black",(C==="#000000"||!C&&!d.has("textColor"))&&"ring-2 ring-blue-600 ring-offset-1 border-blue-600",C!=="#000000"&&(C||d.has("textColor"))&&"border-gray-300"),title:"Default (Black)",children:[e.jsx("span",{className:"text-[10px] text-white font-bold",children:"A"}),(C==="#000000"||!C&&!d.has("textColor"))&&e.jsx("span",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("span",{className:"w-2 h-2 bg-white rounded-full shadow-sm"})})]}),On.filter(D=>D.value!=="transparent").map(D=>{const S=C===D.value;return e.jsxs("button",{type:"button",onClick:O=>{O.preventDefault(),O.stopPropagation(),P(S?"#000000":D.value)},className:Ae("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md flex items-center justify-center relative",S&&"ring-2 ring-blue-600 ring-offset-1 border-blue-600",!S&&"border-gray-300"),title:S?`${D.name} (Click to reset to default)`:D.name,style:{color:D.value,borderColor:S?"#2563eb":D.value},children:[e.jsx("span",{className:"text-xs font-bold",children:"A"}),S&&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-${D.value}`)})]}),C&&C!=="#000000"&&e.jsx("div",{className:"mb-2",children:e.jsx(F,{type:"button",variant:"outline",size:"sm",className:"w-full h-7 text-xs",onClick:D=>{D.stopPropagation(),P("#000000")},title:"Reset to default black",children:"Reset to Default"})}),e.jsxs("div",{className:"border-t border-gray-200 pt-2 mt-2",children:[e.jsx("div",{className:"text-xs font-semibold text-gray-700 mb-1.5",children:"Custom Color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:C||A,onChange:D=>{const S=D.target.value;N(S),P(S)},className:"w-8 h-8 rounded border border-gray-300 cursor-pointer",title:"Pick a custom text color"}),e.jsx("input",{type:"text",value:C||A,onChange:D=>{const S=D.target.value;N(S)},onKeyDown:D=>{if(D.key==="Enter"){D.preventDefault();const S=D.currentTarget.value;/^#[0-9A-Fa-f]{6}$/.test(S)&&P(S)}},onBlur:D=>{const S=D.target.value;/^#[0-9A-Fa-f]{6}$/.test(S)?P(S):S===""&&N(C||"#000000")},placeholder:"#000000",className:"flex-1 h-7 px-2 text-xs border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500",title:"Enter hex color code (Press Enter or click Apply)"}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>P(A),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(F,{type:"button",variant:"ghost",size:"sm",className:Ae("h-7 w-7 p-0",d.has("h1")&&"bg-blue-100 text-blue-700"),onClick:()=>j("formatBlock","<h1>"),title:"Heading 1",children:e.jsx(Pf,{className:"h-4 w-4"})}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:Ae("h-7 w-7 p-0",d.has("h2")&&"bg-blue-100 text-blue-700"),onClick:()=>j("formatBlock","<h2>"),title:"Heading 2",children:e.jsx(If,{className:"h-4 w-4"})}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:Ae("h-7 w-7 p-0",d.has("h3")&&"bg-blue-100 text-blue-700"),onClick:()=>j("formatBlock","<h3>"),title:"Heading 3",children:e.jsx(Ef,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-1 border-r border-gray-300 pr-2",children:[e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:Ae("h-7 w-7 p-0",d.has("ul")&&"bg-blue-100 text-blue-700"),onClick:()=>j("insertUnorderedList"),title:"Bullet List",children:e.jsx(Nx,{className:"h-4 w-4"})}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:Ae("h-7 w-7 p-0",d.has("ol")&&"bg-blue-100 text-blue-700"),onClick:()=>j("insertOrderedList"),title:"Numbered List",children:e.jsx(Ff,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:Ae("h-7 w-7 p-0",d.has("left")&&"bg-blue-100 text-blue-700"),onClick:()=>j("justifyLeft"),title:"Align Left",children:e.jsx(Sx,{className:"h-4 w-4"})}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:Ae("h-7 w-7 p-0",d.has("center")&&"bg-blue-100 text-blue-700"),onClick:()=>j("justifyCenter"),title:"Align Center",children:e.jsx(_f,{className:"h-4 w-4"})}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:Ae("h-7 w-7 p-0",d.has("right")&&"bg-blue-100 text-blue-700"),onClick:()=>j("justifyRight"),title:"Align Right",children:e.jsx(Lf,{className:"h-4 w-4"})})]})]}),e.jsx("div",{ref:l,contentEditable:!0,onPaste:T,onInput:B,onFocus:L,onBlur:V,onKeyDown:k,onMouseUp:R,onKeyUp:R,"data-placeholder":a,className:Ae("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 Bs({content:t,className:s}){const a=p.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">${i}</div>`),va(r)},[t]);return t?e.jsx("div",{className:Ae("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 Rh={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(bi,function(){var a=1e3,r=6e4,n=36e5,i="millisecond",l="second",o="minute",c="hour",d="day",m="week",h="month",x="quarter",u="year",g="date",b="Invalid Date",f=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,y=/\[([^\]]+)]|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(k){var L=["th","st","nd","rd"],V=k%100;return"["+k+(L[(V-20)%10]||L[V]||L[0])+"]"}},C=function(k,L,V){var D=String(k);return!D||D.length>=L?k:""+Array(L+1-D.length).join(V)+k},w={s:C,z:function(k){var L=-k.utcOffset(),V=Math.abs(L),D=Math.floor(V/60),S=V%60;return(L<=0?"+":"-")+C(D,2,"0")+":"+C(S,2,"0")},m:function k(L,V){if(L.date()<V.date())return-k(V,L);var D=12*(V.year()-L.year())+(V.month()-L.month()),S=L.clone().add(D,h),O=V-S<0,I=L.clone().add(D+(O?-1:1),h);return+(-(D+(V-S)/(O?S-I:I-S))||0)},a:function(k){return k<0?Math.ceil(k)||0:Math.floor(k)},p:function(k){return{M:h,y:u,w:m,d,D:g,h:c,m:o,s:l,ms:i,Q:x}[k]||String(k||"").toLowerCase().replace(/s$/,"")},u:function(k){return k===void 0}},A="en",N={};N[A]=v;var _="$isDayjsObject",T=function(k){return k instanceof P||!(!k||!k[_])},R=function k(L,V,D){var S;if(!L)return A;if(typeof L=="string"){var O=L.toLowerCase();N[O]&&(S=O),V&&(N[O]=V,S=O);var I=L.split("-");if(!S&&I.length>1)return k(I[0])}else{var M=L.name;N[M]=L,S=M}return!D&&S&&(A=S),S||!D&&A},j=function(k,L){if(T(k))return k.clone();var V=typeof L=="object"?L:{};return V.date=k,V.args=arguments,new P(V)},E=w;E.l=R,E.i=T,E.w=function(k,L){return j(k,{locale:L.$L,utc:L.$u,x:L.$x,$offset:L.$offset})};var P=function(){function k(V){this.$L=R(V.locale,null,!0),this.parse(V),this.$x=this.$x||V.x||{},this[_]=!0}var L=k.prototype;return L.parse=function(V){this.$d=function(D){var S=D.date,O=D.utc;if(S===null)return new Date(NaN);if(E.u(S))return new Date;if(S instanceof Date)return new Date(S);if(typeof S=="string"&&!/Z$/i.test(S)){var I=S.match(f);if(I){var M=I[2]-1||0,W=(I[7]||"0").substring(0,3);return O?new Date(Date.UTC(I[1],M,I[3]||1,I[4]||0,I[5]||0,I[6]||0,W)):new Date(I[1],M,I[3]||1,I[4]||0,I[5]||0,I[6]||0,W)}}return new Date(S)}(V),this.init()},L.init=function(){var V=this.$d;this.$y=V.getFullYear(),this.$M=V.getMonth(),this.$D=V.getDate(),this.$W=V.getDay(),this.$H=V.getHours(),this.$m=V.getMinutes(),this.$s=V.getSeconds(),this.$ms=V.getMilliseconds()},L.$utils=function(){return E},L.isValid=function(){return this.$d.toString()!==b},L.isSame=function(V,D){var S=j(V);return this.startOf(D)<=S&&S<=this.endOf(D)},L.isAfter=function(V,D){return j(V)<this.startOf(D)},L.isBefore=function(V,D){return this.endOf(D)<j(V)},L.$g=function(V,D,S){return E.u(V)?this[D]:this.set(S,V)},L.unix=function(){return Math.floor(this.valueOf()/1e3)},L.valueOf=function(){return this.$d.getTime()},L.startOf=function(V,D){var S=this,O=!!E.u(D)||D,I=E.p(V),M=function(je,le){var ue=E.w(S.$u?Date.UTC(S.$y,le,je):new Date(S.$y,le,je),S);return O?ue:ue.endOf(d)},W=function(je,le){return E.w(S.toDate()[je].apply(S.toDate("s"),(O?[0,0,0,0]:[23,59,59,999]).slice(le)),S)},G=this.$W,re=this.$M,te=this.$D,$="set"+(this.$u?"UTC":"");switch(I){case u:return O?M(1,0):M(31,11);case h:return O?M(1,re):M(0,re+1);case m:var z=this.$locale().weekStart||0,H=(G<z?G+7:G)-z;return M(O?te-H:te+(6-H),re);case d:case g:return W($+"Hours",0);case c:return W($+"Minutes",1);case o:return W($+"Seconds",2);case l:return W($+"Milliseconds",3);default:return this.clone()}},L.endOf=function(V){return this.startOf(V,!1)},L.$set=function(V,D){var S,O=E.p(V),I="set"+(this.$u?"UTC":""),M=(S={},S[d]=I+"Date",S[g]=I+"Date",S[h]=I+"Month",S[u]=I+"FullYear",S[c]=I+"Hours",S[o]=I+"Minutes",S[l]=I+"Seconds",S[i]=I+"Milliseconds",S)[O],W=O===d?this.$D+(D-this.$W):D;if(O===h||O===u){var G=this.clone().set(g,1);G.$d[M](W),G.init(),this.$d=G.set(g,Math.min(this.$D,G.daysInMonth())).$d}else M&&this.$d[M](W);return this.init(),this},L.set=function(V,D){return this.clone().$set(V,D)},L.get=function(V){return this[E.p(V)]()},L.add=function(V,D){var S,O=this;V=Number(V);var I=E.p(D),M=function(re){var te=j(O);return E.w(te.date(te.date()+Math.round(re*V)),O)};if(I===h)return this.set(h,this.$M+V);if(I===u)return this.set(u,this.$y+V);if(I===d)return M(1);if(I===m)return M(7);var W=(S={},S[o]=r,S[c]=n,S[l]=a,S)[I]||1,G=this.$d.getTime()+V*W;return E.w(G,this)},L.subtract=function(V,D){return this.add(-1*V,D)},L.format=function(V){var D=this,S=this.$locale();if(!this.isValid())return S.invalidDate||b;var O=V||"YYYY-MM-DDTHH:mm:ssZ",I=E.z(this),M=this.$H,W=this.$m,G=this.$M,re=S.weekdays,te=S.months,$=S.meridiem,z=function(le,ue,$e,Te){return le&&(le[ue]||le(D,O))||$e[ue].slice(0,Te)},H=function(le){return E.s(M%12||12,le,"0")},je=$||function(le,ue,$e){var Te=le<12?"AM":"PM";return $e?Te.toLowerCase():Te};return O.replace(y,function(le,ue){return ue||function($e){switch($e){case"YY":return String(D.$y).slice(-2);case"YYYY":return E.s(D.$y,4,"0");case"M":return G+1;case"MM":return E.s(G+1,2,"0");case"MMM":return z(S.monthsShort,G,te,3);case"MMMM":return z(te,G);case"D":return D.$D;case"DD":return E.s(D.$D,2,"0");case"d":return String(D.$W);case"dd":return z(S.weekdaysMin,D.$W,re,2);case"ddd":return z(S.weekdaysShort,D.$W,re,3);case"dddd":return re[D.$W];case"H":return String(M);case"HH":return E.s(M,2,"0");case"h":return H(1);case"hh":return H(2);case"a":return je(M,W,!0);case"A":return je(M,W,!1);case"m":return String(W);case"mm":return E.s(W,2,"0");case"s":return String(D.$s);case"ss":return E.s(D.$s,2,"0");case"SSS":return E.s(D.$ms,3,"0");case"Z":return I}return null}(le)||I.replace(":","")})},L.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},L.diff=function(V,D,S){var O,I=this,M=E.p(D),W=j(V),G=(W.utcOffset()-this.utcOffset())*r,re=this-W,te=function(){return E.m(I,W)};switch(M){case u:O=te()/12;break;case h:O=te();break;case x:O=te()/3;break;case m:O=(re-G)/6048e5;break;case d:O=(re-G)/864e5;break;case c:O=re/n;break;case o:O=re/r;break;case l:O=re/a;break;default:O=re}return S?O:E.a(O)},L.daysInMonth=function(){return this.endOf(h).$D},L.$locale=function(){return N[this.$L]},L.locale=function(V,D){if(!V)return this.$L;var S=this.clone(),O=R(V,D,!0);return O&&(S.$L=O),S},L.clone=function(){return E.w(this.$d,this)},L.toDate=function(){return new Date(this.valueOf())},L.toJSON=function(){return this.isValid()?this.toISOString():null},L.toISOString=function(){return this.$d.toISOString()},L.toString=function(){return this.$d.toUTCString()},k}(),B=P.prototype;return j.prototype=B,[["$ms",i],["$s",l],["$m",o],["$H",c],["$W",d],["$M",h],["$y",u],["$D",g]].forEach(function(k){B[k[1]]=function(L){return this.$g(L,k[0],k[1])}}),j.extend=function(k,L){return k.$i||(k(L,P,j),k.$i=!0),j},j.locale=R,j.isDayjs=T,j.unix=function(k){return j(1e3*k)},j.en=N[A],j.Ls=N,j.p={},j})})(Rh);var EN=Rh.exports;const Ht=yi(EN);var Dh={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(bi,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,h,x){return i.fromToBase(d,m,h,x)}n.en.relativeTime=l,i.fromToBase=function(d,m,h,x,u){for(var g,b,f,y=h.$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"}],C=v.length,w=0;w<C;w+=1){var A=v[w];A.d&&(g=x?n(d).diff(h,A.d,!0):h.diff(d,A.d,!0));var N=(a.rounding||Math.round)(Math.abs(g));if(f=g>0,N<=A.r||!A.r){N<=1&&w>0&&(A=v[w-1]);var _=y[A.l];u&&(N=u(""+N)),b=typeof _=="string"?_.replace("%d",N):_(N,m,A.l,f);break}}if(m)return b;var T=f?y.future:y.past;return typeof T=="function"?T(b):T.replace("%s",b)},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)}}})})(Dh);var FN=Dh.exports;const _N=yi(FN);Ht.extend(_N);function LN({request:t,isInitiator:s,needsClosure:a,conclusionRemark:r,setConclusionRemark:n,conclusionLoading:i,conclusionSubmitting:l,aiGenerated:o,handleGenerateConclusion:c,handleFinalizeConclusion:d,onPause:m,onResume:h,onRetrigger:x,currentUserIsApprover:u=!1,pausedByUserId:g,currentUserId:b,generationAttempts:f=0,generationFailed:y=!1,maxAttemptsReached:v=!1}){var j,E,P,B,k,L,V,D;const{user:C}=Jt(),w=t==null?void 0:t.pauseInfo,A=(w==null?void 0:w.isPaused)||!1,N=(j=w==null?void 0:w.pausedBy)==null?void 0:j.userId,_=(C==null?void 0:C.userId)||"",T=A&&h&&(u||s),R=A&&s&&N&&N!==_&&x;return e.jsxs("div",{className:"space-y-4 sm:space-y-6","data-testid":"overview-tab-content",children:[e.jsxs(se,{"data-testid":"initiator-card",children:[e.jsx(ge,{className:"pb-3 sm:pb-4",children:e.jsxs(fe,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Gt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Initiator"]})}),e.jsx(ae,{children:e.jsxs("div",{className:"flex items-start gap-3 sm:gap-4",children:[e.jsx(ts,{className:"h-10 w-10 sm:h-12 sm:w-12 ring-2 ring-white shadow-sm flex-shrink-0",children:e.jsx(ss,{className:"bg-gray-700 text-white font-semibold text-sm",children:((E=t.initiator)==null?void 0:E.avatar)||"U"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-gray-900 text-sm sm:text-base truncate",children:((P=t.initiator)==null?void 0:P.name)||"N/A"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 truncate",children:((B=t.initiator)==null?void 0:B.role)||"N/A"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-500 truncate",children:((k=t.initiator)==null?void 0:k.department)||"N/A"}),e.jsxs("div",{className:"mt-2 sm:mt-3 space-y-1.5 sm:space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs sm:text-sm text-gray-600 min-w-0",children:[e.jsx(Da,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:((L=t.initiator)==null?void 0:L.email)||"N/A"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs sm:text-sm text-gray-600",children:[e.jsx(Ni,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{children:((V=t.initiator)==null?void 0:V.phone)||"N/A"})]})]})]})]})})]}),e.jsxs(se,{"data-testid":"request-details-card",children:[e.jsx(ge,{className:"pb-3 sm:pb-4",children:e.jsxs(fe,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(ke,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Details"]})}),e.jsxs(ae,{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(Bs,{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:as(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:as(t.updatedAt)})]})]})]})]}),A&&w&&e.jsxs(se,{className:"border-orange-300 bg-orange-50/50","data-testid":"pause-status-card",children:[e.jsx(ge,{className:"pb-3 sm:pb-4",children:e.jsxs(fe,{className:"flex items-center gap-2 text-sm sm:text-base text-orange-800",children:[e.jsx(Ka,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Workflow Paused"]})}),e.jsxs(ae,{className:"space-y-3 sm:space-y-4",children:[e.jsx("div",{className:"bg-white rounded-lg p-3 sm:p-4 border border-orange-200",children:e.jsxs("div",{className:"space-y-2 sm:space-y-3",children:[w.pauseReason&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Reason"}),e.jsx(Bs,{content:w.pauseReason,className:"text-sm text-gray-900 mt-1"})]}),w.pausedBy&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Paused By"}),e.jsx("p",{className:"text-sm text-gray-900 mt-1",children:w.pausedBy.name||w.pausedBy.email})]}),w.pauseResumeDate&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Auto-Resume Date"}),e.jsxs("p",{className:"text-sm text-gray-900 mt-1",children:[as(w.pauseResumeDate),Ht(w.pauseResumeDate).isAfter(Ht())&&e.jsxs("span",{className:"ml-2 text-xs text-gray-500",children:["(",Ht(w.pauseResumeDate).fromNow(),")"]})]})]}),w.pausedAt&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Paused At"}),e.jsx("p",{className:"text-sm text-gray-900 mt-1",children:as(w.pausedAt)})]})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-2 border-t border-orange-200",children:[T&&h&&e.jsxs(F,{onClick:h,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(ii,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-1.5"}),"Resume Now"]}),R&&x&&e.jsxs(F,{onClick:x,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(Ye,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-1.5"}),"Request Resume"]})]})]})]}),t.claimDetails&&e.jsxs(se,{children:[e.jsx(ge,{className:"pb-4",children:e.jsxs(fe,{className:"flex items-center gap-2 text-base",children:[e.jsx(ke,{className:"w-5 h-5 text-purple-600"}),"Claim Management Details"]})}),e.jsxs(ae,{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?kh(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(Bs,{content:t.claimDetails.requestDescription,className:"text-sm"})})]})]})]}),t.status==="closed"&&t.conclusionRemark&&e.jsxs(se,{children:[e.jsxs(ge,{className:"bg-gradient-to-r from-gray-50 to-slate-50 border-b border-gray-200",children:[e.jsxs(fe,{className:"flex items-center gap-2 text-base",children:[e.jsx(Re,{className:"w-5 h-5 text-gray-600"}),"Conclusion Remark"]}),e.jsx(Ue,{className:"mt-1 text-xs sm:text-sm",children:"Final summary of this closed request"})]}),e.jsxs(ae,{className:"pt-4",children:[e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-4",children:e.jsx(Bs,{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 ",as(t.closureDate)]}),e.jsxs("span",{children:["By ",((D=t.initiator)==null?void 0:D.name)||"Initiator"]})]})]})]}),a&&e.jsxs(se,{"data-testid":"conclusion-remark-card",children:[e.jsx(ge,{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(fe,{className:`flex items-center gap-2 text-base sm:text-lg ${t.status==="rejected"?"text-red-700":"text-green-700"}`,children:[e.jsx(Re,{className:`w-5 h-5 ${t.status==="rejected"?"text-red-600":"text-green-600"}`}),"Conclusion Remark - Final Step"]}),e.jsx(Ue,{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("div",{className:"flex flex-col items-end gap-1.5",children:[e.jsxs(F,{variant:"outline",size:"sm",onClick:c,disabled:i||v,className:"gap-2 shrink-0 h-9","data-testid":"generate-ai-conclusion-button",children:[e.jsx(Ut,{className:`w-3.5 h-3.5 ${i?"animate-spin":""}`}),o?"Regenerate":"Generate with AI"]}),o&&!v&&!y&&e.jsxs("span",{className:"text-[10px] text-gray-500 font-medium px-1",children:[2-f," attempts remaining"]})]})]})}),e.jsx(ae,{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(it,{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(Pn,{value:r,onChange:S=>n(S),placeholder:"Enter a professional conclusion remark summarizing the request outcome, key decisions, and approvals...",className:"text-sm",minHeight:"160px","data-testid":"conclusion-remark-textarea"}),e.jsx("p",{className:"text-xs text-blue-600 mt-1",children:"💡 Tip: You can paste formatted content (lists, tables) and the formatting will be preserved."}),e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsx("p",{className:"text-xs text-gray-500",children:"This will be the final summary for this request"}),e.jsxs("p",{className:"text-xs text-gray-500","data-testid":"character-count",children:[r?r.replace(/<[^>]*>/g,"").length:0," / 2000 characters"]})]})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs sm:text-sm font-semibold text-blue-900 mb-1.5",children:"Finalizing this request will:"}),e.jsxs("ul",{className:"text-xs sm:text-sm text-blue-800 space-y-0.5 pl-4",children:[e.jsx("li",{className:"list-disc",children:'Change request status to "CLOSED"'}),e.jsx("li",{className:"list-disc",children:"Notify all participants of closure"}),e.jsx("li",{className:"list-disc",children:"Move request to Closed Requests"}),e.jsx("li",{className:"list-disc",children:"Save conclusion remark permanently"})]})]}),e.jsx("div",{className:"flex gap-3 justify-end pt-3 border-t",children:e.jsx(F,{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(it,{className:"w-4 h-4 mr-2 animate-spin"}),"Finalizing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Re,{className:"w-4 h-4 mr-2"}),"Finalize & Close Request"]})})})]})})]})]})}function Zn({delayDuration:t=0,...s}){return e.jsx(L0,{"data-slot":"tooltip-provider",delayDuration:t,...s})}function nl({...t}){return e.jsx(Zn,{children:e.jsx(M0,{"data-slot":"tooltip",...t})})}function il({...t}){return e.jsx($0,{"data-slot":"tooltip-trigger",...t})}function ll({className:t,sideOffset:s=0,children:a,...r}){return e.jsx(O0,{children:e.jsxs(U0,{"data-slot":"tooltip-content",sideOffset:s,className:Ae("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(B0,{className:"bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function ht({...t}){return e.jsx(H0,{"data-slot":"dialog",...t})}function MN({...t}){return e.jsx(z0,{"data-slot":"dialog-portal",...t})}const Ph=p.forwardRef(({className:t,...s},a)=>e.jsx(cx,{ref:a,"data-slot":"dialog-overlay",className:Ae("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}));Ph.displayName=cx.displayName;const dt=p.forwardRef(({className:t,children:s,...a},r)=>e.jsxs(MN,{"data-slot":"dialog-portal",children:[e.jsx(Ph,{}),e.jsxs(dx,{ref:r,"data-slot":"dialog-content",className:Ae("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(V0,{className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[e.jsx(ft,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));dt.displayName=dx.displayName;const pt=p.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,"data-slot":"dialog-header",className:Ae("flex flex-col gap-2 text-center sm:text-left",t),...s}));pt.displayName="DialogHeader";const Rt=p.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,"data-slot":"dialog-footer",className:Ae("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s}));Rt.displayName="DialogFooter";const mt=p.forwardRef(({className:t,...s},a)=>e.jsx(mx,{ref:a,"data-slot":"dialog-title",className:Ae("text-lg leading-none font-semibold",t),...s}));mt.displayName=mx.displayName;const Pt=p.forwardRef(({className:t,...s},a)=>e.jsx(ux,{ref:a,"data-slot":"dialog-description",className:Ae("text-muted-foreground text-sm",t),...s}));Pt.displayName=ux.displayName;function _s({className:t,...s}){return e.jsx("textarea",{"data-slot":"textarea",className:Ae("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 Am=t=>{if(t<8)return Mt(t);const a=Math.floor(t/8),r=t%8;return r>0?`${a}d ${Mt(r)}`:`${a}d`},$N=(t,s)=>{if(s)return e.jsx(Ye,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"});switch(t){case"approved":return e.jsx(Re,{className:"w-4 h-4 sm:w-5 sm:w-5 text-green-600"});case"rejected":return e.jsx(Ct,{className:"w-4 h-4 sm:w-5 sm:h-5 text-red-600"});case"paused":return e.jsx(Ax,{className:"w-4 h-4 sm:w-5 sm:h-5 text-yellow-600"});case"pending":case"in-review":return e.jsx(nt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"});case"waiting":return e.jsx(nt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400"});default:return e.jsx(nt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400"})}};function ON({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}=Jt(),[m,h]=p.useState(!1),[x,u]=p.useState(""),[g,b]=p.useState(!1),f=(a==null?void 0:a.breachReason)||(t==null?void 0:t.breachReason)||"";p.useEffect(()=>{m||u("")},[m]);const y=t.status==="pending"||t.status==="in-review",v=t.status==="approved",C=t.status==="rejected",w=t.status==="waiting",A=t.status==="paused",N=Number(t.tatHours||0),_=t.actualHours??0,T=v&&_?Math.max(0,N-_):0,R=N>0?_/N*100:0,j=R>=100,E=(d==null?void 0:d.role)==="ADMIN",P=Di(d),B=t.approverId===(d==null?void 0:d.userId),k=E||P||B,L=async()=>{var V,D;if(!x.trim()){K.error("Breach Reason Required",{description:"Please enter a reason for the breach."});return}b(!0);try{await DN(t.levelId,x.trim()),h(!1),u(""),K.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(S){console.error("Error updating breach reason:",S);const O=((D=(V=S==null?void 0:S.response)==null?void 0:V.data)==null?void 0:D.error)||(S==null?void 0:S.message)||"Failed to update breach reason. Please try again.";K.error("Failed to Update Breach Reason",{description:O,duration:5e3})}finally{b(!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":y?"border-blue-500 bg-blue-50 shadow-md":v?"border-green-500 bg-green-50":C?"border-red-500 bg-red-50":w?"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":A?"bg-yellow-100":y?"bg-blue-100":v?"bg-green-100":C?"bg-red-100":w?"bg-gray-200":"bg-gray-100"}`,children:$N(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(oe,{variant:"outline",className:`text-xs shrink-0 capitalize ${t.isSkipped?"bg-orange-100 text-orange-800 border-orange-200":y?"bg-yellow-100 text-yellow-800 border-yellow-200":v?"bg-green-100 text-green-800 border-green-200":C?"bg-red-100 text-red-800 border-red-200":w?"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(Zn,{delayDuration:200,children:e.jsxs(nl,{children:[e.jsx(il,{asChild:!0,children:e.jsx("button",{type:"button",className:"inline-flex items-center justify-center cursor-pointer hover:opacity-80 transition-opacity",onClick:V=>V.stopPropagation(),children:e.jsx(Ye,{className:"w-4 h-4 text-orange-600"})})}),e.jsxs(ll,{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(rm,{className:"w-3 h-3"}),"Skip Reason:"]}),e.jsx("p",{className:"text-xs text-gray-700",children:t.skipReason})]})]})}),v&&_&&e.jsx(oe,{className:"bg-green-600 text-white text-xs","data-testid":`${c}-completion-time`,children:Am(_)})]}),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:[N," hours"]})]})]}),v&&_!==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?as(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:Am(_)})]}),e.jsx("div",{className:"space-y-2",children:(()=>{const V=Math.min(100,R),D=()=>j?"bg-red-600":R>=75?"bg-orange-500":R>=50?"bg-amber-500":"bg-green-600",S=()=>j?"text-red-600":R>=75?"text-orange-600":R>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(oa,{value:V,className:"h-2 bg-gray-200",indicatorClassName:D(),"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 ${S()}`,children:[Math.round(V),"% of TAT used"]}),j&&k&&e.jsx(Zn,{children:e.jsxs(nl,{children:[e.jsx(il,{asChild:!0,children:e.jsx(F,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",onClick:()=>{u(f),h(!0)},children:e.jsx(Mn,{className:"w-3 h-3"})})}),e.jsx(ll,{children:e.jsx("p",{children:f?"Edit breach reason":"Add breach reason"})})]})})]}),T>0&&e.jsxs("span",{className:"text-green-600 font-semibold",children:["Saved ",Mt(T)]})]})]})})()}),j&&f&&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(Mn,{className:"w-3.5 h-3.5"}),"Breach Reason:"]}),e.jsx("p",{className:"text-sm text-gray-700 leading-relaxed whitespace-pre-line",children:f})]}),t.comment&&e.jsxs("div",{className:"mt-4 p-3 sm:p-4 bg-blue-50 border-l-4 border-blue-500 rounded-r-lg",children:[e.jsxs("p",{className:"text-xs font-semibold text-gray-700 mb-2 flex items-center gap-1.5",children:[e.jsx(Ds,{className:"w-3.5 h-3.5 text-blue-600"}),"Conclusion Remark:"]}),e.jsx("p",{className:"text-sm text-gray-700 italic leading-relaxed",children:t.comment})]})]}),i&&(y||A)&&(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?ga(a.sla.deadline,!0):"Not set"})]}),e.jsxs("div",{className:`border rounded-lg p-3 ${A?"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(nt,{className:"w-4 h-4"}),"Current Approver - Time Tracking ",A&&"(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," / ",Mt(N)," allocated"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[(()=>{const V=a.sla.percentageUsed||0,D=()=>A?"bg-gray-500":V>=100?"bg-red-600":V>=75?"bg-orange-500":V>=50?"bg-amber-500":"bg-green-600",S=()=>A?"text-gray-600":V>=100?"text-red-600":V>=75?"text-orange-600":V>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(oa,{value:a.sla.percentageUsed,className:"h-3",indicatorClassName:D(),"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 ${S()}`,children:["Progress: ",Math.min(100,a.sla.percentageUsed),"% of TAT used"]}),a.sla.status==="breached"&&k&&e.jsx(Zn,{children:e.jsxs(nl,{children:[e.jsx(il,{asChild:!0,children:e.jsx(F,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",onClick:()=>{u(f),h(!0)},children:e.jsx(Mn,{className:"w-3 h-3"})})}),e.jsx(ll,{children:e.jsx("p",{children:f?"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(li,{className:"w-4 h-4"}),"Deadline Breached"]}),f&&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(Mn,{className:"w-3.5 h-3.5"}),"Breach Reason:"]}),e.jsx("p",{className:"text-sm text-gray-700 leading-relaxed whitespace-pre-line",children:f})]})]}),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(os,{className:"w-4 h-4"}),"Approaching Deadline"]})]})]})]}),w&&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(Ax,{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 ",N," hours for approval"]})]})}),C&&t.comment&&e.jsxs("div",{className:"mt-3 p-3 sm:p-4 bg-red-50 border-l-4 border-red-500 rounded-r-lg",children:[e.jsxs("p",{className:"text-xs font-semibold text-red-700 mb-2 flex items-center gap-1.5",children:[e.jsx(Ct,{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(rm,{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 ",as(t.timestamp)]})]}),t.tatAlerts&&t.tatAlerts.length>0&&e.jsx("div",{className:"mt-2 sm:mt-3 space-y-2",children:t.tatAlerts.map((V,D)=>{var S,O,I,M,W,G;return e.jsx("div",{className:`p-2 sm:p-3 rounded-lg border ${V.isBreached?"bg-red-50 border-red-200":(V.thresholdPercentage||0)===75?"bg-orange-50 border-orange-200":"bg-yellow-50 border-yellow-200"}`,"data-testid":`${c}-tat-alert-${D}`,children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("div",{className:"flex-shrink-0 mt-0.5",children:[(V.thresholdPercentage||0)===50&&e.jsx(Mf,{className:"w-5 h-5 text-yellow-600"}),(V.thresholdPercentage||0)===75&&e.jsx(os,{className:"w-5 h-5 text-orange-600"}),(V.thresholdPercentage||0)===100&&e.jsx(li,{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 ",D+1," - ",V.thresholdPercentage||0,"% TAT"]}),e.jsx(oe,{variant:"outline",className:`text-[10px] sm:text-xs shrink-0 ${V.isBreached?"bg-red-100 text-red-800 border-red-300":"bg-amber-100 text-amber-800 border-amber-300"}`,children:V.isBreached?"BREACHED":"WARNING"})]}),e.jsxs("p",{className:"text-[10px] sm:text-xs md:text-sm text-gray-700 mt-1",children:[V.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:Mt(Number(V.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:[Mt(Number(V.tatHoursElapsed||0)),((S=V.metadata)==null?void 0:S.tatTestMode)&&e.jsxs("span",{className:"text-purple-600 ml-1",children:["(",(Number(V.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 ${(V.tatHoursRemaining||0)<2?"text-red-600":"text-gray-900"}`,children:[Mt(Number(V.tatHoursRemaining||0)),((O=V.metadata)==null?void 0:O.tatTestMode)&&e.jsxs("span",{className:"text-purple-600 ml-1",children:["(",(Number(V.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:V.expectedCompletionTime?ga(V.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"}),(((I=V.metadata)==null?void 0:I.testMode)||((M=V.metadata)==null?void 0:M.tatTestMode))&&e.jsx(oe,{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: ",V.alertSentAt?as(V.alertSentAt):"N/A"]}),(((W=V.metadata)==null?void 0:W.testMode)||((G=V.metadata)==null?void 0:G.tatTestMode))&&e.jsx("p",{className:"text-[10px] text-purple-600 mt-1 italic",children:"Note: Test mode active (1 hour = 1 minute)"})]})]})]})},D)})}),t.timestamp&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:[v?"Approved":C?"Rejected":"Actioned"," on ",as(t.timestamp)]}),n&&!A&&(y||t.status==="pending")&&!v&&!C&&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(F,{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(Ye,{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:A?"Skip this approver to resume the workflow and move to next level":"Skip if approver is unavailable and move to next level"})]})]})]}),e.jsx(ht,{open:m,onOpenChange:h,children:e.jsxs(dt,{className:"sm:max-w-[500px]",children:[e.jsxs(pt,{children:[e.jsx(mt,{children:f?"Edit Breach Reason":"Add Breach Reason"}),e.jsx(Pt,{children:f?"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(_s,{placeholder:"Enter the reason for the breach...",value:x,onChange:V=>u(V.target.value),className:"min-h-[100px]",maxLength:500}),e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:[x.length,"/500 characters"]})]}),e.jsxs(Rt,{children:[e.jsx(F,{variant:"outline",onClick:()=>{h(!1),u("")},disabled:g,children:"Cancel"}),e.jsx(F,{onClick:L,disabled:!x.trim()||g,className:"bg-red-600 hover:bg-red-700",children:g?"Saving...":"Save Reason"})]})]})})]})}function UN({request:t,user:s,isInitiator:a,onSkipApprover:r,onRefresh:n}){return e.jsxs(se,{children:[e.jsx(ge,{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(fe,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(na,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Approval Workflow"]}),e.jsx(Ue,{className:"mt-1 sm:mt-2 text-xs sm:text-sm",children:"Track the approval progress through each step"})]}),t.totalSteps&&(()=>{var u;const i=t.totalSteps||1,l=t.currentStepRaw!==void 0?t.currentStepRaw:t.currentStep||1,o=((u=t.approvalFlow)==null?void 0:u.filter(g=>{const b=(g.status||"").toLowerCase();return b==="approved"||b==="rejected"}).length)||0,c=o>=i,d=(t.status||"").toLowerCase(),m=d==="approved"||d==="rejected"||d==="closed",h=l>i,x=Math.min(Math.max(1,l),i);return h?e.jsxs(oe,{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(oe,{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(oe,{variant:"outline",className:"font-medium text-xs sm:text-sm shrink-0",children:["Step ",x," of ",i," - ",o," completed"]})})()]})}),e.jsx(ae,{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 u,g,b;const o=(u=t.approvals)==null?void 0:u.find(f=>f.levelId===i.levelId),c=(g=s==null?void 0:s.email)==null?void 0:g.toLowerCase(),d=(b=i.approverEmail)==null?void 0:b.toLowerCase(),m=c&&d&&c===d,h=t.currentStepRaw!==void 0?t.currentStepRaw:t.currentStep||1,x=i.step===h;return e.jsx(ON,{step:i,index:l,approval:o,isCurrentUser:m,isInitiator:a,isCurrentLevel:x,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 Mo=p.createContext({});function $o(t){const s=p.useRef(null);return s.current===null&&(s.current=t()),s.current}const Oo=typeof window<"u",Ih=Oo?p.useLayoutEffect:p.useEffect,Fi=p.createContext(null);function Uo(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 Ia=(t,s,a)=>a>s?s:a<t?t:a;let Vo=()=>{};const Ea={},Eh=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function Fh(t){return typeof t=="object"&&t!==null}const _h=t=>/^0[^.\s]+$/u.test(t);function zo(t){let s;return()=>(s===void 0&&(s=t()),s)}const ia=t=>t,BN=(t,s)=>a=>s(t(a)),In=(...t)=>t.reduce(BN),yn=(t,s,a)=>{const r=s-t;return r===0?1:(a-t)/r};class Ho{constructor(){this.subscriptions=[]}add(s){return Uo(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 ja=t=>t*1e3,ra=t=>t/1e3;function Lh(t,s){return s?t*(1e3/s):0}const Mh=(t,s,a)=>(((1-3*a+3*s)*t+(3*a-6*s))*t+3*s)*t,VN=1e-7,zN=12;function HN(t,s,a,r,n){let i,l,o=0;do l=s+(a-s)/2,i=Mh(l,r,n)-t,i>0?a=l:s=l;while(Math.abs(i)>VN&&++o<zN);return l}function En(t,s,a,r){if(t===s&&a===r)return ia;const n=i=>HN(i,0,1,t,a);return i=>i===0||i===1?i:Mh(n(i),s,r)}const $h=t=>s=>s<=.5?t(2*s)/2:(2-t(2*(1-s)))/2,Oh=t=>s=>1-t(1-s),Uh=En(.33,1.53,.69,.99),Go=Oh(Uh),Bh=$h(Go),Vh=t=>(t*=2)<1?.5*Go(t):.5*(2-Math.pow(2,-10*(t-1))),Wo=t=>1-Math.sin(Math.acos(t)),zh=Oh(Wo),Hh=$h(Wo),GN=En(.42,0,1,1),WN=En(0,0,.58,1),Gh=En(.42,0,.58,1),YN=t=>Array.isArray(t)&&typeof t[0]!="number",Wh=t=>Array.isArray(t)&&typeof t[0]=="number",KN={linear:ia,easeIn:GN,easeInOut:Gh,easeOut:WN,circIn:Wo,circInOut:Hh,circOut:zh,backIn:Go,backInOut:Bh,backOut:Uh,anticipate:Vh},XN=t=>typeof t=="string",Tm=t=>{if(Wh(t)){Vo(t.length===4);const[s,a,r,n]=t;return En(s,a,r,n)}else if(XN(t))return KN[t];return t},Un=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function ZN(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,h=!1,x=!1)=>{const g=x&&n?a:r;return h&&l.add(m),g.has(m)||g.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 JN=40;function Yh(t,s){let a=!1,r=!0;const n={delta:0,timestamp:0,isProcessing:!1},i=()=>a=!0,l=Un.reduce((C,w)=>(C[w]=ZN(i),C),{}),{setup:o,read:c,resolveKeyframes:d,preUpdate:m,update:h,preRender:x,render:u,postRender:g}=l,b=()=>{const C=Ea.useManualTiming?n.timestamp:performance.now();a=!1,Ea.useManualTiming||(n.delta=r?1e3/60:Math.max(Math.min(C-n.timestamp,JN),1)),n.timestamp=C,n.isProcessing=!0,o.process(n),c.process(n),d.process(n),m.process(n),h.process(n),x.process(n),u.process(n),g.process(n),n.isProcessing=!1,a&&s&&(r=!1,t(b))},f=()=>{a=!0,r=!0,n.isProcessing||t(b)};return{schedule:Un.reduce((C,w)=>{const A=l[w];return C[w]=(N,_=!1,T=!1)=>(a||f(),A.schedule(N,_,T)),C},{}),cancel:C=>{for(let w=0;w<Un.length;w++)l[Un[w]].cancel(C)},state:n,steps:l}}const{schedule:Ot,cancel:Za,state:js,steps:ol}=Yh(typeof requestAnimationFrame<"u"?requestAnimationFrame:ia,!0);let Jn;function QN(){Jn=void 0}const Vs={now:()=>(Jn===void 0&&Vs.set(js.isProcessing||Ea.useManualTiming?js.timestamp:performance.now()),Jn),set:t=>{Jn=t,queueMicrotask(QN)}},Kh=t=>s=>typeof s=="string"&&s.startsWith(t),Yo=Kh("--"),qN=Kh("var(--"),Ko=t=>qN(t)?ew.test(t.split("/*")[0].trim()):!1,ew=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,Xr={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},vn={...Xr,transform:t=>Ia(0,1,t)},Bn={...Xr,default:1},un=t=>Math.round(t*1e5)/1e5,Xo=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function tw(t){return t==null}const sw=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Zo=(t,s)=>a=>!!(typeof a=="string"&&sw.test(a)&&a.startsWith(t)||s&&!tw(a)&&Object.prototype.hasOwnProperty.call(a,s)),Xh=(t,s,a)=>r=>{if(typeof r!="string")return r;const[n,i,l,o]=r.match(Xo);return{[t]:parseFloat(n),[s]:parseFloat(i),[a]:parseFloat(l),alpha:o!==void 0?parseFloat(o):1}},aw=t=>Ia(0,255,t),cl={...Xr,transform:t=>Math.round(aw(t))},gr={test:Zo("rgb","red"),parse:Xh("red","green","blue"),transform:({red:t,green:s,blue:a,alpha:r=1})=>"rgba("+cl.transform(t)+", "+cl.transform(s)+", "+cl.transform(a)+", "+un(vn.transform(r))+")"};function rw(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 Ul={test:Zo("#"),parse:rw,transform:gr.transform},Fn=t=>({test:s=>typeof s=="string"&&s.endsWith(t)&&s.split(" ").length===1,parse:parseFloat,transform:s=>`${s}${t}`}),za=Fn("deg"),Na=Fn("%"),et=Fn("px"),nw=Fn("vh"),iw=Fn("vw"),km={...Na,parse:t=>Na.parse(t)/100,transform:t=>Na.transform(t*100)},kr={test:Zo("hsl","hue"),parse:Xh("hue","saturation","lightness"),transform:({hue:t,saturation:s,lightness:a,alpha:r=1})=>"hsla("+Math.round(t)+", "+Na.transform(un(s))+", "+Na.transform(un(a))+", "+un(vn.transform(r))+")"},Qt={test:t=>gr.test(t)||Ul.test(t)||kr.test(t),parse:t=>gr.test(t)?gr.parse(t):kr.test(t)?kr.parse(t):Ul.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?gr.transform(t):kr.transform(t),getAnimatableNone:t=>{const s=Qt.parse(t);return s.alpha=0,Qt.transform(s)}},lw=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function ow(t){var s,a;return isNaN(t)&&typeof t=="string"&&(((s=t.match(Xo))==null?void 0:s.length)||0)+(((a=t.match(lw))==null?void 0:a.length)||0)>0}const Zh="number",Jh="color",cw="var",dw="var(",Rm="${}",mw=/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 jn(t){const s=t.toString(),a=[],r={color:[],number:[],var:[]},n=[];let i=0;const o=s.replace(mw,c=>(Qt.test(c)?(r.color.push(i),n.push(Jh),a.push(Qt.parse(c))):c.startsWith(dw)?(r.var.push(i),n.push(cw),a.push(c)):(r.number.push(i),n.push(Zh),a.push(parseFloat(c))),++i,Rm)).split(Rm);return{values:a,split:o,indexes:r,types:n}}function Qh(t){return jn(t).values}function qh(t){const{split:s,types:a}=jn(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===Zh?i+=un(n[l]):o===Jh?i+=Qt.transform(n[l]):i+=n[l]}return i}}const uw=t=>typeof t=="number"?0:Qt.test(t)?Qt.getAnimatableNone(t):t;function xw(t){const s=Qh(t);return qh(t)(s.map(uw))}const Ja={test:ow,parse:Qh,createTransformer:qh,getAnimatableNone:xw};function dl(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 hw({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=dl(c,o,t+1/3),i=dl(c,o,t),l=dl(c,o,t-1/3)}return{red:Math.round(n*255),green:Math.round(i*255),blue:Math.round(l*255),alpha:r}}function mi(t,s){return a=>a>0?s:t}const Wt=(t,s,a)=>t+(s-t)*a,ml=(t,s,a)=>{const r=t*t,n=a*(s*s-r)+r;return n<0?0:Math.sqrt(n)},pw=[Ul,gr,kr],gw=t=>pw.find(s=>s.test(t));function Dm(t){const s=gw(t);if(!s)return!1;let a=s.parse(t);return s===kr&&(a=hw(a)),a}const Pm=(t,s)=>{const a=Dm(t),r=Dm(s);if(!a||!r)return mi(t,s);const n={...a};return i=>(n.red=ml(a.red,r.red,i),n.green=ml(a.green,r.green,i),n.blue=ml(a.blue,r.blue,i),n.alpha=Wt(a.alpha,r.alpha,i),gr.transform(n))},Bl=new Set(["none","hidden"]);function fw(t,s){return Bl.has(t)?a=>a<=0?t:s:a=>a>=1?s:t}function bw(t,s){return a=>Wt(t,s,a)}function Jo(t){return typeof t=="number"?bw:typeof t=="string"?Ko(t)?mi:Qt.test(t)?Pm:jw:Array.isArray(t)?ep:typeof t=="object"?Qt.test(t)?Pm:yw:mi}function ep(t,s){const a=[...t],r=a.length,n=t.map((i,l)=>Jo(i)(i,s[l]));return i=>{for(let l=0;l<r;l++)a[l]=n[l](i);return a}}function yw(t,s){const a={...t,...s},r={};for(const n in a)t[n]!==void 0&&s[n]!==void 0&&(r[n]=Jo(t[n])(t[n],s[n]));return n=>{for(const i in r)a[i]=r[i](n);return a}}function vw(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 jw=(t,s)=>{const a=Ja.createTransformer(s),r=jn(t),n=jn(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?Bl.has(t)&&!n.values.length||Bl.has(s)&&!r.values.length?fw(t,s):In(ep(vw(r,n),n.values),a):mi(t,s)};function tp(t,s,a){return typeof t=="number"&&typeof s=="number"&&typeof a=="number"?Wt(t,s,a):Jo(t)(t,s)}const Nw=t=>{const s=({timestamp:a})=>t(a);return{start:(a=!0)=>Ot.update(s,a),stop:()=>Za(s),now:()=>js.isProcessing?js.timestamp:Vs.now()}},sp=(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)})`},ui=2e4;function Qo(t){let s=0;const a=50;let r=t.next(s);for(;!r.done&&s<ui;)s+=a,r=t.next(s);return s>=ui?1/0:s}function ww(t,s=100,a){const r=a({...t,keyframes:[0,s]}),n=Math.min(Qo(r),ui);return{type:"keyframes",ease:i=>r.next(n*i).value/s,duration:ra(n)}}const Cw=5;function ap(t,s,a){const r=Math.max(s-Cw,0);return Lh(a-t(r),s-r)}const Xt={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},ul=.001;function Sw({duration:t=Xt.duration,bounce:s=Xt.bounce,velocity:a=Xt.velocity,mass:r=Xt.mass}){let n,i,l=1-s;l=Ia(Xt.minDamping,Xt.maxDamping,l),t=Ia(Xt.minDuration,Xt.maxDuration,ra(t)),l<1?(n=d=>{const m=d*l,h=m*t,x=m-a,u=Vl(d,l),g=Math.exp(-h);return ul-x/u*g},i=d=>{const h=d*l*t,x=h*a+a,u=Math.pow(l,2)*Math.pow(d,2)*t,g=Math.exp(-h),b=Vl(Math.pow(d,2),l);return(-n(d)+ul>0?-1:1)*((x-u)*g)/b}):(n=d=>{const m=Math.exp(-d*t),h=(d-a)*t+1;return-ul+m*h},i=d=>{const m=Math.exp(-d*t),h=(a-d)*(t*t);return m*h});const o=5/t,c=Tw(n,i,o);if(t=ja(t),isNaN(c))return{stiffness:Xt.stiffness,damping:Xt.damping,duration:t};{const d=Math.pow(c,2)*r;return{stiffness:d,damping:l*2*Math.sqrt(r*d),duration:t}}}const Aw=12;function Tw(t,s,a){let r=a;for(let n=1;n<Aw;n++)r=r-t(r)/s(r);return r}function Vl(t,s){return t*Math.sqrt(1-s*s)}const kw=["duration","bounce"],Rw=["stiffness","damping","mass"];function Im(t,s){return s.some(a=>t[a]!==void 0)}function Dw(t){let s={velocity:Xt.velocity,stiffness:Xt.stiffness,damping:Xt.damping,mass:Xt.mass,isResolvedFromDuration:!1,...t};if(!Im(t,Rw)&&Im(t,kw))if(t.visualDuration){const a=t.visualDuration,r=2*Math.PI/(a*1.2),n=r*r,i=2*Ia(.05,1,1-(t.bounce||0))*Math.sqrt(n);s={...s,mass:Xt.mass,stiffness:n,damping:i}}else{const a=Sw(t);s={...s,...a,mass:Xt.mass},s.isResolvedFromDuration=!0}return s}function xi(t=Xt.visualDuration,s=Xt.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:h,velocity:x,isResolvedFromDuration:u}=Dw({...a,velocity:-ra(a.velocity||0)}),g=x||0,b=d/(2*Math.sqrt(c*m)),f=l-i,y=ra(Math.sqrt(c/m)),v=Math.abs(f)<5;r||(r=v?Xt.restSpeed.granular:Xt.restSpeed.default),n||(n=v?Xt.restDelta.granular:Xt.restDelta.default);let C;if(b<1){const A=Vl(y,b);C=N=>{const _=Math.exp(-b*y*N);return l-_*((g+b*y*f)/A*Math.sin(A*N)+f*Math.cos(A*N))}}else if(b===1)C=A=>l-Math.exp(-y*A)*(f+(g+y*f)*A);else{const A=y*Math.sqrt(b*b-1);C=N=>{const _=Math.exp(-b*y*N),T=Math.min(A*N,300);return l-_*((g+b*y*f)*Math.sinh(T)+A*f*Math.cosh(T))/A}}const w={calculatedDuration:u&&h||null,next:A=>{const N=C(A);if(u)o.done=A>=h;else{let _=A===0?g:0;b<1&&(_=A===0?ja(g):ap(C,A,N));const T=Math.abs(_)<=r,R=Math.abs(l-N)<=n;o.done=T&&R}return o.value=o.done?l:N,o},toString:()=>{const A=Math.min(Qo(w),ui),N=sp(_=>w.next(A*_).value,A,30);return A+"ms "+N},toTransition:()=>{}};return w}xi.applyToOptions=t=>{const s=ww(t,100,xi);return t.ease=s.ease,t.duration=ja(s.duration),t.type="keyframes",t};function zl({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 h=t[0],x={done:!1,value:h},u=T=>o!==void 0&&T<o||c!==void 0&&T>c,g=T=>o===void 0?c:c===void 0||Math.abs(o-T)<Math.abs(c-T)?o:c;let b=a*s;const f=h+b,y=l===void 0?f:l(f);y!==f&&(b=y-h);const v=T=>-b*Math.exp(-T/r),C=T=>y+v(T),w=T=>{const R=v(T),j=C(T);x.done=Math.abs(R)<=d,x.value=x.done?y:j};let A,N;const _=T=>{u(x.value)&&(A=T,N=xi({keyframes:[x.value,g(x.value)],velocity:ap(C,T,x.value),damping:n,stiffness:i,restDelta:d,restSpeed:m}))};return _(0),{calculatedDuration:null,next:T=>{let R=!1;return!N&&A===void 0&&(R=!0,w(T),_(T)),A!==void 0&&T>=A?N.next(T-A):(!R&&w(T),x)}}}function Pw(t,s,a){const r=[],n=a||Ea.mix||tp,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]||ia:s;o=In(c,o)}r.push(o)}return r}function Iw(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=Pw(s,r,n),c=o.length,d=m=>{if(l&&m<t[0])return s[0];let h=0;if(c>1)for(;h<t.length-2&&!(m<t[h+1]);h++);const x=yn(t[h],t[h+1],m);return o[h](x)};return a?m=>d(Ia(t[0],t[i-1],m)):d}function Ew(t,s){const a=t[t.length-1];for(let r=1;r<=s;r++){const n=yn(0,s,r);t.push(Wt(a,1,n))}}function Fw(t){const s=[0];return Ew(s,t.length-1),s}function _w(t,s){return t.map(a=>a*s)}function Lw(t,s){return t.map(()=>s||Gh).splice(0,t.length-1)}function xn({duration:t=300,keyframes:s,times:a,ease:r="easeInOut"}){const n=YN(r)?r.map(Tm):Tm(r),i={done:!1,value:s[0]},l=_w(a&&a.length===s.length?a:Fw(s),t),o=Iw(l,s,{ease:Array.isArray(n)?n:Lw(s,n)});return{calculatedDuration:t,next:c=>(i.value=o(c),i.done=c>=t,i)}}const Mw=t=>t!==null;function qo(t,{repeat:s,repeatType:a="loop"},r,n=1){const i=t.filter(Mw),o=n<0||s&&a!=="loop"&&s%2===1?0:i.length-1;return!o||r===void 0?i[o]:r}const $w={decay:zl,inertia:zl,tween:xn,keyframes:xn,spring:xi};function rp(t){typeof t.type=="string"&&(t.type=$w[t.type])}class ec{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 Ow=t=>t/100;class tc extends ec{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!==Vs.now()&&this.tick(Vs.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;rp(s);const{type:a=xn,repeat:r=0,repeatDelay:n=0,repeatType:i,velocity:l=0}=s;let{keyframes:o}=s;const c=a||xn;c!==xn&&typeof o[0]!="number"&&(this.mixKeyframes=In(Ow,tp(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=Qo(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:h,repeatType:x,repeatDelay:u,type:g,onUpdate:b,finalKeyframe:f}=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 y=this.currentTime-d*(this.playbackSpeed>=0?1:-1),v=this.playbackSpeed>=0?y<0:y>n;this.currentTime=Math.max(y,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=n);let C=this.currentTime,w=r;if(h){const T=Math.min(this.currentTime,n)/o;let R=Math.floor(T),j=T%1;!j&&T>=1&&(j=1),j===1&&R--,R=Math.min(R,h+1),!!(R%2)&&(x==="reverse"?(j=1-j,u&&(j-=u/o)):x==="mirror"&&(w=l)),C=Ia(0,1,j)*o}const A=v?{done:!1,value:m[0]}:w.next(C);i&&(A.value=i(A.value));let{done:N}=A;!v&&c!==null&&(N=this.playbackSpeed>=0?this.currentTime>=n:this.currentTime<=0);const _=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&N);return _&&g!==zl&&(A.value=qo(m,this.options,f,this.speed)),b&&b(A.value),_&&this.finish(),A}then(s,a){return this.finished.then(s,a)}get duration(){return ra(this.calculatedDuration)}get iterationDuration(){const{delay:s=0}=this.options||{};return this.duration+ra(s)}get time(){return ra(this.currentTime)}set time(s){var a;s=ja(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(Vs.now());const a=this.playbackSpeed!==s;this.playbackSpeed=s,a&&(this.time=ra(this.currentTime))}play(){var n,i;if(this.isStopped)return;const{driver:s=Nw,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(Vs.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 Uw(t){for(let s=1;s<t.length;s++)t[s]??(t[s]=t[s-1])}const fr=t=>t*180/Math.PI,Hl=t=>{const s=fr(Math.atan2(t[1],t[0]));return Gl(s)},Bw={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:Hl,rotateZ:Hl,skewX:t=>fr(Math.atan(t[1])),skewY:t=>fr(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},Gl=t=>(t=t%360,t<0&&(t+=360),t),Em=Hl,Fm=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),_m=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),Vw={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Fm,scaleY:_m,scale:t=>(Fm(t)+_m(t))/2,rotateX:t=>Gl(fr(Math.atan2(t[6],t[5]))),rotateY:t=>Gl(fr(Math.atan2(-t[2],t[0]))),rotateZ:Em,rotate:Em,skewX:t=>fr(Math.atan(t[4])),skewY:t=>fr(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function Wl(t){return t.includes("scale")?1:0}function Yl(t,s){if(!t||t==="none")return Wl(s);const a=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,n;if(a)r=Vw,n=a;else{const o=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=Bw,n=o}if(!n)return Wl(s);const i=r[s],l=n[1].split(",").map(Hw);return typeof i=="function"?i(l):l[i]}const zw=(t,s)=>{const{transform:a="none"}=getComputedStyle(t);return Yl(a,s)};function Hw(t){return parseFloat(t.trim())}const Zr=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Jr=new Set(Zr),Lm=t=>t===Xr||t===et,Gw=new Set(["x","y","z"]),Ww=Zr.filter(t=>!Gw.has(t));function Yw(t){const s=[];return Ww.forEach(a=>{const r=t.getValue(a);r!==void 0&&(s.push([a,r.get()]),r.set(a.startsWith("scale")?1:0))}),s}const br={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})=>Yl(s,"x"),y:(t,{transform:s})=>Yl(s,"y")};br.translateX=br.x;br.translateY=br.y;const yr=new Set;let Kl=!1,Xl=!1,Zl=!1;function np(){if(Xl){const t=Array.from(yr).filter(r=>r.needsMeasurement),s=new Set(t.map(r=>r.element)),a=new Map;s.forEach(r=>{const n=Yw(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)})}Xl=!1,Kl=!1,yr.forEach(t=>t.complete(Zl)),yr.clear()}function ip(){yr.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(Xl=!0)})}function Kw(){Zl=!0,ip(),np(),Zl=!1}class sc{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?(yr.add(this),Kl||(Kl=!0,Ot.read(ip),Ot.resolveKeyframes(np))):(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])}Uw(s)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(s=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,s),yr.delete(this)}cancel(){this.state==="scheduled"&&(yr.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Xw=t=>t.startsWith("--");function Zw(t,s,a){Xw(s)?t.style.setProperty(s,a):t.style[s]=a}const Jw=zo(()=>window.ScrollTimeline!==void 0),Qw={};function qw(t,s){const a=zo(t);return()=>Qw[s]??a()}const lp=qw(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),cn=([t,s,a,r])=>`cubic-bezier(${t}, ${s}, ${a}, ${r})`,Mm={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:cn([0,.65,.55,1]),circOut:cn([.55,0,1,.45]),backIn:cn([.31,.01,.66,-.59]),backOut:cn([.33,1.53,.69,.99])};function op(t,s){if(t)return typeof t=="function"?lp()?sp(t,s):"ease-out":Wh(t)?cn(t):Array.isArray(t)?t.map(a=>op(a,s)||Mm.easeOut):Mm[t]}function e1(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 h=op(o,n);Array.isArray(h)&&(m.easing=h);const x={delay:r,duration:n,easing:Array.isArray(h)?"linear":h,fill:"both",iterations:i+1,direction:l==="reverse"?"alternate":"normal"};return d&&(x.pseudoElement=d),t.animate(m,x)}function cp(t){return typeof t=="function"&&"applyToOptions"in t}function t1({type:t,...s}){return cp(t)&&lp()?t.applyToOptions(s):(s.duration??(s.duration=300),s.ease??(s.ease="easeOut"),s)}class s1 extends ec{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=t1(s);this.animation=e1(a,r,n,d,i),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const m=qo(n,this.options,o,this.speed);this.updateMotionValue?this.updateMotionValue(m):Zw(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 ra(Number(s))}get iterationDuration(){const{delay:s=0}=this.options||{};return this.duration+ra(s)}get time(){return ra(Number(this.animation.currentTime)||0)}set time(s){this.finishedTime=null,this.animation.currentTime=ja(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&&Jw()?(this.animation.timeline=s,ia):a(this)}}const dp={anticipate:Vh,backInOut:Bh,circInOut:Hh};function a1(t){return t in dp}function r1(t){typeof t.ease=="string"&&a1(t.ease)&&(t.ease=dp[t.ease])}const $m=10;class n1 extends s1{constructor(s){r1(s),rp(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 tc({...l,autoplay:!1}),c=ja(this.finishedTime??this.time);a.setWithVelocity(o.sample(c-$m).value,o.sample(c).value,$m),o.stop()}}const Om=(t,s)=>s==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(Ja.test(t)||t==="0")&&!t.startsWith("url("));function i1(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 l1(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=Om(n,s),o=Om(i,s);return!l||!o?!1:i1(t)||(a==="spring"||cp(a))&&r}function Jl(t){t.duration=0,t.type="keyframes"}const o1=new Set(["opacity","clipPath","filter","transform"]),c1=zo(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function d1(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 c1()&&a&&o1.has(a)&&(a!=="transform"||!d)&&!c&&!r&&n!=="mirror"&&i!==0&&l!=="inertia"}const m1=40;class u1 extends ec{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,...h}){var g;super(),this.stop=()=>{var b,f;this._animation&&(this._animation.stop(),(b=this.stopTimeline)==null||b.call(this)),(f=this.keyframeResolver)==null||f.cancel()},this.createdAt=Vs.now();const x={autoplay:s,delay:a,type:r,repeat:n,repeatDelay:i,repeatType:l,name:c,motionValue:d,element:m,...h},u=(m==null?void 0:m.KeyframeResolver)||sc;this.keyframeResolver=new u(o,(b,f,y)=>this.onKeyframesResolved(b,f,x,!y),c,d,m),(g=this.keyframeResolver)==null||g.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=Vs.now(),l1(s,i,l,o)||((Ea.instantAnimations||!c)&&(m==null||m(qo(s,r,a))),s[0]=s[s.length-1],Jl(r),r.repeat=0);const x={startTime:n?this.resolvedAt?this.resolvedAt-this.createdAt>m1?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:a,...r,keyframes:s},u=!d&&d1(x)?new n1({...x,element:x.motionValue.owner.current}):new tc(x);u.finished.then(()=>this.notifyFinished()).catch(ia),this.pendingTimeline&&(this.stopTimeline=u.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=u}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(),Kw()),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 x1=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function h1(t){const s=x1.exec(t);if(!s)return[,];const[,a,r,n]=s;return[`--${a??r}`,n]}function mp(t,s,a=1){const[r,n]=h1(t);if(!r)return;const i=window.getComputedStyle(s).getPropertyValue(r);if(i){const l=i.trim();return Eh(l)?parseFloat(l):l}return Ko(n)?mp(n,s,a+1):n}function ac(t,s){return(t==null?void 0:t[s])??(t==null?void 0:t.default)??t}const up=new Set(["width","height","top","left","right","bottom",...Zr]),p1={test:t=>t==="auto",parse:t=>t},xp=t=>s=>s.test(t),hp=[Xr,et,Na,za,iw,nw,p1],Um=t=>hp.find(xp(t));function g1(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||_h(t):!0}const f1=new Set(["brightness","contrast","saturate","opacity"]);function b1(t){const[s,a]=t.slice(0,-1).split("(");if(s==="drop-shadow")return t;const[r]=a.match(Xo)||[];if(!r)return t;const n=a.replace(r,"");let i=f1.has(s)?1:0;return r!==a&&(i*=100),s+"("+i+n+")"}const y1=/\b([a-z-]*)\(.*?\)/gu,Ql={...Ja,getAnimatableNone:t=>{const s=t.match(y1);return s?s.map(b1).join(" "):t}},Bm={...Xr,transform:Math.round},v1={rotate:za,rotateX:za,rotateY:za,rotateZ:za,scale:Bn,scaleX:Bn,scaleY:Bn,scaleZ:Bn,skew:za,skewX:za,skewY:za,distance:et,translateX:et,translateY:et,translateZ:et,x:et,y:et,z:et,perspective:et,transformPerspective:et,opacity:vn,originX:km,originY:km,originZ:et},rc={borderWidth:et,borderTopWidth:et,borderRightWidth:et,borderBottomWidth:et,borderLeftWidth:et,borderRadius:et,radius:et,borderTopLeftRadius:et,borderTopRightRadius:et,borderBottomRightRadius:et,borderBottomLeftRadius:et,width:et,maxWidth:et,height:et,maxHeight:et,top:et,right:et,bottom:et,left:et,padding:et,paddingTop:et,paddingRight:et,paddingBottom:et,paddingLeft:et,margin:et,marginTop:et,marginRight:et,marginBottom:et,marginLeft:et,backgroundPositionX:et,backgroundPositionY:et,...v1,zIndex:Bm,fillOpacity:vn,strokeOpacity:vn,numOctaves:Bm},j1={...rc,color:Qt,backgroundColor:Qt,outlineColor:Qt,fill:Qt,stroke:Qt,borderColor:Qt,borderTopColor:Qt,borderRightColor:Qt,borderBottomColor:Qt,borderLeftColor:Qt,filter:Ql,WebkitFilter:Ql},pp=t=>j1[t];function gp(t,s){let a=pp(t);return a!==Ql&&(a=Ja),a.getAnimatableNone?a.getAnimatableNone(s):void 0}const N1=new Set(["auto","none","0"]);function w1(t,s,a){let r=0,n;for(;r<t.length&&!n;){const i=t[r];typeof i=="string"&&!N1.has(i)&&jn(i).values.length&&(n=t[r]),r++}if(n&&a)for(const i of s)t[i]=gp(a,n)}class C1 extends sc{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(),Ko(d))){const m=mp(d,a.current);m!==void 0&&(s[c]=m),c===s.length-1&&(this.finalKeyframe=d)}}if(this.resolveNoneKeyframes(),!up.has(r)||s.length!==2)return;const[n,i]=s,l=Um(n),o=Um(i);if(l!==o)if(Lm(l)&&Lm(o))for(let c=0;c<s.length;c++){const d=s[c];typeof d=="string"&&(s[c]=parseFloat(d))}else br[r]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:s,name:a}=this,r=[];for(let n=0;n<s.length;n++)(s[n]===null||g1(s[n]))&&r.push(n);r.length&&w1(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=br[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]=br[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 S1(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 fp=(t,s)=>s&&typeof t=="number"?s.transform(t):t;function bp(t){return Fh(t)&&"offsetHeight"in t}const Vm=30,A1=t=>!isNaN(parseFloat(t));class T1{constructor(s,a={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=r=>{var i;const n=Vs.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=Vs.now(),this.canTrackVelocity===null&&s!==void 0&&(this.canTrackVelocity=A1(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 Ho);const r=this.events[s].add(a);return s==="change"?()=>{r(),Ot.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=Vs.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||s-this.updatedAt>Vm)return 0;const a=Math.min(this.updatedAt-this.prevUpdatedAt,Vm);return Lh(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 Ur(t,s){return new T1(t,s)}const{schedule:nc}=Yh(queueMicrotask,!1),ha={x:!1,y:!1};function yp(){return ha.x||ha.y}function k1(t){return t==="x"||t==="y"?ha[t]?null:(ha[t]=!0,()=>{ha[t]=!1}):ha.x||ha.y?null:(ha.x=ha.y=!0,()=>{ha.x=ha.y=!1})}function vp(t,s){const a=S1(t),r=new AbortController,n={passive:!0,...s,signal:r.signal};return[a,n,()=>r.abort()]}function zm(t){return!(t.pointerType==="touch"||yp())}function R1(t,s,a={}){const[r,n,i]=vp(t,a),l=o=>{if(!zm(o))return;const{target:c}=o,d=s(c,o);if(typeof d!="function"||!c)return;const m=h=>{zm(h)&&(d(h),c.removeEventListener("pointerleave",m))};c.addEventListener("pointerleave",m,n)};return r.forEach(o=>{o.addEventListener("pointerenter",l,n)}),i}const jp=(t,s)=>s?t===s?!0:jp(t,s.parentElement):!1,ic=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,D1=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function P1(t){return D1.has(t.tagName)||t.tabIndex!==-1}const Qn=new WeakSet;function Hm(t){return s=>{s.key==="Enter"&&t(s)}}function xl(t,s){t.dispatchEvent(new PointerEvent("pointer"+s,{isPrimary:!0,bubbles:!0}))}const I1=(t,s)=>{const a=t.currentTarget;if(!a)return;const r=Hm(()=>{if(Qn.has(a))return;xl(a,"down");const n=Hm(()=>{xl(a,"up")}),i=()=>xl(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 Gm(t){return ic(t)&&!yp()}function E1(t,s,a={}){const[r,n,i]=vp(t,a),l=o=>{const c=o.currentTarget;if(!Gm(o))return;Qn.add(c);const d=s(c,o),m=(u,g)=>{window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",x),Qn.has(c)&&Qn.delete(c),Gm(u)&&typeof d=="function"&&d(u,{success:g})},h=u=>{m(u,c===window||c===document||a.useGlobalTarget||jp(c,u.target))},x=u=>{m(u,!1)};window.addEventListener("pointerup",h,n),window.addEventListener("pointercancel",x,n)};return r.forEach(o=>{(a.useGlobalTarget?window:o).addEventListener("pointerdown",l,n),bp(o)&&(o.addEventListener("focus",d=>I1(d,n)),!P1(o)&&!o.hasAttribute("tabindex")&&(o.tabIndex=0))}),i}function Np(t){return Fh(t)&&"ownerSVGElement"in t}function F1(t){return Np(t)&&t.tagName==="svg"}const ks=t=>!!(t&&t.getVelocity),_1=[...hp,Qt,Ja],L1=t=>_1.find(xp(t)),lc=p.createContext({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});function Wm(t,s){if(typeof t=="function")return t(s);t!=null&&(t.current=s)}function M1(...t){return s=>{let a=!1;const r=t.map(n=>{const i=Wm(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():Wm(t[n],null)}}}}function $1(...t){return p.useCallback(M1(...t),t)}class O1 extends p.Component{getSnapshotBeforeUpdate(s){const a=this.props.childRef.current;if(a&&s.isPresent&&!this.props.isPresent){const r=a.offsetParent,n=bp(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 U1({children:t,isPresent:s,anchorX:a,root:r}){const n=p.useId(),i=p.useRef(null),l=p.useRef({width:0,height:0,top:0,left:0,right:0}),{nonce:o}=p.useContext(lc),c=$1(i,t==null?void 0:t.ref);return p.useInsertionEffect(()=>{const{width:d,height:m,top:h,left:x,right:u}=l.current;if(s||!i.current||!d||!m)return;const g=a==="left"?`left: ${x}`:`right: ${u}`;i.current.dataset.motionPopId=n;const b=document.createElement("style");o&&(b.nonce=o);const f=r??document.head;return f.appendChild(b),b.sheet&&b.sheet.insertRule(`
[data-motion-pop-id="${n}"] {
position: absolute !important;
width: ${d}px !important;
height: ${m}px !important;
${g}px !important;
top: ${h}px !important;
}
`),()=>{f.contains(b)&&f.removeChild(b)}},[s]),e.jsx(O1,{isPresent:s,childRef:i,sizeRef:l,children:p.cloneElement(t,{ref:c})})}const B1=({children:t,initial:s,isPresent:a,onExitComplete:r,custom:n,presenceAffectsLayout:i,mode:l,anchorX:o,root:c})=>{const d=$o(V1),m=p.useId();let h=!0,x=p.useMemo(()=>(h=!1,{id:m,initial:s,isPresent:a,custom:n,onExitComplete:u=>{d.set(u,!0);for(const g of d.values())if(!g)return;r&&r()},register:u=>(d.set(u,!1),()=>d.delete(u))}),[a,d,r]);return i&&h&&(x={...x}),p.useMemo(()=>{d.forEach((u,g)=>d.set(g,!1))},[a]),p.useEffect(()=>{!a&&!d.size&&r&&r()},[a]),l==="popLayout"&&(t=e.jsx(U1,{isPresent:a,anchorX:o,root:c,children:t})),e.jsx(Fi.Provider,{value:x,children:t})};function V1(){return new Map}function wp(t=!0){const s=p.useContext(Fi);if(s===null)return[!0,null];const{isPresent:a,onExitComplete:r,register:n}=s,i=p.useId();p.useEffect(()=>{if(t)return n(i)},[t]);const l=p.useCallback(()=>t&&r&&r(i),[i,r,t]);return!a&&r?[!1,l]:[!0]}const Vn=t=>t.key||"";function Ym(t){const s=[];return p.Children.forEach(t,a=>{p.isValidElement(a)&&s.push(a)}),s}const _i=({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]=wp(l),h=p.useMemo(()=>Ym(t),[t]),x=l&&!d?[]:h.map(Vn),u=p.useRef(!0),g=p.useRef(h),b=$o(()=>new Map),[f,y]=p.useState(h),[v,C]=p.useState(h);Ih(()=>{u.current=!1,g.current=h;for(let N=0;N<v.length;N++){const _=Vn(v[N]);x.includes(_)?b.delete(_):b.get(_)!==!0&&b.set(_,!1)}},[v,x.length,x.join("-")]);const w=[];if(h!==f){let N=[...h];for(let _=0;_<v.length;_++){const T=v[_],R=Vn(T);x.includes(R)||(N.splice(_,0,T),w.push(T))}return i==="wait"&&w.length&&(N=w),C(Ym(N)),y(h),null}const{forceRender:A}=p.useContext(Mo);return e.jsx(e.Fragment,{children:v.map(N=>{const _=Vn(N),T=l&&!d?!1:h===v||x.includes(_),R=()=>{if(b.has(_))b.set(_,!0);else return;let j=!0;b.forEach(E=>{E||(j=!1)}),j&&(A==null||A(),C(g.current),l&&(m==null||m()),r&&r())};return e.jsx(B1,{isPresent:T,initial:!u.current||a?void 0:!1,custom:s,presenceAffectsLayout:n,mode:i,root:c,onExitComplete:T?void 0:R,anchorX:o,children:N},_)})})},Cp=p.createContext({strict:!1}),Km={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 Km)Br[t]={isEnabled:s=>Km[t].some(a=>!!s[a])};function z1(t){for(const s in t)Br[s]={...Br[s],...t[s]}}const H1=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 hi(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||H1.has(t)}let Sp=t=>!hi(t);function G1(t){typeof t=="function"&&(Sp=s=>s.startsWith("on")?!hi(s):t(s))}try{G1(require("@emotion/is-prop-valid").default)}catch{}function W1(t,s,a){const r={};for(const n in t)n==="values"&&typeof t.values=="object"||(Sp(n)||a===!0&&hi(n)||!s&&!hi(n)||t.draggable&&n.startsWith("onDrag"))&&(r[n]=t[n]);return r}const Li=p.createContext({});function Mi(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function Nn(t){return typeof t=="string"||Array.isArray(t)}const oc=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],cc=["initial",...oc];function $i(t){return Mi(t.animate)||cc.some(s=>Nn(t[s]))}function Ap(t){return!!($i(t)||t.variants)}function Y1(t,s){if($i(t)){const{initial:a,animate:r}=t;return{initial:a===!1||Nn(a)?a:void 0,animate:Nn(r)?r:void 0}}return t.inherit!==!1?s:{}}function K1(t){const{initial:s,animate:a}=Y1(t,p.useContext(Li));return p.useMemo(()=>({initial:s,animate:a}),[Xm(s),Xm(a)])}function Xm(t){return Array.isArray(t)?t.join(" "):t}const wn={};function X1(t){for(const s in t)wn[s]=t[s],Yo(s)&&(wn[s].isCSSVariable=!0)}function Tp(t,{layout:s,layoutId:a}){return Jr.has(t)||t.startsWith("origin")||(s||a!==void 0)&&(!!wn[t]||t==="opacity")}const Z1={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},J1=Zr.length;function Q1(t,s,a){let r="",n=!0;for(let i=0;i<J1;i++){const l=Zr[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=fp(o,rc[l]);if(!c){n=!1;const m=Z1[l]||l;r+=`${m}(${d}) `}a&&(s[l]=d)}}return r=r.trim(),a?r=a(s,n?"":r):n&&(r="none"),r}function dc(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(Jr.has(c)){l=!0;continue}else if(Yo(c)){n[c]=d;continue}else{const m=fp(d,rc[c]);c.startsWith("origin")?(o=!0,i[c]=m):r[c]=m}}if(s.transform||(l||a?r.transform=Q1(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 mc=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function kp(t,s,a){for(const r in s)!ks(s[r])&&!Tp(r,a)&&(t[r]=s[r])}function q1({transformTemplate:t},s){return p.useMemo(()=>{const a=mc();return dc(a,s,t),Object.assign({},a.vars,a.style)},[s])}function eC(t,s){const a=t.style||{},r={};return kp(r,a,t),Object.assign(r,q1(t,s)),r}function tC(t,s){const a={},r=eC(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 sC={offset:"stroke-dashoffset",array:"stroke-dasharray"},aC={offset:"strokeDashoffset",array:"strokeDasharray"};function rC(t,s,a=1,r=0,n=!0){t.pathLength=1;const i=n?sC:aC;t[i.offset]=et.transform(-r);const l=et.transform(s),o=et.transform(a);t[i.array]=`${l} ${o}`}function Rp(t,{attrX:s,attrY:a,attrScale:r,pathLength:n,pathSpacing:i=1,pathOffset:l=0,...o},c,d,m){if(dc(t,o,d),c){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:h,style:x}=t;h.transform&&(x.transform=h.transform,delete h.transform),(x.transform||h.transformOrigin)&&(x.transformOrigin=h.transformOrigin??"50% 50%",delete h.transformOrigin),x.transform&&(x.transformBox=(m==null?void 0:m.transformBox)??"fill-box",delete h.transformBox),s!==void 0&&(h.x=s),a!==void 0&&(h.y=a),r!==void 0&&(h.scale=r),n!==void 0&&rC(h,n,i,l,!1)}const Dp=()=>({...mc(),attrs:{}}),Pp=t=>typeof t=="string"&&t.toLowerCase()==="svg";function nC(t,s,a,r){const n=p.useMemo(()=>{const i=Dp();return Rp(i,s,Pp(r),t.transformTemplate,t.style),{...i.attrs,style:{...i.style}}},[s]);if(t.style){const i={};kp(i,t.style,t),n.style={...i,...n.style}}return n}const iC=["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 uc(t){return typeof t!="string"||t.includes("-")?!1:!!(iC.indexOf(t)>-1||/[A-Z]/u.test(t))}function lC(t,s,a,{latestValues:r},n,i=!1){const o=(uc(t)?nC:tC)(s,r,n,t),c=W1(s,typeof t=="string",i),d=t!==p.Fragment?{...c,...o,ref:a}:{},{children:m}=s,h=p.useMemo(()=>ks(m)?m.get():m,[m]);return p.createElement(t,{...d,children:h})}function Zm(t){const s=[{},{}];return t==null||t.values.forEach((a,r)=>{s[0][r]=a.get(),s[1][r]=a.getVelocity()}),s}function xc(t,s,a,r){if(typeof s=="function"){const[n,i]=Zm(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]=Zm(r);s=s(a!==void 0?a:t.custom,n,i)}return s}function qn(t){return ks(t)?t.get():t}function oC({scrapeMotionValuesFromProps:t,createRenderState:s},a,r,n){return{latestValues:cC(a,r,n,t),renderState:s()}}function cC(t,s,a,r){const n={},i=r(t,{});for(const x in i)n[x]=qn(i[x]);let{initial:l,animate:o}=t;const c=$i(t),d=Ap(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 h=m?o:l;if(h&&typeof h!="boolean"&&!Mi(h)){const x=Array.isArray(h)?h:[h];for(let u=0;u<x.length;u++){const g=xc(t,x[u]);if(g){const{transitionEnd:b,transition:f,...y}=g;for(const v in y){let C=y[v];if(Array.isArray(C)){const w=m?C.length-1:0;C=C[w]}C!==null&&(n[v]=C)}for(const v in b)n[v]=b[v]}}}return n}const Ip=t=>(s,a)=>{const r=p.useContext(Li),n=p.useContext(Fi),i=()=>oC(t,s,r,n);return a?i():$o(i)};function hc(t,s,a){var i;const{style:r}=t,n={};for(const l in r)(ks(r[l])||s.style&&ks(s.style[l])||Tp(l,t)||((i=a==null?void 0:a.getValue(l))==null?void 0:i.liveStyle)!==void 0)&&(n[l]=r[l]);return n}const dC=Ip({scrapeMotionValuesFromProps:hc,createRenderState:mc});function Ep(t,s,a){const r=hc(t,s,a);for(const n in t)if(ks(t[n])||ks(s[n])){const i=Zr.indexOf(n)!==-1?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n;r[i]=t[n]}return r}const mC=Ip({scrapeMotionValuesFromProps:Ep,createRenderState:Dp}),uC=Symbol.for("motionComponentSymbol");function Rr(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function xC(t,s,a){return p.useCallback(r=>{r&&t.onMount&&t.onMount(r),s&&(r?s.mount(r):s.unmount()),a&&(typeof a=="function"?a(r):Rr(a)&&(a.current=r))},[s])}const pc=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),hC="framerAppearId",Fp="data-"+pc(hC),_p=p.createContext({});function pC(t,s,a,r,n){var b,f;const{visualElement:i}=p.useContext(Li),l=p.useContext(Cp),o=p.useContext(Fi),c=p.useContext(lc).reducedMotion,d=p.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,h=p.useContext(_p);m&&!m.projection&&n&&(m.type==="html"||m.type==="svg")&&gC(d.current,a,n,h);const x=p.useRef(!1);p.useInsertionEffect(()=>{m&&x.current&&m.update(a,o)});const u=a[Fp],g=p.useRef(!!u&&!((b=window.MotionHandoffIsComplete)!=null&&b.call(window,u))&&((f=window.MotionHasOptimisedAnimation)==null?void 0:f.call(window,u)));return Ih(()=>{m&&(x.current=!0,window.MotionIsMounted=!0,m.updateFeatures(),m.scheduleRenderMicrotask(),g.current&&m.animationState&&m.animationState.animateChanges())}),p.useEffect(()=>{m&&(!g.current&&m.animationState&&m.animationState.animateChanges(),g.current&&(queueMicrotask(()=>{var y;(y=window.MotionHandoffMarkAsComplete)==null||y.call(window,u)}),g.current=!1),m.enteringChildren=void 0)}),m}function gC(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:Lp(t.parent)),t.projection.setOptions({layoutId:n,layout:i,alwaysMeasureLayout:!!l||o&&Rr(o),visualElement:t,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:m,layoutScroll:c,layoutRoot:d})}function Lp(t){if(t)return t.options.allowProjection!==!1?t.projection:Lp(t.parent)}function hl(t,{forwardMotionProps:s=!1}={},a,r){a&&z1(a);const n=uc(t)?mC:dC;function i(o,c){let d;const m={...p.useContext(lc),...o,layoutId:fC(o)},{isStatic:h}=m,x=K1(o),u=n(o,h);if(!h&&Oo){bC();const g=yC(m);d=g.MeasureLayout,x.visualElement=pC(t,u,m,r,g.ProjectionNode)}return e.jsxs(Li.Provider,{value:x,children:[d&&x.visualElement?e.jsx(d,{visualElement:x.visualElement,...m}):null,lC(t,o,xC(u,x.visualElement,c),u,h,s)]})}i.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const l=p.forwardRef(i);return l[uC]=t,l}function fC({layoutId:t}){const s=p.useContext(Mo).id;return s&&t!==void 0?s+"-"+t:t}function bC(t,s){p.useContext(Cp).strict}function yC(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 vC(t,s){if(typeof Proxy>"u")return hl;const a=new Map,r=(i,l)=>hl(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,hl(l,void 0,t,s)),a.get(l))})}function Mp({top:t,left:s,right:a,bottom:r}){return{x:{min:s,max:a},y:{min:t,max:r}}}function jC({x:t,y:s}){return{top:s.min,right:t.max,bottom:s.max,left:t.min}}function NC(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 pl(t){return t===void 0||t===1}function ql({scale:t,scaleX:s,scaleY:a}){return!pl(t)||!pl(s)||!pl(a)}function dr(t){return ql(t)||$p(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function $p(t){return Jm(t.x)||Jm(t.y)}function Jm(t){return t&&t!=="0%"}function pi(t,s,a){const r=t-a,n=s*r;return a+n}function Qm(t,s,a,r,n){return n!==void 0&&(t=pi(t,n,r)),pi(t,a,r)+s}function eo(t,s=0,a=1,r,n){t.min=Qm(t.min,s,a,r,n),t.max=Qm(t.max,s,a,r,n)}function Op(t,{x:s,y:a}){eo(t.x,s.translate,s.scale,s.originPoint),eo(t.y,a.translate,a.scale,a.originPoint)}const qm=.999999999999,eu=1.0000000000001;function wC(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&&Pr(t,{x:-i.scroll.offset.x,y:-i.scroll.offset.y}),l&&(s.x*=l.x.scale,s.y*=l.y.scale,Op(t,l)),r&&dr(i.latestValues)&&Pr(t,i.latestValues))}s.x<eu&&s.x>qm&&(s.x=1),s.y<eu&&s.y>qm&&(s.y=1)}function Dr(t,s){t.min=t.min+s,t.max=t.max+s}function tu(t,s,a,r,n=.5){const i=Wt(t.min,t.max,n);eo(t,s,a,i,r)}function Pr(t,s){tu(t.x,s.x,s.scaleX,s.scale,s.originX),tu(t.y,s.y,s.scaleY,s.scale,s.originY)}function Up(t,s){return Mp(NC(t.getBoundingClientRect(),s))}function CC(t,s,a){const r=Up(t,a),{scroll:n}=s;return n&&(Dr(r.x,n.offset.x),Dr(r.y,n.offset.y)),r}const su=()=>({translate:0,scale:1,origin:0,originPoint:0}),Ir=()=>({x:su(),y:su()}),au=()=>({min:0,max:0}),Zt=()=>({x:au(),y:au()}),to={current:null},Bp={current:!1};function SC(){if(Bp.current=!0,!!Oo)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),s=()=>to.current=t.matches;t.addEventListener("change",s),s()}else to.current=!1}const AC=new WeakMap;function TC(t,s,a){for(const r in s){const n=s[r],i=a[r];if(ks(n))t.addValue(r,n);else if(ks(i))t.addValue(r,Ur(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,Ur(l!==void 0?l:n,{owner:t}))}}for(const r in a)s[r]===void 0&&t.removeValue(r);return s}const ru=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class kC{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=sc,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 x=Vs.now();this.renderScheduledAt<x&&(this.renderScheduledAt=x,Ot.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=$i(a),this.isVariantNode=Ap(a),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(s&&s.current);const{willChange:m,...h}=this.scrapeMotionValuesFromProps(a,{},this);for(const x in h){const u=h[x];c[x]!==void 0&&ks(u)&&u.set(c[x])}}mount(s){var a;this.current=s,AC.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)),Bp.current||SC(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:to.current,(a=this.parent)==null||a.addChild(this),this.update(this.props,this.presenceContext)}unmount(){var s;this.projection&&this.projection.unmount(),Za(this.notifyUpdate),Za(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=Jr.has(s);r&&this.onBindTransform&&this.onBindTransform();const n=a.on("change",l=>{this.latestValues[s]=l,this.props.onUpdate&&Ot.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):Zt()}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<ru.length;r++){const n=ru[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=TC(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=Ur(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"&&(Eh(r)||_h(r))?r=parseFloat(r):!L1(r)&&Ja.test(a)&&(r=gp(s,a)),this.setBaseTarget(s,ks(r)?r.get():r)),ks(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=xc(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&&!ks(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 Ho),this.events[s].add(a)}notify(s,...a){this.events[s]&&this.events[s].notify(...a)}scheduleRenderMicrotask(){nc.render(this.render)}}class Vp extends kC{constructor(){super(...arguments),this.KeyframeResolver=C1}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;ks(s)&&(this.childSubscription=s.on("change",a=>{this.current&&(this.current.textContent=`${a}`)}))}}function zp(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 RC(t){return window.getComputedStyle(t)}class DC extends Vp{constructor(){super(...arguments),this.type="html",this.renderInstance=zp}readValueFromInstance(s,a){var r;if(Jr.has(a))return(r=this.projection)!=null&&r.isProjecting?Wl(a):zw(s,a);{const n=RC(s),i=(Yo(a)?n.getPropertyValue(a):n[a])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(s,{transformPagePoint:a}){return Up(s,a)}build(s,a,r){dc(s,a,r.transformTemplate)}scrapeMotionValuesFromProps(s,a,r){return hc(s,a,r)}}const Hp=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 PC(t,s,a,r){zp(t,s,void 0,r);for(const n in s.attrs)t.setAttribute(Hp.has(n)?n:pc(n),s.attrs[n])}class IC extends Vp{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Zt}getBaseTargetFromProps(s,a){return s[a]}readValueFromInstance(s,a){if(Jr.has(a)){const r=pp(a);return r&&r.default||0}return a=Hp.has(a)?a:pc(a),s.getAttribute(a)}scrapeMotionValuesFromProps(s,a,r){return Ep(s,a,r)}build(s,a,r){Rp(s,a,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(s,a,r,n){PC(s,a,r,n)}mount(s){this.isSVGTag=Pp(s.tagName),super.mount(s)}}const EC=(t,s)=>uc(t)?new IC(s):new DC(s,{allowProjection:t!==p.Fragment});function $r(t,s,a){const r=t.getProps();return xc(r,s,a!==void 0?a:r.custom,t)}const so=t=>Array.isArray(t);function FC(t,s,a){t.hasValue(s)?t.getValue(s).set(a):t.addValue(s,Ur(a))}function _C(t){return so(t)?t[t.length-1]||0:t}function LC(t,s){const a=$r(t,s);let{transitionEnd:r={},transition:n={},...i}=a||{};i={...i,...r};for(const l in i){const o=_C(i[l]);FC(t,l,o)}}function MC(t){return!!(ks(t)&&t.add)}function ao(t,s){const a=t.getValue("willChange");if(MC(a))return a.add(s);if(!a&&Ea.WillChange){const r=new Ea.WillChange("auto");t.addValue("willChange",r),r.add(s)}}function Gp(t){return t.props[Fp]}const $C=t=>t!==null;function OC(t,{repeat:s,repeatType:a="loop"},r){const n=t.filter($C),i=s&&a!=="loop"&&s%2===1?0:n.length-1;return n[i]}const UC={type:"spring",stiffness:500,damping:25,restSpeed:10},BC=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),VC={type:"keyframes",duration:.8},zC={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},HC=(t,{keyframes:s})=>s.length>2?VC:Jr.has(t)?t.startsWith("scale")?BC(s[1]):UC:zC;function GC({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 gc=(t,s,a,r={},n,i)=>l=>{const o=ac(r,t)||{},c=o.delay||r.delay||0;let{elapsed:d=0}=r;d=d-ja(c);const m={keyframes:Array.isArray(a)?a:[null,a],ease:"easeOut",velocity:s.getVelocity(),...o,delay:-d,onUpdate:x=>{s.set(x),o.onUpdate&&o.onUpdate(x)},onComplete:()=>{l(),o.onComplete&&o.onComplete()},name:t,motionValue:s,element:i?void 0:n};GC(o)||Object.assign(m,HC(t,m)),m.duration&&(m.duration=ja(m.duration)),m.repeatDelay&&(m.repeatDelay=ja(m.repeatDelay)),m.from!==void 0&&(m.keyframes[0]=m.from);let h=!1;if((m.type===!1||m.duration===0&&!m.repeatDelay)&&(Jl(m),m.delay===0&&(h=!0)),(Ea.instantAnimations||Ea.skipAnimations)&&(h=!0,Jl(m),m.delay=0),m.allowFlatten=!o.type&&!o.ease,h&&!i&&s.get()!==void 0){const x=OC(m.keyframes,o);if(x!==void 0){Ot.update(()=>{m.onUpdate(x),m.onComplete()});return}}return o.isSync?new tc(m):new u1(m)};function WC({protectedKeys:t,needsAnimating:s},a){const r=t.hasOwnProperty(a)&&s[a]!==!0;return s[a]=!1,r}function Wp(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 h=t.getValue(m,t.latestValues[m]??null),x=o[m];if(x===void 0||d&&WC(d,m))continue;const u={delay:a,...ac(i||{},m)},g=h.get();if(g!==void 0&&!h.isAnimating&&!Array.isArray(x)&&x===g&&!u.velocity)continue;let b=!1;if(window.MotionHandoffAnimation){const y=Gp(t);if(y){const v=window.MotionHandoffAnimation(y,m,Ot);v!==null&&(u.startTime=v,b=!0)}}ao(t,m),h.start(gc(m,h,x,t.shouldReduceMotion&&up.has(m)?{type:!1}:u,t,b));const f=h.animation;f&&c.push(f)}return l&&Promise.all(c).then(()=>{Ot.update(()=>{l&&LC(t,l)})}),c}function Yp(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 ro(t,s,a={}){var c;const r=$r(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(Wp(t,r,a)):()=>Promise.resolve(),l=t.variantChildren&&t.variantChildren.size?(d=0)=>{const{delayChildren:m=0,staggerChildren:h,staggerDirection:x}=n;return YC(t,s,d,m,h,x,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 YC(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(ro(c,s,{...l,delay:a+(typeof r=="function"?0:r)+Yp(t.variantChildren,c,r,n,i)}).then(()=>c.notify("AnimationComplete",s)));return Promise.all(o)}function KC(t,s,a={}){t.notify("AnimationStart",s);let r;if(Array.isArray(s)){const n=s.map(i=>ro(t,i,a));r=Promise.all(n)}else if(typeof s=="string")r=ro(t,s,a);else{const n=typeof s=="function"?$r(t,s,a.custom):s;r=Promise.all(Wp(t,n,a))}return r.then(()=>{t.notify("AnimationComplete",s)})}function Kp(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 XC=cc.length;function Xp(t){if(!t)return;if(!t.isControllingVariants){const a=t.parent?Xp(t.parent)||{}:{};return t.props.initial!==void 0&&(a.initial=t.props.initial),a}const s={};for(let a=0;a<XC;a++){const r=cc[a],n=t.props[r];(Nn(n)||n===!1)&&(s[r]=n)}return s}const ZC=[...oc].reverse(),JC=oc.length;function QC(t){return s=>Promise.all(s.map(({animation:a,options:r})=>KC(t,a,r)))}function qC(t){let s=QC(t),a=nu(),r=!0;const n=c=>(d,m)=>{var x;const h=$r(t,m,c==="exit"?(x=t.presenceContext)==null?void 0:x.custom:void 0);if(h){const{transition:u,transitionEnd:g,...b}=h;d={...d,...b,...g}}return d};function i(c){s=c(t)}function l(c){const{props:d}=t,m=Xp(t.parent)||{},h=[],x=new Set;let u={},g=1/0;for(let f=0;f<JC;f++){const y=ZC[f],v=a[y],C=d[y]!==void 0?d[y]:m[y],w=Nn(C),A=y===c?v.isActive:null;A===!1&&(g=f);let N=C===m[y]&&C!==d[y]&&w;if(N&&r&&t.manuallyAnimateOnMount&&(N=!1),v.protectedKeys={...u},!v.isActive&&A===null||!C&&!v.prevProp||Mi(C)||typeof C=="boolean")continue;const _=e2(v.prevProp,C);let T=_||y===c&&v.isActive&&!N&&w||f>g&&w,R=!1;const j=Array.isArray(C)?C:[C];let E=j.reduce(n(y),{});A===!1&&(E={});const{prevResolvedValues:P={}}=v,B={...P,...E},k=D=>{T=!0,x.has(D)&&(R=!0,x.delete(D)),v.needsAnimating[D]=!0;const S=t.getValue(D);S&&(S.liveStyle=!1)};for(const D in B){const S=E[D],O=P[D];if(u.hasOwnProperty(D))continue;let I=!1;so(S)&&so(O)?I=!Kp(S,O):I=S!==O,I?S!=null?k(D):x.add(D):S!==void 0&&x.has(D)?k(D):v.protectedKeys[D]=!0}v.prevProp=C,v.prevResolvedValues=E,v.isActive&&(u={...u,...E}),r&&t.blockInitialAnimation&&(T=!1);const L=N&&_;T&&(!L||R)&&h.push(...j.map(D=>{const S={type:y};if(typeof D=="string"&&r&&!L&&t.manuallyAnimateOnMount&&t.parent){const{parent:O}=t,I=$r(O,D);if(O.enteringChildren&&I){const{delayChildren:M}=I.transition||{};S.delay=Yp(O.enteringChildren,t,M)}}return{animation:D,options:S}}))}if(x.size){const f={};if(typeof d.initial!="boolean"){const y=$r(t,Array.isArray(d.initial)?d.initial[0]:d.initial);y&&y.transition&&(f.transition=y.transition)}x.forEach(y=>{const v=t.getBaseTarget(y),C=t.getValue(y);C&&(C.liveStyle=!0),f[y]=v??null}),h.push({animation:f})}let b=!!h.length;return r&&(d.initial===!1||d.initial===d.animate)&&!t.manuallyAnimateOnMount&&(b=!1),r=!1,b?s(h):Promise.resolve()}function o(c,d){var h;if(a[c].isActive===d)return Promise.resolve();(h=t.variantChildren)==null||h.forEach(x=>{var u;return(u=x.animationState)==null?void 0:u.setActive(c,d)}),a[c].isActive=d;const m=l(c);for(const x in a)a[x].protectedKeys={};return m}return{animateChanges:l,setActive:o,setAnimateFunction:i,getState:()=>a,reset:()=>{a=nu()}}}function e2(t,s){return typeof s=="string"?s!==t:Array.isArray(s)?!Kp(s,t):!1}function lr(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function nu(){return{animate:lr(!0),whileInView:lr(),whileHover:lr(),whileTap:lr(),whileDrag:lr(),whileFocus:lr(),exit:lr()}}class qa{constructor(s){this.isMounted=!1,this.node=s}update(){}}class t2 extends qa{constructor(s){super(s),s.animationState||(s.animationState=qC(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();Mi(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 s2=0;class a2 extends qa{constructor(){super(...arguments),this.id=s2++}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 r2={animation:{Feature:t2},exit:{Feature:a2}};function Cn(t,s,a,r={passive:!0}){return t.addEventListener(s,a,r),()=>t.removeEventListener(s,a)}function _n(t){return{point:{x:t.pageX,y:t.pageY}}}const n2=t=>s=>ic(s)&&t(s,_n(s));function hn(t,s,a,r){return Cn(t,s,n2(a),r)}const Zp=1e-4,i2=1-Zp,l2=1+Zp,Jp=.01,o2=0-Jp,c2=0+Jp;function Rs(t){return t.max-t.min}function d2(t,s,a){return Math.abs(t-s)<=a}function iu(t,s,a,r=.5){t.origin=r,t.originPoint=Wt(s.min,s.max,t.origin),t.scale=Rs(a)/Rs(s),t.translate=Wt(a.min,a.max,t.origin)-t.originPoint,(t.scale>=i2&&t.scale<=l2||isNaN(t.scale))&&(t.scale=1),(t.translate>=o2&&t.translate<=c2||isNaN(t.translate))&&(t.translate=0)}function pn(t,s,a,r){iu(t.x,s.x,a.x,r?r.originX:void 0),iu(t.y,s.y,a.y,r?r.originY:void 0)}function lu(t,s,a){t.min=a.min+s.min,t.max=t.min+Rs(s)}function m2(t,s,a){lu(t.x,s.x,a.x),lu(t.y,s.y,a.y)}function ou(t,s,a){t.min=s.min-a.min,t.max=t.min+Rs(s)}function gn(t,s,a){ou(t.x,s.x,a.x),ou(t.y,s.y,a.y)}function sa(t){return[t("x"),t("y")]}const Qp=({current:t})=>t?t.ownerDocument.defaultView:null,cu=(t,s)=>Math.abs(t-s);function u2(t,s){const a=cu(t.x,s.x),r=cu(t.y,s.y);return Math.sqrt(a**2+r**2)}class qp{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 x=fl(this.lastMoveEventInfo,this.history),u=this.startEvent!==null,g=u2(x.offset,{x:0,y:0})>=this.distanceThreshold;if(!u&&!g)return;const{point:b}=x,{timestamp:f}=js;this.history.push({...b,timestamp:f});const{onStart:y,onMove:v}=this.handlers;u||(y&&y(this.lastMoveEvent,x),this.startEvent=this.lastMoveEvent),v&&v(this.lastMoveEvent,x)},this.handlePointerMove=(x,u)=>{this.lastMoveEvent=x,this.lastMoveEventInfo=gl(u,this.transformPagePoint),Ot.update(this.updatePoint,!0)},this.handlePointerUp=(x,u)=>{this.end();const{onEnd:g,onSessionEnd:b,resumeAnimation:f}=this.handlers;if(this.dragSnapToOrigin&&f&&f(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=fl(x.type==="pointercancel"?this.lastMoveEventInfo:gl(u,this.transformPagePoint),this.history);this.startEvent&&g&&g(x,y),b&&b(x,y)},!ic(s))return;this.dragSnapToOrigin=i,this.handlers=a,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=n||window;const o=_n(s),c=gl(o,this.transformPagePoint),{point:d}=c,{timestamp:m}=js;this.history=[{...d,timestamp:m}];const{onSessionStart:h}=a;h&&h(s,fl(c,this.history)),this.removeListeners=In(hn(this.contextWindow,"pointermove",this.handlePointerMove),hn(this.contextWindow,"pointerup",this.handlePointerUp),hn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(s){this.handlers=s}end(){this.removeListeners&&this.removeListeners(),Za(this.updatePoint)}}function gl(t,s){return s?{point:s(t.point)}:t}function du(t,s){return{x:t.x-s.x,y:t.y-s.y}}function fl({point:t},s){return{point:t,delta:du(t,eg(s)),offset:du(t,x2(s)),velocity:h2(s,.1)}}function x2(t){return t[0]}function eg(t){return t[t.length-1]}function h2(t,s){if(t.length<2)return{x:0,y:0};let a=t.length-1,r=null;const n=eg(t);for(;a>=0&&(r=t[a],!(n.timestamp-r.timestamp>ja(s)));)a--;if(!r)return{x:0,y:0};const i=ra(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 p2(t,{min:s,max:a},r){return s!==void 0&&t<s?t=r?Wt(s,t,r.min):Math.max(t,s):a!==void 0&&t>a&&(t=r?Wt(a,t,r.max):Math.min(t,a)),t}function mu(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 g2(t,{top:s,left:a,bottom:r,right:n}){return{x:mu(t.x,a,n),y:mu(t.y,s,r)}}function uu(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 f2(t,s){return{x:uu(t.x,s.x),y:uu(t.y,s.y)}}function b2(t,s){let a=.5;const r=Rs(t),n=Rs(s);return n>r?a=yn(s.min,s.max-r,t.min):r>n&&(a=yn(t.min,t.max-n,s.min)),Ia(0,1,a)}function y2(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 no=.35;function v2(t=no){return t===!1?t=0:t===!0&&(t=no),{x:xu(t,"left","right"),y:xu(t,"top","bottom")}}function xu(t,s,a){return{min:hu(t,s),max:hu(t,a)}}function hu(t,s){return typeof t=="number"?t:t[s]||0}const j2=new WeakMap;class N2{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=Zt(),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=h=>{const{dragSnapToOrigin:x}=this.getProps();x?this.pauseAnimation():this.stopAnimation(),a&&this.snapToCursor(_n(h).point)},l=(h,x)=>{const{drag:u,dragPropagation:g,onDragStart:b}=this.getProps();if(u&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=k1(u),!this.openDragLock))return;this.latestPointerEvent=h,this.latestPanInfo=x,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),sa(y=>{let v=this.getAxisMotionValue(y).get()||0;if(Na.test(v)){const{projection:C}=this.visualElement;if(C&&C.layout){const w=C.layout.layoutBox[y];w&&(v=Rs(w)*(parseFloat(v)/100))}}this.originPoint[y]=v}),b&&Ot.postRender(()=>b(h,x)),ao(this.visualElement,"transform");const{animationState:f}=this.visualElement;f&&f.setActive("whileDrag",!0)},o=(h,x)=>{this.latestPointerEvent=h,this.latestPanInfo=x;const{dragPropagation:u,dragDirectionLock:g,onDirectionLock:b,onDrag:f}=this.getProps();if(!u&&!this.openDragLock)return;const{offset:y}=x;if(g&&this.currentDirection===null){this.currentDirection=w2(y),this.currentDirection!==null&&b&&b(this.currentDirection);return}this.updateAxis("x",x.point,y),this.updateAxis("y",x.point,y),this.visualElement.render(),f&&f(h,x)},c=(h,x)=>{this.latestPointerEvent=h,this.latestPanInfo=x,this.stop(h,x),this.latestPointerEvent=null,this.latestPanInfo=null},d=()=>sa(h=>{var x;return this.getAnimationState(h)==="paused"&&((x=this.getAxisMotionValue(h).animation)==null?void 0:x.play())}),{dragSnapToOrigin:m}=this.getProps();this.panSession=new qp(s,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:m,distanceThreshold:r,contextWindow:Qp(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&&Ot.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||!zn(s,n,this.currentDirection))return;const i=this.getAxisMotionValue(s);let l=this.originPoint[s]+r[s];this.constraints&&this.constraints[s]&&(l=p2(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&&Rr(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&r?this.constraints=g2(r.layoutBox,s):this.constraints=!1,this.elastic=v2(a),n!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&sa(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=y2(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:s,onMeasureDragConstraints:a}=this.getProps();if(!s||!Rr(s))return!1;const r=s.current,{projection:n}=this.visualElement;if(!n||!n.layout)return!1;const i=CC(r,n.root,this.visualElement.getTransformPagePoint());let l=f2(n.layout.layoutBox,i);if(a){const o=a(jC(l));this.hasMutatedConstraints=!!o,o&&(l=Mp(o))}return l}startAnimation(s){const{drag:a,dragMomentum:r,dragElastic:n,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=sa(m=>{if(!zn(m,a,this.currentDirection))return;let h=c&&c[m]||{};l&&(h={min:0,max:0});const x=n?200:1e6,u=n?40:1e7,g={type:"inertia",velocity:r?s[m]:0,bounceStiffness:x,bounceDamping:u,timeConstant:750,restDelta:1,restSpeed:10,...i,...h};return this.startAxisValueAnimation(m,g)});return Promise.all(d).then(o)}startAxisValueAnimation(s,a){const r=this.getAxisMotionValue(s);return ao(this.visualElement,s),r.start(gc(s,r,0,a,this.visualElement,!1))}stopAnimation(){sa(s=>this.getAxisMotionValue(s).stop())}pauseAnimation(){sa(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){sa(a=>{const{drag:r}=this.getProps();if(!zn(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]-Wt(l,o,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:s,dragConstraints:a}=this.getProps(),{projection:r}=this.visualElement;if(!Rr(a)||!r||!this.constraints)return;this.stopAnimation();const n={x:0,y:0};sa(l=>{const o=this.getAxisMotionValue(l);if(o&&this.constraints!==!1){const c=o.get();n[l]=b2({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(),sa(l=>{if(!zn(l,s,null))return;const o=this.getAxisMotionValue(l),{min:c,max:d}=this.constraints[l];o.set(Wt(c,d,n[l]))})}addListeners(){if(!this.visualElement.current)return;j2.set(this.visualElement,this);const s=this.visualElement.current,a=hn(s,"pointerdown",c=>{const{drag:d,dragListener:m=!0}=this.getProps();d&&m&&this.start(c)}),r=()=>{const{dragConstraints:c}=this.getProps();Rr(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()),Ot.read(r);const l=Cn(window,"resize",()=>this.scalePositionWithinConstraints()),o=n.addEventListener("didUpdate",({delta:c,hasLayoutChanged:d})=>{this.isDragging&&d&&(sa(m=>{const h=this.getAxisMotionValue(m);h&&(this.originPoint[m]+=c[m].translate,h.set(h.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=no,dragMomentum:o=!0}=s;return{...s,drag:a,dragDirectionLock:r,dragPropagation:n,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function zn(t,s,a){return(s===!0||s===t)&&(a===null||a===t)}function w2(t,s=10){let a=null;return Math.abs(t.y)>s?a="y":Math.abs(t.x)>s&&(a="x"),a}class C2 extends qa{constructor(s){super(s),this.removeGroupControls=ia,this.removeListeners=ia,this.controls=new N2(s)}mount(){const{dragControls:s}=this.node.getProps();s&&(this.removeGroupControls=s.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||ia}unmount(){this.removeGroupControls(),this.removeListeners()}}const pu=t=>(s,a)=>{t&&Ot.postRender(()=>t(s,a))};class S2 extends qa{constructor(){super(...arguments),this.removePointerDownListener=ia}onPointerDown(s){this.session=new qp(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Qp(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:a,onPan:r,onPanEnd:n}=this.node.getProps();return{onSessionStart:pu(s),onStart:pu(a),onMove:r,onEnd:(i,l)=>{delete this.session,n&&Ot.postRender(()=>n(i,l))}}}mount(){this.removePointerDownListener=hn(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 ei={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function gu(t,s){return s.max===s.min?0:t/(s.max-s.min)*100}const rn={correct:(t,s)=>{if(!s.target)return t;if(typeof t=="string")if(et.test(t))t=parseFloat(t);else return t;const a=gu(t,s.target.x),r=gu(t,s.target.y);return`${a}% ${r}%`}},A2={correct:(t,{treeScale:s,projectionDelta:a})=>{const r=t,n=Ja.parse(t);if(n.length>5)return r;const i=Ja.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=Wt(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 bl=!1;class T2 extends p.Component{componentDidMount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r,layoutId:n}=this.props,{projection:i}=s;X1(k2),i&&(a.group&&a.group.add(i),r&&r.register&&n&&r.register(i),bl&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,onExitComplete:()=>this.safeToRemove()})),ei.hasEverUpdated=!0}getSnapshotBeforeUpdate(s){const{layoutDependency:a,visualElement:r,drag:n,isPresent:i}=this.props,{projection:l}=r;return l&&(l.isPresent=i,bl=!0,n||s.layoutDependency!==a||a===void 0||s.isPresent!==i?l.willUpdate():this.safeToRemove(),s.isPresent!==i&&(i?l.promote():l.relegate()||Ot.postRender(()=>{const o=l.getStack();(!o||!o.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:s}=this.props.visualElement;s&&(s.root.didUpdate(),nc.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r}=this.props,{projection:n}=s;bl=!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 tg(t){const[s,a]=wp(),r=p.useContext(Mo);return e.jsx(T2,{...t,layoutGroup:r,switchLayoutGroup:p.useContext(_p),isPresent:s,safeToRemove:a})}const k2={borderRadius:{...rn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:rn,borderTopRightRadius:rn,borderBottomLeftRadius:rn,borderBottomRightRadius:rn,boxShadow:A2};function R2(t,s,a){const r=ks(t)?t:Ur(t);return r.start(gc("",r,s,a)),r.animation}const D2=(t,s)=>t.depth-s.depth;class P2{constructor(){this.children=[],this.isDirty=!1}add(s){Uo(this.children,s),this.isDirty=!0}remove(s){Bo(this.children,s),this.isDirty=!0}forEach(s){this.isDirty&&this.children.sort(D2),this.isDirty=!1,this.children.forEach(s)}}function I2(t,s){const a=Vs.now(),r=({timestamp:n})=>{const i=n-a;i>=s&&(Za(r),t(i-s))};return Ot.setup(r,!0),()=>Za(r)}const sg=["TopLeft","TopRight","BottomLeft","BottomRight"],E2=sg.length,fu=t=>typeof t=="string"?parseFloat(t):t,bu=t=>typeof t=="number"||et.test(t);function F2(t,s,a,r,n,i){n?(t.opacity=Wt(0,a.opacity??1,_2(r)),t.opacityExit=Wt(s.opacity??1,0,L2(r))):i&&(t.opacity=Wt(s.opacity??1,a.opacity??1,r));for(let l=0;l<E2;l++){const o=`border${sg[l]}Radius`;let c=yu(s,o),d=yu(a,o);if(c===void 0&&d===void 0)continue;c||(c=0),d||(d=0),c===0||d===0||bu(c)===bu(d)?(t[o]=Math.max(Wt(fu(c),fu(d),r),0),(Na.test(d)||Na.test(c))&&(t[o]+="%")):t[o]=d}(s.rotate||a.rotate)&&(t.rotate=Wt(s.rotate||0,a.rotate||0,r))}function yu(t,s){return t[s]!==void 0?t[s]:t.borderRadius}const _2=ag(0,.5,zh),L2=ag(.5,.95,ia);function ag(t,s,a){return r=>r<t?0:r>s?1:a(yn(t,s,r))}function vu(t,s){t.min=s.min,t.max=s.max}function ta(t,s){vu(t.x,s.x),vu(t.y,s.y)}function ju(t,s){t.translate=s.translate,t.scale=s.scale,t.originPoint=s.originPoint,t.origin=s.origin}function Nu(t,s,a,r,n){return t-=s,t=pi(t,1/a,r),n!==void 0&&(t=pi(t,1/n,r)),t}function M2(t,s=0,a=1,r=.5,n,i=t,l=t){if(Na.test(s)&&(s=parseFloat(s),s=Wt(l.min,l.max,s/100)-l.min),typeof s!="number")return;let o=Wt(i.min,i.max,r);t===i&&(o-=s),t.min=Nu(t.min,s,a,o,n),t.max=Nu(t.max,s,a,o,n)}function wu(t,s,[a,r,n],i,l){M2(t,s[a],s[r],s[n],s.scale,i,l)}const $2=["x","scaleX","originX"],O2=["y","scaleY","originY"];function Cu(t,s,a,r){wu(t.x,s,$2,a?a.x:void 0,r?r.x:void 0),wu(t.y,s,O2,a?a.y:void 0,r?r.y:void 0)}function Su(t){return t.translate===0&&t.scale===1}function rg(t){return Su(t.x)&&Su(t.y)}function Au(t,s){return t.min===s.min&&t.max===s.max}function U2(t,s){return Au(t.x,s.x)&&Au(t.y,s.y)}function Tu(t,s){return Math.round(t.min)===Math.round(s.min)&&Math.round(t.max)===Math.round(s.max)}function ng(t,s){return Tu(t.x,s.x)&&Tu(t.y,s.y)}function ku(t){return Rs(t.x)/Rs(t.y)}function Ru(t,s){return t.translate===s.translate&&t.scale===s.scale&&t.originPoint===s.originPoint}class B2{constructor(){this.members=[]}add(s){Uo(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 V2(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:h,rotateY:x,skewX:u,skewY:g}=a;d&&(r=`perspective(${d}px) ${r}`),m&&(r+=`rotate(${m}deg) `),h&&(r+=`rotateX(${h}deg) `),x&&(r+=`rotateY(${x}deg) `),u&&(r+=`skewX(${u}deg) `),g&&(r+=`skewY(${g}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 yl=["","X","Y","Z"],z2=1e3;let H2=0;function vl(t,s,a,r){const{latestValues:n}=s;n[t]&&(a[t]=n[t],s.setStaticValue(t,0),r&&(r[t]=0))}function ig(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:s}=t.options;if(!s)return;const a=Gp(s);if(window.MotionHasOptimisedAnimation(a,"transform")){const{layout:n,layoutId:i}=t.options;window.MotionCancelOptimisedAnimation(a,"transform",Ot,!(n||i))}const{parent:r}=t;r&&!r.hasCheckedOptimisedAppear&&ig(r)}function lg({attachResizeListener:t,defaultParent:s,measureScroll:a,checkIsScrollRoot:r,resetTransform:n}){return class{constructor(l={},o=s==null?void 0:s()){this.id=H2++,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(Y2),this.nodes.forEach(J2),this.nodes.forEach(Q2),this.nodes.forEach(K2)},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 P2)}addEventListener(l,o){return this.eventHandlers.has(l)||this.eventHandlers.set(l,new Ho),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=Np(l)&&!F1(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,h=0;const x=()=>this.root.updateBlockedByResize=!1;Ot.read(()=>{h=window.innerWidth}),t(l,()=>{const u=window.innerWidth;u!==h&&(h=u,this.root.updateBlockedByResize=!0,m&&m(),m=I2(x,250),ei.hasAnimatedSinceResize&&(ei.hasAnimatedSinceResize=!1,this.nodes.forEach(Iu)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&d&&(o||c)&&this.addEventListener("didUpdate",({delta:m,hasLayoutChanged:h,hasRelativeLayoutChanged:x,layout:u})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const g=this.options.transition||d.getDefaultTransition()||aS,{onLayoutAnimationStart:b,onLayoutAnimationComplete:f}=d.getProps(),y=!this.targetLayout||!ng(this.targetLayout,u),v=!h&&x;if(this.options.layoutRoot||this.resumeFrom||v||h&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const C={...ac(g,"layout"),onPlay:b,onComplete:f};(d.shouldReduceMotion||this.options.layoutRoot)&&(C.delay=0,C.type=!1),this.startAnimation(C),this.setAnimationOrigin(m,v)}else h||Iu(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=u})}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(),Za(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(q2),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&&ig(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let m=0;m<this.path.length;m++){const h=this.path[m];h.shouldResetTransform=!0,h.updateScroll("snapshot"),h.options.layoutRoot&&h.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(Du);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Pu);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(Z2),this.nodes.forEach(G2),this.nodes.forEach(W2)):this.nodes.forEach(Pu),this.clearAllSnapshots();const o=Vs.now();js.delta=Ia(0,1e3/60,o-js.timestamp),js.timestamp=o,js.isProcessing=!0,ol.update.process(js),ol.preRender.process(js),ol.render.process(js),js.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,nc.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(X2),this.sharedNodes.forEach(eS)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,Ot.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){Ot.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Rs(this.snapshot.measuredBox.x)&&!Rs(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let c=0;c<this.path.length;c++)this.path[c].updateScroll();const l=this.layout;this.layout=this.measure(!1),this.layoutCorrected=Zt(),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&&!rg(this.projectionDelta),c=this.getTransformTemplate(),d=c?c(this.latestValues,""):void 0,m=d!==this.prevTransformTemplateValue;l&&this.instance&&(o||dr(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)),rS(c),{animationId:this.root.animationId,measuredBox:o,layoutBox:c,latestValues:{},source:this.id}}measurePageBox(){var d;const{visualElement:l}=this.options;if(!l)return Zt();const o=l.measureViewportBox();if(!(((d=this.scroll)==null?void 0:d.wasRoot)||this.path.some(nS))){const{scroll:m}=this.root;m&&(Dr(o.x,m.offset.x),Dr(o.y,m.offset.y))}return o}removeElementScroll(l){var c;const o=Zt();if(ta(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:h,options:x}=m;m!==this.root&&h&&x.layoutScroll&&(h.wasRoot&&ta(o,l),Dr(o.x,h.offset.x),Dr(o.y,h.offset.y))}return o}applyTransform(l,o=!1){const c=Zt();ta(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&&Pr(c,{x:-m.scroll.offset.x,y:-m.scroll.offset.y}),dr(m.latestValues)&&Pr(c,m.latestValues)}return dr(this.latestValues)&&Pr(c,this.latestValues),c}removeTransform(l){const o=Zt();ta(o,l);for(let c=0;c<this.path.length;c++){const d=this.path[c];if(!d.instance||!dr(d.latestValues))continue;ql(d.latestValues)&&d.updateSnapshot();const m=Zt(),h=d.measurePageBox();ta(m,h),Cu(o,d.latestValues,d.snapshot?d.snapshot.layoutBox:void 0,m)}return dr(this.latestValues)&&Cu(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!==js.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(l=!1){var x;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||(x=this.parent)!=null&&x.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:m,layoutId:h}=this.options;if(!(!this.layout||!(m||h))){if(this.resolvedRelativeTargetAt=js.timestamp,!this.targetDelta&&!this.relativeTarget){const u=this.getClosestProjectingParent();u&&u.layout&&this.animationProgress!==1?(this.relativeParent=u,this.forceRelativeParentToResolveTarget(),this.relativeTarget=Zt(),this.relativeTargetOrigin=Zt(),gn(this.relativeTargetOrigin,this.layout.layoutBox,u.layout.layoutBox),ta(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=Zt(),this.targetWithTransforms=Zt()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),m2(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):ta(this.target,this.layout.layoutBox),Op(this.target,this.targetDelta)):ta(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const u=this.getClosestProjectingParent();u&&!!u.resumingFrom==!!this.resumingFrom&&!u.options.layoutScroll&&u.target&&this.animationProgress!==1?(this.relativeParent=u,this.forceRelativeParentToResolveTarget(),this.relativeTarget=Zt(),this.relativeTargetOrigin=Zt(),gn(this.relativeTargetOrigin,this.target,u.target),ta(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||ql(this.parent.latestValues)||$p(this.parent.latestValues)))return this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}calcProjection(){var g;const l=this.getLead(),o=!!this.resumingFrom||this!==l;let c=!0;if((this.isProjectionDirty||(g=this.parent)!=null&&g.isProjectionDirty)&&(c=!1),o&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(c=!1),this.resolvedRelativeTargetAt===js.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;ta(this.layoutCorrected,this.layout.layoutBox);const h=this.treeScale.x,x=this.treeScale.y;wC(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=Zt());const{target:u}=l;if(!u){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(ju(this.prevProjectionDelta.x,this.projectionDelta.x),ju(this.prevProjectionDelta.y,this.projectionDelta.y)),pn(this.projectionDelta,this.layoutCorrected,u,this.latestValues),(this.treeScale.x!==h||this.treeScale.y!==x||!Ru(this.projectionDelta.x,this.prevProjectionDelta.x)||!Ru(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",u))}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=Ir(),this.projectionDelta=Ir(),this.projectionDeltaWithTransform=Ir()}setAnimationOrigin(l,o=!1){const c=this.snapshot,d=c?c.latestValues:{},m={...this.latestValues},h=Ir();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!o;const x=Zt(),u=c?c.source:void 0,g=this.layout?this.layout.source:void 0,b=u!==g,f=this.getStack(),y=!f||f.members.length<=1,v=!!(b&&!y&&this.options.crossfade===!0&&!this.path.some(sS));this.animationProgress=0;let C;this.mixTargetDelta=w=>{const A=w/1e3;Eu(h.x,l.x,A),Eu(h.y,l.y,A),this.setTargetDelta(h),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(gn(x,this.layout.layoutBox,this.relativeParent.layout.layoutBox),tS(this.relativeTarget,this.relativeTargetOrigin,x,A),C&&U2(this.relativeTarget,C)&&(this.isProjectionDirty=!1),C||(C=Zt()),ta(C,this.relativeTarget)),b&&(this.animationValues=m,F2(m,d,this.latestValues,A,v,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=A},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&&(Za(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Ot.update(()=>{ei.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=Ur(0)),this.currentAnimation=R2(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(z2),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&&og(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||Zt();const h=Rs(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+h;const x=Rs(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+x}ta(o,c),Pr(o,m),pn(this.projectionDeltaWithTransform,this.layoutCorrected,o,m)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new B2),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&&vl("z",l,d,this.animationValues);for(let m=0;m<yl.length;m++)vl(`rotate${yl[m]}`,l,d,this.animationValues),vl(`skew${yl[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=qn(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=qn(o==null?void 0:o.pointerEvents)||""),this.hasProjected&&!dr(this.latestValues)&&(l.transform=c?c({},""):"none",this.hasProjected=!1);return}l.visibility="";const m=d.animationValues||d.latestValues;this.applyTransformsToTarget();let h=V2(this.projectionDeltaWithTransform,this.treeScale,m);c&&(h=c(m,h)),l.transform=h;const{x,y:u}=this.projectionDelta;l.transformOrigin=`${x.origin*100}% ${u.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 g in wn){if(m[g]===void 0)continue;const{correct:b,applyTo:f,isCSSVariable:y}=wn[g],v=h==="none"?m[g]:b(m[g],d);if(f){const C=f.length;for(let w=0;w<C;w++)l[f[w]]=v}else y?this.options.visualElement.renderState.vars[g]=v:l[g]=v}this.options.layoutId&&(l.pointerEvents=d===this?qn(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(Du),this.root.sharedNodes.clear()}}}function G2(t){t.updateLayout()}function W2(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"?sa(h=>{const x=l?s.measuredBox[h]:s.layoutBox[h],u=Rs(x);x.min=r[h].min,x.max=x.min+u}):og(i,s.layoutBox,r)&&sa(h=>{const x=l?s.measuredBox[h]:s.layoutBox[h],u=Rs(r[h]);x.max=x.min+u,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[h].max=t.relativeTarget[h].min+u)});const o=Ir();pn(o,r,s.layoutBox);const c=Ir();l?pn(c,t.applyTransform(n,!0),s.measuredBox):pn(c,r,s.layoutBox);const d=!rg(o);let m=!1;if(!t.resumeFrom){const h=t.getClosestProjectingParent();if(h&&!h.resumeFrom){const{snapshot:x,layout:u}=h;if(x&&u){const g=Zt();gn(g,s.layoutBox,x.layoutBox);const b=Zt();gn(b,r,u.layoutBox),ng(g,b)||(m=!0),h.options.layoutRoot&&(t.relativeTarget=b,t.relativeTargetOrigin=g,t.relativeParent=h)}}}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 Y2(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 K2(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function X2(t){t.clearSnapshot()}function Du(t){t.clearMeasurements()}function Pu(t){t.isLayoutDirty=!1}function Z2(t){const{visualElement:s}=t.options;s&&s.getProps().onBeforeLayoutMeasure&&s.notify("BeforeLayoutMeasure"),t.resetTransform()}function Iu(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function J2(t){t.resolveTargetDelta()}function Q2(t){t.calcProjection()}function q2(t){t.resetSkewAndRotation()}function eS(t){t.removeLeadSnapshot()}function Eu(t,s,a){t.translate=Wt(s.translate,0,a),t.scale=Wt(s.scale,1,a),t.origin=s.origin,t.originPoint=s.originPoint}function Fu(t,s,a,r){t.min=Wt(s.min,a.min,r),t.max=Wt(s.max,a.max,r)}function tS(t,s,a,r){Fu(t.x,s.x,a.x,r),Fu(t.y,s.y,a.y,r)}function sS(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const aS={duration:.45,ease:[.4,0,.1,1]},_u=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),Lu=_u("applewebkit/")&&!_u("chrome/")?Math.round:ia;function Mu(t){t.min=Lu(t.min),t.max=Lu(t.max)}function rS(t){Mu(t.x),Mu(t.y)}function og(t,s,a){return t==="position"||t==="preserve-aspect"&&!d2(ku(s),ku(a),.2)}function nS(t){var s;return t!==t.root&&((s=t.scroll)==null?void 0:s.wasRoot)}const iS=lg({attachResizeListener:(t,s)=>Cn(t,"resize",s),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),jl={current:void 0},cg=lg({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!jl.current){const t=new iS({});t.mount(window),t.setOptions({layoutScroll:!0}),jl.current=t}return jl.current},resetTransform:(t,s)=>{t.style.transform=s!==void 0?s:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),lS={pan:{Feature:S2},drag:{Feature:C2,ProjectionNode:cg,MeasureLayout:tg}};function $u(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&&Ot.postRender(()=>i(s,_n(s)))}class oS extends qa{mount(){const{current:s}=this.node;s&&(this.unmount=R1(s,(a,r)=>($u(this.node,r,"Start"),n=>$u(this.node,n,"End"))))}unmount(){}}class cS extends qa{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=In(Cn(this.node.current,"focus",()=>this.onFocus()),Cn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Ou(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&&Ot.postRender(()=>i(s,_n(s)))}class dS extends qa{mount(){const{current:s}=this.node;s&&(this.unmount=E1(s,(a,r)=>(Ou(this.node,r,"Start"),(n,{success:i})=>Ou(this.node,n,i?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const io=new WeakMap,Nl=new WeakMap,mS=t=>{const s=io.get(t.target);s&&s(t)},uS=t=>{t.forEach(mS)};function xS({root:t,...s}){const a=t||document;Nl.has(a)||Nl.set(a,{});const r=Nl.get(a),n=JSON.stringify(s);return r[n]||(r[n]=new IntersectionObserver(uS,{root:t,...s})),r[n]}function hS(t,s,a){const r=xS(s);return io.set(t,a),r.observe(t),()=>{io.delete(t),r.unobserve(t)}}const pS={some:0,all:1};class gS extends qa{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:pS[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:h}=this.node.getProps(),x=d?m:h;x&&x(c)};return hS(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(fS(s,a))&&this.startObserver()}unmount(){}}function fS({viewport:t={}},{viewport:s={}}={}){return a=>t[a]!==s[a]}const bS={inView:{Feature:gS},tap:{Feature:dS},focus:{Feature:cS},hover:{Feature:oS}},yS={layout:{ProjectionNode:cg,MeasureLayout:tg}},vS={...r2,...bS,...lS,...yS},is=vC(vS,EC),nn=[{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:Yt,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"],disabled:!1},{id:"vendor-payment",name:"Vendor Payment",description:"Streamlined vendor payment approval with PO validation and financial controls",category:"Finance",icon:kx,color:"from-green-500 to-emerald-600",estimatedTime:"3-5 days",steps:5,features:["PO matching","Invoice verification","Multi-level approvals","Payment scheduling"],disabled:!0,comingSoon:!0}];function jS({open:t,onClose:s,onSelectTemplate:a}){var d,m,h;const[r,n]=p.useState(null),[i,l]=p.useState(!1);p.useEffect(()=>{const x=st.getUserData();l((x==null?void 0:x.jobTitle)==="Dealer")},[]);const o=x=>{if(i)return;const u=nn.find(g=>g.id===x);u!=null&&u.disabled||n(x)},c=()=>{r&&(a(r),s())};return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(dt,{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(mt,{className:"sr-only",children:"Select a Template"}),e.jsx(Pt,{className:"sr-only",children:"Choose from pre-configured templates with predefined workflows and approval chains for faster processing."}),e.jsx("button",{onClick:s,className:"!flex absolute top-6 left-6 z-50 w-10 h-10 rounded-full bg-white shadow-lg hover:shadow-xl border border-gray-200 items-center justify-center transition-all hover:scale-110","aria-label":"Go back",children:e.jsx(Cs,{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(is.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(Tx,{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:nn.map((x,u)=>{const g=x.icon,b=r===x.id,f=i||x.disabled;return e.jsx(is.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:u*.1},whileHover:f?{}:{scale:1.03},whileTap:f?{}:{scale:.98},children:e.jsxs(se,{className:`h-full transition-all duration-300 border-2 ${f?"opacity-50 cursor-not-allowed border-gray-200":b?"cursor-pointer border-blue-500 shadow-xl bg-blue-50/50 ring-2 ring-blue-200":"cursor-pointer border-gray-200 hover:border-blue-300 hover:shadow-lg"}`,onClick:()=>o(x.id),children:[e.jsxs(ge,{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 ${x.color} flex items-center justify-center shadow-md`,children:e.jsx(g,{className:"w-7 h-7 text-white"})}),b&&e.jsx(is.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(Ra,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsx(fe,{className:"text-xl mb-2",children:x.name}),e.jsx(Ue,{className:"text-sm leading-relaxed",children:x.description}),i&&e.jsxs("div",{className:"mt-3 flex items-start gap-2 p-2 bg-amber-50 border border-amber-200 rounded-lg",children:[e.jsx(Ye,{className:"w-4 h-4 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-xs text-amber-800",children:"Not accessible for Dealers"})]}),x.comingSoon&&!i&&e.jsxs("div",{className:"mt-3 flex items-start gap-2 p-2 bg-blue-50 border border-blue-200 rounded-lg",children:[e.jsx(Ye,{className:"w-4 h-4 text-blue-600 flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-xs text-blue-800 font-semibold",children:"Coming Soon"})]})]})]}),e.jsxs(ae,{className:"pt-0 space-y-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(oe,{variant:"secondary",className:"text-xs",children:x.category})}),e.jsx(Ps,{}),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(nt,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:x.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:[x.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:[x.features.slice(0,3).map((y,v)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-600",children:[e.jsx(Re,{className:"w-3 h-3 text-green-600 flex-shrink-0"}),e.jsx("span",{children:y})]},v)),x.features.length>3&&e.jsxs("p",{className:"text-xs text-blue-600 italic pl-5",children:["+",x.features.length-3," more features"]})]})]})]})]})},x.id)})}),e.jsxs(is.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(F,{variant:"outline",onClick:s,size:"lg",className:"px-8",children:"Cancel"}),e.jsxs(F,{onClick:c,disabled:!r||i||((d=nn.find(x=>x.id===r))==null?void 0:d.disabled),size:"lg",className:`gap-2 px-8 ${r&&!i&&!((m=nn.find(x=>x.id===r))!=null&&m.disabled)?"bg-blue-600 hover:bg-blue-700":"bg-gray-400 cursor-not-allowed"}`,children:["Continue with Template",e.jsx(ls,{className:"w-4 h-4"})]})]}),e.jsx(_i,{children:r&&e.jsx(is.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:(h=nn.find(x=>x.id===r))==null?void 0:h.name})]})})})]})})]})})}function Nr({fileName:t,fileType:s,fileUrl:a,fileSize:r,attachmentId:n,onDownload:i,open:l,onClose:o}){const[c,d]=p.useState(100),[m,h]=p.useState(0),[x,u]=p.useState(null),[g,b]=p.useState(!1),[f,y]=p.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"),C=s.toLowerCase().includes("pdf"),w=v||C;p.useEffect(()=>{if(!l||!w||!a){u(null);return}return(async()=>{b(!0),y(null);try{let P=a;a.startsWith("/")&&!a.startsWith("//")&&(P=`${window.location.origin}${a}`);const k=await fetch(P,{headers:{Accept:C?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!k.ok){const D=await k.text().catch(()=>"");throw new Error(`Failed to load file: ${k.status} ${k.statusText}. ${D}`)}const L=await k.blob();if(L.size===0)throw new Error("File is empty or could not be loaded");C&&!L.type.includes("pdf")&&L.type!=="application/octet-stream"&&console.warn(`Expected PDF but got ${L.type}`);const V=window.URL.createObjectURL(L);u(V)}catch(j){console.error("Failed to load file for preview:",j),y(j instanceof Error?j.message:"Failed to load file for preview")}finally{b(!1)}})(),()=>{x&&(window.URL.revokeObjectURL(x),u(null))}},[l,a,w,C]);const A=async()=>{if(i&&n)try{await i(n)}catch{alert("Failed to download file")}},N=()=>d(R=>Math.min(R+25,200)),_=()=>d(R=>Math.max(R-25,50)),T=()=>h(R=>(R+90)%360);return e.jsx(ht,{open:l,onOpenChange:o,children:e.jsx(dt,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(pt,{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(mt,{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(F,{variant:"ghost",size:"sm",onClick:_,disabled:c<=50,title:"Zoom out",className:"h-8 w-8 p-0",children:e.jsx($f,{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(F,{variant:"ghost",size:"sm",onClick:N,disabled:c>=200,title:"Zoom in",className:"h-8 w-8 p-0",children:e.jsx(Of,{className:"h-4 w-4"})}),e.jsx(F,{variant:"ghost",size:"sm",onClick:T,title:"Rotate",className:"h-8 w-8 p-0",children:e.jsx(Rx,{className:"h-4 w-4"})})]}),i&&n&&e.jsxs(F,{variant:"outline",size:"sm",onClick:A,className:"gap-2 h-9",children:[e.jsx(At,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Download"})]})]})]})}),e.jsx("div",{className:"file-preview-body bg-gray-100 rounded-lg p-2 sm:p-4",children:g?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full",children:[e.jsx(it,{className:"w-12 h-12 text-blue-600 animate-spin mb-4"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Loading preview..."})]}):f?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-red-100 rounded-full flex items-center justify-center mb-4",children:e.jsx(ft,{className:"w-10 h-10 text-red-600"})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Preview Failed"}),e.jsx("p",{className:"text-sm text-gray-600 mb-6",children:f}),i&&n&&e.jsxs(F,{onClick:A,className:"gap-2",children:[e.jsx(At,{className:"h-4 w-4"}),"Download ",t]})]}):w&&x?e.jsxs(e.Fragment,{children:[v&&e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("img",{src:x,alt:t,style:{transform:`scale(${c/100}) rotate(${m}deg)`,transition:"transform 0.2s ease-in-out",maxWidth:"100%",maxHeight:"100%",objectFit:"contain"},className:"rounded-lg shadow-lg"})}),C&&e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("iframe",{src:x,className:"w-full h-full rounded-lg border-0",title:t,style:{minHeight:"70vh",height:"100%"},onError:()=>{y("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(F,{onClick:A,className:"gap-2",children:[e.jsx(At,{className:"h-4 w-4"}),"Download ",t]})]})})]})})})}function Ln({open:t,onClose:s,violations:a,policyDetails:r}){return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-lg",children:[e.jsxs(pt,{children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(Ye,{className:"w-5 h-5 text-red-600"}),"Policy Violation"]}),e.jsx(Pt,{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(Rt,{children:e.jsx(F,{onClick:s,className:"w-full sm:w-auto",children:"OK"})})]})})}const Qs=async t=>{const s=t?{category:t}:{};return(await ve.get("/users/configurations",{params:s})).data.data},NS=async t=>{const s={};return(await ve.get("/admin/configurations",{params:s})).data.data},wS=async(t,s)=>{await ve.put(`/admin/configurations/${t}`,{configValue:s})},CS=async t=>{await ve.post(`/admin/configurations/${t}/reset`)},SS=async t=>{const s=t?{year:t}:{};return(await ve.get("/admin/holidays",{params:s})).data.data},AS=async t=>(await ve.post("/admin/holidays",t)).data.data,TS=async(t,s)=>(await ve.put(`/admin/holidays/${t}`,s)).data.data,kS=async t=>{await ve.delete(`/admin/holidays/${t}`)},RS=async()=>(await ve.get("/config/activity-types")).data.data,DS=async t=>{const s={activeOnly:t.toString()};return(await ve.get("/admin/activity-types",{params:s})).data.data},PS=async t=>(await ve.post("/admin/activity-types",t)).data.data,IS=async(t,s)=>(await ve.put(`/admin/activity-types/${t}`,s)).data.data,ES=async t=>{await ve.delete(`/admin/activity-types/${t}`)},FS={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 _S(t,s,a){const[r,n]=p.useState(FS),[i,l]=p.useState(null),[o,c]=p.useState(t),[d,m]=p.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[h,x]=p.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[u,g]=p.useState([]);return p.useEffect(()=>{(async()=>{var y;try{const v=await Qs("DOCUMENT_POLICY"),C={};v.forEach(E=>{C[E.configKey]=E.configValue});const w=parseInt(C.MAX_FILE_SIZE_MB||"10"),N=(C.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(E=>E.trim().toLowerCase());x({maxFileSizeMB:w,allowedFileTypes:N});const _=await Qs("SYSTEM_SETTINGS"),T=await Qs("WORKFLOW_SHARING"),R=[..._,...T],j={};R.forEach(E=>{j[E.configKey]=E.configValue}),m({maxApprovalLevels:parseInt(j.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(j.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((y=j.ALLOW_ADD_SPECTATOR)==null?void 0:y.toLowerCase())==="true",maxSpectators:parseInt(j.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(v){console.error("Failed to load policies:",v)}})()},[]),p.useEffect(()=>{if(!t||!s)return;let f=!0;return(async()=>{try{c(!0);const y=await Ts(s);if(!f||!y)return;const v=y.workflow||{},C=Array.isArray(y.approvals)?y.approvals:[],w=Array.isArray(y.participants)?y.participants:[],A=Array.isArray(y.documents)?y.documents.filter(P=>!P.isDeleted):[];g(A);const N=(v.priority||"").toString().toLowerCase(),_={standard:"standard",express:"express"},T=v.templateType==="TEMPLATE"?"existing-template":"custom",R=a.find(P=>P.id===T)||a[0]||null;l(R);const j=C.sort((P,B)=>(P.levelNumber||0)-(B.levelNumber||0)).map(P=>{const B=Number(P.tatHours||24),k=Math.floor(B/24),L=B%24;return{id:P.approverId||`temp-${P.levelNumber}`,name:P.approverName||P.approverEmail||"",email:P.approverEmail||"",role:P.levelName||`Level ${P.levelNumber}`,department:"",avatar:(P.approverName||P.approverEmail||"XX").substring(0,2).toUpperCase(),level:P.levelNumber||1,canClose:!1,tat:k>0?k:L,tatType:k>0?"days":"hours",userId:P.approverId}}),E=w.filter(P=>(P.participantType||P.participant_type||"").toString().toUpperCase().trim()==="SPECTATOR"?!!(P.userEmail||P.user_email||P.email):!1).map((P,B)=>{const k=P.userId||P.user_id||P.id,L=P.userName||P.user_name||P.name||"",V=P.userEmail||P.user_email||P.email||"",S=(L||V||"XX").split(" ").map(O=>O[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{id:k||`spectator-${s}-${B}-${Date.now()}`,userId:k,name:L||V||"Spectator",email:V,role:"Spectator",department:P.department||"",avatar:S,level:1,canClose:!1}});n(P=>({...P,template:T,title:v.title||"",description:v.description||"",priority:_[N]||"standard",approvers:j,approverCount:j.length||1,spectators:E,maxLevel:Math.max(...j.map(B=>B.level||1),1)}))}catch(y){console.error("Failed to load draft:",y)}finally{f&&c(!1)}})(),()=>{f=!1}},[t,s,a]),{formData:r,setFormData:n,updateFormData:(f,y)=>{n(v=>({...v,[f]:y}))},selectedTemplate:i,setSelectedTemplate:l,loadingDraft:o,systemPolicy:d,documentPolicy:h,existingDocuments:u,setExistingDocuments:g}}const Uu=["Template Selection","Basic Information","Approval Workflow","Participants & Access","Documents & Attachments","Review & Submit"];function LS(t,s,a){const[r,n]=p.useState(t?2:1),i=Uu.length,l=h=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(h),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(h=>{if(!h||!h.email||!l(h.email))return!1;if(!h.userId)return!0;const x=h.tatType||"hours";return x==="hours"?h.tat&&h.tat>0&&h.tat<=720:x==="days"?h.tat&&h.tat>0&&h.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:Uu,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:h=>{h>=1&&h<=i&&n(h)},validateEmail:l}}function MS(){const[t,s]=p.useState({open:!1,type:"error",email:"",message:""}),[a,r]=p.useState({open:!1,violations:[]}),[n,i]=p.useState({open:!1,errors:[]});return{validationModal:t,policyViolationModal:a,documentErrorModal:n,openValidationModal:(x,u,g="")=>{s({open:!0,type:x,email:u,message:g})},closeValidationModal:()=>{s(x=>({...x,open:!1}))},openPolicyViolationModal:x=>{r({open:!0,violations:x})},closePolicyViolationModal:()=>{r({open:!1,violations:[]})},openDocumentErrorModal:x=>{i({open:!0,errors:x})},closeDocumentErrorModal:()=>{i({open:!1,errors:[]})}}}function $S(t,s){const a=typeof t=="number"?t:parseInt(String(t))||0;return s==="days"?a*24:a||24}function OS(t,s,a){var n;const r=$S(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 US(t,s){return t.slice(0,s).map((a,r)=>{const n=r+1;return OS(a,n,n===s)})}function Bu(t,s,a,r=!1){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(n=>({userId:(n==null?void 0:n.userId)||"",email:(n==null?void 0:n.email)||"",name:n==null?void 0:n.name,tat:(n==null?void 0:n.tat)||24,tatType:(n==null?void 0:n.tatType)||"hours"})),spectators:(t.spectators||[]).map(n=>({userId:(n==null?void 0:n.userId)||"",name:(n==null?void 0:n.name)||"",email:(n==null?void 0:n.email)||""})),ccList:[],participants:[],isDraft:r}}function Vu(t,s,a,r=!1){const n=US(t.approvers||[],t.approverCount||1);return{title:t.title,description:t.description,priority:t.priority==="express"?"EXPRESS":"STANDARD",approvalLevels:n,participants:[],deleteDocumentIds:a.length>0?a:void 0,isDraft:r}}function BS(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 zu(t,s){return{id:(await _o(t,s||[],"SUPPORTING")).id}}async function Hu(t,s,a,r){const n=a&&a.length>0,i=r.length>0;n||i?await RN(t,s,a||[],r):await kN(t,s)}function VS({formData:t,selectedTemplate:s,documents:a,documentsToDelete:r,user:n,isEditing:i,editRequestId:l,onSubmit:o}){const[c,d]=p.useState(!1),[m,h]=p.useState(!1);return{submitting:c,savingDraft:m,handleSubmit:async()=>{var b,f;if(c||m)return;const g=BS(t.approvers||[],t.approverCount||1);if(!g.valid){alert(g.message);return}d(!0);try{if(i&&l){const y=Vu(t,n,r,!1);await Hu(l,y,a,r),K.success("Request Submitted Successfully!",{description:`Your request "${t.title}" has been submitted and sent for approval.`,duration:5e3}),o==null||o({...t,backendId:l,template:s})}else{const y=Bu(t,s,n,!1),v=await zu(y,a);K.success("Request Submitted Successfully!",{description:`Your request "${t.title}" has been created and sent for approval.`,duration:5e3}),o==null||o({...t,backendId:v.id,template:s})}}catch(y){console.error("Failed to submit workflow:",y),K.error("Failed to Submit Request",{description:((f=(b=y==null?void 0:y.response)==null?void 0:b.data)==null?void 0:f.message)||(y==null?void 0:y.message)||"An error occurred while submitting the request.",duration:5e3}),d(!1)}},handleSaveDraft:async()=>{var g,b;if(!(!s||!t.title.trim()||!t.description.trim()||!t.priority)&&!(c||m)){h(!0);try{if(i&&l){const f=Vu(t,n,r,!0);await Hu(l,f,a,r),K.success("Draft Saved Successfully!",{description:`Your request "${t.title}" has been saved as draft.`,duration:5e3}),o==null||o({...t,backendId:l,template:s})}else{const f=Bu(t,s,n,!0),y=await zu(f,a);K.success("Draft Saved Successfully!",{description:`Your request "${t.title}" has been saved as draft.`,duration:5e3}),o==null||o({...t,backendId:y.id,template:s})}}catch(f){console.error("Failed to save draft:",f),K.error("Failed to Save Draft",{description:((b=(g=f==null?void 0:f.response)==null?void 0:g.data)==null?void 0:b.message)||(f==null?void 0:f.message)||"An error occurred while saving the draft.",duration:5e3}),h(!1)}}}}}async function ca(t,s=10,a="default"){return await ve.get("/users/search",{params:{q:t,limit:s,source:a}})}async function la(t){var a;const s=await ve.post("/users/ensure",t);return((a=s.data)==null?void 0:a.data)||s.data}async function zS(t,s){return await ve.post("/admin/users/assign-role",{email:t,role:s})}async function HS(t,s){return await ve.put(`/admin/users/${t}/role`,{role:s})}async function GS(t,s=1,a=10){return await ve.get("/admin/users/by-role",{params:{role:t||"ELEVATED",page:s,limit:a}})}async function WS(){return await ve.get("/admin/users/role-statistics")}async function YS(t){var a;const s=await ve.get(`/users/${t}`);return((a=s.data)==null?void 0:a.data)||s.data}async function KS(){var s,a;return((a=(s=(await ve.get("/users")).data)==null?void 0:s.data)==null?void 0:a.users)||[]}const ur={searchUsers:ca,getUserById:YS,ensureUserExists:la,assignRole:zS,updateUserRole:HS,getUsersByRole:GS,getRoleStatistics:WS,getAllUsers:KS};async function XS(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 ca(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 la({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 ZS(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 XS(l,s);if(!o.success)return{success:!1,error:o.error};try{const m=(((n=(await ca(l.email,1)).data)==null?void 0:n.data)||[])[0];if(m){const h=await la({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:h.userId,name:h.displayName||l.name,department:h.department||l.department,avatar:(h.displayName||h.email).substring(0,2).toUpperCase()}}}catch(c){console.error(`Failed to update approver ${l.email}:`,c)}}return{success:!0,validatedApprovers:r}}function JS({selectedTemplate:t,setSelectedTemplate:s,updateFormData:a,formData:r,currentStep:n,isStepValid:i,wizardNextStep:l,wizardPrevStep:o,user:c,openValidationModal:d,systemPolicy:m,onPolicyViolation:h,onSubmit:x}){const u=Fs(),[g,b]=p.useState(!1),[f,y]=p.useState(null);return{showTemplateModal:g,setShowTemplateModal:b,previewDocument:f,selectTemplate:T=>{s(T),a("template",T.id),a("category",T.category),a("priority",T.priority);const R=new Date;R.setDate(R.getDate()+T.suggestedSLA),a("slaEndDate",R),T.id!=="custom"&&T.id!=="existing-template"&&u(`/create-admin-request/${T.id}`)},handleTemplateSelection:T=>{T==="claim-management"?u("/claim-management"):T==="vendor-payment"?u("/vendor-payment"):x&&x({templateType:T})},nextStep:async()=>{var T;if(i()){if(n===1&&(t==null?void 0:t.id)==="existing-template"){b(!0);return}if(window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}),n===3){if(m&&h){const E=r.approverCount||1;if(E>m.maxApprovalLevels){h([{type:"Maximum Approval Levels Exceeded",message:`The request has ${E} approval levels, which exceeds the maximum allowed (${m.maxApprovalLevels}). Please reduce the number of approvers.`,currentValue:E,maxValue:m.maxApprovalLevels}]);return}}const R=((T=c==null?void 0:c.email)==null?void 0:T.toLowerCase())||"",j=await ZS(r.approvers,R);if(!j.success&&j.error){d(j.error.type,j.error.email,j.error.message);return}j.validatedApprovers&&a("approvers",j.validatedApprovers)}l()}},prevStep:()=>{o(),window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"})},handlePreviewDocument:(T,R)=>{if(R){const j=T.documentId||T.document_id||"";y({fileName:T.originalFileName||T.fileName||"Document",fileType:T.fileType||T.file_type||"application/octet-stream",fileUrl:Kr(j),fileSize:Number(T.fileSize||T.file_size||0),documentId:j})}else{const j=URL.createObjectURL(T);y({fileName:T.name,fileType:T.type||"application/octet-stream",fileUrl:j,fileSize:T.size,file:T})}},closePreview:()=>{f!=null&&f.fileUrl&&(f!=null&&f.file)&&URL.revokeObjectURL(f.fileUrl),y(null)}}}const Gu=[{id:"custom",name:"Non-Templatized",description:"Create a custom request for unique business needs with full flexibility to define your own workflow and requirements",category:"General",icon:wi,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:ke,estimatedTime:"1-2 days",commonApprovers:["Department Head","Manager"],suggestedSLA:2,priority:"medium",fields:{timeline:!0}}];let vr=null;const Wu=()=>vr,QS=async t=>{const a=(await ve.post("/templates",t)).data.data,r={id:a.templateId||a.id,name:a.templateName||a.name,description:a.templateDescription||a.description,category:a.templateCategory||a.category,priority:a.priority||"medium",estimatedTime:a.estimatedTime||"Variable",approvers:a.approvalLevelsConfig||a.approvers||[],suggestedSLA:a.defaultTatHours||a.suggestedSLA||24,isActive:a.isActive,fields:a.userFieldMappings||a.fields};return vr&&vr.push(r),r},Oi=async()=>{var r;const a=(((r=(await ve.get("/templates")).data)==null?void 0:r.data)||[]).map(n=>({id:n.templateId||n.id,name:n.templateName||n.name,description:n.templateDescription||n.description,category:n.templateCategory||n.category,priority:n.priority||"medium",estimatedTime:n.estimatedTime||"Variable",approvers:n.approvalLevelsConfig||n.approvers||[],suggestedSLA:n.defaultTatHours||n.suggestedSLA||24,isActive:n.isActive,fields:n.userFieldMappings||n.fields}));return vr=a,a},qS=async(t,s)=>{const r=(await ve.put(`/templates/${t}`,s)).data.data,n={id:r.templateId||r.id,name:r.templateName||r.name,description:r.templateDescription||r.description,category:r.templateCategory||r.category,priority:r.priority||"medium",estimatedTime:r.estimatedTime||"Variable",approvers:r.approvalLevelsConfig||r.approvers||[],suggestedSLA:r.defaultTatHours||r.suggestedSLA||24,isActive:r.isActive,fields:r.userFieldMappings||r.fields};return vr&&(vr=vr.map(i=>i.id===t?n:i)),n};function dg({currentStep:t,totalSteps:s,stepNames:a}){const r=Math.round(t/s*100),n=a.length<=3?"max-w-xl":"max-w-6xl";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:`${n} 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-center gap-4 mb-2","data-testid":"wizard-stepper-desktop-steps",children:a.map((i,l)=>e.jsxs("div",{className:"flex items-center flex-1 last:flex-none","data-testid":`wizard-stepper-desktop-step-${l+1}`,children:[e.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center text-xs font-semibold flex-shrink-0 ${l+1<t?"bg-green-500 text-white":l+1===t?"bg-green-500 text-white ring-2 ring-green-500/30 ring-offset-1":"bg-gray-200 text-gray-600"}`,"data-testid":`wizard-stepper-desktop-step-${l+1}-indicator`,children:l+1<t?e.jsx(Ra,{className:"w-4 h-4"}):l+1}),l<a.length-1&&e.jsx("div",{className:`flex-1 h-0.5 mx-2 ${l+1<t?"bg-green-500":"bg-gray-200"}`,"data-testid":`wizard-stepper-desktop-step-${l+1}-connector`})]},l))}),e.jsx("div",{className:"hidden lg:flex justify-between text-xs text-gray-600 mt-2 px-1","data-testid":"wizard-stepper-desktop-labels",children:a.map((i,l)=>e.jsx("span",{className:`${l+1===t?"font-semibold text-green-600":""}`,"data-testid":`wizard-stepper-desktop-label-${l+1}`,children:i},l))})]})]})})}function eA({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(F,{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(Cs,{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(F,{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(it,{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(F,{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(it,{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(Dx,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),"Submit"]})}):e.jsxs(F,{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(ls,{className:"h-3 w-3 sm:h-4 sm:w-4 ml-1 sm:ml-2"})]})]})]})})}const Yu=t=>{switch(t){case"high":return e.jsx(fa,{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(na,{className:"w-4 h-4 text-green-600"});default:return e.jsx(Bt,{className:"w-4 h-4 text-gray-600"})}};function tA({templates:t,selectedTemplate:s,onSelectTemplate:a,adminTemplates:r=[]}){var d;const[n,i]=p.useState("main"),l=Fs(),o=m=>{m.id==="admin-templates-category"?i("admin"):n==="admin"?l(`/create-admin-request/${m.id}`):a(m)},c=n==="main"?[...t]:r;return e.jsxs(is.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:n==="main"?"Choose Your Request Type":"Organization Templates"}),e.jsx("p",{className:"text-lg text-gray-600","data-testid":"template-selection-description",children:n==="main"?"Start with a pre-built template for faster approvals, or create a custom request tailored to your needs.":"Select a pre-configured workflow template defined by your organization."})]}),n==="admin"&&e.jsx("div",{className:"w-full max-w-6xl mb-6 flex justify-start",children:e.jsxs(F,{variant:"ghost",className:"gap-2",onClick:()=>i("main"),children:[e.jsx(Cs,{className:"w-4 h-4"}),"Back to All Types"]})}),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:c.length===0&&n==="admin"?e.jsxs("div",{className:"col-span-full text-center py-12 text-gray-500 bg-gray-50 rounded-lg border-2 border-dashed border-gray-200",children:[e.jsx(Uf,{className:"w-12 h-12 mx-auto mb-3 text-gray-300"}),e.jsx("p",{children:"No admin templates available yet."})]}):c.map(m=>{var g;const x=m.id==="admin-templates-category",u=(s==null?void 0:s.id)===m.id;return e.jsx(is.div,{whileHover:{scale:1.03},whileTap:{scale:.98},transition:{type:"spring",stiffness:300,damping:20},"data-testid":`template-card-${m.id}`,children:e.jsxs(se,{className:`h-full transition-all duration-300 border-2 ${u?"border-blue-500 shadow-xl bg-blue-50/50 ring-2 ring-blue-200 cursor-pointer":x?"border-blue-200 bg-blue-50/30 hover:border-blue-400 hover:shadow-lg cursor-pointer":"border-gray-200 hover:border-blue-300 hover:shadow-lg cursor-pointer"}`,onClick:()=>o(m),"data-testid":`template-card-${m.id}-clickable`,children:[e.jsxs(ge,{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 ${u||x?"bg-blue-100":"bg-gray-100"}`,"data-testid":`template-card-${m.id}-icon`,children:e.jsx(m.icon,{className:`w-7 h-7 ${u||x?"text-blue-600":"text-gray-600"}`})}),u&&e.jsx(is.div,{initial:{scale:0},animate:{scale:1},transition:{type:"spring",stiffness:500,damping:15},"data-testid":`template-card-${m.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(Ra,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-2",children:[e.jsx(fe,{className:"text-xl","data-testid":`template-card-${m.id}-name`,children:m.name}),!1]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oe,{variant:"secondary",className:"text-xs","data-testid":`template-card-${m.id}-category`,children:m.category}),Yu(m.priority)]})]})]}),e.jsxs(ae,{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-${m.id}-description`,children:m.description}),!x&&e.jsxs(e.Fragment,{children:[e.jsx(Ps,{}),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-${m.id}-estimated-time`,children:[e.jsx(nt,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:m.estimatedTime})]}),e.jsxs("div",{className:"flex items-center gap-1.5","data-testid":`template-card-${m.id}-approvers-count`,children:[e.jsx(ps,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[((g=m.commonApprovers)==null?void 0:g.length)||0," approvers"]})]})]})]}),x&&e.jsx("div",{className:"pt-2",children:e.jsx("p",{className:"text-xs text-blue-600 font-medium flex items-center gap-1",children:"Click to browse templates →"})})]})]})},m.id)})}),e.jsx(_i,{children:s&&e.jsx(is.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(se,{className:"bg-gradient-to-br from-blue-50 to-indigo-50 border-2 border-blue-200",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center gap-2 text-blue-900","data-testid":"template-details-title",children:[e.jsx(Hr,{className:"w-5 h-5"}),s.name," - Template Details"]})}),e.jsxs(ae,{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(ne,{className:"text-blue-900 font-semibold",children:"Suggested SLA"}),e.jsxs("p",{className:"text-blue-700 mt-1",children:[s.suggestedSLA," hours"]})]}),e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-priority",children:[e.jsx(ne,{className:"text-blue-900 font-semibold",children:"Priority Level"}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[Yu(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(ne,{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(ne,{className:"text-blue-900 font-semibold",children:"Approvers"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:((d=s.commonApprovers)==null?void 0:d.length)>0?s.commonApprovers.map((m,h)=>e.jsx(oe,{variant:"outline",className:"border-blue-300 text-blue-700 bg-white","data-testid":`template-details-approver-${h}`,children:m},`${s.id}-approver-${h}-${m}`)):e.jsx("span",{className:"text-sm text-gray-500 italic",children:"No specific approvers defined"})})]})]})]})})})]})}function Ie({className:t,type:s,...a}){return e.jsx("input",{type:s,"data-slot":"input",className:Ae("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 sA({className:t,...s}){return e.jsx(G0,{"data-slot":"radio-group",className:Ae("grid gap-3",t),...s})}function Ku({className:t,...s}){return e.jsx(W0,{"data-slot":"radio-group-item",className:Ae("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(Y0,{"data-slot":"radio-group-indicator",className:"relative flex items-center justify-center",children:e.jsx(Bf,{className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}function aA({formData:t,selectedTemplate:s,updateFormData:a}){return e.jsxs(is.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(ke,{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(ne,{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(Ie,{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(ne,{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(Pn,{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(ne,{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(sA,{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(Ku,{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(po,{className:"w-4 h-4 text-red-600"}),e.jsx(ne,{htmlFor:"express",className:"font-medium text-red-900 cursor-pointer",children:"Express"}),e.jsx(oe,{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(Ku,{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(nt,{className:"w-4 h-4 text-blue-600"}),e.jsx(ne,{htmlFor:"standard",className:"font-medium text-blue-900 cursor-pointer",children:"Standard"}),e.jsx(oe,{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(ne,{htmlFor:"amount",className:"text-base font-semibold",children:"Budget Amount"}),e.jsx(Ie,{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(ne,{className:"text-base font-semibold",children:"Currency"}),e.jsxs(Ke,{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(Xe,{})}),e.jsxs(Je,{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(ne,{htmlFor:"vendor",className:"text-base font-semibold",children:"Vendor/Supplier"}),e.jsx(Ie,{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(ne,{htmlFor:"costCenter",className:"text-base font-semibold",children:"Cost Center"}),e.jsx(Ie,{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(ne,{htmlFor:"project",className:"text-base font-semibold",children:"Related Project"}),e.jsx(Ie,{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 mg(){const[t,s]=p.useState([]),[a,r]=p.useState(!1),n=p.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 h=c.slice(1),u=((m=(await ca(h,d)).data)==null?void 0:m.data)||[];s(u)}catch(h){console.error("User search failed:",h),s([])}finally{r(!1)}},300)},clearSearch:()=>{n.current&&clearTimeout(n.current),s([]),r(!1)},ensureUser:async c=>{try{return await la({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 ug(){const[t,s]=p.useState({}),[a,r]=p.useState({}),n=p.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 h=c.slice(1),u=((m=(await ca(h,d)).data)==null?void 0:m.data)||[];s(g=>({...g,[o]:u}))}catch(h){console.error(`User search failed for index ${o}:`,h),s(x=>({...x,[o]:[]}))}finally{r(h=>({...h,[o]:!1}))}},300)},clearSearchForIndex:o=>{n.current[o]&&clearTimeout(n.current[o]),s(c=>({...c,[o]:[]})),r(c=>({...c,[o]:!1}))}}}function rA({formData:t,updateFormData:s,onValidationError:a,systemPolicy:r,onPolicyViolation:n}){var h;const{userSearchResults:i,userSearchLoading:l,searchUsersForIndex:o,clearSearchForIndex:c}=ug();p.useEffect(()=>{const x=t.approverCount||1,u=t.approvers||[];if(u.length<x){const g=[...u];for(let b=u.length;b<x;b++)g[b]||(g[b]={email:"",name:"",level:b+1,tat:""});s("approvers",g)}else u.length>x&&s("approvers",u.slice(0,x))},[t.approverCount,s]);const d=(x,u)=>{var y,v,C,w,A;const g=[...t.approvers],f=((y=g[x])==null?void 0:y.email)!==u;if(g[x]={...g[x],email:u,level:x+1,userId:f||(v=g[x])==null?void 0:v.userId,name:f||(C=g[x])==null?void 0:C.name,department:f||(w=g[x])==null?void 0:w.department,avatar:f||(A=g[x])==null?void 0:A.avatar},s("approvers",g),!u||!u.startsWith("@")||u.length<2){c(x);return}o(x,u,10)},m=async(x,u)=>{var g,b;try{if((g=t.approvers)==null?void 0:g.some((w,A)=>{var N,_;return A!==x&&(w.userId===u.userId||((N=w.email)==null?void 0:N.toLowerCase())===((_=u.email)==null?void 0:_.toLowerCase()))})){a({type:"error",email:u.email,message:"This user is already added as an approver in another level."});return}if((b=t.spectators)==null?void 0:b.some(w=>{var A,N;return w.userId===u.userId||((A=w.email)==null?void 0:A.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 v=await la({userId:u.userId,email:u.email,displayName:u.displayName,firstName:u.firstName,lastName:u.lastName,department:u.department,phone:u.phone,mobilePhone:u.mobilePhone,designation:u.designation,jobTitle:u.jobTitle,manager:u.manager,employeeId:u.employeeId,employeeNumber:u.employeeNumber,secondEmail:u.secondEmail,location:u.location}),C=[...t.approvers];C[x]={...C[x],email:u.email,name:u.displayName||[u.firstName,u.lastName].filter(Boolean).join(" "),userId:v.userId,level:x+1},s("approvers",C),c(x)}catch(f){console.error("Failed to ensure user exists:",f),a({type:"error",email:u.email,message:"Failed to validate user. Please try again."})}};return e.jsxs(is.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(ps,{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(se,{"data-testid":"approval-workflow-config-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"approval-workflow-config-title",children:[e.jsx(Ya,{className:"w-5 h-5"}),"Approval Configuration"]}),e.jsx(Ue,{children:"Configure how many approvers you need and define the approval sequence."})]}),e.jsx(ae,{className:"space-y-6",children:e.jsxs("div",{"data-testid":"approval-workflow-count-field",children:[e.jsx(ne,{className:"text-base font-semibold mb-4 block",children:"Number of Approvers *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(F,{type:"button",variant:"outline",size:"sm",onClick:()=>{const x=t.approverCount||1,u=Math.max(1,x-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(go,{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(F,{type:"button",variant:"outline",size:"sm",onClick:()=>{const u=(t.approverCount||1)+1;if(u>r.maxApprovalLevels){n([{type:"Maximum Approval Levels Exceeded",message:`Cannot add more than ${r.maxApprovalLevels} approval levels. Please remove an approver level or contact your administrator.`,currentValue:u,maxValue:r.maxApprovalLevels}]);return}s("approverCount",u)},disabled:(t.approverCount||1)>=r.maxApprovalLevels,"data-testid":"approval-workflow-increase-count",children:e.jsx(gs,{className:"w-4 h-4"})})]}),e.jsxs("p",{className:"text-sm text-gray-600 mt-2",children:["Maximum ",r.maxApprovalLevels," approver",r.maxApprovalLevels!==1?"s":""," allowed. Each approver will review sequentially."]})]})})]}),e.jsxs(se,{"data-testid":"approval-workflow-hierarchy-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"approval-workflow-hierarchy-title",children:[e.jsx(Ns,{className:"w-5 h-5"}),"Approval Hierarchy *"]}),e.jsxs(Ue,{children:["Define the approval sequence. Each approver will review the request in order from Level 1 to Level ",t.approverCount||1,"."]})]}),e.jsxs(ae,{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(Gt,{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(oe,{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},(x,u)=>{var y,v;const g=u+1,b=g===(t.approverCount||1),f=t.approvers[u]||{email:"",tat:""};return e.jsxs("div",{className:"space-y-3","data-testid":`approval-workflow-approver-level-${g}`,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 ${f.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 ${f.email?"bg-green-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold",children:g})}),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 ",g]}),b&&e.jsx(oe,{variant:"destructive",className:"text-xs",children:"FINAL APPROVER"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{"data-testid":`approval-workflow-approver-${g}-email-field`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(ne,{htmlFor:`approver-${g}`,className:"text-sm font-medium",children:"Email Address *"}),f.email&&f.userId&&e.jsxs(oe,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(Re,{className:"w-3 h-3 mr-1"}),"Verified"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Ie,{id:`approver-${g}`,type:"email",placeholder:"approver@royalenfield.com",value:f.email||"",onChange:C=>d(u,C.target.value),className:"h-10 border-2 border-gray-300 focus:border-blue-500 mt-1 w-full","data-testid":`approval-workflow-approver-${g}-email-input`}),(l[u]||(((y=i[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:l[u]?e.jsx("div",{className:"p-2 text-xs text-gray-500",children:"Searching..."}):e.jsx("ul",{className:"max-h-56 overflow-auto divide-y",children:(v=i[u])==null?void 0:v.map(C=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>m(u,C),"data-testid":`approval-workflow-approver-${g}-search-result-${C.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:C.displayName||C.email}),e.jsx("div",{className:"text-xs text-gray-600",children:C.email})]},C.userId))})})]})]}),e.jsxs("div",{"data-testid":`approval-workflow-approver-${g}-tat-field`,children:[e.jsx(ne,{htmlFor:`tat-${g}`,className:"text-sm font-medium",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Ie,{id:`tat-${g}`,type:"number",placeholder:f.tatType==="days"?"7":"24",min:"1",max:f.tatType==="days"?"30":"720",value:f.tat||"",onChange:C=>{const w=[...t.approvers];w[u]={...w[u],tat:parseInt(C.target.value)||"",level:g,tatType:f.tatType||"hours"},s("approvers",w)},className:"h-10 border-2 border-gray-300 focus:border-blue-500 flex-1","data-testid":`approval-workflow-approver-${g}-tat-input`}),e.jsxs(Ke,{value:f.tatType||"hours",onValueChange:C=>{const w=[...t.approvers];w[u]={...w[u],tatType:C,level:g,tat:""},s("approvers",w)},"data-testid":`approval-workflow-approver-${g}-tat-type-select`,children:[e.jsx(Ze,{className:"w-20 h-10 border-2 border-gray-300",children:e.jsx(Xe,{})}),e.jsxs(Je,{children:[e.jsx(Y,{value:"hours",children:"Hours"}),e.jsx(Y,{value:"days",children:"Days"})]})]})]})]})]})]})]})})]},g)})]})]}),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(Hr,{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},(x,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(nt,{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 g;const x=((g=t.approvers)==null?void 0:g.reduce((b,f)=>{const y=Number(f.tat||0);return(f.tatType||"hours")==="days"?b+y:b+y/24},0))||0,u=Math.ceil(x);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:(h=t.approvers)==null?void 0:h.map((x,u)=>{const g=Number(x.tat||0),f=(x.tatType||"hours")==="days"?g*24:g;return g?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:[f," ",f===1?"hour":"hours"]})]})},u):null})}),(()=>{var g;const x=((g=t.approvers)==null?void 0:g.reduce((b,f)=>{const y=Number(f.tat||0);return(f.tatType||"hours")==="days"?b+y*24:b+y},0))||0,u=Math.ceil(x/8);return x===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:[x,"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 nA({formData:t,updateFormData:s,onValidationError:a,initiatorEmail:r}){const[n,i]=p.useState(""),{searchResults:l,searchLoading:o,searchUsersDebounced:c,clearSearch:d,ensureUser:m}=mg(),h=g=>{if(i(g),!g||!g.startsWith("@")||g.length<2){d();return}c(g,10)},x=async g=>{var b,f;if(g){if(g.email.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:g.email,message:"You cannot add yourself as a spectator."});return}const y=t.spectators.some(C=>{var w,A;return C.userId===g.userId||((w=C.email)==null?void 0:w.toLowerCase())===((A=g.email)==null?void 0:A.toLowerCase())}),v=(b=t.approvers)==null?void 0:b.some(C=>{var w,A;return C.userId===g.userId||((w=C.email)==null?void 0:w.toLowerCase())===((A=g.email)==null?void 0:A.toLowerCase())});if(y){a({type:"error",email:g.email,message:"This user is already added as a spectator."});return}if(v){a({type:"error",email:g.email,message:"This user is already added as an approver. A user cannot be both an approver and a spectator."});return}try{const C=await m(g),w={id:C.userId,userId:C.userId,name:C.displayName||g.email.split("@")[0],email:C.email,avatar:(C.displayName||C.email).substring(0,2).toUpperCase(),role:"Spectator",department:C.department||"",level:1,canClose:!1},A=[...t.spectators,w];s("spectators",A),i(""),d()}catch{a({type:"error",email:g.email,message:"Failed to validate user. Please try again."})}}else if(n&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)){if(n.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:n,message:"You cannot add yourself as a spectator."});return}const y=t.spectators.some(C=>{var w;return((w=C.email)==null?void 0:w.toLowerCase())===n.toLowerCase()}),v=(f=t.approvers)==null?void 0:f.some(C=>{var w;return((w=C.email)==null?void 0:w.toLowerCase())===n.toLowerCase()});if(y){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}}},u=g=>{const b=t.spectators.filter(f=>f.id!==g);s("spectators",b)};return e.jsxs(is.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(se,{"data-testid":"participants-spectators-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{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(oe,{variant:"outline",className:"text-xs","data-testid":"participants-spectators-count",children:t.spectators.length})]}),e.jsx(Ue,{children:"Users who can view and comment but cannot approve"})]}),e.jsxs(ae,{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(Ie,{placeholder:"Use @ sign to add a user",value:n,onChange:g=>h(g.target.value),onKeyPress:async g=>{g.key==="Enter"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)&&(g.preventDefault(),await x())},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(g=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>x(g),"data-testid":`participants-spectators-search-result-${g.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:g.displayName||g.email}),e.jsx("div",{className:"text-xs text-gray-600",children:g.email})]},g.userId))})})]}),e.jsx(F,{size:"sm",onClick:()=>x(),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(Hr,{className:"w-3 h-3 flex-shrink-0"}),e.jsxs("span",{children:["Use ",e.jsx("span",{className:"font-mono bg-blue-100 px-1 rounded",children:"@"})," sign to search users, or type email directly (will be validated against organization directory)"]})]})]}),e.jsx("div",{className:"space-y-2 max-h-40 overflow-y-auto","data-testid":"participants-spectators-list",children:t.spectators.map(g=>e.jsxs("div",{className:"flex items-center justify-between p-2 bg-teal-50 rounded-lg","data-testid":`participants-spectator-${g.id}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ts,{className:"h-6 w-6",children:e.jsx(ss,{className:"bg-teal-600 text-white text-xs",children:g.avatar})}),e.jsx("span",{className:"text-sm font-medium",children:g.name})]}),e.jsx(F,{variant:"ghost",size:"sm",onClick:()=>u(g.id),"data-testid":`participants-spectator-${g.id}-remove`,children:e.jsx(ft,{className:"h-3 w-3"})})]},g.id))})]})]})})})]})}function iA({documentPolicy:t,isEditing:s,documents:a,existingDocuments:r,documentsToDelete:n,onDocumentsChange:i,onExistingDocumentsChange:l,onDocumentsToDeleteChange:o,onPreviewDocument:c,onDocumentErrors:d,fileInputRef:m}){const h=b=>{const f=Array.from(b.target.files||[]);if(f.length===0)return;const y=t.maxFileSizeMB*1024*1024,v=[],C=[];f.forEach(w=>{if(w.size>y){v.push({fileName:w.name,reason:`File size exceeds the maximum allowed size of ${t.maxFileSizeMB}MB. Current size: ${(w.size/1048576).toFixed(2)}MB`});return}const A=w.name.toLowerCase(),N=A.substring(A.lastIndexOf(".")+1);if(!t.allowedFileTypes.includes(N)){v.push({fileName:w.name,reason:`File type "${N}" is not allowed. Allowed types: ${t.allowedFileTypes.join(", ")}`});return}C.push(w)}),C.length>0&&i([...a,...C]),v.length>0&&d&&d(v),b.target&&(b.target.value="")},x=b=>{const f=a.filter((y,v)=>v!==b);i(f)},u=b=>{o([...n,b])},g=(b,f=!1)=>{if(f){const y=(b.fileType||b.file_type||"").toLowerCase(),v=(b.originalFileName||b.fileName||"").toLowerCase();return y.includes("image")||y.includes("pdf")||v.endsWith(".jpg")||v.endsWith(".jpeg")||v.endsWith(".png")||v.endsWith(".gif")||v.endsWith(".pdf")}else{const y=(b.type||"").toLowerCase(),v=(b.name||"").toLowerCase();return y.includes("image")||y.includes("pdf")||v.endsWith(".jpg")||v.endsWith(".jpeg")||v.endsWith(".png")||v.endsWith(".gif")||v.endsWith(".pdf")}};return e.jsxs(is.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(Ks,{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(se,{"data-testid":"documents-upload-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"documents-upload-title",children:[e.jsx(ke,{className:"w-5 h-5"}),"File Upload"]}),e.jsxs(Ue,{children:["Attach supporting documents. Max ",t.maxFileSizeMB,"MB per file. Allowed types: ",t.allowedFileTypes.join(", ")]})]}),e.jsx(ae,{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(Ks,{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:"click to browse"}),e.jsx("input",{type:"file",multiple:!0,accept:t.allowedFileTypes.map(b=>`.${b}`).join(","),onChange:h,className:"hidden",id:"file-upload",ref:m,"data-testid":"documents-file-input"}),e.jsxs(F,{variant:"outline",size:"lg",type:"button",onClick:()=>{var b;return(b=m.current)==null?void 0:b.click()},"data-testid":"documents-browse-button",children:[e.jsx(gs,{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(b=>b.toUpperCase()).join(", ")," (Max ",t.maxFileSizeMB,"MB per file)"]})]})})]}),s&&r.length>0&&e.jsxs(se,{"data-testid":"documents-existing-card",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center justify-between","data-testid":"documents-existing-title",children:[e.jsx("span",{children:"Existing Documents"}),e.jsxs(oe,{variant:"secondary","data-testid":"documents-existing-count",children:[r.filter(b=>!n.includes(b.documentId||b.document_id||"")).length," file",r.filter(b=>!n.includes(b.documentId||b.document_id||"")).length!==1?"s":""]})]})}),e.jsx(ae,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-existing-list",children:r.map(b=>{const f=b.documentId||b.document_id||"";return n.includes(f)?null:e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border bg-gray-50","data-testid":`documents-existing-${f}`,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(ke,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:b.originalFileName||b.fileName||"Document"}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsx("span",{children:b.fileSize?(Number(b.fileSize)/(1024*1024)).toFixed(2)+" MB":"Unknown size"})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g(b,!0)&&e.jsx(F,{variant:"ghost",size:"sm",onClick:()=>c(b,!0),"data-testid":`documents-existing-${f}-preview`,children:e.jsx(bt,{className:"h-4 w-4"})}),e.jsx(F,{variant:"ghost",size:"sm",onClick:()=>u(f),"data-testid":`documents-existing-${f}-delete`,children:e.jsx(ft,{className:"h-4 w-4 text-red-600"})})]})]},f)})})})]}),a.length>0&&e.jsxs(se,{"data-testid":"documents-new-card",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center justify-between","data-testid":"documents-new-title",children:[e.jsx("span",{children:"New Files to Upload"}),e.jsxs(oe,{variant:"secondary","data-testid":"documents-new-count",children:[a.length," file",a.length!==1?"s":""]})]})}),e.jsx(ae,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-new-list",children:a.map((b,f)=>e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-lg border","data-testid":`documents-new-${f}`,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(ke,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:b.name}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsxs("span",{children:[(b.size/(1024*1024)).toFixed(2)," MB"]})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g(b,!1)&&e.jsx(F,{variant:"ghost",size:"sm",onClick:()=>c(b,!1),"data-testid":`documents-new-${f}-preview`,children:e.jsx(bt,{className:"h-4 w-4"})}),e.jsx(F,{variant:"ghost",size:"sm",onClick:()=>x(f),"data-testid":`documents-new-${f}-remove`,children:e.jsx(ft,{className:"h-4 w-4"})})]})]},f))})})]})]})]})}const lA=t=>{switch(t){case"high":return e.jsx(fa,{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(na,{className:"w-4 h-4 text-green-600"});default:return e.jsx(Bt,{className:"w-4 h-4 text-gray-600"})}};function oA({formData:t,selectedTemplate:s}){return e.jsxs(is.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(Re,{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(se,{className:"border-2 border-green-200 bg-green-50/50","data-testid":"review-submit-overview-card",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center gap-2 text-green-900","data-testid":"review-submit-overview-title",children:[e.jsx(Dx,{className:"w-5 h-5"}),"Request Overview"]})}),e.jsxs(ae,{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(ne,{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(oe,{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(ne,{className:"text-green-900 font-semibold",children:"Priority"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[lA(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(ne,{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(ne,{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(se,{"data-testid":"review-submit-basic-info-card",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"review-submit-basic-info-title",children:[e.jsx(ke,{className:"w-5 h-5"}),"Basic Information"]})}),e.jsxs(ae,{className:"space-y-4",children:[e.jsxs("div",{"data-testid":"review-submit-basic-info-description",children:[e.jsx(ne,{className:"font-semibold",children:"Description"}),e.jsx("div",{className:"mt-1 p-3 bg-gray-50 rounded-lg border",children:e.jsx(Bs,{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(ne,{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(se,{className:"border-2 border-orange-200 bg-orange-50/50","data-testid":"review-submit-approval-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2 text-orange-900","data-testid":"review-submit-approval-title",children:[e.jsx(ps,{className:"w-5 h-5"}),"Approval Workflow"]}),e.jsx(Ue,{className:"text-orange-700",children:"Sequential approval hierarchy with TAT (Turn Around Time) for each level"})]}),e.jsx(ae,{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(oe,{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(se,{"data-testid":"review-submit-participants-card",children:[e.jsx(ge,{children:e.jsxs(fe,{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(ae,{className:"space-y-4",children:t.spectators.length>0&&e.jsxs("div",{"data-testid":"review-submit-participants-spectators",children:[e.jsxs(ne,{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(oe,{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(se,{"data-testid":"review-submit-documents-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"review-submit-documents-title",children:[e.jsx(Ks,{className:"w-5 h-5"}),"Documents & Attachments"]}),e.jsxs(Ue,{children:[t.documents.length," document",t.documents.length!==1?"s":""," attached to this request"]})]}),e.jsx(ae,{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(ke,{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(se,{className:"border-2 border-blue-200 bg-blue-50/50","data-testid":"review-submit-confirmation-card",children:e.jsx(ae,{className:"pt-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(Re,{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 cA({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(F,{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(Cs,{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 dA({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(_i,{mode:"wait",children:t})})})}function mA({modal:t,onClose:s}){return e.jsx(ht,{open:t.open,onOpenChange:a=>!a&&s(),"data-testid":"create-request-validation-modal",children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(pt,{children:[e.jsxs(mt,{className:"flex items-center gap-2","data-testid":"validation-modal-title",children:[t.type==="self-assign"&&e.jsxs(e.Fragment,{children:[e.jsx(Ye,{className:"w-5 h-5 text-amber-600"}),"Cannot Add Yourself"]}),t.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsx(Ye,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}),t.type==="error"&&e.jsxs(e.Fragment,{children:[e.jsx(Ye,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})]}),e.jsx(Pt,{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(wi,{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(Rt,{children:e.jsx(F,{onClick:s,className:"w-full sm:w-auto","data-testid":"validation-modal-ok-button",children:t.type==="not-found"?"Fix Email":"OK"})})]})})}function uA({modal:t,documentPolicy:s,onClose:a}){return e.jsx(ht,{open:t.open,onOpenChange:r=>!r&&a(),"data-testid":"create-request-document-error-modal",children:e.jsxs(dt,{className:"sm:max-w-lg",children:[e.jsxs(pt,{children:[e.jsxs(mt,{className:"flex items-center gap-2","data-testid":"document-error-modal-title",children:[e.jsx(Ye,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Pt,{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(Rt,{children:e.jsx(F,{onClick:a,className:"w-full sm:w-auto","data-testid":"document-error-modal-ok-button",children:"OK"})})]})})}function Xu({onBack:t,onSubmit:s,requestId:a,isEditMode:r=!1}){const n=Fa(),i=Fs(),l=n.requestId||a||"",o=r&&!!l,{user:c}=Jt(),[d,m]=p.useState([]);p.useEffect(()=>{(async()=>{try{const Be=(await Oi()).map(Ee=>({id:Ee.id,name:Ee.name,description:Ee.description,category:Ee.category,icon:ke,estimatedTime:Ee.estimatedTime,commonApprovers:Ee.approvers.map(ze=>ze.name),workflowApprovers:Ee.approvers,suggestedSLA:Ee.suggestedSLA,priority:Ee.priority,fields:Ee.fields||{}}));m(Be)}catch(be){console.error("Failed to fetch admin templates:",be)}})()},[]);const h=p.useMemo(()=>[...Gu,...d],[d]),{formData:x,updateFormData:u,selectedTemplate:g,setSelectedTemplate:b,loadingDraft:f,systemPolicy:y,documentPolicy:v,existingDocuments:C,setExistingDocuments:w}=_S(o,l,h),{currentStep:A,totalSteps:N,stepNames:_,isStepValid:T,nextStep:R,prevStep:j}=LS(o,g,x),[E,P]=p.useState([]),[B,k]=p.useState([]),L=p.useRef(null),{validationModal:V,policyViolationModal:D,documentErrorModal:S,openValidationModal:O,closeValidationModal:I,openPolicyViolationModal:M,closePolicyViolationModal:W,openDocumentErrorModal:G,closeDocumentErrorModal:re}=MS(),{submitting:te,savingDraft:$,handleSubmit:z,handleSaveDraft:H}=VS({formData:x,selectedTemplate:g,documents:E,documentsToDelete:B,user:c,isEditing:o,editRequestId:l,onSubmit:s}),{showTemplateModal:je,setShowTemplateModal:le,previewDocument:ue,selectTemplate:$e,handleTemplateSelection:Te,nextStep:Ve,prevStep:Qe,handlePreviewDocument:Fe,closePreview:Q}=JS({selectedTemplate:g,setSelectedTemplate:b,updateFormData:u,formData:x,currentStep:A,isStepValid:T,wizardNextStep:R,wizardPrevStep:j,user:c,openValidationModal:O,systemPolicy:y,onPolicyViolation:M,onSubmit:s}),pe=p.useCallback(()=>{if(A===1){i("/dashboard",{replace:!0});return}A===3||A===4?t?t():window.history.length>1?window.history.back():i("/dashboard",{replace:!0}):Qe()},[A,t,i,Qe]),Ce=p.useRef(!0),Oe=p.useRef(!1);p.useEffect(()=>{Ce.current&&x.documents&&x.documents.length>0&&!Oe.current&&(P(x.documents),Oe.current=!0),Ce.current=!1},[x.documents]);const X=p.useRef(!1),Z=p.useRef(E);p.useEffect(()=>{if(X.current){X.current=!1,Z.current=E;return}Z.current!==E&&(u("documents",E),Z.current=E)},[E]);const me=()=>{switch(A){case 1:return e.jsx(tA,{templates:Gu,selectedTemplate:g,onSelectTemplate:$e,adminTemplates:d});case 2:return e.jsx(aA,{formData:x,selectedTemplate:g,updateFormData:u});case 3:return e.jsx(rA,{formData:x,updateFormData:u,systemPolicy:y,onValidationError:J=>O(J.type,J.email,J.message),onPolicyViolation:M});case 4:return e.jsx(nA,{formData:x,updateFormData:u,onValidationError:J=>O(J.type,J.email,J.message),initiatorEmail:(c==null?void 0:c.email)||""});case 5:return e.jsx(iA,{documentPolicy:v,isEditing:o,documents:E,existingDocuments:C,documentsToDelete:B,onDocumentsChange:P,onExistingDocumentsChange:w,onDocumentsToDeleteChange:k,onPreviewDocument:Fe,onDocumentErrors:J=>G(J),fileInputRef:L});case 6:return e.jsx(oA,{formData:x,selectedTemplate:g});default:return null}};return f?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(cA,{isEditing:o,currentStep:A,totalSteps:N,stepNames:_,onBack:pe}),e.jsx(dg,{currentStep:A,totalSteps:N,stepNames:_}),e.jsx(dA,{children:me()}),e.jsx(eA,{currentStep:A,totalSteps:N,isStepValid:T(),onPrev:Qe,onNext:Ve,onSubmit:z,onSaveDraft:H,submitting:te,savingDraft:$,loadingDraft:f,isEditing:o}),e.jsx(jS,{open:je,onClose:()=>le(!1),onSelectTemplate:Te}),ue&&e.jsx(Nr,{fileName:ue.fileName,fileType:ue.fileType,fileUrl:ue.fileUrl,fileSize:ue.fileSize,open:!!ue,onClose:Q,onDownload:async()=>{if(ue.file){const J=document.createElement("a");J.href=ue.fileUrl,J.download=ue.fileName,document.body.appendChild(J),J.click(),document.body.removeChild(J)}else ue.documentId&&await ws(ue.documentId)},attachmentId:ue.documentId}),e.jsx(mA,{modal:V,onClose:I}),e.jsx(uA,{modal:S,documentPolicy:v,onClose:re}),e.jsx(Ln,{open:D.open,onClose:W,violations:D.violations,policyDetails:{maxApprovalLevels:y.maxApprovalLevels,maxParticipants:y.maxParticipants,allowSpectators:y.allowSpectators,maxSpectators:y.maxSpectators}})]})}function Ui({className:t,...s}){return e.jsx(K0,{"data-slot":"tabs",className:Ae("flex flex-col gap-2",t),...s})}function Bi({className:t,...s}){return e.jsx(X0,{"data-slot":"tabs-list",className:Ae("bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-xl p-[3px] flex",t),...s})}function rs({className:t,...s}){return e.jsx(Z0,{"data-slot":"tabs-trigger",className:Ae("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 ns({className:t,...s}){return e.jsx(J0,{"data-slot":"tabs-content",className:Ae("flex-1 outline-none",t),...s})}function fc(t,s=[],a){const[r,n]=p.useState(null),[i,l]=p.useState(!1),[o,c]=p.useState(!0),[d,m]=p.useState(null),[h,x]=p.useState(null),[u,g]=p.useState(!1),b=(A,N)=>(A||N||"NA").toString().split(" ").map(T=>T[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),f=A=>{const N=(A||"").toUpperCase();return N==="IN_PROGRESS"?"in-review":N==="PENDING"?"pending":N==="APPROVED"?"approved":N==="REJECTED"?"rejected":N==="CLOSED"?"closed":N==="SKIPPED"?"skipped":(A||"").toLowerCase()},y=p.useCallback(async()=>{var A,N,_,T,R,j,E,P,B,k,L,V,D;l(!0);try{const S=await Is.getWorkflowDetails(t);if(!S){console.warn("[useRequestDetails] No details returned from API");return}const O=S.workflow||{},I=Array.isArray(S.approvals)?S.approvals:[],M=Array.isArray(S.participants)?S.participants:[],W=Array.isArray(S.documents)?S.documents:[],G=S.summary||{},re=Array.isArray(S.tatAlerts)?S.tatAlerts:[];re.length>0;const te=(G==null?void 0:G.currentLevel)||O.currentLevel||1,$=I.map(X=>{const Z=X.levelNumber||0,me=(X.status||"").toString().toUpperCase(),J=X.levelId||X.level_id;let be=f(X.status);Z>te&&me!=="APPROVED"&&me!=="REJECTED"?be="waiting":Z===te&&me==="PENDING"&&(be="pending");const Be=re.filter(Ee=>Ee.levelId===J);return{step:Z,levelId:J,role:X.levelName||X.approverName||"Approver",status:be,approver:X.approverName||X.approverEmail,approverId:X.approverId||X.approver_id,approverEmail:X.approverEmail,tatHours:Number(X.tatHours||0),elapsedHours:Number(X.elapsedHours||0),remainingHours:Number(X.remainingHours||0),tatPercentageUsed:Number(X.tatPercentageUsed||0),actualHours:X.levelEndTime&&X.levelStartTime?Math.max(0,(new Date(X.levelEndTime).getTime()-new Date(X.levelStartTime).getTime())/(1e3*60*60)):void 0,comment:X.comments||void 0,timestamp:X.actionDate||void 0,levelStartTime:X.levelStartTime||X.tatStartTime,tatAlerts:Be,skipReason:X.skipReason||void 0,isSkipped:me==="SKIPPED"||X.isSkipped||!1}}),z=M.filter(X=>(X.participantType||X.participant_type||"").toUpperCase()==="SPECTATOR").map(X=>({name:X.userName||X.user_name||X.userEmail||X.user_email,role:"Spectator",email:X.userEmail||X.user_email,avatar:b(X.userName||X.user_name,X.userEmail||X.user_email)})),H=X=>{var me,J;if(!X)return;const Z=M.find(be=>be.userId===X||be.user_id===X);return Z!=null&&Z.userName||Z!=null&&Z.user_name?Z.userName||Z.user_name:O.initiatorId===X?((me=O.initiator)==null?void 0:me.displayName)||((J=O.initiator)==null?void 0:J.email):X},je=W.map(X=>{const Z=Number(X.fileSize||X.file_size||0),me=(Z/(1024*1024)).toFixed(2)+" MB";return{documentId:X.documentId||X.document_id,name:X.originalFileName||X.fileName||X.file_name,fileType:X.fileType||X.file_type||"",size:me,sizeBytes:Z,uploadedBy:H(X.uploadedBy||X.uploaded_by),uploadedAt:X.uploadedAt||X.uploaded_at}}),le=Array.isArray(S.activities)?S.activities.filter(X=>(X.type||"").toLowerCase()!=="sla_warning"):[];let ue=null;if(O.isPaused||!1)try{ue=await Cm(O.requestId)}catch{}let Te=null,Ve=null,Qe=null,Fe=null;if(O.workflowType==="CLAIM_MANAGEMENT"||O.templateType==="claim-management")try{const X=await ve.get(`/dealer-claims/${O.requestId}`),Z=((A=X.data)==null?void 0:A.data)||X.data;if(Z){Te=Z.claimDetails||Z.claim_details,Ve=Z.proposalDetails||Z.proposal_details,Qe=Z.completionDetails||Z.completion_details,Fe=Z.internalOrder||Z.internal_order||null;const me=Z.budgetTracking||Z.budget_tracking||null,J=Z.invoice||null,be=Z.creditNote||Z.credit_note||null,Be=Z.completionExpenses||Z.completion_expenses||null;Te&&(Te.budgetTracking=me,Te.invoice=J,Te.creditNote=be,Te.completionExpenses=Be)}else console.warn("[useRequestDetails] No claimData found in response")}catch(X){console.error("[useRequestDetails] Error fetching claim details:",{error:(X==null?void 0:X.message)||X,status:(N=X==null?void 0:X.response)==null?void 0:N.status,statusText:(_=X==null?void 0:X.response)==null?void 0:_.statusText,responseData:(T=X==null?void 0:X.response)==null?void 0:T.data,requestId:O.requestId})}const Q={...O,id:O.requestNumber||O.requestId,requestId:O.requestId,requestNumber:O.requestNumber,title:O.title,description:O.description,status:f(O.status),priority:(O.priority||"").toString().toLowerCase(),workflowType:O.workflowType||(O.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),approvalFlow:$,approvals:I,participants:M,documents:je,spectators:z,summary:G,sla:(G==null?void 0:G.sla)||O.sla||null,initiator:{name:((R=O.initiator)==null?void 0:R.displayName)||((j=O.initiator)==null?void 0:j.email),role:((E=O.initiator)==null?void 0:E.designation)||void 0,department:((P=O.initiator)==null?void 0:P.department)||void 0,email:((B=O.initiator)==null?void 0:B.email)||void 0,phone:((k=O.initiator)==null?void 0:k.phone)||void 0,avatar:b((L=O.initiator)==null?void 0:L.displayName,(V=O.initiator)==null?void 0:V.email)},createdAt:O.createdAt,updatedAt:O.updatedAt,totalSteps:O.totalLevels||1,currentStepRaw:(G==null?void 0:G.currentLevel)||O.currentLevel||1,currentStep:Math.min(Math.max(1,(G==null?void 0:G.currentLevel)||O.currentLevel||1),O.totalLevels||1),auditTrail:le,conclusionRemark:O.conclusionRemark||null,closureDate:O.closureDate||null,pauseInfo:ue||null,claimDetails:Te||null,proposalDetails:Ve||null,completionDetails:Qe||null,internalOrder:Fe||null,budgetTracking:(Te==null?void 0:Te.budgetTracking)||null,invoice:(Te==null?void 0:Te.invoice)||null,creditNote:(Te==null?void 0:Te.creditNote)||null,completionExpenses:(Te==null?void 0:Te.completionExpenses)||null};n(Q);const pe=(D=a==null?void 0:a.email)==null?void 0:D.toLowerCase(),Ce=I.find(X=>{const Z=(X.status||"").toString().toUpperCase(),me=(X.approverEmail||"").toLowerCase(),J=X.levelNumber||0;return(Z==="PENDING"||Z==="IN_PROGRESS"||Z==="PAUSED")&&me===pe&&J===te});x(Ce||null);const Oe=a==null?void 0:a.userId;if(Oe){const X=M.some(Z=>(Z.participantType||Z.participant_type||"").toUpperCase()==="SPECTATOR"&&(Z.userId||Z.user_id)===Oe);g(X)}else g(!1)}catch(S){console.error("[useRequestDetails] Error refreshing details:",S),alert("Failed to refresh request details. Please try again.")}finally{l(!1)}},[t,a]);p.useEffect(()=>{if(!t){c(!1);return}let A=!0;return c(!0),m(null),(async()=>{var N,_,T,R,j,E,P,B,k,L,V,D,S,O;try{const I=await Is.getWorkflowDetails(t);if(!A||!I){A&&c(!1);return}const M=I.workflow||{},W=Array.isArray(I.approvals)?I.approvals:[],G=Array.isArray(I.participants)?I.participants:[],re=Array.isArray(I.documents)?I.documents:[],te=I.summary||{},$=Array.isArray(I.tatAlerts)?I.tatAlerts:[],z=(M.priority||"").toString().toLowerCase(),H=(te==null?void 0:te.currentLevel)||M.currentLevel||1,je=W.map(J=>{const be=J.levelNumber||0,Be=(J.status||"").toString().toUpperCase(),Ee=J.levelId||J.level_id;let ze=f(J.status);Be==="PAUSED"?ze="paused":be>H&&Be!=="APPROVED"&&Be!=="REJECTED"?ze="waiting":be===H&&(Be==="PENDING"||Be==="IN_PROGRESS")&&(ze=Be==="IN_PROGRESS"?"in-review":"pending");const vt=$.filter(ut=>ut.levelId===Ee);return{step:be,levelId:Ee,role:J.levelName||J.approverName||"Approver",status:ze,approver:J.approverName||J.approverEmail,approverId:J.approverId||J.approver_id,approverEmail:J.approverEmail,tatHours:Number(J.tatHours||0),elapsedHours:Number(J.elapsedHours||0),remainingHours:Number(J.remainingHours||0),tatPercentageUsed:Number(J.tatPercentageUsed||0),actualHours:J.elapsedHours!==void 0&&J.elapsedHours!==null?Number(J.elapsedHours):void 0,comment:J.comments||void 0,timestamp:J.actionDate||void 0,levelStartTime:J.levelStartTime||J.tatStartTime,tatAlerts:vt}}),le=G.filter(J=>(J.participantType||"").toUpperCase()==="SPECTATOR").map(J=>({name:J.userName||J.userEmail,role:"Spectator",avatar:b(J.userName,J.userEmail)})),ue=J=>{var Be,Ee;if(!J)return;const be=G.find(ze=>ze.userId===J);return be!=null&&be.userName?be.userName:M.initiatorId===J?((Be=M.initiator)==null?void 0:Be.displayName)||((Ee=M.initiator)==null?void 0:Ee.email):J},$e=re.map(J=>{const be=Number(J.fileSize||0),Be=(be/(1024*1024)).toFixed(2)+" MB";return{documentId:J.documentId||J.document_id,name:J.originalFileName||J.fileName,fileType:J.fileType||J.file_type||"",size:Be,sizeBytes:be,uploadedBy:ue(J.uploadedBy),uploadedAt:J.uploadedAt}}),Te=Array.isArray(I.activities)?I.activities.filter(J=>(J.type||"").toLowerCase()!=="sla_warning"):[];let Ve=null;if(M.isPaused||!1)try{Ve=await Cm(M.requestId)}catch{}let Fe=null,Q=null,pe=null,Ce=null;if(M.workflowType==="CLAIM_MANAGEMENT"||M.templateType==="claim-management")try{const J=await ve.get(`/dealer-claims/${M.requestId}`),be=((N=J.data)==null?void 0:N.data)||J.data;if(be){Fe=be.claimDetails||be.claim_details,Q=be.proposalDetails||be.proposal_details,pe=be.completionDetails||be.completion_details,Ce=be.internalOrder||be.internal_order||null;const Be=be.budgetTracking||be.budget_tracking||null,Ee=be.invoice||null,ze=be.creditNote||be.credit_note||null,vt=be.completionExpenses||be.completion_expenses||null;Fe&&(Fe.budgetTracking=Be,Fe.invoice=Ee,Fe.creditNote=ze,Fe.completionExpenses=vt)}}catch(J){console.error("[useRequestDetails] Initial load - Error fetching claim details:",{error:(J==null?void 0:J.message)||J,status:(_=J==null?void 0:J.response)==null?void 0:_.status,requestId:M.requestId})}const Oe={id:M.requestNumber||M.requestId,requestId:M.requestId,title:M.title,description:M.description,priority:z,status:f(M.status),workflowType:M.workflowType||(M.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),summary:te,initiator:{name:((T=M.initiator)==null?void 0:T.displayName)||((R=M.initiator)==null?void 0:R.email),role:((j=M.initiator)==null?void 0:j.designation)||void 0,department:((E=M.initiator)==null?void 0:E.department)||void 0,email:((P=M.initiator)==null?void 0:P.email)||void 0,phone:((B=M.initiator)==null?void 0:B.phone)||void 0,avatar:b((k=M.initiator)==null?void 0:k.displayName,(L=M.initiator)==null?void 0:L.email)},createdAt:M.createdAt,updatedAt:M.updatedAt,totalSteps:M.totalLevels||1,currentStepRaw:(te==null?void 0:te.currentLevel)||M.currentLevel||1,currentStep:Math.min(Math.max(1,(te==null?void 0:te.currentLevel)||M.currentLevel||1),M.totalLevels||1),approvalFlow:je,approvals:W,documents:$e,spectators:le,auditTrail:Te,conclusionRemark:M.conclusionRemark||null,closureDate:M.closureDate||null,pauseInfo:Ve||null,claimDetails:Fe||null,proposalDetails:Q||null,completionDetails:pe||null,internalOrder:Ce||null,budgetTracking:(Fe==null?void 0:Fe.budgetTracking)||null,invoice:(Fe==null?void 0:Fe.invoice)||null,creditNote:(Fe==null?void 0:Fe.creditNote)||null,completionExpenses:(Fe==null?void 0:Fe.completionExpenses)||null};n(Oe);const X=(V=a==null?void 0:a.email)==null?void 0:V.toLowerCase(),Z=W.find(J=>{const be=(J.status||"").toString().toUpperCase(),Be=(J.approverEmail||"").toLowerCase(),Ee=J.levelNumber||0;return(be==="PENDING"||be==="IN_PROGRESS"||be==="PAUSED")&&Be===X&&Ee===H});x(Z||null);const me=a==null?void 0:a.userId;if(me){const J=G.some(be=>(be.participantType||"").toUpperCase()==="SPECTATOR"&&be.userId===me);g(J)}else g(!1)}catch(I){if(console.error("[useRequestDetails] Error loading request details:",I),A){if(((D=I==null?void 0:I.response)==null?void 0:D.status)===403){const M=((O=(S=I==null?void 0:I.response)==null?void 0:S.data)==null?void 0:O.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:M})}n(null)}}finally{A&&c(!1)}})(),()=>{A=!1}},[t,a]);const v=p.useMemo(()=>{if(r)return r;const A=s.find(N=>N.id===t||N.requestNumber===t||N.request_number===t);return A||null},[t,s,r]),C=p.useMemo(()=>{var _,T,R;if(!v||!a)return!1;const A=(_=a==null?void 0:a.email)==null?void 0:_.toLowerCase(),N=(R=(T=v.initiator)==null?void 0:T.email)==null?void 0:R.toLowerCase();return A===N},[v,a]),w=p.useMemo(()=>{var N;if(!v)return[];const A=[];return(N=v.initiator)!=null&&N.email&&A.push({email:v.initiator.email.toLowerCase(),participantType:"INITIATOR",name:v.initiator.name}),v.approvalFlow&&Array.isArray(v.approvalFlow)&&v.approvalFlow.forEach(_=>{_.approverEmail&&A.push({email:_.approverEmail.toLowerCase(),participantType:"APPROVER",name:_.approver})}),v.spectators&&Array.isArray(v.spectators)&&v.spectators.forEach(_=>{_.email&&A.push({email:_.email.toLowerCase(),participantType:"SPECTATOR",name:_.name})}),v.participants&&Array.isArray(v.participants)&&v.participants.forEach(_=>{const T=(_.userEmail||_.email||"").toLowerCase(),R=(_.participantType||_.participant_type||"").toUpperCase(),j=_.userName||_.user_name||_.name;T&&R&&!A.find(E=>E.email===T)&&A.push({email:T,participantType:R,name:j})}),A},[v]);return p.useEffect(()=>{if(!t||!r)return;const A=Or();if(!A)return;const N=_=>{((_==null?void 0:_.requestId)===r.requestId||(_==null?void 0:_.requestNumber)===t)&&y()};return A.on("request:updated",N),()=>{A.off("request:updated",N)}},[t,r,y]),{request:v,apiRequest:r,loading:o,refreshing:i,refreshDetails:y,currentApprovalLevel:h,isSpectator:u,isInitiator:C,existingParticipants:w,accessDenied:d}}function xg(t,s,a,r){const[n,i]=p.useState([]),[l,o]=p.useState(0),[c,d]=p.useState([]);return p.useEffect(()=>{if(!t){console.warn("[useRequestSocket] No requestIdentifier, cannot join socket room");return}let m=!0,h=t;return(async()=>{var b;try{const f=await Is.getWorkflowDetails(t);(b=f==null?void 0:f.workflow)!=null&&b.requestId&&m&&(h=f.workflow.requestId)}catch(f){console.error("[useRequestSocket] Failed to resolve UUID:",f)}if(!m)return;const x=Or();if(!x){console.error("[useRequestSocket] Socket not available");return}const u=r==null?void 0:r.userId,g=()=>{Ol(x,h,u)};return x.connected?g():x.on("connect",g),()=>{m&&(x.off("connect",g),lh(x,h))}})(),()=>{m=!1}},[t,r]),p.useEffect(()=>{!t||!s||(async()=>{try{const m=await Mr(t),h=s.auditTrail||[],x=[...m,...h];x.sort((u,g)=>{const b=new Date(u.createdAt||u.created_at||u.timestamp||0).getTime(),f=new Date(g.createdAt||g.created_at||g.timestamp||0).getTime();return b-f}),i(x)}catch(m){console.error("[useRequestSocket] Failed to fetch and merge messages:",m)}})()},[t,s]),p.useEffect(()=>{if(!t)return;const m=Or();if(!m)return;const h=u=>{a!=="worknotes"&&o(g=>g+1),(async()=>{try{const g=await Mr(t),b=(s==null?void 0:s.auditTrail)||[],f=[...g,...b].sort((y,v)=>{const C=new Date(y.createdAt||y.created_at||y.timestamp||0).getTime(),w=new Date(v.createdAt||v.created_at||v.timestamp||0).getTime();return C-w});i(f)}catch(g){console.error("[useRequestSocket] Failed to refresh messages:",g)}})()},x=u=>{const g=u.type==="breach"?"⏰":u.type==="threshold2"?"⚠️":"⏳";(async()=>{try{const b=await Is.getWorkflowDetails(t);b&&(Array.isArray(b.tatAlerts)&&b.tatAlerts,"Notification"in window&&Notification.permission==="granted"&&new Notification(`${g} TAT Alert`,{body:u.message,icon:"/favicon.ico",tag:`tat-${u.requestId}-${u.type}`,requireInteraction:!1}))}catch(b){console.error("[useRequestSocket] Failed to refresh after TAT alert:",b)}})()};return m.on("noteHandler",h),m.on("worknote:new",h),m.on("tat:alert",x),()=>{m.off("noteHandler",h),m.off("worknote:new",h),m.off("tat:alert",x)}},[t,a,s]),p.useEffect(()=>{a==="worknotes"&&o(0)},[a]),{mergedMessages:n,unreadWorkNotes:l,workNoteAttachments:c,setWorkNoteAttachments:d}}async function dn(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 ve.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}}const xA=["MALWARE_DETECTED","FILE_VALIDATION_FAILED","CONTENT_THREAT_DETECTED","SCAN_UNAVAILABLE","SCAN_ERROR"],hA={MALWARE_DETECTED:"🛑 Malware Detected",FILE_VALIDATION_FAILED:"⛔ File Rejected",CONTENT_THREAT_DETECTED:"⚠️ Malicious Content Detected",SCAN_UNAVAILABLE:"🔒 Security Scan Unavailable",SCAN_ERROR:"❌ Security Scan Error"};function bc(t){var l,o,c,d;const s=(l=t==null?void 0:t.response)==null?void 0:l.data;if(!(s!=null&&s.error))return!1;const a=s.error;if(!xA.includes(a))return!1;const r=hA[a]||"Security Error",n=s.message||"File was blocked by security scan";let i="";return s.details&&((o=s.details.signatures)!=null&&o.length?i=`Virus: ${s.details.signatures.join(", ")}`:(c=s.details.errors)!=null&&c.length?i=s.details.errors[0]||"":(d=s.details.threats)!=null&&d.length&&(i=s.details.threats.map(m=>m.description).join(", "))),K.error(r,{description:i||n,duration:8e3,style:{background:"#fef2f2",border:"1px solid #fca5a5",color:"#991b1b"}}),!0}function hg(t,s){const[a,r]=p.useState(!1),[n,i]=p.useState(null),[l,o]=p.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[c,d]=p.useState({show:!1,errors:[]});p.useEffect(()=>{(async()=>{try{const g=await Qs("DOCUMENT_POLICY"),b={};g.forEach(C=>{b[C.configKey]=C.configValue});const f=parseInt(b.MAX_FILE_SIZE_MB||"10"),v=(b.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(C=>C.trim().toLowerCase());o({maxFileSizeMB:f,allowedFileTypes:v})}catch(g){console.error("Failed to load document policy:",g)}})()},[]);const m=u=>{const g=l.maxFileSizeMB*1024*1024;if(u.size>g)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${l.maxFileSizeMB}MB. Current size: ${(u.size/(1024*1024)).toFixed(2)}MB`};const b=u.name.toLowerCase(),f=b.substring(b.lastIndexOf(".")+1);return l.allowedFileTypes.includes(f)?{valid:!0}:{valid:!1,reason:`File type "${f}" is not allowed. Allowed types: ${l.allowedFileTypes.join(", ")}`}},h=async u=>{var v,C;const g=u.target.files;if(!g||g.length===0)return;const b=Array.from(g),f=[],y=[];if(b.forEach(w=>{const A=m(w);A.valid?y.push(w):f.push({fileName:w.name,reason:A.reason||"Unknown validation error"})}),f.length>0&&d({show:!0,errors:f}),y.length===0){u.target&&(u.target.value="");return}r(!0);try{const w=y[0],A=t==null?void 0:t.requestId;if(!A){K.error("Request ID not found");return}w&&await dn(w,A,"SUPPORTING"),await s(),y.length<b.length?K.warning(`${y.length} of ${b.length} file(s) were uploaded. ${f.length} file(s) were rejected.`):K.success("Document uploaded successfully")}catch(w){console.error("[useDocumentUpload] Upload error:",w),bc(w)||K.error(((C=(v=w==null?void 0:w.response)==null?void 0:v.data)==null?void 0:C.message)||"Failed to upload document")}finally{r(!1),u.target&&(u.target.value="")}};return{uploadingDocument:a,handleDocumentUpload:h,triggerFileInput:()=>{const u=document.createElement("input");u.type="file",u.accept=l.allowedFileTypes.map(g=>`.${g}`).join(","),u.onchange=h,u.click()},previewDocument:n,setPreviewDocument:i,documentPolicy:l,documentError:c,setDocumentError:d}}const pA="modulepreload",gA=function(t){return"/"+t},Zu={},wl=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=gA(c),c in Zu)return;Zu[c]=!0;const d=c.endsWith(".css"),m=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${m}`))return;const h=document.createElement("link");if(h.rel=d?"stylesheet":pA,d||(h.as="script"),h.crossOrigin="",h.href=c,o&&h.setAttribute("nonce",o),document.head.appendChild(h),d)return new Promise((x,u)=>{h.addEventListener("load",x),h.addEventListener("error",()=>u(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)})};function pg(t,s,a,r,n,i,l){const[o,c]=p.useState(""),[d,m]=p.useState(!1),[h,x]=p.useState(!1),[u,g]=p.useState(!1),[b,f]=p.useState(0),[y,v]=p.useState(!1),[C,w]=p.useState(!1),[A,N]=p.useState(0),_=async()=>{var P;const j=(t==null?void 0:t.conclusionRemark)||(t==null?void 0:t.conclusion_remark),E=(t==null?void 0:t.aiGeneratedConclusion)||(t==null?void 0:t.ai_generated_conclusion);if(j||E){c(j||E),g(!!E);return}try{const{getConclusion:B}=await wl(async()=>{const{getConclusion:L}=await import("./conclusionApi-Nd172SfW.js");return{getConclusion:L}},__vite__mapDeps([0,1,2,3,4,5,6,7])),k=await B(t.requestId||s);k&&(k.aiGeneratedRemark||k.finalRemark)&&(c(k.finalRemark||k.aiGeneratedRemark||""),g(!!k.aiGeneratedRemark))}catch(B){((P=B==null?void 0:B.response)==null?void 0:P.status)!==404&&console.error("[useConclusionRemark] Error fetching conclusion:",B)}},T=async()=>{if(!C)try{m(!0),v(!1);const{generateConclusion:j}=await wl(async()=>{const{generateConclusion:k}=await import("./conclusionApi-Nd172SfW.js");return{generateConclusion:k}},__vite__mapDeps([0,1,2,3,4,5,6,7])),E=await j(t.requestId||s),P=b+1;if(f(P),!(E!=null&&E.aiGeneratedRemark)||E.aiGeneratedRemark.toLowerCase().includes("unable to generate")||E.aiGeneratedRemark.toLowerCase().includes("sorry")){const k=A+1;N(k),k>=2?(w(!0),i==null||i({success:!1,title:"AI Generation Limit Reached",message:"We're unable to process a conclusion remark at this time after 2 attempts. Please proceed with a manual approach using the editor below."})):i==null||i({success:!1,title:"System Note",message:"We're unable to process a conclusion remark at the moment. You have one more attempt remaining, or you can proceed manually."}),l==null||l(!0),c((E==null?void 0:E.aiGeneratedRemark)||""),g(!1);return}c(E.aiGeneratedRemark),g(!0),N(0),P>=2&&(w(!0),i==null||i({success:!0,title:"Maximum Attempts Reached",message:"You've reached the maximum of 2 regeneration attempts. Feel free to manually edit the current suggestion to fit your specific needs."}),l==null||l(!0))}catch(j){console.error("[useConclusionRemark] AI generation failed:",j);const E=A+1;N(E),g(!1),E>=2?(w(!0),i==null||i({success:!1,title:"System Note",message:"We're unable to process your request at the moment. Since the maximum of 2 attempts is reached, please proceed with a manual approach."})):i==null||i({success:!1,title:"System Note",message:"We're unable to process your request at the moment. You have one more attempt remaining, or you can proceed manually."}),l==null||l(!0)}finally{m(!1)}},R=async()=>{var E,P;const j=o.replace(/<[^>]*>/g,"").trim();if(!j){i==null||i({success:!1,title:"Validation Error",message:"Conclusion remark cannot be empty"}),l==null||l(!0);return}if(j.length>2e3){i==null||i({success:!1,title:"Validation Error",message:"Conclusion remark exceeds 2000 characters limit"}),l==null||l(!0);return}try{x(!0);const{finalizeConclusion:B}=await wl(async()=>{const{finalizeConclusion:k}=await import("./conclusionApi-Nd172SfW.js");return{finalizeConclusion:k}},__vite__mapDeps([0,1,2,3,4,5,6,7]));await B(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(B){i==null||i({success:!1,title:"Error",message:((P=(E=B.response)==null?void 0:E.data)==null?void 0:P.error)||"Failed to finalize conclusion"}),l==null||l(!0)}finally{x(!1)}};return p.useEffect(()=>{var k;const j=(k=t==null?void 0:t.status)==null?void 0:k.toLowerCase();if(!((j==="approved"||j==="rejected"||j==="closed")&&a&&!o))return;const P=(t==null?void 0:t.conclusionRemark)||(t==null?void 0:t.conclusion_remark),B=(t==null?void 0:t.aiGeneratedConclusion)||(t==null?void 0:t.ai_generated_conclusion);P||B?(c(P||B),g(!!B)):_()},[t==null?void 0:t.status,t==null?void 0:t.conclusionRemark,t==null?void 0:t.aiGeneratedConclusion,a,o]),{conclusionRemark:o,setConclusionRemark:c,conclusionLoading:d,conclusionSubmitting:h,aiGenerated:u,handleGenerateConclusion:T,handleFinalizeConclusion:R,generationAttempts:b,generationFailed:y,maxAttemptsReached:C}}function gg(t,s,a){const[r,n]=p.useState(!1),[i,l]=p.useState(!1),[o,c]=p.useState(!1),[d,m]=p.useState(!1),[h,x]=p.useState(!1),[u,g]=p.useState(!1),[b,f]=p.useState(null),[y,v]=p.useState(null);return{showApproveModal:r,setShowApproveModal:n,showRejectModal:i,setShowRejectModal:l,showAddApproverModal:o,setShowAddApproverModal:c,showAddSpectatorModal:d,setShowAddSpectatorModal:m,showSkipApproverModal:h,setShowSkipApproverModal:x,showActionStatusModal:u,setShowActionStatusModal:g,skipApproverData:b,setSkipApproverData:f,actionStatus:y,setActionStatus:v,handleApproveConfirm:async T=>{var j,E;const R=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!R){alert("Approval level not found");return}await on(t,R,T||""),await new Promise(P=>setTimeout(P,500)),await a(),(j=window==null?void 0:window.closeModal)==null||j.call(window),(E=window==null?void 0:window.toast)==null||E.call(window,"Approved successfully")},handleRejectConfirm:async T=>{var j,E;if(!(T!=null&&T.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 Tr(t,R,T.trim(),T.trim()),await a(),(j=window==null?void 0:window.closeModal)==null||j.call(window),(E=window==null?void 0:window.toast)==null||E.call(window,"Rejected successfully")},handleAddApprover:async(T,R,j)=>{var E,P;try{await wh(t,T,R,j),await a(),c(!1),v==null||v({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${j} with ${R}h TAT`}),g==null||g(!0)}catch(B){throw v==null||v({success:!1,title:"Failed to Add Approver",message:((P=(E=B==null?void 0:B.response)==null?void 0:E.data)==null?void 0:P.error)||"Failed to add approver. Please try again."}),g==null||g(!0),B}},handleSkipApprover:async T=>{var R,j;if(b)try{await wN(t,b.levelId,T),await a(),x(!1),f(null),v==null||v({success:!0,title:"Approver Skipped",message:"Approver skipped successfully. The workflow has moved to the next level."}),g==null||g(!0)}catch(E){throw v==null||v({success:!1,title:"Failed to Skip Approver",message:((j=(R=E==null?void 0:E.response)==null?void 0:R.data)==null?void 0:j.error)||"Failed to skip approver. Please try again."}),g==null||g(!0),E}},handleAddSpectator:async T=>{var R,j;try{await Ch(t,T),await a(),m(!1),v==null||v({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),g==null||g(!0)}catch(E){throw v==null||v({success:!1,title:"Failed to Add Spectator",message:((j=(R=E==null?void 0:E.response)==null?void 0:R.data)==null?void 0:j.error)||"Failed to add spectator. Please try again."}),g==null||g(!0),E}}}}const fA=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 Vr({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(ke,{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&&e.jsxs("span",{children:[t.size," • "]}),t.uploadedBy&&e.jsxs("span",{children:["Uploaded by ",t.uploadedBy," on "]}),as(t.uploadedAt)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&fA(t.fileType)&&s&&e.jsx(F,{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(F,{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(At,{className:"w-4 h-4"})})]})]})}function bA({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(se,{children:[e.jsx(ge,{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(fe,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(ke,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Documents"]}),e.jsx(Ue,{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(F,{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(Ks,{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(ae,{children:t.documents&&t.documents.length>0?e.jsx("div",{className:"space-y-3",children:t.documents.map((o,c)=>e.jsx(Vr,{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(se,{children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Ds,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"Work Note Attachments"]}),e.jsx(Ue,{className:"text-xs sm:text-sm",children:"Files shared in work notes discussions"})]}),e.jsx(ae,{children:s&&s.length>0?e.jsx("div",{className:"space-y-3",children:s.map((o,c)=>e.jsx(Vr,{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 yA=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"}}},vA=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}}},jA=t=>{switch(t){case"approval":case"approved":return e.jsx(Re,{className:"w-5 h-5 text-green-600"});case"rejection":case"rejected":return e.jsx(Ct,{className:"w-5 h-5 text-red-600"});case"comment":return e.jsx(Ds,{className:"w-5 h-5 text-blue-600"});case"status_change":case"updated":return e.jsx(Ut,{className:"w-5 h-5 text-orange-600"});case"assignment":return e.jsx(Ci,{className:"w-5 h-5 text-purple-600"});case"created":return e.jsx(ke,{className:"w-5 h-5 text-blue-600"});case"reminder":return e.jsx(nt,{className:"w-5 h-5 text-yellow-600"});case"document_added":return e.jsx(ji,{className:"w-5 h-5 text-indigo-600"});case"sla_warning":return e.jsx(os,{className:"w-5 h-5 text-amber-600"});default:return e.jsx(It,{className:"w-5 h-5 text-gray-600"})}};function NA({request:t}){return e.jsxs(se,{children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(It,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Activity Timeline"]}),e.jsx(Ue,{className:"text-xs sm:text-sm",children:"Complete audit trail of all request activities"})]}),e.jsx(ae,{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:jA(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:as(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(It,{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 fg({open:t,onClose:s,success:a,title:r,message:n}){return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsx(pt,{children:e.jsxs(mt,{className:"flex items-center gap-2",children:[a?e.jsx(Re,{className:"w-5 h-5 text-green-600"}):e.jsx(Ye,{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(Re,{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(Ct,{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(Rt,{children:e.jsx(F,{onClick:s,className:`w-full ${a?"bg-green-600 hover:bg-green-700":"bg-gray-600 hover:bg-gray-700"}`,children:"OK"})})]})})}function bg({open:t,onClose:s,onConfirm:a,existingParticipants:r=[]}){const[n,i]=p.useState(""),[l,o]=p.useState(!1),[c,d]=p.useState([]),[m,h]=p.useState(!1),[x,u]=p.useState(null),g=p.useRef(null),b=p.useRef(null),[f,y]=p.useState({open:!1,type:"error",email:"",message:""}),[v,C]=p.useState({open:!1,violations:[]}),[w,A]=p.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20});p.useEffect(()=>{t&&(async()=>{var E;try{const P=await Qs("WORKFLOW_SHARING"),B=await Qs("TAT_SETTINGS"),k=[...P,...B],L={};k.forEach(V=>{L[V.configKey]=V.configValue}),A({maxApprovalLevels:parseInt(L.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(L.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((E=L.ALLOW_ADD_SPECTATOR)==null?void 0:E.toLowerCase())==="true",maxSpectators:parseInt(L.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(P){console.error("Failed to load system policy:",P)}})()},[t]);const N=async()=>{var D,S;const j=n.trim().toLowerCase();if(!j){y({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(j)){y({open:!0,type:"error",email:j,message:"Please enter a valid email address"});return}const P=r.find(O=>(O.email||"").toLowerCase()===j);if(P){const O=((D=P.participantType)==null?void 0:D.toUpperCase())||"PARTICIPANT",I=P.name||j;if(O==="INITIATOR"){y({open:!0,type:"error",email:j,message:`${I} is the request initiator and cannot be added as a spectator.`});return}else if(O==="APPROVER"){y({open:!0,type:"error",email:j,message:`${I} is already an approver on this request and cannot be added as a spectator.`});return}else if(O==="SPECTATOR"){y({open:!0,type:"error",email:j,message:`${I} is already a spectator on this request.`});return}else{y({open:!0,type:"error",email:j,message:`${I} is already a participant on this request.`});return}}const B=[];w.allowSpectators||B.push({type:"Spectators Not Allowed",message:"Adding spectators is not allowed by system policy."});const L=r.filter(O=>(O.participantType||"").toUpperCase()==="SPECTATOR").length;L>=w.maxSpectators&&B.push({type:"Maximum Spectators Exceeded",message:"This request has reached the maximum number of spectators allowed.",currentValue:L,maxValue:w.maxSpectators});const V=r.length+1;if(V>w.maxParticipants&&B.push({type:"Maximum Participants Exceeded",message:"Adding this spectator would exceed the maximum participants limit.",currentValue:V,maxValue:w.maxParticipants}),B.length>0){C({open:!0,violations:B});return}if(!x||x.email.toLowerCase()!==j)try{const I=((S=(await ca(j,1)).data)==null?void 0:S.data)||[];if(I.length===0){y({open:!0,type:"not-found",email:j,message:""});return}const M=I[0];await la({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})}catch(O){console.error("Failed to validate spectator:",O),y({open:!0,type:"error",email:j,message:"Failed to validate user. Please try again."});return}try{o(!0),await a(j),i(""),u(null),s()}catch(O){console.error("Failed to add spectator:",O)}finally{o(!1)}},_=()=>{l||(i(""),u(null),d([]),h(!1),s())};p.useEffect(()=>{c.length>0&&b.current&&b.current.scrollTo({top:b.current.scrollHeight,behavior:"smooth"})},[c.length]),p.useEffect(()=>()=>{g.current&&clearTimeout(g.current)},[]);const T=j=>{if(i(j),x&&x.email.toLowerCase()!==j.toLowerCase()&&u(null),g.current&&clearTimeout(g.current),!j||!j.startsWith("@")||j.length<2){d([]),h(!1);return}h(!0),g.current=setTimeout(async()=>{var E;try{const P=j.slice(1),k=((E=(await ca(P,10)).data)==null?void 0:E.data)||[];d(k)}catch(P){console.error("Search failed:",P),d([])}finally{h(!1)}},300)},R=async j=>{try{await la({userId:j.userId,email:j.email,displayName:j.displayName,firstName:j.firstName,lastName:j.lastName,department:j.department,phone:j.phone,mobilePhone:j.mobilePhone,designation:j.designation,jobTitle:j.jobTitle,manager:j.manager,employeeId:j.employeeId,employeeNumber:j.employeeNumber,secondEmail:j.secondEmail,location:j.location}),i(j.email),u(j),d([]),h(!1)}catch(E){console.error("Failed to ensure user exists:",E),y({open:!0,type:"error",email:j.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(ht,{open:t,onOpenChange:_,children:[e.jsxs(dt,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:_,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:l,children:[e.jsx(ft,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(pt,{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(mt,{className:"text-xl font-bold text-gray-900",children:"Add Spectator"})]})}),e.jsxs("div",{ref:b,className:"space-y-4 px-6 py-4 pb-8 overflow-y-auto flex-1",children:[e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed",children:"Add a 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(Si,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Ie,{type:"text",placeholder:"@username or user@example.com",value:n,onChange:j=>T(j.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(j=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>R(j),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ts,{className:"h-8 w-8",children:e.jsx(ss,{className:"bg-purple-100 text-purple-800 text-xs font-semibold",children:(j.displayName||j.email).split(" ").map(E=>E[0]).join("").slice(0,2).toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:j.displayName||[j.firstName,j.lastName].filter(Boolean).join(" ")||j.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:j.email}),j.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:j.designation})]})]})},j.userId))}):null})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Type ",e.jsx("span",{className:"font-semibold",children:"@username"})," to search for users, or enter email directly."]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(F,{type:"button",variant:"outline",onClick:_,className:"flex-1 h-11 border-gray-300",disabled:l,children:"Cancel"}),e.jsxs(F,{type:"button",onClick:N,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(ht,{open:f.open,onOpenChange:j=>y(E=>({...E,open:j})),children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(pt,{children:[e.jsx(mt,{className:"flex items-center gap-2",children:f.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(Ye,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ye,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(Pt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[f.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:f.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(wi,{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."]})})]}),f.type==="error"&&e.jsxs(e.Fragment,{children:[f.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:f.email}),"."]}),f.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:f.message})})]})]})})]}),e.jsx(Rt,{children:e.jsx(F,{onClick:()=>y(j=>({...j,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(Ln,{open:v.open,onClose:()=>C({open:!1,violations:[]}),violations:v.violations,policyDetails:{maxApprovalLevels:w.maxApprovalLevels,maxParticipants:w.maxParticipants,allowSpectators:w.allowSpectators,maxSpectators:w.maxSpectators}})]})}function yg({open:t,onClose:s,onConfirm:a,existingParticipants:r=[],currentLevels:n=[],maxApprovalLevels:i,onPolicyViolation:l}){const[o,c]=p.useState(""),[d,m]=p.useState(24),[h,x]=p.useState(null),[u,g]=p.useState(!1),[b,f]=p.useState([]),[y,v]=p.useState(!1),[C,w]=p.useState(null),A=p.useRef(null),N=p.useRef(null),[_,T]=p.useState({open:!1,type:"error",email:"",message:""}),R=n.filter(S=>S&&(S.status==="approved"||S.status==="rejected"||S.status==="skipped")),j=Math.max(1,R.length+1),E=Math.max(1,n.length+1),P=E>=j?Array.from({length:E-j+1},(S,O)=>j+O):[j];p.useEffect(()=>{P.length>0&&h===null&&x(P[0]||null)},[P.length,h]);const B=async()=>{var G,re;const S=o.trim().toLowerCase();if(!S){T({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(S)){T({open:!0,type:"error",email:S,message:"Please enter a valid email address"});return}if(!d||d<=0){T({open:!0,type:"error",email:"",message:"Please enter valid TAT hours (minimum 1 hour)"});return}if(d>720){T({open:!0,type:"error",email:"",message:"TAT hours cannot exceed 720 hours (30 days)"});return}if(!h){T({open:!0,type:"error",email:"",message:"Please select an approval level"});return}if(h<j){T({open:!0,type:"error",email:"",message:`Cannot add approver at level ${h}. Minimum allowed level is ${j} (after completed levels)`});return}const I=n.length>0?Math.max(...n.map(te=>te.levelNumber),0):0,M=h>I?h:I+1;if(i&&M>i){l?l([{type:"Maximum Approval Levels Exceeded",message:`Adding an approver at level ${h} would result in ${M} approval levels, which exceeds the maximum allowed (${i}). Please remove an approver or contact your administrator.`,currentValue:M,maxValue:i}]):T({open:!0,type:"error",email:"",message:`Cannot add approver. This would exceed the maximum allowed approval levels (${i}). Current request has ${I} level(s).`});return}const W=r.find(te=>(te.email||"").toLowerCase()===S);if(W){const te=((G=W.participantType)==null?void 0:G.toUpperCase())||"PARTICIPANT",$=W.name||S;if(te==="INITIATOR"){T({open:!0,type:"error",email:S,message:`${$} is the request initiator and cannot be added as an approver.`});return}else if(te==="APPROVER"){T({open:!0,type:"error",email:S,message:`${$} is already an approver on this request.`});return}else if(te==="SPECTATOR"){T({open:!0,type:"error",email:S,message:`${$} is currently a spectator on this request and cannot be added as an approver. Please remove them as spectator first.`});return}else{T({open:!0,type:"error",email:S,message:`${$} is already a participant on this request.`});return}}if(!C||C.email.toLowerCase()!==S)try{const $=((re=(await ca(S,1)).data)==null?void 0:re.data)||[];if($.length===0){T({open:!0,type:"not-found",email:S,message:""});return}const z=$[0];await la({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(te){console.error("Failed to validate approver:",te),T({open:!0,type:"error",email:S,message:"Failed to validate user. Please try again."});return}try{g(!0),await a(S,d,h),c(""),m(24),x(null),w(null),s()}catch(te){console.error("Failed to add approver:",te)}finally{g(!1)}},k=()=>{u||(c(""),m(24),x(null),w(null),f([]),v(!1),s())},L=S=>{const O=S.toLowerCase();return O==="approved"?e.jsx(Re,{className:"w-4 h-4 text-green-600"}):O==="rejected"?e.jsx(Ct,{className:"w-4 h-4 text-red-600"}):O==="skipped"?e.jsx(Ye,{className:"w-4 h-4 text-orange-600"}):O==="in-review"||O==="pending"?e.jsx(nt,{className:"w-4 h-4 text-blue-600"}):e.jsx(nt,{className:"w-4 h-4 text-gray-400"})};p.useEffect(()=>{b.length>0&&N.current&&N.current.scrollTo({top:N.current.scrollHeight,behavior:"smooth"})},[b.length]),p.useEffect(()=>()=>{A.current&&clearTimeout(A.current)},[]);const V=S=>{if(c(S),C&&C.email.toLowerCase()!==S.toLowerCase()&&w(null),A.current&&clearTimeout(A.current),!S||!S.startsWith("@")||S.length<2){f([]),v(!1);return}v(!0),A.current=setTimeout(async()=>{var O;try{const I=S.slice(1),W=((O=(await ca(I,10)).data)==null?void 0:O.data)||[];f(W)}catch(I){console.error("Search failed:",I),f([])}finally{v(!1)}},300)},D=async S=>{try{await la({userId:S.userId,email:S.email,displayName:S.displayName,firstName:S.firstName,lastName:S.lastName,department:S.department,phone:S.phone,mobilePhone:S.mobilePhone,designation:S.designation,jobTitle:S.jobTitle,manager:S.manager,employeeId:S.employeeId,employeeNumber:S.employeeNumber,secondEmail:S.secondEmail,location:S.location}),c(S.email),w(S),f([]),v(!1)}catch(O){console.error("Failed to ensure user exists:",O),T({open:!0,type:"error",email:S.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(ht,{open:t,onOpenChange:k,children:[e.jsxs(dt,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:k,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:u,children:[e.jsx(ft,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(pt,{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(ps,{className:"w-5 h-5 text-blue-600"})}),e.jsx(mt,{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."}),i&&e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-2",children:e.jsxs("p",{className:"text-xs text-blue-800",children:[" Max: ",i," level",i!==1?"s":"",n.length>0&&e.jsxs("span",{className:"ml-2",children:["(",Math.max(...n.map(S=>S.levelNumber),0),"/",i,")"]})]})}),n.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-sm font-semibold text-gray-700",children:"Current Approval Levels"}),e.jsx("div",{className:"max-h-40 overflow-y-auto space-y-2 border rounded-lg p-3 bg-gray-50",children:n.map(S=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-md ${S.status==="approved"?"bg-green-100 border border-green-200":S.status==="rejected"?"bg-red-100 border border-red-200":S.status==="skipped"?"bg-orange-100 border border-orange-200":"bg-white border border-gray-200"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-blue-600 text-white text-xs font-semibold flex items-center justify-center",children:S.levelNumber}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:S.approverName}),e.jsxs("p",{className:"text-xs text-gray-500",children:[S.tatHours,"h TAT"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[L(S.status),e.jsx(oe,{variant:"outline",className:`text-xs ${S.status==="approved"?"bg-green-50 text-green-700 border-green-300":S.status==="rejected"?"bg-red-50 text-red-700 border-red-300":S.status==="skipped"?"bg-orange-50 text-orange-700 border-orange-300":"bg-blue-50 text-blue-700 border-blue-300"}`,children:S.status})]})]},S.levelNumber))}),e.jsxs("p",{className:"text-xs text-gray-500",children:[" New approver can only be added at level ",j," or higher (after completed levels)"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-sm font-medium text-gray-700",children:"Approval Level *"}),e.jsxs(Ke,{value:(h==null?void 0:h.toString())||"",onValueChange:S=>x(Number(S)),disabled:u,children:[e.jsx(Ze,{className:"h-11 border-gray-300",children:e.jsx(Xe,{placeholder:"Select level"})}),e.jsx(Je,{children:P.map(S=>e.jsx(Y,{value:S.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ns,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Level ",S]}),S<=n.length&&e.jsxs("span",{className:"text-xs text-gray-500",children:["(will shift existing Level ",S,")"]})]})},S))})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Choose where to insert the new approver. Existing levels will be automatically shifted."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{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(Ie,{type:"number",min:"1",max:"720",value:d,onChange:S=>m(Number(S.target.value)),className:"h-11 border-gray-300 flex-1",disabled:u,placeholder:"24"}),e.jsxs("div",{className:"flex items-center gap-1 text-sm text-gray-600 bg-gray-100 px-3 h-11 rounded-md border border-gray-300",children:[e.jsx(nt,{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(Si,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Ie,{type:"text",placeholder:"@username or user@example.com",value:o,onChange:S=>V(S.target.value),className:"pl-10 h-11 border-gray-300",disabled:u,autoFocus:!0}),(y||b.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..."}):b.length>0?e.jsx("ul",{className:"divide-y",children:b.map(S=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>D(S),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ts,{className:"h-8 w-8",children:e.jsx(ss,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:(S.displayName||S.email).split(" ").map(O=>O[0]).join("").slice(0,2).toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:S.displayName||[S.firstName,S.lastName].filter(Boolean).join(" ")||S.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:S.email}),S.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:S.designation})]})]})},S.userId))}):null})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Type ",e.jsx("span",{className:"font-semibold",children:"@username"})," to search for users, or enter email directly."]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(F,{type:"button",variant:"outline",onClick:k,className:"flex-1 h-11 border-gray-300",disabled:u,children:"Cancel"}),e.jsxs(F,{type:"button",onClick:B,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:u||!o.trim()||!h||!d,children:[e.jsx(ps,{className:"w-4 h-4 mr-2"}),u?"Adding...":`Add at Level ${h||"?"}`]})]})]}),e.jsx(ht,{open:_.open,onOpenChange:S=>T(O=>({...O,open:S})),children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(pt,{children:[e.jsx(mt,{className:"flex items-center gap-2",children:_.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(Ye,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ye,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(Pt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[_.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:_.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(wi,{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."]})})]}),_.type==="error"&&e.jsxs(e.Fragment,{children:[_.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:_.email}),"."]}),_.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:_.message})})]})]})})]}),e.jsx(Rt,{children:e.jsx(F,{onClick:()=>T(S=>({...S,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const wA=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"}},CA=t=>{switch(t){case"online":return"Online";case"away":return"Away";case"offline":return"Offline";default:return"Unknown"}},SA=t=>{const s=t.replace(/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,(a,r,n,i)=>{const l=n+a.length,o=i[l];return!o||/\s|[.,!?;:]|@/.test(o)?'<span class="inline-flex items-center px-2.5 py-0.5 rounded-md bg-blue-50 text-blue-800 font-black text-base border-2 border-blue-400 shadow-sm">@'+r+"</span>":a}).replace(/\n/g,"<br />");return va(s)},AA=t=>t<1024?t+" B":t<1024*1024?(t/1024).toFixed(1)+" KB":(t/(1024*1024)).toFixed(1)+" MB",Ju=({type:t})=>{const s="w-4 h-4",a=t.toLowerCase();return a.includes("pdf")?e.jsx(ke,{className:`${s} text-red-600`}):a.includes("excel")||a.includes("spreadsheet")||a.includes("xlsx")?e.jsx(Ix,{className:`${s} text-green-600`}):a.includes("powerpoint")||a.includes("presentation")||a.includes("pptx")?e.jsx(ke,{className:`${s} text-orange-600`}):a.includes("word")||a.includes("document")||a.includes("docx")?e.jsx(ke,{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(Yn,{className:`${s} text-purple-600`}):e.jsx(ji,{className:`${s} text-gray-600`})};function vg({requestId:t,messages:s,onSend:a,skipSocketJoin:r=!1,requestTitle:n,onAttachmentsExtracted:i,isInitiator:l=!1,isSpectator:o=!1,currentLevels:c=[],onAddApprover:d,maxApprovalLevels:m,onPolicyViolation:h}){const x=Fa(),u=t||x.requestId||"",[g,b]=p.useState(""),[f,y]=p.useState(""),[v,C]=p.useState(!1),[w,A]=p.useState([]),[N,_]=p.useState(!1),[T,R]=p.useState([]),[j,E]=p.useState(null),[P,B]=p.useState(null),[k,L]=p.useState(!1),[V,D]=p.useState(!1),[S,O]=p.useState(!1),[I,M]=p.useState({success:!0,title:"",message:""}),W=p.useRef(null),G=p.useRef(null),re=p.useRef(null),te=p.useRef(!1),[$,z]=p.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[H,je]=p.useState({open:!1,errors:[]}),le=p.useMemo(()=>({id:u,title:n||"Request Details"}),[u,n]),[ue,$e]=p.useState([]),Te=ue.filter(q=>q.status==="online"),Ve=w.filter(q=>q.content.toLowerCase().includes(f.toLowerCase())||q.user.name.toLowerCase().includes(f.toLowerCase())),Qe=p.useMemo(()=>o!==void 0?o:!j||ue.length===0?!1:ue.some(q=>{const Ne=q.userId||q.user_id,ee=(q.role||"").toString().toUpperCase(),_e=(q.participantType||q.participant_type||"").toString().toUpperCase();return Ne===j&&(ee==="SPECTATOR"||_e==="SPECTATOR")}),[o,j,ue]);p.useEffect(()=>{},[ue]),p.useEffect(()=>{!u||!j||s||(async()=>{try{const q=await Mr(u),Ne=Array.isArray(q)?q.map(ee=>{const _e=ee.userId||ee.user_id;return{id:ee.noteId||ee.id||String(Math.random()),user:{name:ee.userName||"User",avatar:(ee.userName||"U").slice(0,2).toUpperCase(),role:ee.userRole||"Participant"},content:ee.message||"",timestamp:ee.createdAt||new Date().toISOString(),isCurrentUser:_e===j,attachments:Array.isArray(ee.attachments)?ee.attachments.map(Le=>({attachmentId:Le.attachmentId||Le.attachment_id,name:Le.fileName||Le.file_name||Le.name,fileName:Le.fileName||Le.file_name||Le.name,url:Le.storageUrl||Le.storage_url||Le.url||"#",type:Le.fileType||Le.file_type||Le.type||"file",fileType:Le.fileType||Le.file_type||Le.type||"file",fileSize:Le.fileSize||Le.file_size})):void 0}}):[];A(Ne)}catch(q){console.error("[WorkNoteChat] Failed to load messages:",q)}})()},[u,j,s]);const Fe=p.useMemo(()=>{const q=[];return w.forEach(Ne=>{Ne.attachments&&Ne.attachments.length>0&&Ne.attachments.forEach(ee=>{q.push({attachmentId:ee.attachmentId||ee.attachment_id,name:ee.fileName||ee.file_name||ee.name||"Untitled",fileName:ee.fileName||ee.file_name||ee.name||"Untitled",size:ee.fileSize||ee.file_size,type:ee.fileType||ee.file_type||ee.type||"file",uploadedBy:Ne.user.name,uploadedAt:Ne.timestamp,url:ee.storageUrl||ee.storage_url||ee.url||"#"})})}),q},[w]);p.useEffect(()=>{i&&Fe.length>=0&&i(Fe)},[Fe,i]);const Q=p.useMemo(()=>ue.map(q=>({email:(q.email||"").toLowerCase(),participantType:q.role==="Initiator"?"INITIATOR":q.role==="Approver"?"APPROVER":q.role==="Spectator"?"SPECTATOR":"PARTICIPANT",name:q.name})),[ue]),pe=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()}},Ce=()=>{var q;(q=W.current)==null||q.scrollIntoView({behavior:"smooth"})};p.useEffect(()=>{Ce()},[w]);const Oe=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()}};p.useEffect(()=>{te.current||u&&(async()=>{try{const q=await Ts(u),Ne=Array.isArray(q==null?void 0:q.participants)?q.participants:[];if(Ne.length===0)return;const ee=Ne.map(Me=>{const qe=Me.participantType||Me.participant_type||"participant",He=Me.userId||Me.user_id||"";return{name:Me.userName||Me.user_name||Me.user_email||Me.userEmail||"User",avatar:(Me.userName||Me.user_name||Me.user_email||"U").toString().split(" ").map(at=>at[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Oe(qe.toString()),status:"offline",email:Me.userEmail||Me.user_email||"",permissions:["read","write","mention"],userId:He}});te.current=!0,$e(ee);let _e=0;const Le=3,We=()=>{re.current&&re.current.connected?(re.current.emit("request:online-users",{requestId:u}),_e++,_e<Le&&setTimeout(We,500)):(_e++,_e<Le&&setTimeout(We,200))};setTimeout(We,100)}catch(q){console.error("[WorkNoteChat] ❌ Failed to load participants:",q)}})()},[u]),p.useEffect(()=>()=>{u&&(te.current=!1)},[u]),p.useEffect(()=>{const q=localStorage.getItem("userData");if(q)try{const Ne=JSON.parse(q),ee=(Ne==null?void 0:Ne.id)||(Ne==null?void 0:Ne.userId)||(Ne==null?void 0:Ne.user_id)||null;E(ee)}catch(Ne){console.error("[WorkNoteChat] Failed to parse userData:",Ne)}},[]),p.useEffect(()=>{(async()=>{try{const Ne=await Qs("DOCUMENT_POLICY"),ee={};Ne.forEach(Me=>{ee[Me.configKey]=Me.configValue});const _e=parseInt(ee.MAX_FILE_SIZE_MB||"10"),We=(ee.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(Me=>Me.trim().toLowerCase());z({maxFileSizeMB:_e,allowedFileTypes:We})}catch(Ne){console.error("Failed to load document policy:",Ne)}})()},[]),p.useEffect(()=>{if(!j)return;let q=u;return(async()=>{var Ne;try{const ee=await Ts(u);(Ne=ee==null?void 0:ee.workflow)!=null&&Ne.requestId&&(q=ee.workflow.requestId)}catch{}try{const ee=Or();r?$e(ct=>ct.map(St=>St.userId===j?{...St,status:"online"}:St)):(Ol(ee,q,j),$e(ct=>ct.map(St=>St.userId===j?{...St,status:"online"}:St)));const _e=ct=>{const rt=(ct==null?void 0:ct.note)||ct;if(!rt)return;const St=rt.noteId||rt.id;A(ds=>{if(ds.some(kt=>kt.id===St))return ds;const Vt=rt.userName||rt.user_name||"User",Ca=rt.userRole||rt.user_role,qs=pe(Ca),er=rt.userId||rt.user_id,da={id:St||String(Date.now()),user:{name:Vt,avatar:Vt.split(" ").map(kt=>kt[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:qs},content:rt.message||"",timestamp:rt.createdAt||new Date().toISOString(),isCurrentUser:er===j,attachments:Array.isArray(rt.attachments)?rt.attachments.map(kt=>({attachmentId:kt.attachmentId||kt.attachment_id,name:kt.fileName||kt.file_name||kt.name,fileName:kt.fileName||kt.file_name||kt.name,url:kt.storageUrl||kt.storage_url||kt.url||"#",type:kt.fileType||kt.file_type||kt.type||"file",fileType:kt.fileType||kt.file_type||kt.type||"file",fileSize:kt.fileSize||kt.file_size})):void 0};return[...ds,da]})},Le=ct=>{$e(rt=>rt.length===0||!rt.find(Vt=>Vt.userId===ct.userId)?rt:rt.map(Vt=>Vt.userId===ct.userId?{...Vt,status:"online"}:Vt))},We=ct=>{ct.userId!==j&&$e(rt=>rt.length===0||!rt.find(Vt=>Vt.userId===ct.userId)?rt:rt.map(Vt=>Vt.userId===ct.userId?{...Vt,status:"offline"}:Vt))},Me=ct=>{$e(rt=>rt.length===0?rt:rt.map(ds=>{const Vt=ds.userId||"";if(Vt===j)return{...ds,status:"online"};const qs=ct.userIds.includes(Vt);return{...ds,status:qs?"online":"offline"}}))},qe=()=>{$e(ct=>ct.map(St=>St.userId===j?{...St,status:"online"}:St)),r||Ol(ee,q,j),te.current&&(ee.emit("request:online-users",{requestId:q}),setTimeout(()=>ee.emit("request:online-users",{requestId:q}),300),setTimeout(()=>ee.emit("request:online-users",{requestId:q}),800))},He=ct=>{console.error("[WorkNoteChat] ❌ Socket error:",ct)},at=ct=>{console.warn("[WorkNoteChat] ⚠️ Socket disconnected:",ct),$e(rt=>rt.map(St=>St.userId===j?St:{...St,status:"offline"}))},Ss=ct=>{ct.includes("presence")||ct.includes("worknote")||ct.includes("request")};ee.on("connect",qe),ee.on("disconnect",at),ee.on("error",He),ee.on("worknote:new",_e),ee.on("presence:join",Le),ee.on("presence:leave",We),ee.on("presence:online",Me),ee.onAny(Ss),re.current=ee,ee.connected&&te.current&&(ee.emit("request:online-users",{requestId:q}),setTimeout(()=>{ee.emit("request:online-users",{requestId:q})},300),setTimeout(()=>{ee.emit("request:online-users",{requestId:q})},800),setTimeout(()=>{ee.emit("request:online-users",{requestId:q})},1500));const Kt=()=>{ee.off("connect",qe),ee.off("disconnect",at),ee.off("error",He),ee.off("worknote:new",_e),ee.off("presence:join",Le),ee.off("presence:leave",We),ee.off("presence:online",Me),ee.offAny(Ss),r||lh(ee,q),re.current=null};window.__wn_cleanup=Kt}catch{}})(),()=>{var Ne;try{(Ne=window.__wn_cleanup)==null||Ne.call(window)}catch{}}},[u,j,r]);const X=async()=>{if(g.trim()||T.length>0){const q=ut(g),Ne=q.map(Le=>{const We=ue.find(Me=>Me.name.toLowerCase().includes(Le.toLowerCase()));return We==null?void 0:We.userId}).filter(Boolean),ee=T.map(Le=>({name:Le.name,url:URL.createObjectURL(Le),type:Le.type.split("/")[1]||"file"})),_e={id:Date.now().toString(),user:{name:"You",avatar:"YO",role:"Current User"},content:g,timestamp:new Date().toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0}),mentions:q,isHighPriority:g.includes("!important")||g.includes("urgent"),attachments:ee.length>0?ee:void 0,isCurrentUser:!0};if(a)try{await a(g,T)}catch{}else try{await Nh(u,{message:g,mentions:Ne},T);const Le=await Mr(u),We=Array.isArray(Le)?Le.map(Me=>{const qe=Me.userId||Me.user_id;return{id:Me.noteId||Me.id||String(Math.random()),user:{name:Me.userName||"User",avatar:(Me.userName||"U").slice(0,2).toUpperCase(),role:Me.userRole||"Participant"},content:Me.message||"",timestamp:Me.createdAt||new Date().toISOString(),isCurrentUser:qe===j,attachments:Array.isArray(Me.attachments)?Me.attachments.map(He=>({attachmentId:He.attachmentId||He.attachment_id,name:He.fileName||He.file_name||He.name,fileName:He.fileName||He.file_name||He.name,url:He.storageUrl||He.storage_url||He.url||"#",type:He.fileType||He.file_type||He.type||"file",fileType:He.fileType||He.file_type||He.type||"file",fileSize:He.fileSize||He.file_size})):void 0}}):[];A(We)}catch{A(Le=>[...Le,_e])}b(""),R([])}};p.useEffect(()=>{if(s&&Array.isArray(s))try{const Ne=s.filter(ee=>(ee.type||"").toLowerCase()!=="sla_warning").map(ee=>{var Le;if(ee.type||ee.activityType||ee.isSystem)return{id:ee.id||`activity-${ee.timestamp||Date.now()}-${Math.random()}`,user:{name:"System",avatar:"SY",role:"System"},content:ee.details||ee.action||ee.content||"",timestamp:ee.timestamp||ee.createdAt||ee.created_at||new Date().toISOString(),isSystem:!0,isCurrentUser:!1};{const We=ee.userName||ee.user_name||((Le=ee.user)==null?void 0:Le.name)||"User",Me=ee.userRole||ee.user_role,qe=pe(Me),He=ee.userId||ee.user_id;return{id:ee.noteId||ee.note_id||ee.id||String(Math.random()),user:{name:We,avatar:We.split(" ").map(at=>at[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:qe},content:ee.message||ee.content||"",timestamp:ee.createdAt||ee.created_at||ee.timestamp||new Date().toISOString(),isSystem:!1,attachments:Array.isArray(ee.attachments)?ee.attachments.map(at=>({attachmentId:at.attachmentId||at.attachment_id,name:at.fileName||at.file_name||at.name,fileName:at.fileName||at.file_name||at.name,url:at.storageUrl||at.storage_url||at.url||"#",type:at.fileType||at.file_type||at.type||"file",fileType:at.fileType||at.file_type||at.type||"file",fileSize:at.fileSize||at.file_size})):void 0,isCurrentUser:He===j}}}).sort((ee,_e)=>new Date(ee.timestamp).getTime()-new Date(_e.timestamp).getTime());A(Ne)}catch(q){console.error("[WorkNoteChat] Error mapping messages:",q)}else(async()=>{try{const q=await Mr(u),Ne=Array.isArray(q)?q.map(ee=>{const _e=ee.userName||ee.user_name||"User",Le=ee.userRole||ee.user_role,We=pe(Le),Me=ee.userId||ee.user_id;return{id:ee.noteId||ee.note_id||ee.id||String(Math.random()),user:{name:_e,avatar:_e.split(" ").map(qe=>qe[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:We},content:ee.message||"",timestamp:ee.createdAt||ee.created_at||new Date().toISOString(),attachments:Array.isArray(ee.attachments)?ee.attachments.map(qe=>({attachmentId:qe.attachmentId||qe.attachment_id,name:qe.fileName||qe.file_name||qe.name,fileName:qe.fileName||qe.file_name||qe.name,url:qe.storageUrl||qe.storage_url||qe.url||"#",type:qe.fileType||qe.file_type||qe.type||"file",fileType:qe.fileType||qe.file_type||qe.type||"file",fileSize:qe.fileSize||qe.file_size})):void 0,isCurrentUser:Me===j}}):[];A(Ne)}catch(q){console.error("[WorkNoteChat] Error loading work notes:",q)}})()},[s,u,ue]);const Z=q=>{const Ne=$.maxFileSizeMB*1024*1024;if(q.size>Ne)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${$.maxFileSizeMB}MB. Current size: ${(q.size/(1024*1024)).toFixed(2)}MB`};const ee=q.name.toLowerCase(),_e=ee.substring(ee.lastIndexOf(".")+1);return $.allowedFileTypes.includes(_e)?{valid:!0}:{valid:!1,reason:`File type "${_e}" is not allowed. Allowed types: ${$.allowedFileTypes.join(", ")}`}},me=q=>{if(!q.target.files||q.target.files.length===0)return;const Ne=Array.from(q.target.files),ee=[],_e=[];Ne.forEach(Le=>{const We=Z(Le);We.valid?_e.push(Le):ee.push({fileName:Le.name,reason:We.reason||"Unknown validation error"})}),ee.length>0&&je({open:!0,errors:ee}),_e.length>0&&(R(Le=>[...Le,..._e]),_e.length<Ne.length?K.warning(`${_e.length} of ${Ne.length} file(s) were added. ${ee.length} file(s) were rejected.`):K.success(`${_e.length} file(s) added successfully`)),q.target&&(q.target.value="")},J=q=>{R(Ne=>Ne.filter((ee,_e)=>_e!==q)),G.current&&(G.current.value="")},be=q=>{b(Ne=>Ne+q),C(!1)},Be=()=>{var q;(q=G.current)==null||q.click()},Ee=async q=>{var Ne,ee;try{await Ch(u,q);const _e=await Ts(u),Le=Array.isArray(_e==null?void 0:_e.participants)?_e.participants:[];if(Le.length){const We=Le.map(Me=>{const qe=Me.participantType||Me.participant_type||"participant",He=Me.userId||Me.user_id||"",at=Me.userName||Me.user_name||Me.userEmail||Me.user_email||"User",Ss=Me.userEmail||Me.user_email||"",Kt=at.split(" ").map(ct=>ct[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:at,avatar:Kt,role:Oe(qe),status:"offline",email:Ss,lastSeen:void 0,permissions:["read"],userId:He}});$e(We),re.current&&re.current.connected&&re.current.emit("request:online-users",{requestId:u})}L(!1),M({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),O(!0)}catch(_e){throw console.error("Failed to add spectator:",_e),M({success:!1,title:"Failed to Add Spectator",message:((ee=(Ne=_e==null?void 0:_e.response)==null?void 0:Ne.data)==null?void 0:ee.error)||"Failed to add spectator. Please try again."}),O(!0),_e}},ze=async(q,Ne,ee)=>{var _e,Le;if(d)await d(q,Ne,ee),D(!1);else try{await wh(u,q,Ne,ee);const We=await Ts(u),Me=Array.isArray(We==null?void 0:We.participants)?We.participants:[];if(Me.length){const qe=Me.map(He=>{const at=He.participantType||He.participant_type||"participant",Ss=He.userId||He.user_id||"",Kt=He.userName||He.user_name||He.userEmail||He.user_email||"User",ct=He.userEmail||He.user_email||"",rt=Kt.split(" ").map(St=>St[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:Kt,avatar:rt,role:Oe(at),status:"offline",email:ct,lastSeen:void 0,permissions:["read"],userId:Ss}});$e(qe),re.current&&re.current.connected&&re.current.emit("request:online-users",{requestId:u})}D(!1),M({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${ee} with ${Ne}h TAT`}),O(!0)}catch(We){throw console.error("Failed to add approver:",We),M({success:!1,title:"Failed to Add Approver",message:((Le=(_e=We==null?void 0:We.response)==null?void 0:_e.data)==null?void 0:Le.error)||"Failed to add approver. Please try again."}),O(!0),We}},vt=["😊","😂","🤣","😁","😃","😄","😅","😆","😉","😌","😍","🥰","😘","😗","😙","😚","🙂","🤗","🤩","🤔","🤨","😐","😑","😶","🙄","😏","😒","🙃","😬","🤐","😴","😪","😵","🤯","🤪","😜","😝","😛","🤤","😋","😎","🤓","🧐","😕","😟","🙁","☹️","😮","😯","😲","😳","🥺","😦","😧","😨","😰","😥","😢","😭","😱","😖","😣","😞","😓","😩","😫","🥱","😤","😡","😠","🤬","😈","👿","💀","☠️","💩","🤡","👹","👺","👻","👋","🤚","🖐️","✋","🖖","👌","🤌","🤏","✌️","🤞","🤟","🤘","🤙","👈","👉","👆","🖕","👇","☝️","👍","👎","✊","👊","🤛","🤜","👏","🙌","👐","🤲","🤝","🙏","💪","🦾","🦿","🦵","🦶","👂","🦻","👃","🧠","❤️","🧡","💛","💚","💙","💜","🖤","🤍","🤎","💔","❣️","💕","💞","💓","💗","💖","💘","💝","💟","❤️‍🔥","💼","📊","📈","📉","💻","⌨️","🖥️","🖨️","🖱️","💾","💿","📱","☎️","📞","📟","📠","📧","✉️","📨","📩","📮","📪","📫","📬","📭","📄","📃","📑","📝","✏️","✒️","🖊️","🖋️","📏","📐","📌","📍","🗂️","📁","📂","✅","✔️","☑️","🎯","🎖️","🏆","🥇","🥈","🥉","⭐","🌟","✨","💫","🔥","💥","⚡","💯","🎉","🎊","🎈","⚠️","🚫","❌","⛔","🚷","🚯","🚱","🚳","🔞","📵","❗","❓","❕","❔","‼️","⁉️","💢","💬","💭","🗯️","⏰","⏱️","⏲️","⏳","⌛","📅","📆","🗓️","📇","🕐","🕑","🕒","🕓","🕔","🕕","🕖","🕗","🕘","🕙","🕚","🚀","🎯","🎲","🎰","🧩","🔍","🔎","🔑","🗝️","🔒","🔓","🔐","🔏","🔔","🔕","📣","📢","💡","🔦","🏮","","","✖️","➗","♾️","‼️","⁉️","❓","❔","❕","🔄","🔃","🔂","▶️","⏸️","⏯️","⏹️","⏺️","⏭️","⏮️","⏩","⏪","⏫","⏬","◀️","🔼","🔽","➡️","⬅️","⬆️","⬇️","↗️","↘️","↙️","↖️","↕️","↔️","↪️","↩️","⤴️"],ut=q=>{const Ne=/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,ee=[];let _e;for(;(_e=Ne.exec(q))!==null;)if(_e[1]){const Le=_e.index+_e[0].length,We=q.slice(Le),Me=q[Le];(We.startsWith("@")||!Me||/\s|[.,!?;:]|@/.test(Me))&&ee.push(_e[1].trim())}return ee},Tt=q=>{q.key==="Enter"&&!q.shiftKey&&(q.preventDefault(),X())},cs=(q,Ne)=>{A(ee=>ee.map(_e=>{if(_e.id===q){const Le=_e.reactions||[],We=Le.find(Me=>Me.emoji===Ne);if(We)if(We.users.includes("You")){if(We.users=We.users.filter(Me=>Me!=="You"),We.users.length===0)return{..._e,reactions:Le.filter(Me=>Me.emoji!==Ne)}}else We.users.push("You");else Le.push({emoji:Ne,users:["You"]});return{..._e,reactions:Le}}return _e}))};return e.jsxs("div",{className:"h-full flex flex-col bg-gray-50 overflow-hidden",children:[e.jsx("div",{className:"bg-white border-b border-gray-200 px-3 sm:px-6 py-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-4 min-w-0 flex-1",children:[e.jsx("div",{className:"w-10 h-10 sm:w-12 sm:h-12 bg-gradient-to-br from-blue-500 to-purple-600 rounded-xl flex items-center justify-center shadow-lg shrink-0",children:e.jsx(Ds,{className:"w-5 h-5 sm:w-6 sm:h-6 text-white"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h1",{className:"text-lg sm:text-2xl font-bold text-gray-900",children:"Work Notes"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("p",{className:"text-gray-600 text-sm sm:text-base truncate",children:le.title}),e.jsx(oe,{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:[Te.slice(0,3).map((q,Ne)=>e.jsx(ts,{className:"h-8 w-8 ring-2 ring-white shadow-sm",children:e.jsx(ss,{className:"bg-blue-500 text-white text-xs font-semibold",children:q.avatar})},Ne)),Te.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:["+",Te.length-3]})]})}),e.jsx(F,{variant:"outline",size:"sm",onClick:()=>_(!N),className:"lg:hidden",children:e.jsx(ps,{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(Es,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Ie,{placeholder:"Search messages...",value:f,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:[Ve.map(q=>{const Ne=q.isCurrentUser||!1;return e.jsxs("div",{className:`flex gap-2 sm:gap-3 lg:gap-4 ${q.isSystem?"justify-center":Ne?"justify-end":""}`,children:[!q.isSystem&&!Ne&&e.jsx(ts,{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(ss,{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:`${Ne?"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(It,{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:as(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 ${Ne?"justify-end":""}`,children:[e.jsxs("span",{className:"font-semibold text-gray-900 text-sm sm:text-base truncate",children:[q.user.name," ",Ne&&e.jsx("span",{className:"text-xs text-gray-500 font-normal",children:"(you)"})]}),e.jsx(oe,{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(nt,{className:"w-3 h-3"}),as(q.timestamp)]}),q.isHighPriority&&e.jsxs(oe,{variant:"destructive",className:"text-xs flex-shrink-0",children:[e.jsx(Vf,{className:"w-3 h-3 mr-1"}),"Priority"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 sm:p-4 shadow-sm ${Ne?"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:SA(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((ee,_e)=>{const Le=ee.fileSize||ee.file_size,We=ee.fileName||ee.file_name||ee.name,Me=ee.fileType||ee.file_type||ee.type||"",qe=ee.attachmentId||ee.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(Ju,{type:Me})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs sm:text-sm font-medium text-gray-700 truncate",children:We}),Le&&e.jsx("p",{className:"text-xs text-gray-500",children:AA(Le)})]}),qe&&(()=>{const He=(Me||"").toLowerCase();return He.includes("image")||He.includes("pdf")||He.includes("jpg")||He.includes("jpeg")||He.includes("png")||He.includes("gif")})()&&e.jsx(F,{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:He=>{He.preventDefault(),He.stopPropagation();const at=TN(qe);B({fileName:We,fileType:Me,fileUrl:at,fileSize:Le,attachmentId:qe})},title:"Preview file",children:e.jsx(bt,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),e.jsx(F,{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 He=>{if(He.preventDefault(),He.stopPropagation(),!qe){K.error("Cannot download: Attachment ID missing");return}try{await Sm(qe)}catch{K.error("Failed to download file")}},title:"Download file",children:e.jsx(At,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]},_e)})})}),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((ee,_e)=>e.jsxs("button",{onClick:()=>cs(q.id,ee.emoji),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs sm:text-sm transition-colors flex-shrink-0 ${ee.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:ee.emoji}),e.jsx("span",{className:"text-xs font-medium",children:ee.users.length})]},_e)),e.jsx(F,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-7 sm:w-7 p-0 flex-shrink-0",onClick:()=>C(!v),children:e.jsx(gs,{className:"w-2 h-2 sm:w-3 sm:h-3"})})]})]})]})}),!q.isSystem&&Ne&&e.jsx(ts,{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(ss,{className:"bg-blue-500 text-white font-semibold text-xs sm:text-sm",children:q.user.avatar})})]},q.id)}),e.jsx("div",{ref:W})]})}),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:G,onChange:me,className:"hidden",multiple:!0,accept:$.allowedFileTypes.map(q=>`.${q}`).join(",")}),T.length>0&&e.jsx("div",{className:"mb-3 space-y-2 max-h-32 overflow-y-auto pr-2",children:T.map((q,Ne)=>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(Ju,{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(F,{variant:"ghost",size:"sm",onClick:()=>J(Ne),className:"h-6 w-6 p-0 hover:bg-red-100 flex-shrink-0",children:e.jsx(ft,{className:"h-3 w-3 text-red-600"})})]},Ne))}),e.jsxs("div",{className:"relative mb-2",children:[(()=>{const q=g.lastIndexOf("@"),Ne=q>=0;if(!Ne)return null;const ee=g.slice(q+1),_e=ee.trim(),Le=ee.endsWith(" "),We=_e.length>0,Me=_e.includes(" ")&&!Le,qe=Le&&We;if(!(Ne&&ee.length<=20&&!Me&&!qe))return null;const at=_e.toLowerCase(),Ss=ue.filter(Kt=>Kt.userId===j?!1:at?Kt.name.toLowerCase().includes(at):!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:Ss.length>0?Ss.map((Kt,ct)=>e.jsxs("button",{type:"button",onClick:rt=>{rt.preventDefault(),rt.stopPropagation();const St=g.lastIndexOf("@"),ds=g.slice(0,St);b(ds+"@"+Kt.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(ts,{className:"h-10 w-10",children:e.jsx(ss,{className:`text-white text-sm font-semibold ${Kt.role==="Initiator"?"bg-green-600":Kt.role==="Approver"?"bg-purple-600":"bg-blue-500"}`,children:Kt.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:Kt.name}),e.jsx("p",{className:"text-xs text-gray-600",children:Kt.role})]})]},ct)):e.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:at?`No participants found matching "${at}"`:"No other participants available"})})]})})(),e.jsx(_s,{placeholder:"Type your message... Use @username to mention someone",value:g,onChange:q=>b(q.target.value),onKeyPress:Tt,className:"min-h-[50px] sm:min-h-[60px] resize-none border-gray-200 focus:ring-blue-500 focus:border-blue-500 w-full text-sm",rows:2}),v&&e.jsxs("div",{className:"absolute bottom-full left-0 mb-2 bg-white border border-gray-200 rounded-lg shadow-xl p-3 z-50 w-full sm:w-96 max-h-80 overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 sticky top-0 bg-white pb-2 border-b",children:[e.jsx("span",{className:"text-sm font-semibold text-gray-700",children:"Pick an emoji"}),e.jsx(F,{variant:"ghost",size:"sm",onClick:()=>C(!1),className:"h-6 w-6 p-0",children:e.jsx(ft,{className:"h-3 w-3"})})]}),e.jsx("div",{className:"grid grid-cols-8 sm:grid-cols-10 gap-1",children:vt.map((q,Ne)=>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},Ne))})]})]}),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(F,{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:Be,title:"Attach file",children:e.jsx(ji,{className:"h-4 w-4"})}),e.jsx(F,{variant:"ghost",size:"sm",className:"text-gray-500 h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600 flex-shrink-0",onClick:()=>C(!v),title:"Add emoji",children:e.jsx(zf,{className:"h-4 w-4"})}),e.jsx(F,{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:()=>b(q=>q+"@"),title:"Mention someone",children:e.jsx(Si,{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:[g.length,"/2000"]}),e.jsxs(F,{onClick:X,disabled:!g.trim()&&T.length===0,className:"bg-blue-600 hover:bg-blue-700 h-8 sm:h-9 px-3 sm:px-4 disabled:opacity-50 disabled:cursor-not-allowed flex-shrink-0",size:"sm",children:[e.jsx(Px,{className:"h-4 w-4 sm:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Send"})]})]})]})]})})]}),N&&e.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 z-40 lg:hidden",onClick:()=>_(!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(F,{variant:"ghost",size:"sm",onClick:()=>_(!1),className:"lg:hidden h-8 w-8 p-0",children:e.jsx(ft,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-3 sm:space-y-4 overflow-y-auto flex-1 pr-2",children:ue.map((q,Ne)=>{const ee=q.userId===j;return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ts,{className:"h-9 w-9 sm:h-10 sm:w-10",children:e.jsx(ss,{className:`text-white font-semibold text-sm ${q.role==="Initiator"?"bg-green-600":ee?"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 ${wA(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," ",ee&&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:CA(q.status)})]}),q.lastSeen&&q.status==="offline"&&e.jsx("p",{className:"text-xs text-gray-400",children:q.lastSeen})]})]},Ne)})})]}),!Qe&&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(F,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>D(!0),children:[e.jsx(Ci,{className:"h-4 w-4"}),"Add Approver"]}),e.jsxs(F,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>L(!0),children:[e.jsx(bt,{className:"h-4 w-4"}),"Add Spectator"]})]})]})]})]}),P&&e.jsx(Nr,{fileName:P.fileName,fileType:P.fileType,fileUrl:P.fileUrl,fileSize:P.fileSize,attachmentId:P.attachmentId,onDownload:Sm,open:!!P,onClose:()=>B(null)}),!Qe&&e.jsx(bg,{open:k,onClose:()=>L(!1),onConfirm:Ee,requestIdDisplay:u,requestTitle:le.title,existingParticipants:Q}),!Qe&&l&&e.jsx(yg,{open:V,onClose:()=>D(!1),onConfirm:ze,requestIdDisplay:u,requestTitle:le.title,existingParticipants:Q,currentLevels:c,maxApprovalLevels:m,onPolicyViolation:h}),e.jsx(ht,{open:H.open,onOpenChange:q=>je(Ne=>({...Ne,open:q})),children:e.jsxs(dt,{className:"sm:max-w-lg",children:[e.jsxs(pt,{children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(Ye,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Pt,{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:H.errors.map((q,Ne)=>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})]},Ne))}),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(Rt,{children:e.jsx(F,{onClick:()=>je({open:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(fg,{open:S,onClose:()=>O(!1),success:I.success,title:I.title,message:I.message})]})}function TA({requestId:t,requestTitle:s,mergedMessages:a,setWorkNoteAttachments:r,isInitiator:n,isSpectator:i,currentLevels:l,onAddApprover:o,maxApprovalLevels:c,onPolicyViolation:d}){return e.jsx("div",{className:"h-[calc(100vh-300px)] min-h-[600px]",children:e.jsx(vg,{requestId:t,requestTitle:s,skipSocketJoin:!0,messages:a,onAttachmentsExtracted:r,isInitiator:n,isSpectator:i,currentLevels:l,onAddApprover:o,maxApprovalLevels:c,onPolicyViolation:d})})}function kA({summary:t,loading:s,onShare:a,isInitiator:r}){const n=o=>{const c=o.toLowerCase();return c==="approved"?e.jsx(Re,{className:"h-4 w-4 text-green-600"}):c==="rejected"?e.jsx(Ct,{className:"h-4 w-4 text-red-600"}):c==="pending"||c==="in progress"?e.jsx(nt,{className:"h-4 w-4 text-orange-600"}):e.jsx(ke,{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(it,{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(F,{variant:"outline",size:"sm",onClick:a,className:"flex items-center gap-2",children:[e.jsx(Sn,{className:"w-4 h-4"}),e.jsx("span",{children:"Share"})]}):e.jsxs(oe,{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(Bs,{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:Ge(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:Ge(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"}),o.remarks?e.jsx(Bs,{content:o.remarks,className:"text-sm text-gray-700"}):e.jsx("p",{className:"text-sm text-gray-700",children:"—"})]})]},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(oe,{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(Bs,{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(ke,{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 RA({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(Ha,{className:"h-4 w-4 text-gray-600"}):s==="approved"?e.jsx(Re,{className:"h-4 w-4 text-green-600"}):s==="rejected"?e.jsx(Ct,{className:"h-4 w-4 text-red-600"}):e.jsx(nt,{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(Ha,{className:`h-4 w-4 ${c.icon}`}):e.jsx(nt,{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(oe,{className:`text-xs ${c.badge}`,"data-testid":`${r}-badge`,children:[i,"% elapsed ",a&&"(frozen)"]})]}),e.jsx(oa,{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:[Mt(t.elapsedHours||0)," elapsed"]}),e.jsxs("span",{className:`font-semibold ${d==="breached"||d==="critical"?c.text:"text-gray-700"}`,"data-testid":`${r}-remaining`,children:[Mt(t.remainingHours||0)," remaining"]})]}),t.deadline&&e.jsxs("p",{className:"text-xs text-gray-500","data-testid":`${r}-deadline`,children:["Due: ",ga(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(os,{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(li,{className:"h-3.5 w-3.5"}),"URGENT - Deadline Passed"]})]})}function DA({request:t,refreshing:s,onBack:a,onRefresh:r,onShareSummary:n,isInitiator:i,slaData:l,isPaused:o=!1}){var m;const c=yA((t==null?void 0:t.priority)||"standard"),d=vA((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(F,{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(Cs,{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(ke,{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(oe,{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(oe,{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 h=(t==null?void 0:t.workflowType)||(t==null?void 0:t.workflow_type),x=(t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"",u=(x==null?void 0:x.toUpperCase())||"",g=h==="CLAIM_MANAGEMENT"||h==="DEALER_CLAIM"||x==="claim-management"||u==="DEALER CLAIM"||u==="DEALER_CLAIM";let b="Non-Templatized",f="bg-purple-100 !text-purple-600 border-purple-200";return g?(b="Dealer Claim",f="bg-blue-100 !text-blue-700 border-blue-200"):u==="TEMPLATE"&&(b="Template"),e.jsx(oe,{className:`${f} rounded-full px-2 sm:px-3 text-xs shrink-0`,variant:"outline","data-testid":"template-type-badge",children:b})})()]})]})]})]}),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(F,{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(Sn,{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(F,{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(Ut,{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(RA,{sla:l,requestStatus:t.status,isPaused:o,testId:"request-sla"})})]})}async function yc(t){return(await ve.get(`/summaries/${t}`)).data.data}async function PA(t,s){return(await ve.post(`/summaries/${t}/share`,{userIds:s})).data.data}async function IA(t={}){var n,i;const{page:s=1,limit:a=20}=t,r=await ve.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 jg(t){await ve.patch(`/summaries/shared/${t}/view`)}async function Ng(t){var s;try{return(await ve.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 EA(t){return(await ve.get(`/summaries/${t}/recipients`)).data.data||[]}function FA({activityInfo:t,className:s,createdAt:a,updatedAt:r}){if(!t)return console.warn("[ActivityInformationCard] activityInfo is missing"),e.jsx(se,{className:s,children:e.jsx(ae,{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 Ge(new Date(l),"MMM d, yyyy")}catch{return l}};return e.jsxs(se,{className:s,children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center gap-2 text-base",children:[e.jsx(xt,{className:"w-5 h-5 text-blue-600"}),"Activity Information"]})}),e.jsxs(ae,{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(fo,{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!==void 0&&t.estimatedBudget!==null?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(Yt,{className:"w-4 h-4 text-blue-600"}),n(t.closedExpensesBreakdown&&t.closedExpensesBreakdown.length>0?t.closedExpensesBreakdown.reduce((l,o)=>l+(o.totalAmt||Number(o.amount)+Number(o.gstAmt||0)),0):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.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg overflow-hidden",children:e.jsxs("table",{className:"w-full text-xs sm:text-sm",children:[e.jsx("thead",{className:"bg-blue-100/50",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2 text-left font-semibold text-blue-900",children:"Description"}),e.jsx("th",{className:"px-3 py-2 text-right font-semibold text-blue-900 w-24",children:"Base"}),e.jsx("th",{className:"px-3 py-2 text-right font-semibold text-blue-900 w-24",children:"GST"}),e.jsx("th",{className:"px-3 py-2 text-right font-semibold text-blue-900 w-28",children:"Total"})]})}),e.jsxs("tbody",{className:"divide-y divide-blue-200/50",children:[t.closedExpensesBreakdown.map((l,o)=>e.jsxs("tr",{className:"hover:bg-blue-100/30",children:[e.jsxs("td",{className:"px-3 py-2 text-gray-700",children:[l.description,l.gstRate?e.jsxs("span",{className:"text-[10px] text-gray-400 block",children:[l.gstRate,"% GST"]}):null]}),e.jsx("td",{className:"px-3 py-2 text-right text-gray-900",children:n(l.amount)}),e.jsx("td",{className:"px-3 py-2 text-right text-gray-900",children:n(l.gstAmt||0)}),e.jsx("td",{className:"px-3 py-2 text-right font-medium text-gray-900",children:n(l.totalAmt||Number(l.amount)+Number(l.gstAmt||0))})]},o)),e.jsxs("tr",{className:"bg-blue-100/50 font-bold",children:[e.jsx("td",{colSpan:3,className:"px-3 py-2 text-blue-900",children:"Final Claim Amount"}),e.jsx("td",{className:"px-3 py-2 text-right text-blue-700",children:n(t.closedExpensesBreakdown.reduce((l,o)=>l+(o.totalAmt||Number(o.amount)+Number(o.gstAmt||0)),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(Bs,{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:as(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:as(r)})]})]})]})]})}function _A({dealerInfo:t,className:s}){return t?!t.dealerCode&&!t.dealerName?(console.warn("[DealerInformationCard] Dealer info missing essential fields:",t),e.jsx(se,{className:s,children:e.jsx(ae,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Dealer information incomplete"})})})):e.jsxs(se,{className:s,children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ai,{className:"w-5 h-5 text-purple-600"}),"Dealer Information"]})}),e.jsxs(ae,{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(Da,{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(Ni,{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(fo,{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(se,{className:s,children:e.jsx(ae,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Dealer information not available"})})}))}function LA({ioDetails:t,dmsDetails:s,claimAmount:a,estimatedBudgetBreakdown:r,closedExpensesBreakdown:n,visibility:i,onEditClaimAmount:l,className:o}){const c=x=>x==null||Number.isNaN(x)?"₹0.00":`₹${x.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,d=x=>{if(!x)return"";try{return Ge(new Date(x),"MMM d, yyyy, h:mm a")}catch{return x||""}},m=x=>!x||x.length===0?0:x.reduce((u,g)=>u+(g.totalAmt??g.amount+(g.gstAmt??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(se,{className:`bg-gradient-to-br from-blue-50 to-purple-50 border-2 border-blue-200 ${o}`,children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"text-base flex items-center gap-2",children:[e.jsx(It,{className:"w-4 h-4 text-blue-600"}),"Process Details"]}),e.jsx(Ue,{children:"Workflow reference numbers"})]}),e.jsxs(ae,{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(Yt,{className:"w-4 h-4 text-blue-600"}),e.jsx(ne,{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(It,{className:"w-4 h-4 text-purple-600"}),e.jsx(ne,{className:"text-xs font-semibold text-purple-900 uppercase tracking-wide",children:"E-Invoice Details"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3 mb-2",children:s.ackNo&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"Ack No"}),e.jsx("p",{className:"font-bold text-sm text-purple-700",children:s.ackNo})]})}),s.irn&&e.jsxs("div",{className:"mb-2 p-2 bg-purple-50 rounded border border-purple-100",children:[e.jsx("p",{className:"text-[10px] text-purple-600 uppercase font-semibold",children:"IRN"}),e.jsx("p",{className:"text-[10px] font-mono break-all text-gray-700 leading-tight",children:s.irn})]}),s.signedInvoiceUrl&&e.jsxs(F,{variant:"outline",size:"sm",className:"w-full h-8 text-xs gap-2 mb-2 border-purple-200 text-purple-700 hover:bg-purple-50",onClick:()=>window.open(s.signedInvoiceUrl,"_blank"),children:[e.jsx(Yt,{className:"w-3.5 h-3.5"}),"View E-Invoice"]}),s.remarks&&e.jsxs("div",{className:"pt-2 border-t border-purple-100",children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase 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-[10px] text-gray-500",children:["By ",s.createdByName]}),e.jsx("p",{className:"text-[10px] 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(ne,{className:"text-xs font-semibold text-green-900 uppercase tracking-wide",children:"Claim Amount"})]}),i.canEditClaimAmount&&l&&e.jsxs(F,{variant:"outline",size:"sm",onClick:l,className:"h-7 px-2 text-xs border-green-300 hover:bg-green-50",children:[e.jsx(oi,{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(Yt,{className:"w-4 h-4 text-amber-600"}),e.jsx(ne,{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((x,u)=>e.jsxs("div",{className:"flex justify-between items-center text-[10px] sm:text-xs",children:[e.jsx("div",{className:"text-gray-700 truncate mr-2",title:x.description,children:x.description}),e.jsx("span",{className:"font-medium text-gray-900 whitespace-nowrap",children:c(x.totalAmt??x.amount+(x.gstAmt??0))})]},u)),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(Yt,{className:"w-4 h-4 text-indigo-600"}),e.jsx(ne,{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((x,u)=>e.jsxs("div",{className:"flex justify-between items-center text-[10px] sm:text-xs",children:[e.jsx("div",{className:"text-gray-700 truncate mr-2",title:x.description,children:x.description}),e.jsx("span",{className:"font-medium text-gray-900 whitespace-nowrap",children:c(x.totalAmt??x.amount+(x.gstAmt??0))})]},u)),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 MA({proposalDetails:t,className:s}){const r=(()=>{const o=t.totalEstimatedBudget??t.estimatedBudgetTotal;return o??(t.costBreakup&&t.costBreakup.length>0?t.costBreakup.reduce((d,m)=>{const h=m.amount||0,x=m.gstAmt||0,u=m.totalAmt||Number(h)+Number(x);return d+(Number.isNaN(u)?0:u)},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 Ge(new Date(o),"MMM d, yyyy, h:mm a")}catch{return o||""}},l=o=>{if(!o)return"-";try{return Ge(new Date(o),"MMM d, yyyy")}catch{return o||"-"}};return e.jsxs(se,{className:s,children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2 text-base",children:[e.jsx(Yt,{className:"w-5 h-5 text-green-600"}),"Proposal Details"]}),t.submittedOn&&e.jsxs(Ue,{children:["Submitted on ",i(t.submittedOn)]})]}),e.jsxs(ae,{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:"Base Amount"}),e.jsx("th",{className:"px-4 py-2 text-right text-xs font-semibold text-gray-700 uppercase tracking-wide",children:"GST"}),e.jsx("th",{className:"px-4 py-2 text-right text-xs font-semibold text-gray-700 uppercase tracking-wide",children:"Total"})]})}),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.jsxs("td",{className:"px-4 py-3 text-sm text-gray-900",children:[e.jsx("div",{children:o.description}),o.gstRate?e.jsx("div",{className:"text-[10px] text-gray-400",children:o.cgstAmt?`CGST: ${o.gstRate/2}%, SGST: ${o.gstRate/2}%`:`IGST: ${o.gstRate}%`}):null]}),e.jsx("td",{className:"px-4 py-3 text-sm text-gray-900 text-right",children:n(o.amount)}),e.jsx("td",{className:"px-4 py-3 text-sm text-gray-900 text-right",children:n(o.gstAmt)}),e.jsx("td",{className:"px-4 py-3 text-sm text-gray-900 text-right font-medium",children:n(o.totalAmt||Number(o.amount||0)+Number(o.gstAmt||0))})]},c)),e.jsxs("tr",{className:"bg-green-50 font-semibold",children:[e.jsx("td",{colSpan:3,className:"px-4 py-3 text-sm text-gray-900",children:"Estimated Budget (Total Inclusive of GST)"}),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(xt,{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 $A({initiatorInfo:t,className:s}){const a=r=>r.split(" ").map(n=>n[0]).join("").toUpperCase().slice(0,2);return e.jsxs(se,{className:s,children:[e.jsx(ge,{children:e.jsx(fe,{className:"text-base",children:"Request Initiator"})}),e.jsx(ae,{children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(ts,{className:"h-14 w-14 ring-2 ring-white shadow-md",children:e.jsx(ss,{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(Da,{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(Ni,{className:"w-4 h-4"}),e.jsx("span",{children:t.phone})]})]})]})]})})]})}function vc(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 wg(t,s){var a,r;try{if(!vc(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||{},h=t.completionExpenses||t.completion_expenses||[],x=n.periodStartDate||n.period_start_date,u=n.periodEndDate||n.period_end_date,g=n.activityName||n.activity_name||"",b=n.activityType||n.activity_type||"",f=n.location||"",y=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),C=v!=null?Number(v):void 0,w=Array.isArray(h)&&h.length>0?h.map(P=>({description:P.description||P.itemDescription||P.item_description||"",amount:Number(P.amount)||0,gstRate:P.gstRate??P.gst_rate,gstAmt:P.gstAmt??P.gst_amt,cgstAmt:P.cgstAmt??P.cgst_amt,sgstAmt:P.sgstAmt??P.sgst_amt,igstAmt:P.igstAmt??P.igst_amt,totalAmt:P.totalAmt??P.total_amt})):(l==null?void 0:l.closedExpenses)||(l==null?void 0:l.closed_expenses)||(l==null?void 0:l.closedExpensesBreakdown)||[],A={activityName:g,activityType:b,defaultGstRate:n.defaultGstRate||18,requestedDate:n.activityDate||n.activity_date||t.createdAt,location:f,period:x&&u?{startDate:x,endDate:u}:void 0,estimatedBudget:y,closedExpenses:C,closedExpensesBreakdown:w,description:t.description||""},N={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)||""};(!N.dealerCode||!N.dealerName)&&console.warn("[claimDataMapper] Dealer information is missing from claimDetails:",{hasClaimDetails:!!n,dealerCode:N.dealerCode,dealerName:N.dealerName,rawClaimDetails:n,availableKeys:n?Object.keys(n):[]});const _=(i==null?void 0:i.expectedCompletionDate)||(i==null?void 0:i.expected_completion_date),T=i?{proposalDocumentUrl:i.proposalDocumentUrl||i.proposal_document_url,costBreakup:Array.isArray(i.costItems||i.cost_items)?(i.costItems||i.cost_items).map(P=>({description:P.description||P.itemDescription||P.item_description||"",amount:Number(P.amount)||0,gstRate:Number(P.gstRate??P.gst_rate??0),gstAmt:Number(P.gstAmt??P.gst_amt??0),cgstAmt:Number(P.cgstAmt??P.cgst_amt??0),sgstAmt:Number(P.sgstAmt??P.sgst_amt??0),igstAmt:Number(P.igstAmt??P.igst_amt??0),totalAmt:Number(P.totalAmt??P.total_amt??0)})):Array.isArray(i.costBreakup||i.cost_breakup)?(i.costBreakup||i.cost_breakup).map(P=>({description:P.description||P.itemDescription||P.item_description||"",amount:Number(P.amount)||0,gstRate:P.gstRate??P.gst_rate,gstAmt:P.gstAmt??P.gst_amt,cgstAmt:P.cgstAmt??P.cgst_amt,sgstAmt:P.sgstAmt??P.sgst_amt,igstAmt:P.igstAmt??P.igst_amt,totalAmt:P.totalAmt??P.total_amt})):[],totalEstimatedBudget:i.totalEstimatedBudget||i.total_estimated_budget||0,timelineMode:i.timelineMode||i.timeline_mode,expectedCompletionDate:_,expectedCompletionDays:i.expectedCompletionDays||i.expected_completion_days,timelineForClosure:_,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||""},j={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,irn:d.irn||n.irn,ackNo:d.ackNo||n.ackNo,ackDate:d.ackDate||n.ackDate,signedInvoiceUrl:d.signedInvoiceUrl||n.signedInvoiceUrl,taxBreakdown:d.taxBreakdown||n.taxBreakdown},E={estimated:A.estimatedBudget||0,closed:A.closedExpenses||0};return{activityInfo:A,dealerInfo:N,proposalDetails:T,ioDetails:Object.keys(R).some(P=>R[P])?R:void 0,dmsDetails:Object.keys(j).some(P=>j[P])?j:void 0,claimAmount:E}}catch(n){return console.error("[claimDataMapper] Error mapping claim data:",n),null}}function Cg(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 Sg(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 OA({request:t,isInitiator:s,isSpectator:a,currentApprovalLevel:r,onAddApprover:n,onAddSpectator:i,onApprove:l,onReject:o,onPause:c,onResume:d,onRetrigger:m,summaryId:h,refreshTrigger:x,pausedByUserId:u,currentUserId:g,apiRequest:b,onEditClaimAmount:f}){var V,D,S,O,I;const{user:y}=Jt(),[v,C]=p.useState([]),[w,A]=p.useState(!1),[N,_]=p.useState(!1),T=(t==null?void 0:t.status)==="closed",R=((V=t==null?void 0:t.pauseInfo)==null?void 0:V.isPaused)||!1,j=u||((S=(D=t==null?void 0:t.pauseInfo)==null?void 0:D.pausedBy)==null?void 0:S.userId),E=g||(y==null?void 0:y.userId)||"",P=!R&&!T&&(r||s),B=R&&d&&(r||s),k=R&&s&&j&&j!==E&&m;p.useEffect(()=>{if(!R||!r||!(t!=null&&t.requestId)){_(!1);return}(async()=>{var W;try{const te=(((W=(await Ga.list({page:1,limit:50,unreadOnly:!0})).data)==null?void 0:W.notifications)||[]).some($=>$.requestId===t.requestId&&$.notificationType==="pause_retrigger_request");_(te)}catch(G){console.error("Failed to check retrigger notifications:",G),_(!1)}})()},[R,r,t==null?void 0:t.requestId,x]),p.useEffect(()=>{(async()=>{if(!T||!h||!s){C([]);return}try{A(!0);const W=await EA(h);C(W)}catch(W){console.error("Failed to fetch shared recipients:",W),C([])}finally{A(!1)}})()},[T,h,s,x]);const L=p.useMemo(()=>{if(!b||!vc(b))return null;const M=wg(b);if(!M)return null;const W=Cg(b,E),G=Sg(W);return{claimRequest:M,visibility:G}},[b,E]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[!a&&t.status!=="closed"&&e.jsxs(se,{"data-testid":"quick-actions-card",children:[e.jsx(ge,{className:"pb-2",children:e.jsx(fe,{className:"text-sm sm:text-base",children:"Quick Actions"})}),e.jsxs(ae,{className:"space-y-2",children:[s&&t.status!=="closed"&&e.jsxs(F,{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(Ci,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Add Approver"]}),t.status!=="closed"&&e.jsxs(F,{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"]}),P&&c&&e.jsxs(F,{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(Ka,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Pause Workflow"]}),B&&e.jsxs(F,{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(ii,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Resume Workflow"]}),k&&e.jsxs(F,{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(Ye,{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(F,{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(Re,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Approve Request"]}),e.jsxs(F,{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(Ct,{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:j===E?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-xs text-orange-800 font-medium flex items-center justify-center gap-1.5",children:[N&&e.jsx(Ye,{className:"w-3.5 h-3.5"}),N?"Initiator has requested you to resume":"You paused this workflow"]}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:N?"Please review and resume if appropriate":'Click "Resume Workflow" to continue'})]}):r&&j!==E&&N?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(Ye,{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&&j!==E?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-orange-800 font-medium",children:"Workflow is paused"}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:"You can resume to continue approval"})]}):s&&j&&j!==E?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-orange-800 font-medium",children:"Approver has paused this workflow"}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:k?'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(se,{"data-testid":"spectators-card",children:[e.jsx(ge,{className:"pb-2",children:e.jsx(fe,{className:"text-sm sm:text-base",children:"Spectators"})}),e.jsx(ae,{className:"space-y-3",children:t.spectators&&t.spectators.length>0?t.spectators.map((M,W)=>e.jsxs("div",{className:"flex items-center gap-3","data-testid":`spectator-${W}`,children:[e.jsx(ts,{className:"h-8 w-8",children:e.jsx(ss,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:M.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:M.name}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:M.role})]})]},W)):e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"No spectators added"})})})]}),T&&s&&e.jsxs(se,{"data-testid":"shared-recipients-card",children:[e.jsx(ge,{className:"pb-2",children:e.jsxs(fe,{className:"text-sm sm:text-base flex items-center gap-2",children:[e.jsx(Sn,{className:"w-4 h-4"}),"Summary Shared With"]})}),e.jsx(ae,{className:"space-y-3",children:w?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((M,W)=>{const G=(M.displayName||"NA").split(" ").map(re=>re[0]).join("").slice(0,2).toUpperCase();return e.jsxs("div",{className:"flex items-center gap-3","data-testid":`shared-recipient-${W}`,children:[e.jsx(ts,{className:"h-8 w-8",children:e.jsx(ss,{className:"bg-green-100 text-green-800 text-xs font-semibold",children:G})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:M.displayName}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:M.email}),M.isRead&&e.jsx("p",{className:"text-xs text-green-600 mt-0.5",children:"Viewed"})]})]},M.userId||W)}):e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Summary not shared yet"})})})]}),L&&e.jsx(LA,{ioDetails:L.claimRequest.ioDetails,dmsDetails:L.claimRequest.dmsDetails,claimAmount:{amount:L.claimRequest.claimAmount.closed||L.claimRequest.claimAmount.estimated||0},estimatedBudgetBreakdown:(O=L.claimRequest.proposalDetails)==null?void 0:O.costBreakup,closedExpensesBreakdown:(I=L.claimRequest.activityInfo)==null?void 0:I.closedExpensesBreakdown,visibility:L.visibility,onEditClaimAmount:f})]})}function UA({open:t,onClose:s,onConfirm:a,defaultDescription:r="",title:n="Approve Request",requestIdDisplay:i,requestTitle:l}){const[o,c]=p.useState(r),[d,m]=p.useState(!1),h=(o==null?void 0:o.length)||0,x=p.useMemo(()=>o.slice(0,500),[o]),u=async()=>{try{m(!0),await a(x),s()}finally{m(!1)}};return e.jsx(ht,{open:t,onOpenChange:g=>!g&&s(),children:e.jsxs(dt,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(pt,{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(Re,{className:"w-7 h-7 text-green-600"})}),e.jsxs("div",{children:[e.jsx(mt,{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(oe,{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(_s,{value:x,onChange:g=>c(g.target.value),rows:5,placeholder:"Enter your approval comments and any conditions or notes...",className:"border-gray-300"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsx("span",{children:"Comments are required and will be visible to all participants"}),e.jsxs("span",{children:[Math.min(h,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(Re,{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(Rt,{className:"mt-4",children:[e.jsx(F,{variant:"outline",onClick:s,disabled:d,children:"Cancel"}),e.jsxs(F,{onClick:u,disabled:d,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(Re,{className:"w-4 h-4 mr-2"}),d?"Approving...":"Approve Request"]})]})]})})}function BA({open:t,onClose:s,onConfirm:a,defaultDescription:r="",title:n="Reject Request",requestIdDisplay:i,requestTitle:l}){const[o,c]=p.useState(r),[d,m]=p.useState(!1),h=(o==null?void 0:o.length)||0,x=p.useMemo(()=>o.slice(0,500),[o]),u=async()=>{if(!x.trim()){alert("Comments & remarks are required");return}try{m(!0),await a(x),s()}finally{m(!1)}};return e.jsx(ht,{open:t,onOpenChange:g=>!g&&s(),children:e.jsxs(dt,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(pt,{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(Ct,{className:"w-7 h-7 text-red-600"})}),e.jsxs("div",{children:[e.jsx(mt,{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(oe,{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(_s,{value:x,onChange:g=>c(g.target.value),rows:5,placeholder:"Enter detailed reasons for rejection and any suggestions for improvement...",className:"border-gray-300"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsx("span",{children:"Comments are required and will be visible to all participants"}),e.jsxs("span",{children:[Math.min(h,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(Ye,{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(Rt,{className:"mt-4",children:[e.jsx(F,{variant:"outline",onClick:s,disabled:d,children:"Cancel"}),e.jsxs(F,{variant:"destructive",onClick:u,disabled:d,children:[e.jsx(Ct,{className:"w-4 h-4 mr-2"}),d?"Rejecting...":"Reject Request"]})]})]})})}function VA({open:t,onClose:s,onConfirm:a,approverName:r,levelNumber:n,requestIdDisplay:i,requestTitle:l}){const[o,c]=p.useState(""),[d,m]=p.useState(!1),h=async()=>{if(o.trim())try{m(!0),await a(o.trim()),c(""),s()}catch(u){console.error("Failed to skip approver:",u)}finally{m(!1)}},x=()=>{d||(c(""),s())};return e.jsx(ht,{open:t,onOpenChange:x,children:e.jsxs(dt,{className:"sm:max-w-md max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:x,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:d,children:[e.jsx(ft,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(pt,{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(Ye,{className:"w-5 h-5 text-orange-600"})}),e.jsx(mt,{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(Ye,{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(ne,{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(ne,{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(ne,{htmlFor:"skip-reason",className:"text-sm font-semibold text-gray-700",children:"Reason for Skipping *"}),e.jsx(_s,{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:u=>c(u.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(F,{type:"button",variant:"outline",onClick:x,className:"flex-1 h-11 border-gray-300",disabled:d,children:"Cancel"}),e.jsxs(F,{type:"button",onClick:h,className:"flex-1 h-11 bg-orange-600 hover:bg-orange-700 text-white",disabled:d||!o.trim(),children:[e.jsx(Ye,{className:"w-4 h-4 mr-2"}),d?"Skipping...":"Skip Approver"]})]})]})})}function zA({showApproveModal:t,showRejectModal:s,showAddApproverModal:a,showAddSpectatorModal:r,showSkipApproverModal:n,showActionStatusModal:i,previewDocument:l,documentError:o,request:c,skipApproverData:d,actionStatus:m,existingParticipants:h,currentLevels:x,maxApprovalLevels:u,onPolicyViolation:g,setShowApproveModal:b,setShowRejectModal:f,setShowAddApproverModal:y,setShowAddSpectatorModal:v,setShowSkipApproverModal:C,setShowActionStatusModal:w,setPreviewDocument:A,setDocumentError:N,setSkipApproverData:_,setActionStatus:T,handleApproveConfirm:R,handleRejectConfirm:j,handleAddApprover:E,handleAddSpectator:P,handleSkipApprover:B,downloadDocument:k,documentPolicy:L}){return e.jsxs(e.Fragment,{children:[e.jsx(UA,{open:t,onClose:()=>b(!1),onConfirm:R,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(BA,{open:s,onClose:()=>f(!1),onConfirm:j,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(yg,{open:a,onClose:()=>y(!1),onConfirm:E,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:h,currentLevels:x,maxApprovalLevels:u,onPolicyViolation:g}),e.jsx(bg,{open:r,onClose:()=>v(!1),onConfirm:P,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:h}),e.jsx(VA,{open:n,onClose:()=>{C(!1),_(null)},onConfirm:B,approverName:d==null?void 0:d.approverName,levelNumber:d==null?void 0:d.levelNumber,requestIdDisplay:c.id,requestTitle:c.title}),l&&e.jsx(Nr,{fileName:l.fileName,fileType:l.fileType,fileUrl:Kr(l.documentId),fileSize:l.fileSize,attachmentId:l.documentId,onDownload:k,open:!!l,onClose:()=>A(null)}),m&&e.jsx(fg,{open:i,onClose:()=>{w(!1),T(null)},success:m.success,title:m.title,message:m.message}),e.jsx(ht,{open:o.show,onOpenChange:V=>N(D=>({...D,show:V})),children:e.jsxs(dt,{className:"sm:max-w-lg",children:[e.jsxs(pt,{children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(Ye,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Pt,{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((V,D)=>e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3",children:[e.jsx("p",{className:"font-medium text-red-900 text-sm",children:V.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:V.reason})]},D))}),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: ",L.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",L.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(Rt,{children:e.jsx(F,{onClick:()=>N({show:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const Ag={DocumentsTab:bA,ActivityTab:NA,WorkNotesTab:TA,SummaryTab:kA,RequestDetailHeader:DA,QuickActionsSidebar:OA,RequestDetailModals:zA};function HA({className:t,...s}){return e.jsx(Q0,{"data-slot":"checkbox",className:Ae("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(q0,{"data-slot":"checkbox-indicator",className:"flex items-center justify-center text-current transition-none",children:e.jsx(Ra,{className:"size-3.5"})})})}function Tg({isOpen:t,onClose:s,summaryId:a,requestTitle:r,onSuccess:n}){const[i,l]=p.useState(""),[o,c]=p.useState([]),[d,m]=p.useState(new Set),[h,x]=p.useState(!1),[u,g]=p.useState(!1);p.useEffect(()=>{if(!t){c([]);return}if(!i||!i.startsWith("@")||i.length<2){c([]),x(!1);return}const v=setTimeout(async()=>{var C;try{x(!0);const w=i.slice(1),A=await ca(w,10),N=((C=A==null?void 0:A.data)==null?void 0:C.data)||(A==null?void 0:A.data)||[];c(Array.isArray(N)?N:[])}catch(w){console.error("Failed to search users:",w),K.error("Failed to search users")}finally{x(!1)}},300);return()=>clearTimeout(v)},[i,t]);const b=v=>{m(C=>{const w=new Set(C);return w.has(v)?w.delete(v):w.add(v),w})},f=async()=>{var v,C;if(d.size===0){K.error("Please select at least one user to share with");return}try{g(!0),await PA(a,Array.from(d)),K.success(`Summary shared with ${d.size} user(s)`),m(new Set),l(""),c([]),n==null||n(),s()}catch(w){console.error("Failed to share summary:",w),K.error(((C=(v=w==null?void 0:w.response)==null?void 0:v.data)==null?void 0:C.message)||"Failed to share summary")}finally{g(!1)}},y=()=>{m(new Set),l(""),c([]),s()};return e.jsx(ht,{open:t,onOpenChange:y,children:e.jsxs(dt,{className:"sm:max-w-[500px]",children:[e.jsx(pt,{children:e.jsx(mt,{children:"Share Summary"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{children:[e.jsx(ne,{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(ne,{htmlFor:"user-search",className:"text-sm font-medium text-gray-700",children:"Search Users"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(Es,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(Ie,{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)"})]}),h&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(it,{className:"h-5 w-5 animate-spin text-blue-600"})}),!h&&o.length>0&&e.jsx("div",{className:"border rounded-lg max-h-[300px] overflow-y-auto",children:o.map(v=>{const C=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:()=>b(v.userId),children:[e.jsx("div",{onClick:w=>w.stopPropagation(),onMouseDown:w=>w.stopPropagation(),className:"flex items-center",children:e.jsx(HA,{checked:C,onCheckedChange:()=>b(v.userId)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gt,{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)})}),!h&&i&&i.startsWith("@")&&o.length===0&&e.jsx("div",{className:"text-center py-8 text-gray-500 text-sm",children:"No users found"}),!h&&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 C=o.find(w=>w.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:(C==null?void 0:C.displayName)||(C==null?void 0:C.email)||v}),e.jsx("button",{onClick:()=>b(v),className:"ml-1 hover:text-red-600",children:e.jsx(ft,{className:"h-3 w-3"})})]},v)})})]})]}),e.jsxs(Rt,{children:[e.jsx(F,{variant:"outline",onClick:y,disabled:u,children:"Cancel"}),e.jsx(F,{onClick:f,disabled:u||d.size===0,children:u?e.jsxs(e.Fragment,{children:[e.jsx(it,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):`Share with ${d.size} user(s)`})]})]})})}function kg({isOpen:t,onClose:s,requestId:a,levelId:r,onSuccess:n}){const[i,l]=p.useState(""),[o,c]=p.useState(""),[d,m]=p.useState(!1),h=()=>Ht().add(1,"month").format("YYYY-MM-DD"),x=()=>Ht().add(1,"month").format("YYYY-MM-DD"),u=()=>Ht().add(1,"day").format("YYYY-MM-DD");p.useEffect(()=>{t&&!o&&c(h())},[t]);const g=async()=>{var C,w,A,N;if(!i.trim()){K.error("Please provide a reason for pausing");return}if(!o){K.error("Please select a resume date");return}const f=Ht(o),y=Ht().add(1,"month"),v=Ht().add(1,"day");if(f.isAfter(y)){K.error("Resume date cannot be more than 1 month from now");return}if(f.isBefore(v,"day")){K.error("Resume date must be at least 1 day from now");return}try{m(!0),await CN(a,r,i.trim(),f.toDate()),K.success("Workflow paused successfully"),n&&await n(),l(""),c(h()),s()}catch(_){console.error("Failed to pause workflow:",_),K.error(((w=(C=_==null?void 0:_.response)==null?void 0:C.data)==null?void 0:w.error)||((N=(A=_==null?void 0:_.response)==null?void 0:A.data)==null?void 0:N.message)||"Failed to pause workflow")}finally{m(!1)}},b=()=>{d||(l(""),c(h()),s())};return e.jsx(ht,{open:t,onOpenChange:b,children:e.jsxs(dt,{className:"sm:max-w-[500px]",children:[e.jsx(pt,{children:e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(Ka,{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(ne,{htmlFor:"pause-reason",className:"text-sm font-medium",children:["Reason for Pausing ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(_s,{id:"pause-reason",value:i,onChange:f=>l(f.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(ne,{htmlFor:"resume-date",className:"text-sm font-medium",children:["Resume Date ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Ie,{id:"resume-date",type:"date",value:o,onChange:f=>c(f.target.value),min:u(),max:x(),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(Rt,{children:[e.jsx(F,{variant:"outline",onClick:b,disabled:d,children:"Cancel"}),e.jsx(F,{onClick:g,disabled:d||!i.trim()||!o,className:"bg-orange-600 hover:bg-orange-700 text-white",children:d?e.jsxs(e.Fragment,{children:[e.jsx(it,{className:"w-4 h-4 mr-2 animate-spin"}),"Pausing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ka,{className:"w-4 h-4 mr-2"}),"Pause Workflow"]})})]})]})})}function Rg({isOpen:t,onClose:s,requestId:a,onSuccess:r}){const[n,i]=p.useState(""),[l,o]=p.useState(!1),c=async()=>{var m,h,x,u;try{o(!0),await SN(a,n.trim()||void 0),K.success("Workflow resumed successfully"),r&&await r(),i(""),s()}catch(g){console.error("Failed to resume workflow:",g),K.error(((h=(m=g==null?void 0:g.response)==null?void 0:m.data)==null?void 0:h.error)||((u=(x=g==null?void 0:g.response)==null?void 0:x.data)==null?void 0:u.message)||"Failed to resume workflow")}finally{o(!1)}},d=()=>{l||(i(""),s())};return e.jsx(ht,{open:t,onOpenChange:d,children:e.jsxs(dt,{className:"sm:max-w-[500px]",children:[e.jsx(pt,{children:e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(ii,{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(ne,{htmlFor:"resume-notes",className:"text-sm font-medium",children:"Notes (Optional)"}),e.jsx(_s,{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(Rt,{children:[e.jsx(F,{variant:"outline",onClick:d,disabled:l,children:"Cancel"}),e.jsx(F,{onClick:c,disabled:l,className:"bg-green-600 hover:bg-green-700 text-white",children:l?e.jsxs(e.Fragment,{children:[e.jsx(it,{className:"w-4 h-4 mr-2 animate-spin"}),"Resuming..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ii,{className:"w-4 h-4 mr-2"}),"Resume Workflow"]})})]})]})})}function Dg({isOpen:t,onClose:s,requestId:a,approverName:r,onSuccess:n}){const[i,l]=p.useState(!1),o=async()=>{var c,d,m,h;try{l(!0),await AN(a),K.success("Retrigger request sent to approver"),n&&await n(),s()}catch(x){console.error("Failed to retrigger pause:",x),K.error(((d=(c=x==null?void 0:x.response)==null?void 0:c.data)==null?void 0:d.error)||((h=(m=x==null?void 0:x.response)==null?void 0:m.data)==null?void 0:h.message)||"Failed to send retrigger request")}finally{l(!1)}};return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-[450px]",children:[e.jsx(pt,{children:e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(Ye,{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(Rt,{children:[e.jsx(F,{variant:"outline",onClick:s,disabled:i,children:"Cancel"}),e.jsx(F,{onClick:o,disabled:i,className:"bg-orange-600 hover:bg-orange-700 text-white",children:i?e.jsxs(e.Fragment,{children:[e.jsx(it,{className:"w-4 h-4 mr-2 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ye,{className:"w-4 h-4 mr-2"}),"Send Request"]})})]})]})})}const{DocumentsTab:GA,ActivityTab:WA,WorkNotesTab:YA,SummaryTab:KA,RequestDetailHeader:XA,QuickActionsSidebar:ZA,RequestDetailModals:JA}=Ag;let QA=class extends p.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(os,{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(F,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(F,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}};function qA({requestId:t,onBack:s,dynamicRequests:a=[]}){var wr,La,sr,Ma,ar,$a,ba,Oa;const n=Fa().requestId||t||"",l=new URLSearchParams(window.location.search).get("tab")||"overview",[o,c]=p.useState(l),[d,m]=p.useState(!1),[h,x]=p.useState(null),[u,g]=p.useState(null),[b,f]=p.useState(!1),[y,v]=p.useState(0),[C,w]=p.useState(!1),[A,N]=p.useState(!1),[_,T]=p.useState(!1),[R,j]=p.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[E,P]=p.useState({open:!1,violations:[]}),{user:B}=Jt(),{request:k,apiRequest:L,loading:V,refreshing:D,refreshDetails:S,currentApprovalLevel:O,isSpectator:I,isInitiator:M,existingParticipants:W,accessDenied:G}=fc(n,a,B),{mergedMessages:re,unreadWorkNotes:te,workNoteAttachments:$,setWorkNoteAttachments:z}=xg(n,L,o,B),{uploadingDocument:H,triggerFileInput:je,previewDocument:le,setPreviewDocument:ue,documentPolicy:$e,documentError:Te,setDocumentError:Ve}=hg(L,S),{showApproveModal:Qe,setShowApproveModal:Fe,showRejectModal:Q,setShowRejectModal:pe,showAddApproverModal:Ce,setShowAddApproverModal:Oe,showAddSpectatorModal:X,setShowAddSpectatorModal:Z,showSkipApproverModal:me,setShowSkipApproverModal:J,showActionStatusModal:be,setShowActionStatusModal:Be,skipApproverData:Ee,setSkipApproverData:ze,actionStatus:vt,setActionStatus:ut,handleApproveConfirm:Tt,handleRejectConfirm:cs,handleAddApprover:q,handleSkipApprover:Ne,handleAddSpectator:ee}=gg(n,O,S),{conclusionRemark:_e,setConclusionRemark:Le,conclusionLoading:We,conclusionSubmitting:Me,aiGenerated:qe,handleGenerateConclusion:He,handleFinalizeConclusion:at,generationAttempts:Ss,generationFailed:Kt,maxAttemptsReached:ct}=pg(k,n,M,S,s,ut,Be);p.useEffect(()=>{(async()=>{var ms;try{const zs=await Qs("SYSTEM_SETTINGS"),rr=await Qs("WORKFLOW_SHARING"),nr=[...zs,...rr],ma={};nr.forEach(jt=>{ma[jt.configKey]=jt.configValue}),j({maxApprovalLevels:parseInt(ma.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(ma.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((ms=ma.ALLOW_ADD_SPECTATOR)==null?void 0:ms.toLowerCase())==="true",maxSpectators:parseInt(ma.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(zs){console.error("Failed to load system policy:",zs)}})()},[]),p.useEffect(()=>{const ms=new URLSearchParams(window.location.search).get("tab");ms&&c(ms)},[n]);const rt=()=>{S()},St=()=>{w(!0)},ds=()=>{N(!0)},Vt=async()=>{await S()},Ca=()=>{T(!0)},qs=async()=>{await S()},er=async()=>{await S()},da=async()=>{if(!(L!=null&&L.requestId)){K.error("Request ID not found");return}if(!h){K.error("Summary not available. Please ensure the request is closed and the summary has been generated.");return}m(!0)},kt=((k==null?void 0:k.status)==="approved"||(k==null?void 0:k.status)==="rejected")&&M,_a=(k==null?void 0:k.status)==="closed";p.useEffect(()=>{(async()=>{if(!_a||!(L!=null&&L.requestId)){g(null),x(null);return}try{f(!0);const ms=await Ng(L.requestId);if(ms!=null&&ms.summaryId){x(ms.summaryId);try{const zs=await yc(ms.summaryId);g(zs)}catch(zs){console.error("Failed to fetch summary details:",zs),g(null),x(null)}}else g(null),x(null)}catch{g(null),x(null)}finally{f(!1)}})()},[_a,L==null?void 0:L.requestId]);const tr=((k==null?void 0:k.approvalFlow)||[]).filter(Ft=>Ft&&typeof Ft.step=="number").map(Ft=>({levelNumber:Ft.step||0,approverName:Ft.approver||"Unknown",status:Ft.status||"pending",tatHours:Ft.tatHours||24}));return V&&!k&&!L?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(Ut,{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..."})]})}):G!=null&&G.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(Ex,{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:G.message}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsxs(F,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(Cs,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(F,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})}):k?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(XA,{request:k,refreshing:D,onBack:s||(()=>window.history.back()),onRefresh:rt,onShareSummary:da,isInitiator:M,slaData:((wr=k==null?void 0:k.summary)==null?void 0:wr.sla)||(k==null?void 0:k.sla)||null,isPaused:((La=k==null?void 0:k.pauseInfo)==null?void 0:La.isPaused)||!1}),e.jsxs(Ui,{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(Bi,{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(rs,{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(Fx,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Overview"})]}),_a&&u&&e.jsxs(rs,{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(_x,{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(rs,{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(na,{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(rs,{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(ke,{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(rs,{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(It,{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(rs,{value:"worknotes",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900 relative col-span-2 sm:col-span-1","data-testid":"tab-worknotes",children:[e.jsx(Ds,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Work Notes"}),te>0&&e.jsx(oe,{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:te>9?"9+":te})]})]})}),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(ns,{value:"overview",className:"mt-0","data-testid":"overview-tab-content",children:e.jsx(LN,{request:k,isInitiator:M,needsClosure:kt,conclusionRemark:_e,setConclusionRemark:Le,conclusionLoading:We,conclusionSubmitting:Me,aiGenerated:qe,handleGenerateConclusion:He,handleFinalizeConclusion:at,onPause:St,onResume:ds,onRetrigger:Ca,currentUserIsApprover:!!O,pausedByUserId:(Ma=(sr=k==null?void 0:k.pauseInfo)==null?void 0:sr.pausedBy)==null?void 0:Ma.userId,currentUserId:B==null?void 0:B.userId,generationAttempts:Ss,generationFailed:Kt,maxAttemptsReached:ct})}),_a&&e.jsx(ns,{value:"summary",className:"mt-0","data-testid":"summary-tab-content",children:e.jsx(KA,{summary:u,loading:b,onShare:da,isInitiator:M})}),e.jsx(ns,{value:"workflow",className:"mt-0",children:e.jsx(UN,{request:k,user:B,isInitiator:M,onSkipApprover:Ft=>{if(!Ft.levelId){alert("Level ID not available");return}ze(Ft),J(!0)},onRefresh:S})}),e.jsx(ns,{value:"documents",className:"mt-0",children:e.jsx(GA,{request:k,workNoteAttachments:$,uploadingDocument:H,documentPolicy:$e,triggerFileInput:je,setPreviewDocument:ue,downloadDocument:ws})}),e.jsx(ns,{value:"activity",className:"mt-0",children:e.jsx(WA,{request:k})}),e.jsx(ns,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:o!=="worknotes",children:e.jsx(YA,{requestId:n,requestTitle:k.title,mergedMessages:re,setWorkNoteAttachments:z,isInitiator:M,isSpectator:I,currentLevels:tr,onAddApprover:q,maxApprovalLevels:R.maxApprovalLevels,onPolicyViolation:Ft=>P({open:!0,violations:Ft})})})]}),o!=="worknotes"&&e.jsx(ZA,{request:k,isInitiator:M,isSpectator:I,currentApprovalLevel:O,onAddApprover:()=>Oe(!0),onAddSpectator:()=>Z(!0),onApprove:()=>Fe(!0),onReject:()=>pe(!0),onPause:St,onResume:ds,onRetrigger:Ca,summaryId:h,refreshTrigger:y,pausedByUserId:($a=(ar=k==null?void 0:k.pauseInfo)==null?void 0:ar.pausedBy)==null?void 0:$a.userId,currentUserId:B==null?void 0:B.userId,apiRequest:L})]})]})]})}),d&&h&&e.jsx(Tg,{isOpen:d,onClose:()=>m(!1),summaryId:h,requestTitle:(k==null?void 0:k.title)||"N/A",onSuccess:()=>{S(),v(Ft=>Ft+1)}}),C&&(L==null?void 0:L.requestId)&&e.jsx(kg,{isOpen:C,onClose:()=>w(!1),requestId:L.requestId,levelId:(O==null?void 0:O.levelId)||null,onSuccess:qs}),A&&(L==null?void 0:L.requestId)&&e.jsx(Rg,{isOpen:A,onClose:()=>N(!1),requestId:L.requestId,onSuccess:Vt}),_&&(L==null?void 0:L.requestId)&&e.jsx(Dg,{isOpen:_,onClose:()=>T(!1),requestId:L.requestId,approverName:(Oa=(ba=k==null?void 0:k.pauseInfo)==null?void 0:ba.pausedBy)==null?void 0:Oa.name,onSuccess:er}),e.jsx(JA,{showApproveModal:Qe,showRejectModal:Q,showAddApproverModal:Ce,showAddSpectatorModal:X,showSkipApproverModal:me,showActionStatusModal:be,previewDocument:le,documentError:Te,request:k,skipApproverData:Ee,actionStatus:vt,existingParticipants:W,currentLevels:tr,maxApprovalLevels:R.maxApprovalLevels,onPolicyViolation:Ft=>P({open:!0,violations:Ft}),setShowApproveModal:Fe,setShowRejectModal:pe,setShowAddApproverModal:Oe,setShowAddSpectatorModal:Z,setShowSkipApproverModal:J,setShowActionStatusModal:Be,setPreviewDocument:ue,setDocumentError:Ve,setSkipApproverData:ze,setActionStatus:ut,handleApproveConfirm:Tt,handleRejectConfirm:cs,handleAddApprover:q,handleAddSpectator:ee,handleSkipApprover:Ne,downloadDocument:ws,documentPolicy:$e}),e.jsx(Ln,{open:E.open,onClose:()=>P({open:!1,violations:[]}),violations:E.violations,policyDetails:{maxApprovalLevels:R.maxApprovalLevels,maxParticipants:R.maxParticipants,allowSpectators:R.allowSpectators,maxSpectators:R.maxSpectators}})]}):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(ke,{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(F,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(Cs,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(F,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})})}function eT(t){return e.jsx(QA,{children:e.jsx(qA,{...t})})}function tT({searchTerm:t,statusFilter:s,priorityFilter:a,templateTypeFilter:r,sortBy:n,sortOrder:i,onSearchChange:l,onStatusFilterChange:o,onPriorityFilterChange:c,onTemplateTypeFilterChange:d,onSortByChange:m,onSortOrderChange:h,onClearFilters:x,activeFiltersCount:u}){return e.jsxs(se,{className:"shadow-lg border-0",children:[e.jsx(ge,{className:"pb-3 sm:pb-4 px-3 sm:px-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("div",{className:"p-1.5 sm:p-2 bg-blue-100 rounded-lg",children:e.jsx(Qa,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(Ue,{className:"text-xs sm:text-sm",children:u>0&&e.jsxs("span",{className:"text-blue-600 font-medium",children:[u," filter",u>1?"s":""," active"]})})]})]}),u>0&&e.jsxs(F,{variant:"ghost",size:"sm",onClick:x,className:"text-red-600 hover:bg-red-50 gap-1 h-8 sm:h-9 px-2 sm:px-3",children:[e.jsx(ft,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Clear"})]})]})}),e.jsx(ae,{className:"space-y-3 sm:space-y-4 px-3 sm:px-6",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Es,{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(Ie,{placeholder:"Search requests, IDs...",value:t,onChange:g=>l(g.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(Ke,{value:a,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 focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Xe,{placeholder:"All Priorities"})}),e.jsxs(Je,{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(fa,{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(Ke,{value:s,onValueChange:o,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(Xe,{placeholder:"All Statuses"})}),e.jsxs(Je,{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(Ke,{value:r,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 focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Xe,{placeholder:"All Templates"})}),e.jsxs(Je,{children:[e.jsx(Y,{value:"all",children:"All Templates"}),e.jsx(Y,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(Y,{value:"DEALER CLAIM",children:"Dealer Claim"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ke,{value:n,onValueChange:g=>m(g),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(Xe,{placeholder:"Sort by"})}),e.jsxs(Je,{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(F,{variant:"outline",size:"sm",onClick:()=>h(i==="asc"?"desc":"asc"),className:"px-2 sm:px-3 h-9 sm:h-10 md:h-11",children:i==="asc"?e.jsx(Ti,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(ki,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function sT({searchTerm:t,priorityFilter:s,statusFilter:a,templateTypeFilter:r,sortBy:n,sortOrder:i,activeFiltersCount:l,onSearchChange:o,onPriorityChange:c,onStatusChange:d,onTemplateTypeChange:m,onSortByChange:h,onSortOrderChange:x,onClearFilters:u}){return e.jsxs(se,{className:"shadow-lg border-0","data-testid":"closed-requests-filters",children:[e.jsx(ge,{className:"pb-3 sm:pb-4 px-3 sm:px-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("div",{className:"p-1.5 sm:p-2 bg-blue-100 rounded-lg",children:e.jsx(Qa,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(Ue,{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(F,{variant:"ghost",size:"sm",onClick:u,className:"text-red-600 hover:bg-red-50 gap-1 h-8 sm:h-9 px-2 sm:px-3","data-testid":"closed-requests-clear-filters",children:[e.jsx(ft,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Clear"})]})]})}),e.jsx(ae,{className:"space-y-3 sm:space-y-4 px-3 sm:px-6",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Es,{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(Ie,{placeholder:"Search requests, IDs...",value:t,onChange:g=>o(g.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(Ke,{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(Xe,{placeholder:"All Priorities"})}),e.jsxs(Je,{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(fa,{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(Ke,{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(Xe,{placeholder:"Closure Type"})}),e.jsxs(Je,{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(Re,{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(Ct,{className:"w-4 h-4 text-red-600"}),e.jsx("span",{children:"Closed After Rejection"})]})})]})]}),e.jsxs(Ke,{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(Xe,{placeholder:"All Templates"})}),e.jsxs(Je,{children:[e.jsx(Y,{value:"all",children:"All Templates"}),e.jsx(Y,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(Y,{value:"DEALER CLAIM",children:"Dealer Claim"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ke,{value:n,onValueChange:g=>h(g),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(Xe,{placeholder:"Sort by"})}),e.jsxs(Je,{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(F,{variant:"outline",size:"sm",onClick:x,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(Ti,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(ki,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function aT({searchTerm:t,statusFilter:s,priorityFilter:a,templateTypeFilter:r,departmentFilter:n,slaComplianceFilter:i,initiatorFilter:l,approverFilter:o,approverFilterType:c,dateRange:d,customStartDate:m,customEndDate:h,showCustomDatePicker:x,departments:u,loadingDepartments:g,initiatorSearch:b,approverSearch:f,onSearchChange:y,onStatusChange:v,onPriorityChange:C,onTemplateTypeChange:w,onDepartmentChange:A,onSlaComplianceChange:N,onInitiatorChange:_,onApproverChange:T,onApproverTypeChange:R,onDateRangeChange:j,onCustomStartDateChange:E,onCustomEndDateChange:P,onShowCustomDatePickerChange:B,onApplyCustomDate:k,onClearFilters:L,hasActiveFilters:V}){return e.jsx(se,{className:"border-gray-200 shadow-md","data-testid":"user-all-requests-filters",children:e.jsx(ae,{className:"p-4 sm:p-6",children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qa,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),V&&e.jsx(oe,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),V&&e.jsxs(F,{variant:"ghost",size:"sm",onClick:L,className:"gap-2",children:[e.jsx(Ut,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Ps,{}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 lg:grid-cols-5 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative md:col-span-3 lg:col-span-1",children:[e.jsx(Es,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Ie,{placeholder:"Search requests...",value:t,onChange:D=>y(D.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(Ke,{value:s,onValueChange:v,children:[e.jsx(Ze,{className:"h-10","data-testid":"status-filter",children:e.jsx(Xe,{placeholder:"All Status"})}),e.jsxs(Je,{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(Ke,{value:a,onValueChange:C,children:[e.jsx(Ze,{className:"h-10","data-testid":"priority-filter",children:e.jsx(Xe,{placeholder:"All Priority"})}),e.jsxs(Je,{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(Ke,{value:r,onValueChange:w,children:[e.jsx(Ze,{className:"h-10","data-testid":"template-type-filter",children:e.jsx(Xe,{placeholder:"All Templates"})}),e.jsxs(Je,{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(Ke,{value:n,onValueChange:A,disabled:g||u.length===0,children:[e.jsx(Ze,{className:"h-10","data-testid":"department-filter",children:e.jsx(Xe,{placeholder:g?"Loading...":"All Departments"})}),e.jsxs(Je,{children:[e.jsx(Y,{value:"all",children:"All Departments"}),u.map(D=>e.jsx(Y,{value:D,children:D},D))]})]}),e.jsxs(Ke,{value:i,onValueChange:N,children:[e.jsx(Ze,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(Xe,{placeholder:"All SLA Status"})}),e.jsxs(Je,{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(ne,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:b.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:b.selectedUser.displayName||b.selectedUser.email}),e.jsx(F,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:b.handleClear,children:e.jsx(ft,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ie,{placeholder:"Search initiator...",value:b.searchQuery,onChange:D=>b.handleSearch(D.target.value),onFocus:()=>{b.searchResults.length>0&&b.setShowResults(!0)},onBlur:()=>setTimeout(()=>b.setShowResults(!1),200),className:"h-10","data-testid":"initiator-search-input"}),b.showResults&&b.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:b.searchResults.map(D=>e.jsx("button",{type:"button",onClick:()=>b.handleSelect(D),className:"w-full px-4 py-2 text-left hover:bg-gray-50",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-medium text-gray-900",children:D.displayName||D.email}),D.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:D.email})]})},D.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(ne,{className:"text-sm font-medium text-gray-700",children:"Approver"}),o!=="all"&&R&&e.jsxs(Ke,{value:c,onValueChange:D=>R(D),children:[e.jsx(Ze,{className:"h-7 w-32 text-xs",children:e.jsx(Xe,{})}),e.jsxs(Je,{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(F,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:f.handleClear,children:e.jsx(ft,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ie,{placeholder:"Search approver...",value:f.searchQuery,onChange:D=>f.handleSearch(D.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(D=>e.jsx("button",{type:"button",onClick:()=>f.handleSelect(D),className:"w-full px-4 py-2 text-left hover:bg-gray-50",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-medium text-gray-900",children:D.displayName||D.email}),D.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:D.email})]})},D.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(xt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ke,{value:d,onValueChange:D=>j(D),children:[e.jsx(Ze,{className:"w-[160px] h-10",children:e.jsx(Xe,{placeholder:"Date Range"})}),e.jsxs(Je,{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"})]})]}),d==="custom"&&e.jsxs(Xs,{open:x,onOpenChange:B,children:[e.jsx(Zs,{asChild:!0,children:e.jsxs(F,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(xt,{className:"w-4 h-4"}),m&&h?`${Ge(m,"MMM d, yyyy")} - ${Ge(h,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Js,{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(ne,{htmlFor:"start-date",children:"Start Date"}),e.jsx(Us,{value:m||null,onChange:D=>{const S=D?new Date(D):void 0;S?(E==null||E(S),h&&S>h&&(P==null||P(S))):E==null||E(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"end-date",children:"End Date"}),e.jsx(Us,{value:h||null,onChange:D=>{const S=D?new Date(D):void 0;S?(P==null||P(S),m&&S<m&&(E==null||E(S))):P==null||P(void 0)},minDate:m||void 0,maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(F,{size:"sm",onClick:k,disabled:!m||!h,className:"flex-1 bg-re-green hover:bg-re-green/90",children:"Apply Range"}),e.jsx(F,{size:"sm",variant:"outline",onClick:()=>{B==null||B(!1),E==null||E(void 0),P==null||P(void 0),j("month")},children:"Cancel"})]})]})})]})]})]})})})}function rT({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:h=!1,handleGenerateConclusion:x,handleFinalizeConclusion:u,generationAttempts:g=0,generationFailed:b=!1,maxAttemptsReached:f=!1}){var A,N,_,T,R,j,E,P,B;if(!vc(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 y=wg(s);if(!y)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."})]});const v=Cg(s,a),C=Sg(v),w={name:((A=s.initiator)==null?void 0:A.name)||((N=s.initiator)==null?void 0:N.displayName)||((_=s.initiator)==null?void 0:_.email)||"Unknown",role:((T=s.initiator)==null?void 0:T.role)||((R=s.initiator)==null?void 0:R.designation)||"Initiator",department:((j=s.initiator)==null?void 0:j.department)||s.department||"",email:((E=s.initiator)==null?void 0:E.email)||"N/A",phone:((P=s.initiator)==null?void 0:P.phone)||((B=s.initiator)==null?void 0:B.mobile)};return e.jsxs("div",{className:`space-y-6 ${i}`,children:[e.jsx(FA,{activityInfo:y.activityInfo,createdAt:s==null?void 0:s.createdAt,updatedAt:s==null?void 0:s.updatedAt}),e.jsx(_A,{dealerInfo:y.dealerInfo}),C.showProposalDetails&&y.proposalDetails&&e.jsx(MA,{proposalDetails:y.proposalDetails}),e.jsx($A,{initiatorInfo:w}),(s==null?void 0:s.status)==="closed"&&(s==null?void 0:s.conclusionRemark)&&e.jsxs(se,{children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2 text-base",children:[e.jsx(Re,{className:"w-5 h-5 text-gray-600"}),"Conclusion Remark"]}),e.jsx(Ue,{className:"mt-1 text-xs sm:text-sm",children:"Final summary of this closed request"})]}),e.jsxs(ae,{className:"pt-4",children:[e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-4",children:e.jsx(Bs,{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 ",as(s.closureDate)]}),e.jsxs("span",{children:["By ",w.name]})]})]})]}),l&&e.jsxs(se,{"data-testid":"conclusion-remark-card",children:[e.jsx(ge,{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(fe,{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(Re,{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(Ue,{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."})]}),x&&e.jsxs("div",{className:"flex flex-col items-end gap-1.5",children:[e.jsxs(F,{variant:"outline",size:"sm",onClick:x,disabled:d||f,className:"gap-2 shrink-0 h-9","data-testid":"generate-ai-conclusion-button",children:[e.jsx(Ut,{className:`w-3.5 h-3.5 ${d?"animate-spin":""}`}),h?"Regenerate":"Generate with AI"]}),h&&!f&&!b&&e.jsxs("span",{className:"text-[10px] text-gray-500 font-medium px-1",children:[2-g," attempts remaining"]})]})]})}),e.jsx(ae,{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(it,{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"}),h&&e.jsx("span",{className:"text-xs text-blue-600","data-testid":"ai-generated-label",children:"✓ System-generated suggestion (editable)"})]}),c&&e.jsx(Pn,{value:o,onChange:k=>c(k),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"})]})]}),u&&e.jsx("div",{className:"flex gap-3 justify-end pt-3 border-t",children:e.jsx(F,{onClick:u,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(it,{className:"w-4 h-4 mr-2 animate-spin"}),"Finalizing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Re,{className:"w-4 h-4 mr-2"}),"Finalize & Close Request"]})})})]})})]})]})}function nT({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]=p.useState(""),[h,x]=p.useState(!1),[u,g]=p.useState(null),b=async()=>{if(!d.trim()){K.error("Please provide approval comments");return}try{x(!0),g("approve"),await a(d),y(),s()}catch(C){console.error("Failed to approve request:",C),K.error("Failed to approve request. Please try again.")}finally{x(!1),g(null)}},f=async()=>{if(!d.trim()){K.error("Please provide rejection reason");return}try{x(!0),g("reject"),await r(d),y(),s()}catch(C){console.error("Failed to reject request:",C),K.error("Failed to reject request. Please try again.")}finally{x(!1),g(null)}},y=()=>{m(""),g(null)},v=()=>{h||(y(),s())};return t?e.jsx(ht,{open:t,onOpenChange:v,children:e.jsxs(dt,{className:"dealer-proposal-modal overflow-hidden flex flex-col max-w-3xl",children:[e.jsxs(pt,{className:"flex-shrink-0 pb-3 lg:pb-4 px-6 pt-4 lg:pt-6 border-b",children:[e.jsxs(mt,{className:"flex items-center gap-2 text-lg lg:text-xl",children:[e.jsx(Re,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"}),"Review Request"]}),e.jsxs(Pt,{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(ke,{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(Ds,{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(Bs,{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(_s,{placeholder:"Provide your evaluation comments, approval conditions, or rejection reasons...",value:d,onChange:C=>m(C.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(Ct,{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(Rt,{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(F,{variant:"outline",onClick:v,disabled:h,className:"border-2",children:"Cancel"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(F,{onClick:f,disabled:!d.trim()||h,variant:"destructive",className:"bg-red-600 hover:bg-red-700",children:h&&u==="reject"?"Rejecting...":e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"w-4 h-4 mr-2"}),"Reject"]})}),e.jsx(F,{onClick:b,disabled:!d.trim()||h,className:"bg-green-600 hover:bg-green-700 text-white",children:h&&u==="approve"?"Approving...":e.jsxs(e.Fragment,{children:[e.jsx(Re,{className:"w-4 h-4 mr-2"}),"Approve"]})})]})]})]})}):null}function iT({isOpen:t,onClose:s,onDownload:a,onSendToDealer:r,creditNoteData:n,dealerInfo:i,activityName:l,requestNumber:o,requestId:c,dueDate:d,taxationType:m}){const[h,x]=p.useState(!1),[u,g]=p.useState(!1),b=m==="Non GST"||m==="Non-GST",f=(n==null?void 0:n.creditNoteNumber)&&(n==null?void 0:n.creditNoteNumber)!=="",y=(n==null?void 0:n.creditNoteNumber)||"",v=n!=null&&n.creditNoteDate?as(n.creditNoteDate,{includeTime:!1,format:"short"}):"",C=(n==null?void 0:n.creditNoteAmount)||0,w=(n==null?void 0:n.status)||"PENDING",A=(i==null?void 0:i.dealerName)||"Jaipur Royal Enfield",N=(i==null?void 0:i.dealerCode)||"RE-JP-009",_=l||"Activity",T=o||"RE-REQ-2024-CM-101",R=d?as(d,{includeTime:!1,format:"short"}):"Jan 4, 2026",j=async()=>{if(a)try{x(!0),await a(),K.success("Credit note downloaded successfully")}catch(B){console.error("Failed to download credit note:",B),K.error("Failed to download credit note. Please try again.")}finally{x(!1)}else K.info("Credit note will be automatically saved to Documents tab")},E=async()=>{if(r)try{g(!0),await r(),K.success("Credit note sent to dealer successfully"),s()}catch(B){console.error("Failed to send credit note to dealer:",B),K.error("Failed to send credit note. Please try again.")}finally{g(!1)}else K.info("Email notification will be sent to dealer with credit note attachment")},P=B=>`₹${B.toLocaleString("en-IN",{minimumFractionDigits:0,maximumFractionDigits:0})}`;return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-lg lg:max-w-[1000px] max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(pt,{children:[e.jsxs(mt,{className:"font-semibold flex items-center gap-2 text-2xl flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yt,{className:"w-6 h-6 text-[--re-green]"}),"Credit Note from SAP"]}),m&&e.jsx(oe,{className:`ml-2 border-none shadow-sm ${b?"bg-indigo-600 text-white hover:bg-indigo-700":"bg-emerald-600 text-white hover:bg-emerald-700"}`,children:b?"Non-GST Claim":"GST Claim"})]}),e.jsx(Pt,{className:"text-base",children:"Review and send credit note to dealer"})]}),e.jsxs("div",{className:"space-y-5 py-4",children:[f?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(oe,{className:"bg-green-600 text-white px-4 py-2 text-base",children:[e.jsx(Re,{className:"w-4 h-4 mr-2"}),w==="APPROVED"?"Approved":w==="ISSUED"?"Issued":w==="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(ne,{className:"font-medium text-xs text-gray-600 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(Hf,{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(ne,{className:"font-medium text-xs text-gray-600 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(xt,{className:"w-3 h-3"}),"Issue Date"]}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:v})]})]})]}),e.jsxs("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-5",children:[e.jsxs(ne,{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:P(C)})]})]}):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(Yt,{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(Ai,{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(ne,{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:A})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(ne,{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(ne,{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:_})]})]})]}),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(ke,{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(ne,{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:T})]}),e.jsxs("div",{children:[e.jsx(ne,{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:R})]})]})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start gap-3",children:[e.jsx(ke,{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(Rt,{className:"flex-col-reverse gap-2 sm:flex-row flex items-center justify-between sm:justify-between",children:[e.jsx(F,{variant:"outline",onClick:s,disabled:h||u,className:"border-2",children:"Close"}),e.jsx("div",{className:"flex gap-2",children:f&&e.jsxs(e.Fragment,{children:[e.jsxs(F,{variant:"outline",onClick:j,disabled:h||u,className:"border-blue-600 text-blue-600 hover:bg-blue-50",children:[e.jsx(At,{className:"w-4 h-4 mr-2"}),h?"Downloading...":"Download"]}),e.jsxs(F,{onClick:E,disabled:h||u,className:"bg-green-600 hover:bg-green-700 text-white shadow-md",children:[e.jsx(Px,{className:"w-4 h-4 mr-2"}),u?"Sending...":"Send to Dealer"]})]})})]})]})})}const Er=(t,s)=>{if(!t)return{isValid:!0,message:""};const a=t.trim();if(!/^\d+$/.test(a))return{isValid:!1,message:"Code must contain only digits"};if(s){if(!a.startsWith("99"))return{isValid:!1,message:"SAC (Service) code must start with 99"};if(a.length!==6)return{isValid:!1,message:"SAC code must be exactly 6 digits"}}else{if(![4,6,8].includes(a.length))return{isValid:!1,message:"HSN code must be 4, 6, or 8 digits"};if(a.startsWith("99"))return{isValid:!1,message:"HSN code should not start with 99 (use SAC type for services)"}}return{isValid:!0,message:""}},lT={"01":"Jammu and Kashmir","02":"Himachal Pradesh","03":"Punjab","04":"Chandigarh","05":"Uttarakhand","06":"Haryana","07":"Delhi","08":"Rajasthan","09":"Uttar Pradesh",10:"Bihar",11:"Sikkim",12:"Arunachal Pradesh",13:"Nagaland",14:"Manipur",15:"Mizoram",16:"Tripura",17:"Meghalaya",18:"Assam",19:"West Bengal",20:"Jharkhand",21:"Odisha",22:"Chhattisgarh",23:"Madhya Pradesh",24:"Gujarat",25:"Daman and Diu",26:"Dadra and Nagar Haveli",27:"Maharashtra",29:"Karnataka",30:"Goa",31:"Lakshadweep Islands",32:"Kerala",33:"Tamil Nadu",34:"Pondicherry",35:"Andaman and Nicobar",36:"Telangana",37:"Andhra Pradesh",38:"Ladakh",97:"Others"},oT="33",cT=new Set(["04","25","26","31","35","38"]),Pg=t=>{if(!t||t.length<2)return null;const s=t.substring(0,2);return lT[s]?s:null},dT=t=>t?cT.has(t):!1,mT=t=>t?t!==oT:!1,Ig=t=>{if(!t)return{isIGST:!1,isCGST:!0,isSGST:!0,isUTGST:!1};if(mT(t))return{isIGST:!0,isCGST:!1,isSGST:!1,isUTGST:!1};const a=dT(t);return{isIGST:!1,isCGST:!0,isSGST:!a,isUTGST:a}};function uT({isOpen:t,onClose:s,onSubmit:a,dealerName:r="Jaipur Royal Enfield",dealerGSTIN:n,activityName:i="Activity",requestId:l,defaultGstRate:o=18,documentPolicy:c,taxationType:d}){var Oe,X;const[m,h]=p.useState(""),[x,u]=p.useState(""),g=p.useMemo(()=>{const Z=Pg(n);return Ig(Z)},[n]),b=p.useMemo(()=>d==="Non GST"||d==="Non-GST",[d]),[f,y]=p.useState([]),[v,C]=p.useState([]),[w,A]=p.useState([]),[N,_]=p.useState([]),[T,R]=p.useState(null),[j,E]=p.useState(""),[P,B]=p.useState(!1),[k,L]=p.useState(null),V=p.useRef(null),D=p.useRef(null),S=p.useRef(null),O=p.useRef(null),I=Z=>{const me=Z.type.toLowerCase(),J=Z.name.toLowerCase();return me.includes("image")||me.includes("pdf")||J.endsWith(".pdf")||J.endsWith(".jpg")||J.endsWith(".jpeg")||J.endsWith(".png")||J.endsWith(".gif")||J.endsWith(".webp")};p.useEffect(()=>()=>{k!=null&&k.url&&URL.revokeObjectURL(k.url)},[k]),p.useEffect(()=>{f.length===0&&y([{id:"1",description:"",amount:0,gstRate:o||0,gstAmt:0,quantity:1,hsnCode:"",isService:!1,cgstRate:0,cgstAmt:0,sgstRate:0,sgstAmt:0,igstRate:0,igstAmt:0,utgstRate:0,utgstAmt:0,cessRate:0,cessAmt:0,totalAmt:0}])},[o]);const M=Z=>{if(!I(Z)){K.error("Preview is only available for images and PDF files");return}k!=null&&k.url&&URL.revokeObjectURL(k.url);const me=URL.createObjectURL(Z);L({file:Z,url:me})},W=Z=>{const me=URL.createObjectURL(Z),J=document.createElement("a");J.href=me,J.download=Z.name,document.body.appendChild(J),J.click(),document.body.removeChild(J),URL.revokeObjectURL(me)},G=p.useMemo(()=>f.reduce((Z,me)=>Z+(me.totalAmt||me.amount||0),0),[f]),re=(Z,me,J=1)=>{const be=Z*J,Be=be*(me.cgstRate||0)/100,Ee=be*(me.sgstRate||0)/100,ze=be*(me.utgstRate||0)/100,vt=be*(me.igstRate||0)/100,ut=Be+Ee+ze+vt,Tt=be+ut;return{cgstRate:me.cgstRate,cgstAmt:Be,sgstRate:me.sgstRate,sgstAmt:Ee,utgstRate:me.utgstRate,utgstAmt:ze,igstRate:me.igstRate,igstAmt:vt,gstAmt:ut,gstRate:(me.cgstRate||0)+(me.sgstRate||0)+(me.utgstRate||0)+(me.igstRate||0),totalAmt:Tt}},te=p.useMemo(()=>{const Z=m!=="",me=v.length>0,J=w.length>0,be=j.trim().length>0,Be=b?!1:f.some(Ee=>{const{isValid:ze}=Er(Ee.hsnCode,Ee.isService);return!ze});return Z&&me&&J&&be&&!Be},[m,v,w,j,b,f]),$=new Date().toISOString().split("T")[0],z=()=>{y([...f,{id:Date.now().toString(),description:"",amount:0,gstRate:o||0,gstAmt:0,quantity:1,hsnCode:"",isService:!1,cgstRate:0,cgstAmt:0,sgstRate:0,sgstAmt:0,igstRate:0,igstAmt:0,utgstRate:0,utgstAmt:0,cessRate:0,cessAmt:0,totalAmt:0}])},H=(Z,me,J)=>{y(f.map(be=>{if(be.id===Z){let Be={...be,[me]:J};if(["amount","gstRate","cgstRate","sgstRate","utgstRate","igstRate","quantity"].includes(me)){const Ee=me==="amount"?parseFloat(J)||0:be.amount,ze=me==="quantity"?parseInt(J)||1:be.quantity;let vt=be.cgstRate,ut=be.sgstRate,Tt=be.utgstRate,cs=be.igstRate;if(me==="cgstRate"){if(!g.isCGST)return be;vt=parseFloat(J)||0,g.isUTGST?(Tt=vt,ut=0):(ut=vt,Tt=0),cs=0}else if(me==="sgstRate"){if(!g.isSGST)return be;ut=parseFloat(J)||0,vt=ut,Tt=0,cs=0}else if(me==="utgstRate"){if(!g.isUTGST)return be;Tt=parseFloat(J)||0,vt=Tt,ut=0,cs=0}else if(me==="igstRate"){if(!g.isIGST)return be;cs=parseFloat(J)||0,vt=0,ut=0,Tt=0}else if(me==="gstRate"){const Ne=parseFloat(J)||0;g.isIGST?(cs=Ne,vt=0,ut=0,Tt=0):(vt=Ne/2,g.isUTGST?(Tt=Ne/2,ut=0):(ut=Ne/2,Tt=0),cs=0)}const q=re(Ee,{cgstRate:vt,sgstRate:ut,igstRate:cs,utgstRate:Tt},ze);return{...Be,amount:Ee,quantity:ze,...q}}return Be}return be}))},je=Z=>{y(f.filter(me=>me.id!==Z))},le=Z=>{const me=Array.from(Z.target.files||[]);if(me.length>0){const J=[],be=c.maxFileSizeMB*1024*1024,Be=[".pdf",".doc",".docx",".zip",".rar"];me.forEach(Ee=>{var ut,Tt;const ze="."+((ut=Ee.name.split(".").pop())==null?void 0:ut.toLowerCase()),vt=((Tt=Ee.name.split(".").pop())==null?void 0:Tt.toLowerCase())||"";if(Ee.size>be){K.error(`"${Ee.name}" exceeds ${c.maxFileSizeMB}MB limit and was not added.`);return}if(!Be.includes(ze)){K.error(`"${Ee.name}" is not a supported document type (PDF, DOC, ZIP).`);return}if(!c.allowedFileTypes.includes(vt)){K.error(`"${Ee.name}" has an unallowed file type according to system policy.`);return}J.push(Ee)}),J.length>0&&C([...v,...J]),V.current&&(V.current.value="")}},ue=Z=>{C(v.filter((me,J)=>J!==Z))},$e=Z=>{const me=Array.from(Z.target.files||[]);if(me.length>0){const J=[],be=c.maxFileSizeMB*1024*1024;me.forEach(Be=>{var ze;const Ee=((ze=Be.name.split(".").pop())==null?void 0:ze.toLowerCase())||"";if(Be.size>be){K.error(`Photo "${Be.name}" exceeds ${c.maxFileSizeMB}MB limit.`);return}if(!Be.type.startsWith("image/")){K.error(`"${Be.name}" is not an image file.`);return}if(!c.allowedFileTypes.includes(Ee)){K.error(`"${Be.name}" has an unsupported image format.`);return}J.push(Be)}),J.length>0&&A([...w,...J]),D.current&&(D.current.value="")}},Te=Z=>{A(w.filter((me,J)=>J!==Z))},Ve=Z=>{const me=Array.from(Z.target.files||[]);if(me.length>0){const J=[],be=c.maxFileSizeMB*1024*1024,Be=[".pdf",".jpg",".jpeg",".png"];me.forEach(Ee=>{var ut,Tt;const ze="."+((ut=Ee.name.split(".").pop())==null?void 0:ut.toLowerCase()),vt=((Tt=Ee.name.split(".").pop())==null?void 0:Tt.toLowerCase())||"";if(Ee.size>be){K.error(`Invoice "${Ee.name}" exceeds ${c.maxFileSizeMB}MB limit.`);return}if(!Be.includes(ze)){K.error(`"${Ee.name}" is not a supported type (PDF, JPG, PNG).`);return}if(!c.allowedFileTypes.includes(vt)){K.error(`"${Ee.name}" format is not allowed by system policy.`);return}J.push(Ee)}),J.length>0&&_([...N,...J]),S.current&&(S.current.value="")}},Qe=Z=>{_(N.filter((me,J)=>J!==Z))},Fe=Z=>{var J,be,Be;const me=(J=Z.target.files)==null?void 0:J[0];if(me){const Ee=c.maxFileSizeMB*1024*1024,ze=[".pdf",".xlsx",".xls",".csv"],vt="."+((be=me.name.split(".").pop())==null?void 0:be.toLowerCase()),ut=((Be=me.name.split(".").pop())==null?void 0:Be.toLowerCase())||"";if(me.size>Ee){K.error(`Attendance file exceeds ${c.maxFileSizeMB}MB limit.`),O.current&&(O.current.value="");return}if(!ze.includes(vt)){K.error("Please upload PDF, Excel, or CSV files only"),O.current&&(O.current.value="");return}if(!c.allowedFileTypes.includes(ut)){K.error(`"${me.name}" format is not allowed by system policy.`),O.current&&(O.current.value="");return}R(me)}},Q=async()=>{if(!te){K.error("Please fill all required fields");return}const Z=f.filter(J=>J.description.trim()!==""&&J.amount>0);if(!b&&Z.some(J=>J.description.trim()!==""&&J.amount>0&&(J.gstRate===0||!J.gstRate))&&!window.confirm(`One or more expenses have 0% GST. Are you sure you want to proceed?
Note: If these items are taxable, please provide a valid GST rate to ensure correct E-Invoice generation.`)){B(!1);return}try{B(!0),await a({activityCompletionDate:m,numberOfParticipants:x?parseInt(x):void 0,closedExpenses:Z,totalClosedExpenses:G,completionDocuments:v,activityPhotos:w,invoicesReceipts:N.length>0?N:void 0,attendanceSheet:T||void 0,completionDescription:j}),pe(),s()}catch(J){console.error("Failed to submit completion documents:",J),bc(J)||K.error("Failed to submit completion documents. Please try again.")}finally{B(!1)}},pe=()=>{k!=null&&k.url&&URL.revokeObjectURL(k.url),L(null),h(""),u(""),y([{id:"1",description:"",amount:0,gstRate:o||0,gstAmt:0,quantity:1,hsnCode:"",isService:!1,cgstRate:0,cgstAmt:0,sgstRate:0,sgstAmt:0,igstRate:0,igstAmt:0,utgstRate:0,utgstAmt:0,cessRate:0,cessAmt:0,totalAmt:0}]),C([]),A([]),_([]),R(null),E(""),V.current&&(V.current.value=""),D.current&&(D.current.value=""),S.current&&(S.current.value=""),O.current&&(O.current.value="")},Ce=()=>{P||(pe(),s())};return e.jsxs(e.Fragment,{children:[e.jsx(ht,{open:t,onOpenChange:Ce,children:e.jsxs(dt,{className:"dealer-completion-documents-modal overflow-hidden flex flex-col",children:[e.jsxs(pt,{className:"px-6 pt-6 pb-3 flex-shrink-0",children:[e.jsxs(mt,{className:"font-semibold flex items-center gap-2 text-xl sm:text-2xl flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ks,{className:"w-5 h-5 sm:w-6 sm:h-6 text-[--re-green]"}),"Activity Completion Documents"]}),d&&e.jsx(oe,{className:`ml-2 border-none shadow-sm ${d==="GST"?"bg-emerald-600 text-white hover:bg-emerald-700":"bg-indigo-600 text-white hover:bg-indigo-700"}`,children:d==="GST"?"GST Claim":"Non-GST Claim"})]}),e.jsx(Pt,{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:"})," ",i]}),e.jsx("div",{className:"mt-2",children:"Please upload completion documents, photos, and provide details about the completed activity."})]})]}),e.jsxs("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",children:[e.jsxs("div",{className:"space-y-1.5 sm:space-y-2",children:[e.jsxs(ne,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",htmlFor:"completionDate",children:[e.jsx(xt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Activity Completion Date *"]}),e.jsx(Us,{value:m||null,onChange:Z=>h(Z||""),maxDate:$,placeholderText:"dd/mm/yyyy",className:"w-full max-w-[280px]",wrapperClassName:"max-w-[280px]"})]}),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(oe,{className:"bg-secondary text-secondary-foreground text-xs",children:"Optional"})]}),!b&&e.jsx("div",{className:"text-[10px] text-gray-500 italic mt-0.5",children:"Tax fields are automatically toggled based on the dealer's state (Inter-state vs Intra-state)."}),e.jsxs(F,{type:"button",onClick:z,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white",size:"sm",children:[e.jsx(gs,{className:"w-4 h-4 mr-1"}),"Add Expense"]})]}),e.jsx("div",{className:"space-y-3 sm:space-y-4 max-h-[400px] overflow-y-auto pr-1",children:f.map(Z=>e.jsxs("div",{className:"p-4 border rounded-lg bg-gray-50/50 space-y-4 relative group",children:[e.jsxs("div",{className:"flex gap-3 items-start w-full",children:[e.jsxs("div",{className:`${b?"flex-[3]":"flex-1"} min-w-0`,children:[e.jsx(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Item description"}),e.jsx(Ie,{placeholder:"e.g., Venue rental, Refreshments",value:Z.description,onChange:me=>H(Z.id,"description",me.target.value),className:"w-full bg-white text-sm"})]}),b&&e.jsxs("div",{className:"w-28 sm:w-36 flex-shrink-0",children:[e.jsx(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Amount"}),e.jsxs("div",{className:"relative",children:[e.jsx(Wa,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),e.jsx(Ie,{type:"number",placeholder:"0.00",min:"0",step:"0.01",value:Z.amount||"",onChange:me=>H(Z.id,"amount",me.target.value),className:"w-full bg-white text-sm pl-8"})]})]}),!b&&e.jsxs("div",{className:"w-28 sm:w-36 flex-shrink-0",children:[e.jsx(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Amount (Base)"}),e.jsxs("div",{className:"relative",children:[e.jsx(Wa,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),e.jsx(Ie,{type:"number",placeholder:"0.00",min:"0",step:"0.01",value:Z.amount||"",onChange:me=>H(Z.id,"amount",me.target.value),className:"w-full bg-white text-sm pl-8"})]})]}),!b&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"w-20 sm:w-24 flex-shrink-0",children:[e.jsx(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"HSN Code"}),e.jsx(Ie,{placeholder:"HSN",value:Z.hsnCode||"",onChange:me=>H(Z.id,"hsnCode",me.target.value),className:`w-full bg-white text-sm ${Er(Z.hsnCode,Z.isService).isValid?"":"border-red-500 focus-visible:ring-red-500"}`}),!Er(Z.hsnCode,Z.isService).isValid&&e.jsx("span",{className:"text-[9px] text-red-500 mt-1 block leading-tight",children:Er(Z.hsnCode,Z.isService).message})]}),e.jsxs("div",{className:"w-24 sm:w-28 flex-shrink-0",children:[e.jsx(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Item Type"}),e.jsxs("select",{value:Z.isService?"SAC":"HSN",onChange:me=>H(Z.id,"isService",me.target.value==="SAC"),className:"flex h-9 w-full rounded-md border border-input bg-white px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",children:[e.jsx("option",{value:"HSN",children:"HSN (Goods)"}),e.jsx("option",{value:"SAC",children:"SAC (Service)"})]})]}),e.jsxs("div",{className:"w-14 sm:w-16 flex-shrink-0",children:[e.jsx(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"CGST %"}),e.jsx(Ie,{type:"number",placeholder:"%",min:"0",max:"100",step:"0.1",value:Z.cgstRate||"",onChange:me=>H(Z.id,"cgstRate",me.target.value),disabled:!g.isCGST,className:"w-full bg-white text-xs px-1 text-center disabled:bg-gray-100 disabled:text-gray-400"})]}),e.jsxs("div",{className:"w-14 sm:w-16 flex-shrink-0",children:[e.jsx(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"SGST %"}),e.jsx(Ie,{type:"number",placeholder:"%",min:"0",max:"100",step:"0.1",value:Z.sgstRate||"",onChange:me=>H(Z.id,"sgstRate",me.target.value),disabled:!g.isSGST,className:"w-full bg-white text-xs px-1 text-center disabled:bg-gray-100 disabled:text-gray-400"})]}),e.jsxs("div",{className:"w-14 sm:w-16 flex-shrink-0",children:[e.jsx(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"UTGST %"}),e.jsx(Ie,{type:"number",placeholder:"%",min:"0",max:"100",step:"0.1",value:Z.utgstRate||"",onChange:me=>H(Z.id,"utgstRate",me.target.value),disabled:!g.isUTGST,className:"w-full bg-white text-xs px-1 text-center disabled:bg-gray-100 disabled:text-gray-400"})]}),e.jsxs("div",{className:"w-14 sm:w-16 flex-shrink-0",children:[e.jsx(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"IGST %"}),e.jsx(Ie,{type:"number",placeholder:"%",min:"0",max:"100",step:"0.1",value:Z.igstRate||"",onChange:me=>H(Z.id,"igstRate",me.target.value),disabled:!g.isIGST,className:"w-full bg-white text-xs px-1 text-center disabled:bg-gray-100 disabled:text-gray-400"})]})]}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:"mt-5 hover:bg-red-100 hover:text-red-700 flex-shrink-0 h-9 w-9 p-0",onClick:()=>je(Z.id),children:e.jsx(ft,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:`grid grid-cols-2 sm:grid-cols-5 gap-3 pt-3 border-t border-dashed border-gray-200 ${b?"items-center":""}`,children:[b?e.jsx("div",{className:"col-span-4 invisible"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap gap-4 text-gray-500 font-medium",children:[e.jsxs("span",{children:["CGST: ",e.jsxs("span",{className:"text-gray-900 font-semibold",children:["₹",(Z.cgstAmt||0).toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),Z.sgstAmt>0&&e.jsxs("span",{children:["SGST: ",e.jsxs("span",{className:"text-gray-900 font-semibold",children:["₹",(Z.sgstAmt||0).toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),Z.utgstAmt>0&&e.jsxs("span",{children:["UTGST: ",e.jsxs("span",{className:"text-gray-900 font-semibold",children:["₹",(Z.utgstAmt||0).toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),e.jsxs("span",{children:["IGST: ",e.jsxs("span",{className:"text-gray-900 font-semibold",children:["₹",(Z.igstAmt||0).toLocaleString("en-IN",{minimumFractionDigits:1})]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-4 items-center sm:justify-end",children:[e.jsxs("span",{className:"text-gray-500",children:["GST Total: ",e.jsxs("span",{className:"text-gray-900 font-bold",children:["₹",(Z.gstAmt||0).toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),e.jsxs(oe,{className:"bg-[#2d4a3e] text-white px-3 py-1 text-xs",children:["Item Total: ₹",(Z.totalAmt||0).toLocaleString("en-IN",{minimumFractionDigits:1})]})]})]}),e.jsxs("div",{className:"flex flex-col items-end",children:[e.jsx("span",{className:"text-[10px] text-gray-500 uppercase",children:"Item Total"}),e.jsxs("span",{className:"text-sm font-bold text-[#2d4a3e]",children:["₹",(Z.amount||0).toLocaleString("en-IN",{minimumFractionDigits:2})]})]})]})]},Z.id))}),f.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.'}),f.length>0&&G>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:["₹",G.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(oe,{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(ne,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",children:[e.jsx(ke,{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 ${v.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:V,type:"file",multiple:!0,accept:[".pdf",".doc",".docx",".zip",".rar"].filter(Z=>c.allowedFileTypes.includes(Z.replace(".",""))).join(","),className:"hidden",id:"completionDocs",onChange:le}),e.jsx("label",{htmlFor:"completionDocs",className:"cursor-pointer flex flex-col items-center gap-2",children:v.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Ws,{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:[v.length," document",v.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(Ks,{className:"w-8 h-8 text-gray-400"}),e.jsxs("span",{className:"text-sm text-gray-600",children:["Click to upload documents (Max ",c.maxFileSizeMB,"MB)"]}),e.jsx("p",{className:"text-[10px] text-gray-400",children:"PDF, DOC, ZIP allowed"})]})})]}),v.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 (",v.length,"):"]}),v.map((Z,me)=>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(ke,{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:Z.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[I(Z)&&e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>M(Z),title:"Preview file",children:e.jsx(bt,{className:"w-3.5 h-3.5"})}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>W(Z),title:"Download file",children:e.jsx(At,{className:"w-3.5 h-3.5"})}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>ue(me),title:"Remove document",children:e.jsx(ft,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},me))]})]}),e.jsxs("div",{children:[e.jsxs(ne,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",children:[e.jsx(Yn,{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 ${w.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:D,type:"file",multiple:!0,accept:[".jpg",".jpeg",".png",".gif",".webp"].filter(Z=>c.allowedFileTypes.includes(Z.replace(".",""))).join(","),className:"hidden",id:"completionPhotos",onChange:$e}),e.jsx("label",{htmlFor:"completionPhotos",className:"cursor-pointer flex flex-col items-center gap-2",children:w.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Ws,{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:[w.length," photo",w.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(Yn,{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)"})]})})]}),w.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 (",w.length,"):"]}),w.map((Z,me)=>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(Yn,{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:Z.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[I(Z)&&e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>M(Z),title:"Preview photo",children:e.jsx(bt,{className:"w-3.5 h-3.5"})}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>W(Z),title:"Download photo",children:e.jsx(At,{className:"w-3.5 h-3.5"})}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>Te(me),title:"Remove photo",children:e.jsx(ft,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},me))]})]})]})]}),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(oe,{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(ne,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",children:[e.jsx(Yt,{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 ${N.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:S,type:"file",multiple:!0,accept:[".pdf",".jpg",".jpeg",".png"].filter(Z=>c.allowedFileTypes.includes(Z.replace(".",""))).join(","),className:"hidden",id:"invoiceReceipts",onChange:Ve}),e.jsx("label",{htmlFor:"invoiceReceipts",className:"cursor-pointer flex flex-col items-center gap-2",children:N.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Ws,{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:[N.length," document",N.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(Yt,{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)"})]})})]}),N.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 (",N.length,"):"]}),N.map((Z,me)=>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(Yt,{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:Z.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[I(Z)&&e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>M(Z),title:"Preview file",children:e.jsx(bt,{className:"w-3.5 h-3.5"})}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>W(Z),title:"Download file",children:e.jsx(At,{className:"w-3.5 h-3.5"})}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>Qe(me),title:"Remove document",children:e.jsx(ft,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},me))]})]}),e.jsxs("div",{children:[e.jsx(ne,{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 ${T?"border-blue-500 bg-blue-50 hover:border-blue-600":"border-gray-300 hover:border-blue-500 bg-white"}`,children:[e.jsx("input",{ref:O,type:"file",accept:[".pdf",".xlsx",".xls",".csv"].filter(Z=>c.allowedFileTypes.includes(Z.replace(".",""))).join(","),className:"hidden",id:"attendanceDoc",onChange:Fe}),e.jsx("label",{htmlFor:"attendanceDoc",className:"cursor-pointer flex flex-col items-center gap-2",children:T?e.jsxs(e.Fragment,{children:[e.jsx(Ws,{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:T.name}),e.jsx("span",{className:"text-xs text-blue-600",children:"Document selected"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ks,{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)"})]})})]}),T&&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(ke,{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:T.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[I(T)&&e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>M(T),title:"Preview file",children:e.jsx(bt,{className:"w-3.5 h-3.5"})}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>W(T),title:"Download file",children:e.jsx(At,{className:"w-3.5 h-3.5"})}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>{R(null),O.current&&(O.current.value="")},title:"Remove document",children:e.jsx(ft,{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(ne,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",htmlFor:"completionDescription",children:"Brief Description of Completion *"}),e.jsx(_s,{id:"completionDescription",placeholder:"Provide a brief description of the completed activity, including key highlights, outcomes, challenges faced, and any relevant observations...",value:j,onChange:Z=>E(Z.target.value),className:"min-h-[100px] sm:min-h-[120px] text-sm"}),e.jsxs("p",{className:"text-xs text-gray-500",children:[j.length," characters"]})]}),!te&&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(Ye,{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(Rt,{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(F,{variant:"outline",onClick:Ce,disabled:P,className:"border-2",children:"Cancel"}),e.jsx(F,{onClick:Q,disabled:P||!te,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white disabled:bg-gray-300 disabled:text-gray-500",children:P?"Submitting...":"Submit Documents"})]})]})}),k&&e.jsx(ht,{open:!!k,onOpenChange:()=>{k!=null&&k.url&&URL.revokeObjectURL(k.url),L(null)},children:e.jsx(dt,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(pt,{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(mt,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:k.file.name}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[k.file.type||"Unknown type"," • ",(k.file.size/1024).toFixed(1)," KB"]})]})]}),e.jsx("div",{className:"flex items-center gap-2 flex-wrap mr-2",children:e.jsxs(F,{variant:"outline",size:"sm",onClick:()=>W(k.file),className:"gap-2 h-9",children:[e.jsx(At,{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:(Oe=k.file.type)!=null&&Oe.includes("image")?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("img",{src:k.url,alt:k.file.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"},className:"rounded-lg shadow-lg"})}):(X=k.file.type)!=null&&X.includes("pdf")||k.file.name.toLowerCase().endsWith(".pdf")?e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("iframe",{src:k.url,className:"w-full h-full rounded-lg border-0",title:k.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(F,{onClick:()=>W(k.file),className:"gap-2",children:[e.jsx(At,{className:"h-4 w-4"}),"Download ",k.file.name]})]})})]})})})]})}function xT({isOpen:t,onClose:s,onSubmit:a,dealerName:r="Jaipur Royal Enfield",dealerGSTIN:n,activityName:i="Activity",requestId:l,previousProposalData:o,defaultGstRate:c=18,documentPolicy:d,taxationType:m}){const[h,x]=p.useState(null),u=p.useMemo(()=>{const Q=Pg(n);return Ig(Q)},[n]),g=p.useMemo(()=>m==="Non GST"||m==="Non-GST",[m]),[b,f]=p.useState([{id:"1",description:"",amount:0,gstRate:c||0,gstAmt:0,quantity:1,hsnCode:"",isService:!1,cgstRate:0,cgstAmt:0,sgstRate:0,sgstAmt:0,igstRate:0,igstAmt:0,utgstRate:0,utgstAmt:0,cessRate:0,cessAmt:0,totalAmt:0}]),y=(Q,pe,Ce=1)=>{const Oe=Q*Ce,X=Oe*(pe.cgstRate||0)/100,Z=Oe*(pe.sgstRate||0)/100,me=Oe*(pe.utgstRate||0)/100,J=Oe*(pe.igstRate||0)/100,be=X+Z+me+J,Be=Oe+be;return{cgstRate:pe.cgstRate,cgstAmt:X,sgstRate:pe.sgstRate,sgstAmt:Z,utgstRate:pe.utgstRate,utgstAmt:me,igstRate:pe.igstRate,igstAmt:J,gstAmt:be,gstRate:(pe.cgstRate||0)+(pe.sgstRate||0)+(pe.utgstRate||0)+(pe.igstRate||0),totalAmt:Be}},[v,C]=p.useState("date"),[w,A]=p.useState(""),[N,_]=p.useState(""),[T,R]=p.useState([]),[j,E]=p.useState(""),[P,B]=p.useState(!1),[k,L]=p.useState(null),[V,D]=p.useState(!1),S=p.useRef(null),O=p.useRef(null),I=Q=>{if(!Q)return!1;const pe=Q.toLowerCase();return pe.endsWith(".pdf")||!!pe.match(/\.(jpg|jpeg|png|gif|webp)$/i)},M=Q=>I(Q.name);p.useEffect(()=>()=>{k!=null&&k.fileUrl&&k.fileUrl.startsWith("blob:")&&URL.revokeObjectURL(k.fileUrl)},[k]);const W=Q=>{if(!M(Q)){K.error("Preview is only available for images and PDF files");return}k!=null&&k.fileUrl&&k.fileUrl.startsWith("blob:")&&URL.revokeObjectURL(k.fileUrl);const pe=URL.createObjectURL(Q);L({fileName:Q.name,fileType:Q.type,documentId:"",fileUrl:pe,fileSize:Q.size})},G=Q=>{const pe=Q.originalFileName||Q.fileName||Q.name||"Document",Ce=Q.documentId||Q.id||"",Oe=pe.toLowerCase().endsWith(".pdf")?"application/pdf":"image/jpeg";let X="";if(Ce)X=Kr(Ce);else if(X=Q.storageUrl||Q.documentUrl||"",X&&!X.startsWith("http")){const Z="https://reflow-uat.royalenfield.com",me=Z.endsWith("/")?Z.slice(0,-1):Z,J=X.startsWith("/")?X:`/${X}`;X=`${me}${J}`}L({fileName:pe,fileType:Oe,documentId:Ce,fileUrl:X})},re=Q=>{const pe=URL.createObjectURL(Q),Ce=document.createElement("a");Ce.href=pe,Ce.download=Q.name,document.body.appendChild(Ce),Ce.click(),document.body.removeChild(Ce),URL.revokeObjectURL(pe)},te=p.useMemo(()=>b.reduce((Q,pe)=>Q+(pe.totalAmt||pe.amount||0),0),[b]),$=p.useMemo(()=>{const Q=h!==null,pe=b.length>0&&b.every(Z=>Z.description.trim()!==""&&Z.amount>0),Ce=v==="date"?w!=="":N!==""&&parseInt(N)>0,Oe=j.trim().length>0,X=g?!1:b.some(Z=>{const{isValid:me}=Er(Z.hsnCode,Z.isService);return!me});return Q&&pe&&Ce&&Oe&&!X},[h,b,v,w,N,j,g]),z=Q=>{var Ce,Oe,X;const pe=(Ce=Q.target.files)==null?void 0:Ce[0];if(pe){const Z=d.maxFileSizeMB*1024*1024;if(pe.size>Z){K.error(`File size exceeds the maximum allowed size of ${d.maxFileSizeMB}MB. Current size: ${(pe.size/(1024*1024)).toFixed(2)}MB`),S.current&&(S.current.value="");return}const me=[".pdf",".doc",".docx"],J="."+((Oe=pe.name.split(".").pop())==null?void 0:Oe.toLowerCase()),be=((X=pe.name.split(".").pop())==null?void 0:X.toLowerCase())||"";if(!me.includes(J)||!d.allowedFileTypes.includes(be)){K.error("Please upload a valid PDF, DOC, or DOCX file as per system policy"),S.current&&(S.current.value="");return}x(pe)}},H=Q=>{const pe=Array.from(Q.target.files||[]),Ce=[],Oe=d.maxFileSizeMB*1024*1024;pe.forEach(X=>{var me;if(X.size>Oe){K.error(`"${X.name}" exceeds ${d.maxFileSizeMB}MB limit and was not added.`);return}const Z=((me=X.name.split(".").pop())==null?void 0:me.toLowerCase())||"";if(!d.allowedFileTypes.includes(Z)){K.error(`"${X.name}" has an unsupported file type and was not added.`);return}Ce.push(X)}),Ce.length>0&&R(X=>[...X,...Ce]),O.current&&(O.current.value="")},je=()=>{f(Q=>[...Q,{id:Date.now().toString(),description:"",amount:0,gstRate:c||0,gstAmt:0,quantity:1,hsnCode:"",isService:!1,cgstRate:0,cgstAmt:0,sgstRate:0,sgstAmt:0,igstRate:0,igstAmt:0,utgstRate:0,utgstAmt:0,cessRate:0,cessAmt:0,totalAmt:0}])},le=Q=>{b.length>1&&f(pe=>pe.filter(Ce=>Ce.id!==Q))},ue=(Q,pe,Ce)=>{f(Oe=>Oe.map(X=>{if(X.id===Q){let Z={...X,[pe]:Ce};if(["amount","gstRate","cgstRate","sgstRate","utgstRate","igstRate","quantity"].includes(pe)){const me=pe==="amount"?parseFloat(Ce)||0:X.amount,J=pe==="quantity"?parseInt(Ce)||1:X.quantity;let be=X.cgstRate,Be=X.sgstRate,Ee=X.utgstRate,ze=X.igstRate;if(pe==="cgstRate"){if(!u.isCGST)return X;be=parseFloat(Ce)||0,u.isUTGST?(Ee=be,Be=0):(Be=be,Ee=0),ze=0}else if(pe==="sgstRate"){if(!u.isSGST)return X;Be=parseFloat(Ce)||0,be=Be,Ee=0,ze=0}else if(pe==="utgstRate"){if(!u.isUTGST)return X;Ee=parseFloat(Ce)||0,be=Ee,Be=0,ze=0}else if(pe==="igstRate"){if(!u.isIGST)return X;ze=parseFloat(Ce)||0,be=0,Be=0,Ee=0}else if(pe==="gstRate"){const ut=parseFloat(Ce)||0;u.isIGST?(ze=ut,be=0,Be=0,Ee=0):(be=ut/2,u.isUTGST?(Ee=ut/2,Be=0):(Be=ut/2,Ee=0),ze=0)}const vt=y(me,{cgstRate:be,sgstRate:Be,igstRate:ze,utgstRate:Ee},J);return{...Z,amount:me,quantity:J,...vt}}return Z}return X}))},$e=Q=>{R(pe=>pe.filter((Ce,Oe)=>Oe!==Q))},Te=async()=>{if(!$){K.error("Please fill all required fields");return}let Q=w||"";if(v==="days"&&N){const pe=parseInt(N),Ce=new Date;Ce.setDate(Ce.getDate()+pe),Q=Ce.toISOString().split("T")[0]}try{if(B(!0),!g&&b.some(Ce=>Ce.description.trim()!==""&&Ce.amount>0&&(Ce.gstRate===0||!Ce.gstRate))&&!window.confirm(`One or more items have 0% GST. Are you sure you want to proceed?
Note: If these items are taxable, please provide a valid GST rate to ensure correct E-Invoice generation.`)){B(!1);return}await a({proposalDocument:h,costBreakup:b.filter(Ce=>Ce.description.trim()!==""&&Ce.amount>0),expectedCompletionDate:Q,otherDocuments:T,dealerComments:j}),Ve(),s()}catch(pe){console.error("Failed to submit proposal:",pe),bc(pe)||K.error("Failed to submit proposal. Please try again.")}finally{B(!1)}},Ve=()=>{k!=null&&k.fileUrl&&k.fileUrl.startsWith("blob:")&&URL.revokeObjectURL(k.fileUrl),L(null),x(null),f([{id:"1",description:"",amount:0,gstRate:0,gstAmt:0,quantity:1,hsnCode:"",isService:!1,cgstRate:0,cgstAmt:0,sgstRate:0,sgstAmt:0,igstRate:0,igstAmt:0,utgstRate:0,utgstAmt:0,cessRate:0,cessAmt:0,totalAmt:0}]),C("date"),A(""),_(""),R([]),E(""),S.current&&(S.current.value=""),O.current&&(O.current.value="")},Qe=()=>{P||(Ve(),s())},Fe=new Date().toISOString().split("T")[0];return e.jsxs(ht,{open:t,onOpenChange:Qe,children:[e.jsxs(dt,{className:"dealer-proposal-modal overflow-hidden flex flex-col",children:[e.jsxs(pt,{className:"flex-shrink-0 pb-3 lg:pb-4",children:[e.jsxs(mt,{className:"flex items-center gap-2 text-xl lg:text-2xl flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ks,{className:"w-5 h-5 lg:w-6 lg:h-6 text-[--re-green]"}),"Dealer Proposal Submission"]}),m&&e.jsx(oe,{className:`ml-2 border-none shadow-sm ${m==="GST"?"bg-emerald-600 text-white hover:bg-emerald-700":"bg-indigo-600 text-white hover:bg-indigo-700"}`,children:m==="GST"?"GST Claim":"Non-GST Claim"})]}),e.jsx(Pt,{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:"})," ",i]})]}),e.jsx("div",{className:"mt-1",children:"Please upload proposal document, provide cost breakdown, timeline, and detailed comments."})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto overflow-x-hidden min-h-0 py-3 lg:py-4",children:[o&&e.jsx("div",{className:"mb-6 mx-1",children:e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg overflow-hidden cursor-pointer hover:bg-amber-100/50 transition-colors",onClick:()=>D(!V),children:[e.jsxs("div",{className:"px-4 py-3 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ke,{className:"w-4 h-4 text-amber-700"}),e.jsx("span",{className:"text-sm font-semibold text-amber-900",children:"Reference: Previous Proposal Details"}),e.jsxs(oe,{variant:"secondary",className:"bg-amber-200 text-amber-800 text-[10px]",children:["₹",Number(o.totalEstimatedBudget||o.totalBudget||0).toLocaleString("en-IN")]})]}),e.jsx(F,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-amber-700",children:V?e.jsx(go,{className:"w-4 h-4"}):e.jsx(gs,{className:"w-4 h-4"})})]}),V&&e.jsxs("div",{className:"px-4 pb-4 border-t border-amber-200 space-y-4 bg-white/50",children:[e.jsxs("div",{className:"flex flex-wrap gap-4 text-xs",children:[o.expectedCompletionDate&&e.jsxs("div",{className:"flex items-center gap-1.5 text-gray-700",children:[e.jsx(xt,{className:"w-3.5 h-3.5 text-gray-500"}),e.jsx("span",{className:"font-medium",children:"Expected Completion:"}),e.jsx("span",{children:new Date(o.expectedCompletionDate).toLocaleDateString("en-IN")})]}),o.documentUrl&&e.jsx("div",{className:"flex items-center gap-1.5",children:I(o.documentUrl)?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"w-3.5 h-3.5 text-blue-500"}),e.jsx("a",{href:o.documentUrl,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline font-medium flex items-center gap-1",children:"View Previous Document"})]}):e.jsxs(e.Fragment,{children:[e.jsx(At,{className:"w-3.5 h-3.5 text-blue-500"}),e.jsx("a",{href:o.documentUrl,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline font-medium flex items-center gap-1",children:"Download Previous Document"})]})}),o.otherDocuments&&o.otherDocuments.length>0&&e.jsxs("div",{className:"w-full pt-2 border-t border-amber-200/50",children:[e.jsxs("p",{className:"text-[10px] font-semibold text-gray-700 mb-1.5 flex items-center gap-1",children:[e.jsx(ke,{className:"w-3 h-3"}),"Supporting Documents"]}),e.jsx("div",{className:"space-y-2 max-h-[150px] overflow-y-auto",children:o.otherDocuments.map((Q,pe)=>e.jsx(Vr,{document:{documentId:Q.documentId||Q.id||"",name:Q.originalFileName||Q.fileName||Q.name||"Supporting Document",fileType:(Q.originalFileName||Q.fileName||Q.name||"").split(".").pop()||"file",uploadedAt:Q.uploadedAt||new Date().toISOString()},onPreview:I(Q.originalFileName||Q.fileName||Q.name||"")?()=>G(Q):void 0,onDownload:async Ce=>{if(Ce)await ws(Ce);else{let Oe=Q.storageUrl||Q.documentUrl;if(Oe&&!Oe.startsWith("http")){const X="https://reflow-uat.royalenfield.com",Z=X.endsWith("/")?X.slice(0,-1):X,me=Oe.startsWith("/")?Oe:`/${Oe}`;Oe=`${Z}${me}`}Oe&&window.open(Oe,"_blank")}}},pe))})]})]}),(o.costItems||o.costBreakup)&&(o.costItems||o.costBreakup).length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"text-xs font-semibold text-gray-700 mb-2",children:"Previous Cost Breakdown:"}),e.jsx("div",{className:"border rounded-md overflow-hidden text-xs",children:e.jsxs("table",{className:"w-full text-left",children:[e.jsx("thead",{className:"bg-gray-50 text-gray-600",children:e.jsxs("tr",{children:[e.jsx("th",{className:"p-2 font-medium",children:"Description"}),e.jsx("th",{className:"p-2 font-medium text-right",children:"Qty"}),e.jsx("th",{className:"p-2 font-medium text-right",children:"Amount"})]})}),e.jsxs("tbody",{className:"divide-y",children:[(o.costItems||o.costBreakup).map((Q,pe)=>e.jsxs("tr",{className:"bg-white",children:[e.jsx("td",{className:"p-2 text-gray-800",children:Q.description}),e.jsx("td",{className:"p-2 text-right text-gray-800 font-medium",children:Q.quantity||1}),e.jsxs("td",{className:"p-2 text-right text-gray-800 font-medium",children:["₹",Number(Q.amount).toLocaleString("en-IN")]})]},pe)),e.jsxs("tr",{className:"bg-gray-50 font-bold",children:[e.jsx("td",{colSpan:2,className:"p-2 text-gray-900",children:"Total"}),e.jsxs("td",{className:"p-2 text-right text-gray-900",children:["₹",Number(o.totalEstimatedBudget||o.totalBudget||0).toLocaleString("en-IN")]})]})]})]})})]}),(o.comments||o.dealerComments)&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-700 mb-1",children:"Previous Comments:"}),e.jsxs("div",{className:"bg-white border rounded p-2 text-xs text-gray-600 italic",children:['"',o.comments||o.dealerComments,'"']})]})]})]})}),e.jsxs("div",{className:"space-y-6 lg:space-y-0 lg:grid lg:grid-cols-2 lg:gap-x-8 lg:gap-y-6 lg:items-start",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(oe,{variant:"outline",className:"text-xs border-red-500 text-red-700 bg-red-50 font-medium",children:"Required"})]}),e.jsxs("div",{className:`border-2 border-dashed rounded-lg p-3 lg:p-4 transition-all duration-200 ${h?"border-green-500 bg-green-50":"border-gray-300 bg-white"}`,children:[e.jsx("input",{ref:S,type:"file",accept:[".pdf",".doc",".docx"].filter(Q=>d.allowedFileTypes.includes(Q.replace(".",""))).join(","),className:"hidden",id:"proposalDoc",onChange:z}),e.jsx("label",{htmlFor:"proposalDoc",className:"cursor-pointer flex flex-col items-center gap-2",children:h?e.jsxs("div",{className:"flex flex-col items-center gap-2 w-full text-center",children:[e.jsx(Ws,{className:"w-8 h-8 text-green-600"}),e.jsx("span",{className:"text-sm font-semibold text-green-700 truncate w-full px-2",children:h.name}),e.jsxs("div",{className:"flex gap-2",children:[M(h)&&e.jsx(F,{type:"button",variant:"outline",size:"sm",onClick:()=>W(h),className:"h-7 text-[10px]",children:"Preview"}),e.jsx(F,{type:"button",variant:"outline",size:"sm",onClick:()=>re(h),className:"h-7 text-[10px]",children:"Download"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ks,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600",children:"Upload Proposal (PDF, DOC)"})]})})]})]}),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(oe,{variant:"outline",className:"text-xs border-red-500 text-red-700 bg-red-50 font-medium",children:"Required"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(F,{type:"button",onClick:()=>C("date"),className:v==="date"?"bg-[#2d4a3e] text-white flex-1":"border flex-1",size:"sm",children:"Date"}),e.jsx(F,{type:"button",onClick:()=>C("days"),className:v==="days"?"bg-[#2d4a3e] text-white flex-1":"border flex-1",size:"sm",children:"Days"})]}),v==="date"?e.jsx(Us,{value:w||null,onChange:Q=>A(Q||""),minDate:Fe,placeholderText:"dd/mm/yyyy",className:"w-full"}):e.jsx(Ie,{type:"number",placeholder:"Enter number of days",min:"1",value:N,onChange:Q=>_(Q.target.value),className:"h-10 w-full"})]})]}),e.jsxs("div",{className:"lg:col-span-2 space-y-3 py-4 border-y border-gray-100 mt-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-lg text-[#2d4a3e]",children:"Cost Breakup"}),e.jsx(oe,{variant:"outline",className:"text-xs border-[#2d4a3e] text-[#2d4a3e] bg-green-50 font-medium",children:"Required"})]}),!g&&e.jsx("div",{className:"text-[10px] text-gray-500 italic mt-0.5",children:"Tax fields are automatically toggled based on the dealer's state (Inter-state vs Intra-state)."}),e.jsxs(F,{type:"button",onClick:je,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white",size:"sm",children:[e.jsx(gs,{className:"w-4 h-4 mr-1"}),"Add Item"]})]}),e.jsx("div",{className:"space-y-4 max-h-[400px] overflow-y-auto pr-1",children:b.map(Q=>e.jsx("div",{className:"p-4 border rounded-xl bg-gray-50/50 hover:bg-gray-50 transition-colors shadow-sm relative group",children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex gap-3 items-start",children:[e.jsxs("div",{className:`${g?"flex-[3]":"flex-1"}`,children:[e.jsx(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Item Description"}),e.jsx(Ie,{placeholder:"e.g., Venue branding, Logistics, etc.",value:Q.description,onChange:pe=>ue(Q.id,"description",pe.target.value),className:"w-full bg-white shadow-sm"})]}),g&&e.jsxs("div",{className:"flex-1 min-w-[140px]",children:[e.jsx(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Amount"}),e.jsxs("div",{className:"relative",children:[e.jsx(Wa,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),e.jsx(Ie,{type:"number",value:Q.amount||"",onChange:pe=>ue(Q.id,"amount",pe.target.value),className:"pl-8 bg-white shadow-sm"})]})]}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:"mt-6 hover:bg-red-50 hover:text-red-600 h-9 w-9 p-0 rounded-full",onClick:()=>le(Q.id),disabled:b.length===1,children:e.jsx(ft,{className:"w-4 h-4"})})]}),!g&&e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-3 items-start",children:[e.jsxs("div",{className:"flex-1 min-w-[140px]",children:[e.jsx(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Amount (Base)"}),e.jsxs("div",{className:"relative",children:[e.jsx(Wa,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),e.jsx(Ie,{type:"number",value:Q.amount||"",onChange:pe=>ue(Q.id,"amount",pe.target.value),className:"pl-8 bg-white shadow-sm"})]})]}),e.jsxs("div",{className:"w-28 sm:w-32",children:[e.jsx(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"HSN/SAC"}),e.jsx(Ie,{value:Q.hsnCode||"",onChange:pe=>ue(Q.id,"hsnCode",pe.target.value),className:`bg-white shadow-sm ${Er(Q.hsnCode,Q.isService).isValid?"":"border-red-500"}`})]}),e.jsxs("div",{className:"w-28 sm:w-32",children:[e.jsx(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Type"}),e.jsxs("select",{value:Q.isService?"SAC":"HSN",onChange:pe=>ue(Q.id,"isService",pe.target.value==="SAC"),className:"flex h-10 w-full rounded-md border border-input bg-white px-3 py-2 text-sm shadow-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-[#2d4a3e]",children:[e.jsx("option",{value:"HSN",children:"HSN (Goods)"}),e.jsx("option",{value:"SAC",children:"SAC (Service)"})]})]}),e.jsxs("div",{className:"w-16",children:[e.jsx(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"CGST %"}),e.jsx(Ie,{type:"number",value:Q.cgstRate||"",onChange:pe=>ue(Q.id,"cgstRate",pe.target.value),disabled:!u.isCGST,className:"bg-white shadow-sm text-center px-1 disabled:bg-gray-100 disabled:text-gray-400"})]}),e.jsxs("div",{className:"w-16",children:[e.jsx(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"SGST %"}),e.jsx(Ie,{type:"number",value:Q.sgstRate||"",onChange:pe=>ue(Q.id,"sgstRate",pe.target.value),disabled:!u.isSGST,className:"bg-white shadow-sm text-center px-1 disabled:bg-gray-100 disabled:text-gray-400"})]}),e.jsxs("div",{className:"w-16",children:[e.jsx(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"UTGST %"}),e.jsx(Ie,{type:"number",value:Q.utgstRate||"",onChange:pe=>ue(Q.id,"utgstRate",pe.target.value),disabled:!u.isUTGST,className:"bg-white shadow-sm text-center px-1 disabled:bg-gray-100 disabled:text-gray-400"})]}),e.jsxs("div",{className:"w-16",children:[e.jsx(ne,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"IGST %"}),e.jsx(Ie,{type:"number",value:Q.igstRate||"",onChange:pe=>ue(Q.id,"igstRate",pe.target.value),disabled:!u.isIGST,className:"bg-white shadow-sm text-center px-1 disabled:bg-gray-100 disabled:text-gray-400"})]})]}),!g&&e.jsxs("div",{className:"flex flex-wrap gap-4 pt-3 border-t border-dashed items-center justify-between text-xs",children:[e.jsxs("div",{className:"flex gap-4 text-gray-500 font-medium",children:[e.jsxs("span",{children:["CGST: ",e.jsxs("span",{className:"text-gray-900",children:["₹",Q.cgstAmt.toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),Q.sgstAmt>0&&e.jsxs("span",{children:["SGST: ",e.jsxs("span",{className:"text-gray-900",children:["₹",Q.sgstAmt.toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),Q.utgstAmt>0&&e.jsxs("span",{children:["UTGST: ",e.jsxs("span",{className:"text-gray-900",children:["₹",Q.utgstAmt.toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),e.jsxs("span",{children:["IGST: ",e.jsxs("span",{className:"text-gray-900",children:["₹",Q.igstAmt.toLocaleString("en-IN",{minimumFractionDigits:1})]})]})]}),e.jsxs("div",{className:"flex gap-4 items-center",children:[e.jsxs("span",{className:"text-gray-500",children:["GST Total: ",e.jsxs("span",{className:"text-gray-900 font-semibold",children:["₹",Q.gstAmt.toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),e.jsxs("span",{className:"text-sm font-bold text-[#2d4a3e] bg-green-50 px-3 py-1 rounded-lg",children:["Item Total: ₹",Q.totalAmt.toLocaleString("en-IN",{minimumFractionDigits:1})]})]})]})]})},Q.id))}),e.jsxs("div",{className:"bg-[#2d4a3e] rounded-xl p-5 text-white flex items-center justify-between shadow-lg",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-white/20 rounded-lg",children:e.jsx(Wa,{className:"w-6 h-6"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-white/70 uppercase font-bold tracking-wider",children:"Estimated Total Budget"}),!g&&e.jsx("p",{className:"text-sm text-white/90",children:"Inclusive of all applicable taxes"})]})]}),e.jsxs("div",{className:"text-3xl font-bold border-l border-white/20 pl-6",children:["₹",te.toLocaleString("en-IN",{minimumFractionDigits:2})]})]})]}),e.jsxs("div",{className:"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 Documents"}),e.jsx(oe,{variant:"outline",className:"text-xs border-gray-300 text-gray-500 bg-gray-50 font-medium",children:"Optional"})]}),e.jsxs("div",{className:`border-2 border-dashed rounded-lg p-3 lg:p-4 transition-all duration-200 ${T.length>0?"border-blue-500 bg-blue-50":"border-gray-300 bg-white"}`,children:[e.jsx("input",{ref:O,type:"file",multiple:!0,accept:d.allowedFileTypes.map(Q=>`.${Q}`).join(","),className:"hidden",id:"otherDocs",onChange:H}),e.jsxs("label",{htmlFor:"otherDocs",className:"cursor-pointer flex flex-col items-center gap-2",children:[e.jsx(Ks,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600",children:T.length>0?`${T.length} files selected`:"Upload supporting files"}),e.jsx("span",{className:"text-[10px] text-gray-400",children:"Click to add documents"})]})]}),T.length>0&&e.jsx("div",{className:"mt-2 space-y-2 max-h-[120px] overflow-y-auto",children:T.map((Q,pe)=>e.jsxs("div",{className:"flex items-center justify-between bg-blue-50 border border-blue-100 p-2 rounded-lg text-xs",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0 pr-2",children:[e.jsx(ke,{className:"w-3.5 h-3.5 text-blue-600 flex-shrink-0"}),e.jsx("span",{className:"text-gray-700 font-medium truncate",children:Q.name})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[M(Q)&&e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-blue-100",onClick:()=>W(Q),children:e.jsx(bt,{className:"w-3 h-3"})}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-green-100",onClick:()=>re(Q),children:e.jsx(At,{className:"w-3 h-3"})}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-red-100 hover:text-red-600",onClick:()=>$e(pe),children:e.jsx(ft,{className:"w-3 h-3"})})]})]},pe))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"font-semibold text-base lg:text-lg",children:"Dealer Comments *"}),e.jsx(_s,{placeholder:"Details about execution, special requirements, etc.",value:j,onChange:Q=>E(Q.target.value),className:"min-h-[100px] bg-white shadow-sm"})]})]}),!$&&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 mt-4",children:[e.jsx(Ye,{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(Rt,{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(F,{variant:"outline",onClick:Qe,disabled:P,className:"border-2",children:"Cancel"}),e.jsx(F,{onClick:Te,disabled:!$||P,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white disabled:bg-gray-300 disabled:text-gray-500",children:P?"Submitting...":"Submit Documents"})]})]}),k&&e.jsx(Nr,{fileName:k.fileName||"",fileType:k.fileType||"",fileUrl:k.fileUrl||"",fileSize:k.fileSize||0,attachmentId:k.documentId||"",onDownload:ws,open:!!k,onClose:()=>L(null)})]})}function hT({isOpen:t,onClose:s,onApprove:a,onReject:r,requestTitle:n,requestId:i,preFilledIONumber:l,preFilledBlockedAmount:o,preFilledRemainingBalance:c,taxationType:d}){const[m,h]=p.useState("approve"),[x,u]=p.useState(""),[g,b]=p.useState(!1),f=p.useMemo(()=>d==="Non GST"||d==="Non-GST",[d]),y=l||"";p.useEffect(()=>{t&&(u(""),h("approve"))},[t]);const v=x.length,C=500,w=p.useMemo(()=>(m==="reject"||y.trim().length>0)&&x.trim().length>0,[m,y,x]),A=async()=>{if(!w){if(m==="approve"&&!y.trim()){K.error("IO number is required. Please block amount from IO tab first.");return}if(!x.trim()){K.error("Please provide comments");return}return}try{b(!0),m==="approve"?await a({ioNumber:y.trim(),comments:x.trim()}):await r(x.trim()),N(),s()}catch(T){console.error(`Failed to ${m} request:`,T),K.error(`Failed to ${m} request. Please try again.`)}finally{b(!1)}},N=()=>{h("approve"),u("")},_=()=>{g||(N(),s())};return e.jsx(ht,{open:t,onOpenChange:_,children:e.jsxs(dt,{className:"dept-lead-io-modal overflow-hidden flex flex-col",children:[e.jsxs(pt,{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(Re,{className:"w-5 h-5 lg:w-6 lg:h-6 text-green-600"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(mt,{className:"font-semibold text-lg lg:text-xl flex items-center gap-2 flex-wrap",children:["Review and Approve",d&&e.jsx(oe,{className:`ml-2 border-none shadow-sm ${f?"bg-indigo-600 text-white hover:bg-indigo-700":"bg-emerald-600 text-white hover:bg-emerald-700"}`,children:f?"Non-GST Claim":"GST Claim"})]}),e.jsx(Pt,{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(oe,{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(oe,{className:"bg-green-100 text-green-800 border-green-200 text-xs",children:[e.jsx(Re,{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(F,{type:"button",onClick:()=>h("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(Re,{className:"w-4 h-4 mr-1"}),"Approve"]}),e.jsxs(F,{type:"button",onClick:()=>h("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(Ct,{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(Yt,{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(ne,{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(Ie,{id:"ioNumber",value:y||"—",disabled:!0,readOnly:!0,className:"bg-gray-100 h-8 lg:h-9 cursor-not-allowed text-xs lg:text-sm"}),!y&&e.jsx("p",{className:"text-xs text-red-600 mt-1",children:"⚠️ IO number not found. Please block amount from IO tab first."}),y&&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:[o!==void 0&&o>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:["₹",o.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})}),c!=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:["₹",c.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})})]})]}),e.jsxs("div",{className:`space-y-1.5 ${m==="approve"?"":"lg:col-span-2"}`,children:[e.jsxs(ne,{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(_s,{id:"comment",placeholder:m==="approve"?"Enter your approval comments and any conditions or notes...":"Enter detailed reasons for rejection...",value:x,onChange:T=>{const R=T.target.value;R.length<=C&&u(R)},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(os,{className:"w-3 h-3"}),"Required and visible to all"]}),e.jsxs("span",{children:[v,"/",C]})]})]})]})]})}),e.jsxs(Rt,{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(F,{variant:"outline",onClick:_,disabled:g,className:"text-sm lg:text-base",children:"Cancel"}),e.jsx(F,{onClick:A,disabled:!w||g,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:g?`${m==="approve"?"Approving":"Rejecting"}...`:e.jsxs(e.Fragment,{children:[e.jsx(Re,{className:"w-4 h-4 mr-2"}),m==="approve"?"Approve Request":"Reject Request"]})})]})]})})}function pT({isOpen:t,onClose:s,onPush:a,completionDetails:r,ioDetails:n,completionDocuments:i,requestTitle:l,requestNumber:o,taxationType:c}){var P,B;const d=p.useMemo(()=>c==="Non GST"||c==="Non-GST",[c]),[m,h]=p.useState(""),[x,u]=p.useState(!1),[g,b]=p.useState(null),[f,y]=p.useState(!1),v=m.length,C=500,w=p.useMemo(()=>r!=null&&r.totalClosedExpenses?r.totalClosedExpenses:r!=null&&r.closedExpenses&&Array.isArray(r.closedExpenses)?r.closedExpenses.reduce((k,L)=>{const V=typeof L=="object"&&L.amount||0,D=typeof L=="object"&&L.gstAmt||0,S=L.totalAmt||V+D;return k+(Number(S)||0)},0):0,[r]),A=k=>{if(!k)return"—";try{return new Date(k).toLocaleDateString("en-IN",{year:"numeric",month:"long",day:"numeric"})}catch{return k}},N=k=>`₹${k.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,_=k=>{if(!k.name)return!1;const L=k.name.toLowerCase();return L.endsWith(".pdf")||L.endsWith(".jpg")||L.endsWith(".jpeg")||L.endsWith(".png")||L.endsWith(".gif")||L.endsWith(".webp")},T=async k=>{if(!k.id){K.error("Document preview not available - document ID missing");return}y(!0);try{const L=Kr(k.id),V=k.name.toLowerCase(),D=V.endsWith(".pdf"),S=V.match(/\.(jpg|jpeg|png|gif|webp)$/i),O=!0,I=O?null:localStorage.getItem("accessToken"),W=await fetch(L,{headers:{Accept:D?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!W.ok)throw new Error(`Failed to load file: ${W.status} ${W.statusText}`);const G=await W.blob();if(G.size===0)throw new Error("File is empty or could not be loaded");const re=window.URL.createObjectURL(G);b({name:k.name,url:re,type:G.type||(D?"application/pdf":S?"image":void 0),size:G.size})}catch(L){console.error("Failed to load document preview:",L),K.error("Failed to load document preview")}finally{y(!1)}};p.useEffect(()=>()=>{g!=null&&g.url&&g.url.startsWith("blob:")&&window.URL.revokeObjectURL(g.url)},[g]);const R=async()=>{if(!m.trim()){K.error("Please provide comments before proceeding");return}try{u(!0),await a(m.trim()),j(),s()}catch(k){console.error("Failed to generate e-invoice:",k),K.error("Failed to generate e-invoice. Please try again.")}finally{u(!1)}},j=()=>{h("")},E=()=>{x||(j(),s())};return e.jsxs(e.Fragment,{children:[e.jsx(ht,{open:t,onOpenChange:E,children:e.jsxs(dt,{className:"settlement-push-modal overflow-hidden flex flex-col w-full max-w-none",children:[e.jsxs(pt,{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(It,{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.jsxs(mt,{className:"font-semibold text-lg sm:text-xl flex items-center gap-2 flex-wrap",children:["E-Invoice Generation & Sync",c&&e.jsx(oe,{className:`ml-2 border-none shadow-sm ${d?"bg-indigo-600 text-white hover:bg-indigo-700":"bg-emerald-600 text-white hover:bg-emerald-700"}`,children:d?"Non-GST Claim":"GST Claim"})]}),e.jsx(Pt,{className:"text-xs sm:text-sm mt-1",children:"Review completion details and expenses before generating e-invoice and initiating SAP settlement"})]})]}),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(oe,{variant:"outline",className:"font-mono text-xs",children:"Requestor Claim Approval"})]}),o&&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:o})]}),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:l||"—"})]}),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(oe,{className:"bg-indigo-100 text-indigo-800 border-indigo-200 text-xs",children:[e.jsx(It,{className:"w-3 h-3 mr-1"}),"SYNC TO SAP"]})]})]})]}),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(se,{children:[e.jsxs(ge,{className:"pb-3",children:[e.jsxs(fe,{className:"flex items-center gap-2 text-base sm:text-lg",children:[e.jsx(Ws,{className:"w-4 h-4 sm:w-5 sm:h-5 text-green-600"}),"Completion Details"]}),e.jsx(Ue,{className:"text-xs sm:text-sm",children:"Review activity completion information"})]}),e.jsxs(ae,{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:A(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(se,{children:[e.jsxs(ge,{className:"pb-3",children:[e.jsxs(fe,{className:"flex items-center gap-2 text-base sm:text-lg",children:[e.jsx(Yt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"IO Details"]}),e.jsx(Ue,{className:"text-xs sm:text-sm",children:"Internal Order information for budget reference"})]}),e.jsxs(ae,{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:N(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:N(n.remainingBalance)})]})]})]}),(r==null?void 0:r.closedExpenses)&&r.closedExpenses.length>0&&e.jsxs(se,{className:"md:col-span-2 lg:col-span-3",children:[e.jsxs(ge,{className:"pb-3",children:[e.jsxs(fe,{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(Ue,{className:"text-xs sm:text-sm",children:"Review closed expenses breakdown (Base + GST)"})]}),e.jsxs(ae,{children:[e.jsxs("div",{className:"grid grid-cols-12 gap-2 mb-2 px-3 text-xs font-medium text-gray-500 uppercase tracking-wider hidden sm:grid",children:[e.jsx("div",{className:`${d?"col-span-8":"col-span-4"}`,children:"Description"}),e.jsx("div",{className:"col-span-2 text-right",children:"Base"}),!d&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"col-span-2 text-right",children:"GST Rate"}),e.jsx("div",{className:"col-span-2 text-right",children:"GST Amt"})]}),e.jsx("div",{className:"col-span-2 text-right",children:"Total"})]}),e.jsx("div",{className:"space-y-2 max-h-[300px] overflow-y-auto",children:r.closedExpenses.map((k,L)=>{const V=typeof k=="object"&&k.amount||0,D=typeof k=="object"&&k.gstRate||0,S=typeof k=="object"&&k.gstAmt||0,O=typeof k=="object"?k.totalAmt||V+S:0;return e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-12 gap-2 items-center py-2 px-3 bg-gray-50 rounded border text-xs sm:text-sm",children:[e.jsxs("div",{className:"sm:hidden flex justify-between w-full mb-1",children:[e.jsx("span",{className:"font-semibold text-gray-900",children:k.description||`Expense ${L+1}`}),e.jsx("span",{className:"font-bold text-gray-900",children:N(O)})]}),e.jsxs("div",{className:"sm:hidden flex justify-between w-full text-xs text-gray-500",children:[e.jsxs("span",{children:["Base: ",N(V)]}),!d&&e.jsxs("span",{children:["GST: ",D,"% (",N(S),")"]})]}),e.jsx("div",{className:`hidden sm:block ${d?"col-span-8":"col-span-4"} min-w-0`,children:e.jsx("p",{className:"font-medium text-gray-900 truncate",title:k.description,children:k.description||`Expense ${L+1}`})}),e.jsx("div",{className:"hidden sm:block col-span-2 text-right text-gray-600",children:N(V)}),!d&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"hidden sm:block col-span-2 text-right text-gray-600",children:[D,"%"]}),e.jsx("div",{className:"hidden sm:block col-span-2 text-right text-gray-600",children:N(S)})]}),e.jsx("div",{className:"hidden sm:block col-span-2 text-right font-semibold text-gray-900",children:N(O)})]},L)})}),e.jsxs("div",{className:"flex items-center justify-between py-2 sm:py-3 px-3 sm:px-4 bg-blue-50 rounded border-2 border-blue-200 mt-3 sm:mt-4",children:[e.jsx("span",{className:"text-xs sm:text-sm font-semibold text-gray-900",children:"Total Closed Expenses:"}),e.jsx("span",{className:"text-sm sm:text-base font-bold text-blue-700",children:N(w)})]})]})]})]}),i&&e.jsxs("div",{className:"space-y-4",children:[i.completionDocuments&&i.completionDocuments.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 sm:text-base flex items-center gap-2",children:[e.jsx(Ws,{className:"w-4 h-4 sm:w-5 sm:h-5 text-green-600"}),"Completion Documents"]}),e.jsxs(oe,{variant:"secondary",className:"text-xs",children:[i.completionDocuments.length," file(s)"]})]}),e.jsx("div",{className:"space-y-2 max-h-[200px] overflow-y-auto",children:i.completionDocuments.map((k,L)=>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(Ws,{className:"w-4 h-4 lg:w-5 lg:h-5 text-green-600 flex-shrink-0"}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx("p",{className:"font-medium text-xs lg:text-sm text-gray-900 truncate",title:k.name,children:k.name})})]}),k.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[_(k)&&e.jsx("button",{type:"button",onClick:()=>T(k),disabled:f,className:"p-2 hover:bg-gray-200 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Preview document",children:f?e.jsx(it,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600 animate-spin"}):e.jsx(bt,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{try{k.id&&await ws(k.id)}catch(V){console.error("Failed to download document:",V),K.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(At,{className:"w-4 h-4 lg:w-5 lg:h-5 text-gray-600"})})]})]},L))})]}),i.activityPhotos&&i.activityPhotos.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 sm:text-base flex items-center gap-2",children:[e.jsx(It,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Activity Photos"]}),e.jsxs(oe,{variant:"secondary",className:"text-xs",children:[i.activityPhotos.length," file(s)"]})]}),e.jsx("div",{className:"space-y-2 max-h-[200px] overflow-y-auto",children:i.activityPhotos.map((k,L)=>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(It,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600 flex-shrink-0"}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx("p",{className:"font-medium text-xs lg:text-sm text-gray-900 truncate",title:k.name,children:k.name})})]}),k.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[_(k)&&e.jsx("button",{type:"button",onClick:()=>T(k),disabled:f,className:"p-2 hover:bg-gray-200 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Preview photo",children:f?e.jsx(it,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600 animate-spin"}):e.jsx(bt,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{try{k.id&&await ws(k.id)}catch(V){console.error("Failed to download document:",V),K.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download photo",children:e.jsx(At,{className:"w-4 h-4 lg:w-5 lg:h-5 text-gray-600"})})]})]},L))})]}),i.invoicesReceipts&&i.invoicesReceipts.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 sm:text-base flex items-center gap-2",children:[e.jsx(Yt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"Invoices / Receipts"]}),e.jsxs(oe,{variant:"secondary",className:"text-xs",children:[i.invoicesReceipts.length," file(s)"]})]}),e.jsx("div",{className:"space-y-2 max-h-[200px] overflow-y-auto",children:i.invoicesReceipts.map((k,L)=>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(Yt,{className:"w-4 h-4 lg:w-5 lg:h-5 text-purple-600 flex-shrink-0"}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx("p",{className:"font-medium text-xs lg:text-sm text-gray-900 truncate",title:k.name,children:k.name})})]}),k.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[_(k)&&e.jsx("button",{type:"button",onClick:()=>T(k),disabled:f,className:"p-2 hover:bg-gray-200 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Preview document",children:f?e.jsx(it,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600 animate-spin"}):e.jsx(bt,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{try{k.id&&await ws(k.id)}catch(V){console.error("Failed to download document:",V),K.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(At,{className:"w-4 h-4 lg:w-5 lg:h-5 text-gray-600"})})]})]},L))})]}),i.attendanceSheet&&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 sm:text-base flex items-center gap-2",children:[e.jsx(It,{className:"w-4 h-4 sm:w-5 sm:h-5 text-indigo-600"}),"Attendance Sheet"]})}),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(It,{className:"w-4 h-4 lg:w-5 lg:h-5 text-indigo-600 flex-shrink-0"}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx("p",{className:"font-medium text-xs lg:text-sm text-gray-900 truncate",title:i.attendanceSheet.name,children:i.attendanceSheet.name})})]}),i.attendanceSheet.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[_(i.attendanceSheet)&&e.jsx("button",{type:"button",onClick:()=>T(i.attendanceSheet),disabled:f,className:"p-2 hover:bg-gray-200 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Preview document",children:f?e.jsx(it,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600 animate-spin"}):e.jsx(bt,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{var k;try{(k=i.attendanceSheet)!=null&&k.id&&await ws(i.attendanceSheet.id)}catch(L){console.error("Failed to download document:",L),K.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(At,{className:"w-4 h-4 lg:w-5 lg:h-5 text-gray-600"})})]})]})]})]}),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(os,{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 generation"}),e.jsx("p",{className:"text-xs text-yellow-700 mt-1",children:"Once submitted, the system will generate an e-invoice and initiate the SAP settlement process."})]})]})}),e.jsxs("div",{className:"space-y-1.5 max-w-2xl",children:[e.jsxs(ne,{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(_s,{id:"comment",placeholder:"Enter your comments about e-invoice generation (e.g., verified expenses, ready for settlement)...",value:m,onChange:k=>{const L=k.target.value;L.length<=C&&h(L)},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(os,{className:"w-3 h-3"}),"Required and visible to all"]}),e.jsxs("span",{children:[v,"/",C]})]})]})]})}),e.jsxs(Rt,{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(F,{variant:"outline",onClick:E,disabled:x,children:"Cancel"}),e.jsx(F,{onClick:R,disabled:!m.trim()||x,className:"bg-indigo-600 hover:bg-indigo-700 text-white",children:x?"Processing...":e.jsxs(e.Fragment,{children:[e.jsx(It,{className:"w-4 h-4 mr-2"}),"Generate & Sync"]})})]})]})}),g&&e.jsx(ht,{open:!!g,onOpenChange:()=>b(null),children:e.jsx(dt,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(pt,{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(mt,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:g.name}),g.type&&e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[g.type," ",g.size&&`• ${(g.size/1024).toFixed(1)} KB`]})]})]}),e.jsx("div",{className:"flex items-center gap-2 flex-wrap mr-2",children:e.jsxs(F,{variant:"outline",size:"sm",onClick:()=>{const k=document.createElement("a");k.href=g.url,k.download=g.name,k.click()},className:"gap-2 h-9",children:[e.jsx(At,{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:f?e.jsx("div",{className:"flex items-center justify-center h-full min-h-[70vh]",children:e.jsxs("div",{className:"text-center",children:[e.jsx(it,{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..."})]})}):g.name.toLowerCase().endsWith(".pdf")||(P=g.type)!=null&&P.includes("pdf")?e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("iframe",{src:g.url,className:"w-full h-full rounded-lg border-0",title:g.name,style:{minHeight:"70vh",height:"100%"}})}):g.name.match(/\.(jpg|jpeg|png|gif|webp)$/i)||(B=g.type)!=null&&B.includes("image")?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("img",{src:g.url,alt:g.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(F,{onClick:()=>{const k=document.createElement("a");k.href=g.url,k.download=g.name,k.click()},className:"gap-2",children:[e.jsx(At,{className:"h-4 w-4"}),"Download ",g.name]})]})})]})})})]})}function gT({isOpen:t,onClose:s,stepNumber:a,stepName:r,requestNumber:n="RE-REQ-2024-CM-101",recipientEmail:i="system@undefined",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.`,h=o||m;return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-2xl lg:max-w-[1000px] max-w-2xl",children:[e.jsx(pt,{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(Da,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(mt,{className:"text-lg leading-none font-semibold",children:"Email Notification Template"}),e.jsxs(Pt,{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(Gt,{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(Da,{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(Ai,{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:h})}),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(xt,{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(oe,{className:"bg-blue-50 text-blue-700 border-blue-200",children:["Step ",a]}),e.jsx(oe,{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(F,{variant:"outline",onClick:s,className:"h-9",children:[e.jsx(ft,{className:"w-4 h-4 mr-2"}),"Close"]})})]})})}function fT({isOpen:t,onClose:s,onApprove:a,onReject:r,onRequestRevision:n,proposalData:i,dealerName:l="Dealer",activityName:o="Activity",requestId:c,request:d,previousProposalData:m,taxationType:h}){const x=p.useMemo(()=>h==="Non GST"||h==="Non-GST",[h]),[u,g]=p.useState(""),[b,f]=p.useState(!1),[y,v]=p.useState(null),[C,w]=p.useState(!1),A=(d==null?void 0:d.internalOrder)||(d==null?void 0:d.internal_order),_=((A==null?void 0:A.ioBlockedAmount)||(A==null?void 0:A.io_blocked_amount)||0)>0,[T,R]=p.useState(null),j=p.useMemo(()=>{if(!(i!=null&&i.costBreakup))return 0;const O=Array.isArray(i.costBreakup)?i.costBreakup:typeof i.costBreakup=="string"?JSON.parse(i.costBreakup):[];return Array.isArray(O)?O.reduce((I,M)=>{const W=typeof M=="object"&&M.amount||0,G=typeof M=="object"&&M.quantity||1,re=W*G,te=typeof M=="object"&&M.gstAmt||0,$=M.totalAmt||re+te;return I+(Number($)||0)},0):0},[i]),E=O=>{if(!O)return"—";try{return new Date(O).toLocaleDateString("en-IN",{year:"numeric",month:"long",day:"numeric"})}catch{return O}},P=O=>{if(!O.name)return!1;const I=O.name.toLowerCase();return I.endsWith(".pdf")||I.endsWith(".jpg")||I.endsWith(".jpeg")||I.endsWith(".png")||I.endsWith(".gif")||I.endsWith(".webp")},B=O=>{let I=O.url||O.storageUrl||"";const M=O.id||O.documentId||"";if(!M&&!I){K.error("Document preview not available");return}if(I&&!I.startsWith("http")&&!I.startsWith("blob:")){const W="https://reflow-uat.royalenfield.com",G=W.endsWith("/")?W.slice(0,-1):W,re=I.startsWith("/")?I:`/${I}`;I=`${G}${re}`}R({name:O.name||"Document",url:I||(M?Kr(M):""),type:(O.name||"").toLowerCase().endsWith(".pdf")?"application/pdf":"image/jpeg",id:M})};p.useEffect(()=>()=>{T!=null&&T.url&&T.url.startsWith("blob:")&&window.URL.revokeObjectURL(T.url)},[T]);const k=async()=>{if(!u.trim()){K.error("Please provide approval comments");return}try{f(!0),v("approve"),await a(u),D(),s()}catch(O){console.error("Failed to approve proposal:",O),K.error("Failed to approve proposal. Please try again.")}finally{f(!1),v(null)}},L=async()=>{if(!u.trim()){K.error("Please provide rejection reason");return}try{f(!0),v("reject"),await r(u),D(),s()}catch(O){console.error("Failed to reject proposal:",O),K.error("Failed to reject proposal. Please try again.")}finally{f(!1),v(null)}},V=async()=>{if(!u.trim()){K.error("Please provide reasons for requesting a revision");return}if(!n){K.error("Revision feature is not available");return}try{f(!0),v("revision"),await n(u),D(),s()}catch(O){console.error("Failed to request revision:",O),K.error("Failed to request revision. Please try again.")}finally{f(!1),v(null)}},D=()=>{g(""),v(null)},S=()=>{b||(D(),s())};return t?e.jsxs(ht,{open:t,onOpenChange:S,children:[e.jsxs(dt,{className:"dealer-proposal-modal overflow-hidden flex flex-col",children:[e.jsxs(pt,{className:"flex-shrink-0 pb-3 lg:pb-4 px-6 pt-4 lg:pt-6 border-b",children:[e.jsxs(mt,{className:"flex items-center gap-2 text-lg lg:text-xl flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Re,{className:"w-4 h-4 lg:w-5 lg:h-5 text-green-600"}),"Requestor Evaluation & Confirmation"]}),h&&e.jsx(oe,{className:`ml-2 border-none shadow-sm ${x?"bg-indigo-600 text-white hover:bg-indigo-700":"bg-emerald-600 text-white hover:bg-emerald-700"}`,children:x?"Non-GST Claim":"GST Claim"})]}),e.jsx(Pt,{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:"})," ",l]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Activity:"})," ",o]})]}),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.jsxs("div",{className:"flex-1 overflow-y-auto overflow-x-hidden min-h-0 py-3 lg:py-4 px-6",children:[m&&e.jsx("div",{className:"mb-6",children:e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg overflow-hidden cursor-pointer hover:bg-amber-100/50 transition-colors",onClick:()=>w(!C),children:[e.jsxs("div",{className:"px-4 py-3 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ke,{className:"w-4 h-4 text-amber-700"}),e.jsx("span",{className:"text-sm font-semibold text-amber-900",children:"Reference: Previous Proposal Details (last revision)"}),e.jsxs(oe,{variant:"secondary",className:"bg-amber-200 text-amber-800 text-[10px]",children:["₹",Number(m.totalEstimatedBudget||m.totalBudget||0).toLocaleString("en-IN")]})]}),e.jsx(F,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-amber-700",children:C?e.jsx(go,{className:"w-4 h-4"}):e.jsx(gs,{className:"w-4 h-4"})})]}),C&&e.jsxs("div",{className:"px-4 pb-4 border-t border-amber-200 space-y-4 bg-white/50",children:[e.jsxs("div",{className:"flex flex-wrap gap-4 text-xs mt-3",children:[m.expectedCompletionDate&&e.jsxs("div",{className:"flex items-center gap-1.5 text-gray-700",children:[e.jsx(xt,{className:"w-3.5 h-3.5 text-gray-500"}),e.jsx("span",{className:"font-medium",children:"Expected Completion:"}),e.jsx("span",{children:new Date(m.expectedCompletionDate).toLocaleDateString("en-IN")})]}),m.documentUrl&&e.jsx("div",{className:"flex items-center gap-1.5",children:P({name:m.documentUrl})?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"w-3.5 h-3.5 text-blue-500"}),e.jsx("a",{href:m.documentUrl,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline font-medium flex items-center gap-1",children:"View Previous Document"})]}):e.jsxs(e.Fragment,{children:[e.jsx(At,{className:"w-3.5 h-3.5 text-blue-500"}),e.jsx("a",{href:m.documentUrl,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline font-medium flex items-center gap-1",children:"Download Previous Document"})]})})]}),(m.costItems||m.costBreakup)&&(m.costItems||m.costBreakup).length>0&&e.jsxs("div",{className:"w-full pt-2 border-t border-amber-200/50",children:[e.jsxs("p",{className:"text-[10px] font-semibold text-gray-700 mb-2 flex items-center gap-1",children:[e.jsx(Wa,{className:"w-3 h-3"}),"Previous Cost Breakdown"]}),e.jsx("div",{className:"border rounded-md overflow-hidden text-[10px]",children:e.jsxs("table",{className:"w-full text-left",children:[e.jsx("thead",{className:"bg-gray-50 text-gray-600",children:e.jsxs("tr",{children:[e.jsx("th",{className:"p-2 font-medium",children:"Description"}),e.jsx("th",{className:"p-2 font-medium text-right",children:"Amount"})]})}),e.jsxs("tbody",{className:"divide-y",children:[(m.costItems||m.costBreakup).map((O,I)=>e.jsxs("tr",{className:"bg-white",children:[e.jsx("td",{className:"p-2 text-gray-800",children:O.description}),e.jsxs("td",{className:"p-2 text-right text-gray-800 font-medium",children:["₹",Number(O.amount).toLocaleString("en-IN")]})]},I)),e.jsxs("tr",{className:"bg-gray-50 font-bold border-t",children:[e.jsx("td",{className:"p-2 text-gray-900",children:"Total"}),e.jsxs("td",{className:"p-2 text-right text-gray-900",children:["₹",Number(m.totalEstimatedBudget||m.totalBudget||0).toLocaleString("en-IN")]})]})]})]})})]}),m.otherDocuments&&m.otherDocuments.length>0&&e.jsxs("div",{className:"w-full pt-2 border-t border-amber-200/50",children:[e.jsxs("p",{className:"text-[10px] font-semibold text-gray-700 mb-1.5 flex items-center gap-1",children:[e.jsx(ke,{className:"w-3 h-3"}),"Supporting Documents"]}),e.jsx("div",{className:"space-y-2 max-h-[150px] overflow-y-auto",children:m.otherDocuments.map((O,I)=>e.jsx(Vr,{document:{documentId:O.documentId||O.id||"",name:O.originalFileName||O.fileName||O.name||"Supporting Document",fileType:(O.originalFileName||O.fileName||O.name||"").split(".").pop()||"file",uploadedAt:O.uploadedAt||new Date().toISOString()},onPreview:P({name:O.originalFileName||O.fileName||O.name||""})?()=>B(O):void 0,onDownload:async M=>{if(M)await ws(M);else{let W=O.storageUrl||O.documentUrl;if(W&&!W.startsWith("http")){const G="https://reflow-uat.royalenfield.com",re=G.endsWith("/")?G.slice(0,-1):G,te=W.startsWith("/")?W:`/${W}`;W=`${re}${te}`}W&&window.open(W,"_blank")}}},I))})]}),(m.comments||m.dealerComments)&&e.jsxs("div",{className:"w-full pt-2 border-t border-amber-200/50",children:[e.jsxs("p",{className:"text-[10px] font-semibold text-gray-700 mb-1 flex items-center gap-1",children:[e.jsx(Ds,{className:"w-3 h-3"}),"Previous Comments"]}),e.jsxs("div",{className:"text-[10px] text-gray-600 bg-white p-2 border border-gray-100 rounded italic",children:['"',m.comments||m.dealerComments,'"']})]})]})]})}),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(ke,{className:"w-4 h-4 text-blue-600"}),"Proposal Document"]})}),i!=null&&i.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(ke,{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:i.proposalDocument.name,children:i.proposalDocument.name}),(i==null?void 0:i.submittedAt)&&e.jsxs("p",{className:"text-xs text-gray-500 truncate",children:["Submitted on ",E(i.submittedAt)]})]})]}),e.jsx("div",{className:"flex items-center gap-2 flex-shrink-0",children:i.proposalDocument.id&&e.jsxs(e.Fragment,{children:[P(i.proposalDocument)&&e.jsx("button",{type:"button",onClick:()=>B(i.proposalDocument),className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Preview document",children:e.jsx(bt,{className:"w-5 h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{var O;try{(O=i.proposalDocument)!=null&&O.id&&await ws(i.proposalDocument.id)}catch(I){console.error("Failed to download document:",I),K.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(At,{className:"w-5 h-5 text-gray-600"})})]})})]}):e.jsx("p",{className:"text-xs text-gray-500 italic",children:"No proposal document available"})]}),(i==null?void 0:i.otherDocuments)&&i.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(ke,{className:"w-4 h-4 text-gray-600"}),"Other Supporting Documents"]}),e.jsxs(oe,{variant:"secondary",className:"text-xs",children:[i.otherDocuments.length," file(s)"]})]}),e.jsx("div",{className:"space-y-2 max-h-[150px] lg:max-h-[140px] overflow-y-auto",children:i.otherDocuments.map((O,I)=>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(ke,{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:O.name,children:O.name})]}),O.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[P(O)&&e.jsx("button",{type:"button",onClick:()=>B(O),className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Preview document",children:e.jsx(bt,{className:"w-5 h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{try{O.id&&await ws(O.id)}catch(M){console.error("Failed to download document:",M),K.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(At,{className:"w-5 h-5 text-gray-600"})})]})]},I))})]})]}),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(Wa,{className:"w-4 h-4 text-green-600"}),"Cost Breakup"]})}),(()=>{const O=i!=null&&i.costBreakup?Array.isArray(i.costBreakup)?i.costBreakup:typeof i.costBreakup=="string"?JSON.parse(i.costBreakup):[]:[];return O&&Array.isArray(O)&&O.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 ${x?"grid-cols-3":"grid-cols-4"} gap-4 text-xs lg:text-sm font-semibold text-gray-700`,children:[e.jsx("div",{className:"col-span-1",children:"Item Description"}),e.jsx("div",{className:"text-right",children:"Base"}),!x&&e.jsx("div",{className:"text-right",children:"GST"}),e.jsx("div",{className:"text-right",children:"Total"})]})}),e.jsx("div",{className:"divide-y",children:O.map((I,M)=>e.jsxs("div",{className:`px-3 lg:px-4 py-2 lg:py-3 grid ${x?"grid-cols-3":"grid-cols-4"} gap-4`,children:[e.jsxs("div",{className:"col-span-1 text-xs lg:text-sm text-gray-700",children:[(I==null?void 0:I.description)||"N/A",!x&&(I!=null&&I.gstRate)?e.jsxs("span",{className:"block text-[10px] text-gray-400",children:[I.gstRate,"% GST"]}):null]}),e.jsxs("div",{className:"text-xs lg:text-sm text-gray-900 text-right",children:["₹",(Number(I==null?void 0:I.amount)||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),!x&&e.jsxs("div",{className:"text-xs lg:text-sm text-gray-900 text-right",children:["₹",(Number(I==null?void 0:I.gstAmt)||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),e.jsxs("div",{className:"text-xs lg:text-sm font-semibold text-gray-900 text-right",children:["₹",(Number((I==null?void 0:I.totalAmt)||((I==null?void 0:I.amount)||0)*((I==null?void 0:I.quantity)||1)+((I==null?void 0:I.gstAmt)||0))||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]},(I==null?void 0:I.id)||(I==null?void 0:I.description)||M))})]}),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(Wa,{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:["₹",j.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(xt,{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:i!=null&&i.expectedCompletionDate?E(i.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(Ds,{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:(i==null?void 0:i.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(_s,{placeholder:"Provide your evaluation comments, approval conditions, or rejection reasons...",value:u,onChange:O=>g(O.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:[u.length," characters"]})]})]})}),!u.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(Ct,{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(Rt,{className:"flex flex-col 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(F,{variant:"outline",onClick:S,disabled:b,className:"border-2 w-full sm:w-auto",children:"Cancel"}),e.jsxs("div",{className:"flex flex-col gap-2 w-full sm:w-auto",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(F,{onClick:V,disabled:!u.trim()||b,variant:"secondary",className:"bg-amber-100 hover:bg-amber-200 text-amber-900 border border-amber-200 w-full sm:w-auto",children:b&&y==="revision"?"Requesting...":e.jsxs(e.Fragment,{children:[e.jsx(Ds,{className:"w-4 h-4 mr-2"}),"Request Revised Quotation"]})}),e.jsx(F,{onClick:L,disabled:!u.trim()||b,variant:"destructive",className:"bg-red-600 hover:bg-red-700 w-full sm:w-auto",children:b&&y==="reject"?"Rejecting...":e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"w-4 h-4 mr-2"}),"Reject (Cancel Request)"]})}),e.jsx(F,{onClick:k,disabled:!u.trim()||!_||b,className:"bg-green-600 hover:bg-green-700 text-white disabled:opacity-50 disabled:cursor-not-allowed w-full sm:w-auto",title:_?"":"Please block IO budget before approving",children:b&&y==="approve"?"Approving...":e.jsxs(e.Fragment,{children:[e.jsx(Re,{className:"w-4 h-4 mr-2"}),"Approve (Continue to Dept Lead)"]})})]}),!_&&e.jsx("p",{className:"text-xs text-red-600 text-center sm:text-left",children:"Please block IO budget in the IO Tab before approving"})]})]})]}),T&&e.jsx(Nr,{fileName:T.name,fileType:T.type||"",fileUrl:T.url,fileSize:T.size,attachmentId:T.id,onDownload:ws,open:!!T,onClose:()=>R(null)})]}):null}function bT({isOpen:t,onClose:s,snapshot:a,type:r,title:n}){const[i,l]=p.useState(null);if(!a)return null;const o=r==="PROPOSAL",c=u=>Number(u||0).toLocaleString("en-IN",{maximumFractionDigits:2,style:"currency",currency:"INR"}),d=u=>{if(!u)return null;try{return new Date(u).toLocaleDateString("en-IN",{day:"numeric",month:"short",year:"numeric"})}catch{return u}},m=u=>{if(!u)return!1;const g=u.toLowerCase();return g.endsWith(".pdf")||!!g.match(/\.(jpg|jpeg|png|gif|webp)$/i)},h=u=>{var b;const g=(b=(u||"").split(".").pop())==null?void 0:b.toLowerCase();return g==="pdf"?"pdf":["jpg","jpeg","png","gif","webp"].includes(g||"")?"image":"file"},x=u=>{const g=u.fileName||u.originalFileName||(o?"Proposal Document":"Completion Document"),b=u.documentId||"",f=g.toLowerCase().endsWith(".pdf")?"application/pdf":"image/jpeg";let y="";if(b)y=Kr(b);else if(y=u.storageUrl||u.documentUrl||"",y&&!y.startsWith("http")){const v="https://reflow-uat.royalenfield.com",C=v.endsWith("/")?v.slice(0,-1):v,w=y.startsWith("/")?y:`/${y}`;y=`${C}${w}`}l({fileName:g,fileType:f,documentId:b,fileUrl:y,fileSize:u.sizeBytes})};return e.jsxs(e.Fragment,{children:[e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"max-w-2xl max-h-[90vh] flex flex-col p-0 gap-0 overflow-hidden",children:[e.jsxs(pt,{className:"px-6 py-4 border-b",children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[o?e.jsx(ke,{className:"w-5 h-5 text-blue-600"}):e.jsx(Yt,{className:"w-5 h-5 text-green-600"}),n||(o?"Proposal Snapshot Details":"Completion Snapshot Details")]}),e.jsxs(Pt,{children:["View detailed snapshot of the ",o?"proposal":"completion request"," at this version."]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto min-h-0 px-6 py-4",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg border border-gray-100",children:[e.jsx("p",{className:"text-xs text-gray-500 font-medium mb-1",children:o?"Total Budget":"Total Expenses"}),e.jsx("p",{className:`text-lg font-bold ${o?"text-blue-700":"text-green-700"}`,children:c(a.totalBudget||a.totalExpenses)})]}),o&&a.expectedCompletionDate&&e.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg border border-gray-100",children:[e.jsxs("p",{className:"text-xs text-gray-500 font-medium mb-1 flex items-center gap-1",children:[e.jsx(xt,{className:"w-3 h-3"}),"Expected Completion"]}),e.jsx("p",{className:"text-sm font-semibold text-gray-700",children:d(a.expectedCompletionDate)})]})]}),a.documentUrl&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-semibold text-gray-900 border-b pb-1",children:"Primary Document"}),e.jsx(Vr,{document:{documentId:"",name:o?"Proposal Document":"Completion Document",fileType:h(a.documentUrl),uploadedAt:new Date().toISOString()},onPreview:m(a.documentUrl)?()=>x({fileName:o?"Proposal Document":"Completion Document",documentUrl:a.documentUrl}):void 0,onDownload:async()=>{let u=a.documentUrl;if(!u.startsWith("http")){const g="https://reflow-uat.royalenfield.com",b=g.endsWith("/")?g.slice(0,-1):g,f=u.startsWith("/")?u:`/${u}`;u=`${b}${f}`}window.open(u,"_blank")}})]}),a.otherDocuments&&a.otherDocuments.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h4",{className:"text-sm font-semibold text-gray-900 border-b pb-1 flex items-center justify-between",children:[e.jsx("span",{children:"Supporting Documents"}),e.jsxs(oe,{variant:"secondary",className:"text-[10px] h-5",children:[a.otherDocuments.length," Files"]})]}),e.jsx("div",{className:"space-y-2",children:a.otherDocuments.map((u,g)=>e.jsx(Vr,{document:{documentId:u.documentId||"",name:u.originalFileName||u.fileName||"Supporting Document",fileType:h(u.originalFileName||u.fileName||""),uploadedAt:u.uploadedAt||new Date().toISOString()},onPreview:m(u.originalFileName||u.fileName||"")?()=>x(u):void 0,onDownload:u.documentId?ws:async()=>{let b=u.storageUrl||u.documentUrl;if(b&&!b.startsWith("http")){const f="https://reflow-uat.royalenfield.com",y=f.endsWith("/")?f.slice(0,-1):f,v=b.startsWith("/")?b:`/${b}`;b=`${y}${v}`}b&&window.open(b,"_blank")}},g))})]}),(a.costItems||a.expenses)&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-semibold text-gray-900 border-b pb-1",children:o?"Cost Breakdown":"Expenses Breakdown"}),e.jsx("div",{className:"border rounded-md overflow-hidden text-sm",children:e.jsxs("table",{className:"w-full text-left",children:[e.jsx("thead",{className:"bg-gray-50 text-gray-600 text-xs uppercase",children:e.jsxs("tr",{children:[e.jsx("th",{className:"p-3 font-medium",children:"Description"}),e.jsx("th",{className:"p-3 font-medium text-right",children:"Amount"})]})}),e.jsxs("tbody",{className:"divide-y divide-gray-100",children:[(a.costItems||a.expenses).length>0?(a.costItems||a.expenses).map((u,g)=>e.jsxs("tr",{className:"bg-white hover:bg-gray-50/50",children:[e.jsx("td",{className:"p-3 text-gray-800",children:u.description}),e.jsx("td",{className:"p-3 text-right text-gray-900 font-medium tabular-nums",children:c(u.amount)})]},g)):e.jsx("tr",{children:e.jsx("td",{colSpan:2,className:"p-4 text-center text-gray-500 italic text-xs",children:"No breakdown items available"})}),e.jsxs("tr",{className:"bg-gray-50/80 font-semibold text-gray-900 border-t-2 border-gray-100",children:[e.jsx("td",{className:"p-3",children:"Total"}),e.jsx("td",{className:"p-3 text-right tabular-nums",children:c(a.totalBudget||a.totalExpenses)})]})]})]})})]}),a.comments&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h4",{className:"text-sm font-semibold text-gray-900 border-b pb-1 flex items-center gap-1",children:[e.jsx(Sx,{className:"w-4 h-4"}),"Comments"]}),e.jsx("div",{className:"bg-gray-50 rounded-lg p-3 text-sm text-gray-700 italic border border-gray-100",children:a.comments})]})]})}),e.jsx("div",{className:"px-6 py-4 border-t bg-gray-50 flex justify-end",children:e.jsx(F,{onClick:s,children:"Close"})})]})}),i&&e.jsx(Nr,{fileName:i.fileName,fileType:i.fileType,fileUrl:i.fileUrl,fileSize:i.fileSize,attachmentId:i.documentId,onDownload:ws,open:!!i,onClose:()=>l(null)})]})}async function yT(t){var s;try{const a=await ve.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 vT(t){var s;try{const a=await ve.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 jT(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 ve.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 NT(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.completionDescription&&r.append("completionDescription",s.completionDescription),s.completionDocuments&&s.completionDocuments.forEach(i=>{r.append("completionDocuments",i)}),s.activityPhotos&&s.activityPhotos.forEach(i=>{r.append("activityPhotos",i)});const n=await ve.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 wT(t,s){var a;try{const r=await ve.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 Eg(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 ve.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 CT(t,s){var a;try{const r=await ve.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 ST(t){var s;try{const a=await ve.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}}async function AT(t,s,a){var r;try{const n={};t&&(n.dateRange=t),s&&(n.startDate=s),a&&(n.endDate=a);const i=await ve.get("/dealer-claims/dashboard",{params:n});return((r=i.data)==null?void 0:r.data)||i.data}catch(n){throw console.error("[DealerClaimAPI] Error fetching dealer dashboard:",n),n}}const Ar=t=>{if(!t)return"";try{return as(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}}},TT=t=>{switch(t){case"approved":return e.jsx(Re,{className:"w-5 h-5 text-green-600"});case"pending":return e.jsx(nt,{className:"w-5 h-5 text-blue-600"});case"rejected":return e.jsx(Re,{className:"w-5 h-5 text-red-600"});default:return e.jsx(nt,{className:"w-5 h-5 text-gray-400"})}},kT=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"}},RT=(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",DT=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 PT({request:t,user:s,isInitiator:a,onSkipApprover:r,onRefresh:n,documentPolicy:i}){var ar,$a,ba,Oa,Ft,ms,zs,rr,nr,ma,jt,us,Ls,ea,Cr,ua,Ua,Qr,qr,en,Ac,Tc,kc,Rc,Dc,Pc,Ic,Ec,Fc,_c,Lc,Mc,$c,Oc,Uc,Bc,Vc,zc,Hc,Gc,Wc,Yc,Kc,Xc,Zc,Jc,Qc,qc,ed,td,sd,ad,rd,nd,id,ld,od,cd,dd,md,ud,xd,hd,pd,gd,fd,bd,yd,vd,jd,Nd,wd,Cd,Sd,Ad,Td,kd,Rd,Dd,Pd,Id,Ed,Fd,_d,Ld,Md,$d,Od,Ud,Bd,Vd,zd,Hd,Gd,Wd,Yd,Kd,Xd,Zd,Jd,Qd,qd,em;const[l,o]=p.useState(!1),[c,d]=p.useState(!1),[m,h]=p.useState(!1),[x,u]=p.useState(!1),[g,b]=p.useState(!1),[f,y]=p.useState(!1),[v,C]=p.useState(!1),[w,A]=p.useState(null),[N,_]=p.useState(!1),[T,R]=p.useState(null),[j,E]=p.useState([]),[P,B]=p.useState(!1),[k,L]=p.useState(new Set),[V,D]=p.useState(null),[S,O]=p.useState(null),[I,M]=p.useState(!1),[W,G]=p.useState(!1),[re,te]=p.useState([]),[$,z]=p.useState(0);p.useEffect(()=>{(async()=>{if(t!=null&&t.id||t!=null&&t.requestId){const Pe=t.id||t.requestId;try{const xe=await Ts(Pe),ce=(xe==null?void 0:xe.approvalLevels)||(xe==null?void 0:xe.approvals)||[];if(ce&&ce.length>0){const he=ce.map(ie=>{var Se;return{step:ie.levelNumber||ie.level_number||0,levelNumber:ie.levelNumber||ie.level_number||0,levelName:ie.levelName||ie.level_name,approver:ie.approverName||ie.approver_name||"",approverEmail:(ie.approverEmail||ie.approver_email||"").toLowerCase(),status:((Se=ie.status)==null?void 0:Se.toLowerCase())||"waiting",tatHours:ie.tatHours||ie.tat_hours||24,elapsedHours:ie.elapsedHours||ie.elapsed_hours,approvedAt:ie.actionDate||ie.action_date,comment:ie.comments||ie.comment,levelId:ie.levelId||ie.level_id}}).sort((ie,Se)=>(ie.levelNumber||0)-(Se.levelNumber||0));te(ie=>ie.length!==he.length||ie.some((we,ye)=>{const yt=he[ye];return!yt||we.levelNumber!==yt.levelNumber||we.levelName!==yt.levelName||we.approverEmail!==yt.approverEmail||we.status!==yt.status})?he:ie)}else te([])}catch(xe){console.warn("Failed to load approval flows from API:",xe),t!=null&&t.approvalFlow&&t.approvalFlow.length>0&&te(t.approvalFlow)}}else t!=null&&t.approvalFlow&&t.approvalFlow.length>0&&te(t.approvalFlow)})()},[t==null?void 0:t.id,t==null?void 0:t.requestId,t==null?void 0:t.totalLevels,$]),p.useEffect(()=>{if(t!=null&&t.id||t!=null&&t.requestId){const U=t.id||t.requestId;(async()=>{try{const xe=await Ts(U),ce=(xe==null?void 0:xe.approvalLevels)||(xe==null?void 0:xe.approvals)||[];if(ce&&ce.length>0){const he=ce.map(ie=>{var Se;return{step:ie.levelNumber||ie.level_number||0,levelNumber:ie.levelNumber||ie.level_number||0,levelName:ie.levelName||ie.level_name,approver:ie.approverName||ie.approver_name||"",approverEmail:(ie.approverEmail||ie.approver_email||"").toLowerCase(),status:((Se=ie.status)==null?void 0:Se.toLowerCase())||"waiting",tatHours:ie.tatHours||ie.tat_hours||24,elapsedHours:ie.elapsedHours||ie.elapsed_hours,approvedAt:ie.actionDate||ie.action_date,comment:ie.comments||ie.comment,levelId:ie.levelId||ie.level_id}}).sort((ie,Se)=>(ie.levelNumber||0)-(Se.levelNumber||0));te(he)}}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 H=async()=>{z(U=>U+1),await new Promise(U=>setTimeout(U,500)),n==null||n(),je()},je=async()=>{if(t!=null&&t.id||t!=null&&t.requestId)try{const Pe=[...await PN(t.id||t.requestId)||[]].sort((xe,ce)=>new Date(ce.createdAt).getTime()-new Date(xe.createdAt).getTime());E(Pe)}catch(U){console.warn("Failed to load version history:",U)}};p.useEffect(()=>{je()},[t==null?void 0:t.id,t==null?void 0:t.requestId,$]);const le=(U,Pe,xe)=>{var ie;const ce=((t==null?void 0:t.totalLevels)||0)>5||(((ie=t==null?void 0:t.approvalLevels)==null?void 0:ie.length)||0)>5;if(Pe&&Pe.trim()&&(Pe.toLowerCase().includes("additional approver")||!/^step\s+\d+$/i.test(Pe)))return Pe;const he=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"}:{1:"Dealer - Proposal Submission",2:"Requestor Evaluation & Confirmation",3:"Department Lead Approval",4:"Dealer - Completion Documents",5:"Requestor - Claim Approval",6:"E-Invoice Generation",7:"Credit Note from SAP"};return he[U]?he[U]:xe&&xe!=="Unknown"&&xe!=="System"?`Additional Approver - ${xe}`:`Additional Approver - Step ${U}`},ue=(U,Pe,xe)=>{var Se;if(Pe&&Pe.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.";const he=((t==null?void 0:t.totalLevels)||0)>5||(((Se=t==null?void 0:t.approvalLevels)==null?void 0:Se.length)||0)>5;if(Pe&&Pe.trim()){const we=Pe.toLowerCase();if(we.includes("dealer")&&we.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(we.includes("requestor")&&(we.includes("evaluation")||we.includes("confirmation")))return"Requestor evaluates the request and confirms with comments. Decision point: Confirms? (YES → Continue to Dept Lead / NO → Request is cancelled)";if(we.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(we.includes("activity creation"))return"Activity is created. Activity confirmation email is auto-triggered to dealer / requestor / Lead. IO confirmation to be made.";if(we.includes("dealer")&&(we.includes("completion")||we.includes("documents")))return"Dealer submits the necessary documents upon completion of the activity including document attachments (Zip Folder) and brief description";if(we.includes("requestor")&&(we.includes("claim")||we.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(we.includes("e-invoice")||we.includes("invoice generation")||we.includes("dms"))return"E-Invoice will be generated upon settlement initiation.";if(we.includes("credit note")||we.includes("sap"))return"Got credit note from SAP. Review and send to dealer to complete the claim management process."}const ie=he?{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 upon settlement initiation.",8:"Got credit note from SAP. Review and send to dealer to complete the claim management process."}:{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:"Dealer submits the necessary documents upon completion of the activity including document attachments (Zip Folder) and brief description",5:"Requestor approves the claim in full or can modify the amount. If more information is required, can request additional details from dealer.",6:"E-Invoice will be generated upon settlement initiation.",7:"Got credit note from SAP. Review and send to dealer to complete the claim management process."};return ie[U]?ie[U]:xe&&xe!=="Unknown"&&xe!=="System"?`${xe} will review and approve this request.`:`Step ${U} approval required.`},$e=U=>{if(!j||j.length===0||!U)return{current:null,previous:null};const ce=[...j.filter(Se=>{var we;return!!(Se.levelName&&Se.levelName.trim()===U.trim()||(we=Se.snapshotData)!=null&&we.levelName&&Se.snapshotData.levelName.trim()===U.trim())})].sort((Se,we)=>{if(we.version!==Se.version)return we.version-Se.version;const ye=Se.snapshotType==="APPROVE"?1:Se.snapshotType==="PROPOSAL"||Se.snapshotType==="COMPLETION"?2:3,yt=we.snapshotType==="APPROVE"?1:we.snapshotType==="PROPOSAL"||we.snapshotType==="COMPLETION"?2:3;return ye-yt}).filter((Se,we,ye)=>Se.snapshotType==="WORKFLOW"?!ye.some(gt=>gt.snapshotType==="APPROVE"&&gt.levelName===Se.levelName&&gt.version>=Se.version):!0),he=ce.length>0?ce[0]:null,ie=ce.length>1?ce[1]:null;return{current:he,previous:ie,all:ce}},Te=(t==null?void 0:t.currentLevel)||(t==null?void 0:t.current_level)||(t==null?void 0:t.currentStep),Ve=Te!=null?Number(Te):null,Qe=((t==null?void 0:t.status)||"").toUpperCase(),Fe=Qe==="REJECTED",Q=Qe==="CLOSED",pe=!Fe&&!Q&&(Qe==="PENDING"||Qe==="IN_PROGRESS"||Qe==="IN-PROGRESS"),Ce=re.find(U=>{var ce,he;const Pe=U.levelId||U.level_id,xe=(ce=t==null?void 0:t.approvals)==null?void 0:ce.find(ie=>ie.levelId===Pe);return((he=xe==null?void 0:xe.status)==null?void 0:he.toLowerCase())==="rejected"}),Oe=Ce?Number(Ce.levelNumber||Ce.level_number||Ce.step||0):null,X=re.map((U,Pe)=>{var xa,fs,de,lt,zt,bs,wt;const xe=Number(U.levelNumber||U.level_number||U.step||Pe+1),ce=U.levelName||U.level_name,he=(xa=t==null?void 0:t.approvals)==null?void 0:xa.find(De=>De.levelId===U.levelId);let ie;if(ce&&ce.toLowerCase().includes("department lead")||xe===3){const De=(t==null?void 0:t.internalOrder)||(t==null?void 0:t.internal_order);(De!=null&&De.ioNumber||De!=null&&De.io_number)&&(ie={ioNumber:De.ioNumber||De.io_number||"",blockedAmount:De.ioBlockedAmount||De.io_blocked_amount||0,availableBalance:De.ioAvailableBalance||De.io_available_balance||0,remainingBalance:De.ioRemainingBalance||De.io_remaining_balance||0,organizedBy:((fs=De.organizer)==null?void 0:fs.displayName)||((de=De.organizer)==null?void 0:de.name)||De.organizedBy||U.approver||"N/A",organizedAt:De.organizedAt||De.organized_at||U.approvedAt||(t==null?void 0:t.updatedAt)||""})}let we;xe===6&&(he!=null&&he.dmsDetails?we={dmsNumber:he.dmsDetails.dmsNumber||"",dmsRemarks:he.dmsDetails.dmsRemarks||"",pushedBy:he.dmsDetails.pushedBy||U.approver,pushedAt:he.dmsDetails.pushedAt||U.approvedAt||""}:t!=null&&t.dmsNumber&&(we={dmsNumber:t.dmsNumber||"",dmsRemarks:t.dmsRemarks||((lt=t.dmsDetails)==null?void 0:lt.dmsRemarks)||"",pushedBy:U.approver,pushedAt:U.approvedAt||t.updatedAt||""}));let ye;if(Fe||Q)((zt=he==null?void 0:he.status)==null?void 0:zt.toLowerCase())==="rejected"?ye="rejected":Oe!==null&&xe>Oe?ye="waiting":((bs=he==null?void 0:he.status)==null?void 0:bs.toLowerCase())==="approved"?ye="approved":Oe!==null&&xe<Oe?((wt=he==null?void 0:he.status)==null?void 0:wt.toLowerCase())==="approved"?ye="approved":ye="waiting":(Ve!==null&&xe>Ve,ye="waiting");else if(pe&&Ve!==null&&Ve>0)if(xe>Ve)ye="waiting";else if(xe<Ve)if(he!=null&&he.status){const De=he.status.toLowerCase();De==="approved"?ye="approved":De==="rejected"?ye="rejected":ye="waiting"}else ye="waiting";else if(he!=null&&he.status){const De=he.status.toLowerCase();De==="approved"?ye="approved":De==="rejected"?ye="rejected":ye="in_progress"}else{const De=(U.status||"pending").toLowerCase();De==="in-review"||De==="in_review"||De==="in review"||De==="pending"?ye="in_progress":ye=De}else if(he!=null&&he.status){const De=he.status.toLowerCase();De==="approved"?ye="approved":De==="rejected"?ye="rejected":De==="pending"||De==="in_progress"||De==="in-progress"?ye="in_progress":ye=(U.status||"waiting").toLowerCase()}else{const De=(U.status||"waiting").toLowerCase();De==="in-review"||De==="in_review"||De==="in review"||De==="pending"?ye="in_progress":ye=De}const gt=ye==="waiting"?0:U.elapsedHours||0,xs=U.approver||U.approverName||"Unknown",Nt=ce?$e(ce):{current:null,previous:null};return{step:xe,title:le(xe,ce,xs),approver:xs,description:ue(xe,ce,xs)||U.description||"",tatHours:U.tatHours||24,status:ye,comment:U.comment||(he==null?void 0:he.comment),approvedAt:U.approvedAt||(he==null?void 0:he.timestamp),elapsedHours:gt,ioDetails:ie,dmsDetails:we,einvoiceUrl:xe===7?he==null?void 0:he.einvoiceUrl:void 0,emailTemplateUrl:(he==null?void 0:he.emailTemplateUrl)||void 0,versionHistory:Nt}});let Z=null,me=1;if(Fe||Q)Oe!==null?me=Oe:Ve!==null?me=Ve:me=(t==null?void 0:t.currentStep)||1;else if(pe){const U=Ve!==null?X.find(Pe=>Pe.step===Ve):null;Z=U&&(U.status==="pending"||U.status==="in_progress")?U:X.find(Pe=>{var ce;const xe=((ce=Pe.status)==null?void 0:ce.toLowerCase())||"";return xe==="pending"||xe==="in_progress"||xe==="in-review"||xe==="in_review"}),me=Z?Z.step:Ve||(t==null?void 0:t.currentStep)||1}else me=Ve||(t==null?void 0:t.currentStep)||1;const J=((ar=s==null?void 0:s.email)==null?void 0:ar.toLowerCase())||"",be=(($a=t==null?void 0:t.dealerEmail)==null?void 0:$a.toLowerCase())||((Oa=(ba=t==null?void 0:t.dealer)==null?void 0:ba.email)==null?void 0:Oa.toLowerCase())||((ms=(Ft=t==null?void 0:t.claimDetails)==null?void 0:Ft.dealerEmail)==null?void 0:ms.toLowerCase())||((rr=(zs=t==null?void 0:t.claimDetails)==null?void 0:zs.dealer_email)==null?void 0:rr.toLowerCase())||"",Be=be&&J===be,Ee=re.find(U=>(U.step||U.levelNumber||U.level_number)===me),ze=((Ee==null?void 0:Ee.approverEmail)||"").toLowerCase(),vt=ze&&J===ze,ut=((ma=(nr=t==null?void 0:t.initiator)==null?void 0:nr.email)==null?void 0:ma.toLowerCase())||((jt=t==null?void 0:t.initiatorEmail)==null?void 0:jt.toLowerCase())||"",Tt=re.find(U=>{const Pe=(U.approverEmail||"").toLowerCase(),xe=(U.levelName||"").toLowerCase();return ut&&Pe===ut||xe.includes("requestor evaluation")||xe.includes("requestor")&&xe.includes("confirmation")}),cs=Tt&&(Tt.step||Tt.levelNumber||Tt.level_number)||2,q=Tt||re.find(U=>(U.step||U.levelNumber||U.level_number)===2),Ne=((q==null?void 0:q.approverEmail)||"").toLowerCase(),ee=Ne&&J===Ne,_e=re.find(U=>(U.step||U.levelNumber||U.level_number)===1),Le=((_e==null?void 0:_e.approverEmail)||"").toLowerCase(),We=Le&&J===Le,Me=re.find(U=>(U.levelName||"").toLowerCase().includes("department lead")),qe=((Me==null?void 0:Me.approverEmail)||"").toLowerCase(),He=qe&&J===qe,at=async U=>{var Pe,xe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ce=t.id||t.requestId;U.proposalDocument&&await dn(U.proposalDocument,ce,"APPROVAL");for(const ie of U.otherDocuments)await dn(ie,ce,"SUPPORTING");const he=U.costBreakup.reduce((ie,Se)=>ie+(Se.totalAmt||Se.amount||0),0);await jT(ce,{proposalDocument:U.proposalDocument||void 0,costBreakup:U.costBreakup.map(ie=>({description:ie.description,amount:ie.amount,gstRate:ie.gstRate,gstAmt:ie.gstAmt,cgstRate:ie.cgstRate,cgstAmt:ie.cgstAmt,sgstRate:ie.sgstRate,sgstAmt:ie.sgstAmt,igstRate:ie.igstRate,igstAmt:ie.igstAmt,utgstRate:ie.utgstRate,utgstAmt:ie.utgstAmt,cessRate:ie.cessRate,cessAmt:ie.cessAmt,totalAmt:ie.totalAmt,quantity:ie.quantity,hsnCode:ie.hsnCode,isService:ie.isService})),totalEstimatedBudget:he,expectedCompletionDate:U.expectedCompletionDate,dealerComments:U.dealerComments}),K.success("Proposal submitted successfully"),H()}catch(ce){console.error("Failed to submit proposal:",ce);const he=((xe=(Pe=ce==null?void 0:ce.response)==null?void 0:Pe.data)==null?void 0:xe.message)||(ce==null?void 0:ce.message)||"Failed to submit proposal. Please try again.";throw K.error(he),ce}},Ss=async U=>{var Pe,xe,ce,he,ie;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Se=t.id||t.requestId,we=await Ts(Se),ye=(we==null?void 0:we.approvalLevels)||(we==null?void 0:we.approvals)||[],yt=((xe=(Pe=t==null?void 0:t.initiator)==null?void 0:Pe.email)==null?void 0:xe.toLowerCase())||((ce=t==null?void 0:t.initiatorEmail)==null?void 0:ce.toLowerCase())||"",gt=ye.find(Nt=>{const xa=(Nt.approverEmail||Nt.approver_email||"").toLowerCase(),fs=(Nt.levelName||Nt.level_name||"").toLowerCase(),de=Nt.levelNumber||Nt.level_number;return yt&&xa===yt||fs.includes("requestor evaluation")||fs.includes("requestor")&&fs.includes("confirmation")||de===cs})||ye.find(Nt=>(Nt.levelNumber||Nt.level_number)===2);if(!(gt!=null&&gt.levelId)&&!(gt!=null&&gt.level_id))throw new Error("Initiator approval level not found");const xs=gt.levelId||gt.level_id;await on(Se,xs,U),K.success("Proposal approved successfully"),H()}catch(Se){console.error("Failed to approve proposal:",Se);const we=((ie=(he=Se==null?void 0:Se.response)==null?void 0:he.data)==null?void 0:ie.message)||(Se==null?void 0:Se.message)||"Failed to approve proposal. Please try again.";throw K.error(we),Se}},Kt=async U=>{var Pe,xe,ce,he,ie;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Se=t.id||t.requestId,we=await Ts(Se),ye=(we==null?void 0:we.approvalLevels)||(we==null?void 0:we.approvals)||[],yt=((xe=(Pe=t==null?void 0:t.initiator)==null?void 0:Pe.email)==null?void 0:xe.toLowerCase())||((ce=t==null?void 0:t.initiatorEmail)==null?void 0:ce.toLowerCase())||"",gt=ye.find(Nt=>{const xa=(Nt.approverEmail||Nt.approver_email||"").toLowerCase(),fs=(Nt.levelName||Nt.level_name||"").toLowerCase(),de=Nt.levelNumber||Nt.level_number;return yt&&xa===yt||fs.includes("requestor evaluation")||fs.includes("requestor")&&fs.includes("confirmation")||de===cs})||ye.find(Nt=>(Nt.levelNumber||Nt.level_number)===2);if(!(gt!=null&&gt.levelId)&&!(gt!=null&&gt.level_id))throw new Error("Initiator approval level not found");const xs=gt.levelId||gt.level_id;await Tr(Se,xs,"Proposal rejected by requestor",U),K.success("Proposal rejected. Request has been cancelled."),H()}catch(Se){console.error("Failed to reject proposal:",Se);const we=((ie=(he=Se==null?void 0:Se.response)==null?void 0:he.data)==null?void 0:ie.message)||(Se==null?void 0:Se.message)||"Failed to reject proposal. Please try again.";throw K.error(we),Se}},ct=async U=>{var Pe,xe,ce,he,ie;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Se=t.id||t.requestId,we=await Ts(Se),ye=(we==null?void 0:we.approvalLevels)||(we==null?void 0:we.approvals)||[],yt=((xe=(Pe=t==null?void 0:t.initiator)==null?void 0:Pe.email)==null?void 0:xe.toLowerCase())||((ce=t==null?void 0:t.initiatorEmail)==null?void 0:ce.toLowerCase())||"",gt=ye.find(Nt=>{const xa=(Nt.approverEmail||Nt.approver_email||"").toLowerCase(),fs=(Nt.levelName||Nt.level_name||"").toLowerCase(),de=Nt.levelNumber||Nt.level_number;return yt&&xa===yt||fs.includes("requestor evaluation")||fs.includes("requestor")&&fs.includes("confirmation")||de===cs})||ye.find(Nt=>(Nt.levelNumber||Nt.level_number)===2);if(!(gt!=null&&gt.levelId)&&!(gt!=null&&gt.level_id))throw new Error("Initiator approval level not found");const xs=gt.levelId||gt.level_id;await Tr(Se,xs,"Revised Quotation Requested",U),K.success("Revision requested. Request returned to dealer."),H()}catch(Se){console.error("Failed to request revision:",Se);const we=((ie=(he=Se==null?void 0:Se.response)==null?void 0:he.data)==null?void 0:ie.message)||(Se==null?void 0:Se.message)||"Failed to request revision. Please try again.";throw K.error(we),Se}},rt=async U=>{var Pe,xe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ce=t.id||t.requestId,he=await Ts(ce),ie=(he==null?void 0:he.approvalLevels)||(he==null?void 0:he.approvals)||[],Se=ie.find(ye=>(ye.levelName||ye.level_name||"").toLowerCase().includes("department lead"))||ie.find(ye=>(ye.levelNumber||ye.level_number)===3);if(!(Se!=null&&Se.levelId)&&!(Se!=null&&Se.level_id))throw new Error("Department Lead approval level not found");const we=Se.levelId||Se.level_id;await Eg(ce,{ioNumber:U.ioNumber}),await on(ce,we,U.comments),K.success("Request approved and IO organized successfully"),H()}catch(ce){console.error("Failed to approve and organize IO:",ce);const he=((xe=(Pe=ce==null?void 0:ce.response)==null?void 0:Pe.data)==null?void 0:xe.message)||(ce==null?void 0:ce.message)||"Failed to approve request. Please try again.";throw K.error(he),ce}},St=async U=>{var Pe,xe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ce=t.id||t.requestId,he=U.closedExpenses.map(ie=>({description:ie.description,amount:ie.amount,gstRate:ie.gstRate,gstAmt:ie.gstAmt,cgstRate:ie.cgstRate,cgstAmt:ie.cgstAmt,sgstRate:ie.sgstRate,sgstAmt:ie.sgstAmt,igstRate:ie.igstRate,igstAmt:ie.igstAmt,utgstRate:ie.utgstRate,utgstAmt:ie.utgstAmt,cessRate:ie.cessRate,cessAmt:ie.cessAmt,totalAmt:ie.totalAmt,quantity:ie.quantity,hsnCode:ie.hsnCode,isService:ie.isService}));if(await NT(ce,{activityCompletionDate:U.activityCompletionDate,numberOfParticipants:U.numberOfParticipants,closedExpenses:he,totalClosedExpenses:U.totalClosedExpenses,completionDocuments:U.completionDocuments,activityPhotos:U.activityPhotos,completionDescription:U.completionDescription}),U.invoicesReceipts&&U.invoicesReceipts.length>0)for(const ie of U.invoicesReceipts)await dn(ie,ce,"SUPPORTING");U.attendanceSheet&&await dn(U.attendanceSheet,ce,"SUPPORTING"),K.success("Completion documents submitted successfully"),H()}catch(ce){console.error("Failed to submit completion documents:",ce);const he=((xe=(Pe=ce==null?void 0:ce.response)==null?void 0:Pe.data)==null?void 0:xe.message)||(ce==null?void 0:ce.message)||"Failed to submit completion documents. Please try again.";throw K.error(he),ce}},ds=async U=>{var Pe,xe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ce=t.id||t.requestId,he=new Date().toISOString().slice(0,10);await CT(ce,{eInvoiceDate:he}),K.success("E-Invoice generation initiated successfully."),H()}catch(ce){console.error("[DealerClaimWorkflowTab] Error generating e-invoice:",ce);let ie=((xe=(Pe=ce==null?void 0:ce.response)==null?void 0:Pe.data)==null?void 0:xe.message)||(ce==null?void 0:ce.message)||"E-Invoice generation failed. Please try again.";throw ie.length>300&&(ie=ie.substring(0,300)+"..."),K.error(ie),ce}},Vt=async U=>{var Pe,xe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ce=t.id||t.requestId,he=await Ts(ce),ie=(he==null?void 0:he.approvalLevels)||(he==null?void 0:he.approvals)||[],Se=ie.find(ye=>(ye.levelName||ye.level_name||"").toLowerCase().includes("department lead"))||ie.find(ye=>(ye.levelNumber||ye.level_number)===3);if(!(Se!=null&&Se.levelId)&&!(Se!=null&&Se.level_id))throw new Error("Department Lead approval level not found");const we=Se.levelId||Se.level_id;await Tr(ce,we,"Dept Lead rejected - More clarification required",U),K.success("Request rejected. Request has been cancelled."),H()}catch(ce){console.error("Failed to reject request:",ce);const he=((xe=(Pe=ce==null?void 0:ce.response)==null?void 0:Pe.data)==null?void 0:xe.message)||(ce==null?void 0:ce.message)||"Failed to reject request. Please try again.";throw K.error(he),ce}},[Ca,qs]=p.useState(null);p.useEffect(()=>{if(!t){qs(null);return}(async()=>{try{const Pe=t.id||t.requestId;if(!Pe){qs(null);return}const xe=await Ts(Pe),ce=(xe==null?void 0:xe.documents)||[],he=t.proposalDetails||(xe==null?void 0:xe.proposalDetails)||{},ie=ce.find(ye=>ye.category==="APPROVAL"||ye.type==="proposal"||ye.documentCategory==="APPROVAL"),Se=ce.filter(ye=>ye.category==="SUPPORTING"||ye.type==="supporting"||ye.documentCategory==="SUPPORTING");let we=he.costBreakup||[];if(typeof we=="string")try{we=JSON.parse(we)}catch(ye){console.warn("Failed to parse costBreakup JSON:",ye),we=[]}Array.isArray(we)||(we=[]),qs({proposalDocument:ie?{name:ie.fileName||ie.file_name||ie.name,id:ie.documentId||ie.document_id||ie.id}:void 0,costBreakup:we,expectedCompletionDate:he.expectedCompletionDate||"",otherDocuments:Se.map(ye=>({name:ye.fileName||ye.file_name||ye.name,id:ye.documentId||ye.document_id||ye.id})),dealerComments:he.dealerComments||"",submittedAt:he.submittedAt})}catch(Pe){console.warn("Failed to load proposal data:",Pe);const xe=t.proposalDetails||{};let ce=xe.costBreakup||[];if(typeof ce=="string")try{ce=JSON.parse(ce)}catch(he){console.warn("Failed to parse costBreakup JSON:",he),ce=[]}Array.isArray(ce)||(ce=[]),qs({proposalDocument:void 0,costBreakup:ce,expectedCompletionDate:xe.expectedCompletionDate||"",otherDocuments:[],dealerComments:xe.dealerComments||"",submittedAt:xe.submittedAt})}})()},[t]);const[er,da]=p.useState(null);p.useEffect(()=>{if(!t){da(null);return}(async()=>{try{const Pe=t.id||t.requestId;if(!Pe){da(null);return}const xe=await Ts(Pe),ce=(xe==null?void 0:xe.documents)||[],he=[],ie=[],Se=[];let we=null;ce.forEach(ye=>{const yt=(ye.category||ye.documentCategory||ye.type||"").toUpperCase(),gt=(ye.fileName||ye.file_name||ye.name||"").toLowerCase(),xs={name:ye.fileName||ye.file_name||ye.name,id:ye.documentId||ye.document_id||ye.id,url:ye.url||ye.storageUrl||ye.storage_url};yt==="COMPLETION"||yt==="COMPLETION_DOCUMENT"?he.push(xs):yt==="ACTIVITY_PHOTO"||yt==="PHOTO"||yt==="IMAGE"?ie.push(xs):yt==="ATTENDANCE"||yt==="ATTENDANCE_SHEET"?we=xs:(yt==="SUPPORTING"||yt==="INVOICE"||yt==="RECEIPT")&&(!we&&(gt.includes("attendance")||gt.includes("participant"))?we=xs:Se.push(xs))}),he.length===0&&ie.length===0&&t.completionDetails,da({completionDocuments:he,activityPhotos:ie,invoicesReceipts:Se,attendanceSheet:we})}catch(Pe){console.warn("Failed to load completion documents:",Pe),da(null)}})()},[t]);const kt=async()=>{try{const U=t.id||t.requestId;if(!U){K.error("Request ID not found");return}const xe=await fetch(`https://reflow-uat.royalenfield.com/api/v1//dealer-claims/${U}/e-invoice/csv`,{headers:{Authorization:`Bearer ${st.getAccessToken()}`}});if(!xe.ok)throw new Error("Failed to download CSV");const ce=await xe.blob(),he=window.URL.createObjectURL(ce),ie=document.createElement("a");ie.href=he,ie.download=`Invoice_${t.requestNumber||"Export"}.csv`,document.body.appendChild(ie),ie.click(),window.URL.revokeObjectURL(he),document.body.removeChild(ie),K.success("CSV downloaded successfully")}catch(U){console.error("Error downloading CSV:",U),K.error("Failed to download CSV")}},_a=async()=>{try{const U=t.id||t.requestId;if(!U){K.error("Request ID not found");return}if(!t.invoice&&!t.irn){K.error("Invoice not generated yet");return}G(!0),M(!0);const xe=await fetch(`https://reflow-uat.royalenfield.com/api/v1//dealer-claims/${U}/e-invoice/pdf`,{headers:{Authorization:`Bearer ${st.getAccessToken()}`}});if(!xe.ok)throw new Error("Failed to fetch invoice PDF");const ce=await xe.blob(),he=window.URL.createObjectURL(ce);S&&window.URL.revokeObjectURL(S),O(he)}catch(U){console.error("Failed to preview invoice:",U),K.error("Failed to load invoice preview"),M(!1)}finally{G(!1)}},tr=()=>{M(!1),S&&(window.URL.revokeObjectURL(S),O(null))},wr=()=>{if(S){const U=document.createElement("a");U.href=S,U.download=`Invoice_${t.requestNumber||"Download"}.pdf`,document.body.appendChild(U),U.click(),document.body.removeChild(U),K.success("Invoice PDF downloaded")}},La=((us=t==null?void 0:t.claimDetails)==null?void 0:us.dealerName)||((Ls=t==null?void 0:t.dealerInfo)==null?void 0:Ls.name)||"Dealer",sr=((ea=t==null?void 0:t.claimDetails)==null?void 0:ea.dealerGstin)||((Cr=t==null?void 0:t.dealerInfo)==null?void 0:Cr.gstin)||((ua=t==null?void 0:t.dealerInfo)==null?void 0:ua.dealerGSTIN),Ma=((Ua=t==null?void 0:t.claimDetails)==null?void 0:Ua.activityName)||((Qr=t==null?void 0:t.activityInfo)==null?void 0:Qr.activityName)||(t==null?void 0:t.title)||"Activity";return e.jsxs(e.Fragment,{children:[e.jsxs(se,{children:[e.jsx(ge,{children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(na,{className:"w-5 h-5 text-purple-600"}),"Claim Management Workflow"]}),e.jsx(Ue,{className:"mt-2",children:"Approval process for dealer claim management"})]})})}),e.jsxs(ae,{children:[(t==null?void 0:t.status)==="rejected"&&!(t!=null&&t.closureDate||t!=null&&t.closure_date)&&a?e.jsxs("div",{className:"mb-6 p-4 bg-amber-50 border-l-4 border-amber-500 rounded-lg flex items-start gap-4 shadow-sm",children:[e.jsx("div",{className:"p-2 bg-amber-100 rounded-full",children:e.jsx(os,{className:"w-5 h-5 text-amber-600"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"text-sm font-bold text-amber-900 mb-1",children:"Action Required: Request Returned"}),e.jsxs("p",{className:"text-xs text-amber-800 leading-relaxed mb-3",children:["This request has been returned to you by the department head.",a?"You can choose to resubmit, discuss with the dealer, request a revision, or cancel the request.":"The initiator needs to take action to proceed."]})]})]}):null,e.jsx("div",{className:"space-y-4",children:X.map((U,Pe)=>{var gt,xs,Nt,xa,fs;const ce=(((gt=U.status)==null?void 0:gt.toLowerCase())||"")==="in_progress",he=U.step===me,ie=pe&&ce&&he,Se=U.status==="approved",we=re.find(de=>(de.step||de.levelNumber||de.level_number)===U.step),ye=we!=null&&we.levelId?(xs=t==null?void 0:t.approvals)==null?void 0:xs.find(de=>de.levelId===we.levelId||de.level_id===we.levelId):null,yt=(ye==null?void 0:ye.status)==="PAUSED"||((Nt=t==null?void 0:t.pauseInfo)==null?void 0:Nt.isPaused)&&(((xa=t==null?void 0:t.pauseInfo)==null?void 0:xa.levelId)===(ye==null?void 0:ye.levelId)||((fs=t==null?void 0:t.pauseInfo)==null?void 0:fs.level_id)===(ye==null?void 0:ye.levelId));return e.jsx("div",{className:`relative p-5 rounded-lg border-2 transition-all ${RT(U.status,ie)}`,children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:`p-3 rounded-xl ${DT(U.status)}`,children:TT(U.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:U.title}),e.jsx(oe,{className:kT(U.status),children:U.status.toLowerCase()}),U.emailTemplateUrl&&U.status==="approved"&&e.jsx(F,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-blue-100",title:"View email template",onClick:()=>{A({stepNumber:U.step,stepName:U.title}),C(!0)},children:e.jsx(Da,{className:"w-3.5 h-3.5 text-blue-600"})}),U.step===7&&U.einvoiceUrl&&Se&&e.jsx(F,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-green-100",title:"Download E-Invoice",onClick:()=>window.open(U.einvoiceUrl,"_blank"),children:e.jsx(At,{className:"w-3.5 h-3.5 text-green-600"})}),(()=>{const de=(U.levelName||U.title||"").toLowerCase().includes("requestor claim")||(U.levelName||U.title||"").toLowerCase().includes("requestor - claim"),lt=(t==null?void 0:t.invoice)||(t==null?void 0:t.irn)&&U.status==="approved";return de&&lt&&e.jsx(F,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-amber-100",title:"Preview Invoice",onClick:_a,children:e.jsx(Yt,{className:"w-3.5 h-3.5 text-amber-600"})})})(),(()=>{const de=(U.levelName||U.title||"").toLowerCase().includes("requestor claim")||(U.levelName||U.title||"").toLowerCase().includes("requestor - claim"),lt=(t==null?void 0:t.invoice)||(t==null?void 0:t.irn)&&U.status==="approved";return de&&lt&&e.jsx(F,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-emerald-100 ml-1",title:"Export CSV",onClick:kt,children:e.jsx(Ix,{className:"w-3.5 h-3.5 text-emerald-600"})})})()]}),e.jsx("p",{className:"text-sm text-gray-600",children:U.approver}),e.jsx("p",{className:"text-sm text-gray-500 mt-2 italic",children:U.description})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:["TAT: ",Mt(U.tatHours)]}),U.elapsedHours&&(ie||Se)&&e.jsxs("p",{className:"text-xs text-gray-600 font-medium",children:["Elapsed: ",Mt(U.elapsedHours)]})]})]}),U.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:U.comment})}),U.versionHistory&&U.versionHistory.all&&U.versionHistory.all.length>0&&e.jsxs("div",{className:"mt-3",children:[e.jsxs(F,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs text-amber-700 hover:text-amber-800 hover:bg-amber-50",onClick:()=>{const de=new Set(k);de.has(U.step)?de.delete(U.step):de.add(U.step),L(de)},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Lx,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"font-medium",children:"Version History"}),U.versionHistory.all&&U.versionHistory.all.length>0&&e.jsxs(oe,{className:"bg-amber-100 text-amber-800 text-[10px] px-1.5 py-0",children:[U.versionHistory.all.length," Versions"]})]}),k.has(U.step)?e.jsx(wx,{className:"w-4 h-4"}):e.jsx(ho,{className:"w-4 h-4"})]}),k.has(U.step)&&U.versionHistory.all&&e.jsx("div",{className:"mt-2 space-y-3 p-3 bg-amber-50/50 rounded-lg border border-amber-200 text-left",children:U.versionHistory.all.map((de,lt)=>{var zt,bs,wt,De;return e.jsxs("div",{className:`space-y-2 ${lt>0?"pt-2 border-t border-amber-200":""}`,children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(oe,{className:`${lt===0?"bg-amber-500":"bg-gray-400"} text-white text-[10px] px-2 py-0.5`,children:[lt===0?"Current":"Previous",": v",de.version]}),e.jsx("span",{className:"text-[10px] text-gray-600 font-medium",children:Ar(de.createdAt)})]})}),e.jsx("p",{className:"text-xs text-gray-700 font-medium",children:de.changeReason||"Version Update"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:`w-3 h-3 rounded-full ${lt===0?"bg-blue-100":"bg-gray-100"} flex items-center justify-center`,children:e.jsx("span",{className:`text-[8px] font-bold ${lt===0?"text-blue-600":"text-gray-600"}`,children:((bs=(zt=de.changer)==null?void 0:zt.displayName)==null?void 0:bs.charAt(0))||"U"})}),e.jsxs("span",{className:"text-[10px] text-gray-600",children:["By ",((wt=de.changer)==null?void 0:wt.displayName)||((De=de.changer)==null?void 0:De.email)||"Unknown User"]})]}),de.snapshotType==="PROPOSAL"&&de.snapshotData&&e.jsxs("div",{className:"mt-2 p-2 bg-white rounded border border-amber-200",children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold text-gray-700",children:"Proposal Snapshot"}),e.jsxs("p",{className:"text-[10px] text-gray-600",children:["Budget: ₹",Number(de.snapshotData.totalBudget||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),e.jsxs("button",{className:"text-[10px] text-blue-600 hover:text-blue-800 hover:underline font-medium flex items-center gap-1 transition-colors",onClick:()=>D({data:de.snapshotData,type:"PROPOSAL",title:`Proposal (v${de.version})`}),children:[e.jsx(bt,{className:"w-3 h-3"}),"View Details"]})]}),de.snapshotData.comments&&e.jsxs("p",{className:"text-[10px] text-gray-600 mt-1 line-clamp-2",children:["Comments: ",de.snapshotData.comments]})]}),de.snapshotType==="INTERNAL_ORDER"&&de.snapshotData&&e.jsxs("div",{className:"mt-2 p-2 bg-white rounded border border-amber-200",children:[e.jsx("p",{className:"text-[10px] font-semibold text-gray-700 mb-1",children:"IO Block Snapshot:"}),e.jsxs("p",{className:"text-[10px] text-gray-600",children:["IO Number: ",de.snapshotData.ioNumber||"N/A"]}),e.jsxs("p",{className:"text-[10px] text-gray-600",children:["Blocked Amount: ₹",Number(de.snapshotData.blockedAmount||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),de.snapshotData.sapDocumentNumber&&e.jsxs("p",{className:"text-[10px] text-gray-600",children:["SAP Doc: ",de.snapshotData.sapDocumentNumber]})]}),de.snapshotType==="COMPLETION"&&de.snapshotData&&e.jsxs("div",{className:"mt-2 p-2 bg-white rounded border border-amber-200",children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold text-gray-700",children:"Completion Snapshot"}),e.jsxs("p",{className:"text-[10px] text-gray-600",children:["Total: ₹",Number(de.snapshotData.totalExpenses||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),e.jsxs("button",{className:"text-[10px] text-blue-600 hover:text-blue-800 hover:underline font-medium flex items-center gap-1 transition-colors",onClick:()=>D({data:de.snapshotData,type:"COMPLETION",title:`Completion (v${de.version})`}),children:[e.jsx(bt,{className:"w-3 h-3"}),"View Details"]})]}),de.snapshotData.comments&&e.jsxs("p",{className:"text-[10px] text-gray-600 mt-1 line-clamp-2",children:["Comments: ",de.snapshotData.comments]})]}),de.snapshotType==="APPROVE"&&de.snapshotData&&e.jsxs("div",{className:"mt-2 p-2 bg-white rounded border border-amber-200",children:[e.jsxs("p",{className:"text-[10px] font-semibold text-gray-700 mb-1",children:[de.snapshotData.action==="APPROVE"?"Approval":"Rejection"," Snapshot:"]}),e.jsxs("p",{className:"text-[10px] text-gray-600",children:["By: ",de.snapshotData.approverName||de.snapshotData.approverEmail||"Unknown"]}),de.snapshotData.comments&&e.jsxs("p",{className:"text-[10px] text-gray-600 mt-1",children:["Comments: ",de.snapshotData.comments.substring(0,100),de.snapshotData.comments.length>100?"...":""]}),de.snapshotData.rejectionReason&&e.jsxs("p",{className:"text-[10px] text-red-600 mt-1",children:["Rejection Reason: ",de.snapshotData.rejectionReason.substring(0,100),de.snapshotData.rejectionReason.length>100?"...":""]})]}),de.snapshotType==="WORKFLOW"&&de.snapshotData&&de.snapshotData.comments&&e.jsxs("div",{className:"mt-2 p-2 bg-white rounded border border-amber-200",children:[e.jsx("p",{className:"text-[10px] font-semibold text-gray-700 mb-1",children:"Approval Comment:"}),e.jsxs("p",{className:"text-[10px] text-gray-600",children:[de.snapshotData.comments.substring(0,100),de.snapshotData.comments.length>100?"...":""]})]})]},lt)})})]}),ie&&(ye==null?void 0:ye.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:ye.sla.deadline?ga(ye.sla.deadline,!0):"Not set"})]}),e.jsxs("div",{className:`border rounded-lg p-3 ${yt?"bg-gray-100 border-gray-300":(ye.sla.percentageUsed||0)>=100?"bg-red-50 border-red-200":(ye.sla.percentageUsed||0)>=75?"bg-orange-50 border-orange-200":(ye.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(nt,{className:"w-4 h-4"}),"Current Approver - Time Tracking ",yt&&"(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:ye.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:[ye.sla.elapsedText||"0 hours"," / ",Mt(U.tatHours)," allocated"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[(()=>{const de=ye.sla.percentageUsed||0,lt=()=>yt?"bg-gray-500":de>=100?"bg-red-600":de>=75?"bg-orange-500":de>=50?"bg-amber-500":"bg-green-600",zt=()=>yt?"text-gray-600":de>=100?"text-red-600":de>=75?"text-orange-600":de>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(oa,{value:de,className:"h-3",indicatorClassName:lt()}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:`text-xs font-semibold ${zt()}`,children:["Progress: ",Math.min(100,de),"% of TAT used"]}),e.jsxs("span",{className:"text-xs font-medium text-gray-700",children:[ye.sla.remainingText||"0 hours"," remaining"]})]})]})})(),ye.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(li,{className:"w-4 h-4"}),"Deadline Breached"]}),ye.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(os,{className:"w-4 h-4"}),"Approaching Deadline"]})]})]})]}),(()=>{const de=U.levelName||U.level_name;return(de&&de.toLowerCase().includes("department lead")||U.title&&U.title.toLowerCase().includes("department lead"))&&U.status==="approved"&&U.ioDetails&&U.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(Yt,{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:U.ioDetails.ioNumber})]}),U.ioDetails.blockedAmount!==void 0&&U.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:["₹",U.ioDetails.blockedAmount.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),U.ioDetails.remainingBalance!==void 0&&U.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:["₹",U.ioDetails.remainingBalance.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),e.jsxs("div",{className:"pt-1.5 border-t border-blue-100 text-xs text-gray-500",children:["Organised by ",U.ioDetails.organizedBy||U.approver||"N/A"," on"," ",U.ioDetails.organizedAt?Ar(U.ioDetails.organizedAt):U.approvedAt?Ar(U.approvedAt):"N/A"]})]})]})})(),U.step===6&&U.dmsDetails&&U.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(It,{className:"w-4 h-4 text-purple-600"}),e.jsx("p",{className:"text-xs font-semibold text-purple-900 uppercase tracking-wide",children:"E-Invoice & Settlement 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:"Settlement ID:"}),e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:U.dmsDetails.dmsNumber})]}),U.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:"Settlement Remarks:"}),e.jsx("p",{className:"text-sm text-gray-900",children:U.dmsDetails.dmsRemarks})]}),U.dmsDetails.pushedAt&&e.jsxs("div",{className:"pt-1.5 border-t border-purple-100 text-xs text-gray-500",children:["Initiated by ",U.dmsDetails.pushedBy," on"," ",Ar(U.dmsDetails.pushedAt)]})]})]}),(()=>{const de=re.find(De=>(De.step||De.levelNumber||De.level_number)===U.step),lt=((de==null?void 0:de.approverEmail)||"").toLowerCase(),zt=lt&&J===lt,bs=U.step===1||(de==null?void 0:de.levelName)&&de.levelName.toLowerCase().includes("dealer");return ie&&(zt||bs&&Be)})()&&e.jsxs("div",{className:"mt-4 flex gap-2",children:[(()=>{const de=((we==null?void 0:we.levelName)||U.title||"").toLowerCase();return(U.step===1||de.includes("proposal")||de.includes("submission"))&&(Be||We)})()&&e.jsxs(F,{className:"bg-purple-600 hover:bg-purple-700",onClick:()=>{o(!0)},children:[e.jsx(Ks,{className:"w-4 h-4 mr-2"}),"Submit Proposal"]}),(()=>{const de=((we==null?void 0:we.levelName)||U.title||"").toLowerCase();return(de.includes("requestor evaluation")||de.includes("confirmation")||U.step===cs)&&(a||ee)})()&&e.jsxs(F,{className:"bg-blue-600 hover:bg-blue-700",onClick:()=>{d(!0)},children:[e.jsx(Re,{className:"w-4 h-4 mr-2"}),"Review Request"]}),(()=>{const de=re.find(De=>(De.step||De.levelNumber||De.level_number)===U.step);if(!((de==null?void 0:de.levelName)||U.title||"").toLowerCase().includes("initiator action")||!(a||J===ut))return null;const wt=async De=>{var As,$t;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ys=t.requestId||t.id;await Th(ys,De,{reason:""}),K.success(`Action "${De==="REVISE"?"Revision Requested":"Request Reopened"}" performed successfully`),H()}catch(ys){console.error("Failed to perform initiator action:",ys);const e0=(($t=(As=ys==null?void 0:ys.response)==null?void 0:As.data)==null?void 0:$t.message)||(ys==null?void 0:ys.message)||"Failed to perform action";K.error(e0)}};return e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(F,{variant:"outline",className:"border-orange-500 text-orange-600 hover:bg-orange-50",onClick:()=>wt("REVISE"),children:[e.jsx(Ut,{className:"w-4 h-4 mr-2"}),"Request Re-quotation"]}),e.jsxs(F,{variant:"outline",className:"border-blue-500 text-blue-600 hover:bg-blue-50",onClick:()=>wt("REOPEN"),children:[e.jsx(Rx,{className:"w-4 h-4 mr-2"}),"Reopen"]})]})})(),(()=>{const de=re.find($t=>($t.levelName||"").toLowerCase().includes("department lead"));if(!(de&&U.step===(de.step||de.levelNumber||de.level_number)))return null;const zt=((de==null?void 0:de.approverEmail)||"").toLowerCase();if(!(zt&&J===zt||He||vt))return null;const wt=(t==null?void 0:t.internalOrder)||(t==null?void 0:t.internal_order),De=(wt==null?void 0:wt.ioNumber)||(wt==null?void 0:wt.io_number)||(t==null?void 0:t.ioNumber)||"",As=De&&De.trim()!=="";return e.jsxs("div",{className:"space-y-1",children:[e.jsxs(F,{className:"bg-green-600 hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>{h(!0)},disabled:!As,children:[e.jsx(Re,{className:"w-4 h-4 mr-2"}),"Review and Approve"]}),!As&&e.jsx("p",{className:"text-xs text-amber-600",children:"Please add an IO number in the IO tab before approving this step."})]})})(),(()=>{const de=re.find(De=>(De.step||De.levelNumber||De.level_number)===U.step),lt=((de==null?void 0:de.approverEmail)||"").toLowerCase(),zt=Be&&lt===be,bs=((de==null?void 0:de.levelName)||U.title||"").toLowerCase(),wt=bs.includes("dealer completion")||bs.includes("completion documents");return zt&&wt})()&&e.jsxs(F,{className:"bg-purple-600 hover:bg-purple-700",onClick:()=>{u(!0)},children:[e.jsx(Ks,{className:"w-4 h-4 mr-2"}),"Upload Completion Docs"]}),(()=>{const de=re.find(wt=>{const De=(wt.levelName||"").toLowerCase();return De.includes("requestor claim")||De.includes("requestor - claim")});if(!(de&&U.step===(de.step||de.levelNumber||de.level_number)))return null;const zt=((de==null?void 0:de.approverEmail)||"").toLowerCase();return a||zt&&J===zt?e.jsxs(F,{className:"bg-indigo-600 hover:bg-indigo-700",onClick:()=>{b(!0)},children:[e.jsx(It,{className:"w-4 h-4 mr-2"}),"Generate E-Invoice & Sync"]}):null})(),(()=>{var As;const de=((we==null?void 0:we.levelName)||U.title||"").toLowerCase(),lt=de.includes("credit note")||de.includes("sap")||U.step===8&&!de.includes("additional"),zt=((we==null?void 0:we.approverEmail)||"").toLowerCase(),bs=zt&&J===zt,wt=((As=s==null?void 0:s.role)==null?void 0:As.toUpperCase())||"";return lt&&(bs||(wt==="FINANCE"||wt==="ADMIN"))})()&&e.jsxs(F,{className:"bg-green-600 hover:bg-green-700",onClick:()=>{y(!0)},children:[e.jsx(Yt,{className:"w-4 h-4 mr-2"}),"View & Send Credit Note"]}),(()=>{const de=re.find(wt=>(wt.step||wt.levelNumber||wt.level_number)===U.step),lt=((de==null?void 0:de.levelName)||U.title||"").toLowerCase(),zt=lt.includes("additional approver"),bs=U.step===1||lt.includes("proposal")||lt.includes("submission")||lt.includes("requestor evaluation")||lt.includes("confirmation")||lt.includes("department lead")||lt.includes("dealer completion")||lt.includes("completion documents")||lt.includes("requestor claim")||lt.includes("requestor - claim")||lt.includes("credit note")||lt.includes("sap");if(zt||!bs){const wt=(de==null?void 0:de.levelId)||(de==null?void 0:de.level_id);if(wt){const De=(de==null?void 0:de.levelName)||(de==null?void 0:de.level_name)||U.title||"Approval Level",As=(de==null?void 0:de.approverName)||(de==null?void 0:de.approver_name)||U.approver||"Approver";return e.jsxs(F,{className:"bg-blue-600 hover:bg-blue-700",onClick:()=>{R({levelId:wt,levelName:De,approverName:As}),_(!0)},children:[e.jsx(Re,{className:"w-4 h-4 mr-2"}),"Review Request"]})}return e.jsxs(e.Fragment,{children:[e.jsxs(F,{className:"bg-green-600 hover:bg-green-700",onClick:async()=>{var De,As;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const $t=t.id||t.requestId;if(!wt){K.error("Approval level not found");return}await on($t,wt,""),K.success("Request approved successfully"),H()}catch($t){console.error("Failed to approve:",$t);const ys=((As=(De=$t==null?void 0:$t.response)==null?void 0:De.data)==null?void 0:As.message)||($t==null?void 0:$t.message)||"Failed to approve request. Please try again.";K.error(ys)}},children:[e.jsx(Re,{className:"w-4 h-4 mr-2"}),"Approve"]}),e.jsxs(F,{variant:"destructive",onClick:async()=>{var De,As;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const $t=t.id||t.requestId;if(!wt){K.error("Approval level not found");return}const ys=prompt("Please provide a reason for rejection:");if(ys===null)return;await Tr($t,wt,"Request rejected",ys),K.success("Request rejected successfully"),H()}catch($t){console.error("Failed to reject:",$t);const ys=((As=(De=$t==null?void 0:$t.response)==null?void 0:De.data)==null?void 0:As.message)||($t==null?void 0:$t.message)||"Failed to reject request. Please try again.";K.error(ys)}},children:[e.jsx(Ct,{className:"w-4 h-4 mr-2"}),"Reject"]})]})}return null})()]}),U.approvedAt&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Approved on ",Ar(U.approvedAt)]})]})]})},Pe)})})]})]}),e.jsx(xT,{isOpen:l,onClose:()=>o(!1),onSubmit:at,dealerName:La,dealerGSTIN:sr,activityName:Ma,defaultGstRate:(qr=t==null?void 0:t.claimDetails)==null?void 0:qr.defaultGstRate,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),previousProposalData:(en=j==null?void 0:j.find(U=>U.snapshotType==="PROPOSAL"))==null?void 0:en.snapshotData,documentPolicy:i,taxationType:(Ac=t==null?void 0:t.claimDetails)==null?void 0:Ac.taxationType}),e.jsx(fT,{isOpen:c,onClose:()=>{d(!1)},onApprove:Ss,onReject:Kt,onRequestRevision:ct,proposalData:Ca,dealerName:La,activityName:Ma,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),request:t,previousProposalData:(()=>{const U=(j==null?void 0:j.filter(Pe=>Pe.snapshotType==="PROPOSAL"))||[];return U.length>1?U[1].snapshotData:null})(),taxationType:(Tc=t==null?void 0:t.claimDetails)==null?void 0:Tc.taxationType}),e.jsx(hT,{isOpen:m,onClose:()=>h(!1),onApprove:rt,onReject:Vt,requestTitle:t==null?void 0:t.title,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),preFilledIONumber:((kc=t==null?void 0:t.internalOrder)==null?void 0:kc.ioNumber)||((Rc=t==null?void 0:t.internalOrder)==null?void 0:Rc.io_number)||((Dc=t==null?void 0:t.internal_order)==null?void 0:Dc.ioNumber)||((Pc=t==null?void 0:t.internal_order)==null?void 0:Pc.io_number)||void 0,preFilledBlockedAmount:((Ic=t==null?void 0:t.internalOrder)==null?void 0:Ic.ioBlockedAmount)||((Ec=t==null?void 0:t.internalOrder)==null?void 0:Ec.io_blocked_amount)||((Fc=t==null?void 0:t.internal_order)==null?void 0:Fc.ioBlockedAmount)||((_c=t==null?void 0:t.internal_order)==null?void 0:_c.io_blocked_amount)||void 0,preFilledRemainingBalance:((Lc=t==null?void 0:t.internalOrder)==null?void 0:Lc.ioRemainingBalance)||((Mc=t==null?void 0:t.internalOrder)==null?void 0:Mc.io_remaining_balance)||(($c=t==null?void 0:t.internal_order)==null?void 0:$c.ioRemainingBalance)||((Oc=t==null?void 0:t.internal_order)==null?void 0:Oc.io_remaining_balance)||void 0,taxationType:(Uc=t==null?void 0:t.claimDetails)==null?void 0:Uc.taxationType}),e.jsx(uT,{isOpen:x,onClose:()=>u(!1),onSubmit:St,dealerName:La,dealerGSTIN:sr,activityName:Ma,defaultGstRate:(Bc=t==null?void 0:t.claimDetails)==null?void 0:Bc.defaultGstRate,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),documentPolicy:i,taxationType:(Vc=t==null?void 0:t.claimDetails)==null?void 0:Vc.taxationType}),e.jsx(pT,{isOpen:g,onClose:()=>b(!1),onPush:ds,completionDetails:{activityCompletionDate:((zc=t==null?void 0:t.completionDetails)==null?void 0:zc.activityCompletionDate)||((Hc=t==null?void 0:t.completionDetails)==null?void 0:Hc.activity_completion_date),numberOfParticipants:((Gc=t==null?void 0:t.completionDetails)==null?void 0:Gc.numberOfParticipants)||((Wc=t==null?void 0:t.completionDetails)==null?void 0:Wc.number_of_participants),closedExpenses:(t==null?void 0:t.completionExpenses)||(t==null?void 0:t.completion_expenses)||((Yc=t==null?void 0:t.completionDetails)==null?void 0:Yc.closedExpenses)||((Kc=t==null?void 0:t.completionDetails)==null?void 0:Kc.closed_expenses),totalClosedExpenses:((Xc=t==null?void 0:t.budgetTracking)==null?void 0:Xc.closedExpenses)||((Zc=t==null?void 0:t.budgetTracking)==null?void 0:Zc.closed_expenses)||((Jc=t==null?void 0:t.completionDetails)==null?void 0:Jc.totalClosedExpenses)||((Qc=t==null?void 0:t.completionDetails)==null?void 0:Qc.total_closed_expenses),completionDescription:((qc=t==null?void 0:t.completionDetails)==null?void 0:qc.completionDescription)||((ed=t==null?void 0:t.completionDetails)==null?void 0:ed.completion_description)},ioDetails:{ioNumber:((td=t==null?void 0:t.internalOrder)==null?void 0:td.ioNumber)||((sd=t==null?void 0:t.internalOrder)==null?void 0:sd.io_number)||((ad=t==null?void 0:t.internal_order)==null?void 0:ad.ioNumber)||((rd=t==null?void 0:t.internal_order)==null?void 0:rd.io_number),blockedAmount:((nd=t==null?void 0:t.internalOrder)==null?void 0:nd.ioBlockedAmount)||((id=t==null?void 0:t.internalOrder)==null?void 0:id.io_blocked_amount)||((ld=t==null?void 0:t.internal_order)==null?void 0:ld.ioBlockedAmount)||((od=t==null?void 0:t.internal_order)==null?void 0:od.io_blocked_amount),availableBalance:((cd=t==null?void 0:t.internalOrder)==null?void 0:cd.ioAvailableBalance)||((dd=t==null?void 0:t.internalOrder)==null?void 0:dd.io_available_balance)||((md=t==null?void 0:t.internal_order)==null?void 0:md.ioAvailableBalance)||((ud=t==null?void 0:t.internal_order)==null?void 0:ud.io_available_balance),remainingBalance:((xd=t==null?void 0:t.internalOrder)==null?void 0:xd.ioRemainingBalance)||((hd=t==null?void 0:t.internalOrder)==null?void 0:hd.io_remaining_balance)||((pd=t==null?void 0:t.internal_order)==null?void 0:pd.ioRemainingBalance)||((gd=t==null?void 0:t.internal_order)==null?void 0:gd.io_remaining_balance)},completionDocuments:er,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),taxationType:(fd=t==null?void 0:t.claimDetails)==null?void 0:fd.taxationType}),e.jsx(iT,{isOpen:f,onClose:()=>y(!1),taxationType:(bd=t==null?void 0:t.claimDetails)==null?void 0:bd.taxationType,onDownload:async()=>{K.info("Download functionality will be implemented")},onSendToDealer:async()=>{var U,Pe;try{const xe=(t==null?void 0:t.requestId)||(t==null?void 0:t.id);if(!xe){K.error("Request ID not found");return}await ST(xe),K.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=((Pe=(U=xe==null?void 0:xe.response)==null?void 0:U.data)==null?void 0:Pe.message)||(xe==null?void 0:xe.message)||"Failed to send credit note to dealer";K.error(ce)}},creditNoteData:{creditNoteNumber:((yd=t==null?void 0:t.creditNote)==null?void 0:yd.creditNoteNumber)||((vd=t==null?void 0:t.creditNote)==null?void 0:vd.credit_note_number)||((Nd=(jd=t==null?void 0:t.claimDetails)==null?void 0:jd.creditNote)==null?void 0:Nd.creditNoteNumber)||((wd=t==null?void 0:t.claimDetails)==null?void 0:wd.creditNoteNumber)||((Cd=t==null?void 0:t.claimDetails)==null?void 0:Cd.credit_note_number),creditNoteDate:((Sd=t==null?void 0:t.creditNote)==null?void 0:Sd.creditNoteDate)||((Ad=t==null?void 0:t.creditNote)==null?void 0:Ad.credit_note_date)||((kd=(Td=t==null?void 0:t.claimDetails)==null?void 0:Td.creditNote)==null?void 0:kd.creditNoteDate)||((Rd=t==null?void 0:t.claimDetails)==null?void 0:Rd.creditNoteDate)||((Dd=t==null?void 0:t.claimDetails)==null?void 0:Dd.credit_note_date),creditNoteAmount:(Pd=t==null?void 0:t.creditNote)!=null&&Pd.creditNoteAmount?Number((Id=t==null?void 0:t.creditNote)==null?void 0:Id.creditNoteAmount):(Ed=t==null?void 0:t.creditNote)!=null&&Ed.credit_note_amount?Number((Fd=t==null?void 0:t.creditNote)==null?void 0:Fd.credit_note_amount):(Ld=(_d=t==null?void 0:t.claimDetails)==null?void 0:_d.creditNote)!=null&&Ld.creditNoteAmount?Number(($d=(Md=t==null?void 0:t.claimDetails)==null?void 0:Md.creditNote)==null?void 0:$d.creditNoteAmount):(Od=t==null?void 0:t.claimDetails)!=null&&Od.creditNoteAmount?Number((Ud=t==null?void 0:t.claimDetails)==null?void 0:Ud.creditNoteAmount):(Bd=t==null?void 0:t.claimDetails)!=null&&Bd.credit_note_amount?Number((Vd=t==null?void 0:t.claimDetails)==null?void 0:Vd.credit_note_amount):void 0,status:((zd=t==null?void 0:t.creditNote)==null?void 0:zd.status)||((Gd=(Hd=t==null?void 0:t.claimDetails)==null?void 0:Hd.creditNote)==null?void 0:Gd.status)||((Wd=t==null?void 0:t.creditNote)!=null&&Wd.creditNoteNumber?"CONFIRMED":"PENDING")},dealerInfo:{dealerName:((Yd=t==null?void 0:t.claimDetails)==null?void 0:Yd.dealerName)||((Kd=t==null?void 0:t.claimDetails)==null?void 0:Kd.dealer_name),dealerCode:((Xd=t==null?void 0:t.claimDetails)==null?void 0:Xd.dealerCode)||((Zd=t==null?void 0:t.claimDetails)==null?void 0:Zd.dealer_code),dealerEmail:((Jd=t==null?void 0:t.claimDetails)==null?void 0:Jd.dealerEmail)||((Qd=t==null?void 0:t.claimDetails)==null?void 0:Qd.dealer_email)},activityName:((qd=t==null?void 0:t.claimDetails)==null?void 0:qd.activityName)||((em=t==null?void 0:t.claimDetails)==null?void 0:em.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(gT,{isOpen:v,onClose:()=>{C(!1),A(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@undefined"}),T&&e.jsx(nT,{isOpen:N,onClose:()=>{_(!1),R(null)},onApprove:async U=>{var Pe,xe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ce=t.id||t.requestId,he=T.levelId;if(!he){K.error("Approval level not found");return}await on(ce,he,U),K.success("Request approved successfully"),H(),_(!1),R(null)}catch(ce){console.error("Failed to approve:",ce);const he=((xe=(Pe=ce==null?void 0:ce.response)==null?void 0:Pe.data)==null?void 0:xe.message)||(ce==null?void 0:ce.message)||"Failed to approve request. Please try again.";throw K.error(he),ce}},onReject:async U=>{var Pe,xe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ce=t.id||t.requestId,he=T.levelId;if(!he){K.error("Approval level not found");return}await Tr(ce,he,"Request rejected",U),K.success("Request rejected successfully"),H(),_(!1),R(null)}catch(ce){console.error("Failed to reject:",ce);const he=((xe=(Pe=ce==null?void 0:ce.response)==null?void 0:Pe.data)==null?void 0:xe.message)||(ce==null?void 0:ce.message)||"Failed to reject request. Please try again.";throw K.error(he),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:T.levelName,approverName:T.approverName}),j&&j.length>0&&e.jsxs(se,{className:"mt-6 border-amber-100 bg-amber-50/30",children:[e.jsxs(ge,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(fe,{className:"text-sm font-bold flex items-center gap-2 text-amber-900",children:[e.jsx(It,{className:"w-4 h-4"}),"Revision History & Audit Trail"]}),e.jsx(F,{variant:"ghost",size:"sm",onClick:()=>B(!P),className:"text-amber-700 hover:text-amber-800 hover:bg-amber-100",children:P?"Hide History":"View History"})]}),e.jsx(Ue,{className:"text-xs text-amber-700",children:"Records of all revisions and actions taken on this request"})]}),P&&e.jsx(ae,{children:e.jsx("div",{className:"space-y-4",children:j.map((U,Pe)=>{var xe,ce,he,ie;return e.jsxs("div",{className:"relative pl-6 pb-4 border-l-2 border-amber-200 last:border-0 last:pb-0",children:[e.jsx("div",{className:"absolute left-[-9px] top-0 w-4 h-4 rounded-full bg-amber-500 border-2 border-white shadow-sm"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[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-bold text-amber-900",children:["Version ",U.version]}),U.snapshotType&&e.jsx(oe,{className:"bg-blue-100 text-blue-700 text-[9px] px-1.5 py-0",children:U.snapshotType}),U.levelNumber&&e.jsxs(oe,{className:"bg-gray-100 text-gray-600 text-[9px] px-1.5 py-0",children:["Step ",U.levelNumber]})]}),e.jsx("span",{className:"text-[10px] text-amber-600 font-medium bg-amber-100 px-2 py-0.5 rounded-full",children:Ar(U.createdAt)})]}),e.jsx("p",{className:"text-xs font-medium text-gray-800",children:U.changeReason||"Version Update"}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[e.jsx("div",{className:"w-4 h-4 rounded-full bg-blue-100 flex items-center justify-center",children:e.jsx("span",{className:"text-[8px] font-bold text-blue-600",children:((ce=(xe=U.changer)==null?void 0:xe.displayName)==null?void 0:ce.charAt(0))||"U"})}),e.jsxs("span",{className:"text-xs text-gray-500",children:["By ",((he=U.changer)==null?void 0:he.displayName)||((ie=U.changer)==null?void 0:ie.email)||"Unknown User"]})]}),U.snapshotType==="PROPOSAL"&&U.snapshotData&&e.jsxs("div",{className:"mt-2 p-2 bg-white rounded border border-amber-200 text-[10px]",children:[e.jsx("p",{className:"font-semibold text-gray-700 mb-1",children:"Proposal:"}),U.snapshotData.documentUrl&&e.jsx("div",{className:"flex items-center gap-2 mb-1",children:e.jsxs(F,{variant:"link",size:"sm",className:"h-auto p-0 text-blue-600 hover:text-blue-700 font-small flex items-center gap-1",onClick:()=>D({data:U.snapshotData,type:"PROPOSAL",title:`Historical Proposal (Version ${U.version})`}),children:["View Details",e.jsx(bt,{className:"w-2 h-2"})]})}),e.jsxs("p",{className:"text-gray-600",children:["Budget: ₹",Number(U.snapshotData.totalBudget||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),U.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",U.snapshotData.comments.substring(0,80),U.snapshotData.comments.length>80?"...":""]})]}),U.snapshotType==="COMPLETION"&&U.snapshotData&&e.jsxs("div",{className:"mt-2 p-2 bg-white rounded border border-amber-200 text-[10px]",children:[e.jsx("p",{className:"font-semibold text-gray-700 mb-1",children:"Completion:"}),U.snapshotData.documentUrl&&e.jsx("div",{className:"flex items-center gap-2 mb-1",children:e.jsxs(F,{variant:"link",size:"sm",className:"h-auto p-0 text-blue-600 hover:text-blue-700 font-medium flex items-center gap-1",onClick:()=>D({data:U.snapshotData,type:"COMPLETION",title:`Historical Completion (Version ${U.version})`}),children:["View Details",e.jsx(bt,{className:"w-3 h-3"})]})}),e.jsxs("p",{className:"text-gray-600",children:["Total Expenses: ₹",Number(U.snapshotData.totalExpenses||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),U.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",U.snapshotData.comments.substring(0,80),U.snapshotData.comments.length>80?"...":""]})]}),U.snapshotType==="INTERNAL_ORDER"&&U.snapshotData&&e.jsxs("div",{className:"mt-2 p-2 bg-white rounded border border-amber-200 text-[10px]",children:[e.jsx("p",{className:"font-semibold text-gray-700 mb-1",children:"IO Block:"}),e.jsxs("p",{className:"text-gray-600",children:["IO Number: ",U.snapshotData.ioNumber||"N/A"]}),e.jsxs("p",{className:"text-gray-600",children:["Blocked: ₹",Number(U.snapshotData.blockedAmount||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),U.snapshotData.sapDocumentNumber&&e.jsxs("p",{className:"text-gray-600",children:["SAP Doc: ",U.snapshotData.sapDocumentNumber]})]}),U.snapshotType==="APPROVE"&&U.snapshotData&&e.jsxs("div",{className:"mt-2 p-2 bg-white rounded border border-amber-200 text-[10px]",children:[e.jsxs("p",{className:"font-semibold text-gray-700 mb-1",children:[U.snapshotData.action==="APPROVE"?"Approval":"Rejection",":"]}),e.jsxs("p",{className:"text-gray-600",children:["By: ",U.snapshotData.approverName||U.snapshotData.approverEmail||"Unknown"]}),U.snapshotData.levelName&&e.jsxs("p",{className:"text-gray-600",children:["Level: ",U.snapshotData.levelName]}),U.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",U.snapshotData.comments.substring(0,80),U.snapshotData.comments.length>80?"...":""]}),U.snapshotData.rejectionReason&&e.jsxs("p",{className:"text-red-600 mt-1",children:["Rejection Reason: ",U.snapshotData.rejectionReason.substring(0,80),U.snapshotData.rejectionReason.length>80?"...":""]})]}),U.snapshotType==="WORKFLOW"&&U.snapshotData&&e.jsxs("div",{className:"mt-2 p-2 bg-white rounded border border-amber-200 text-[10px]",children:[e.jsx("p",{className:"font-semibold text-gray-700 mb-1",children:"Workflow:"}),e.jsxs("p",{className:"text-gray-600",children:["Status: ",U.snapshotData.status||"N/A"]}),U.snapshotData.currentLevel&&e.jsxs("p",{className:"text-gray-600",children:["Current Level: ",U.snapshotData.currentLevel]})]})]})]},U.historyId||Pe)})})})]}),e.jsx(bT,{isOpen:!!V,onClose:()=>D(null),snapshot:V==null?void 0:V.data,type:(V==null?void 0:V.type)||"PROPOSAL",title:V==null?void 0:V.title}),I&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/60",onClick:tr}),e.jsxs("div",{className:"relative w-[95vw] max-w-5xl h-[90vh] bg-white rounded-xl shadow-2xl flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b bg-gray-50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yt,{className:"w-5 h-5 text-amber-600"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Invoice Preview"}),e.jsx(oe,{className:"bg-amber-100 text-amber-800 text-xs",children:t.requestNumber})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[S&&e.jsxs(F,{variant:"outline",size:"sm",onClick:wr,className:"gap-1.5 text-xs",children:[e.jsx(At,{className:"w-3.5 h-3.5"}),"Download"]}),e.jsx(F,{variant:"ghost",size:"icon",onClick:tr,className:"h-8 w-8 hover:bg-gray-200",children:e.jsx(ft,{className:"w-4 h-4"})})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden",children:W?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-3",children:[e.jsx(it,{className:"w-8 h-8 text-amber-600 animate-spin"}),e.jsx("p",{className:"text-sm text-gray-500",children:"Loading invoice..."})]}):S?e.jsx("iframe",{src:S,className:"w-full h-full border-0",title:"Invoice PDF Preview"}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Failed to load invoice"})})})]})]})]})}function IT({request:t,apiRequest:s,onRefresh:a}){const{user:r}=Jt(),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.ioBlockedAmount)||(i==null?void 0:i.io_blocked_amount)||0,c=(i==null?void 0:i.ioAvailableBalance)||(i==null?void 0:i.io_available_balance)||0,d=(i==null?void 0:i.ioRemainingBalance)||(i==null?void 0:i.io_remaining_balance)||0,m=(i==null?void 0:i.sapDocumentNumber)||(i==null?void 0:i.sap_document_number)||"",h=(i==null?void 0:i.organizer)||null,x=(s==null?void 0:s.proposalDetails)||{},u=Number((x==null?void 0:x.totalEstimatedBudget)||(x==null?void 0:x.total_estimated_budget)||0),[g,b]=p.useState(l),[f,y]=p.useState(!1),[v,C]=p.useState(null),[w,A]=p.useState(""),[N,_]=p.useState(null),[T,R]=p.useState(!1);p.useEffect(()=>{if(i&&l){const P=Number(c)||0,B=(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(b(l),o>0){const k=Number(o)||0,L=Number(d)||0,V=P-k;Math.abs(L-V)>.01&&console.warn("[IOTab] ⚠️ Remaining balance calculation issue detected!",{availableBalance:P,blockedAmount:k,expectedRemaining:V,backendRemaining:L,difference:L-V}),_({ioNumber:l,blockedAmount:k,availableBalance:P,remainingBalance:L,blockedDate:i.organizedAt||i.organized_at||new Date().toISOString(),blockedBy:B,sapDocumentNumber:m,status:i.status==="BLOCKED"?"blocked":i.status==="RELEASED"?"released":"blocked"}),P>0&&C(P)}}},[i,l,o,c,d,m,h]);const j=async()=>{var P,B;if(!g.trim()){K.error("Please enter an IO number");return}if(!n){K.error("Request ID not found");return}y(!0);try{const k=await wT(n,g.trim());k.isValid&&k.availableBalance>0?(C(k.availableBalance),u>0?A(String(u)):A(String(k.availableBalance)),K.success(`IO fetched from SAP. Available balance: ₹${k.availableBalance.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`)):(K.error("Invalid IO number or no available balance found"),C(null),A(""))}catch(k){console.error("Failed to fetch IO budget:",k);const L=((B=(P=k==null?void 0:k.response)==null?void 0:P.data)==null?void 0:B.message)||(k==null?void 0:k.message)||"Failed to validate IO number or fetch budget from SAP";K.error(L),C(null)}finally{y(!1)}},E=async()=>{var k,L;if(!g.trim()||v===null){K.error("Please fetch IO amount first");return}if(!n){K.error("Request ID not found");return}const P=parseFloat(w);if(!w||isNaN(P)||P<=0){K.error("Please enter a valid amount to block");return}const B=parseFloat(P.toFixed(2));if(B>v){K.error("Amount to block exceeds available IO budget");return}if(u>0){const V=parseFloat(u.toFixed(2));if(Math.abs(B-V)>.01){K.error(`Amount to block must be exactly equal to the estimated budget (₹${V.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})})`);return}}R(!0);try{const V=parseFloat(v.toFixed(2)),D=parseFloat((V-B).toFixed(2)),S={ioNumber:g.trim(),ioAvailableBalance:V,ioBlockedAmount:B,ioRemainingBalance:D};await Eg(n,S);const O=await vT(n),I=(O==null?void 0:O.internalOrder)||(O==null?void 0:O.internal_order);if(I){const M=Number(I.ioBlockedAmount||I.io_blocked_amount||B),W=Number(I.ioRemainingBalance||I.io_remaining_balance||0),G=v-M;Math.abs(M-B)>.01&&console.warn("[IOTab] ⚠️ Amount mismatch! Sent:",B,"Saved:",M),Math.abs(W-G)>.01&&console.warn("[IOTab] ⚠️ Remaining balance calculation issue detected!",{availableBalance:v,blockedAmount:M,expectedRemaining:G,backendRemaining:W,difference:W-G});const re=r,te=(re==null?void 0:re.displayName)||(re==null?void 0:re.display_name)||(re==null?void 0:re.name)||(re!=null&&re.firstName&&(re!=null&&re.lastName)?`${re.firstName} ${re.lastName}`.trim():null)||(re==null?void 0:re.email)||"Current User",$={ioNumber:I.ioNumber||I.io_number||g,blockedAmount:M,availableBalance:v,remainingBalance:W,blockedDate:I.organizedAt||I.organized_at||new Date().toISOString(),blockedBy:te,sapDocumentNumber:I.sapDocumentNumber||I.sap_document_number||"",status:"blocked"};_($),A(""),K.success("IO budget blocked successfully in SAP"),a==null||a()}else K.error("IO blocked but failed to fetch updated details"),a==null||a()}catch(V){console.error("Failed to block IO budget:",V);const D=((L=(k=V==null?void 0:V.response)==null?void 0:k.data)==null?void 0:L.message)||(V==null?void 0:V.message)||"Failed to block IO budget in SAP";K.error(D)}finally{R(!1)}};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(se,{children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(Pa,{className:"w-5 h-5 text-[#2d4a3e]"}),"IO Budget Management"]}),e.jsx(Ue,{children:"Enter IO number to fetch available budget from SAP"})]}),e.jsxs(ae,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(ne,{htmlFor:"ioNumber",children:"IO Number *"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ie,{id:"ioNumber",placeholder:"Enter IO number (e.g., IO-2024-12345)",value:g,onChange:P=>b(P.target.value),disabled:f||!!N,className:"flex-1"}),e.jsxs(F,{onClick:j,disabled:!g.trim()||f||!!N,className:"bg-[#2d4a3e] hover:bg-[#1f3329]",children:[e.jsx(At,{className:"w-4 h-4 mr-2"}),f?"Fetching...":"Fetch Amount"]})]})]}),!v&&!N&&g.trim()&&e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4",children:e.jsxs("p",{className:"text-sm text-blue-800",children:[e.jsx("strong",{children:"Next Step:"}),' Click "Fetch Amount" to validate the IO number and get available balance from SAP.']})}),v!==null&&!N&&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:["₹",v.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),e.jsx(Re,{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(ne,{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(Ie,{type:"number",id:"blockAmount",placeholder:"Enter amount to block",min:"0",step:"0.01",value:w,onChange:P=>A(P.target.value),className:"pl-8"})]}),u>0&&e.jsx("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-xs text-amber-800",children:[e.jsx("strong",{children:"Required:"})," Amount must be exactly equal to the estimated budget: ",e.jsxs("strong",{children:["₹",u.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})})]}),e.jsxs(F,{onClick:E,disabled:T||!w||parseFloat(w)<=0||parseFloat(w)>v||u>0&&Math.abs(parseFloat(w)-u)>.01,className:"w-full bg-[#2d4a3e] hover:bg-[#1f3329]",children:[e.jsx(Bt,{className:"w-4 h-4 mr-2"}),T?"Blocking in SAP...":"Block IO in SAP"]})]})]})]}),e.jsxs(se,{children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(Re,{className:"w-5 h-5 text-green-600"}),"IO Blocked Details"]}),e.jsx(Ue,{children:"Details of IO blocked in SAP system"})]}),e.jsx(ae,{children:N?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(Re,{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:N.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:N.sapDocumentNumber||"N/A"})]}),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:["₹",N.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:["₹",N.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:["₹",N.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:N.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(N.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(oe,{className:"bg-green-100 text-green-800 border-green-200",children:[e.jsx(Re,{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"})]})})]})]})}async function ET(t,s=10){var a;try{const r={limit:s};t&&(r.q=t);const n=await ve.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 FT(t){var s,a,r;try{const n=await ve.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 $s=[{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 _T({formData:t,updateFormData:s,onValidationError:a,currentUserEmail:r="",currentUserId:n="",currentUserName:i="",onValidate:l,maxApprovalLevels:o,onPolicyViolation:c}){const{userSearchResults:d,userSearchLoading:m,searchUsersForIndex:h,clearSearchForIndex:x}=ug(),[u,g]=p.useState(!1),[b,f]=p.useState(""),[y,v]=p.useState(24),[C,w]=p.useState("hours"),[A,N]=p.useState(3),[_,T]=p.useState([]),[R,j]=p.useState(!1),[E,P]=p.useState(null),B=p.useRef(null),k=()=>{const $=t.approvers||[],z=[];return $s.forEach(H=>{if(H.isAuto||H.approverType==="dealer"||H.approverType==="initiator")return;const je=$.find(le=>le.level===H.level);(!je||!je.email||!je.userId||!je.tat)&&z.push(`${H.name}`)}),{isValid:z.length===0,missingSteps:z}};p.useEffect(()=>{if(l){const $=k();l($.isValid)}},[t.approvers]),p.useEffect(()=>{const $=t.approvers||[];if($.length>0){const z=[],H=$.filter(le=>le.isAdditional);$s.forEach(le=>{const ue=$.find($e=>$e.originalStepLevel===le.level||!$e.originalStepLevel&&!$e.isAdditional&&$e.level===le.level);if(ue)z.push(ue);else if(le.isAuto){const $e=le.level===8?"finance@royalenfield.com":"system@royalenfield.com",Te=le.level===8?"System/Finance":"System";z.push({email:$e,name:Te,level:le.level,tat:le.defaultTat,tatType:"hours",originalStepLevel:le.level})}else le.approverType==="dealer"?z.push({email:t.dealerEmail||"",name:t.dealerName||"",level:le.level,tat:le.defaultTat,tatType:"hours",originalStepLevel:le.level}):le.approverType==="initiator"?z.push({email:r||"",name:i||r||"User",userId:n,level:le.level,tat:le.defaultTat,tatType:"hours",originalStepLevel:le.level}):z.push({email:"",name:"",level:le.level,tat:le.defaultTat,tatType:"hours",originalStepLevel:le.level})}),H.forEach(le=>{z.push(le)}),z.sort((le,ue)=>le.level-ue.level),JSON.stringify($.map(le=>({level:le.level,originalStepLevel:le.originalStepLevel})))!==JSON.stringify(z.map(le=>({level:le.level,originalStepLevel:le.originalStepLevel})))&&s("approvers",z)}else{const z=[];$s.forEach(H=>{H.isAuto||(H.approverType==="dealer"?z.push({email:t.dealerEmail||"",name:t.dealerName||"",level:H.level,tat:H.defaultTat,tatType:"hours",originalStepLevel:H.level}):H.approverType==="initiator"?z.push({email:r||"",name:i||r||"User",userId:n,level:H.level,tat:H.defaultTat,tatType:"hours",originalStepLevel:H.level}):z.push({email:"",name:"",level:H.level,tat:H.defaultTat,tatType:"hours",originalStepLevel:H.level}))}),s("approvers",z)}},[t.dealerEmail,t.dealerName,r,n,i]);const L=($,z)=>{const H=[...t.approvers||[]],je=H.findIndex(le=>le.originalStepLevel===$||!le.originalStepLevel&&le.level===$&&!le.isAdditional);if(je===-1){const le=$s.find(ue=>ue.level===$);H.push({email:z,name:"",level:$,tat:(le==null?void 0:le.defaultTat)||48,tatType:"hours",originalStepLevel:$})}else{const le=H[je];if(le){const ue=le.email;H[je]={...le,email:z,name:z!==ue?"":le.name,userId:z!==ue?void 0:le.userId}}}if(s("approvers",H),!z||!z.startsWith("@")||z.length<2){x($-1);return}h($-1,z,10)},V=async($,z)=>{var H,je;try{const le=$s.find(Fe=>Fe.level===$);if(le&&!le.isAuto&&le.approverType!=="initiator"&&((H=z.email)==null?void 0:H.toLowerCase())===(r==null?void 0:r.toLowerCase())){K.error(`You cannot assign yourself as ${le.name} approver.`),a&&a({type:"self-assign",email:z.email,message:`You cannot assign yourself as ${le.name} approver.`});return}if((t.approvers||[]).some(Fe=>{var Q,pe;return Fe.level!==$&&(Fe.userId===z.userId||((Q=Fe.email)==null?void 0:Q.toLowerCase())===((pe=z.email)==null?void 0:pe.toLowerCase()))})){K.error("This user is already assigned to another step."),a&&a({type:"error",email:z.email,message:"This user is already assigned to another step."});return}const Te=await la({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}),Ve=[...t.approvers||[]],Qe=Ve.findIndex(Fe=>Fe.originalStepLevel===$||!Fe.originalStepLevel&&Fe.level===$&&!Fe.isAdditional);if(Qe===-1){const Fe=$s.find(Q=>Q.level===$);Ve.push({email:z.email,name:z.displayName||[z.firstName,z.lastName].filter(Boolean).join(" "),userId:Te.userId,level:$,tat:(Fe==null?void 0:Fe.defaultTat)||48,tatType:"hours",originalStepLevel:$})}else{const Fe=Ve[Qe];Fe&&(Ve[Qe]={...Fe,email:z.email,name:z.displayName||[z.firstName,z.lastName].filter(Boolean).join(" "),userId:Te.userId,originalStepLevel:Fe.originalStepLevel||$})}s("approvers",Ve),x($-1),K.success(`Approver for ${(je=$s.find(Fe=>Fe.level===$))==null?void 0:je.name} selected successfully.`)}catch(le){console.error("Failed to ensure user exists:",le),K.error("Failed to validate user. Please try again."),a&&a({type:"error",email:z.email,message:"Failed to validate user. Please try again."})}},D=($,z)=>{const H=[...t.approvers||[]],je=H.findIndex(le=>le.originalStepLevel===$||!le.originalStepLevel&&le.level===$&&!le.isAdditional);if(je!==-1){const le=H[je];le&&(H[je]={...le,tat:z},s("approvers",H))}},S=($,z)=>{const H=[...t.approvers||[]],je=H.findIndex(le=>le.originalStepLevel===$||!le.originalStepLevel&&le.level===$&&!le.isAdditional);if(je!==-1){const le=H[je];le&&(H[je]={...le,tatType:z,tat:""},s("approvers",H))}},O=$=>{if(f($),E&&E.email.toLowerCase()!==$.toLowerCase()&&P(null),B.current&&clearTimeout(B.current),!$||!$.startsWith("@")||$.length<2){T([]),j(!1);return}j(!0),B.current=setTimeout(async()=>{var z;try{const H=$.slice(1),le=((z=(await ca(H,10)).data)==null?void 0:z.data)||[];T(le)}catch(H){console.error("Search failed:",H),T([])}finally{j(!1)}},300)},I=async $=>{try{await la({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}),f($.email),P($),T([]),j(!1)}catch(z){console.error("Failed to ensure user exists:",z),K.error("Failed to verify user. Please try again.")}},M=async()=>{var Q,pe;const $=b.trim().toLowerCase();if(!$){K.error("Please enter an email address");return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test($)){K.error("Please enter a valid email address");return}const H=typeof y=="string"?Number(y):y;if(!H||H<=0||isNaN(H)){K.error("Please enter valid TAT (minimum 1)");return}const je=C==="days"?30:720;if((C==="days"?H*24:H)>720){K.error(`TAT cannot exceed ${je} ${C==="days"?"days":"hours"}`);return}const ue=$s.find(Ce=>Ce.name==="Requestor Claim Approval");if(ue&&A>=ue.level){K.error('Additional approvers cannot be added after "Requestor Claim Approval" as it is considered final.');return}if($===(r==null?void 0:r.toLowerCase())){K.error("You cannot add yourself as an additional approver.");return}const $e=t.approvers||[];if($e.some(Ce=>{var Oe;return Ce.userId&&(E==null?void 0:E.userId)&&Ce.userId===E.userId||((Oe=Ce.email)==null?void 0:Oe.toLowerCase())===$})){K.error("This user is already assigned as an approver.");return}const Ve=$e.find(Ce=>Ce.originalStepLevel===A||!Ce.originalStepLevel&&!Ce.isAdditional&&Ce.level===A),Fe=(Ve?Ve.level:A)+1;if(o){const Oe=new Set($e.map(X=>X.level)).size+1;if(Oe>o){const X=[{type:"max_approval_levels",message:`Adding this approver would create ${Oe} approval levels, which exceeds the maximum allowed (${o}). Please remove some approvers before adding a new one.`,currentValue:Oe,maxValue:o}];c?c(X):K.error(((Q=X[0])==null?void 0:Q.message)||"Maximum approval levels exceeded");return}}if(!E||E.email.toLowerCase()!==$)try{const Oe=((pe=(await ca($,1)).data)==null?void 0:pe.data)||[];if(Oe.length===0){K.error("User not found in organization directory. Please use @ to search for users.");return}const X=Oe[0];await la({userId:X.userId,email:X.email,displayName:X.displayName,firstName:X.firstName,lastName:X.lastName,department:X.department,phone:X.phone,mobilePhone:X.mobilePhone,designation:X.designation,jobTitle:X.jobTitle,manager:X.manager,employeeId:X.employeeId,employeeNumber:X.employeeNumber,secondEmail:X.secondEmail,location:X.location});const Z={email:X.email,name:X.displayName||[X.firstName,X.lastName].filter(Boolean).join(" "),userId:X.userId,level:Fe,tat:typeof y=="string"?Number(y):y,tatType:C,isAdditional:!0,insertAfterLevel:A,stepName:`Additional Approver - ${X.displayName||X.email}`},me=$e.map(J=>J.level>=Fe?{...J,level:J.level+1}:J);me.push(Z),me.sort((J,be)=>J.level-be.level),s("approvers",me),K.success("Additional approver added and subsequent steps shifted")}catch(Ce){console.error("Failed to validate approver:",Ce),K.error("Failed to validate user. Please try again.");return}else{const Ce={email:E.email,name:E.displayName||[E.firstName,E.lastName].filter(Boolean).join(" "),userId:E.userId,level:Fe,tat:y,tatType:C,isAdditional:!0,insertAfterLevel:A,stepName:`Additional Approver - ${E.displayName||E.email}`},Oe=$e.map(X=>X.level>=Fe?{...X,level:X.level+1}:X);Oe.push(Ce),Oe.sort((X,Z)=>X.level-Z.level),s("approvers",Oe),K.success("Additional approver added and subsequent steps shifted")}f(""),v(24),w("hours"),N(3),P(null),T([]),g(!1)},W=$=>{const z=[...t.approvers||[]];if(!z.find(ue=>ue.level===$))return;const le=z.filter(ue=>ue.level!==$).map(ue=>ue.level>$&&!ue.isAdditional?{...ue,level:ue.level-1}:ue);le.sort((ue,$e)=>ue.level-$e.level),s("approvers",le),K.success("Additional approver removed and subsequent steps shifted back")},G=()=>[...t.approvers||[]].sort((z,H)=>z.level-H.level),re=t.approvers||[],te=G();return e.jsxs(is.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(ps,{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(se,{className:"border-2 border-blue-200 bg-blue-50",children:e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2 text-blue-900",children:[e.jsx(Hr,{className:"w-5 h-5"}),"Workflow Steps Information"]}),e.jsxs(Ue,{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.',o&&e.jsxs("span",{className:"block mt-2 text-gray-600",children:["Max: ",o," level",o!==1?"s":"",(()=>{const $=t.approvers||[],H=new Set($.map(je=>je.level)).size;return H>0?e.jsxs("span",{children:[" (",H,"/",o,")"]}):null})()]})]})]})}),e.jsxs(se,{className:"border-2",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(Ns,{className:"w-5 h-5"}),"Approval Hierarchy"]}),e.jsx(Ue,{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(ae,{className:"space-y-2 pt-4",children:[e.jsxs("div",{className:"mb-4 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2",children:[o&&e.jsxs("p",{className:"text-sm text-gray-600",children:["Max: ",o," level",o!==1?"s":"",(()=>{const $=t.approvers||[],H=new Set($.map(je=>je.level)).size;return H>0?e.jsxs("span",{children:[" (",H,"/",o,")"]}):null})()]}),e.jsxs(F,{type:"button",variant:"outline",onClick:()=>g(!0),className:"flex items-center gap-2",children:[e.jsx(gs,{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(Gt,{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(oe,{variant:"secondary",className:"text-xs",children:"YOU"})]}),e.jsx("p",{className:"text-xs text-blue-700",children:"Creates and submits the request"})]})]})}),(()=>{const $=te.filter(H=>H.isAdditional&&H.insertAfterLevel===0);let z=$.length;return $s.filter(H=>!H.isAuto).map((H,je,le)=>{const ue=re.find(Q=>Q.originalStepLevel===H.level||!Q.originalStepLevel&&Q.level===H.level&&!Q.isAdditional)||{email:"",name:"",level:H.level,tat:H.defaultTat,tatType:"hours",originalStepLevel:H.level},$e=je===le.length-1,Te=H.isAuto||H.approverType==="dealer"||H.approverType==="initiator",Ve=!H.isAuto,Qe=te.filter(Q=>Q.isAdditional&&Q.insertAfterLevel===H.level).sort((Q,pe)=>Q.level-pe.level),Fe=z+1;return z++,z+=Qe.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"})}),je===0&&$.map((Q,pe)=>{const Ce=pe+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:Ce})}),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(oe,{variant:"outline",className:"text-xs bg-purple-50 text-purple-700 border-purple-300",children:"ADDITIONAL"}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",onClick:()=>W(Q.level),className:"h-6 w-6 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",children:e.jsx(ft,{className:"w-3 h-3"})})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:Q.name||Q.email}),e.jsxs("div",{className:"text-xs text-gray-500",children:[e.jsxs("div",{children:["Email: ",Q.email]}),e.jsxs("div",{children:["TAT: ",Q.tat," ",Q.tatType]})]})]})]})})]},`additional-${Q.level}`)}),e.jsx("div",{className:`p-3 rounded-lg border-2 transition-all ${ue.email&&ue.userId?"border-green-200 bg-green-50":Te?"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 ${ue.email&&ue.userId?"bg-green-600":Te?"bg-blue-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold text-sm",children:Fe})}),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:H.name}),$e&&e.jsx(oe,{variant:"destructive",className:"text-xs",children:"FINAL"}),Te&&e.jsx(oe,{variant:"outline",className:"text-xs",children:"PRE-FILLED"})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:H.description}),Ve&&(()=>{var Ce,Oe;const Q=!!(ue.email&&ue.userId),pe=!ue.email&&!Te;return 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(ne,{htmlFor:`approver-${H.level}`,className:`text-xs font-bold ${pe?"text-blue-900":Q?"text-green-900":"text-gray-900"}`,children:["Approver Email ",!Te&&"*",pe&&e.jsx("span",{className:"ml-2 text-[10px] font-semibold italic text-blue-600",children:"(Required)"})]}),Q&&e.jsxs(oe,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(Re,{className:"w-3 h-3 mr-1"}),"Verified"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Ie,{id:`approver-${H.level}`,type:"text",placeholder:Te?ue.email:"@username or email...",value:ue.email||"",onChange:X=>{const Z=X.target.value;Te||L(H.level,Z)},disabled:Te||H.isAuto,className:`h-9 border-2 transition-all mt-1 w-full text-sm ${Te?"bg-gray-100/80 border-gray-300 text-gray-700 cursor-not-allowed font-medium":Q?"bg-green-50/50 border-green-600 focus:border-green-700 ring-offset-green-50 focus:ring-1 focus:ring-green-100 font-semibold text-gray-900":"bg-white border-blue-300 shadow-sm shadow-blue-100/50 focus:border-blue-500 focus:ring-1 focus:ring-blue-100 text-gray-900"}`}),!Te&&!H.isAuto&&(m[H.level-1]||(((Ce=d[H.level-1])==null?void 0:Ce.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:m[H.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:(Oe=d[H.level-1])==null?void 0:Oe.map(X=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>V(H.level,X),children:[e.jsx("div",{className:"font-medium text-gray-900",children:X.displayName||X.email}),e.jsx("div",{className:"text-xs text-gray-600",children:X.email}),X.department&&e.jsx("div",{className:"text-xs text-gray-500",children:X.department})]},X.userId))})})]}),ue.name&&e.jsxs("p",{className:"text-xs text-green-600 mt-1",children:["Selected: ",e.jsx("span",{className:"font-semibold",children:ue.name})]})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:`tat-${H.level}`,className:`text-xs font-bold ${pe?"text-blue-900":Q?"text-green-900":"text-gray-900"}`,children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Ie,{id:`tat-${H.level}`,type:"number",placeholder:ue.tatType==="days"?"7":"24",min:"1",max:ue.tatType==="days"?"30":"720",value:ue.tat||"",onChange:X=>D(H.level,parseInt(X.target.value)||""),disabled:H.isAuto,className:`h-9 border-2 transition-all flex-1 text-sm ${Te?"bg-gray-100/80 border-gray-300 text-gray-700 cursor-not-allowed font-medium":Q?"bg-green-50/50 border-green-600 focus:border-green-700 focus:ring-1 focus:ring-green-100 font-semibold text-gray-900":"bg-white border-blue-300 shadow-sm shadow-blue-100/50 focus:border-blue-500 focus:ring-1 focus:ring-blue-100 text-gray-900"}`}),e.jsxs(Ke,{value:ue.tatType||"hours",onValueChange:X=>S(H.level,X),disabled:H.isAuto,children:[e.jsx(Ze,{className:`w-20 h-9 border-2 transition-all text-sm ${Te?"bg-gray-100/80 border-gray-300 text-gray-700 cursor-not-allowed":Q?"bg-green-50/50 border-green-600 focus:border-green-700 focus:ring-1 focus:ring-green-100 text-gray-900 font-medium":"bg-white border-blue-300 focus:border-blue-500 focus:ring-1 focus:ring-blue-100 text-gray-900"}`,children:e.jsx(Xe,{})}),e.jsxs(Je,{children:[e.jsx(Y,{value:"hours",children:"Hours"}),e.jsx(Y,{value:"days",children:"Days"})]})]})]})]})]})})()]})]})}),Qe.map((Q,pe)=>{const Ce=Fe+pe+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:Ce})}),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:Q.stepName||"Additional Approver"}),e.jsx(oe,{variant:"outline",className:"text-xs bg-purple-50 text-purple-700 border-purple-300",children:"ADDITIONAL"}),Q.email&&Q.userId&&e.jsxs(oe,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(Re,{className:"w-3 h-3 mr-1"}),"Verified"]}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",onClick:()=>W(Q.level),className:"h-6 w-6 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",children:e.jsx(ft,{className:"w-3 h-3"})})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:Q.name||Q.email||"No approver assigned"}),Q.email&&e.jsxs("div",{className:"text-xs text-gray-500 space-y-1",children:[e.jsxs("div",{children:["Email: ",Q.email]}),Q.tat&&e.jsxs("div",{children:["TAT: ",Q.tat," ",Q.tatType]})]})]})]})})]},`additional-${Q.level}`)})]},H.level)})})()]})]}),e.jsxs(se,{className:"border-2",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(nt,{className:"w-5 h-5"}),"TAT Summary"]})}),e.jsx(ae,{children:e.jsx("div",{className:"space-y-3",children:te.map($=>{const z=$.originalStepLevel?$s.find(ue=>ue.level===$.originalStepLevel):$s.find(ue=>ue.level===$.level&&!$.isAdditional);if(z!=null&&z.isAuto)return null;const H=Number($.tat||0),le=($.tatType||"hours")==="days"?H*24:H;if(!H)return null;if($.isAdditional){const ue=$s.find($e=>$e.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 "${(ue==null?void 0:ue.name)||"Unknown"}")`}),e.jsxs("span",{className:"text-sm text-gray-600",children:[le," 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:(z==null?void 0:z.name)||"Unknown"}),e.jsxs("span",{className:"text-sm text-gray-600",children:[le," hours"]})]},$.level)})})})]})]}),e.jsx(ht,{open:u,onOpenChange:g,children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(pt,{children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(gs,{className:"w-5 h-5 text-blue-600"}),"Add Additional Approver"]}),e.jsx(Pt,{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(ne,{className:"text-sm font-medium",children:"Insert After Step *"}),e.jsxs(Ke,{value:A.toString(),onValueChange:$=>N(Number($)),children:[e.jsx(Ze,{className:"h-11 border-gray-300",children:e.jsx(Xe,{placeholder:"Select step"})}),e.jsx(Je,{children:$s.filter($=>{if($.isAuto)return!1;const z=$s.find(H=>H.name==="Requestor Claim Approval");return!(z&&$.level>=z.level)}).map($=>e.jsx(Y,{value:$.level.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ns,{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.'}),o&&e.jsxs("p",{className:"text-xs text-gray-600 mt-2",children:["Max: ",o," level",o!==1?"s":"",(()=>{const $=t.approvers||[],H=new Set($.map(je=>je.level)).size;return H>0?e.jsxs("span",{children:[" (",H,"/",o,")"]}):null})()]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-sm font-medium",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ie,{type:"number",min:"1",max:C==="days"?"30":"720",value:y,onChange:$=>{const z=$.target.value;if(z==="")v("");else{const H=Number(z);!isNaN(H)&&H>=0&&v(H)}},onBlur:$=>{const z=$.target.value;(!z||z===""||Number(z)<=0)&&v(24)},className:"h-11 border-gray-300 flex-1",placeholder:"24"}),e.jsxs(Ke,{value:C,onValueChange:$=>w($),children:[e.jsx(Ze,{className:"w-24 h-11 border-gray-300",children:e.jsx(Xe,{})}),e.jsxs(Je,{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-",C==="days"?"30 days":"720 hours",")"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-sm font-medium",children:"Email Address *"}),e.jsxs("div",{className:"relative",children:[e.jsx(Si,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Ie,{type:"text",placeholder:"@username or user@example.com",value:b,onChange:$=>O($.target.value),className:"pl-10 h-11 border-gray-300",autoFocus:!0}),(R||_.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:R?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):_.length>0?e.jsx("ul",{className:"divide-y",children:_.map($=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>I($),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(Rt,{children:[e.jsx(F,{type:"button",variant:"outline",onClick:()=>{g(!1),f(""),v(24),w("hours"),N(3),P(null),T([])},className:"flex-1",children:"Cancel"}),e.jsxs(F,{type:"button",onClick:M,className:"flex-1 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:!b.trim()||!y,children:[e.jsx(gs,{className:"w-4 h-4 mr-2"}),"Add Approver"]})]})]})})]})}const Cl=[{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"}],Sl=["Claim Details","Approver Selection","Review & Submit"];function LT({onBack:t,onSubmit:s}){const{user:a}=Jt(),[r,n]=p.useState(1),[i,l]=p.useState(!1),[o,c]=p.useState([]),[d,m]=p.useState(!1),[h,x]=p.useState(""),u=p.useRef(null),[g,b]=p.useState(!1),f=p.useRef(null),[y,v]=p.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[C,w]=p.useState({open:!1,violations:[]}),[A,N]=p.useState([]),[_,T]=p.useState(!0);p.useEffect(()=>{(async()=>{try{T(!0);const M=await RS();N(M)}catch(M){console.error("Failed to load activity types:",M),K.error("Failed to load activity types. Please refresh the page.")}finally{T(!1)}})()},[]),p.useEffect(()=>{(async()=>{var M;try{const W=await Qs("SYSTEM_SETTINGS"),G=await Qs("WORKFLOW_SHARING"),re=[...W,...G],te={};re.forEach($=>{te[$.configKey]=$.configValue}),v({maxApprovalLevels:parseInt(te.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(te.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((M=te.ALLOW_ADD_SPECTATOR)==null?void 0:M.toLowerCase())==="true",maxSpectators:parseInt(te.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(W){console.error("Failed to load system policy:",W)}})()},[]),p.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const[R,j]=p.useState({activityName:"",activityType:"",dealerCode:"",dealerName:"",dealerEmail:"",dealerPhone:"",dealerAddress:"",activityDate:void 0,location:"",requestDescription:"",periodStartDate:void 0,periodEndDate:void 0,estimatedBudget:"",approvers:[]}),E=Sl.length,P=I=>{if(x(I),u.current&&clearTimeout(u.current),!I||I.trim().length<2){c([]),m(!1);return}m(!0),u.current=setTimeout(async()=>{try{const M=await ET(I,10);c(M)}catch(M){console.error("Error searching dealers:",M),c([])}finally{m(!1)}},300)},B=(I,M)=>{j(W=>{const G={...W,[I]:M};if(I==="periodStartDate")M&&G.periodEndDate&&M>G.periodEndDate&&(G.periodEndDate=void 0,K.error("End date must be on or after the start date. End date has been cleared."));else if(I==="periodEndDate"&&M&&G.periodStartDate&&M<G.periodStartDate)return K.error("End date must be on or after the start date."),W;return G})},k=()=>{switch(r){case 1:return R.activityName&&R.activityType&&R.dealerCode&&R.dealerName&&R.activityDate&&R.location&&R.requestDescription;case 2:const M=(R.approvers||[]).find(W=>W.originalStepLevel===3||!W.originalStepLevel&&W.level===3&&!W.isAdditional);return(M==null?void 0:M.email)&&(M==null?void 0:M.userId)&&(M==null?void 0:M.tat);case 3:return!0;default:return!1}},L=()=>{if(r<E){if(!k()){if(r===2){const M=(R.approvers||[]).find(G=>G.originalStepLevel===3||!G.originalStepLevel&&G.level===3&&!G.isAdditional),W=[];(!(M!=null&&M.email)||!(M!=null&&M.userId)||!(M!=null&&M.tat))&&W.push("Department Lead Approval"),W.length>0?K.error(`Please add missing approvers: ${W.join(", ")}`):K.error("Please complete all required approver selections (email, user verification, and TAT) before proceeding.")}else K.error("Please complete all required fields before proceeding.");return}n(r+1)}},V=()=>{r>1&&n(r-1)},D=async I=>{l(!0);try{const M=await FT(I.dealerCode);if(!M.isLoggedIn){K.error(`Dealer "${M.dealerName||M.displayName}" (${M.dealerCode}) is not mapped to the system.`,{duration:5e3}),x(""),c([]),B("dealerCode",""),B("dealerName",""),B("dealerEmail",""),B("dealerPhone",""),B("dealerAddress",""),l(!1);return}B("dealerCode",M.dealerCode),B("dealerName",M.dealerName||M.displayName),B("dealerEmail",M.email||""),B("dealerPhone",M.phone||""),B("dealerAddress",""),x(M.dealerName||M.displayName),c([]),K.success(`Dealer "${M.dealerName||M.displayName}" verified and mapped to the System`)}catch{K.error("Dealer is not mapped to the system",{duration:5e3}),x(""),c([]),B("dealerCode",""),B("dealerName",""),B("dealerEmail",""),B("dealerPhone",""),B("dealerAddress","")}finally{l(!1)}},S=()=>{if(g)return;const M=[...R.approvers||[]].sort(($,z)=>$.level-z.level),W=new Map,G=[];if(M.forEach($=>{W.has($.level)?G.push($.level):W.set($.level,$)}),G.length>0){K.error(`Duplicate approver levels detected: ${G.join(", ")}. Please refresh and try again.`),console.error("Duplicate levels found:",G,M);return}const re=M.map($=>{const z={email:$.email,name:$.name,userId:$.userId,level:$.level,tat:$.tat,tatType:$.tatType};return $.isAdditional&&$.stepName&&(z.stepName=$.stepName,z.isAdditional=!0),$.originalStepLevel&&(z.originalStepLevel=$.originalStepLevel),z}),te={...R,templateType:"claim-management",submittedAt:new Date().toISOString(),status:"pending",currentStep:"initiator-review",approvers:re};if(b(!0),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{b(!1),f.current=null},3e4),s)try{s(te)}catch($){f.current&&(clearTimeout(f.current),f.current=null),b(!1),console.error("Error submitting claim:",$)}else f.current&&(clearTimeout(f.current),f.current=null),b(!1)},O=()=>{switch(r){case 1:return e.jsxs(is.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(Yt,{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(ne,{htmlFor:"activityName",className:"text-base font-semibold",children:"Activity Name *"}),e.jsx(Ie,{id:"activityName",placeholder:"e.g., Himalayan Adventure Fest 2024",value:R.activityName,onChange:I=>B("activityName",I.target.value),className:"mt-2 h-12"})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"activityType",className:"text-base font-semibold",children:"Activity Type *"}),e.jsxs(Ke,{value:R.activityType,onValueChange:I=>B("activityType",I),disabled:_,children:[e.jsx(Ze,{className:"mt-2 !h-12 data-[size=default]:!h-12",id:"activityType",children:e.jsx(Xe,{placeholder:_?"Loading activity types...":"Select activity type"})}),e.jsx(Je,{children:A.length>0?A.map(I=>e.jsx(Y,{value:I.title,children:I.title},I.activityTypeId)):e.jsx("div",{className:"px-2 py-1.5 text-sm text-gray-500 text-center",children:"No activity types available"})})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{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(Ie,{placeholder:"Type dealer code, name, or email to search...",value:R.dealerCode?`${R.dealerName} (${R.dealerCode})`:h,onChange:I=>{R.dealerCode?(B("dealerCode",""),B("dealerName",""),B("dealerEmail",""),B("dealerPhone",""),B("dealerAddress",""),x(I.target.value)):P(I.target.value)},onFocus:()=>{h&&h.length>=2&&P(h)},className:"h-12 border-2 border-gray-300 focus:border-blue-500",disabled:i}),R.dealerCode&&e.jsx("div",{className:"absolute right-3 top-1/2 -translate-y-1/2",children:e.jsxs(oe,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(Re,{className:"w-3 h-3 mr-1"}),"Verified"]})}),(d||o.length>0)&&!R.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(I=>e.jsx("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>D(I),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:I.dealerName||I.displayName}),e.jsxs("div",{className:"text-xs text-gray-600",children:[e.jsx("span",{className:"font-mono",children:I.dealerCode}),I.email&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1",children:"•"}),e.jsx("span",{children:I.email})]})]}),I.city&&I.state&&e.jsxs("div",{className:"text-xs text-gray-500",children:[I.city,", ",I.state]})]}),e.jsx("div",{className:"ml-2 flex-shrink-0",children:I.isLoggedIn?e.jsx(Re,{className:"w-4 h-4 text-green-600"}):e.jsx(Ct,{className:"w-4 h-4 text-red-500"})})]})},I.dealerId))})})]})}),R.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:R.dealerName})," (",R.dealerCode,")"]}),R.dealerEmail&&e.jsxs("p",{className:"text-xs text-gray-500",children:["Email: ",R.dealerEmail]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-base font-semibold",children:"Date *"}),e.jsxs(Xs,{children:[e.jsx(Zs,{asChild:!0,children:e.jsxs(F,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12 pl-3",children:[e.jsx(xt,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:R.activityDate?Ge(R.activityDate,"d MMM yyyy"):"Select date"})]})}),e.jsx(Js,{className:"w-auto p-0",align:"start",children:e.jsx(Xn,{mode:"single",selected:R.activityDate,onSelect:I=>B("activityDate",I),initialFocus:!0})})]})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"location",className:"text-base font-semibold",children:"Location *"}),e.jsx(Ie,{id:"location",placeholder:"e.g., Mumbai, Maharashtra",value:R.location,onChange:I=>B("location",I.target.value),className:"mt-2 h-12"})]})]}),e.jsxs("div",{children:[e.jsx(ne,{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(Pn,{value:R.requestDescription||"",onChange:I=>B("requestDescription",I),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(ne,{className:"text-base font-semibold",children:"Period (If Any)"}),e.jsx(oe,{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(ne,{className:"text-sm text-gray-600",children:"Start Date"}),e.jsxs(Xs,{children:[e.jsx(Zs,{asChild:!0,children:e.jsxs(F,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12 pl-3",children:[e.jsx(xt,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:R.periodStartDate?Ge(R.periodStartDate,"d MMM yyyy"):"Start date"})]})}),e.jsx(Js,{className:"w-auto p-0",align:"start",children:e.jsx(Xn,{mode:"single",selected:R.periodStartDate,onSelect:I=>B("periodStartDate",I),initialFocus:!0,toDate:R.periodEndDate||void 0})})]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-sm text-gray-600",children:"End Date"}),e.jsxs(Xs,{children:[e.jsx(Zs,{asChild:!0,children:e.jsxs(F,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12 pl-3",disabled:!R.periodStartDate,children:[e.jsx(xt,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:R.periodEndDate?Ge(R.periodEndDate,"d MMM yyyy"):"End date"})]})}),e.jsx(Js,{className:"w-auto p-0",align:"start",children:e.jsx(Xn,{mode:"single",selected:R.periodEndDate,onSelect:I=>B("periodEndDate",I),initialFocus:!0,fromDate:R.periodStartDate||void 0})})]}),!R.periodStartDate&&e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Please select start date first"})]})]}),(R.periodStartDate||R.periodEndDate)&&e.jsx("div",{className:"mt-2",children:R.periodStartDate&&R.periodEndDate?e.jsxs("p",{className:"text-xs text-gray-600",children:["Period: ",Ge(R.periodStartDate,"d MMM yyyy")," - ",Ge(R.periodEndDate,"d MMM yyyy")]}):e.jsx("p",{className:"text-xs text-gray-500",children:R.periodStartDate?"Please select end date for the period":"Please select start date first"})})]})]})]});case 2:return e.jsx(_T,{formData:R,updateFormData:B,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"),maxApprovalLevels:y.maxApprovalLevels,onPolicyViolation:I=>w({open:!0,violations:I})});case 3:return e.jsxs(is.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(Re,{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(se,{className:"border-2",children:[e.jsx(ge,{className:"bg-gradient-to-br from-blue-50 to-indigo-50",children:e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(Yt,{className:"w-5 h-5 text-blue-600"}),"Activity Information"]})}),e.jsx(ae,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:R.activityName})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Type"}),e.jsx(oe,{variant:"secondary",className:"mt-1",children:R.activityType})]})]})})]}),e.jsxs(se,{className:"border-2",children:[e.jsx(ge,{className:"bg-gradient-to-br from-green-50 to-emerald-50",children:e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(Ai,{className:"w-5 h-5 text-green-600"}),"Dealer Information"]})}),e.jsx(ae,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(ne,{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:R.dealerCode})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:R.dealerName})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Email"}),e.jsx("p",{className:"text-gray-900 mt-1",children:R.dealerEmail})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Phone"}),e.jsx("p",{className:"text-gray-900 mt-1",children:R.dealerPhone})]}),R.dealerAddress&&e.jsxs("div",{className:"col-span-2",children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Address"}),e.jsx("p",{className:"text-gray-900 mt-1",children:R.dealerAddress})]})]})})]}),e.jsxs(se,{className:"border-2",children:[e.jsx(ge,{className:"bg-gradient-to-br from-purple-50 to-indigo-50",children:e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(ps,{className:"w-5 h-5 text-purple-600"}),"Selected Approvers"]})}),e.jsx(ae,{className:"pt-6 space-y-4",children:e.jsx("div",{className:"space-y-3",children:[...R.approvers||[]].filter(M=>{var W,G;return!((W=M.email)!=null&&W.includes("system@"))&&!((G=M.email)!=null&&G.includes("finance@"))}).sort((M,W)=>M.level-W.level).map(M=>{const W=Number(M.tat||0),re=(M.tatType||"hours")==="days"?W*24:W;let te="Unknown",$="";if(M.isAdditional){te=M.stepName||"Additional Approver";const z=Cl.find(H=>H.level===M.insertAfterLevel);$=M.stepName||`Additional Approver (after "${(z==null?void 0:z.name)||"Unknown"}")`}else{const z=M.originalStepLevel?Cl.find(H=>H.level===M.originalStepLevel):Cl.find(H=>H.level===M.level&&!H.isAuto);te=(z==null?void 0:z.name)||"Unknown",$=te}return e.jsx("div",{className:`p-3 rounded-lg border ${M.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(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:$}),M.isAdditional&&e.jsx(oe,{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:M.name||M.email||"Not selected"}),M.email&&e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:M.email})]}),e.jsxs("div",{className:"text-right ml-4",children:[e.jsxs("p",{className:"text-sm font-semibold text-gray-900",children:[re," hours"]}),e.jsx("p",{className:"text-xs text-gray-500",children:"TAT"})]})]})},`${M.level}-${M.email}`)})})})]}),e.jsxs(se,{className:"border-2",children:[e.jsx(ge,{className:"bg-gradient-to-br from-purple-50 to-pink-50",children:e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(xt,{className:"w-5 h-5 text-purple-600"}),"Date & Location"]})}),e.jsx(ae,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:R.activityDate?Ge(R.activityDate,"PPP"):"N/A"})]}),e.jsxs("div",{children:[e.jsx(ne,{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(fo,{className:"w-4 h-4 text-gray-500"}),e.jsx("p",{className:"font-semibold text-gray-900",children:R.location})]})]}),R.estimatedBudget&&e.jsxs("div",{className:"col-span-2",children:[e.jsx(ne,{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:R.estimatedBudget})]})]})})]}),e.jsxs(se,{className:"border-2",children:[e.jsx(ge,{className:"bg-gradient-to-br from-orange-50 to-amber-50",children:e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(ke,{className:"w-5 h-5 text-orange-600"}),"Request Details"]})}),e.jsx(ae,{className:"pt-6 space-y-4",children:e.jsxs("div",{children:[e.jsx(ne,{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(Bs,{content:R.requestDescription||"",className:"text-sm"})})]})})]}),(R.periodStartDate||R.periodEndDate)&&e.jsxs(se,{className:"border-2",children:[e.jsx(ge,{className:"bg-gradient-to-br from-cyan-50 to-blue-50",children:e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(nt,{className:"w-5 h-5 text-cyan-600"}),"Period"]})}),e.jsx(ae,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Start Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:R.periodStartDate?Ge(R.periodStartDate,"PPP"):"Not specified"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"End Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:R.periodEndDate?Ge(R.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(Hr,{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.jsxs("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(F,{variant:"ghost",onClick:t,className:"mb-3 sm:mb-4 gap-2 text-sm sm:text-base",children:[e.jsx(Cs,{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(oe,{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 ",E,": ",e.jsx("span",{className:"hidden sm:inline",children:Sl[r-1]})]})]})}),e.jsxs("div",{className:"mt-4 sm:mt-6",children:[e.jsx(oa,{value:r/E*100,className:"h-2"}),e.jsx("div",{className:"flex justify-between mt-2 px-1",children:Sl.map((I,M)=>e.jsx("span",{className:`text-xs sm:text-sm ${M+1<=r?"text-blue-600 font-medium":"text-gray-400"}`,children:M+1},M))})]})]}),e.jsx(se,{className:"mb-6 sm:mb-8",children:e.jsx(ae,{className:"p-4 sm:p-6 lg:p-8",children:e.jsx(_i,{mode:"wait",children:O()})})}),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(F,{variant:"outline",onClick:V,disabled:r===1,className:"gap-2 w-full sm:w-auto order-2 sm:order-1",children:[e.jsx(Cs,{className:"w-4 h-4"}),"Previous"]}),r<E?e.jsxs(F,{onClick:L,className:`gap-2 w-full sm:w-auto order-1 sm:order-2 ${k()?"":"opacity-50 cursor-pointer hover:opacity-60"}`,children:["Next",e.jsx(ls,{className:"w-4 h-4"})]}):e.jsx(F,{onClick:S,disabled:!k()||g,className:"gap-2 bg-green-600 hover:bg-green-700 w-full sm:w-auto order-1 sm:order-2",children:g?e.jsxs(e.Fragment,{children:[e.jsx(it,{className:"w-4 h-4 animate-spin"}),"Submitting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ra,{className:"w-4 h-4"}),"Submit Claim Request"]})})]})]}),e.jsx(Ln,{open:C.open,onClose:()=>w({open:!1,violations:[]}),violations:C.violations,policyDetails:{maxApprovalLevels:y.maxApprovalLevels,maxParticipants:y.maxParticipants,allowSpectators:y.allowSpectators,maxSpectators:y.maxSpectators}})]})}const{DocumentsTab:MT,ActivityTab:$T,WorkNotesTab:OT,SummaryTab:UT,RequestDetailHeader:BT,QuickActionsSidebar:VT,RequestDetailModals:zT}=Ag;let HT=class extends p.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(os,{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(F,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(F,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}};function GT({requestId:t,onBack:s,dynamicRequests:a=[]}){var Ft,ms,zs,rr,nr,ma;const n=Fa().requestId||t||"",l=new URLSearchParams(window.location.search).get("tab")||"overview",[o,c]=p.useState(l),[d,m]=p.useState(!1),[h,x]=p.useState(null),[u,g]=p.useState(null),[b,f]=p.useState(!1),[y,v]=p.useState(0),[C,w]=p.useState(!1),[A,N]=p.useState(!1),[_,T]=p.useState(!1),[R,j]=p.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[E,P]=p.useState({open:!1,violations:[]}),{user:B}=Jt(),{request:k,apiRequest:L,loading:V,refreshing:D,refreshDetails:S,currentApprovalLevel:O,isSpectator:I,isInitiator:M,existingParticipants:W,accessDenied:G}=fc(n,a,B),re=(B==null?void 0:B.userId)||"",te=M,{mergedMessages:$,unreadWorkNotes:z,workNoteAttachments:H,setWorkNoteAttachments:je}=xg(n,L,o,B),{uploadingDocument:le,triggerFileInput:ue,previewDocument:$e,setPreviewDocument:Te,documentPolicy:Ve,documentError:Qe,setDocumentError:Fe}=hg(L,S),[Q,pe]=p.useState(null),Ce=Q||O,{showApproveModal:Oe,setShowApproveModal:X,showRejectModal:Z,setShowRejectModal:me,showAddApproverModal:J,setShowAddApproverModal:be,showAddSpectatorModal:Be,setShowAddSpectatorModal:Ee,showSkipApproverModal:ze,setShowSkipApproverModal:vt,showActionStatusModal:ut,setShowActionStatusModal:Tt,skipApproverData:cs,setSkipApproverData:q,actionStatus:Ne,setActionStatus:ee,handleApproveConfirm:_e,handleRejectConfirm:Le,handleAddApprover:We,handleSkipApprover:Me,handleAddSpectator:qe}=gg(n,Ce,S),He=async jt=>{await _e(jt),pe(null)},at=async jt=>{await Le(jt),pe(null)},Ss=((k==null?void 0:k.status)||(L==null?void 0:L.status)||"").toLowerCase(),Kt=(Ss==="approved"||Ss==="rejected")&&M,{conclusionRemark:ct,setConclusionRemark:rt,conclusionLoading:St,conclusionSubmitting:ds,aiGenerated:Vt,handleGenerateConclusion:Ca,handleFinalizeConclusion:qs,generationAttempts:er,generationFailed:da,maxAttemptsReached:kt}=pg(k,n,M,S,s,ee,Tt);p.useEffect(()=>{(async()=>{var us;try{const Ls=await Qs("SYSTEM_SETTINGS"),ea=await Qs("WORKFLOW_SHARING"),Cr=[...Ls,...ea],ua={};Cr.forEach(Ua=>{ua[Ua.configKey]=Ua.configValue}),j({maxApprovalLevels:parseInt(ua.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(ua.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((us=ua.ALLOW_ADD_SPECTATOR)==null?void 0:us.toLowerCase())==="true",maxSpectators:parseInt(ua.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(Ls){console.error("Failed to load system policy:",Ls)}})()},[]),p.useEffect(()=>{const us=new URLSearchParams(window.location.search).get("tab");us&&c(us)},[n]);const _a=()=>{S()},tr=()=>{w(!0)},wr=()=>{N(!0)},La=async()=>{await S()},sr=()=>{T(!0)},Ma=async()=>{await S()},ar=async()=>{await S()},$a=async()=>{if(!(L!=null&&L.requestId)){K.error("Request ID not found");return}if(!h){K.error("Summary not available. Please ensure the request is closed and the summary has been generated.");return}m(!0)},ba=(k==null?void 0:k.status)==="closed";p.useEffect(()=>{(async()=>{if(!ba||!(L!=null&&L.requestId)){g(null),x(null);return}try{f(!0);const us=await Ng(L.requestId);if(us!=null&&us.summaryId){x(us.summaryId);try{const Ls=await yc(us.summaryId);g(Ls)}catch(Ls){console.error("Failed to fetch summary details:",Ls),g(null),x(null)}}else g(null),x(null)}catch{g(null),x(null)}finally{f(!1)}})()},[ba,L==null?void 0:L.requestId]),p.useEffect(()=>{if(!re||!(L!=null&&L.requestId))return;const jt=Or();if(!jt)return;oh(jt,re);const us=Ls=>{var Ua,Qr,qr,en;const ea=Ls==null?void 0:Ls.notification;if(!ea)return;const Cr=ea.requestId||ea.request_id,ua=((Ua=ea.metadata)==null?void 0:Ua.requestNumber)||((Qr=ea.metadata)==null?void 0:Qr.request_number);Cr!==L.requestId&&ua!==n&&ua!==L.requestNumber||((qr=ea.metadata)!=null&&qr.creditNoteNumber||(en=ea.metadata)!=null&&en.credit_note_number)&&S()};return jt.on("notification:new",us),()=>{jt.off("notification:new",us)}},[re,L==null?void 0:L.requestId,n,S]);const Oa=((k==null?void 0:k.approvalFlow)||[]).filter(jt=>jt&&typeof jt.step=="number").map(jt=>({levelNumber:jt.step||0,approverName:jt.approver||"Unknown",status:jt.status||"pending",tatHours:jt.tatHours||24}));return V&&!k&&!L?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(Ut,{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..."})]})}):G!=null&&G.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(Ex,{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:G.message}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsxs(F,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(Cs,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(F,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})}):k?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(BT,{request:k,refreshing:D,onBack:s||(()=>window.history.back()),onRefresh:_a,onShareSummary:$a,isInitiator:M,slaData:((Ft=k==null?void 0:k.summary)==null?void 0:Ft.sla)||(k==null?void 0:k.sla)||null,isPaused:((ms=k==null?void 0:k.pauseInfo)==null?void 0:ms.isPaused)||!1}),e.jsxs(Ui,{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(Bi,{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(rs,{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(Fx,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Overview"})]}),ba&&u&&e.jsxs(rs,{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(_x,{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(rs,{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(na,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Workflow"})]}),te&&e.jsxs(rs,{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(rs,{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(ke,{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(rs,{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(It,{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(rs,{value:"worknotes",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900 relative col-span-2 sm:col-span-1","data-testid":"tab-worknotes",children:[e.jsx(Ds,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Work Notes"}),z>0&&e.jsx(oe,{className:"absolute -top-1 -right-1 h-5 w-5 rounded-full bg-red-500 text-white text-[10px] flex items-center justify-center p-0","data-testid":"worknotes-unread-badge",children:z>9?"9+":z})]})]})}),e.jsxs("div",{className: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(ns,{value:"overview",className:"mt-0","data-testid":"overview-tab-content",children:e.jsx(rT,{request:k,apiRequest:L,currentUserId:re,isInitiator:M,needsClosure:Kt,conclusionRemark:ct,setConclusionRemark:rt,conclusionLoading:St,conclusionSubmitting:ds,aiGenerated:Vt,handleGenerateConclusion:Ca,handleFinalizeConclusion:qs,generationAttempts:er,generationFailed:da,maxAttemptsReached:kt})}),ba&&e.jsx(ns,{value:"summary",className:"mt-0","data-testid":"summary-tab-content",children:e.jsx(UT,{summary:u,loading:b,onShare:$a,isInitiator:M})}),e.jsx(ns,{value:"workflow",className:"mt-0",children:e.jsx(PT,{request:k,user:B,isInitiator:M,onSkipApprover:jt=>{if(!jt.levelId){alert("Level ID not available");return}q(jt),vt(!0)},onRefresh:S,documentPolicy:Ve})}),te&&e.jsx(ns,{value:"io",className:"mt-0",children:e.jsx(IT,{request:k,apiRequest:L,onRefresh:S})}),e.jsx(ns,{value:"documents",className:"mt-0",children:e.jsx(MT,{request:k,workNoteAttachments:H,uploadingDocument:le,documentPolicy:Ve,triggerFileInput:ue,setPreviewDocument:Te,downloadDocument:ws})}),e.jsx(ns,{value:"activity",className:"mt-0",children:e.jsx($T,{request:k})}),e.jsx(ns,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:o!=="worknotes",children:e.jsx(OT,{requestId:n,requestTitle:k.title,mergedMessages:$,setWorkNoteAttachments:je,isInitiator:M,isSpectator:I,currentLevels:Oa,onAddApprover:We,maxApprovalLevels:R.maxApprovalLevels,onPolicyViolation:jt=>P({open:!0,violations:jt})})})]}),o!=="worknotes"&&e.jsx(VT,{request:k,isInitiator:M,isSpectator:I,currentApprovalLevel:O,onAddApprover:()=>be(!0),onAddSpectator:()=>Ee(!0),onApprove:()=>X(!0),onReject:()=>me(!0),onPause:tr,onResume:wr,onRetrigger:sr,summaryId:h,refreshTrigger:y,pausedByUserId:(rr=(zs=k==null?void 0:k.pauseInfo)==null?void 0:zs.pausedBy)==null?void 0:rr.userId,currentUserId:re,apiRequest:L})]})]})]})}),d&&h&&e.jsx(Tg,{isOpen:d,onClose:()=>m(!1),summaryId:h,requestTitle:(k==null?void 0:k.title)||"N/A",onSuccess:()=>{S(),v(jt=>jt+1)}}),C&&(L==null?void 0:L.requestId)&&e.jsx(kg,{isOpen:C,onClose:()=>w(!1),requestId:L.requestId,levelId:(O==null?void 0:O.levelId)||null,onSuccess:Ma}),A&&(L==null?void 0:L.requestId)&&e.jsx(Rg,{isOpen:A,onClose:()=>N(!1),requestId:L.requestId,onSuccess:La}),_&&(L==null?void 0:L.requestId)&&e.jsx(Dg,{isOpen:_,onClose:()=>T(!1),requestId:L.requestId,approverName:(ma=(nr=k==null?void 0:k.pauseInfo)==null?void 0:nr.pausedBy)==null?void 0:ma.name,onSuccess:ar}),e.jsx(zT,{showApproveModal:Oe,showRejectModal:Z,showAddApproverModal:J,showAddSpectatorModal:Be,showSkipApproverModal:ze,showActionStatusModal:ut,previewDocument:$e,documentError:Qe,request:k,skipApproverData:cs,actionStatus:Ne,existingParticipants:W,currentLevels:Oa,maxApprovalLevels:R.maxApprovalLevels,onPolicyViolation:jt=>P({open:!0,violations:jt}),setShowApproveModal:X,setShowRejectModal:me,setShowAddApproverModal:be,setShowAddSpectatorModal:Ee,setShowSkipApproverModal:vt,setShowActionStatusModal:Tt,setPreviewDocument:Te,setDocumentError:Fe,setSkipApproverData:q,setActionStatus:ee,handleApproveConfirm:He,handleRejectConfirm:at,handleAddApprover:We,handleAddSpectator:qe,handleSkipApprover:Me,downloadDocument:ws,documentPolicy:Ve}),e.jsx(Ln,{open:E.open,onClose:()=>P({open:!1,violations:[]}),violations:E.violations,policyDetails:{maxApprovalLevels:R.maxApprovalLevels,maxParticipants:R.maxParticipants,allowSpectators:R.allowSpectators,maxSpectators:R.maxSpectators}})]}):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(ke,{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(F,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(Cs,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(F,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})})}function WT(t){return e.jsx(HT,{children:e.jsx(GT,{...t})})}function YT({onNavigate:t,onNewRequest:s}){const[a,r]=p.useState(!0),[n,i]=p.useState(!1),[l,o]=p.useState({totalClaims:0,totalValue:0,approved:0,rejected:0,pending:0,credited:0,pendingCredit:0,approvedValue:0,rejectedValue:0,pendingValue:0,creditedValue:0,pendingCreditValue:0}),[c,d]=p.useState([]),[m,h]=p.useState("all"),[x,u]=p.useState(),[g,b]=p.useState(),f=async(P=!1)=>{try{P?i(!0):r(!0);const B=await AT(m||"all",x,g);o(B.kpis||{totalClaims:0,totalValue:0,approved:0,rejected:0,pending:0,credited:0,pendingCredit:0,approvedValue:0,rejectedValue:0,pendingValue:0,creditedValue:0,pendingCreditValue:0}),d(B.categoryData||[])}catch(B){console.error("[DealerDashboard] Error fetching data:",B),K.error("Failed to load dashboard data. Please try again later."),o({totalClaims:0,totalValue:0,approved:0,rejected:0,pending:0,credited:0,pendingCredit:0,approvedValue:0,rejectedValue:0,pendingValue:0,creditedValue:0,pendingCreditValue:0}),d([])}finally{r(!1),i(!1)}};p.useEffect(()=>{f()},[]);const y=(P,B=!1)=>{if(P==null||isNaN(P))return"₹0";const k=typeof P=="string"?parseFloat(P):Number(P);return k<=0?"₹0":B||k<1e4?`₹${Math.round(k).toLocaleString("en-IN")}`:k>=1e5?`₹${(k/1e5).toFixed(1)}L`:k>=1e3?`₹${(k/1e3).toFixed(1)}K`:`₹${Math.round(k).toLocaleString("en-IN")}`},v=P=>P.toLocaleString("en-IN"),C=()=>l.totalClaims===0?0:(l.approved/l.totalClaims*100).toFixed(1),w=()=>l.approved===0?0:(l.credited/l.approved*100).toFixed(1),A=p.useMemo(()=>{const P=c.reduce((B,k)=>B+k.raised,0);return P===0?[]:c.map(B=>({name:B.activityType.length>20?B.activityType.substring(0,20)+"...":B.activityType,value:B.raised,fullName:B.activityType,percentage:(B.raised/P*100).toFixed(0)}))},[c]),N=p.useMemo(()=>c.map(P=>({name:P.activityType.length>15?P.activityType.substring(0,15)+"...":P.activityType,fullName:P.activityType,Raised:P.raised,Approved:P.approved,Rejected:P.rejected,Pending:P.pending})),[c]),_=p.useMemo(()=>c.map(P=>({name:P.activityType.length>15?P.activityType.substring(0,15)+"...":P.activityType,fullName:P.activityType,Raised:P.raisedValue,Approved:P.approvedValue,Credited:P.creditedValue})),[c]),T=["#166534","#15803d","#16a34a","#22c55e","#4ade80","#86efac","#bbf7d0"],R=p.useMemo(()=>c.length===0?null:c.reduce((P,B)=>B.approvalRate>((P==null?void 0:P.approvalRate)||0)?B:P),[c]),j=p.useMemo(()=>c.length===0?null:c.reduce((P,B)=>B.raisedValue>((P==null?void 0:P.raisedValue)||0)?B:P),[c]);return a?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(Ut,{className:"w-8 h-8 animate-spin text-blue-600"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading dashboard..."})]})}):l.totalClaims===0&&c.length===0?e.jsxs("div",{className:"space-y-6 max-w-[1600px] mx-auto p-4",children:[e.jsxs(se,{className:"border-0 shadow-xl relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900"}),e.jsx(ae,{className:"relative z-10 p-8 lg:p-12",children:e.jsx("div",{className:"flex flex-col lg:flex-row items-start lg:items-center justify-between gap-6",children:e.jsxs("div",{className:"text-white",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[e.jsx("div",{className:"w-16 h-16 bg-yellow-400 rounded-xl flex items-center justify-center shadow-lg",children:e.jsx(Ns,{className:"w-8 h-8 text-slate-900"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-4xl text-white font-bold",children:"Claims Analytics Dashboard"}),e.jsx("p",{className:"text-xl text-gray-200 mt-1",children:"Comprehensive insights into approval workflows"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-4 mt-8",children:[e.jsxs(F,{onClick:()=>t==null?void 0:t("/new-request"),className:"bg-blue-600 hover:bg-blue-700 text-white border-0 shadow-lg hover:shadow-xl transition-all duration-200",children:[e.jsx(ke,{className:"w-5 h-5 mr-2"}),"Create New Claim"]}),e.jsxs(F,{onClick:()=>{i(!0),f(!0)},disabled:n,variant:"outline",className:"bg-white/10 hover:bg-white/20 text-white border-white/20",children:[e.jsx(Ut,{className:`w-5 h-5 mr-2 ${n?"animate-spin":""}`}),"Refresh"]})]})]})})})]}),e.jsx(se,{className:"shadow-lg",children:e.jsxs(ae,{className:"flex flex-col items-center justify-center py-16 px-4",children:[e.jsx("div",{className:"w-24 h-24 bg-gray-100 rounded-full flex items-center justify-center mb-6",children:e.jsx(El,{className:"w-12 h-12 text-gray-400"})}),e.jsx("h2",{className:"text-2xl font-semibold text-gray-900 mb-2",children:"No Claims Data Available"}),e.jsx("p",{className:"text-gray-600 text-center max-w-md mb-6",children:"You don't have any claims data yet. Once you create and submit claim requests, your analytics will appear here."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs(F,{onClick:()=>t==null?void 0:t("/new-request"),className:"bg-blue-600 hover:bg-blue-700 text-white",children:[e.jsx(ke,{className:"w-5 h-5 mr-2"}),"Create Your First Claim"]}),e.jsxs(F,{onClick:()=>{i(!0),f(!0)},disabled:n,variant:"outline",children:[e.jsx(Ut,{className:`w-5 h-5 mr-2 ${n?"animate-spin":""}`}),"Refresh Data"]})]})]})})]}):e.jsxs("div",{className:"space-y-6 max-w-[1600px] mx-auto p-4",children:[e.jsxs(se,{className:"border-0 shadow-xl relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900"}),e.jsx(ae,{className:"relative z-10 p-8 lg:p-12",children:e.jsxs("div",{className:"flex flex-col lg:flex-row items-start lg:items-center justify-between gap-6",children:[e.jsxs("div",{className:"text-white",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[e.jsx("div",{className:"w-16 h-16 bg-yellow-400 rounded-xl flex items-center justify-center shadow-lg",children:e.jsx(Ns,{className:"w-8 h-8 text-slate-900"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-4xl text-white font-bold",children:"Claims Analytics Dashboard"}),e.jsx("p",{className:"text-xl text-gray-200 mt-1",children:"Comprehensive insights into approval workflows"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-4 mt-8",children:[e.jsxs(F,{onClick:()=>t==null?void 0:t("/requests?status=pending"),className:"bg-blue-600 hover:bg-blue-700 text-white border-0 shadow-lg hover:shadow-xl transition-all duration-200",children:[e.jsx(nt,{className:"w-5 h-5 mr-2"}),"View Pending Claims"]}),e.jsxs(F,{onClick:()=>t==null?void 0:t("/requests"),className:"bg-emerald-600 hover:bg-emerald-700 text-white border-0 shadow-lg hover:shadow-xl transition-all duration-200",children:[e.jsx(ke,{className:"w-5 h-5 mr-2"}),"My Claims"]})]})]}),e.jsx("div",{className:"hidden lg:flex items-center gap-4",children:e.jsx("div",{className:"w-24 h-24 bg-yellow-400/20 rounded-full flex items-center justify-center",children:e.jsx("div",{className:"w-16 h-16 bg-yellow-400/30 rounded-full flex items-center justify-center",children:e.jsx(Fl,{className:"w-8 h-8 text-yellow-400"})})})})]})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 xl:grid-cols-6 gap-4",children:[e.jsxs(se,{className:"border-l-4 border-l-blue-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(ge,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(fe,{className:"text-sm text-muted-foreground",children:"Raised Claims"}),e.jsx("div",{className:"p-2 rounded-lg bg-blue-50",children:e.jsx(ke,{className:"h-4 w-4 text-blue-600"})})]})}),e.jsxs(ae,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:v(l.totalClaims)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:y(l.totalValue,!0)})]})]}),e.jsxs(se,{className:"border-l-4 border-l-green-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(ge,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(fe,{className:"text-sm text-muted-foreground",children:"Approved"}),e.jsx("div",{className:"p-2 rounded-lg bg-green-50",children:e.jsx(Re,{className:"h-4 w-4 text-green-600"})})]})}),e.jsxs(ae,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:v(l.approved)}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx(na,{className:"h-3 w-3 text-green-600"}),e.jsxs("p",{className:"text-xs text-green-600",children:[C(),"% approval rate"]})]})]})]}),e.jsxs(se,{className:"border-l-4 border-l-red-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(ge,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(fe,{className:"text-sm text-muted-foreground",children:"Rejected"}),e.jsx("div",{className:"p-2 rounded-lg bg-red-50",children:e.jsx(Ct,{className:"h-4 w-4 text-red-600"})})]})}),e.jsxs(ae,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:v(l.rejected)}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx(Gf,{className:"h-3 w-3 text-red-600"}),e.jsxs("p",{className:"text-xs text-red-600",children:[l.totalClaims>0?(l.rejected/l.totalClaims*100).toFixed(1):0,"% rejection rate"]})]})]})]}),e.jsxs(se,{className:"border-l-4 border-l-orange-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(ge,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(fe,{className:"text-sm text-muted-foreground",children:"Pending"}),e.jsx("div",{className:"p-2 rounded-lg bg-orange-50",children:e.jsx(nt,{className:"h-4 w-4 text-orange-600"})})]})}),e.jsxs(ae,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:v(l.pending)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:y(l.pendingValue)})]})]}),e.jsxs(se,{className:"border-l-4 border-l-emerald-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(ge,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(fe,{className:"text-sm text-muted-foreground",children:"Credited"}),e.jsx("div",{className:"p-2 rounded-lg bg-emerald-50",children:e.jsx(Wf,{className:"h-4 w-4 text-emerald-600"})})]})}),e.jsxs(ae,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:v(l.credited)}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx(na,{className:"h-3 w-3 text-emerald-600"}),e.jsxs("p",{className:"text-xs text-emerald-600",children:[w(),"% credit rate"]})]})]})]}),e.jsxs(se,{className:"border-l-4 border-l-amber-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(ge,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(fe,{className:"text-sm text-muted-foreground",children:"Pending Credit"}),e.jsx("div",{className:"p-2 rounded-lg bg-amber-50",children:e.jsx(os,{className:"h-4 w-4 text-amber-600"})})]})}),e.jsxs(ae,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:v(l.pendingCredit)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:y(l.pendingCreditValue)})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(se,{className:"shadow-lg",children:[e.jsx(ge,{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(El,{className:"h-5 w-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(fe,{children:"Claims Distribution by Activity Type"}),e.jsx(Ue,{children:"Total claims raised across activity types"})]})]})}),e.jsxs(ae,{children:[e.jsx(Fr,{width:"100%",height:300,children:e.jsxs(hx,{children:[e.jsx(px,{data:A,cx:"50%",cy:"50%",labelLine:!1,label:({name:P,percentage:B})=>`${P}: ${B}%`,outerRadius:80,fill:"#8884d8",dataKey:"value",children:A.map((P,B)=>e.jsx(gx,{fill:T[B%T.length]},`cell-${B}`))}),e.jsx(_r,{})]})}),e.jsx("div",{className:"grid grid-cols-3 gap-2 mt-4",children:A.slice(0,3).map((P,B)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-gray-50",children:[e.jsx("div",{className:"w-3 h-3 rounded",style:{backgroundColor:T[B%T.length]}}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-600",children:P.name}),e.jsx("p",{className:"text-sm text-gray-900",children:v(P.value)})]})]},B))})]})]}),e.jsxs(se,{className:"shadow-lg",children:[e.jsx(ge,{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(Fl,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(fe,{children:"Claims Status by Activity Type"}),e.jsx(Ue,{children:"Count comparison across workflow stages"})]})]})}),e.jsx(ae,{children:e.jsx(Fr,{width:"100%",height:300,children:e.jsxs(Dl,{data:N,children:[e.jsx(si,{strokeDasharray:"3 3"}),e.jsx(ai,{dataKey:"name"}),e.jsx(ri,{}),e.jsx(_r,{}),e.jsx(ni,{}),e.jsx(ya,{dataKey:"Raised",fill:"#3b82f6"}),e.jsx(ya,{dataKey:"Approved",fill:"#22c55e"}),e.jsx(ya,{dataKey:"Rejected",fill:"#ef4444"}),e.jsx(ya,{dataKey:"Pending",fill:"#f59e0b"})]})})})]})]}),e.jsxs(se,{className:"shadow-lg",children:[e.jsx(ge,{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(It,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsx(fe,{children:"Detailed Activity Type Breakdown"}),e.jsx(Ue,{children:"In-depth analysis of claims by type and status"})]})]})}),e.jsx(ae,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg mb-4 text-gray-900",children:"Activity Type Value Comparison"}),e.jsx(Fr,{width:"100%",height:350,children:e.jsxs(Dl,{data:_,children:[e.jsx(si,{strokeDasharray:"3 3"}),e.jsx(ai,{dataKey:"name"}),e.jsx(ri,{tickFormatter:P=>y(P)}),e.jsx(_r,{formatter:P=>y(P),labelFormatter:P=>P}),e.jsx(ni,{}),e.jsx(ya,{dataKey:"Raised",fill:"#3b82f6"}),e.jsx(ya,{dataKey:"Approved",fill:"#22c55e"}),e.jsx(ya,{dataKey:"Credited",fill:"#10b981"})]})})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mt-6",children:c.slice(0,3).map((P,B)=>e.jsxs(se,{className:"shadow-md hover:shadow-lg transition-shadow",children:[e.jsx(ge,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(fe,{className:"text-base",children:P.activityType}),e.jsxs(oe,{className:"bg-emerald-50 text-emerald-700 border-emerald-200",children:[P.approvalRate.toFixed(1),"% approved"]})]})}),e.jsxs(ae,{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:"Raised:"}),e.jsxs("span",{className:"text-gray-900",children:[v(P.raised)," (",y(P.raisedValue),")"]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:"Approved:"}),e.jsxs("span",{className:"text-green-600",children:[v(P.approved)," (",y(P.approvedValue),")"]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:"Rejected:"}),e.jsxs("span",{className:"text-red-600",children:[v(P.rejected)," (",y(P.rejectedValue),")"]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:"Pending:"}),e.jsxs("span",{className:"text-orange-600",children:[v(P.pending)," (",y(P.pendingValue),")"]})]}),e.jsx("div",{className:"h-px bg-gray-200 my-2"}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:"Credited:"}),e.jsxs("span",{className:"text-emerald-600",children:[v(P.credited)," (",y(P.creditedValue),")"]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:"Pending Credit:"}),e.jsxs("span",{className:"text-amber-600",children:[v(P.pendingCredit)," (",y(P.pendingCreditValue),")"]})]})]}),e.jsxs("div",{className:"pt-2",children:[e.jsxs("div",{className:"flex justify-between text-xs text-gray-600 mb-1",children:[e.jsx("span",{children:"Credit Rate"}),e.jsxs("span",{children:[P.creditRate.toFixed(1),"%"]})]}),e.jsx(oa,{value:P.creditRate,className:"h-2"})]})]})]},B))})]})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsx(se,{className:"border-t-4 border-t-green-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(ae,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("div",{className:"p-3 bg-green-100 rounded-lg",children:e.jsx(Bt,{className:"h-6 w-6 text-green-600"})}),e.jsx(na,{className:"h-5 w-5 text-green-600"})]}),e.jsx("h3",{className:"text-sm text-gray-600 mb-1",children:"Best Performing"}),e.jsx("p",{className:"text-xl text-gray-900 mb-1",children:(R==null?void 0:R.activityType)||"N/A"}),e.jsxs("p",{className:"text-sm text-green-600",children:[(R==null?void 0:R.approvalRate.toFixed(2))||0,"% approval rate"]})]})}),e.jsx(se,{className:"border-t-4 border-t-blue-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(ae,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("div",{className:"p-3 bg-blue-100 rounded-lg",children:e.jsx(Pa,{className:"h-6 w-6 text-blue-600"})}),e.jsx(It,{className:"h-5 w-5 text-blue-600"})]}),e.jsx("h3",{className:"text-sm text-gray-600 mb-1",children:"Top Activity Type"}),e.jsx("p",{className:"text-xl text-gray-900 mb-1",children:(j==null?void 0:j.activityType)||"N/A"}),e.jsxs("p",{className:"text-sm text-blue-600",children:[j?y(j.raisedValue,!0):"₹0"," raised"]})]})}),e.jsx(se,{className:"border-t-4 border-t-emerald-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(ae,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("div",{className:"p-3 bg-emerald-100 rounded-lg",children:e.jsx(po,{className:"h-6 w-6 text-emerald-600"})}),e.jsx(Re,{className:"h-5 w-5 text-emerald-600"})]}),e.jsx("h3",{className:"text-sm text-gray-600 mb-1",children:"Overall Credit Rate"}),e.jsxs("p",{className:"text-xl text-gray-900 mb-1",children:[w(),"%"]}),e.jsxs("p",{className:"text-sm text-emerald-600",children:[v(l.credited)," claims credited"]})]})}),e.jsx(se,{className:"border-t-4 border-t-amber-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(ae,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("div",{className:"p-3 bg-amber-100 rounded-lg",children:e.jsx(kx,{className:"h-6 w-6 text-amber-600"})}),e.jsx(os,{className:"h-5 w-5 text-amber-600"})]}),e.jsx("h3",{className:"text-sm text-gray-600 mb-1",children:"Pending Action"}),e.jsx("p",{className:"text-xl text-gray-900 mb-1",children:v(l.pendingCredit)}),e.jsxs("p",{className:"text-sm text-amber-600",children:[y(l.pendingCreditValue)," awaiting credit"]})]})})]})]})}function KT({searchTerm:t,sortBy:s,sortOrder:a,onSearchChange:r,onSortByChange:n,onSortOrderChange:i,onClearFilters:l,activeFiltersCount:o,...c}){return e.jsxs(se,{className:"shadow-lg border-0",children:[e.jsx(ge,{className:"pb-3 sm:pb-4 px-3 sm:px-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("div",{className:"p-1.5 sm:p-2 bg-blue-100 rounded-lg",children:e.jsx(Qa,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(Ue,{className:"text-xs sm:text-sm",children:o>0&&e.jsxs("span",{className:"text-blue-600 font-medium",children:[o," filter",o>1?"s":""," active"]})})]})]}),o>0&&e.jsxs(F,{variant:"ghost",size:"sm",onClick:l,className:"text-red-600 hover:bg-red-50 gap-1 h-8 sm:h-9 px-2 sm:px-3",children:[e.jsx(ft,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Clear"})]})]})}),e.jsx(ae,{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 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Es,{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(Ie,{placeholder:"Search requests, IDs...",value:t,onChange:d=>r(d.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("div",{className:"flex gap-2",children:[e.jsxs(Ke,{value:s,onValueChange:d=>n(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 focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Xe,{placeholder:"Sort by"})}),e.jsxs(Je,{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(F,{variant:"outline",size:"sm",onClick:()=>i(a==="asc"?"desc":"asc"),className:"px-2 sm:px-3 h-9 sm:h-10 md:h-11",children:a==="asc"?e.jsx(Ti,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(ki,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function XT({searchTerm:t,statusFilter:s="all",sortBy:a,sortOrder:r,onSearchChange:n,onStatusChange:i,onSortByChange:l,onSortOrderChange:o,onClearFilters:c,activeFiltersCount:d,...m}){return e.jsxs(se,{className:"shadow-lg border-0","data-testid":"dealer-closed-requests-filters",children:[e.jsx(ge,{className:"pb-3 sm:pb-4 px-3 sm:px-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("div",{className:"p-1.5 sm:p-2 bg-blue-100 rounded-lg",children:e.jsx(Qa,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(Ue,{className:"text-xs sm:text-sm",children:d>0&&e.jsxs("span",{className:"text-blue-600 font-medium",children:[d," filter",d>1?"s":""," active"]})})]})]}),d>0&&e.jsxs(F,{variant:"ghost",size:"sm",onClick:c,className:"text-red-600 hover:bg-red-50 gap-1 h-8 sm:h-9 px-2 sm:px-3","data-testid":"dealer-closed-requests-clear-filters",children:[e.jsx(ft,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Clear"})]})]})}),e.jsx(ae,{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-3 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Es,{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(Ie,{placeholder:"Search requests, IDs...",value:t,onChange:h=>n(h.target.value),className:"pl-9 sm:pl-10 h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200 transition-colors","data-testid":"dealer-closed-requests-search"})]}),i&&e.jsxs(Ke,{value:s,onValueChange:i,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","data-testid":"dealer-closed-requests-status-filter",children:e.jsx(Xe,{placeholder:"Closure Type"})}),e.jsxs(Je,{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(Re,{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(Ct,{className:"w-4 h-4 text-red-600"}),e.jsx("span",{children:"Closed After Rejection"})]})})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ke,{value:a,onValueChange:h=>l(h),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","data-testid":"dealer-closed-requests-sort-by",children:e.jsx(Xe,{placeholder:"Sort by"})}),e.jsxs(Je,{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(F,{variant:"outline",size:"sm",onClick:o,className:"px-2 sm:px-3 h-9 sm:h-10 md:h-11","data-testid":"dealer-closed-requests-sort-order",children:r==="asc"?e.jsx(Ti,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(ki,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function ZT({searchTerm:t,statusFilter:s,initiatorFilter:a,approverFilter:r,approverFilterType:n,dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,initiatorSearch:d,approverSearch:m,onSearchChange:h,onStatusChange:x,onInitiatorChange:u,onApproverChange:g,onApproverTypeChange:b,onDateRangeChange:f,onCustomStartDateChange:y,onCustomEndDateChange:v,onShowCustomDatePickerChange:C,onApplyCustomDate:w,onClearFilters:A,hasActiveFilters:N,..._}){return e.jsx(se,{className:"border-gray-200 shadow-md","data-testid":"dealer-user-all-requests-filters",children:e.jsx(ae,{className:"p-4 sm:p-6",children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qa,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Filters"}),N&&e.jsx(oe,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),N&&e.jsxs(F,{variant:"ghost",size:"sm",onClick:A,className:"gap-2",children:[e.jsx(Ut,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Ps,{}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Es,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Ie,{placeholder:"Search requests...",value:t,onChange:T=>h(T.target.value),className:"pl-10 h-10","data-testid":"dealer-search-input"})]}),e.jsxs(Ke,{value:s,onValueChange:x,children:[e.jsx(Ze,{className:"h-10","data-testid":"dealer-status-filter",children:e.jsx(Xe,{placeholder:"All Status"})}),e.jsxs(Je,{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("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(ne,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:d.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:d.selectedUser.displayName||d.selectedUser.email}),e.jsx(F,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:d.handleClear,children:e.jsx(ft,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ie,{placeholder:"Search initiator...",value:d.searchQuery,onChange:T=>d.handleSearch(T.target.value),onFocus:()=>{d.searchResults.length>0&&d.setShowResults(!0)},onBlur:()=>setTimeout(()=>d.setShowResults(!1),200),className:"h-10","data-testid":"dealer-initiator-search-input"}),d.showResults&&d.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:d.searchResults.map(T=>e.jsx("button",{type:"button",onClick:()=>d.handleSelect(T),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:T.displayName||T.email}),T.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:T.email})]})},T.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(ne,{className:"text-sm font-medium text-gray-700",children:"Approver"}),r!=="all"&&b&&e.jsxs(Ke,{value:n,onValueChange:T=>b(T),children:[e.jsx(Ze,{className:"h-7 w-32 text-xs",children:e.jsx(Xe,{})}),e.jsxs(Je,{children:[e.jsx(Y,{value:"current",children:"Current Only"}),e.jsx(Y,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:m.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:m.selectedUser.displayName||m.selectedUser.email}),e.jsx(F,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:m.handleClear,children:e.jsx(ft,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ie,{placeholder:"Search approver...",value:m.searchQuery,onChange:T=>m.handleSearch(T.target.value),onFocus:()=>{m.searchResults.length>0&&m.setShowResults(!0)},onBlur:()=>setTimeout(()=>m.setShowResults(!1),200),className:"h-10","data-testid":"dealer-approver-search-input"}),m.showResults&&m.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:m.searchResults.map(T=>e.jsx("button",{type:"button",onClick:()=>m.handleSelect(T),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:T.displayName||T.email}),T.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:T.email})]})},T.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(xt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ke,{value:i,onValueChange:T=>f(T),children:[e.jsx(Ze,{className:"w-[160px] h-10",children:e.jsx(Xe,{placeholder:"Date Range"})}),e.jsxs(Je,{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==="custom"&&e.jsxs(Xs,{open:c,onOpenChange:C,children:[e.jsx(Zs,{asChild:!0,children:e.jsxs(F,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(xt,{className:"w-4 h-4"}),l&&o?`${Ge(l,"MMM d, yyyy")} - ${Ge(o,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Js,{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(ne,{htmlFor:"start-date",children:"Start Date"}),e.jsx(Us,{value:l||null,onChange:T=>{const R=T?new Date(T):void 0;R?(y==null||y(R),o&&R>o&&(v==null||v(R))):y==null||y(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"end-date",children:"End Date"}),e.jsx(Us,{value:o||null,onChange:T=>{const R=T?new Date(T):void 0;R?(v==null||v(R),l&&R<l&&(y==null||y(R))):v==null||v(void 0)},minDate:l||void 0,maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(F,{size:"sm",onClick:w,disabled:!l||!o,className:"flex-1 bg-re-green hover:bg-re-green/90",children:"Apply"}),e.jsx(F,{size:"sm",variant:"outline",onClick:()=>{C==null||C(!1),y==null||y(void 0),v==null||v(void 0),f("month")},children:"Cancel"})]})]})})]})]})]})})})}function JT(t){switch(t){case"DEALER_CLAIM":return WT;case"CUSTOM":default:return eT}}function QT(t){switch(t){case"DEALER":return KT;case"STANDARD":default:return tT}}function qT(t){switch(t){case"DEALER":return XT;case"STANDARD":default:return sT}}function e5(t){switch(t){case"DEALER":return ZT;case"STANDARD":default:return aT}}const t5=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:fa,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"}}},s5=t=>{switch(t){case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:nt,iconColor:"text-yellow-600",label:"Pending"};case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:Ye,iconColor:"text-green-600",label:"Needs Closure"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ct,iconColor:"text-red-600",label:"Rejected"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Re,iconColor:"text-gray-600",label:"Closed"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ye,iconColor:"text-gray-600",label:t}}};function a5({onViewRequest:t}){const[s,a]=p.useState([]),[r,n]=p.useState(!1),[i,l]=p.useState(!1),[o,c]=p.useState(1),[d,m]=p.useState(0),[h]=p.useState(10),x=p.useRef(null),u=pN(),g=p.useMemo(()=>{try{const R=st.getUserData();return Lo(R)}catch(R){return console.error("[OpenRequests] Error getting user filter type:",R),"STANDARD"}},[]),b=p.useMemo(()=>QT(g),[g]),f=g==="DEALER",y=R=>({search:u.searchTerm||void 0,status:R&&!f&&u.statusFilter!=="all"?u.statusFilter:void 0,priority:!f&&u.priorityFilter!=="all"?u.priorityFilter:void 0,templateType:!f&&u.templateTypeFilter!=="all"?u.templateTypeFilter:void 0,sortBy:u.sortBy,sortOrder:u.sortOrder}),v=p.useCallback(async(R=1,j)=>{try{R===1&&(n(!0),a([]));const E=await Is.listOpenForMe({page:R,limit:h,search:j==null?void 0:j.search,status:j==null?void 0:j.status,priority:j==null?void 0:j.priority,templateType:j==null?void 0:j.templateType,sortBy:j==null?void 0:j.sortBy,sortOrder:j==null?void 0:j.sortOrder}),P=Array.isArray(E==null?void 0:E.data)?E.data:[],B=E==null?void 0:E.pagination;B&&(u.setCurrentPage(B.page||1),c(B.totalPages||1),m(B.total||0));const k=P.map(L=>{var D,S,O,I;const V=L.submittedAt||L.submitted_at||L.createdAt||L.created_at;return{id:L.requestNumber||L.request_number||L.requestId,requestId:L.requestId,displayId:L.requestNumber||L.request_number||L.requestId,title:L.title,description:L.description,status:(L.status||"").toString().toLowerCase().replace("_","-"),priority:(L.priority||"").toString().toLowerCase(),initiator:{name:((D=L.initiator)==null?void 0:D.displayName)||((S=L.initiator)==null?void 0:S.email)||"—",avatar:(((O=L.initiator)==null?void 0:O.displayName)||((I=L.initiator)==null?void 0:I.email)||"NA").split(" ").map(M=>M[0]).join("").slice(0,2).toUpperCase()},currentApprover:L.currentApprover?{name:L.currentApprover.name||L.currentApprover.email||"—",avatar:(L.currentApprover.name||L.currentApprover.email||"CA").split(" ").map(M=>M[0]).join("").slice(0,2).toUpperCase(),sla:L.currentApprover.sla}:void 0,createdAt:V||"—",approvalStep:L.currentLevel?`Step ${L.currentLevel} of ${L.totalLevels||"?"}`:void 0,department:L.department,currentLevelSLA:L.currentLevelSLA,templateType:L.templateType||L.template_type}});a(k)}finally{n(!1),l(!1)}},[h,u]);x.current=v;const C=p.useCallback(()=>{l(!0),v(u.currentPage,y(!0))},[u.currentPage,v]),w=p.useCallback(R=>{R>=1&&R<=o&&(u.setCurrentPage(R),v(R,y(!0)))},[o,u,v]),A=()=>{const R=[];let E=Math.max(1,u.currentPage-Math.floor(2.5)),P=Math.min(o,E+5-1);P-E<4&&(E=Math.max(1,P-5+1));for(let B=E;B<=P;B++)R.push(B);return R},N=p.useRef(!1);p.useEffect(()=>{if(!N.current){N.current=!0;const R=u.currentPage||1;v(R,y(!0))}},[]);const _=p.useRef({searchTerm:u.searchTerm,statusFilter:u.statusFilter,priorityFilter:u.priorityFilter,templateTypeFilter:u.templateTypeFilter,sortBy:u.sortBy,sortOrder:u.sortOrder,isDealer:f});p.useEffect(()=>{if(!N.current)return;const R=_.current;if(!(R.searchTerm!==u.searchTerm||R.statusFilter!==u.statusFilter||R.priorityFilter!==u.priorityFilter||R.templateTypeFilter!==u.templateTypeFilter||R.sortBy!==u.sortBy||R.sortOrder!==u.sortOrder||R.isDealer!==f))return;const E=setTimeout(()=>{u.setCurrentPage(1),v(1,y(!0)),_.current={searchTerm:u.searchTerm,statusFilter:u.statusFilter,priorityFilter:u.priorityFilter,templateTypeFilter:u.templateTypeFilter,sortBy:u.sortBy,sortOrder:u.sortOrder,isDealer:f}},u.searchTerm?500:0);return()=>clearTimeout(E)},[u.searchTerm,u.statusFilter,u.priorityFilter,u.templateTypeFilter,u.sortBy,u.sortOrder,f]);const T=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(ke,{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(oe,{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(F,{variant:"outline",size:"sm",className:"gap-1 sm:gap-2 h-8 sm:h-9",onClick:C,disabled:i,children:[e.jsx(Ut,{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.jsx(b,{searchTerm:u.searchTerm,statusFilter:u.statusFilter,priorityFilter:u.priorityFilter,templateTypeFilter:u.templateTypeFilter,sortBy:u.sortBy,sortOrder:u.sortOrder,onSearchChange:u.setSearchTerm,onStatusFilterChange:u.setStatusFilter,onPriorityFilterChange:u.setPriorityFilter,onTemplateTypeFilterChange:u.setTemplateTypeFilter,onSortByChange:u.setSortBy,onSortOrderChange:u.setSortOrder,onClearFilters:u.clearFilters,activeFiltersCount:u.activeFiltersCount}),e.jsx("div",{className:"space-y-3",children:T.map(R=>{const j=t5(R.priority),E=s5(R.status);return e.jsx(se,{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(R.id,R.title),children:e.jsx(ae,{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 ${j.color} border shadow-sm`,children:e.jsx(j.icon,{className:`w-5 h-5 ${j.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:R.displayId||R.id}),e.jsxs(oe,{variant:"outline",className:`${E.color} text-xs px-2.5 py-0.5 font-semibold shrink-0`,children:[e.jsx(E.icon,{className:"w-3.5 h-3.5 mr-1"}),E.label||R.status]}),R.department&&e.jsx(oe,{variant:"secondary",className:"bg-blue-50 text-blue-700 text-xs px-2.5 py-0.5 hidden sm:inline-flex",children:R.department}),e.jsx(oe,{variant:"outline",className:`${j.color} text-xs px-2.5 py-0.5 capitalize hidden md:inline-flex`,children:R.priority}),(()=>{const P=(R==null?void 0:R.templateType)||(R==null?void 0:R.template_type)||"",B=(P==null?void 0:P.toUpperCase())||"";let k="Non-Templatized",L="bg-purple-100 !text-purple-600 border-purple-200";return B==="DEALER CLAIM"?(k="Dealer Claim",L="bg-blue-100 !text-blue-700 border-blue-200"):B==="TEMPLATE"&&(k="Template"),e.jsx(oe,{variant:"outline",className:`${L} text-xs px-2.5 py-0.5 shrink-0 hidden md:inline-flex`,"data-testid":"template-type-badge",children:k})})()]}),e.jsx("h4",{className:"text-sm font-semibold text-gray-800 line-clamp-1 leading-relaxed",children:R.title}),R.currentLevelSLA&&(()=>{var V;const P=!!(R.isPaused||(V=R.pauseInfo)!=null&&V.isPaused||R.status==="paused"),B=R.currentLevelSLA.percentageUsed||0,L=P?{bg:"bg-gray-100 border border-gray-300",progress:"bg-gray-500",text:"text-gray-600",icon:"text-gray-600"}:B>=100?{bg:"bg-red-50 border border-red-200",progress:"bg-red-600",text:"text-red-600",icon:"text-blue-600"}:B>=75?{bg:"bg-orange-50 border border-orange-200",progress:"bg-orange-500",text:"text-orange-600",icon:"text-blue-600"}:B>=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 ${L.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:[P?e.jsx(Ha,{className:`w-3.5 h-3.5 ${L.icon}`}):e.jsx(nt,{className:`w-3.5 h-3.5 ${L.icon}`}),e.jsxs("span",{className:"text-xs font-medium text-gray-900",children:["TAT: ",B,"% ",P&&"(paused)"]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"text-gray-600",children:R.currentLevelSLA.elapsedText}),e.jsxs("span",{className:`font-semibold ${L.text}`,children:[R.currentLevelSLA.remainingText," left"]})]})]}),e.jsx(oa,{value:B,className:"h-1.5",indicatorClassName:L.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(ts,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(ss,{className:"bg-gradient-to-br from-slate-700 to-slate-900 text-white text-[10px] font-bold",children:R.initiator.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:R.initiator.name})]}),R.currentApprover&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ts,{className:"h-6 w-6 ring-2 ring-yellow-200 shadow-sm",children:e.jsx(ss,{className:"bg-yellow-500 text-white text-[10px] font-bold",children:R.currentApprover.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:R.currentApprover.name})]}),R.approvalStep&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ye,{className:"w-3.5 h-3.5 text-blue-500"}),e.jsx("span",{className:"font-medium",children:R.approvalStep})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(xt,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",R.createdAt!=="—"?ga(R.createdAt):"—"]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(ls,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})},R.id)})}),T.length===0&&e.jsx(se,{className:"shadow-lg border-0",children:e.jsxs(ae,{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(ke,{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:u.searchTerm||u.activeFiltersCount>0?"Try adjusting your filters or search terms to see more results.":"No open requests available at the moment."}),u.activeFiltersCount>0&&e.jsx(F,{variant:"outline",className:"mt-4",onClick:u.clearFilters,children:"Clear all filters"})]})}),o>1&&!r&&e.jsx(se,{className:"shadow-md",children:e.jsx(ae,{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 ",(u.currentPage-1)*h+1," to ",Math.min(u.currentPage*h,d)," of ",d," open requests"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(F,{variant:"outline",size:"sm",onClick:()=>w(u.currentPage-1),disabled:u.currentPage===1,className:"h-8 w-8 p-0",children:e.jsx(ls,{className:"h-4 w-4 rotate-180"})}),u.currentPage>3&&o>5&&e.jsxs(e.Fragment,{children:[e.jsx(F,{variant:"outline",size:"sm",onClick:()=>w(1),className:"h-8 w-8 p-0",children:"1"}),e.jsx("span",{className:"text-muted-foreground",children:"..."})]}),A().map(R=>e.jsx(F,{variant:R===u.currentPage?"default":"outline",size:"sm",onClick:()=>w(R),className:`h-8 w-8 p-0 ${R===u.currentPage?"bg-re-green text-white hover:bg-re-green/90":""}`,children:R},R)),u.currentPage<o-2&&o>5&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"..."}),e.jsx(F,{variant:"outline",size:"sm",onClick:()=>w(o),className:"h-8 w-8 p-0",children:o})]}),e.jsx(F,{variant:"outline",size:"sm",onClick:()=>w(u.currentPage+1),disabled:u.currentPage===o,className:"h-8 w-8 p-0",children:e.jsx(ls,{className:"h-4 w-4"})})]})]})})})]})}function r5({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(ke,{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(oe,{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(F,{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(Ut,{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 n5(t){switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:fa,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 i5(t){switch(t){case"closed":return{color:"bg-slate-100 text-slate-800 border-slate-300",icon:Re,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:Ct,iconColor:"text-red-600",label:"Rejected",description:"Request was declined"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ye,iconColor:"text-gray-600",label:t,description:""}}}function l5({request:t,onViewRequest:s}){const a=n5(t.priority),r=i5(t.status),n=a.icon,i=r.icon;return e.jsx(se,{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(ae,{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(oe,{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(oe,{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(oe,{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="Non-Templatized",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(oe,{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(ts,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(ss,{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(Re,{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(xt,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",t.createdAt!=="—"?ga(t.createdAt,!0):"—"]})]}),t.dueDate&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Re,{className:"w-3.5 h-3.5 text-slate-600"}),e.jsxs("span",{className:"font-medium",children:["Closed: ",ga(t.dueDate,!0)]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(ls,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})})}function o5({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(l5,{request:r,onViewRequest:a},r.id))})}function c5({searchTerm:t,activeFiltersCount:s,onClearFilters:a}){return e.jsx(se,{className:"shadow-lg border-0","data-testid":"closed-requests-empty",children:e.jsxs(ae,{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(ke,{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(F,{variant:"outline",className:"mt-4",onClick:a,"data-testid":"closed-requests-empty-clear-filters",children:"Clear all filters"})]})})}function d5(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 m5({pagination:t,onPageChange:s}){const{currentPage:a,totalPages:r,totalRecords:n,itemsPerPage:i}=t;if(r<=1)return null;const l=d5(a,r);return e.jsx(se,{className:"shadow-md","data-testid":"closed-requests-pagination",children:e.jsx(ae,{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(F,{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(ls,{className:"h-4 w-4 rotate-180"})}),a>3&&r>5&&e.jsxs(e.Fragment,{children:[e.jsx(F,{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(F,{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(F,{variant:"outline",size:"sm",onClick:()=>s(r),className:"h-8 w-8 p-0","data-testid":"closed-requests-pagination-last",children:r})]}),e.jsx(F,{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(ls,{className:"h-4 w-4"})})]})]})})})}function u5(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 x5(t){return t.map(u5)}function h5({itemsPerPage:t=10}={}){const[s,a]=p.useState([]),[r,n]=p.useState(!1),[i,l]=p.useState(!1),[o,c]=p.useState({currentPage:1,totalPages:1,totalRecords:0,itemsPerPage:t}),d=p.useCallback(async(h=1,x)=>{try{h===1&&(n(!0),a([]));const u=await Is.listClosedByMe({page:h,limit:t,search:x==null?void 0:x.search,status:x!=null&&x.status&&x.status!=="all"?x.status:void 0,priority:x==null?void 0:x.priority,templateType:x==null?void 0:x.templateType,sortBy:x==null?void 0:x.sortBy,sortOrder:x==null?void 0:x.sortOrder}),g=Array.isArray(u==null?void 0:u.data)?u.data:[],b=x5(g);a(b);const f=u==null?void 0:u.pagination;f&&c({currentPage:f.page||1,totalPages:f.totalPages||1,totalRecords:f.total||0,itemsPerPage:t})}catch(u){console.error("[ClosedRequests] Error fetching requests:",u),a([])}finally{n(!1),l(!1)}},[t]),m=p.useCallback(h=>{l(!0),d(o.currentPage,h)},[d,o.currentPage]);return{requests:s,loading:r,refreshing:i,pagination:o,fetchRequests:d,handleRefresh:m}}const p5={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",sortBy:"created",sortOrder:"desc",currentPage:1},Fg=Gr({name:"closedRequests",initialState:p5,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:g5,setStatusFilter:f5,setPriorityFilter:b5,setTemplateTypeFilter:y5,setSortBy:v5,setSortOrder:j5,setCurrentPage:N5,clearFilters:w5}=Fg.actions;function C5({onFiltersChange:t,debounceMs:s=500}={}){const a=Tn(),r=p.useRef(null),n=p.useRef(!0),{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:c,sortBy:d,sortOrder:m,currentPage:h}=Yr(N=>N.closedRequests),x=p.useCallback(N=>a(g5(N)),[a]),u=p.useCallback(N=>a(f5(N)),[a]),g=p.useCallback(N=>a(b5(N)),[a]),b=p.useCallback(N=>a(y5(N)),[a]),f=p.useCallback(N=>a(v5(N)),[a]),y=p.useCallback(N=>a(j5(N)),[a]),v=p.useCallback(N=>a(N5(N)),[a]),C=p.useCallback(()=>({search:i,status:l,priority:o,templateType:c!=="all"?c:void 0,sortBy:d,sortOrder:m}),[i,l,o,c,d,m]);p.useEffect(()=>{if(n.current){n.current=!1;return}r.current&&clearTimeout(r.current);const N=setTimeout(()=>{t&&t(C())},i?s:0);return r.current=N,()=>{r.current&&clearTimeout(r.current)}},[i,l,o,c,d,m,t,C,s]);const w=p.useCallback(()=>{a(w5())},[a]),A=[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:h,setSearchTerm:x,setPriorityFilter:g,setStatusFilter:u,setTemplateTypeFilter:b,setSortBy:f,setSortOrder:y,setCurrentPage:v,clearFilters:w,activeFiltersCount:A,getFilters:C}}function S5({onViewRequest:t}){const s=h5({itemsPerPage:10}),a=p.useRef(s.fetchRequests);a.current=s.fetchRequests;const r=C5(),n=p.useMemo(()=>{try{const h=st.getUserData();return Lo(h)}catch(h){return console.error("[ClosedRequests] Error getting user filter type:",h),"STANDARD"}},[]),i=p.useMemo(()=>qT(n),[n]),l=n==="DEALER",o=p.useRef({searchTerm:r.searchTerm,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,templateTypeFilter:r.templateTypeFilter,sortBy:r.sortBy,sortOrder:r.sortOrder}),c=p.useRef(!1);p.useEffect(()=>{const h=r.currentPage||1;a.current(h,{search:r.searchTerm||void 0,status:r.statusFilter!=="all"?r.statusFilter:void 0,priority:!l&&r.priorityFilter!=="all"?r.priorityFilter:void 0,templateType:!l&&r.templateTypeFilter!=="all"?r.templateTypeFilter:void 0,sortBy:r.sortBy,sortOrder:r.sortOrder}),c.current=!0},[l]),p.useEffect(()=>{if(!c.current)return;const h=o.current;if(!(h.searchTerm!==r.searchTerm||h.statusFilter!==r.statusFilter||h.priorityFilter!==r.priorityFilter||h.templateTypeFilter!==r.templateTypeFilter||h.sortBy!==r.sortBy||h.sortOrder!==r.sortOrder))return;const u=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}),o.current={searchTerm:r.searchTerm,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,templateTypeFilter:r.templateTypeFilter,sortBy:r.sortBy,sortOrder:r.sortOrder}},r.searchTerm!==h.searchTerm?500:0);return()=>clearTimeout(u)},[r.searchTerm,r.statusFilter,r.priorityFilter,r.templateTypeFilter,r.sortBy,r.sortOrder,l]);const d=p.useCallback(h=>{h>=1&&h<=s.pagination.totalPages&&(r.setCurrentPage(h),s.fetchRequests(h,{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]),m=p.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(r5,{totalRecords:s.pagination.totalRecords,loading:s.loading,refreshing:s.refreshing,onRefresh:m}),e.jsx(i,{searchTerm:r.searchTerm,priorityFilter:r.priorityFilter,statusFilter:r.statusFilter,templateTypeFilter:r.templateTypeFilter,sortBy:r.sortBy,sortOrder:r.sortOrder,activeFiltersCount:l?[r.searchTerm,r.statusFilter!=="all"?r.statusFilter:null].filter(Boolean).length: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(o5,{requests:s.requests,loading:s.loading,onViewRequest:t}),s.requests.length===0&&!s.loading&&e.jsx(c5,{searchTerm:r.searchTerm,activeFiltersCount:r.activeFiltersCount,onClearFilters:r.clearFilters}),!s.loading&&e.jsx(m5,{pagination:s.pagination,onPageChange:d})]})}function A5(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 T5(t){return A5(t)?"DEALER_CLAIM":"CUSTOM"}function k5(t,s){return`/request/${t}`}class R5 extends p.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(os,{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(F,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(F,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}}function D5({requestId:t,onBack:s,dynamicRequests:a=[]}){const n=Fa().requestId||t||"",{user:i}=Jt(),{apiRequest:l,loading:o}=fc(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(Ut,{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=T5(l),d=JT(c);return e.jsx(d,{requestId:t,onBack:s,dynamicRequests:a})}function P5(t){return e.jsx(R5,{children:e.jsx(D5,{...t})})}function I5({onViewSummary:t}){const s=Fs(),[a,r]=p.useState([]),[n,i]=p.useState(!0),[l,o]=p.useState(""),[c,d]=p.useState(1),[m,h]=p.useState(1),[x,u]=p.useState(0),g=10,b=p.useCallback(async(C=1)=>{try{i(!0);const w=await IA({page:C,limit:g});r(w.data||[]),h(w.pagination.totalPages||1),u(w.pagination.total||0),d(w.pagination.page||1)}catch(w){console.error("Failed to fetch shared summaries:",w),K.error("Failed to load shared summaries")}finally{i(!1)}},[]);p.useEffect(()=>{b(1)},[b]);const f=async C=>{try{await jg(C),r(w=>w.map(A=>A.sharedSummaryId===C?{...A,isRead:!0,viewedAt:new Date().toISOString()}:A)),t?t(C):s(`/shared-summaries/${C}`)}catch(w){console.error("Failed to mark as viewed:",w),t?t(C):s(`/shared-summaries/${C}`)}},y=C=>{C>=1&&C<=m&&b(C)},v=a.filter(C=>{var A,N,_,T;if(!l)return!0;const w=l.toLowerCase();return((A=C.title)==null?void 0:A.toLowerCase().includes(w))||((N=C.requestNumber)==null?void 0:N.toLowerCase().includes(w))||((_=C.initiatorName)==null?void 0:_.toLowerCase().includes(w))||((T=C.sharedByName)==null?void 0:T.toLowerCase().includes(w))});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(Es,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(Ie,{placeholder:"Search by title, request number, or user...",value:l,onChange:C=>o(C.target.value),className:"pl-10 text-sm sm:text-base"})]})}),n&&e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(it,{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(ke,{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(C=>e.jsx("div",{className:`bg-white rounded-lg shadow-sm border-2 transition-all cursor-pointer hover:shadow-md ${C.isRead?"border-gray-200":"border-blue-300 bg-blue-50"}`,onClick:()=>f(C.sharedSummaryId),children:e.jsx("div",{className:"p-3 sm:p-4 md:p-6",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0 w-full sm:w-auto",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[C.isRead?e.jsx(Yf,{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:C.title}),!C.isRead&&e.jsx("span",{className:"px-2 py-0.5 bg-blue-100 text-blue-700 text-xs font-medium rounded-full flex-shrink-0",children:"New"})]}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-600 mb-2 sm:mb-3 break-words",children:["Request: ",e.jsx("span",{className:"font-medium",children:C.requestNumber})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:flex-wrap items-start sm:items-center gap-2 sm:gap-3 md:gap-4 text-xs sm:text-sm text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(Gt,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Initiator: ",e.jsx("span",{className:"font-medium",children:C.initiatorName})]})]}),e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(Gt,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Shared by: ",e.jsx("span",{className:"font-medium",children:C.sharedByName})]})]}),e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(xt,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Shared: ",Ge(new Date(C.sharedAt),"MMM dd, yyyy HH:mm")]})]}),C.viewedAt&&e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(bt,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Viewed: ",Ge(new Date(C.viewedAt),"MMM dd, yyyy HH:mm")]})]})]})]}),e.jsx(F,{variant:"outline",size:"sm",className:"w-full sm:w-auto flex-shrink-0",onClick:w=>{w.stopPropagation(),f(C.sharedSummaryId)},children:"View"})]})})},C.sharedSummaryId))}),m>1&&e.jsxs("div",{className:"flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-3 sm:gap-4 bg-white rounded-lg shadow-sm border border-gray-200 p-3 sm:p-4",children:[e.jsxs("div",{className:"text-xs sm:text-sm text-gray-600 text-center sm:text-left",children:["Showing ",(c-1)*g+1," to ",Math.min(c*g,x)," of ",x," summaries"]}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.jsx(F,{variant:"outline",size:"sm",onClick:()=>y(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(F,{variant:"outline",size:"sm",onClick:()=>y(c+1),disabled:c===m,className:"text-xs sm:text-sm",children:"Next"})]})]})]})]})})}function E5(){const{sharedSummaryId:t}=Fa(),s=Fs(),[a,r]=p.useState(null),[n,i]=p.useState(!0);p.useEffect(()=>{if(!t){s("/shared-summaries");return}(async()=>{var m,h;try{i(!0);try{await jg(t)}catch(u){console.warn("Failed to mark as viewed:",u)}const x=await yc(t);r(x)}catch(x){console.error("Failed to fetch summary details:",x),K.error(((h=(m=x==null?void 0:x.response)==null?void 0:m.data)==null?void 0:h.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(Re,{className:"h-4 w-4 text-green-600"}):m==="rejected"?e.jsx(Ct,{className:"h-4 w-4 text-red-600"}):m==="pending"||m==="in progress"?e.jsx(nt,{className:"h-4 w-4 text-orange-600"}):e.jsx(ke,{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(it,{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(F,{variant:"ghost",size:"sm",onClick:()=>s("/shared-summaries"),className:"mb-4",children:[e.jsx(Cs,{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(oe,{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(Bs,{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:Ge(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:Ge(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(oe,{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(Bs,{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(ke,{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(F,{onClick:()=>s("/shared-summaries"),children:"Go Back"})]})})}function F5(){const{requestId:t}=Fa(),s=Fs(),a=i=>{s(`/${i}`)},r=()=>{s("/new-request")},n=()=>{s("/login")};return e.jsx(vs,{currentPage:"work-notes",onNavigate:a,onNewRequest:r,onLogout:n,children:e.jsx("div",{className:"h-full w-full overflow-hidden",children:e.jsx(vg,{requestId:t||""})})})}function _g({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(oe,{variant:"secondary",className:"text-xs sm:text-sm md:text-base px-2 sm:px-3 md:px-4 py-1 sm:py-1.5 md:py-2 bg-slate-100 text-slate-800 font-semibold","data-testid":`${i}-badge`,children:[r.loading?"Loading…":r.value,e.jsx("span",{className:"hidden sm:inline ml-1",children:r.label})]}),n]})]})}function Gs({label:t,value:s,icon:a,iconColor:r,gradient:n,textColor:i,valueColor:l,testId:o="stats-card",onClick:c}){return e.jsx(se,{className:`${n} border transition-shadow ${c?"cursor-pointer hover:shadow-lg":"hover:shadow-md"}`,"data-testid":o,onClick:c,children:e.jsx(ae,{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 _5({stats:t,onStatusFilter:s}){const a=r=>{s&&s(r)};return e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-3 sm:gap-4","data-testid":"my-requests-stats",children:[e.jsx(Gs,{label:"Total",value:t.total,icon:ke,iconColor:"text-blue-600",gradient:"bg-gradient-to-br from-blue-50 to-blue-100 border-blue-200",textColor:"text-blue-700",valueColor:"text-blue-900",testId:"stat-total",onClick:s?()=>a("all"):void 0}),e.jsx(Gs,{label:"Pending",value:t.pending,icon:nt,iconColor:"text-orange-600",gradient:"bg-gradient-to-br from-orange-50 to-orange-100 border-orange-200",textColor:"text-orange-700",valueColor:"text-orange-900",testId:"stat-pending",onClick:s?()=>a("pending"):void 0}),e.jsx(Gs,{label:"Paused",value:t.paused,icon:Ka,iconColor:"text-amber-600",gradient:"bg-gradient-to-br from-amber-50 to-amber-100 border-amber-200",textColor:"text-amber-700",valueColor:"text-amber-900",testId:"stat-paused",onClick:s?()=>a("paused"):void 0}),e.jsx(Gs,{label:"Approved",value:t.approved,icon:Re,iconColor:"text-green-600",gradient:"bg-gradient-to-br from-green-50 to-green-100 border-green-200",textColor:"text-green-700",valueColor:"text-green-900",testId:"stat-approved",onClick:s?()=>a("approved"):void 0}),e.jsx(Gs,{label:"Rejected",value:t.rejected,icon:Ct,iconColor:"text-red-600",gradient:"bg-gradient-to-br from-red-50 to-red-100 border-red-200",textColor:"text-red-700",valueColor:"text-red-900",testId:"stat-rejected",onClick:s?()=>a("rejected"):void 0}),e.jsx(Gs,{label:"Draft",value:t.draft,icon:bo,iconColor:"text-gray-600",gradient:"bg-gradient-to-br from-gray-50 to-gray-100 border-gray-200",textColor:"text-gray-700",valueColor:"text-gray-900",testId:"stat-draft",onClick:s?()=>a("draft"):void 0}),e.jsx(Gs,{label:"Closed",value:t.closed,icon:yo,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 L5({searchTerm:t,statusFilter:s,priorityFilter:a,templateTypeFilter:r,onSearchChange:n,onStatusChange:i,onPriorityChange:l,onTemplateTypeChange:o}){return e.jsx(se,{className:"border-gray-200","data-testid":"my-requests-filters",children:e.jsx(ae,{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(Es,{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(Ie,{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(Ke,{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(Xe,{placeholder:"Status"})}),e.jsxs(Je,{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(Ke,{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(Xe,{placeholder:"Priority"})}),e.jsxs(Je,{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(Ke,{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(Xe,{placeholder:"Template Type"})}),e.jsxs(Je,{children:[e.jsx(Y,{value:"all",children:"All Templates"}),e.jsx(Y,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(Y,{value:"DEALER CLAIM",children:"Dealer Claim"})]})]})]})]})})})}function M5(t){switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:fa,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 $5(t){switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:Re,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ct,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:nt,iconColor:"text-yellow-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Re,iconColor:"text-gray-600"};case"draft":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:bo,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ye,iconColor:"text-gray-600"}}}const O5=t=>{if(!t)return"";let s=t.replace(/<(address|article|aside|blockquote|canvas|dd|div|dl|dt|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hr|li|main|nav|noscript|ol|p|pre|section|table|tfoot|ul|video)[^>]*>/gi," ");return s=s.replace(/<br\s*\/?>/gi," "),s=s.replace(/<[^>]*>/g,""),s=s.replace(/\s+/g," ").trim(),s=s.replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#039;/g,"'"),s};function U5({request:t,index:s,onViewRequest:a}){var o;const r=$5(t.status),n=M5(t.priority),i=r.icon,l=n.icon;return e.jsx(is.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:s*.1},children:e.jsx(se,{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(ae,{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(oe,{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(oe,{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(Ka,{className:"w-3 h-3 mr-1"}),"Paused"]}),e.jsxs(oe,{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="Non-Templatized",h="bg-purple-100 !text-purple-600 border-purple-200";return d==="DEALER CLAIM"?(m="Dealer Claim",h="bg-blue-100 !text-blue-700 border-blue-200"):d==="TEMPLATE"&&(m="Template"),e.jsx(oe,{variant:"outline",className:`${h} 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:O5(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:"})," ",ga(t.submittedDate)]})]})]}),e.jsx(ls,{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(Gt,{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(na,{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(nt,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{"data-testid":"submitted-timestamp",children:["Submitted: ",ga(t.submittedDate)]})]})]})]})})})})}function B5({requests:t,loading:s,searchTerm:a,statusFilter:r,priorityFilter:n,onViewRequest:i}){if(s)return e.jsx(se,{"data-testid":"loading-state",children:e.jsx(ae,{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(se,{"data-testid":"empty-state",children:e.jsxs(ae,{className:"p-12 text-center",children:[e.jsx(ke,{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(U5,{request:l,index:o,onViewRequest:i},l.id))})}function V5(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 Lg(t){return Array.isArray(t)?t.map(V5):[]}function z5({itemsPerPage:t=10}={}){const[s,a]=p.useState([]),[r,n]=p.useState(!1),[i,l]=p.useState(!1),[o,c]=p.useState({currentPage:1,totalPages:1,totalRecords:0,itemsPerPage:t}),d=p.useCallback(async(m=1,h)=>{try{m===1&&(n(!0),a([]));const x=await Is.listMyInitiatedWorkflows({page:m,limit:t,search:h==null?void 0:h.search,status:h==null?void 0:h.status,priority:h==null?void 0:h.priority,templateType:h==null?void 0:h.templateType}),u=Array.isArray(x==null?void 0:x.data)?x.data:[],g=Lg(u);a(g),l(!0);const b=x==null?void 0:x.pagination;b&&c({currentPage:b.page||1,totalPages:b.totalPages||1,totalRecords:b.total||0,itemsPerPage:t})}catch(x){console.error("[MyRequests] Error fetching requests:",x),a([]),l(!0)}finally{n(!1)}},[t]);return{requests:s,loading:r,hasFetchedFromApi:i,pagination:o,fetchMyRequests:d}}const H5={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",currentPage:1},Mg=Gr({name:"myRequests",initialState:H5,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:G5,setStatusFilter:W5,setPriorityFilter:Y5,setTemplateTypeFilter:K5,setCurrentPage:X5,clearFilters:Z5}=Mg.actions;function J5({onFiltersChange:t,debounceMs:s=500}={}){const a=Tn(),r=p.useRef(null),n=p.useRef(!0),{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:c,currentPage:d}=Yr(y=>y.myRequests),m=p.useCallback(y=>a(G5(y)),[a]),h=p.useCallback(y=>a(W5(y)),[a]),x=p.useCallback(y=>a(Y5(y)),[a]),u=p.useCallback(y=>a(K5(y)),[a]),g=p.useCallback(y=>a(X5(y)),[a]),b=p.useCallback(()=>({search:i,status:l,priority:o,templateType:c}),[i,l,o,c]);p.useEffect(()=>{if(n.current){n.current=!1;return}r.current&&clearTimeout(r.current);const y=setTimeout(()=>{t&&t(b())},i?s:0);return r.current=y,()=>{r.current&&clearTimeout(r.current)}},[i,l,o,c,t,b,s]);const f=p.useCallback(()=>{a(Z5())},[a]);return{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:c,currentPage:d,setSearchTerm:m,setStatusFilter:h,setPriorityFilter:x,setTemplateTypeFilter:u,setCurrentPage:g,getFilters:b,resetFilters:f}}function Q5({onViewRequest:t,dynamicRequests:s=[]}){const{user:a}=Jt(),r=z5({itemsPerPage:10}),n=p.useRef(r.fetchMyRequests);n.current=r.fetchMyRequests;const i=J5(),l=p.useRef({searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,templateTypeFilter:i.templateTypeFilter}),o=p.useRef(!1);p.useEffect(()=>{const y=i.currentPage||1;n.current(y,{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},[]),p.useEffect(()=>{if(!o.current)return;const y=l.current;if(!(y.searchTerm!==i.searchTerm||y.statusFilter!==i.statusFilter||y.priorityFilter!==i.priorityFilter||y.templateTypeFilter!==i.templateTypeFilter))return;const C=setTimeout(()=>{i.setCurrentPage(1),n.current(1,{search:i.searchTerm||void 0,status:i.statusFilter!=="all"?i.statusFilter:void 0,priority:i.priorityFilter!=="all"?i.priorityFilter:void 0,templateType:i.templateTypeFilter!=="all"?i.templateTypeFilter:void 0}),l.current={searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,templateTypeFilter:i.templateTypeFilter}},i.searchTerm!==y.searchTerm?500:0);return()=>clearTimeout(C)},[i.searchTerm,i.statusFilter,i.priorityFilter,i.templateTypeFilter]);const[c,d]=p.useState(null),[m,h]=p.useState(!1),x=p.useCallback(async()=>{if(a!=null&&a.userId)try{h(!0);const y=await Dt.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:y.totalRequests||0,pending:y.openRequests||0,paused:y.pausedRequests||0,approved:y.approvedRequests||0,rejected:y.rejectedRequests||0,draft:y.draftRequests||0,closed:y.closedRequests||0})}catch(y){console.error("Failed to fetch backend stats:",y),d(null)}finally{h(!1)}},[a==null?void 0:a.userId,i.searchTerm,i.priorityFilter,i.templateTypeFilter]);p.useEffect(()=>{const y=setTimeout(()=>{x()},i.searchTerm?500:0);return()=>clearTimeout(y)},[i.searchTerm,i.priorityFilter,i.templateTypeFilter,x]);const u=Lg(s),g=r.hasFetchedFromApi?r.requests:u,b=p.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]),f=p.useCallback(y=>{y>=1&&y<=r.pagination.totalPages&&(i.setCurrentPage(y),r.fetchMyRequests(y,{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(_g,{icon:ke,title:"My Requests",description:"Track and manage all your submitted requests",badge:{value:`${b.total} total`,label:"requests",loading:r.loading||m},testId:"my-requests-header"}),e.jsx(_5,{stats:b,onStatusFilter:y=>{i.setStatusFilter(y)}}),e.jsx(L5,{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(B5,{requests:g,loading:r.loading,searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,onViewRequest:t}),e.jsx(jr,{currentPage:i.currentPage||r.pagination.currentPage,totalPages:r.pagination.totalPages,totalRecords:r.pagination.totalRecords,itemsPerPage:r.pagination.itemsPerPage,onPageChange:f,loading:r.loading,itemLabel:"requests",testIdPrefix:"my-requests-pagination"})]})}function $g({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(_g,{icon:ke,title:i(),description:l(),testId:"requests-header"}),e.jsx(oe,{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(F,{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(Ut,{className:"w-4 h-4 mr-2 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(At,{className:"w-4 h-4 mr-2"}),"Export"]})})]})}function Og({stats:t,onStatusFilter:s}){const a=r=>{s&&s(r)};return e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3 sm:gap-4","data-testid":"requests-stats",children:[e.jsx(Gs,{label:"Total",value:t.total,icon:ke,iconColor:"text-blue-600",gradient:"bg-gradient-to-br from-blue-50 to-blue-100 border-blue-200",textColor:"text-blue-700",valueColor:"text-blue-900",testId:"stat-total",onClick:s?()=>a("all"):void 0}),e.jsx(Gs,{label:"Pending",value:t.pending,icon:nt,iconColor:"text-orange-600",gradient:"bg-gradient-to-br from-orange-50 to-orange-100 border-orange-200",textColor:"text-orange-700",valueColor:"text-orange-900",testId:"stat-pending",onClick:s?()=>a("pending"):void 0}),e.jsx(Gs,{label:"Paused",value:t.paused,icon:Ka,iconColor:"text-amber-600",gradient:"bg-gradient-to-br from-amber-50 to-amber-100 border-amber-200",textColor:"text-amber-700",valueColor:"text-amber-900",testId:"stat-paused",onClick:s?()=>a("paused"):void 0}),e.jsx(Gs,{label:"Approved",value:t.approved,icon:Re,iconColor:"text-green-600",gradient:"bg-gradient-to-br from-green-50 to-green-100 border-green-200",textColor:"text-green-700",valueColor:"text-green-900",testId:"stat-approved",onClick:s?()=>a("approved"):void 0}),e.jsx(Gs,{label:"Rejected",value:t.rejected,icon:Ct,iconColor:"text-red-600",gradient:"bg-gradient-to-br from-red-50 to-red-100 border-red-200",textColor:"text-red-700",valueColor:"text-red-900",testId:"stat-rejected",onClick:s?()=>a("rejected"):void 0}),e.jsx(Gs,{label:"Closed",value:t.closed,icon:yo,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 q5=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:fa,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"}}},ek=t=>{switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:Re,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ct,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:nt,iconColor:"text-yellow-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Re,iconColor:"text-gray-600"};case"draft":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:bo,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ye,iconColor:"text-gray-600"}}},tk=t=>{if(!t)return"";let s=t.replace(/<(address|article|aside|blockquote|canvas|dd|div|dl|dt|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hr|li|main|nav|noscript|ol|p|pre|section|table|tfoot|ul|video)[^>]*>/gi," ");return s=s.replace(/<br\s*\/?>/gi," "),s=s.replace(/<[^>]*>/g,""),s=s.replace(/\s+/g," ").trim(),s=s.replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#039;/g,"'"),s};function sk({request:t,index:s,onViewRequest:a}){var o;const r=ek(t.status),n=q5(t.priority),i=r.icon,l=n.icon;return e.jsx(is.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:s*.1},children:e.jsx(se,{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(ae,{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(oe,{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(oe,{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(Ka,{className:"w-3 h-3 mr-1"}),"Paused"]}),e.jsxs(oe,{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="Non-Templatized",h="bg-purple-100 !text-purple-600 border-purple-200";return d==="DEALER CLAIM"?(m="Dealer Claim",h="bg-blue-100 !text-blue-700 border-blue-200"):d==="TEMPLATE"&&(m="Template"),e.jsx(oe,{variant:"outline",className:`${h} font-medium text-xs shrink-0`,"data-testid":"template-type-badge",children:m})})(),t.department&&e.jsx(oe,{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:tk(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:"})," ",ga(t.submittedDate)]})]})]}),e.jsx(ls,{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(Gt,{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(na,{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(nt,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{"data-testid":"submitted-timestamp",children:["Submitted: ",ga(t.submittedDate)]})]})]})]})})})})}function Ug({requests:t,loading:s,hasActiveFilters:a,onViewRequest:r}){return s?e.jsx(se,{"data-testid":"loading-state",children:e.jsx(ae,{className:"p-6 text-sm text-gray-600",children:"Loading requests…"})}):t.length===0?e.jsx(se,{"data-testid":"empty-state",children:e.jsxs(ae,{className:"p-12 text-center",children:[e.jsx(ke,{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(sk,{request:n,index:i,onViewRequest:r},n.id))})}const ak={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},Bg=Gr({name:"requests",initialState:ak,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:rk,setStatusFilter:nk,setPriorityFilter:ik,setTemplateTypeFilter:lk,setSlaComplianceFilter:ok,setDepartmentFilter:ck,setInitiatorFilter:dk,setApproverFilter:mk,setApproverFilterType:uk,setDateRange:Qu,setCustomStartDate:Al,setCustomEndDate:Tl,setShowCustomDatePicker:Hn,setCurrentPage:xk,clearFilters:hk}=Bg.actions;function Vg(){const t=Tn(),{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,slaComplianceFilter:i,departmentFilter:l,initiatorFilter:o,approverFilter:c,approverFilterType:d,dateRange:m,customStartDate:h,customEndDate:x,showCustomDatePicker:u,currentPage:g}=Yr(S=>S.requests),b=p.useCallback(S=>t(rk(S)),[t]),f=p.useCallback(S=>t(nk(S)),[t]),y=p.useCallback(S=>t(ik(S)),[t]),v=p.useCallback(S=>t(lk(S)),[t]),C=p.useCallback(S=>t(ok(S)),[t]),w=p.useCallback(S=>t(ck(S)),[t]),A=p.useCallback(S=>t(dk(S)),[t]),N=p.useCallback(S=>t(mk(S)),[t]),_=p.useCallback(S=>t(uk(S)),[t]),T=p.useCallback(S=>t(Qu(S)),[t]),R=p.useCallback(S=>t(Al(S)),[t]),j=p.useCallback(S=>t(Tl(S)),[t]),E=p.useCallback(S=>t(Hn(S)),[t]),P=p.useCallback(S=>t(xk(S)),[t]),B=p.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:h,endDate:x}),[s,a,r,n,i,l,o,c,d,m,h,x]),k=p.useCallback(()=>{t(hk())},[t]),L=p.useCallback(S=>{const O=S;t(Qu(O)),O!=="custom"?(t(Al(void 0)),t(Tl(void 0)),t(Hn(!1))):t(Hn(!0))},[t]),V=p.useCallback(()=>{h&&x&&(h>x&&(t(Al(x)),t(Tl(h))),t(Hn(!1)))},[h,x,t]);return{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,slaComplianceFilter:i,departmentFilter:l,initiatorFilter:o,approverFilter:c,approverFilterType:d,dateRange:m,customStartDate:h,customEndDate:x,showCustomDatePicker:u,currentPage:g,hasActiveFilters:!!(s||a!=="all"||r!=="all"||n!=="all"||i!=="all"||l!=="all"||o!=="all"||c!=="all"||m!=="all"||h||x),setSearchTerm:b,setStatusFilter:f,setPriorityFilter:y,setTemplateTypeFilter:v,setSlaComplianceFilter:C,setDepartmentFilter:w,setInitiatorFilter:A,setApproverFilter:N,setApproverFilterType:_,setDateRange:T,setCustomStartDate:R,setCustomEndDate:j,setShowCustomDatePicker:E,setCurrentPage:P,getFilters:B,clearFilters:k,handleDateRangeChange:L,handleApplyCustomDate:V}}function gi({filterValue:t,onFilterChange:s,source:a="default"}){const[r,n]=p.useState(""),[i,l]=p.useState([]),[o,c]=p.useState(!1),[d,m]=p.useState(null),[h,x]=p.useState(!1),u=p.useRef(null);p.useEffect(()=>{async function y(){if(t!=="all"&&!d)try{const v=await ur.getUserById(t);v&&(m(v),n(v.displayName||v.email))}catch(v){console.error("Failed to fetch user detail for search:",v)}else t==="all"&&(m(null),n(""))}y()},[t]),p.useEffect(()=>()=>{u.current&&clearTimeout(u.current)},[]);const g=p.useCallback(y=>{if(n(y),u.current&&clearTimeout(u.current),!y||y.trim().length<2){l([]),c(!1);return}u.current=setTimeout(async()=>{var v;x(!0);try{const w=((v=(await ur.searchUsers(y.trim(),10,a)).data)==null?void 0:v.data)||[];l(w),c(w.length>0)}catch(C){console.error("Search API failed:",C),l([]),c(!1)}finally{x(!1)}},400)},[a]),b=p.useCallback(y=>{m(y),s(y.userId),n(y.displayName||y.email),c(!1),l([])},[s]),f=p.useCallback(()=>{m(null),s("all"),n(""),c(!1),l([])},[s]);return{searchQuery:r,searchResults:i,showResults:o,selectedUser:d,searching:h,handleSearch:g,handleSelect:b,handleClear:f,setShowResults:c}}function pk(t){var d,m,h,x,u,g,b;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 f=t.approvals.find(y=>{const v=(y.status||"").toString().toUpperCase();return v==="PENDING"||v==="IN_PROGRESS"});if(f)n=f.approverName||((d=f.approver)==null?void 0:d.name)||((m=f.approver)==null?void 0:m.displayName)||f.approverEmail||((h=f.approver)==null?void 0:h.email)||"—";else{const v=[...t.approvals].sort((C,w)=>{const A=C.levelNumber||C.level_number||0;return(w.levelNumber||w.level_number||0)-A})[0];v&&(n=v.approverName||((x=v.approver)==null?void 0:x.name)||((u=v.approver)==null?void 0:u.displayName)||v.approverEmail||((g=v.approver)==null?void 0:g.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 f=t.approvals.find(y=>{const v=(y.status||"").toString().toUpperCase();return v==="PENDING"||v==="IN_PROGRESS"});if(f){const y=f.levelNumber||f.level_number||0,v=c||t.approvals.length;i=`${y} 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||((b=t.initiator)==null?void 0:b.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 zg(t){return Array.isArray(t)?t.map(pk):[]}function gk(t,s,a,r,n,i){if(t.length>0){const l=t.length,o=t.filter(u=>{const g=(u.status||"").toString().toUpperCase();return g==="PENDING"||g==="IN_PROGRESS"}).length,c=t.filter(u=>(u.status||"").toString().toUpperCase()==="APPROVED").length,d=t.filter(u=>(u.status||"").toString().toUpperCase()==="REJECTED").length,m=t.filter(u=>(u.status||"").toString().toUpperCase()==="DRAFT").length,h=t.filter(u=>(u.status||"").toString().toUpperCase()==="CLOSED").length,x=t.filter(u=>(u.status||"").toString().toUpperCase()==="PAUSED").length;return{total:l,pending:o,paused:x,approved:c,rejected:d,draft:m,closed:h}}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 Hg={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(bi,function(){return function(a,r){r.prototype.isSameOrBefore=function(n,i){return this.isSame(n,i)||this.isBefore(n,i)}}})})(Hg);var fk=Hg.exports;const Gg=yi(fk);var Wg={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(bi,function(){return function(a,r){r.prototype.isSameOrAfter=function(n,i){return this.isSame(n,i)||this.isAfter(n,i)}}})})(Wg);var bk=Wg.exports;const Yg=yi(bk);Ht.extend(Yg);Ht.extend(Gg);function yk(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,h;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(x=>{const u=(x.status||"").toString().toUpperCase();return u==="IN_PROGRESS"||u==="PENDING"}))==null?void 0:d.approverId)||((h=(m=n.approvals)==null?void 0:m.find(x=>{const u=(x.status||"").toString().toUpperCase();return u==="IN_PROGRESS"||u==="PENDING"}))==null?void 0:h.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,h,x,u,g,b,f,y,v,C;const n=s.slaCompliance||"";if(n.toLowerCase()==="compliant"){const w=(r.status||"").toString().toUpperCase();if(!(w==="APPROVED"||w==="REJECTED"||w==="CLOSED"))return!1;const N=((c=r.currentLevelSLA)==null?void 0:c.status)||((m=(d=r.currentApprover)==null?void 0:d.sla)==null?void 0:m.status)||((h=r.sla)==null?void 0:h.status)||((u=(x=r.summary)==null?void 0:x.sla)==null?void 0:u.status);return N?N!=="breached"&&N.toLowerCase()!=="breached":!0}const i=((g=r.currentLevelSLA)==null?void 0:g.status)||((f=(b=r.currentApprover)==null?void 0:b.sla)==null?void 0:f.status)||((y=r.sla)==null?void 0:y.status)||((C=(v=r.summary)==null?void 0:v.sla)==null?void 0:C.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=Ht(s.startDate).startOf("day").toDate(),n=Ht(s.endDate).endOf("day").toDate();else{const i=Ht();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 h=Ht(m).startOf("day").toDate(),x=Ht(r).startOf("day").toDate(),u=Ht(n).endOf("day").toDate();return h>=x&&h<=u}const o=Ht(l).startOf("day").toDate(),c=Ht(r).startOf("day").toDate(),d=Ht(n).endOf("day").toDate();return o>=c&&o<=d}))}return a}Ht.extend(Gg);Ht.extend(Yg);function vk(t){if(!t)return"N/A";try{const s=typeof t=="string"?new Date(t):t;return Ge(s,"yyyy-MM-dd HH:mm:ss")}catch{return"N/A"}}async function Kg(t,s){const a=yk(t,s),r=[["Request Number","Title","Status","Priority","Initiator","Department","Current Approver","Approval Level","Submitted Date","Description"].join(",")];a.forEach(c=>{var v,C,w,A,N;const d=(c.status||"").toString().toLowerCase().replace("_","-"),m=(c.priority||"").toString().toLowerCase(),h=((v=c.initiator)==null?void 0:v.displayName)||((C=c.initiator)==null?void 0:C.email)||c.initiatorName||"N/A",x=c.department||((w=c.initiator)==null?void 0:w.department)||"N/A",u=((A=c.currentApprover)==null?void 0:A.displayName)||((N=c.currentApprover)==null?void 0:N.email)||c.currentApproverName||"N/A",g=c.currentApproverLevel||c.approvalLevel||c.currentLevel||"N/A",b=vk(c.submittedAt||c.createdAt||c.submitted_at||c.created_at),f=(c.description||"").replace(/"/g,'""').replace(/\n/g," ").replace(/\r/g,""),y=[c.requestNumber||c.request_number||"",`"${(c.title||"").replace(/"/g,'""')}"`,d,m,`"${h.replace(/"/g,'""')}"`,`"${x.replace(/"/g,'""')}"`,`"${u.replace(/"/g,'""')}"`,g,b,`"${f}"`];r.push(y.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 jk({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 Is.listWorkflows({page:t,limit:s,...c});let m=[];Array.isArray(d==null?void 0:d.data)?m=d.data:Array.isArray(d)&&(m=d);const h=m.filter(g=>(g.status||"").toString().toUpperCase()!=="DRAFT"),x=(d==null?void 0:d.pagination)||{page:t,limit:s,total:h.length,totalPages:1};return{data:h,allData:[],filteredData:h,pagination:{page:x.page,limit:x.limit||s,total:x.total||h.length,totalPages:x.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 Is.listParticipantRequests({page:t,limit:s,...c});let m=[];Array.isArray(d==null?void 0:d.data)?m=d.data:Array.isArray(d)&&(m=d);const h=m.filter(u=>(u.status||"").toString().toUpperCase()!=="DRAFT"),x=(d==null?void 0:d.pagination)||{page:t,limit:s,total:h.length,totalPages:1};return{data:h,allData:[],filteredData:h,pagination:x}}}async function Nk(t){const a=[];let r=1,n=!0;const i=100;for(;n&&r<=i;){const l=t?await Is.listWorkflows({page:r,limit:100}):await Is.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 wk({onViewRequest:t}){const{user:s}=Jt(),a=Yr(I=>I.dashboard.viewAsUser),r=p.useMemo(()=>Di(s),[s]),n=p.useMemo(()=>r&&!a,[r,a]),i=Vg(),[l,o]=p.useState([]),[c,d]=p.useState(!1),[m,h]=p.useState(!1),[x,u]=p.useState(null),[g,b]=p.useState([]),[f,y]=p.useState(!1),[v,C]=p.useState(1),[w,A]=p.useState(0),[N]=p.useState(10),_=gi({filterValue:i.initiatorFilter,onFilterChange:i.setInitiatorFilter,source:"local"}),T=gi({filterValue:i.approverFilter,onFilterChange:i.setApproverFilter,source:"local"}),R=p.useCallback(async(I,M,W,G)=>{try{const re=G==null?void 0:G.slaCompliance;if(re&&re!=="all"&&re!=="breached"&&re!=="compliant"){const $={};G!=null&&G.search&&($.search=G.search),G!=null&&G.priority&&G.priority!=="all"&&($.priority=G.priority),G!=null&&G.department&&G.department!=="all"&&($.department=G.department),G!=null&&G.initiator&&G.initiator!=="all"&&($.initiator=G.initiator),G!=null&&G.approver&&G.approver!=="all"&&($.approver=G.approver,$.approverType=G.approverType||"current"),$.slaCompliance=re,I&&($.dateRange=I),M&&($.startDate=M.toISOString()),W&&($.endDate=W.toISOString());const z=n?await Is.listWorkflows({page:1,limit:1e3,...$}):await Is.listParticipantRequests({page:1,limit:1e3,...$}),H=Array.isArray(z==null?void 0:z.data)?z.data:[],je=H.length,le=H.filter(Ve=>{const Qe=(Ve.status||"").toString().toUpperCase();return Qe==="PENDING"||Qe==="IN_PROGRESS"}).length,ue=H.filter(Ve=>(Ve.status||"").toString().toUpperCase()==="APPROVED").length,$e=H.filter(Ve=>(Ve.status||"").toString().toUpperCase()==="REJECTED").length,Te=H.filter(Ve=>(Ve.status||"").toString().toUpperCase()==="CLOSED").length;u({total:je,pending:le,paused:0,approved:ue,rejected:$e,draft:0,closed:Te})}else{const $=await Dt.getRequestStats(I,M?M.toISOString():void 0,W?W.toISOString():void 0,void 0,G==null?void 0:G.priority,G==null?void 0:G.templateType,G==null?void 0:G.department,G==null?void 0:G.initiator,G==null?void 0:G.approver,G==null?void 0:G.approverType,G==null?void 0:G.search,G==null?void 0:G.slaCompliance,!n);u({total:$.totalRequests||0,pending:$.openRequests||0,paused:$.pausedRequests||0,approved:$.approvedRequests||0,rejected:$.rejectedRequests||0,draft:$.draftRequests||0,closed:$.closedRequests||0})}}catch(re){console.error("Failed to fetch backend stats:",re)}finally{}},[n]),j=p.useCallback(async()=>{try{y(!0);const I=await Dt.getDepartments();b(I)}catch{}finally{y(!1)}},[]),E=p.useRef(i),P=p.useRef(R);p.useEffect(()=>{E.current=i,P.current=R},[i,R]),p.useEffect(()=>{const I=new URLSearchParams(window.location.search),M=I.get("approver"),W=I.get("approverType"),G=I.get("slaCompliance"),re=I.get("dateRange"),te=I.get("startDate"),$=I.get("endDate");M&&i.setApproverFilter(M),(W==="current"||W==="any")&&i.setApproverFilterType(W),G&&i.setSlaComplianceFilter(G),re&&i.setDateRange(re),te&&i.setCustomStartDate(new Date(te)),$&&i.setCustomEndDate(new Date($))},[]);const B=p.useCallback(async(I=1)=>{try{I===1&&(d(!0),o([]));const M=E.current.getFilters(),W=await jk({page:I,itemsPerPage:N,filters:M,isOrgLevel:n});o(W.data),i.setCurrentPage(W.pagination.page),C(W.pagination.totalPages),A(W.pagination.total)}catch{o([])}finally{d(!1)}},[N,n]),k=p.useCallback(async()=>{try{h(!0);const I=await Nk(n);await Kg(I,i.getFilters())}catch(I){console.error("Failed to export requests:",I),alert("Failed to export requests. Please try again.")}finally{h(!1)}},[n,i]);p.useEffect(()=>{j()},[j]),p.useEffect(()=>{const I=setTimeout(()=>{const M={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";P.current(W,i.customStartDate,i.customEndDate,M)},i.searchTerm?500:0);return()=>clearTimeout(I)},[n,i.dateRange,i.customStartDate,i.customEndDate,i.priorityFilter,i.templateTypeFilter,i.departmentFilter,i.initiatorFilter,i.approverFilter,i.approverFilterType,i.searchTerm,i.slaComplianceFilter]);const L=p.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}),V=p.useRef(!1);p.useEffect(()=>{const I=i.currentPage||1;B(I),V.current=!0},[]),p.useEffect(()=>{if(!V.current)return;const I=L.current;if(!(I.searchTerm!==i.searchTerm||I.statusFilter!==i.statusFilter||I.priorityFilter!==i.priorityFilter||I.templateTypeFilter!==i.templateTypeFilter||I.slaComplianceFilter!==i.slaComplianceFilter||I.departmentFilter!==i.departmentFilter||I.initiatorFilter!==i.initiatorFilter||I.approverFilter!==i.approverFilter||I.approverFilterType!==i.approverFilterType||I.dateRange!==i.dateRange||I.customStartDate!==i.customStartDate||I.customEndDate!==i.customEndDate||I.isOrgLevel!==n))return;const W=setTimeout(()=>{i.setCurrentPage(1),B(1),L.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!==I.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 D=p.useCallback(I=>{I>=1&&I<=v&&(i.setCurrentPage(I),B(I))},[v,B,i]),S=p.useMemo(()=>zg(l),[l]),O=p.useMemo(()=>x?{total:x.total||0,pending:x.pending||0,paused:x.paused||0,approved:x.approved||0,rejected:x.rejected||0,draft:x.draft||0,closed:x.closed||0}:gk([],n,x,!1,w,S),[n,x,w,S]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"requests-page",children:[e.jsx($g,{isOrgLevel:n,isAdmin:r,loading:c,exporting:m,onExport:k}),e.jsx(Og,{stats:O,onStatusFilter:I=>{i.setStatusFilter(I)}}),e.jsx(se,{className:"border-gray-200 shadow-md","data-testid":"requests-filters",children:e.jsx(ae,{className:"p-4 sm:p-6",children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qa,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),i.hasActiveFilters&&e.jsx(oe,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),i.hasActiveFilters&&e.jsxs(F,{variant:"ghost",size:"sm",onClick:i.clearFilters,className:"gap-2",children:[e.jsx(Ut,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Ps,{}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 lg:grid-cols-5 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative md:col-span-3 lg:col-span-1",children:[e.jsx(Es,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Ie,{placeholder:"Search requests...",value:i.searchTerm,onChange:I=>i.setSearchTerm(I.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(Ke,{value:i.statusFilter,onValueChange:i.setStatusFilter,children:[e.jsx(Ze,{className:"h-10","data-testid":"status-filter",children:e.jsx(Xe,{placeholder:"All Status"})}),e.jsxs(Je,{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(Ke,{value:i.priorityFilter,onValueChange:i.setPriorityFilter,children:[e.jsx(Ze,{className:"h-10","data-testid":"priority-filter",children:e.jsx(Xe,{placeholder:"All Priority"})}),e.jsxs(Je,{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(Ke,{value:i.templateTypeFilter,onValueChange:i.setTemplateTypeFilter,children:[e.jsx(Ze,{className:"h-10","data-testid":"template-type-filter",children:e.jsx(Xe,{placeholder:"All Templates"})}),e.jsxs(Je,{children:[e.jsx(Y,{value:"all",children:"All Templates"}),e.jsx(Y,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(Y,{value:"DEALER CLAIM",children:"Dealer Claim"})]})]}),e.jsxs(Ke,{value:i.departmentFilter,onValueChange:i.setDepartmentFilter,disabled:f||g.length===0,children:[e.jsx(Ze,{className:"h-10","data-testid":"department-filter",children:e.jsx(Xe,{placeholder:f?"Loading...":"All Departments"})}),e.jsxs(Je,{children:[e.jsx(Y,{value:"all",children:"All Departments"}),g.map(I=>e.jsx(Y,{value:I,children:I},I))]})]}),e.jsxs(Ke,{value:i.slaComplianceFilter,onValueChange:i.setSlaComplianceFilter,children:[e.jsx(Ze,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(Xe,{placeholder:"All SLA Status"})}),e.jsxs(Je,{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(ne,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:_.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:_.selectedUser.displayName||_.selectedUser.email}),e.jsx(F,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:_.handleClear,children:e.jsx(ft,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ie,{placeholder:"Search initiator...",value:_.searchQuery,onChange:I=>_.handleSearch(I.target.value),onFocus:()=>{_.searchResults.length>0&&_.setShowResults(!0)},onBlur:()=>setTimeout(()=>_.setShowResults(!1),200),className:"h-10","data-testid":"initiator-search-input"}),_.showResults&&_.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:_.searchResults.map(I=>e.jsx("button",{type:"button",onClick:()=>_.handleSelect(I),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:I.displayName||I.email}),I.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:I.email})]})},I.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(ne,{className:"text-sm font-medium text-gray-700",children:"Approver"}),i.approverFilter!=="all"&&e.jsxs(Ke,{value:i.approverFilterType,onValueChange:I=>i.setApproverFilterType(I),children:[e.jsx(Ze,{className:"h-7 w-32 text-xs",children:e.jsx(Xe,{})}),e.jsxs(Je,{children:[e.jsx(Y,{value:"current",children:"Current Only"}),e.jsx(Y,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:T.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:T.selectedUser.displayName||T.selectedUser.email}),e.jsx(F,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:T.handleClear,children:e.jsx(ft,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ie,{placeholder:"Search approver...",value:T.searchQuery,onChange:I=>T.handleSearch(I.target.value),onFocus:()=>{T.searchResults.length>0&&T.setShowResults(!0)},onBlur:()=>setTimeout(()=>T.setShowResults(!1),200),className:"h-10","data-testid":"approver-search-input"}),T.showResults&&T.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:T.searchResults.map(I=>e.jsx("button",{type:"button",onClick:()=>T.handleSelect(I),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:I.displayName||I.email}),I.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:I.email})]})},I.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(xt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ke,{value:i.dateRange,onValueChange:i.handleDateRangeChange,children:[e.jsx(Ze,{className:"w-[160px] h-10",children:e.jsx(Xe,{placeholder:"Date Range"})}),e.jsxs(Je,{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(Xs,{open:i.showCustomDatePicker,onOpenChange:i.setShowCustomDatePicker,children:[e.jsx(Zs,{asChild:!0,children:e.jsxs(F,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(xt,{className:"w-4 h-4"}),i.customStartDate&&i.customEndDate?`${Ge(i.customStartDate,"MMM d, yyyy")} - ${Ge(i.customEndDate,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Js,{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(ne,{htmlFor:"start-date",children:"Start Date"}),e.jsx(Us,{value:i.customStartDate||null,onChange:I=>{const M=I?new Date(I):void 0;M?(i.setCustomStartDate(M),i.customEndDate&&M>i.customEndDate&&i.setCustomEndDate(M)):i.setCustomStartDate(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"end-date",children:"End Date"}),e.jsx(Us,{value:i.customEndDate||null,onChange:I=>{const M=I?new Date(I):void 0;M?(i.setCustomEndDate(M),i.customStartDate&&M<i.customStartDate&&i.setCustomStartDate(M)):i.setCustomEndDate(void 0)},minDate:i.customStartDate||void 0,maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsx(F,{className:"w-full bg-[#2d4a3e] hover:bg-[#1f3329] text-white",onClick:i.handleApplyCustomDate,disabled:!i.customStartDate||!i.customEndDate,children:"Apply Range"})]}),e.jsx("div",{className:"flex gap-2 pt-2 border-t",children:e.jsx(F,{size:"sm",variant:"outline",onClick:()=>{i.setShowCustomDatePicker(!1),i.setCustomStartDate(void 0),i.setCustomEndDate(void 0),i.setDateRange("month")},children:"Cancel"})})]})})]})]})]})})}),e.jsx(Ug,{requests:S,loading:c,hasActiveFilters:i.hasActiveFilters,onViewRequest:t}),e.jsx(jr,{currentPage:i.currentPage||1,totalPages:v,totalRecords:w,itemsPerPage:N,onPageChange:D,loading:c,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}async function Ck({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 Is.listParticipantRequests({page:t,limit:s,...r});let i=[];Array.isArray(n==null?void 0:n.data)?i=n.data:Array.isArray(n)&&(i=n);const 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 qu=100;async function Sk(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 Is.listParticipantRequests({page:r,limit:qu,...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===qu}}return s}function Ak({onViewRequest:t}){const s=Vg(),a=p.useMemo(()=>{try{const W=st.getUserData();return Lo(W)}catch(W){return console.error("[UserAllRequests] Error getting user filter type:",W),"STANDARD"}},[]),r=p.useMemo(()=>e5(a),[a]),n=a==="DEALER",i=p.useCallback(()=>{const W=s.getFilters();if(n){const{priority:G,templateType:re,department:te,slaCompliance:$,...z}=W;return z}return W},[s,n]),l=p.useCallback(()=>n?!!(s.searchTerm||s.statusFilter!=="all"||s.initiatorFilter!=="all"||s.approverFilter!=="all"||s.dateRange!=="all"||s.customStartDate||s.customEndDate):s.hasActiveFilters,[n,s]),[o,c]=p.useState([]),[d,m]=p.useState(!1),[h,x]=p.useState(!1),[u,g]=p.useState(null),[b,f]=p.useState([]),[y,v]=p.useState(!1),[C,w]=p.useState(1),[A,N]=p.useState(0),[_]=p.useState(10),T=gi({filterValue:s.initiatorFilter,onFilterChange:s.setInitiatorFilter,source:"local"}),R=gi({filterValue:s.approverFilter,onFilterChange:s.setApproverFilter,source:"local"}),j=p.useCallback(async(W,G,re,te)=>{try{const $=await Dt.getRequestStats(W,G?G.toISOString():void 0,re?re.toISOString():void 0,void 0,te==null?void 0:te.priority,te==null?void 0:te.templateType,te==null?void 0:te.department,te==null?void 0:te.initiator,te==null?void 0:te.approver,te==null?void 0:te.approverType,te==null?void 0:te.search,te==null?void 0:te.slaCompliance,!0);g({total:$.totalRequests||0,pending:$.openRequests||0,paused:$.pausedRequests||0,approved:$.approvedRequests||0,rejected:$.rejectedRequests||0,draft:$.draftRequests||0,closed:$.closedRequests||0})}catch($){console.error("Failed to fetch backend stats:",$)}},[]),E=p.useCallback(async()=>{try{v(!0);const W=await Dt.getDepartments();f(W)}catch{}finally{v(!1)}},[]),P=p.useRef(s),B=p.useRef(j),k=p.useRef(i);p.useEffect(()=>{P.current=s,B.current=j,k.current=i},[s,j,i]);const L=p.useCallback(async(W=1)=>{try{W===1&&(m(!0),c([]));const G=k.current(),re=await Ck({page:W,itemsPerPage:_,filters:G});c(re.data),s.setCurrentPage(re.pagination.page),w(re.pagination.totalPages),N(re.pagination.total)}catch{c([])}finally{m(!1)}},[_,s]),V=p.useCallback(async()=>{try{x(!0);const W=i(),G=await Sk(W);await Kg(G,W)}catch(W){console.error("Failed to export requests:",W),alert("Failed to export requests. Please try again.")}finally{x(!1)}},[i]);p.useEffect(()=>{E()},[E]),p.useEffect(()=>{const W=setTimeout(()=>{const G={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};n||(s.priorityFilter!=="all"&&(G.priority=s.priorityFilter),s.templateTypeFilter!=="all"&&(G.templateType=s.templateTypeFilter),s.departmentFilter!=="all"&&(G.department=s.departmentFilter),s.slaComplianceFilter!=="all"&&(G.slaCompliance=s.slaComplianceFilter));const re=s.dateRange==="all"?"all":s.dateRange||"month";B.current(re,s.customStartDate,s.customEndDate,G)},s.searchTerm?500:0);return()=>clearTimeout(W)},[s.searchTerm,s.priorityFilter,s.slaComplianceFilter,s.departmentFilter,s.initiatorFilter,s.approverFilter,s.approverFilterType,s.dateRange,s.customStartDate,s.customEndDate,s.templateTypeFilter,n]);const D=p.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}),S=p.useRef(!1);p.useEffect(()=>{const W=s.currentPage||1;L(W),S.current=!0},[]),p.useEffect(()=>{if(!S.current)return;const W=D.current;if(!(W.searchTerm!==s.searchTerm||W.statusFilter!==s.statusFilter||W.priorityFilter!==s.priorityFilter||W.templateTypeFilter!==s.templateTypeFilter||W.slaComplianceFilter!==s.slaComplianceFilter||W.departmentFilter!==s.departmentFilter||W.initiatorFilter!==s.initiatorFilter||W.approverFilter!==s.approverFilter||W.approverFilterType!==s.approverFilterType||W.dateRange!==s.dateRange||W.customStartDate!==s.customStartDate||W.customEndDate!==s.customEndDate))return;const re=setTimeout(()=>{s.setCurrentPage(1),L(1),D.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!==W.searchTerm?500:0);return()=>clearTimeout(re)},[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 O=p.useCallback(W=>{W>=1&&W<=C&&(s.setCurrentPage(W),L(W))},[C,L,s]),I=p.useMemo(()=>zg(o),[o]),M=p.useMemo(()=>{if(u)return{total:u.total||0,pending:u.pending||0,paused:u.paused||0,approved:u.approved||0,rejected:u.rejected||0,draft:u.draft||0,closed:u.closed||0};const W=I.filter(z=>{const H=(z.status||"").toString().toLowerCase();return H==="pending"||H==="in-progress"}).length,G=I.filter(z=>(z.status||"").toString().toLowerCase()==="paused").length,re=I.filter(z=>(z.status||"").toString().toLowerCase()==="approved").length,te=I.filter(z=>(z.status||"").toString().toLowerCase()==="rejected").length,$=I.filter(z=>(z.status||"").toString().toLowerCase()==="closed").length;return{total:A>0?A:I.length,pending:W,paused:G,approved:re,rejected:te,draft:0,closed:$}},[u,A,I]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"user-all-requests-page",children:[e.jsx($g,{isOrgLevel:!1,isAdmin:!1,loading:d,exporting:h,onExport:V}),e.jsx(Og,{stats:M,onStatusFilter:W=>{s.setStatusFilter(W)}}),e.jsx(r,{searchTerm:s.searchTerm,statusFilter:s.statusFilter,priorityFilter:s.priorityFilter,templateTypeFilter:s.templateTypeFilter,departmentFilter:s.departmentFilter,slaComplianceFilter:s.slaComplianceFilter,initiatorFilter:s.initiatorFilter,approverFilter:s.approverFilter,approverFilterType:s.approverFilterType,dateRange:s.dateRange,customStartDate:s.customStartDate,customEndDate:s.customEndDate,showCustomDatePicker:s.showCustomDatePicker,departments:b,loadingDepartments:y,initiatorSearch:T,approverSearch:R,onSearchChange:s.setSearchTerm,onStatusChange:s.setStatusFilter,onPriorityChange:s.setPriorityFilter,onTemplateTypeChange:s.setTemplateTypeFilter,onDepartmentChange:s.setDepartmentFilter,onSlaComplianceChange:s.setSlaComplianceFilter,onInitiatorChange:s.setInitiatorFilter,onApproverChange:s.setApproverFilter,onApproverTypeChange:s.setApproverFilterType,onDateRangeChange:s.handleDateRangeChange,onCustomStartDateChange:s.setCustomStartDate,onCustomEndDateChange:s.setCustomEndDate,onShowCustomDatePickerChange:s.setShowCustomDatePicker,onApplyCustomDate:s.handleApplyCustomDate,onClearFilters:s.clearFilters,hasActiveFilters:l()}),e.jsx(Ug,{requests:I,loading:d,hasActiveFilters:s.hasActiveFilters,onViewRequest:t}),e.jsx(jr,{currentPage:s.currentPage||1,totalPages:C,totalRecords:A,itemsPerPage:_,onPageChange:O,loading:d,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}function Tk(){const t=Fs();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(se,{children:e.jsxs(ae,{className:"p-8 text-center",children:[e.jsx(Ye,{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(F,{onClick:()=>t(-1),className:"mt-4","data-testid":"back-button",children:[e.jsx(Cs,{className:"w-4 h-4 mr-2"}),"Back"]})]})})})})}function kk({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(ps,{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(F,{variant:"outline",size:"sm",onClick:a,disabled:s,className:"gap-2","data-testid":"refresh-button",children:[e.jsx(Ut,{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(se,{children:[e.jsx(ge,{className:"pb-3",children:e.jsx(fe,{className:"text-sm font-medium text-gray-600",children:"TAT Compliance"})}),e.jsxs(ae,{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(oa,{value:s,className:"mt-2 h-2"})]})]}),e.jsxs(se,{children:[e.jsx(ge,{className:"pb-3",children:e.jsx(fe,{className:"text-sm font-medium text-gray-600",children:"Total Approved"})}),e.jsxs(ae,{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(Re,{className:"w-5 h-5 text-blue-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Requests handled"})]})]}),e.jsxs(se,{children:[e.jsx(ge,{className:"pb-3",children:e.jsx(fe,{className:"text-sm font-medium text-gray-600",children:"Avg Response Time"})}),e.jsxs(ae,{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(vo,{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(se,{children:[e.jsx(ge,{className:"pb-3",children:e.jsx(fe,{className:"text-sm font-medium text-gray-600",children:"Pending Actions"})}),e.jsxs(ae,{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(nt,{className:"w-5 h-5 text-orange-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Awaiting approval"})]})]})]})}function Dk({approverName:t,approverStats:s,dateRange:a="all",customStartDate:r,customEndDate:n}){return e.jsxs(se,{"data-testid":"approver-actions-stats",children:[e.jsxs(ge,{children:[e.jsx(fe,{children:"Approver's Actions"}),e.jsxs(Ue,{children:["Statistics for all requests by ",t," ",a&&a!=="all"?Jj(a,r,n,""):"(all time)"]})]}),e.jsxs(ae,{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(ps,{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(Re,{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(Ct,{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(nt,{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(yo,{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(ke,{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(Kf,{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(Ye,{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(Fl,{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 Pk({searchTerm:t,statusFilter:s,priorityFilter:a,slaComplianceFilter:r,dateRange:n,customStartDate:i,customEndDate:l,showCustomDatePicker:o,tempCustomStartDate:c,tempCustomEndDate:d,onSearchChange:m,onStatusChange:h,onPriorityChange:x,onSlaComplianceChange:u,onDateRangeChange:g,onShowCustomDatePickerChange:b,onTempStartDateChange:f,onTempEndDateChange:y,onApplyCustomDate:v,onClearFilters:C}){return e.jsxs(se,{"data-testid":"approver-performance-filters",children:[e.jsx(ge,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(fe,{children:"Filters"}),e.jsx(F,{variant:"ghost",size:"sm",onClick:C,className:"text-xs","data-testid":"clear-filters-button",children:"Clear All"})]})}),e.jsx(ae,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-6 gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Es,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(Ie,{placeholder:"Search requests...",value:t,onChange:w=>m(w.target.value),className:"pl-10","data-testid":"search-input"})]}),e.jsxs(Ke,{value:s,onValueChange:h,children:[e.jsx(Ze,{"data-testid":"status-filter",children:e.jsx(Xe,{placeholder:"Status"})}),e.jsxs(Je,{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(Ke,{value:a,onValueChange:x,children:[e.jsx(Ze,{"data-testid":"priority-filter",children:e.jsx(Xe,{placeholder:"Priority"})}),e.jsxs(Je,{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(Ke,{value:r,onValueChange:u,children:[e.jsx(Ze,{"data-testid":"sla-compliance-filter",children:e.jsx(Xe,{placeholder:"SLA Compliance"})}),e.jsxs(Je,{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(xt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ke,{value:n,onValueChange:g,children:[e.jsx(Ze,{className:"flex-1","data-testid":"date-range-filter",children:e.jsx(Xe,{placeholder:"Date Range"})}),e.jsxs(Je,{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(Xs,{open:o,onOpenChange:b,children:[e.jsx(Zs,{asChild:!0,children:e.jsxs(F,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(xt,{className:"w-4 h-4"}),c&&d?`${Ge(c,"MMM d")} - ${Ge(d,"MMM d")}`:"Select dates"]})}),e.jsx(Js,{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(ne,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(Ie,{id:"start-date",type:"date",value:c?Ge(c,"yyyy-MM-dd"):"",onChange:w=>{const A=w.target.value?new Date(w.target.value):void 0;A?(f(A),d&&A>d&&y(A)):f(void 0)},max:Ge(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(Ie,{id:"end-date",type:"date",value:d?Ge(d,"yyyy-MM-dd"):"",onChange:w=>{const A=w.target.value?new Date(w.target.value):void 0;A?(y(A),c&&A<c&&f(A)):y(void 0)},min:c?Ge(c,"yyyy-MM-dd"):void 0,max:Ge(new Date,"yyyy-MM-dd"),className:"w-full"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(F,{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(F,{size:"sm",variant:"outline",onClick:()=>{b(!1),f(i),y(l),(!i||!l)&&g("all")},"data-testid":"cancel-date-button",children:"Cancel"})]})]})})]})]})]})})]})}const Ik=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:na,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"}}},Ek=t=>{switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:Re,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ct,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:nt,iconColor:"text-yellow-600"};case"in-progress":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:nt,iconColor:"text-blue-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Re,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:ke,iconColor:"text-gray-600"}}},Fk=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 _k(t){if(!t)return"N/A";try{return Ge(new Date(t),"MMM d, yyyy")}catch{return"N/A"}}function Lk(t){if(!t)return"N/A";try{return Ge(new Date(t),"MMM d, yyyy HH:mm")}catch{return"N/A"}}function fi(t){const{requestId:s,status:a,request:r,navigate:n}=t;if((a==null?void 0:a.toLowerCase())==="draft"||a==="DRAFT"){n(`/edit-request/${s}`);return}const l=k5(s);n(l)}function Mk({requests:t,loading:s,approverName:a,currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:l,onPageChange:o}){const c=Fs();return e.jsxs(se,{"data-testid":"approver-performance-request-list",children:[e.jsxs(ge,{children:[e.jsx(fe,{children:"Request Details"}),e.jsxs(Ue,{children:["All requests handled by ",a," with applied filters"]})]}),e.jsxs(ae,{children:[s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"loading-state",children:[e.jsx(Ut,{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(ke,{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=Ik(d.priority),h=Ek(d.status),x=Fk(d.slaStatus||""),u=m.icon,g=h.icon;return e.jsx(se,{className:"hover:shadow-md transition-shadow cursor-pointer",onClick:()=>{fi({requestId:d.requestId,requestTitle:d.title,status:d.status,request:d,navigate:c})},"data-testid":`request-card-${d.requestId}`,children:e.jsx(ae,{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(oe,{className:m.color,"data-testid":"priority-badge",children:[e.jsx(u,{className:`w-3 h-3 mr-1 ${m.iconColor}`}),d.priority]}),e.jsxs(oe,{className:h.color,"data-testid":"status-badge",children:[e.jsx(g,{className:`w-3 h-3 mr-1 ${h.iconColor}`}),d.status]}),d.approvalStatus&&e.jsx(oe,{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(Re,{className:"w-3 h-3 mr-1"}),"Approved"]}):d.approvalStatus==="rejected"||d.approvalStatus==="REJECTED"?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"w-3 h-3 mr-1"}),"Rejected"]}):e.jsxs(e.Fragment,{children:[e.jsx(nt,{className:"w-3 h-3 mr-1"}),"Pending"]})}),d.slaStatus&&e.jsx(oe,{className:x.color,"data-testid":"sla-status-badge",children:x.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(Gt,{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(nt,{className:"w-3 h-3"}),"Submitted: ",_k(d.submissionDate)]}),d.approvalActionDate&&e.jsxs("span",{className:"flex items-center gap-1","data-testid":"action-date",children:[e.jsx(Re,{className:"w-3 h-3"}),"Action: ",Lk(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(vo,{className:"w-3 h-3"}),Mt(d.levelElapsedHours)," / ",Mt(d.levelTatHours||0)," TAT"]})]})]}),e.jsx(F,{variant:"ghost",size:"sm",onClick:b=>{b.stopPropagation(),fi({requestId:d.requestId,requestTitle:d.title,status:d.status,request:d,navigate:c})},"data-testid":"view-request-button",children:e.jsx(ls,{className:"w-4 h-4"})})]})})},d.requestId)})}),n>0&&e.jsx("div",{className:"mt-6","data-testid":"pagination-container",children:e.jsx(jr,{currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:l,onPageChange:o,itemLabel:"requests",testIdPrefix:"approver-performance"})})]})]})}function $k(){const[t]=Ox(),[s,a]=p.useState(""),[r,n]=p.useState(t.get("status")||"all"),[i,l]=p.useState(t.get("priority")||"all"),[o,c]=p.useState(t.get("slaCompliance")||"all"),[d,m]=p.useState(t.get("dateRange")||"all"),[h,x]=p.useState(t.get("startDate")?new Date(t.get("startDate")):void 0),[u,g]=p.useState(t.get("endDate")?new Date(t.get("endDate")):void 0),[b,f]=p.useState(!1),[y,v]=p.useState(void 0),[C,w]=p.useState(void 0),A=p.useCallback(()=>{a(""),n("all"),l("all"),c("all"),m("all"),x(void 0),g(void 0),v(void 0),w(void 0),f(!1)},[]),N=p.useCallback(T=>{const R=T;m(R),R!=="custom"?(x(void 0),g(void 0),v(void 0),w(void 0),f(!1)):(v(h),w(u),f(!0))},[h,u]),_=p.useCallback(()=>{if(y&&C){if(y>C){const T=y;x(C),g(T),v(C),w(T)}else x(y),g(C);f(!1)}},[y,C]);return{searchTerm:s,statusFilter:r,priorityFilter:i,slaComplianceFilter:o,dateRange:d,customStartDate:h,customEndDate:u,showCustomDatePicker:b,tempCustomStartDate:y,tempCustomEndDate:C,setSearchTerm:a,setStatusFilter:n,setPriorityFilter:l,setSlaComplianceFilter:c,setDateRange:m,setCustomStartDate:x,setCustomEndDate:g,setShowCustomDatePicker:f,setTempCustomStartDate:v,setTempCustomEndDate:w,clearFilters:A,handleDateRangeChange:N,handleApplyCustomDate:_}}function Ok({approverId:t,dateRange:s,customStartDate:a,customEndDate:r,statusFilter:n,priorityFilter:i,slaComplianceFilter:l,searchTerm:o,itemsPerPage:c}){const[d,m]=p.useState([]),[h,x]=p.useState(null),[u,g]=p.useState([]),[b,f]=p.useState(!0),[y,v]=p.useState(!1),[C,w]=p.useState(1),[A,N]=p.useState(1),[_,T]=p.useState(0),R=p.useRef(!0),j=p.useCallback(async()=>{if(t)try{const k=s==="all"?void 0:s,L=await Dt.getSingleApproverStats(t,k,a,r,i!=="all"?i:void 0,l!=="all"?l:void 0);x(L)}catch(k){console.error("[ApproverPerformance] Failed to fetch approver stats:",k),x(null)}},[t,s,a,r,i,l]),E=p.useCallback(async(k=1)=>{if(!t){f(!1);return}try{f(!0);const L=await Dt.getRequestsByApprover(t,k,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(L.requests),T(L.pagination.totalRecords),N(L.pagination.totalPages),w(L.pagination.currentPage),g(L.requests)}catch(L){console.error("Failed to fetch requests:",L)}finally{f(!1),v(!1)}},[t,s,a,r,n,i,l,o,c]);p.useEffect(()=>{R.current&&(R.current=!1,j(),E(1))},[]),p.useEffect(()=>{R.current||j()},[s,a,r,i,l]),p.useEffect(()=>{R.current||E(1)},[s,a,r,n,i,l,o]);const P=p.useCallback(()=>{v(!0),j(),E(1)},[j,E]),B=p.useCallback(k=>{E(k)},[E]);return{requests:d,approverStats:h,allFilteredRequests:u,loading:b,refreshing:y,currentPage:C,totalPages:A,totalRecords:_,handleRefresh:P,handlePageChange:B}}const ex=10;function Uk(){const[t]=Ox(),s=t.get("approverId")||"",a=t.get("approverName")||"Unknown Approver",r=$k(),n=Ok({approverId:s,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,slaComplianceFilter:r.slaComplianceFilter,searchTerm:r.searchTerm,itemsPerPage:ex});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(kk,{approverName:a,refreshing:n.refreshing,onRefresh:n.handleRefresh}),n.approverStats&&e.jsx(Rk,{approverStats:n.approverStats}),n.approverStats&&e.jsx(Dk,{approverName:a,approverStats:n.approverStats,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate}),e.jsx(Pk,{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(Mk,{requests:n.requests,loading:n.loading,approverName:a,currentPage:n.currentPage,totalPages:n.totalPages,totalRecords:n.totalRecords,itemsPerPage:ex,onPageChange:n.handlePageChange})]}):e.jsx(Tk,{})}function Bk(){const{user:t}=Jt(),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(se,{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(ae,{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(ts,{className:"h-24 w-24 ring-4 ring-white/20 shadow-xl",children:[e.jsx(Ii,{src:(t==null?void 0:t.picture)||""}),e.jsx(ss,{className:"bg-yellow-400 text-slate-900 text-2xl font-bold",children:s()})]}),cr(t)&&e.jsx("div",{className:"absolute -bottom-2 -right-2 bg-yellow-400 rounded-full p-1.5 shadow-lg",children:e.jsx(Ns,{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:[cr(t)&&e.jsxs(oe,{className:"bg-yellow-400 text-slate-900 hover:bg-yellow-400 font-semibold",children:[e.jsx(Ns,{className:"w-3 h-3 mr-1"}),"Administrator"]}),tn(t)&&e.jsxs(oe,{className:"bg-blue-400 text-slate-900 hover:bg-blue-400 font-semibold",children:[e.jsx(ps,{className:"w-3 h-3 mr-1"}),"Management"]}),(t==null?void 0:t.employeeId)&&e.jsxs(oe,{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(se,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(ge,{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(Gt,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg text-gray-900",children:"Personal Information"}),e.jsx(Ue,{className:"text-gray-600",children:"Your personal details"})]})]})}),e.jsx(ae,{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(Da,{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(Gt,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"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(Gt,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"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(Gt,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"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(Ni,{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(se,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(ge,{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(nm,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg text-gray-900",children:"Professional Information"}),e.jsx(Ue,{className:"text-gray-600",children:"Work-related details"})]})]})}),e.jsx(ae,{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(Gt,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"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(xo,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"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(nm,{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(Ns,{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(oe,{variant:cr(t)||tn(t)?"default":"secondary",className:cr(t)?"bg-yellow-400 text-slate-900":tn(t)?"bg-blue-400 text-slate-900":"",children:cr(t)?"Administrator":tn(t)?"Management":"User"}),(cr(t)||tn(t))&&e.jsx(Re,{className:"w-4 h-4 text-green-600"})]})]})]})]})})]})]}),e.jsxs(se,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(ge,{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(xt,{className:"h-5 w-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg text-gray-900",children:"Account Status"}),e.jsx(Ue,{className:"text-gray-600",children:"Account information and activity"})]})]})}),e.jsx(ae,{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(Re,{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(oe,{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 Gn="BBb78N3tSTEw6mPbBmvEDX2bhYEDKPc_zffL-vxPV8FBSmR1qSpy9gdV8zt-WFF-q2NPpVmL4BhbUzLSHVAPjcI",Vk="https://reflow-uat.royalenfield.com";function kl(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 zk(){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 Hk(t){if(Gn.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:kl(Gn)})}else try{s=await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:kl(Gn)})}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:kl(Gn)})}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(`${Vk}/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 Gk(){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 zk()}catch(a){throw new Error(`Service worker registration failed: ${(a==null?void 0:a.message)||"Unknown error"}`)}try{await Hk(s)}catch(a){throw a}}function Wk({className:t,defaultValue:s,value:a,min:r=0,max:n=100,...i}){const l=p.useMemo(()=>Array.isArray(a)?a:Array.isArray(s)?s:[r,n],[a,s,r,n]);return e.jsxs(ef,{"data-slot":"slider",defaultValue:s,value:a,min:r,max:n,className:Ae("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(tf,{"data-slot":"slider-track",className:Ae("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(sf,{"data-slot":"slider-range",className:Ae("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full")})}),Array.from({length:l.length},(o,c)=>e.jsx(af,{"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 Yk({onConfigUpdate:t}){const[s,a]=p.useState([]),[r,n]=p.useState(!0),[i,l]=p.useState(null),[o,c]=p.useState(null),[d,m]=p.useState({}),[h,x]=p.useState(null);p.useEffect(()=>{u()},[]);const u=async()=>{var j,E;try{n(!0),c(null);const P=await NS();a(P)}catch(P){c(((E=(j=P.response)==null?void 0:j.data)==null?void 0:E.error)||"Failed to load configurations")}finally{n(!1)}},g=async j=>{var E,P;try{l(j.configKey),c(null);const B=d[j.configKey]??j.configValue;if(j.validationRules){const k=parseFloat(B);if(j.valueType==="NUMBER"){if(j.validationRules.min!==void 0&&k<j.validationRules.min)throw new Error(`Value must be at least ${j.validationRules.min}`);if(j.validationRules.max!==void 0&&k>j.validationRules.max)throw new Error(`Value must be at most ${j.validationRules.max}`)}}await wS(j.configKey,B),a(k=>k.map(L=>L.configKey===j.configKey?{...L,configValue:B}:L)),m(k=>{const L={...k};return delete L[j.configKey],L}),x(`${j.displayName} updated successfully`),setTimeout(()=>x(null),3e3),t&&t()}catch(B){c(B.message||((P=(E=B.response)==null?void 0:E.data)==null?void 0:P.error)||"Failed to save configuration")}finally{l(null)}},b=async j=>{var E,P;if(confirm(`Reset "${j.displayName}" to default value?`))try{l(j.configKey),c(null),await CS(j.configKey),a(B=>B.map(k=>k.configKey===j.configKey?{...k,configValue:k.defaultValue||""}:k)),m(B=>{const k={...B};return delete k[j.configKey],k}),x(`${j.displayName} reset to default`),setTimeout(()=>x(null),3e3)}catch(B){c(((P=(E=B.response)==null?void 0:E.data)==null?void 0:P.error)||"Failed to reset configuration")}finally{l(null)}},f=(j,E)=>{m(P=>({...P,[j]:E}))},y=j=>d[j.configKey]??j.configValue,v=j=>d[j.configKey]!==void 0&&d[j.configKey]!==j.configValue,C=j=>{var B,k,L,V;const E=y(j),P=i===j.configKey;if(!j.isEditable)return e.jsxs("div",{className:"p-3 bg-slate-100 border border-slate-200 rounded-md",children:[e.jsx("p",{className:"text-sm text-slate-700 font-mono",children:j.configValue}),e.jsxs("p",{className:"text-xs text-slate-500 mt-1.5 flex items-center gap-1",children:[e.jsx(Ye,{className:"w-3 h-3"}),"This setting cannot be modified"]})]});switch(j.uiComponent||j.valueType.toLowerCase()){case"toggle":return e.jsxs("div",{className:"flex items-center justify-between p-3 bg-slate-50 border border-slate-200 rounded-md hover:bg-slate-100 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`w-2 h-2 rounded-full ${E==="true"?"bg-green-500":"bg-slate-400"}`}),e.jsx("span",{className:`text-sm font-medium ${E==="true"?"text-green-700":"text-slate-600"}`,children:E==="true"?"Enabled":"Disabled"})]}),e.jsx(mn,{checked:E==="true",onCheckedChange:I=>f(j.configKey,I?"true":"false"),disabled:P})]});case"slider":const D=parseInt(E)||0,S=((B=j.validationRules)==null?void 0:B.min)||0,O=((k=j.validationRules)==null?void 0:k.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:[D,"%"]}),e.jsxs("span",{className:"text-xs text-slate-500 bg-slate-100 px-2 py-1 rounded-sm border border-slate-200",children:["Range: ",S,"-",O]})]}),e.jsx(Wk,{value:[D],min:S,max:O,step:1,onValueChange:([I])=>{I!==void 0&&f(j.configKey,I.toString())},disabled:P,className:"w-full"})]});case"number":return e.jsx(Ie,{type:"number",value:E,onChange:I=>f(j.configKey,I.target.value),disabled:P,min:(L=j.validationRules)==null?void 0:L.min,max:(V=j.validationRules)==null?void 0:V.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(Ie,{type:"text",value:E,onChange:I=>f(j.configKey,I.target.value),disabled:P,className:"font-mono border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 rounded-md transition-all shadow-sm"})}},w=j=>{switch(j){case"TAT_SETTINGS":return e.jsx(nt,{className:"w-5 h-5"});case"DOCUMENT_POLICY":return e.jsx(ke,{className:"w-5 h-5"});case"NOTIFICATION_RULES":return e.jsx(aa,{className:"w-5 h-5"});case"AI_CONFIGURATION":return e.jsx(Tx,{className:"w-5 h-5"});case"WORKFLOW_SHARING":return e.jsx(Sn,{className:"w-5 h-5"});default:return e.jsx(Ya,{className:"w-5 h-5"})}},A=["DASHBOARD_LAYOUT"],N=["ALLOW_EXTERNAL_SHARING","NOTIFICATION_BATCH_DELAY_MS","AI_REMARK_MAX_CHARACTERS"],_=s.filter(j=>!A.includes(j.configCategory)&&!N.includes(j.configKey)),T=_.reduce((j,E)=>(j[E.configCategory]||(j[E.configCategory]=[]),j[E.configCategory].push(E),j),{});if(Object.keys(T).forEach(j=>{const E=T[j];E&&E.sort((P,B)=>P.sortOrder-B.sortOrder)}),r)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(it,{className:"w-8 h-8 animate-spin text-gray-400"})});if(_.length===0)return e.jsx(se,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(ae,{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(Ya,{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(T);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(Re,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-green-900",children:h})]}),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(Ye,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:o}),e.jsx(F,{size:"sm",variant:"ghost",onClick:()=>c(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsxs(Ui,{defaultValue:R[0],className:"w-full",children:[e.jsx(Bi,{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(j=>e.jsx(rs,{value:j,className:"flex-1 min-w-[120px] text-[10px] xs:text-xs sm:text-sm font-medium py-2 sm:py-2.5 px-2 sm:px-3 rounded-sm data-[state=active]:bg-white data-[state=active]:shadow-sm data-[state=active]:text-slate-900 transition-all",children:e.jsx("span",{className:"truncate block",children:j.replace(/_/g," ")})},j))}),R.map(j=>{var E,P,B;return e.jsx(ns,{value:j,className:"space-y-4 mt-6",children:e.jsxs(se,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ge,{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:w(j)})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg font-semibold text-slate-900",children:j.replace(/_/g," ")}),e.jsxs(Ue,{className:"text-sm",children:[((E=T[j])==null?void 0:E.length)||0," setting",(((P=T[j])==null?void 0:P.length)||0)!==1?"s":""," available"]})]})]})}),e.jsx(ae,{className:"space-y-6",children:(B=T[j])==null?void 0:B.map(k=>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(ne,{className:"text-sm font-semibold text-slate-900",children:k.displayName}),v(k)&&e.jsx(oe,{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"}),k.requiresRestart&&e.jsx(oe,{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"})]}),k.description&&e.jsx("p",{className:"text-xs text-slate-600 mt-1 leading-relaxed",children:k.description}),k.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:k.defaultValue})]})]})}),C(k),k.isEditable&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(F,{size:"sm",onClick:()=>g(k),disabled:!v(k)||i===k.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===k.configKey?e.jsxs(e.Fragment,{children:[e.jsx(it,{className:"w-4 h-4 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Mx,{className:"w-4 h-4"}),"Save Changes"]})}),k.defaultValue&&e.jsxs(F,{size:"sm",variant:"outline",onClick:()=>b(k),disabled:i===k.configKey,className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(Xf,{className:"w-4 h-4"}),"Reset to Default"]})]})]},k.configKey))})]})},j)})]})]})}function Kk(){const[t,s]=p.useState([]),[a,r]=p.useState(!0),[n,i]=p.useState(new Date().getFullYear()),[l,o]=p.useState(!1),[c,d]=p.useState(null),[m,h]=p.useState(null),[x,u]=p.useState(null),[g,b]=p.useState({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1});p.useEffect(()=>{f()},[n]);const f=async()=>{var j,E;try{r(!0),h(null);const P=await SS(n);s(P)}catch(P){h(((E=(j=P.response)==null?void 0:j.data)==null?void 0:E.error)||"Failed to load holidays")}finally{r(!1)}},y=()=>{b({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1}),d(null),o(!0)},v=j=>{b({holidayDate:j.holidayDate,holidayName:j.holidayName,description:j.description||"",holidayType:j.holidayType,isRecurring:j.isRecurring}),d(j),o(!0)},C=()=>{if(c)return;const j=new Date;return j.setDate(j.getDate()+1),j.toISOString().split("T")[0]},w=async()=>{var j,E;try{if(h(null),!g.holidayDate||!g.holidayName){h("Holiday date and name are required");return}c?(await TS(c.holidayId,g),u("Holiday updated successfully")):(await AS(g),u("Holiday created successfully")),await f(),o(!1),setTimeout(()=>u(null),3e3)}catch(P){h(((E=(j=P.response)==null?void 0:j.data)==null?void 0:E.error)||"Failed to save holiday")}},A=async j=>{var E,P;if(confirm(`Delete "${j.holidayName}"?`))try{h(null),await kS(j.holidayId),u("Holiday deleted successfully"),await f(),setTimeout(()=>u(null),3e3)}catch(B){h(((P=(E=B.response)==null?void 0:E.data)==null?void 0:P.error)||"Failed to delete holiday")}},N=j=>{switch(j){case"NATIONAL":return"bg-gradient-to-r from-red-50 to-rose-50 text-red-800 border-red-300";case"REGIONAL":return"bg-gradient-to-r from-blue-50 to-cyan-50 text-blue-800 border-blue-300";case"ORGANIZATIONAL":return"bg-gradient-to-r from-purple-50 to-violet-50 text-purple-800 border-purple-300";case"OPTIONAL":return"bg-gradient-to-r from-slate-50 to-gray-50 text-slate-700 border-slate-300"}},_=Array.from({length:5},(j,E)=>new Date().getFullYear()-1+E),T=t.reduce((j,E)=>{const P=new Date(E.holidayDate).toLocaleString("default",{month:"long"});return j[P]||(j[P]=[]),j[P].push(E),j},{}),R=Object.keys(T).sort((j,E)=>{const P=new Date(Date.parse(j+" 1, 2000")).getMonth(),B=new Date(Date.parse(E+" 1, 2000")).getMonth();return P-B});return e.jsxs("div",{className:"space-y-6",children:[x&&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(Re,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-green-900",children:x})]}),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(Ye,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:m}),e.jsx(F,{size:"sm",variant:"ghost",onClick:()=>h(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsx(se,{className:"shadow-lg border-0 rounded-md",children:e.jsx(ge,{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(xt,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Holiday Calendar"}),e.jsx(Ue,{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(Ke,{value:n.toString(),onValueChange:j=>i(parseInt(j)),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(Xe,{})}),e.jsx(Je,{className:"rounded-md",children:_.map(j=>e.jsx(Y,{value:j.toString(),children:j},j))})]}),e.jsxs(F,{onClick:y,className:"gap-2 bg-re-green hover:bg-re-green/90 text-white shadow-sm flex-1 sm:flex-initial",children:[e.jsx(gs,{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(it,{className:"w-8 h-8 animate-spin text-gray-400"})}):t.length===0?e.jsx(se,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(ae,{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(xt,{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(F,{onClick:y,variant:"outline",className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(gs,{className:"w-4 h-4"}),"Add First Holiday"]})]})}):e.jsx("div",{className:"space-y-4 sm:space-y-6",children:R.map(j=>{var E,P,B;return e.jsxs(se,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ge,{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(fe,{className:"text-base sm:text-lg font-semibold text-slate-900",children:[j," ",n]}),e.jsxs(Ue,{className:"text-xs sm:text-sm",children:[((E=T[j])==null?void 0:E.length)||0," holiday",(((P=T[j])==null?void 0:P.length)||0)!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-blue-50 rounded-md",children:e.jsx(xt,{className:"w-4 h-4 text-blue-600"})})]})}),e.jsx(ae,{className:"space-y-3 pt-4",children:(B=T[j])==null?void 0:B.map(k=>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:k.holidayName}),e.jsx(oe,{variant:"outline",className:`${N(k.holidayType)} text-[10px] sm:text-xs font-medium shadow-sm`,children:k.holidayType}),k.isRecurring&&e.jsx(oe,{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:kh(k.holidayDate)}),k.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-1.5 line-clamp-2",children:k.description})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-2 self-end sm:self-auto",children:[e.jsxs(F,{size:"sm",variant:"ghost",onClick:()=>v(k),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(oi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]}),e.jsxs(F,{size:"sm",variant:"ghost",onClick:()=>A(k),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(Ri,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Delete"})]})]})]},k.holidayId))})]},j)})}),e.jsx(ht,{open:l,onOpenChange:o,children:e.jsxs(dt,{className:"sm:max-w-[550px] max-h-[90vh] rounded-lg flex flex-col p-0",children:[e.jsx(pt,{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(xt,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(mt,{className:"text-xl font-semibold text-slate-900",children:c?"Edit Holiday":"Add New Holiday"}),e.jsx(Pt,{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(ne,{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(Ie,{id:"date",type:"date",value:g.holidayDate,onChange:j=>b({...g,holidayDate:j.target.value}),min:C(),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:c?"Select the holiday date":"Select the holiday date (minimum: tomorrow)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{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(Ie,{id:"name",placeholder:"e.g., Diwali, Republic Day, Christmas",value:g.holidayName,onChange:j=>b({...g,holidayName:j.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Enter the official name of the holiday"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{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(Ie,{id:"description",placeholder:"Add additional details about this holiday...",value:g.description,onChange:j=>b({...g,description:j.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Optional description or notes about the holiday"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"type",className:"text-sm font-semibold text-slate-900",children:"Holiday Type"}),e.jsxs(Ke,{value:g.holidayType,onValueChange:j=>b({...g,holidayType:j}),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(Xe,{})}),e.jsxs(Je,{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:()=>b({...g,isRecurring:!g.isRecurring}),children:[e.jsx("input",{type:"checkbox",id:"recurring",checked:g.isRecurring,onChange:j=>b({...g,isRecurring:j.target.checked}),className:"mt-0.5 rounded border-slate-300 text-re-green focus:ring-2 focus:ring-re-green/20 focus:ring-offset-0 w-4 h-4 cursor-pointer"}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ne,{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(Rt,{className:"gap-3 pt-4 border-t border-slate-100 px-6 pb-6 flex-shrink-0",children:[e.jsx(F,{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(F,{onClick:w,disabled:!g.holidayDate||!g.holidayName,className:"h-11 bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx(xt,{className:"w-4 h-4 mr-2"}),c?"Update Holiday":"Add Holiday"]})]})]})})]})}function Xk(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function Zk(){const[t,s]=p.useState(""),[a,r]=p.useState([]),[n,i]=p.useState(!1),[l,o]=p.useState(null),[c,d]=p.useState("USER"),[m,h]=p.useState(!1),[x,u]=p.useState(null),[g,b]=p.useState([]),[f,y]=p.useState(!1),[v,C]=p.useState({admins:0,management:0,users:0}),[w,A]=p.useState("ELEVATED"),[N,_]=p.useState(1),[T,R]=p.useState(1),[j,E]=p.useState(0),P=10,B=p.useRef(null),k=p.useRef(null),L=p.useCallback(Xk(async $=>{var z,H,je;if(!$||!$.startsWith("@")||$.length<2){r([]),i(!1);return}i(!0);try{const le=$.slice(1),$e=((z=(await ur.searchUsers(le,20)).data)==null?void 0:z.data)||[];r($e)}catch(le){console.error("Search failed:",le),u({type:"error",text:((je=(H=le.response)==null?void 0:H.data)==null?void 0:je.message)||"Failed to search users"})}finally{i(!1)}},300),[]),V=$=>{const z=$.target.value;s(z),L(z)},D=async $=>{o($),s($.email),r([]);const z=g.find(H=>H.email.toLowerCase()===$.email.toLowerCase()||H.userId===$.userId);if(z&&z.role)d(z.role);else try{const je=(await ur.getAllUsers()).find(le=>le.email&&le.email.toLowerCase()===$.email.toLowerCase()||le.userId&&le.userId===$.userId);je&&je.role?d(je.role):d("USER")}catch(H){console.error("Failed to check user role:",H),d("USER")}},S=async()=>{var $,z;if(!l||!c){u({type:"error",text:"Please select a user and role"});return}h(!0),u(null);try{await ur.assignRole(l.email,c),u({type:"success",text:`Successfully assigned ${c} role to ${l.displayName||l.email}`}),o(null),s(""),d("USER"),await O(),await I()}catch(H){console.error("Role assignment failed:",H),u({type:"error",text:((z=($=H.response)==null?void 0:$.data)==null?void 0:z.error)||"Failed to assign role"})}finally{h(!1)}},O=async($=N)=>{var z,H,je,le,ue,$e;y(!0);try{const Te=await ur.getUsersByRole(w,$,P),Ve=((H=(z=Te.data)==null?void 0:z.data)==null?void 0:H.users)||[],Qe=(le=(je=Te.data)==null?void 0:je.data)==null?void 0:le.pagination,Fe=($e=(ue=Te.data)==null?void 0:ue.data)==null?void 0:$e.summary;b(Ve),Qe&&(_(Qe.currentPage),R(Qe.totalPages),E(Qe.totalUsers)),Fe&&C({admins:Fe.ADMIN||0,management:Fe.MANAGEMENT||0,users:Fe.USER||0})}catch(Te){console.error("Failed to fetch users:",Te)}finally{y(!1)}},I=async()=>{var $,z,H,je,le,ue;try{const $e=await ur.getRoleStatistics(),Te=((z=($=$e.data)==null?void 0:$.data)==null?void 0:z.statistics)||((H=$e.data)==null?void 0:H.statistics)||[];C({admins:parseInt(((je=Te.find(Ve=>Ve.role==="ADMIN"))==null?void 0:je.count)||"0"),management:parseInt(((le=Te.find(Ve=>Ve.role==="MANAGEMENT"))==null?void 0:le.count)||"0"),users:parseInt(((ue=Te.find(Ve=>Ve.role==="USER"))==null?void 0:ue.count)||"0")})}catch($e){console.error("Failed to fetch statistics:",$e)}};p.useEffect(()=>{O(1),I()},[w]);const M=$=>{A($),_(1)},W=$=>{O($)},G=$=>{A($),_(1),requestAnimationFrame(()=>{const z=k.current;z&&z.scrollIntoView({behavior:"smooth",block:"start"})})};p.useEffect(()=>{const $=z=>{B.current&&!B.current.contains(z.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",$),()=>{document.removeEventListener("mousedown",$)}},[a]);const re=$=>{switch($){case"ADMIN":return"bg-yellow-400 text-slate-800";case"MANAGEMENT":return"bg-blue-400 text-slate-800";default:return"bg-gray-400 text-slate-800"}},te=$=>{switch($){case"ADMIN":return e.jsx($n,{className:"w-5 h-5 text-slate-800"});case"MANAGEMENT":return e.jsx(ps,{className:"w-5 h-5 text-slate-800"});default:return e.jsx(Gt,{className:"w-5 h-5 text-slate-800"})}};return e.jsxs(se,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ge,{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(Zf,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg font-semibold text-gray-900",children:"User Role Management"}),e.jsx(Ue,{className:"text-sm text-gray-600",children:"Search for users, assign roles, and manage user permissions across the system"})]})]})}),e.jsxs(ae,{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(se,{className:`border-2 bg-gradient-to-br from-yellow-50 to-yellow-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${w==="ADMIN"?"border-yellow-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"admin-count-card",onClick:()=>G("ADMIN"),children:e.jsx(ae,{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:w==="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($n,{className:"w-6 h-6 text-slate-800"})})]})})}),e.jsx(se,{className:`border-2 bg-gradient-to-br from-blue-50 to-blue-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${w==="MANAGEMENT"?"border-blue-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"management-count-card",onClick:()=>G("MANAGEMENT"),children:e.jsx(ae,{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:w==="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(ps,{className:"w-6 h-6 text-slate-800"})})]})})}),e.jsx(se,{className:`border-2 bg-gradient-to-br from-gray-50 to-gray-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${w==="USER"?"border-gray-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"user-count-card",onClick:()=>G("USER"),children:e.jsx(ae,{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:w==="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(Gt,{className:"w-6 h-6 text-slate-800"})})]})})})]}),e.jsx(Ps,{}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-gray-900 mb-1",children:"Assign User Role"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Search for a user in Okta and assign them a role"})]}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",ref:B,children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Search User"}),e.jsxs("div",{className:"relative",children:[e.jsx(Es,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none"}),e.jsx(Ie,{type:"text",placeholder:"Type @ to search users...",value:t,onChange:V,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(it,{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:()=>D($),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(F,{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(Ke,{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(Xe,{placeholder:"Select role"})}),e.jsxs(Je,{children:[e.jsx(Y,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gt,{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(ps,{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($n,{className:"w-4 h-4 text-yellow-600"}),e.jsx("span",{children:"Administrator - Full access"})]})})]})]})]}),e.jsx(F,{onClick:S,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(it,{className:"w-4 h-4 mr-2 animate-spin"}),"Assigning Role..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ns,{className:"w-4 h-4 mr-2"}),"Assign Role"]})}),x&&e.jsx("div",{className:`border-2 rounded-lg p-4 ${x.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:[x.type==="success"?e.jsx(Re,{className:"w-5 h-5 text-green-600 shrink-0 mt-0.5"}):e.jsx(Ye,{className:"w-5 h-5 text-red-600 shrink-0 mt-0.5"}),e.jsx("p",{className:`text-sm ${x.type==="success"?"text-green-800":"text-red-800"}`,children:x.text})]})})]})]}),e.jsx(Ps,{}),e.jsxs("div",{ref:k,children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-gray-900 mb-1",children:"User Management"}),e.jsxs("p",{className:"text-sm text-gray-600",children:["View and manage user roles (",j," ",w!=="ALL"&&w!=="ELEVATED"?w.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(Ke,{value:w,onValueChange:M,children:[e.jsx(Ze,{className:"w-[200px] h-10 border rounded-lg border-gray-300",children:e.jsx(Xe,{placeholder:"Filter by role"})}),e.jsxs(Je,{children:[e.jsx(Y,{value:"ELEVATED",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ns,{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($n,{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(ps,{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(Gt,{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(ps,{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:f?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsx(it,{className:"w-6 h-6 animate-spin text-purple-500 mb-2"}),e.jsx("p",{className:"text-sm text-gray-500",children:"Loading users..."})]}):g.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-gray-100 flex items-center justify-center mx-auto mb-3",children:e.jsx(ps,{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:w==="ELEVATED"?"Assign ADMIN or MANAGEMENT roles to see users here":"No users match the selected filter"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-2","data-testid":"users-list",children:g.map($=>e.jsx("div",{className:"border border-gray-200 hover:border-re-green hover:shadow-sm transition-all rounded-lg bg-white p-4","data-testid":`user-${$.email}`,children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx("div",{className:`w-10 h-10 rounded-lg ${re($.role)} flex items-center justify-center shadow-sm`,children:te($.role)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-semibold text-gray-900 truncate",children:$.displayName}),e.jsx("p",{className:"text-sm text-gray-600 truncate",children:$.email}),$.department&&e.jsxs("p",{className:"text-xs text-gray-500 mt-1 truncate",children:[$.department,$.designation?` • ${$.designation}`:""]})]})]}),e.jsx(oe,{className:`${re($.role)} shrink-0`,"data-testid":`role-badge-${$.role}`,children:$.role})]})},$.userId))}),T>1&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("div",{className:"text-sm text-gray-600",children:["Showing ",(N-1)*P+1," to ",Math.min(N*P,j)," of ",j," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(F,{variant:"outline",size:"sm",onClick:()=>W(N-1),disabled:N===1,"data-testid":"prev-page-button",children:"Previous"}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,T)},($,z)=>{let H;return T<=5||N<=3?H=z+1:N>=T-2?H=T-4+z:H=N-2+z,e.jsx(F,{variant:N===H?"default":"outline",size:"sm",onClick:()=>W(H),className:`w-9 h-9 p-0 ${N===H?"bg-re-green hover:bg-re-green/90 text-white":""}`,"data-testid":`page-${H}-button`,children:H},H)})}),e.jsx(F,{variant:"outline",size:"sm",onClick:()=>W(N+1),disabled:N===T,"data-testid":"next-page-button",children:"Next"})]})]})]})})]})]})]})}function Jk(){const[t,s]=p.useState([]),[a,r]=p.useState(!0),[n,i]=p.useState(!1),[l,o]=p.useState(null),[c,d]=p.useState(null),[m,h]=p.useState(null),[x,u]=p.useState({title:"",itemCode:"",taxationType:"",sapRefNo:""});p.useEffect(()=>{g()},[]);const g=async()=>{var A,N;try{r(!0),d(null);const _=await DS(!1);s(_)}catch(_){const T=((N=(A=_.response)==null?void 0:A.data)==null?void 0:N.error)||"Failed to load activity types";d(T),K.error(T)}finally{r(!1)}},b=()=>{u({title:"",itemCode:"",taxationType:"",sapRefNo:""}),o(null),i(!0)},f=A=>{u({title:A.title,itemCode:A.itemCode||"",taxationType:A.taxationType||"",sapRefNo:A.sapRefNo||""}),o(A),i(!0)},y=async()=>{var A,N;try{if(d(null),!x.title.trim()||!x.taxationType.trim()||!x.sapRefNo.trim()){d("Title, Taxation Type, and Claim Document Type (SAP Ref) are required"),K.error("Please fill in all mandatory fields");return}const _={title:x.title.trim(),itemCode:x.itemCode.trim()||null,taxationType:x.taxationType.trim(),sapRefNo:x.sapRefNo.trim()};l?(await IS(l.activityTypeId,_),h("Activity type updated successfully"),K.success("Activity type updated successfully")):(await PS(_),h("Activity type created successfully"),K.success("Activity type created successfully")),await g(),i(!1),setTimeout(()=>h(null),3e3)}catch(_){const T=((N=(A=_.response)==null?void 0:A.data)==null?void 0:N.error)||"Failed to save activity type";d(T),K.error(T)}},v=async A=>{var N,_;if(confirm(`Delete "${A.title}"? This will deactivate the activity type.`))try{d(null),await ES(A.activityTypeId),h("Activity type deleted successfully"),K.success("Activity type deleted successfully"),await g(),setTimeout(()=>h(null),3e3)}catch(T){const R=((_=(N=T.response)==null?void 0:N.data)==null?void 0:_.error)||"Failed to delete activity type";d(R),K.error(R)}},C=t.filter(A=>A.isActive!==!1&&A.isActive!==void 0),w=t.filter(A=>A.isActive===!1);return e.jsxs("div",{className:"space-y-6",children:[m&&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(Re,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-green-900",children:m})]}),c&&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(Ye,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:c}),e.jsx(F,{size:"sm",variant:"ghost",onClick:()=>d(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsx(se,{className:"shadow-lg border-0 rounded-md",children:e.jsx(ge,{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(ke,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Activity Types"}),e.jsx(Ue,{className:"text-sm",children:"Manage dealer claim activity types"})]})]}),e.jsxs(F,{onClick:b,className:"gap-2 bg-re-green hover:bg-re-green/90 text-white shadow-sm",children:[e.jsx(gs,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Add Activity Type"}),e.jsx("span",{className:"xs:hidden",children:"Add"})]})]})})}),a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(it,{className:"w-8 h-8 animate-spin text-gray-400"})}):C.length===0?e.jsx(se,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(ae,{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(ke,{className:"w-10 h-10 text-slate-400"})}),e.jsx("p",{className:"text-slate-700 font-medium text-lg",children:"No activity types found"}),e.jsx("p",{className:"text-sm text-slate-500 mt-2 mb-6",children:"Add activity types for dealer claim management"}),e.jsxs(F,{onClick:b,variant:"outline",className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(gs,{className:"w-4 h-4"}),"Add First Activity Type"]})]})}):e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[e.jsxs(se,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ge,{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.jsx(fe,{className:"text-base sm:text-lg font-semibold text-slate-900",children:"Active Activity Types"}),e.jsxs(Ue,{className:"text-xs sm:text-sm",children:[C.length," active type",C.length!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-green-50 rounded-md",children:e.jsx(Re,{className:"w-4 h-4 text-green-600"})})]})}),e.jsx(ae,{className:"space-y-3 pt-4",children:C.map(A=>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",children:A.title}),e.jsx(oe,{variant:"outline",className:"bg-gradient-to-r from-green-50 to-emerald-50 text-green-800 border-green-300 text-[10px] sm:text-xs font-medium shadow-sm",children:"Active"})]}),e.jsxs("div",{className:"flex flex-wrap gap-3 text-xs sm:text-sm text-slate-600",children:[A.itemCode&&e.jsxs("span",{className:"font-medium",children:["Item Code: ",e.jsx("span",{className:"text-slate-900",children:A.itemCode})]}),A.taxationType&&e.jsxs("span",{className:"font-medium",children:["Taxation: ",e.jsx("span",{className:"text-slate-900",children:A.taxationType})]}),A.sapRefNo&&e.jsxs("span",{className:"font-medium",children:["SAP Ref: ",e.jsx("span",{className:"text-slate-900",children:A.sapRefNo})]}),!A.itemCode&&!A.taxationType&&!A.sapRefNo&&e.jsx("span",{className:"text-slate-500 italic",children:"No additional details"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-2 self-end sm:self-auto",children:[e.jsxs(F,{size:"sm",variant:"ghost",onClick:()=>f(A),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(oi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]}),e.jsxs(F,{size:"sm",variant:"ghost",onClick:()=>v(A),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(Ri,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Delete"})]})]})]},A.activityTypeId))})]}),w.length>0&&e.jsxs(se,{className:"shadow-lg border-0 rounded-md border-amber-200",children:[e.jsx(ge,{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.jsx(fe,{className:"text-base sm:text-lg font-semibold text-slate-900",children:"Inactive Activity Types"}),e.jsxs(Ue,{className:"text-xs sm:text-sm",children:[w.length," inactive type",w.length!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-amber-50 rounded-md",children:e.jsx(Ye,{className:"w-4 h-4 text-amber-600"})})]})}),e.jsx(ae,{className:"space-y-3 pt-4",children:w.map(A=>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-amber-50/50 border border-amber-200 rounded-md hover:bg-amber-50 hover:border-amber-300 transition-all shadow-sm",children:[e.jsx("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-700 text-sm sm:text-base line-through",children:A.title}),e.jsx(oe,{variant:"outline",className:"bg-gradient-to-r from-amber-50 to-orange-50 text-amber-800 border-amber-300 text-[10px] sm:text-xs font-medium shadow-sm",children:"Inactive"})]})}),e.jsx("div",{className:"flex items-center gap-2 sm:gap-2 self-end sm:self-auto",children:e.jsxs(F,{size:"sm",variant:"ghost",onClick:()=>f(A),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(oi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]})})]},A.activityTypeId))})]})]}),e.jsx(ht,{open:n,onOpenChange:i,children:e.jsxs(dt,{className:"sm:max-w-[550px] max-h-[90vh] rounded-lg flex flex-col p-0",children:[e.jsx(pt,{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(ke,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(mt,{className:"text-xl font-semibold text-slate-900",children:l?"Edit Activity Type":"Add New Activity Type"}),e.jsx(Pt,{className:"text-sm text-slate-600 mt-1",children:l?"Update activity type information":"Add a new activity type for dealer claim management"})]})]})}),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(ne,{htmlFor:"title",className:"text-sm font-semibold text-slate-900 flex items-center gap-1",children:["Title ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Ie,{id:"title",placeholder:"e.g., Riders Mania Claims, Legal Claims Reimbursement",value:x.title,onChange:A=>u({...x,title:A.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 activity type title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"itemCode",className:"text-sm font-semibold text-slate-900",children:["Item Code ",e.jsx("span",{className:"text-slate-400 font-normal text-xs",children:"(Optional)"})]}),e.jsx(Ie,{id:"itemCode",placeholder:"e.g., 1, 2, 3",value:x.itemCode,onChange:A=>u({...x,itemCode:A.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 item code for the activity type"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"taxationType",className:"text-sm font-semibold text-slate-900 flex items-center gap-1",children:["Taxation Type ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsxs(Ke,{value:x.taxationType,onValueChange:A=>u({...x,taxationType:A}),children:[e.jsx(Ze,{id:"taxationType",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(Xe,{placeholder:"Select Taxation Type"})}),e.jsxs(Je,{className:"rounded-lg",children:[e.jsx(Y,{value:"GST",className:"p-3",children:"GST"}),e.jsx(Y,{value:"Non GST",className:"p-3",children:"Non GST"})]})]}),e.jsx("p",{className:"text-xs text-slate-500",children:"Select whether the activity is GST or Non-GST"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"sapRefNo",className:"text-sm font-semibold text-slate-900 flex items-center gap-1",children:["Claim Document Type (SAP Ref) ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Ie,{id:"sapRefNo",placeholder:"e.g., ZCNS, ZRE",value:x.sapRefNo,onChange:A=>u({...x,sapRefNo:A.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:"Required SAP reference number for CSV generation"})]})]}),e.jsxs(Rt,{className:"gap-3 pt-4 border-t border-slate-100 px-6 pb-6 flex-shrink-0",children:[e.jsx(F,{variant:"outline",onClick:()=>i(!1),className:"h-11 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:"Cancel"}),e.jsxs(F,{onClick:y,disabled:!x.title.trim()||!x.taxationType||!x.sapRefNo.trim(),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(ke,{className:"w-4 h-4 mr-2"}),l?"Update Activity Type":"Add Activity Type"]})]})]})})]})}function Qk({open:t,onClose:s,success:a,message:r}){return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(pt,{children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(aa,{className:"w-5 h-5 text-blue-600"}),"Push Notifications"]}),e.jsx(Pt,{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(Re,{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(Ct,{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(Rt,{children:e.jsx(F,{onClick:s,className:"w-full",children:a?"Done":"Close"})})]})})}const qk=async()=>(await ve.get("/user/preferences/notifications")).data.data,e4=async t=>(await ve.put("/user/preferences/notifications",t)).data.data;function t4({open:t,onClose:s}){const[a,r]=p.useState({emailNotificationsEnabled:!0,pushNotificationsEnabled:!0,inAppNotificationsEnabled:!0}),[n,i]=p.useState(!0),[l,o]=p.useState(null),[c,d]=p.useState(null),[m,h]=p.useState(null);p.useEffect(()=>{t&&x()},[t]);const x=async()=>{var g,b;try{i(!0),h(null);const f=await qk();r(f)}catch(f){console.error("[NotificationPreferences] Failed to load preferences:",f),h(((b=(g=f.response)==null?void 0:g.data)==null?void 0:b.message)||"Failed to load notification preferences")}finally{i(!1)}},u=async(g,b)=>{var f,y;try{o(g),h(null),d(null);const v={[g]:b},C=await e4(v);r(C),d(`${g==="emailNotificationsEnabled"?"Email":g==="pushNotificationsEnabled"?"Push":"In-App"} notifications ${b?"enabled":"disabled"}`),setTimeout(()=>d(null),3e3)}catch(v){console.error("[NotificationPreferences] Failed to update preference:",v),h(((y=(f=v.response)==null?void 0:f.data)==null?void 0:y.message)||"Failed to update notification preference"),x()}finally{o(null)}};return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-[600px] max-h-[85vh] overflow-y-auto",children:[e.jsx(pt,{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(Ya,{className:"h-6 w-6 text-white"})}),e.jsxs("div",{children:[e.jsx(mt,{className:"text-xl font-semibold",children:"Notification Preferences"}),e.jsx(Pt,{className:"text-sm",children:"Customize how you receive notifications for workflow updates"})]})]})}),e.jsx(Ps,{className:"my-4"}),n?e.jsx("div",{className:"p-12 flex items-center justify-center",children:e.jsx(it,{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(Re,{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(Ye,{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(Da,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(ne,{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(it,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(mn,{id:"email-notifications-modal",checked:a.emailNotificationsEnabled,onCheckedChange:g=>u("emailNotificationsEnabled",g),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(aa,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(ne,{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(it,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(mn,{id:"push-notifications-modal",checked:a.pushNotificationsEnabled,onCheckedChange:g=>u("pushNotificationsEnabled",g),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(Ds,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(ne,{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(it,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(mn,{id:"inapp-notifications-modal",checked:a.inAppNotificationsEnabled,onCheckedChange:g=>u("inAppNotificationsEnabled",g),disabled:l==="inAppNotificationsEnabled"})]})]})}),e.jsx(Ps,{}),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 s4(){const t=Fs(),{user:s}=Jt(),a=cr(s),[r,n]=p.useState(!1),[i,l]=p.useState(!1),[o,c]=p.useState(),[d,m]=p.useState(!1),[h,x]=p.useState(!1),[u,g]=p.useState(!1),[b,f]=p.useState(!0),[y,v]=p.useState(!1);p.useEffect(()=>{C()},[]);const C=async()=>{try{f(!0);const A=await Py();g(A.length>0)}catch(A){console.error("Failed to check subscription status:",A),g(!1)}finally{f(!1)}},w=async()=>{m(!0),n(!1);try{if(!("Notification"in window)){l(!1),c("Notifications are not supported in this browser. Please use a modern browser like Chrome, Firefox, or Edge."),n(!0),m(!1);return}let A=Notification.permission;if(A==="denied"){l(!1),c(`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.`),n(!0),m(!1);return}if(A==="default"&&(A=await Notification.requestPermission(),A==="denied")){l(!1),c(`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`),n(!0),m(!1);return}if(A!=="granted"){l(!1),c("Notification permission is required to enable push notifications. Please grant permission and try again."),n(!0),m(!1);return}await Gk(),l(!0),c("Push notifications have been successfully enabled! You will now receive notifications for workflow updates, approvals, and TAT alerts."),n(!0),await C()}catch(A){console.error("[Settings] Error enabling notifications:",A),l(!1);const N=(A==null?void 0:A.message)||"Unknown error occurred";c(N.includes("permission")?"Notification permission was denied. Please enable notifications in your browser settings and try again.":N.includes("Service worker")?"Service worker registration failed. Please refresh the page and try again.":N.includes("token")?"Authentication required. Please log in again and try enabling notifications.":`Unable to enable push notifications: ${N}`),n(!0)}finally{m(!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(se,{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(ae,{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(Ya,{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"})]})]})})]}),a?e.jsxs(Ui,{defaultValue:"user",className:"w-full",children:[e.jsxs(Bi,{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(rs,{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(Ya,{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(rs,{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(Ns,{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(rs,{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(Jf,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Configuration"}),e.jsx("span",{className:"sm:hidden",children:"Config"})]}),e.jsxs(rs,{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(xt,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Holidays"}),e.jsx("span",{className:"sm:hidden",children:"Holidays"})]}),e.jsxs(rs,{value:"templates",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(ke,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Templates"}),e.jsx("span",{className:"sm:hidden",children:"Templates"})]})]}),e.jsxs("div",{className:"w-full min-h-[600px]",children:[e.jsx(ns,{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(se,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ge,{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(aa,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg font-semibold text-gray-900",children:"Browser Push Setup"}),e.jsx(Ue,{className:"text-sm text-gray-600",children:"Register this browser for push notifications"})]})]})}),e.jsx(ae,{children:e.jsxs("div",{className:"space-y-4",children:[b?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..."})}):u?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(F,{onClick:w,disabled:d||u,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(aa,{className:`w-4 h-4 mr-2 ${d?"animate-pulse":""}`}),d?"Registering...":u?"Already Registered":"Register Browser for Push"]})]})})]}),e.jsxs(se,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ge,{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(Ha,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg font-semibold text-gray-900",children:"Security"}),e.jsx(Ue,{className:"text-sm text-gray-600",children:"Password and security settings"})]})]})}),e.jsx(ae,{children:e.jsx("div",{className:"space-y-6",children:e.jsxs("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 mb-4",children:"Manage your password, API tokens, and other security preferences."}),e.jsxs(F,{onClick:()=>t("/settings/security"),className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all",children:[e.jsx(Ha,{className:"w-4 h-4 mr-2"}),"Manage Security"]})]})})})]}),e.jsxs(se,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ge,{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(im,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg font-semibold text-gray-900",children:"Appearance"}),e.jsx(Ue,{className:"text-sm text-gray-600",children:"Theme and display preferences"})]})]})}),e.jsx(ae,{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(se,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ge,{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(Ns,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg font-semibold text-gray-900",children:"Preferences"}),e.jsx(Ue,{className:"text-sm text-gray-600",children:"Notification and application preferences"})]})]})}),e.jsx(ae,{children:e.jsxs(F,{onClick:()=>x(!0),className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all",children:[e.jsx(Ns,{className:"w-4 h-4 mr-2"}),"Manage Preferences"]})})]})]})}),e.jsx(ns,{value:"roles",className:"mt-0",children:e.jsx(Zk,{})}),e.jsx(ns,{value:"system",className:"mt-0",children:e.jsx(Yk,{})}),e.jsx(ns,{value:"holidays",className:"mt-0",children:e.jsx(Kk,{})}),e.jsx(ns,{value:"templates",className:"mt-0",children:y?e.jsxs("div",{className:"space-y-4",children:[e.jsx(se,{className:"shadow-lg border-0 rounded-md",children:e.jsx(ge,{className:"border-b border-slate-100 py-4 sm:py-5",children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(F,{variant:"ghost",size:"sm",onClick:()=>v(!1),className:"gap-2 hover:bg-slate-100",children:[e.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),"Back"]}),e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(ke,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Dealer Claim Activity Settings"}),e.jsx(Ue,{className:"text-sm",children:"Manage activity types for dealer claim workflows"})]})]})})})}),e.jsx(Jk,{})]}):e.jsxs(se,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ge,{className:"border-b border-slate-100 py-4 sm:py-5",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(ke,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Template Settings"}),e.jsx(Ue,{className:"text-sm",children:"Manage templates and activity types for workflows"})]})]})}),e.jsx(ae,{className:"pt-6",children:e.jsx("div",{className:"space-y-4",children:e.jsx(se,{className:"shadow-md hover:shadow-lg transition-all duration-300 border border-slate-200 rounded-lg cursor-pointer group",onClick:()=>v(!0),children:e.jsx(ae,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-blue-500 to-blue-600 rounded-lg shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(ke,{className:"w-6 h-6 text-white"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900 group-hover:text-blue-600 transition-colors",children:"Dealer Claim Activity Settings"}),e.jsx("p",{className:"text-sm text-slate-600 mt-1",children:"Manage activity types for dealer claim workflows"})]})]}),e.jsx("div",{className:"text-slate-400 group-hover:text-blue-600 transition-colors",children:e.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})})]})})})})})]})})]})]}):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(se,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ge,{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(aa,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg font-semibold text-gray-900",children:"Browser Push Setup"}),e.jsx(Ue,{className:"text-sm text-gray-600",children:"Register this browser for push notifications"})]})]})}),e.jsx(ae,{children:e.jsxs("div",{className:"space-y-4",children:[b?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..."})}):u?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(F,{onClick:w,disabled:d||u,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(aa,{className:`w-4 h-4 mr-2 ${d?"animate-pulse":""}`}),d?"Registering...":u?"Already Registered":"Register Browser for Push"]})]})})]}),e.jsxs(se,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ge,{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(Ha,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg font-semibold text-gray-900",children:"Security"}),e.jsx(Ue,{className:"text-sm text-gray-600",children:"Password and security settings"})]})]})}),e.jsx(ae,{children:e.jsx("div",{className:"space-y-6",children:e.jsxs("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 mb-4",children:"Manage your password, API tokens, and other security preferences."}),e.jsxs(F,{onClick:()=>t("/settings/security"),className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all",children:[e.jsx(Ha,{className:"w-4 h-4 mr-2"}),"Manage Security"]})]})})})]}),e.jsxs(se,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ge,{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(im,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg font-semibold text-gray-900",children:"Appearance"}),e.jsx(Ue,{className:"text-sm text-gray-600",children:"Theme and display preferences"})]})]})}),e.jsx(ae,{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(se,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ge,{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(Ns,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg font-semibold text-gray-900",children:"Preferences"}),e.jsx(Ue,{className:"text-sm text-gray-600",children:"Notification and application preferences"})]})]})}),e.jsx(ae,{children:e.jsxs(F,{onClick:()=>x(!0),className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all",children:[e.jsx(Ns,{className:"w-4 h-4 mr-2"}),"Manage Preferences"]})})]})]})})]}),e.jsx(Qk,{open:r,onClose:()=>n(!1),success:i,message:o}),e.jsx(t4,{open:h,onClose:()=>x(!1)})]})}function jc({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:Ae("w-full caption-bottom text-sm",t),...s})})}function Nc({className:t,...s}){return e.jsx("thead",{"data-slot":"table-header",className:Ae("[&_tr]:border-b",t),...s})}function wc({className:t,...s}){return e.jsx("tbody",{"data-slot":"table-body",className:Ae("[&_tr:last-child]:border-0",t),...s})}function zr({className:t,...s}){return e.jsx("tr",{"data-slot":"table-row",className:Ae("hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",t),...s})}function qt({className:t,...s}){return e.jsx("th",{"data-slot":"table-head",className:Ae("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 es({className:t,...s}){return e.jsx("td",{"data-slot":"table-cell",className:Ae("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",t),...s})}const a4=So("relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",{variants:{variant:{default:"bg-card text-card-foreground",destructive:"text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90"}},defaultVariants:{variant:"default"}});function r4({className:t,variant:s,...a}){return e.jsx("div",{"data-slot":"alert",role:"alert",className:Ae(a4({variant:s}),t),...a})}function n4({className:t,...s}){return e.jsx("div",{"data-slot":"alert-title",className:Ae("col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",t),...s})}function i4({className:t,...s}){return e.jsx("div",{"data-slot":"alert-description",className:Ae("text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",t),...s})}function l4(){const[t,s]=p.useState([]),[a,r]=p.useState(!0),[n,i]=p.useState(!1),[l,o]=p.useState(""),[c,d]=p.useState(""),[m,h]=p.useState(null),[x,u]=p.useState(!1),[g,b]=p.useState(!1),[f,y]=p.useState(null);p.useEffect(()=>{v()},[]);const v=async()=>{try{r(!0);const T=await ve.get("/api-tokens");s(T.data.data.tokens)}catch(T){console.error("Failed to fetch API tokens:",T),K.error("Failed to load API tokens")}finally{r(!1)}},C=async()=>{if(l.trim())try{u(!0);const T={name:l};c&&(T.expiresInDays=Number(c));const R=await ve.post("/api-tokens",T);h(R.data.data.token),K.success("API Token created successfully"),v()}catch(T){console.error("Failed to create token:",T),K.error("Failed to create API token")}finally{u(!1)}},w=T=>{y(T)},A=async()=>{if(f)try{await ve.delete(`/api-tokens/${f.id}`),K.success("Token revoked successfully"),s(t.filter(T=>T.id!==f.id)),y(null)}catch(T){console.error("Failed to revoke token:",T),K.error("Failed to revoke token")}},N=()=>{m&&(navigator.clipboard.writeText(m),b(!0),setTimeout(()=>b(!1),2e3),K.success("Token copied to clipboard"))},_=()=>{i(!1),o(""),d(""),h(null)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-medium text-gray-900",children:"API Tokens"}),e.jsx("p",{className:"text-sm text-gray-500",children:"Manage personal access tokens for external integrations"})]}),e.jsxs(F,{onClick:()=>i(!0),size:"sm",className:"bg-re-green hover:bg-re-green/90 text-white",children:[e.jsx(gs,{className:"w-4 h-4 mr-2"}),"Generate"]})]}),a?e.jsx("div",{className:"text-center py-4 text-gray-500",children:"Loading tokens..."}):t.length===0?e.jsxs("div",{className:"text-center py-8 bg-gray-50 rounded-lg border border-dashed border-gray-300",children:[e.jsx($x,{className:"w-10 h-10 text-gray-300 mx-auto mb-2"}),e.jsx("p",{className:"text-gray-500 font-medium",children:"No API tokens found"}),e.jsx("p",{className:"text-gray-400 text-sm mt-1",children:"Generate a token to access the API programmatically"})]}):e.jsx("div",{className:"rounded-md border",children:e.jsxs(jc,{children:[e.jsx(Nc,{children:e.jsxs(zr,{children:[e.jsx(qt,{children:"Name"}),e.jsx(qt,{children:"Prefix"}),e.jsx(qt,{children:"Last Used"}),e.jsx(qt,{children:"Expires"}),e.jsx(qt,{className:"text-right",children:"Actions"})]})}),e.jsx(wc,{children:t.map(T=>e.jsxs(zr,{children:[e.jsx(es,{className:"font-medium",children:T.name}),e.jsxs(es,{className:"font-mono text-xs bg-slate-100 rounded px-2 py-1 w-fit",children:[T.prefix,"..."]}),e.jsx(es,{className:"text-gray-500 text-sm",children:T.lastUsedAt?Ge(new Date(T.lastUsedAt),"MMM d, yyyy"):"Never"}),e.jsx(es,{className:"text-gray-500 text-sm",children:T.expiresAt?Ge(new Date(T.expiresAt),"MMM d, yyyy"):"No Expiry"}),e.jsx(es,{className:"text-right",children:e.jsxs(F,{variant:"ghost",size:"sm",onClick:()=>w(T),className:"text-red-600 hover:text-red-700 hover:bg-red-50",children:[e.jsx(Ri,{className:"w-4 h-4"}),e.jsx("span",{className:"sr-only",children:"Revoke"})]})})]},T.id))})]})}),e.jsx(ht,{open:n,onOpenChange:T=>!T&&_(),children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(pt,{children:[e.jsx(mt,{children:"Generate API Token"}),e.jsx(Pt,{children:"Create a new token to access the API. Treat this token like a password."})]}),m?e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs(r4,{className:"bg-green-50 border-green-200",children:[e.jsx(Ra,{className:"h-4 w-4 text-green-600"}),e.jsx(n4,{className:"text-green-800",children:"Token Generated Successfully"}),e.jsx(i4,{className:"text-green-700",children:"Please copy your token now. You won't be able to see it again!"})]}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"p-4 bg-slate-900 rounded-md font-mono text-sm text-green-400 break-all pr-10",children:m}),e.jsx(F,{size:"icon",variant:"ghost",className:"absolute top-1 right-1 text-gray-400 hover:text-white hover:bg-slate-800",onClick:N,children:g?e.jsx(Ra,{className:"w-4 h-4 text-green-500"}):e.jsx(Qf,{className:"w-4 h-4"})})]})]}):e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"token-name",children:"Token Name"}),e.jsx(Ie,{id:"token-name",placeholder:"e.g., CI/CD Pipeline, Prometheus",value:l,onChange:T=>o(T.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"token-expiry",children:"Expiration (Days)"}),e.jsx(Ie,{id:"token-expiry",type:"number",min:"1",placeholder:"Leave empty for no expiry",value:c,onChange:T=>{const R=T.target.value;if(R==="")d("");else{const j=parseInt(R);!isNaN(j)&&j>=1&&d(j)}}})]})]}),e.jsx(Rt,{children:m?e.jsx(F,{onClick:_,children:"Done"}):e.jsxs(e.Fragment,{children:[e.jsx(F,{variant:"outline",onClick:_,children:"Cancel"}),e.jsx(F,{onClick:C,disabled:!l.trim()||x,children:x?"Generating...":"Generate Token"})]})})]})}),e.jsx(qx,{open:!!f,onOpenChange:T=>!T&&y(null),children:e.jsxs(To,{children:[e.jsxs(th,{children:[e.jsx(ah,{children:"Revoke API Token"}),e.jsxs(rh,{children:["Are you sure you want to revoke the token ",e.jsx("strong",{children:f==null?void 0:f.name}),"? This action cannot be undone and any applications using this token will lose access immediately."]})]}),e.jsxs(sh,{children:[e.jsx(ih,{children:"Cancel"}),e.jsx(nh,{onClick:A,className:"bg-red-600 hover:bg-red-700 text-white",children:"Revoke Token"})]})]})})]})}function o4(){const t=Fs();return e.jsxs("div",{className:"max-w-7xl mx-auto space-y-6 pb-8",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[e.jsx(F,{variant:"ghost",size:"icon",onClick:()=>t("/settings"),children:e.jsx(Cs,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900",children:"Security Settings"}),e.jsx("p",{className:"text-gray-500",children:"Manage your account security and access tokens"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-6",children:[e.jsxs(se,{className:"shadow-md",children:[e.jsx(ge,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-blue-100 rounded-md",children:e.jsx(Ha,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(fe,{children:"Password"}),e.jsx(Ue,{children:"Manage your sign-in password"})]})]})}),e.jsx(ae,{children:e.jsx("div",{className:"p-4 bg-gray-50 rounded-md border border-gray-200",children:e.jsx("p",{className:"text-sm text-gray-600",children:"Your password is managed through your organization's Single Sign-On (SSO) provider. Please contact your IT administrator to reset or change your password."})})})]}),e.jsxs(se,{className:"shadow-md",children:[e.jsx(ge,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-purple-100 rounded-md",children:e.jsx($x,{className:"w-5 h-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(fe,{children:"API Tokens"}),e.jsx(Ue,{children:"Manage personal access tokens for external integrations"})]})]})}),e.jsx(ae,{children:e.jsx(l4,{})})]})]})]})}function c4({onNavigate:t}){const[s,a]=p.useState([]),[r,n]=p.useState(!0),[i,l]=p.useState(1),[o,c]=p.useState(1),[d,m]=p.useState(0),[h,x]=p.useState("all"),[u,g]=p.useState(!1),b=20,f=async(R=i,j=h==="unread")=>{var E,P;try{n(R===1);const B=await Ga.list({page:R,limit:b,unreadOnly:j}),k=((E=B.data)==null?void 0:E.notifications)||[],L=((P=B.data)==null?void 0:P.pagination)||{},V=L.total||0,D=L.totalPages||1;a(k),m(V),c(D),l(R)}catch(B){console.error("[Notifications] Failed to fetch:",B)}finally{n(!1),g(!1)}};p.useEffect(()=>{l(1),f(1,h==="unread")},[h]);const y=async R=>{var j;try{if(R.isRead||(await Ga.markAsRead(R.notificationId),a(E=>E.map(P=>P.notificationId===R.notificationId?{...P,isRead:!0}:P))),R.actionUrl&&t){const E=(j=R.metadata)==null?void 0:j.requestNumber;if(E){let P=`request/${E}`;(R.notificationType==="mention"||R.notificationType==="comment"||R.notificationType==="worknote")&&(P+="?tab=worknotes"),R.notificationType==="document_added"&&(P+="?tab=documents"),t(P)}}}catch(E){console.error("[Notifications] Error handling notification click:",E)}},v=async()=>{try{g(!0),await Ga.markAllAsRead(),await f(i,h==="unread")}catch(R){console.error("[Notifications] Error marking all as read:",R),g(!1)}},C=async R=>{try{await Ga.delete(R),a(j=>j.filter(E=>E.notificationId!==R)),m(j=>j-1)}catch(j){console.error("[Notifications] Error deleting notification:",j)}},w=()=>{g(!0),f(i,h==="unread")},A=R=>{R<1||R>o||(l(R),f(R,h==="unread"))},N=R=>{const j="w-6 h-6";switch(R){case"mention":case"comment":return e.jsx(Ds,{className:`${j} text-blue-600`});case"worknote":return e.jsx(ke,{className:`${j} text-purple-600`});case"document_added":return e.jsx(ke,{className:`${j} text-teal-600`});case"assignment":return e.jsx(Ci,{className:`${j} text-indigo-600`});case"approval":return e.jsx(Re,{className:`${j} text-green-600`});case"rejection":return e.jsx(Ct,{className:`${j} text-red-600`});case"tat_alert":return e.jsx(nt,{className:`${j} text-orange-600`});case"tat_breach":return e.jsx(Ye,{className:`${j} text-red-600`});case"tat_breach_initiator":return e.jsx(os,{className:`${j} text-amber-600`});default:return e.jsx(aa,{className:`${j} text-gray-600`})}},_=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"}},T=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(aa,{className:"w-8 h-8 text-blue-600"}),"Notifications"]}),e.jsxs("p",{className:"text-gray-600 mt-1",children:[d," total notification",d!==1?"s":"",T>0&&` • ${T} unread`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(F,{variant:"outline",size:"sm",onClick:w,disabled:u,className:"gap-2",children:[e.jsx(Ut,{className:`w-4 h-4 ${u?"animate-spin":""}`}),"Refresh"]}),T>0&&e.jsxs(F,{variant:"outline",size:"sm",onClick:v,disabled:u,className:"gap-2",children:[e.jsx(qf,{className:"w-4 h-4"}),"Mark All Read"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(F,{variant:h==="all"?"default":"outline",size:"sm",onClick:()=>{x("all"),l(1)},children:"All Notifications"}),e.jsxs(F,{variant:h==="unread"?"default":"outline",size:"sm",onClick:()=>{x("unread"),l(1)},children:["Unread",T>0&&e.jsx(oe,{className:"ml-2 bg-red-500 text-white",children:T})]})]}),e.jsxs(se,{children:[e.jsxs(ge,{children:[e.jsx(fe,{children:"Recent Activity"}),e.jsx(Ue,{children:"Stay updated with all your workflow activities and mentions"})]}),e.jsx(ae,{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(aa,{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:h==="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 j;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:()=>y(R),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"shrink-0 mt-0.5",children:N(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(oe,{variant:"outline",className:`text-xs ${_(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:[fx(new Date(R.createdAt),{addSuffix:!0}),((j=R.metadata)==null?void 0:j.requestNumber)&&e.jsxs("span",{className:"ml-2",children:["• ",R.metadata.requestNumber]})]}),e.jsx(F,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-600",onClick:E=>{E.stopPropagation(),C(R.notificationId)},children:e.jsx(Ri,{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)*b+1," to ",Math.min(i*b,d)," of ",d," notifications"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(F,{variant:"outline",size:"sm",onClick:()=>A(i-1),disabled:i===1,children:[e.jsx(Cx,{className:"w-4 h-4"}),"Previous"]}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,o)},(R,j)=>{let E;return o<=5||i<=3?E=j+1:i>=o-2?E=o-4+j:E=i-2+j,e.jsx(F,{variant:i===E?"default":"outline",size:"sm",className:"w-9 h-9 p-0",onClick:()=>A(E),children:E},E)})}),e.jsxs(F,{variant:"outline",size:"sm",onClick:()=>A(i+1),disabled:i===o,children:["Next",e.jsx(vi,{className:"w-4 h-4"})]})]})]})]})}function d4({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(F,{variant:"outline",onClick:t,className:"inline-flex items-center gap-2","data-testid":"back-button",children:[e.jsx(Cs,{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(ke,{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 Cc({dateRange:t,customStartDate:s,customEndDate:a,showCustomDatePicker:r,tempCustomStartDate:n,tempCustomEndDate:i,onDateRangeChange:l,onShowCustomDatePickerChange:o,onStartDateChange:c,onEndDateChange:d,onApply:m,onCancel:h,testIdPrefix:x="date-filter"}){const u=s&&a?`${Ge(s,"d MMM yyyy")} - ${Ge(a,"d MMM yyyy")}`:"Select dates";return e.jsxs("div",{className:"flex items-center gap-2","data-testid":`${x}-container`,children:[e.jsx(xt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ke,{value:t,onValueChange:l,"data-testid":`${x}-select`,children:[e.jsx(Ze,{className:"w-[160px]",children:e.jsx(Xe,{placeholder:"Date Range"})}),e.jsxs(Je,{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(Xs,{open:r,onOpenChange:o,children:[e.jsx(Zs,{asChild:!0,children:e.jsxs(F,{variant:"outline",size:"sm",className:"gap-2","data-testid":`${x}-custom-trigger`,children:[e.jsx(xt,{className:"w-4 h-4"}),u]})}),e.jsx(Js,{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(ne,{htmlFor:`${x}-start-date`,className:"text-sm font-medium",children:"Start Date"}),e.jsx(Us,{value:n||null,onChange:g=>{const b=g?new Date(g):void 0;c(b)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full",id:`${x}-start-date`})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:`${x}-end-date`,className:"text-sm font-medium",children:"End Date"}),e.jsx(Us,{value:i||null,onChange:g=>{const b=g?new Date(g):void 0;d(b)},minDate:n||void 0,maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full",id:`${x}-end-date`})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(F,{size:"sm",onClick:m,disabled:!n||!i,className:"flex-1 bg-re-green hover:bg-re-green/90","data-testid":`${x}-apply-button`,children:"Apply"}),e.jsx(F,{size:"sm",variant:"outline",onClick:h,"data-testid":`${x}-cancel-button`,children:"Cancel"})]})]})})]})]})}function m4(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 Xg(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 Zg(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 u4(t){return t>=20?"bg-red-600":t>=10?"bg-orange-500":"bg-amber-500"}function x4({lifecycleRequests:t,loading:s,loadingPage:a,error:r,pagination:n,dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,exporting:h,onDateRangeChange:x,onShowCustomDatePickerChange:u,onStartDateChange:g,onEndDateChange:b,onApplyCustomDate:f,onCancelCustomDate:y,onPageChange:v,onExport:C,onViewRequest:w}){return e.jsxs(se,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"request-lifecycle-report",children:[e.jsxs(ge,{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(It,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg text-gray-900",children:"Request Lifecycle Report"}),e.jsx(Ue,{className:"text-gray-600",children:"End-to-end workflow status including all approval levels, approvers, dates, and TAT compliance"})]})]}),e.jsxs(F,{variant:"outline",size:"sm",className:"gap-2",onClick:C,disabled:h,"data-testid":"export-lifecycle-button",children:[e.jsx(At,{className:"w-4 h-4"}),h?"Exporting...":"Download CSV"]})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(Cc,{dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,onDateRangeChange:x,onShowCustomDatePickerChange:u,onStartDateChange:g,onEndDateChange:b,onApply:f,onCancel:y,testIdPrefix:"lifecycle"})})]}),e.jsxs(ae,{children:[s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"lifecycle-loading",children:[e.jsx(it,{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(Ye,{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(A=>e.jsx("div",{className:"border rounded-xl overflow-hidden","data-testid":`lifecycle-request-${A.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:()=>w(A.requestId||A.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:N=>{N.stopPropagation(),w(A.requestId||A.id)},className:"font-semibold text-sm text-blue-600 hover:text-blue-800 hover:underline cursor-pointer transition-colors","data-testid":`lifecycle-request-link-${A.id}`,children:A.id}),e.jsx(oe,{className:Xg(A.priority),"data-testid":`lifecycle-priority-${A.id}`,children:A.priority}),e.jsx(oe,{className:Zg(A.status),"data-testid":`lifecycle-status-${A.id}`,children:A.status})]}),e.jsx("p",{className:"text-sm text-gray-700",children:A.title}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["Initiated by ",e.jsx("span",{className:"font-medium",children:A.initiator})," on ",A.initDate]}),A.currentStage&&!A.currentStage.includes("Level")&&e.jsxs("p",{className:"text-xs text-gray-400 mt-0.5",children:["Stage: ",A.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:A.currentStage}),e.jsxs("p",{className:"text-xs text-gray-400 mt-0.5",children:["(Level ",A.currentLevel,"/",A.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:A.overallTAT}),A.breachCount>0&&e.jsxs("p",{className:"text-xs text-red-500 mt-0.5",children:[A.breachCount," breach",A.breachCount>1?"es":""]})]}),e.jsx(F,{variant:"ghost",size:"sm",onClick:()=>w(A.requestId||A.id),className:"gap-1.5","data-testid":`lifecycle-view-button-${A.id}`,children:e.jsx(vi,{className:"w-4 h-4"})})]})]})})},A.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(it,{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(F,{variant:"outline",size:"sm",onClick:()=>v(n.page-1),disabled:n.page<=1||a,"data-testid":"lifecycle-pagination-prev",children:"Previous"}),e.jsx(F,{variant:"outline",size:"sm",onClick:()=>v(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"lifecycle-pagination-next",children:"Next"})]})]})]})]})}function h4({activityLog:t,loading:s,loadingPage:a,error:r,pagination:n,dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,filterCategory:h,filterSeverity:x,exporting:u,onDateRangeChange:g,onShowCustomDatePickerChange:b,onStartDateChange:f,onEndDateChange:y,onApplyCustomDate:v,onCancelCustomDate:C,onCategoryChange:w,onSeverityChange:A,onClearFilters:N,onPageChange:_,onExport:T,onViewRequest:R}){const j=h!=="all"||x!=="all"||i!=="month"||l||o;return e.jsxs(se,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"user-activity-log-report",children:[e.jsxs(ge,{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(Lx,{className:"h-5 w-5 text-indigo-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg text-gray-900",children:"User Activity Log Report"}),e.jsx(Ue,{className:"text-gray-600",children:"Consolidated user actions and activity history"})]})]}),e.jsxs(F,{variant:"outline",size:"sm",className:"gap-2",onClick:T,disabled:u,"data-testid":"export-activity-button",children:[e.jsx(At,{className:"w-4 h-4"}),u?"Exporting...":"Download CSV"]})]}),e.jsxs("div",{className:"mt-4 flex items-center gap-4 flex-wrap",children:[e.jsx(Cc,{dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,onDateRangeChange:g,onShowCustomDatePickerChange:b,onStartDateChange:f,onEndDateChange:y,onApply:v,onCancel:C,testIdPrefix:"activity"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-sm text-gray-600 whitespace-nowrap",children:"Category:"}),e.jsxs(Ke,{value:h,onValueChange:w,"data-testid":"activity-category-filter",children:[e.jsx(Ze,{className:"w-40",children:e.jsx(Xe,{placeholder:"All Categories"})}),e.jsxs(Je,{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(Ke,{value:x,onValueChange:A,"data-testid":"activity-severity-filter",children:[e.jsx(Ze,{className:"w-40",children:e.jsx(Xe,{placeholder:"All Severities"})}),e.jsxs(Je,{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"})]})]})]}),j&&e.jsx(F,{variant:"ghost",size:"sm",onClick:N,className:"text-xs","data-testid":"activity-clear-filters",children:"Clear Filters"})]})]}),e.jsx(ae,{children:s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"activity-loading",children:[e.jsx(it,{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(Ye,{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(jc,{children:[e.jsx(Nc,{children:e.jsxs(zr,{className:"bg-gray-50",children:[e.jsx(qt,{className:"font-semibold",children:"Timestamp"}),e.jsx(qt,{className:"font-semibold",children:"User"}),e.jsx(qt,{className:"font-semibold",children:"Action"}),e.jsx(qt,{className:"font-semibold",children:"Details"}),e.jsx(qt,{className:"font-semibold",children:"IP Address"}),e.jsx(qt,{className:"font-semibold",children:"Request ID"})]})}),e.jsx(wc,{children:t.map((E,P)=>e.jsxs(zr,{className:"hover:bg-gray-50","data-testid":`activity-row-${P}`,children:[e.jsx(es,{className:"text-xs font-medium",children:E.timestamp}),e.jsx(es,{className:"text-sm",children:E.user}),e.jsx(es,{children:e.jsx(oe,{className:m4(E.action),"data-testid":`activity-action-${P}`,children:E.action})}),e.jsx(es,{className:"text-sm text-gray-600",children:E.details}),e.jsx(es,{className:"text-xs font-mono text-gray-500",children:E.ip&&E.ip!=="N/A"?e.jsx("span",{title:E.userAgent||"",children:E.ip}):e.jsx("span",{className:"text-gray-400 italic",title:"IP address not yet captured",children:"N/A"})}),e.jsx(es,{children:E.requestId!=="-"&&E.requestId!=="System Login"?e.jsx("button",{onClick:()=>{const B=E.requestId;B&&R(B)},className:"hover:underline","data-testid":`activity-request-link-${P}`,children:e.jsx(oe,{variant:"outline",className:"text-xs cursor-pointer hover:bg-blue-50 hover:border-blue-300 transition-colors",children:E.requestId})}):e.jsx("span",{className:"text-xs text-gray-400",children:"-"})})]},P))})]}),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(it,{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(F,{variant:"outline",size:"sm",onClick:()=>_(n.page-1),disabled:n.page<=1||a,"data-testid":"activity-pagination-prev",children:"Previous"}),e.jsx(F,{variant:"outline",size:"sm",onClick:()=>_(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"activity-pagination-next",children:"Next"})]})]})]})})]})}function p4({agingWorkflows:t,loading:s,loadingPage:a,error:r,pagination:n,threshold:i,thresholdError:l,dateRange:o,customStartDate:c,customEndDate:d,showCustomDatePicker:m,tempCustomStartDate:h,tempCustomEndDate:x,searchQuery:u,exporting:g,onThresholdChange:b,onThresholdBlur:f,onDateRangeChange:y,onShowCustomDatePickerChange:v,onStartDateChange:C,onEndDateChange:w,onApplyCustomDate:A,onCancelCustomDate:N,onSearchChange:_,onPageChange:T,onExport:R,onViewRequest:j}){return e.jsxs(se,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"workflow-aging-report",children:[e.jsxs(ge,{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(vo,{className:"h-5 w-5 text-amber-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg text-gray-900",children:"Workflow Aging Report"}),e.jsx(Ue,{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(Ie,{type:"number",min:"1",value:i,onChange:E=>b(E.target.value),onBlur:f,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(oe,{variant:"outline",className:"font-semibold","data-testid":"aging-total-badge",children:[n.totalRecords," workflows"]}),e.jsxs(F,{variant:"outline",size:"sm",className:"gap-2",onClick:R,disabled:g,"data-testid":"export-aging-button",children:[e.jsx(At,{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(Cc,{dateRange:o,customStartDate:c,customEndDate:d,showCustomDatePicker:m,tempCustomStartDate:h,tempCustomEndDate:x,onDateRangeChange:y,onShowCustomDatePickerChange:v,onStartDateChange:C,onEndDateChange:w,onApply:A,onCancel:N,testIdPrefix:"aging"}),e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(Es,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(Ie,{placeholder:"Search by Request ID, Title, or Initiator...",value:u,onChange:E=>_(E.target.value),className:"pl-10","data-testid":"aging-search-input"})]})]})]}),e.jsx(ae,{children:s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"aging-loading",children:[e.jsx(it,{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(Ye,{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(jc,{children:[e.jsx(Nc,{children:e.jsxs(zr,{className:"bg-gray-50",children:[e.jsx(qt,{className:"font-semibold",children:"Request ID"}),e.jsx(qt,{className:"font-semibold",children:"Title"}),e.jsx(qt,{className:"font-semibold",children:"Initiator"}),e.jsx(qt,{className:"font-semibold",children:"Start Date"}),e.jsx(qt,{className:"font-semibold",children:"Days Open"}),e.jsx(qt,{className:"font-semibold",children:"Current Stage"}),e.jsx(qt,{className:"font-semibold",children:"Assigned To"}),e.jsx(qt,{className:"font-semibold",children:"Priority"}),e.jsx(qt,{className:"font-semibold",children:"Status"})]})}),e.jsx(wc,{children:t.map(E=>e.jsxs(zr,{className:"hover:bg-gray-50","data-testid":`aging-workflow-${E.id}`,children:[e.jsx(es,{className:"font-medium text-sm",children:e.jsx("button",{onClick:()=>j(E.requestId||E.id),className:"text-blue-600 hover:text-blue-800 hover:underline cursor-pointer transition-colors","data-testid":`aging-request-link-${E.id}`,children:E.id})}),e.jsx(es,{className:"text-sm",children:E.title}),e.jsx(es,{className:"text-sm",children:E.initiator}),e.jsx(es,{className:"text-sm text-gray-600",children:E.startDate}),e.jsx(es,{children:e.jsxs(oe,{className:`${u4(E.daysOpen)} text-white border-transparent`,"data-testid":`aging-days-${E.id}`,children:[E.daysOpen," days",e.jsx("span",{className:"ml-1 text-xs opacity-75",children:"(business)"})]})}),e.jsx(es,{className:"text-sm",children:E.currentStage}),e.jsx(es,{className:"text-sm",children:E.assignedTo&&E.assignedTo!=="N/A"?E.assignedTo:e.jsx("span",{className:"text-gray-400 italic",title:"Assigned approver not available",children:"N/A"})}),e.jsx(es,{children:e.jsx(oe,{className:Xg(E.priority),"data-testid":`aging-priority-${E.id}`,children:E.priority})}),e.jsx(es,{children:e.jsx(oe,{className:Zg(E.status),"data-testid":`aging-status-${E.id}`,children:E.status})})]},E.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(it,{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(F,{variant:"outline",size:"sm",onClick:()=>T(n.page-1),disabled:n.page<=1||a,"data-testid":"aging-pagination-prev",children:"Previous"}),e.jsx(F,{variant:"outline",size:"sm",onClick:()=>T(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"aging-pagination-next",children:"Next"})]})]})]})})]})}function Rl(t="month"){const[s,a]=p.useState(t),[r,n]=p.useState(void 0),[i,l]=p.useState(void 0),[o,c]=p.useState(!1),[d,m]=p.useState(void 0),[h,x]=p.useState(void 0),u=p.useCallback(w=>{const A=w;a(A),A!=="custom"?(n(void 0),l(void 0),m(void 0),x(void 0),c(!1)):(m(r),x(i),c(!0))},[r,i]),g=p.useCallback(()=>{if(d&&h){if(d>h){const w=d;n(h),l(w),m(h),x(w)}else n(d),l(h);c(!1)}},[d,h]),b=p.useCallback(()=>{c(!1),m(r),x(i),(!r||!i)&&(n(void 0),l(void 0),a("month"))},[r,i]),f=p.useCallback(w=>{w?(m(w),h&&w>h&&x(w)):m(void 0)},[h]),y=p.useCallback(w=>{w?(x(w),d&&w<d&&m(w)):x(void 0)},[d]),v=p.useCallback(()=>r&&i?`${Ge(r,"MMM d, yyyy")} - ${Ge(i,"MMM d, yyyy")}`:"Select dates",[r,i]),C=p.useCallback(()=>{a("month"),n(void 0),l(void 0),c(!1),m(void 0),x(void 0)},[]);return{dateRange:s,customStartDate:r,customEndDate:i,showCustomDatePicker:o,tempCustomStartDate:d,tempCustomEndDate:h,setShowCustomDatePicker:c,handleDateRangeChange:u,handleApplyCustomDate:g,handleCancelCustomDate:b,handleStartDateChange:f,handleEndDateChange:y,getDisplayDateRange:v,reset:C}}function g4(t){if(!t&&t!==0)return"N/A";const s=8;if(t<s)return Mt(t);const a=Math.floor(t/s),r=t%s;return r>0?`${a}d ${Mt(r)}`:`${a}d`}function Jg(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 xr(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 Qg(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 f4=10;function b4({dateRange:t,customStartDate:s,customEndDate:a}){const[r,n]=p.useState([]),[i,l]=p.useState(!0),[o,c]=p.useState(!1),[d,m]=p.useState(null),[h,x]=p.useState({page:1,totalPages:1,totalRecords:0}),u=p.useRef(!0),g=p.useCallback(async(b=1)=>{const f=b===1&&u.current;try{f?l(!0):c(!0),m(null);const y=await Dt.getLifecycleReport(b,f4,t,s,a),v=y.lifecycleData.map(C=>{const w=g4(C.overallTATHours);return{id:C.requestNumber,requestId:C.requestId,title:C.title,priority:C.priority||"medium",status:C.status,initiator:C.initiatorName||"Unknown",initDate:Jg(C.submissionDate),currentStage:C.currentStageName||`Level ${C.currentLevel}`,overallTAT:w,currentLevel:C.currentLevel,totalLevels:C.totalLevels,breachCount:C.breachCount||0}});n(v),x({page:y.pagination.currentPage,totalPages:y.pagination.totalPages,totalRecords:y.pagination.totalRecords})}catch(y){console.error("Failed to fetch lifecycle data:",y),m((y==null?void 0:y.message)||"Failed to load lifecycle data")}finally{f?l(!1):c(!1)}f&&(u.current=!1)},[t,s,a]);return p.useEffect(()=>{t==="custom"&&(!s||!a)||g(1)},[t,s,a]),{lifecycleRequests:r,loading:i,loadingPage:o,error:d,pagination:h,fetchData:g}}const y4=20;function v4({dateRange:t,customStartDate:s,customEndDate:a,filterCategory:r,filterSeverity:n}){const[i,l]=p.useState([]),[o,c]=p.useState(!0),[d,m]=p.useState(!1),[h,x]=p.useState(null),[u,g]=p.useState({page:1,totalPages:1,totalRecords:0}),b=p.useRef(!0),f=p.useCallback(async(y=1)=>{const v=y===1&&b.current;try{v?c(!0):m(!0),x(null);const C=await Dt.getActivityLogReport(y,y4,t,void 0,void 0,r&&r!=="all"?r:void 0,n&&n!=="all"?n:void 0,s,a),w=C.activities.map(A=>{const N=Qg(A.type||"",A.details),_=(A.type||"").toLowerCase()==="login"||A.requestId==="00000000-0000-0000-0000-000000000001"||A.requestId==="SYSTEM_LOGIN",T=_?A.details||"User login":A.requestTitle||A.requestNumber||A.details||"N/A";return{timestamp:A.timestamp?Jg(A.timestamp):"N/A",user:A.userName||"Unknown",action:N,details:T,ip:A.ipAddress||"N/A",userAgent:A.userAgent||null,requestId:_?"System Login":A.requestNumber||A.requestId||"-",userId:A.userId}});l(w),g({page:C.pagination.currentPage,totalPages:C.pagination.totalPages,totalRecords:C.pagination.totalRecords})}catch(C){console.error("Failed to fetch activity data:",C),x((C==null?void 0:C.message)||"Failed to load activity data")}finally{v?c(!1):m(!1)}v&&(b.current=!1)},[r,n,t,s,a]);return p.useEffect(()=>{t==="custom"&&(!s||!a)||f(1)},[r,n,t,s,a]),{activityLog:i,loading:o,loadingPage:d,error:h,pagination:u,fetchData:f}}const j4=20;function N4({threshold:t,dateRange:s,customStartDate:a,customEndDate:r,searchQuery:n=""}){const[i,l]=p.useState([]),[o,c]=p.useState(!0),[d,m]=p.useState(!1),[h,x]=p.useState(null),[u,g]=p.useState({page:1,totalPages:1,totalRecords:0}),b=p.useRef(!0),f=p.useCallback(async(v=1)=>{const C=v===1&&b.current;try{C?c(!0):m(!0),x(null);const w=parseInt(t,10);if(isNaN(w)||w<1){x("Please enter a valid threshold (minimum 1 day)");return}const A=await Dt.getWorkflowAgingReport(w,v,j4,s,a,r),N=A.agingData.map(_=>({id:_.requestNumber||_.requestId,requestId:_.requestId,title:_.title,initiator:_.initiatorName||"Unknown",startDate:_.submissionDate?new Date(_.submissionDate).toLocaleDateString():"N/A",daysOpen:_.daysOpen,currentStage:_.currentStageName||`Level ${_.currentLevel}`,assignedTo:_.currentApproverName||"N/A",priority:_.priority||"medium",status:_.status||"pending"}));l(N),g({page:A.pagination.currentPage,totalPages:A.pagination.totalPages,totalRecords:A.pagination.totalRecords})}catch(w){console.error("Failed to fetch aging data:",w),x((w==null?void 0:w.message)||"Failed to load aging data")}finally{C?c(!1):m(!1)}C&&(b.current=!1)},[t,s,a,r]),y=p.useMemo(()=>i.filter(v=>{var w,A,N;if(!n)return!0;const C=n.toLowerCase();return((w=v.id)==null?void 0:w.toLowerCase().includes(C))||((A=v.title)==null?void 0:A.toLowerCase().includes(C))||((N=v.initiator)==null?void 0:N.toLowerCase().includes(C))}),[i,n]);return p.useEffect(()=>{s==="custom"&&(!a||!r)||f(1)},[t,s,a,r]),{agingWorkflows:y,loading:o,loadingPage:d,error:h,pagination:u,fetchData:f}}function w4(t="7"){const[s,a]=p.useState(t),[r,n]=p.useState(null),i=p.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=p.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 C4(t,s,a){const r=await Dt.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?xr(i.submissionDate):"N/A",c=i.closureDate?xr(i.closureDate):"N/A",d=i.overallTATHours||0,m=d>0?(d/8).toFixed(2):"0",h=i.totalLevels||1,x=Math.min(Math.max(1,i.currentLevel||1),h),u=(l==null?void 0:l.approvals)||[];if(u.length===0){const g=[i.requestNumber||"",`"${(i.title||"").replace(/"/g,'""')}"`,i.priority||"medium",i.status||"",`"${(i.initiatorName||"Unknown").replace(/"/g,'""')}"`,o,c,h.toString(),x.toString(),d.toString(),m,(i.breachCount||0).toString(),"N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A"];n.push(g.join(","))}else u.forEach(g=>{const b=g.levelStartTime?xr(g.levelStartTime):"N/A",f=g.levelEndTime||g.completedAt?xr(g.levelEndTime||g.completedAt):"N/A",y=g.tatHours||0,v=g.tatDays||(y>0?(y/8).toFixed(2):"0");let C="N/A",w="N/A",A="N/A",N="N/A";if(g.levelStartTime){const T=new Date(g.levelStartTime);if(w=(((g.levelEndTime||g.completedAt?new Date(g.levelEndTime||g.completedAt):new Date).getTime()-T.getTime())/(1e3*60*60)).toFixed(2),y>0){const E=parseFloat(w);A=Math.max(0,y-E).toFixed(2),N=(E/y*100).toFixed(2),g.status==="APPROVED"||g.status==="REJECTED"?C=E<=y?"Compliant":"Breached":g.status==="IN_PROGRESS"||g.status==="PENDING"?C=E<=y?"On Track":"At Risk":C="N/A"}}const _=[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(),(g.levelNumber||"").toString(),`"${(g.levelName||`Level ${g.levelNumber}`).replace(/"/g,'""')}"`,`"${(g.approverName||"N/A").replace(/"/g,'""')}"`,`"${(g.approverEmail||"N/A").replace(/"/g,'""')}"`,g.status||"PENDING",b,f,y.toString(),v.toString(),C,w,A,N];n.push(_.join(","))})}catch(l){console.error(`Failed to fetch details for request ${i.requestNumber}:`,l);const o=i.submissionDate?xr(i.submissionDate):"N/A",c=i.overallTATHours||0,d=c>0?(c/8).toFixed(2):"0",m=i.totalLevels||1,h=Math.min(Math.max(1,i.currentLevel||1),m),x=[i.requestNumber||"",`"${(i.title||"").replace(/"/g,'""')}"`,i.priority||"medium",i.status||"",`"${(i.initiatorName||"Unknown").replace(/"/g,'""')}"`,o,"N/A",m.toString(),h.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(x.join(","))}Sc(n,`lifecycle-report-end-to-end-${new Date().toISOString().split("T")[0]}.csv`)}async function S4(t,s,a,r,n){const i=await Dt.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=Qg(o.type||"",o.details),m=[o.timestamp?xr(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(","))}),Sc(l,`activity-log-report-${new Date().toISOString().split("T")[0]}.csv`)}async function A4(t,s,a,r){const n=await Dt.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?xr(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(","))}),Sc(i,`workflow-aging-report-${new Date().toISOString().split("T")[0]}.csv`)}function Sc(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 T4(){const[t,s]=p.useState(!1),[a,r]=p.useState(!1),[n,i]=p.useState(!1),l=p.useCallback(async(d,m,h)=>{try{s(!0),await C4(d,m,h)}catch(x){console.error("Failed to export lifecycle data:",x),alert("Failed to export lifecycle data. Please try again.")}finally{s(!1)}},[]),o=p.useCallback(async(d,m,h,x,u)=>{try{r(!0),await S4(d,m,h,x,u)}catch(g){console.error("Failed to export activity data:",g),alert("Failed to export activity data. Please try again.")}finally{r(!1)}},[]),c=p.useCallback(async(d,m,h,x)=>{try{i(!0),await A4(d,m,h,x)}catch(u){console.error("Failed to export aging data:",u),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 k4({onBack:t}){const s=Fs(),[a,r]=p.useState(""),[n,i]=p.useState("all"),[l,o]=p.useState("all"),c=Rl("month"),d=Rl("month"),m=Rl("month"),h=w4("7"),x=b4({dateRange:c.dateRange,customStartDate:c.customStartDate,customEndDate:c.customEndDate}),u=v4({dateRange:d.dateRange,customStartDate:d.customStartDate,customEndDate:d.customEndDate,filterCategory:n,filterSeverity:l}),g=N4({threshold:h.threshold,dateRange:m.dateRange,customStartDate:m.customStartDate,customEndDate:m.customEndDate,searchQuery:a}),b=T4(),f=p.useCallback(()=>{t?t():s("/dashboard")},[t,s]),y=p.useCallback(N=>{fi({requestId:N,navigate:s})},[s]),v=p.useCallback(()=>{b.handleExportLifecycle(c.dateRange,c.customStartDate,c.customEndDate)},[b,c]),C=p.useCallback(()=>{b.handleExportActivity(d.dateRange,d.customStartDate,d.customEndDate,n,l)},[b,d,n,l]),w=p.useCallback(()=>{const N=parseInt(h.threshold,10);!isNaN(N)&&N>=1&&b.handleExportAging(N,m.dateRange,m.customStartDate,m.customEndDate)},[b,h.threshold,m]),A=p.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(d4,{onBack:f}),e.jsx(x4,{lifecycleRequests:x.lifecycleRequests,loading:x.loading,loadingPage:x.loadingPage,error:x.error,pagination:x.pagination,dateRange:c.dateRange,customStartDate:c.customStartDate,customEndDate:c.customEndDate,showCustomDatePicker:c.showCustomDatePicker,tempCustomStartDate:c.tempCustomStartDate,tempCustomEndDate:c.tempCustomEndDate,exporting:b.exportingLifecycle,onDateRangeChange:c.handleDateRangeChange,onShowCustomDatePickerChange:c.setShowCustomDatePicker,onStartDateChange:c.handleStartDateChange,onEndDateChange:c.handleEndDateChange,onApplyCustomDate:c.handleApplyCustomDate,onCancelCustomDate:c.handleCancelCustomDate,onPageChange:x.fetchData,onExport:v,onViewRequest:y}),e.jsx(h4,{activityLog:u.activityLog,loading:u.loading,loadingPage:u.loadingPage,error:u.error,pagination:u.pagination,dateRange:d.dateRange,customStartDate:d.customStartDate,customEndDate:d.customEndDate,showCustomDatePicker:d.showCustomDatePicker,tempCustomStartDate:d.tempCustomStartDate,tempCustomEndDate:d.tempCustomEndDate,filterCategory:n,filterSeverity:l,exporting:b.exportingActivity,onDateRangeChange:d.handleDateRangeChange,onShowCustomDatePickerChange:d.setShowCustomDatePicker,onStartDateChange:d.handleStartDateChange,onEndDateChange:d.handleEndDateChange,onApplyCustomDate:d.handleApplyCustomDate,onCancelCustomDate:d.handleCancelCustomDate,onCategoryChange:i,onSeverityChange:o,onClearFilters:A,onPageChange:u.fetchData,onExport:C,onViewRequest:y}),e.jsx(p4,{agingWorkflows:g.agingWorkflows,loading:g.loading,loadingPage:g.loadingPage,error:g.error,pagination:g.pagination,threshold:h.threshold,thresholdError:h.thresholdError,dateRange:m.dateRange,customStartDate:m.customStartDate,customEndDate:m.customEndDate,showCustomDatePicker:m.showCustomDatePicker,tempCustomStartDate:m.tempCustomStartDate,tempCustomEndDate:m.tempCustomEndDate,searchQuery:a,exporting:b.exportingAging,onThresholdChange:h.handleThresholdChange,onThresholdBlur:h.handleThresholdBlur,onDateRangeChange:m.handleDateRangeChange,onShowCustomDatePickerChange:m.setShowCustomDatePicker,onStartDateChange:m.handleStartDateChange,onEndDateChange:m.handleEndDateChange,onApplyCustomDate:m.handleApplyCustomDate,onCancelCustomDate:m.handleCancelCustomDate,onSearchChange:r,onPageChange:g.fetchData,onExport:w,onViewRequest:y})]})})}function Wn({className:t,...s}){return e.jsx("div",{"data-slot":"skeleton",className:Ae("bg-accent animate-pulse rounded-md",t),...s})}function R4(){const t=Fs(),[s,a]=p.useState(()=>Wu()||[]),[r,n]=p.useState(()=>!Wu()),[i,l]=p.useState(""),o=async()=>{try{s.length===0&&n(!0);const m=await Oi();a(m||[])}catch(m){console.error("Failed to fetch templates:",m),K.error("Failed to load templates")}finally{n(!1)}};p.useEffect(()=>{o()},[]);const c=s.filter(m=>m.name.toLowerCase().includes(i.toLowerCase())||m.category.toLowerCase().includes(i.toLowerCase())),d=m=>{switch(m.toLowerCase()){case"high":return"bg-red-100 text-red-700 border-red-200";case"medium":return"bg-orange-100 text-orange-700 border-orange-200";case"low":return"bg-green-100 text-green-700 border-green-200";default:return"bg-gray-100 text-gray-700 border-gray-200"}};return e.jsxs("div",{className:"max-w-7xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold text-gray-900",children:"Admin Templates"}),e.jsx("p",{className:"text-gray-500",children:"Manage workflow templates for your organization"})]}),e.jsxs(F,{onClick:()=>t("/admin/create-template"),className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(gs,{className:"w-4 h-4 mr-2"}),"Create New Template"]})]}),e.jsx("div",{className:"flex items-center gap-4 bg-white p-4 rounded-lg border border-gray-200 shadow-sm",children:e.jsxs("div",{className:"relative flex-1 max-w-md",children:[e.jsx(Es,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Ie,{placeholder:"Search templates...",className:"pl-10 border-gray-200",value:i,onChange:m=>l(m.target.value)})]})}),r?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(m=>e.jsxs(se,{className:"h-48",children:[e.jsxs(ge,{children:[e.jsx(Wn,{className:"h-6 w-3/4 mb-2"}),e.jsx(Wn,{className:"h-4 w-1/2"})]}),e.jsxs(ae,{children:[e.jsx(Wn,{className:"h-4 w-full mb-2"}),e.jsx(Wn,{className:"h-4 w-2/3"})]})]},m))}):c.length===0?e.jsxs("div",{className:"text-center py-16 bg-white rounded-lg border border-dashed border-gray-300",children:[e.jsx("div",{className:"w-16 h-16 bg-gray-50 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(ke,{className:"w-8 h-8 text-gray-400"})}),e.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No templates found"}),e.jsx("p",{className:"text-gray-500 max-w-sm mx-auto mb-6",children:i?"Try adjusting your search terms":"Get started by creating your first workflow template"}),!i&&e.jsx(F,{onClick:()=>t("/admin/create-template"),variant:"outline",children:"Create Template"})]}):e.jsx("div",{className:"grid gap-6 md:grid-cols-2 lg:grid-cols-3",children:c.map(m=>{var h;return e.jsxs(se,{className:"hover:shadow-md transition-shadow duration-200 group",children:[e.jsxs(ge,{className:"pb-3",children:[e.jsxs("div",{className:"flex justify-between items-start gap-2",children:[e.jsx("div",{className:"p-2 bg-blue-50 rounded-lg text-blue-600 mb-2 w-fit",children:e.jsx(ke,{className:"w-5 h-5"})}),e.jsx(oe,{variant:"outline",className:d(m.priority),children:m.priority})]}),e.jsx(fe,{className:"line-clamp-1 text-lg",children:m.name}),e.jsx(Ue,{className:"line-clamp-3 min-h-[4.5rem]",children:m.description})]}),e.jsxs(ae,{children:[e.jsxs("div",{className:"text-sm text-gray-500 mb-4 space-y-1",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Category:"}),e.jsx("span",{className:"font-medium text-gray-900",children:m.category})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"SLA:"}),e.jsxs("span",{className:"font-medium text-gray-900",children:[m.suggestedSLA," hours"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Approvers:"}),e.jsxs("span",{className:"font-medium text-gray-900",children:[((h=m.approvers)==null?void 0:h.length)||0," levels"]})]})]}),e.jsx("div",{className:"flex gap-2 pt-2 border-t mt-2",children:e.jsxs(F,{variant:"outline",className:"flex-1 text-blue-600 hover:text-blue-700 hover:bg-blue-50 border-blue-100",onClick:()=>t(`/admin/edit-template/${m.id}`),children:[e.jsx(eb,{className:"w-4 h-4 mr-2"}),"Edit"]})})]})]},m.id)})})]})}function tx(){const t=Fs(),{templateId:s}=Fa(),a=!!s,[r,n]=p.useState(!1),[i,l]=p.useState(!1),{searchResults:o,searchLoading:c,searchUsersDebounced:d,clearSearch:m}=mg(),[h,x]=p.useState(""),[u,g]=p.useState({name:"",description:"",category:"General",priority:"medium",estimatedTime:"2 days",suggestedSLA:24,approvers:[]});p.useEffect(()=>{a&&s&&(async()=>{try{l(!0);const T=(await Oi()).find(R=>R.id===s);T?g({name:T.name,description:T.description,category:T.category,priority:T.priority,estimatedTime:T.estimatedTime,suggestedSLA:T.suggestedSLA,approvers:T.approvers||[]}):(K.error("Template not found"),t("/admin/templates"))}catch(_){console.error("Failed to load template:",_),K.error("Failed to load template details")}finally{l(!1)}})()},[a,s,t]);const b=N=>{const{name:_,value:T}=N.target;g(R=>({...R,[_]:T}))},f=(N,_)=>{g(T=>({...T,[N]:_}))},y=N=>{if(x(N),N.startsWith("@")&&N.slice(1).length>=1){d(N,5);return}m()},v=N=>{if(u.approvers.some(_=>_.userId===N.userId)){K.error("Approver already added");return}g(_=>({..._,approvers:[..._.approvers,{userId:N.userId,name:N.displayName||N.email,email:N.email,level:_.approvers.length+1,tat:24,tatType:"hours"}]})),x(""),m()},C=N=>{const _=[...u.approvers];_.splice(N,1),_.forEach((T,R)=>T.level=R+1),g(T=>({...T,approvers:_}))},w=async N=>{if(N.preventDefault(),!u.name||!u.description){K.error("Please fill in required fields");return}if(u.approvers.length===0){K.error("Please add at least one approver");return}const _={...u,approvers:u.approvers.map(T=>({...T,tat:T.tatType==="days"?parseInt(T.tat)*24:parseInt(T.tat)}))};try{n(!0),a&&s?(await qS(s,_),K.success("Template updated successfully")):(await QS(_),K.success("Template created successfully")),t("/admin/templates")}catch(T){K.error(a?"Failed to update template":"Failed to create template"),console.error(T)}finally{n(!1)}};if(i)return e.jsx("div",{className:"flex h-96 items-center justify-center",children:e.jsx(it,{className:"h-8 w-8 animate-spin text-gray-400"})});const A=u.name&&u.description&&u.approvers.length>0&&u.approvers.every(N=>{const _=parseInt(String(N.tat))||0,T=N.tatType==="days"?7:24;return _>=1&&_<=T});return e.jsxs("div",{className:"max-w-4xl mx-auto p-6 space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[e.jsx(F,{variant:"ghost",size:"icon",onClick:()=>t("/admin/templates"),children:e.jsx(Cs,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold text-gray-900",children:a?"Edit Workflow Template":"Create Workflow Template"}),e.jsx("p",{className:"text-gray-500",children:a?"Update existing workflow configuration":"Define a new standardized request workflow"})]})]}),e.jsxs("form",{onSubmit:w,className:"space-y-6",children:[e.jsxs(se,{children:[e.jsxs(ge,{children:[e.jsx(fe,{children:"Basic Information"}),e.jsx(Ue,{children:"General details about the template"})]}),e.jsxs(ae,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"name",children:"Template Name *"}),e.jsx(Ie,{id:"name",name:"name",placeholder:"e.g., Office Stationery Request",value:u.name,onChange:b,className:"border-gray-200",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"category",children:"Category"}),e.jsx("div",{className:"relative",children:e.jsx(Ie,{id:"category",name:"category",placeholder:"e.g., Admin, HR, Finance",value:u.category,onChange:b,className:"border-gray-200"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"description",children:"Description *"}),e.jsx(_s,{id:"description",name:"description",placeholder:"Describe what this request is for...",value:u.description,onChange:b,className:"border-gray-200",required:!0})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"priority",children:"Default Priority"}),e.jsxs(Ke,{name:"priority",value:u.priority,onValueChange:N=>f("priority",N),children:[e.jsx(Ze,{children:e.jsx(Xe,{placeholder:"Select priority"})}),e.jsxs(Je,{children:[e.jsx(Y,{value:"low",children:"Low"}),e.jsx(Y,{value:"medium",children:"Medium"}),e.jsx(Y,{value:"high",children:"High"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"estimatedTime",children:"Estimated Time"}),e.jsx(Ie,{id:"estimatedTime",name:"estimatedTime",placeholder:"e.g., 2 days",value:u.estimatedTime,onChange:b,className:"border-gray-200"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"suggestedSLA",children:"SLA (Hours)"}),e.jsx(Ie,{id:"suggestedSLA",name:"suggestedSLA",type:"number",placeholder:"24",value:u.suggestedSLA,onChange:b,className:"border-gray-200"})]})]})]})]}),e.jsxs(se,{children:[e.jsxs(ge,{children:[e.jsx(fe,{children:"Approver Workflow"}),e.jsx(Ue,{children:"Define static approvers for this template"})]}),e.jsxs(ae,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[u.approvers.map((N,_)=>e.jsxs("div",{className:"flex items-center gap-4 p-3 bg-gray-50 rounded-lg border border-gray-100",children:[e.jsxs(oe,{variant:"outline",className:"bg-white",children:["Level ",N.level]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-gray-900",children:N.name}),e.jsx("div",{className:"text-sm text-gray-500",children:N.email})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(ne,{htmlFor:`tat-${_}`,className:"text-xs whitespace-nowrap",children:"TAT"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ie,{id:`tat-${_}`,type:"number",className:"h-8 w-16 border-gray-200",value:N.tat||"",min:1,max:N.tatType==="days"?7:24,placeholder:N.tatType==="days"?"1":"24",onChange:T=>{if((parseInt(T.target.value)||0)<0)return;const j=[...u.approvers];j[_].tat=T.target.value,g(E=>({...E,approvers:j}))}}),e.jsxs(Ke,{value:N.tatType||"hours",onValueChange:T=>{const R=[...u.approvers];R[_].tatType=T,R[_].tat=1,g(j=>({...j,approvers:R}))},children:[e.jsx(Ze,{className:"h-8 w-20 text-xs px-2",children:e.jsx(Xe,{})}),e.jsxs(Je,{children:[e.jsx(Y,{value:"hours",children:"Hours"}),e.jsx(Y,{value:"days",children:"Days"})]})]})]})]})}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",onClick:()=>C(_),children:e.jsx(ft,{className:"w-4 h-4 text-gray-500 hover:text-red-600"})})]},_)),u.approvers.length===0&&e.jsx("div",{className:"text-center p-8 border-2 border-dashed rounded-lg text-gray-500 text-sm",children:"No approvers defined. Requests will be auto-approved or require manual assignment."})]}),e.jsxs("div",{className:"space-y-2 relative",children:[e.jsx(ne,{children:"Add Approver"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(Ie,{placeholder:"Type '@' to search user by name or email...",value:h,onChange:N=>y(N.target.value),className:"border-gray-200"})}),(c||o.length>0)&&e.jsxs("div",{className:"absolute top-full left-0 right-0 mt-1 bg-white border rounded-lg shadow-lg z-10 max-h-60 overflow-y-auto",children:[c&&e.jsx("div",{className:"p-2 text-sm text-gray-500",children:"Searching..."}),o.map(N=>e.jsxs("div",{className:"p-2 hover:bg-gray-50 cursor-pointer flex items-center gap-3",onClick:()=>v(N),children:[e.jsx(ts,{className:"h-8 w-8",children:e.jsx(ss,{children:(N.displayName||"U").substring(0,2)})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:N.displayName}),e.jsx("div",{className:"text-xs text-gray-500",children:N.email})]})]},N.userId))]})]}),u.approvers.length>0&&e.jsx("div",{className:"mt-6 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(nt,{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:(()=>{const N=u.approvers.reduce((T,R)=>{const j=Number(R.tat||0);return(R.tatType||"hours")==="days"?T+j:T+j/24},0)||0,_=Math.ceil(N);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-lg font-bold text-emerald-800",children:[_," ",_===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:u.approvers.map((N,_)=>{const T=Number(N.tat||0),j=(N.tatType||"hours")==="days"?T*24:T;return T?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 ",_+1]}),e.jsxs("span",{className:"text-sm text-emerald-700",children:[j," ",j===1?"hour":"hours"]})]})},_):null})}),(()=>{const N=u.approvers.reduce((T,R)=>{const j=Number(R.tat||0);return(R.tatType||"hours")==="days"?T+j*24:T+j},0)||0,_=Math.ceil(N/8);return N===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:[N,"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:_}),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"})]})})()]})]})]})})]})]}),e.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[e.jsx(F,{type:"button",variant:"outline",onClick:()=>t("/admin/templates"),children:"Cancel"}),e.jsx(F,{type:"submit",disabled:r||!A,className:"bg-re-green hover:bg-re-green/90",children:r?"Saving...":e.jsxs(e.Fragment,{children:[e.jsx(Mx,{className:"w-4 h-4 mr-2"}),a?"Update Template":"Create Template"]})})]})]})]})}function D4({template:t,formData:s,setFormData:a,documents:r,setDocuments:n}){const i=p.useRef(null),[l,o]=p.useState(null),c=u=>{u.target.files&&u.target.files.length>0&&n([...r,...Array.from(u.target.files)])},d=u=>{const g=[...r];g.splice(u,1),n(g)},m=u=>{const g=URL.createObjectURL(u);o({file:u,url:g})},h=()=>{l!=null&&l.url&&URL.revokeObjectURL(l.url),o(null)},x=u=>u.type.includes("image")||u.type.includes("pdf");return e.jsxs("div",{className:"space-y-6 max-w-4xl mx-auto",children:[e.jsx(se,{className:"shadow-sm",children:e.jsxs(ae,{className:"pt-6",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("h2",{className:"text-xl font-bold text-gray-800",children:t.name}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:t.description})]}),e.jsxs("div",{className:"flex gap-4 text-sm text-gray-600 bg-gray-50 p-3 rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"font-semibold",children:"Category:"})," ",t.category]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"font-semibold",children:"Priority:"}),e.jsx("span",{className:"capitalize",children:t.priority})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"font-semibold",children:"SLA:"})," ",t.suggestedSLA," Hours"]})]})]})}),e.jsx(se,{children:e.jsxs(ae,{className:"pt-6 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"requestTitle",children:"Request Title *"}),e.jsx(Ie,{id:"requestTitle",value:s.title,onChange:u=>a({...s,title:u.target.value}),placeholder:`Request for ${t.name}`,className:"border-gray-200"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"justification",className:"text-base font-semibold",children:"Request Detail *"}),e.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Explain what you need approval for, why it's needed, and any relevant details."}),e.jsx(Pn,{value:s.description||"",onChange:u=>a({...s,description:u}),placeholder:"Provide comprehensive details about your request...",className:"min-h-[120px] text-base border-gray-200 bg-white shadow-sm",minHeight:"120px"})]})]})}),e.jsx(se,{children:e.jsxs(ae,{className:"pt-6 space-y-4",children:[e.jsx(ne,{children:"Supporting Documents"}),e.jsxs("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:bg-gray-50 transition-colors cursor-pointer",onClick:()=>{var u;return(u=i.current)==null?void 0:u.click()},children:[e.jsx(Ks,{className:"w-10 h-10 text-gray-400 mx-auto mb-3"}),e.jsx("p",{className:"text-sm font-medium text-gray-700",children:"Click to upload files"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"PDF, Excel, Images (Max 10MB)"}),e.jsx("input",{ref:i,type:"file",multiple:!0,className:"hidden",onChange:c})]}),r.length>0&&e.jsx("div",{className:"grid grid-cols-1 gap-2 mt-4",children:r.map((u,g)=>e.jsxs("div",{className:"flex items-center justify-between p-3 bg-white border rounded-lg shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-50 rounded-lg flex items-center justify-center",children:e.jsx(ke,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-800 truncate max-w-[200px]",children:u.name}),e.jsxs("p",{className:"text-xs text-gray-500",children:[(u.size/1024/1024).toFixed(2)," MB"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[x(u)&&e.jsx(F,{variant:"ghost",size:"icon",onClick:()=>m(u),children:e.jsx(bt,{className:"w-4 h-4 text-gray-500 hover:text-blue-600"})}),e.jsx(F,{variant:"ghost",size:"icon",onClick:()=>d(g),children:e.jsx(ft,{className:"w-4 h-4 text-gray-500 hover:text-red-500"})})]})]},g))})]})}),l&&e.jsx(Nr,{fileName:l.file.name,fileType:l.file.type,fileUrl:l.url,fileSize:l.file.size,open:!!l,onClose:h})]})}function P4({template:t,formData:s,documents:a}){const r=t.workflowApprovers||[];return e.jsxs("div",{className:"space-y-6 max-w-4xl mx-auto",children:[e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start gap-3",children:[e.jsx(Ye,{className:"w-5 h-5 text-blue-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-blue-900",children:"Ready to Submit?"}),e.jsx("p",{className:"text-sm text-blue-700 mt-1",children:"Please review the details below. This request will follow the standardized approval workflow defined by the administrator."})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[e.jsxs(se,{children:[e.jsx(ge,{className:"pb-3",children:e.jsx(fe,{className:"text-lg",children:"Request Overview"})}),e.jsx(ae,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Title"}),e.jsx("p",{className:"text-base font-medium text-gray-900 mt-1",children:s.title})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Request Detail"}),e.jsx("div",{className:"text-sm text-gray-700 mt-1 prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:va(s.description)}})]}),a.length>0&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider block mb-2",children:["Attachments (",a.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map((n,i)=>e.jsxs(oe,{variant:"secondary",className:"pl-1 pr-2 py-1 flex items-center gap-1.5 h-auto",children:[e.jsx(ke,{className:"w-3 h-3 text-gray-500"}),e.jsx("span",{className:"truncate max-w-[150px]",children:n.name})]},i))})]})]})})]}),e.jsxs(se,{children:[e.jsx(ge,{className:"pb-3",children:e.jsx(fe,{className:"text-lg",children:"Approval Workflow"})}),e.jsx(ae,{children:e.jsx("div",{className:"relative pl-6 border-l-2 border-gray-100 space-y-8 py-2",children:r.map((n,i)=>e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute -left-[31px] top-1 w-4 h-4 rounded-full bg-white border-2 border-blue-500 flex items-center justify-center",children:e.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-blue-500"})}),e.jsxs("div",{className:"bg-gray-50 rounded-lg p-3 border border-gray-100",children:[e.jsxs("div",{className:"flex justify-between items-start mb-1",children:[e.jsxs("div",{children:[e.jsx("h5",{className:"font-semibold text-gray-800 text-sm",children:n.name||n.email}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Level ",n.level," Approver"]})]}),e.jsxs(oe,{variant:"outline",className:"bg-white text-xs",children:[n.tat||24," Hours TAT"]})]}),e.jsx("p",{className:"text-xs text-gray-400",children:n.email})]})]},i))})})]})]}),e.jsx("div",{className:"space-y-6",children:e.jsxs(se,{children:[e.jsx(ge,{className:"pb-3",children:e.jsx(fe,{className:"text-sm uppercase text-gray-500",children:"Properties"})}),e.jsxs(ae,{className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Template"}),e.jsx("span",{className:"text-sm font-medium text-right",children:t.name})]}),e.jsx(Ps,{}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Priority"}),e.jsx(oe,{className:t.priority==="high"?"bg-red-100 text-red-700 hover:bg-red-100":t.priority==="medium"?"bg-orange-100 text-orange-700 hover:bg-orange-100":"bg-green-100 text-green-700 hover:bg-green-100",children:t.priority.toUpperCase()})]}),e.jsx(Ps,{}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Est. Time"}),e.jsx("span",{className:"text-sm text-gray-900",children:t.estimatedTime})]})]})]})})]})]})}function I4(){const{templateId:t}=Fa(),s=Fs(),{user:a}=Jt(),[r,n]=p.useState(!0),[i,l]=p.useState(!1),[o,c]=p.useState(null),[d,m]=p.useState(1),[h,x]=p.useState([]),[u,g]=p.useState({title:"",description:""}),b=["Request Details","Review & Submit"];p.useEffect(()=>{t&&(async()=>{try{n(!0);const C=(await Oi()).find(w=>w.id===t);if(C){const w={id:C.id,name:C.name,description:C.description,category:C.category,icon:ke,estimatedTime:C.estimatedTime,commonApprovers:C.approvers.map(A=>A.name),workflowApprovers:C.approvers,suggestedSLA:C.suggestedSLA,priority:C.priority,fields:C.fields||{}};c(w),g({title:w.name,description:w.description})}else K.error("Template not found")}catch(v){console.error("Error loading template:",v),K.error("Failed to load template details")}finally{n(!1)}})()},[t,s]);const f=async()=>{var y;if(o)try{l(!0);const v={templateId:o.id,templateType:"TEMPLATE",title:u.title,description:u.description,priorityUi:o.priority==="high"?"express":"standard",approverCount:((y=o.workflowApprovers)==null?void 0:y.length)||0,approvers:(o.workflowApprovers||[]).map(w=>({email:w.email,name:w.name,tat:w.tat,tatType:"hours"})),spectators:[],ccList:[]},C=await _o(v,h);C&&C.id&&await Ah(C.id),K.success("Request Submitted Successfully",{description:`Your request "${u.title}" has been created.`}),s("/my-requests")}catch(v){console.error("Submission failed:",v),K.error("Failed to submit request")}finally{l(!1)}};return r?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"})}):o?e.jsxs("div",{className:"h-screen flex flex-col bg-gray-50 overflow-hidden",children:[e.jsxs("header",{className:"bg-white border-b flex-shrink-0 z-10",children:[e.jsxs("div",{className:"max-w-7xl mx-auto px-6 py-4 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(F,{variant:"ghost",size:"icon",onClick:()=>s("/new-request"),children:e.jsx(Cs,{className:"w-5 h-5 text-gray-500"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-bold text-gray-900",children:"New Request"}),e.jsx("p",{className:"text-sm text-gray-500",children:o.name})]})]}),e.jsx(F,{variant:"outline",onClick:()=>s("/dashboard"),children:"Cancel Request"})]}),e.jsx(dg,{currentStep:d,totalSteps:2,stepNames:b})]}),e.jsx("main",{className:"flex-1 overflow-y-auto py-8 px-6 bg-gray-50/50",children:e.jsx("div",{className:"max-w-4xl mx-auto",children:d===1?e.jsx(D4,{template:o,formData:u,setFormData:g,documents:h,setDocuments:x}):e.jsx(P4,{template:o,formData:u,documents:h})})}),e.jsx("footer",{className:"bg-white border-t px-6 py-4 flex-shrink-0 z-10",children:e.jsxs("div",{className:"max-w-4xl mx-auto flex items-center justify-between",children:[e.jsx(F,{variant:"outline",onClick:()=>d===1?s("/new-request"):m(1),disabled:i,children:d===1?"Cancel":"Back to Details"}),e.jsx(F,{onClick:()=>d===1?m(2):f(),disabled:i,className:"bg-re-green hover:bg-re-green/90",children:d===1?e.jsxs(e.Fragment,{children:["Review Request ",e.jsx(vi,{className:"w-4 h-4 ml-1"})]}):e.jsxs(e.Fragment,{children:[i?"Submitting...":"Submit Request"," ",e.jsx(Ra,{className:"w-4 h-4 ml-1"})]})})]})})]}):e.jsx("div",{className:"min-h-screen bg-gray-50 flex flex-col items-center justify-center p-4",children:e.jsxs("div",{className:"bg-white p-8 rounded-lg shadow-md max-w-md w-full text-center",children:[e.jsx("div",{className:"w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(ke,{className:"w-8 h-8 text-red-600"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Template Not Found"}),e.jsx("p",{className:"text-gray-600 mb-6",children:"The requested template could not be loaded. It may have been deleted or you do not have permission to view it."}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsx(F,{variant:"outline",onClick:()=>s("/dashboard"),children:"Go to Dashboard"}),e.jsx(F,{onClick:()=>s("/new-request"),children:"Browse Templates"})]})]})})}function E4({isOpen:t,onClose:s,action:a,requestId:r,requestTitle:n,onSubmit:i}){const[l,o]=p.useState(""),[c,d]=p.useState(!1),m=async()=>{if(!(!l.trim()||l.length>500)){d(!0);try{await i(a,l.trim()),o(""),s()}catch(b){console.error("Error submitting approval action:",b)}finally{d(!1)}}},h=()=>{o(""),s()},u=a==="approve"?{title:"Approve Request",description:"Please provide your approval comments and remarks",icon:Re,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:Ct,iconColor:"text-red-600",buttonColor:"bg-red-600 hover:bg-red-700",badgeColor:"bg-red-100 text-red-800 border-red-200",placeholder:"Enter detailed reasons for rejection and any suggestions for improvement..."},g=u.icon;return e.jsx(ht,{open:t,onOpenChange:h,children:e.jsxs(dt,{className:"max-w-2xl bg-white",children:[e.jsxs(pt,{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:`p-2 rounded-lg ${a==="approve"?"bg-green-100":"bg-red-100"}`,children:e.jsx(g,{className:`w-6 h-6 ${u.iconColor}`})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(mt,{className:"text-xl",children:u.title}),e.jsx(Pt,{className:"mt-1",children:u.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(oe,{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(oe,{className:u.badgeColor,variant:"outline",children:[e.jsx(g,{className:"w-3 h-3 mr-1"}),a==="approve"?"APPROVE":"REJECT"]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"comment",className:"text-sm font-semibold text-gray-900",children:"Comments & Remarks *"}),e.jsx(_s,{id:"comment",placeholder:u.placeholder,value:l,onChange:b=>o(b.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(os,{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(os,{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(Re,{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(Rt,{className:"gap-2",children:[e.jsx(F,{variant:"outline",onClick:h,disabled:c,children:"Cancel"}),e.jsx(F,{onClick:m,disabled:!l.trim()||c||l.length>500,className:u.buttonColor,children:c?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin mr-2"}),"Processing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(g,{className:"w-4 h-4 mr-2"}),a==="approve"?"Approve Request":"Reject Request"]})})]})]})})}var F4=(t,s,a,r,n,i,l,o)=>{let c=document.documentElement,d=["light","dark"];function m(u){(Array.isArray(t)?t:[t]).forEach(g=>{let b=g==="class",f=b&&i?n.map(y=>i[y]||y):n;b?(c.classList.remove(...f),c.classList.add(i&&i[u]?i[u]:u)):c.setAttribute(g,u)}),h(u)}function h(u){o&&d.includes(u)&&(c.style.colorScheme=u)}function x(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}if(r)m(r);else try{let u=localStorage.getItem(s)||a,g=l&&u==="system"?x():u;m(g)}catch{}},_4=p.createContext(void 0),L4={setTheme:t=>{},themes:[]},M4=()=>{var t;return(t=p.useContext(_4))!=null?t:L4};p.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 p.createElement("script",{...d,suppressHydrationWarning:!0,nonce:typeof window>"u"?c:"",dangerouslySetInnerHTML:{__html:`(${F4.toString()})(${m})`}})});const $4=({...t})=>{const{theme:s="system"}=M4();return e.jsx(tb,{theme:s,className:"toaster group",style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)"},...t})};function O4({open:t,onClose:s,onSelect:a,managers:r=[],errorType:n,message:i,isLoading:l=!1}){const o=c=>{a(c)};return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-[600px]",children:[e.jsxs(pt,{children:[e.jsx(mt,{className:"flex items-center gap-2",children:n==="NO_MANAGER_FOUND"?e.jsxs(e.Fragment,{children:[e.jsx(Ye,{className:"w-5 h-5 text-amber-500"}),"Manager Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ws,{className:"w-5 h-5 text-blue-500"}),"Select Your Manager"]})}),e.jsx(Pt,{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(Ye,{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(Gt,{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(Da,{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(xo,{className:"w-4 h-4"}),e.jsx("span",{children:c.department})]})]})]})]}),e.jsx(F,{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(F,{onClick:s,variant:"outline",children:"Close"}):e.jsx(e.Fragment,{children:e.jsx(F,{onClick:s,variant:"outline",disabled:l,children:"Cancel"})})})]})})}function U4({onViewRequest:t}){const{user:s}=Jt();return Di(s)?e.jsx(wk,{onViewRequest:t}):e.jsx(Ak,{onViewRequest:t})}function sx({onNavigate:t,onNewRequest:s}){const[a,r]=p.useState(!1),[n,i]=p.useState(!0);return p.useEffect(()=>{try{const l=st.getUserData();r((l==null?void 0:l.jobTitle)==="Dealer")}catch(l){console.error("[App] Error checking dealer status:",l),r(!1)}finally{i(!1)}},[]),n?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("div",{className:"w-8 h-8 animate-spin rounded-full border-4 border-blue-600 border-t-transparent"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading..."})]})}):a?e.jsx(YT,{onNavigate:t,onNewRequest:s}):e.jsx(nN,{onNavigate:t,onNewRequest:s})}function B4({onLogout:t}){const s=Fs(),[a,r]=p.useState(null),[n,i]=p.useState([]),[l,o]=p.useState(""),[c,d]=p.useState(""),[m,h]=p.useState(!1),[x,u]=p.useState(null);p.useEffect(()=>{const N=localStorage.getItem("dynamicRequests");if(N)try{const _=JSON.parse(N);i(_)}catch(_){console.error("Error parsing dynamic requests:",_)}},[]),p.useEffect(()=>{n.length>0&&localStorage.setItem("dynamicRequests",JSON.stringify(n))},[n]);const g=N=>{if(N==="profile"){s("/profile");return}if(N==="settings"){s("/settings");return}N.startsWith("/")?s(N):s(`/${N}`)},b=(N,_,T,R)=>{o(N),d(_||"Unknown Request"),fi({requestId:N,status:T,request:R,navigate:s})},f=()=>{s(-1)},y=()=>{s("/new-request")},v=N=>{var R,j,E,P,B,k,L,V,D,S,O;if(N.templateType){N.templateType==="claim-management"&&s("/claim-management");return}if(N.backendId){s("/my-requests");return}const T={id:`RE-REQ-2024-${String(n.length+1).padStart(3,"0")}`,title:N.title,description:N.description||"",category:N.category||"General",subcategory:N.subcategory||"",status:"pending",priority:N.priority||"standard",amount:N.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=N.approvers)==null?void 0:R.length)||1,currentApprover:((E=(j=N.approvers)==null?void 0:j[0])==null?void 0:E.name)||((k=(B=(P=N.approvers)==null?void 0:P[0])==null?void 0:B.email)==null?void 0:k.split("@")[0])||"Pending Assignment",approverLevel:`1 of ${((L=N.approvers)==null?void 0:L.length)||1}`,template:"custom",initiator:{name:"Current User",role:N.initiatorRole||"Employee",department:N.department||"General",email:"current.user@royalenfield.com",phone:"+91 98765 43290",avatar:"CU"},department:N.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:(N.approvers||[]).filter(I=>I).map((I,M)=>{var re;const W=(I==null?void 0:I.name)||((re=I==null?void 0:I.email)==null?void 0:re.split("@")[0])||`Approver ${M+1}`,G=(I==null?void 0:I.email)||"";return{step:M+1,approver:`${W}${G?` (${G})`:""}`,role:(I==null?void 0:I.role)||`Level ${(I==null?void 0:I.level)||M+1} Approver`,status:M===0?"pending":"waiting",tatHours:I!=null&&I.tat?typeof I.tat=="string"?parseInt(I.tat):I.tat:48,elapsedHours:0,assignedAt:M===0?new Date().toISOString():null,comment:null,timestamp:null}}),documents:[],spectators:(N.spectators||[]).filter(I=>I&&(I.name||I.email)).map(I=>{var W;const M=(I==null?void 0:I.name)||((W=I==null?void 0:I.email)==null?void 0:W.split("@")[0])||"Observer";return{name:M,role:(I==null?void 0:I.role)||(I==null?void 0:I.department)||"Observer",avatar:M.split(" ").map(G=>G[0]).join("").toUpperCase().slice(0,2)||"OB"}}),auditTrail:[{type:"created",action:"Request Created",details:`Custom request "${N.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 ${((D=(V=N.approvers)==null?void 0:V[0])==null?void 0:D.name)||((O=(S=N.approvers)==null?void 0:S[0])==null?void 0:O.email)||"first approver"}`,user:"System",timestamp:new Date().toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0})}],tags:N.tags||["custom-request"]};i([...n,T]),s("/my-requests")},C=(N,_)=>new Promise(T=>{setTimeout(()=>{N==="approve"?K.success("Request Approved",{description:"The request has been approved and forwarded to the next step.",duration:5e3}):K.error("Request Rejected",{description:"The request has been rejected and returned to the initiator.",duration:5e3}),r(null),T(!0)},1e3)}),w=()=>{r(null)},A=async(N,_)=>{var T,R,j,E,P,B,k;try{const L={activityName:N.activityName,activityType:N.activityType,dealerCode:N.dealerCode,dealerName:N.dealerName,dealerEmail:N.dealerEmail||void 0,dealerPhone:N.dealerPhone||void 0,dealerAddress:N.dealerAddress||void 0,activityDate:N.activityDate?new Date(N.activityDate).toISOString():void 0,location:N.location,requestDescription:N.requestDescription,periodStartDate:N.periodStartDate?new Date(N.periodStartDate).toISOString():void 0,periodEndDate:N.periodEndDate?new Date(N.periodEndDate).toISOString():void 0,estimatedBudget:N.estimatedBudget||void 0,approvers:N.approvers||[]},V=await yT(L);if(!V||!V.request)throw new Error("Invalid response from server: Request object not found");const D=V.request;if(!D.requestNumber&&!D.requestId)throw new Error("Invalid response from server: Request identifier not found");h(!1),u(null),K.success("Claim Request Submitted",{description:"Your claim management request has been created successfully."}),D.requestNumber?s(`/request/${D.requestNumber}`):D.requestId?s(`/request/${D.requestId}`):s("/my-requests")}catch(L){console.error("[App] Error creating claim request:",L);const V=(T=L==null?void 0:L.response)==null?void 0:T.data,D=(V==null?void 0:V.code)||((R=V==null?void 0:V.error)==null?void 0:R.code);if(D==="NO_MANAGER_FOUND"){u({errorType:"NO_MANAGER_FOUND",message:(V==null?void 0:V.message)||((j=V==null?void 0:V.error)==null?void 0:j.message)||"No reporting manager found. Please ensure your manager is correctly configured in the system.",pendingClaimData:N}),h(!0);return}if(D==="MULTIPLE_MANAGERS_FOUND"){const O=(V==null?void 0:V.managers)||((E=V==null?void 0:V.error)==null?void 0:E.managers)||[];u({errorType:"MULTIPLE_MANAGERS_FOUND",managers:O,message:(V==null?void 0:V.message)||((P=V==null?void 0:V.error)==null?void 0:P.message)||"Multiple managers found. Please select one.",pendingClaimData:N}),h(!0);return}const S=((k=(B=L==null?void 0:L.response)==null?void 0:B.data)==null?void 0:k.message)||(L==null?void 0:L.message)||"Failed to create claim request";K.error("Failed to Submit Claim Request",{description:S})}};return e.jsxs("div",{className:"min-h-screen h-screen flex flex-col overflow-hidden bg-background",children:[e.jsxs(nb,{children:[e.jsx(_t,{path:"/login/callback",element:e.jsx(Qx,{})}),e.jsx(_t,{path:"/",element:e.jsx(vs,{currentPage:"dashboard",onNavigate:g,onNewRequest:y,onLogout:t,children:e.jsx(sx,{onNavigate:g,onNewRequest:y})})}),e.jsx(_t,{path:"/dashboard",element:e.jsx(vs,{currentPage:"dashboard",onNavigate:g,onNewRequest:y,onLogout:t,children:e.jsx(sx,{onNavigate:g,onNewRequest:y})})}),e.jsxs(_t,{element:e.jsx(vs,{currentPage:"admin-templates",onNavigate:g,onNewRequest:y,onLogout:t,children:e.jsx(ib,{})}),children:[e.jsx(_t,{path:"/admin/create-template",element:e.jsx(tx,{})}),e.jsx(_t,{path:"/admin/edit-template/:templateId",element:e.jsx(tx,{})}),e.jsx(_t,{path:"/admin/templates",element:e.jsx(R4,{})})]}),e.jsx(_t,{path:"/create-admin-request/:templateId",element:e.jsx(I4,{})}),e.jsx(_t,{path:"/open-requests",element:e.jsx(vs,{currentPage:"open-requests",onNavigate:g,onNewRequest:y,onLogout:t,children:e.jsx(a5,{onViewRequest:b})})}),e.jsx(_t,{path:"/closed-requests",element:e.jsx(vs,{currentPage:"closed-requests",onNavigate:g,onNewRequest:y,onLogout:t,children:e.jsx(S5,{onViewRequest:b})})}),e.jsx(_t,{path:"/shared-summaries",element:e.jsx(vs,{currentPage:"shared-summaries",onNavigate:g,onNewRequest:y,onLogout:t,children:e.jsx(I5,{})})}),e.jsx(_t,{path:"/shared-summaries/:sharedSummaryId",element:e.jsx(vs,{currentPage:"shared-summaries",onNavigate:g,onNewRequest:y,onLogout:t,children:e.jsx(E5,{})})}),e.jsx(_t,{path:"/my-requests",element:e.jsx(vs,{currentPage:"my-requests",onNavigate:g,onNewRequest:y,onLogout:t,children:e.jsx(Q5,{onViewRequest:b,dynamicRequests:n})})}),e.jsx(_t,{path:"/requests",element:e.jsx(vs,{currentPage:"requests",onNavigate:g,onNewRequest:y,onLogout:t,children:e.jsx(U4,{onViewRequest:b})})}),e.jsx(_t,{path:"/approver-performance",element:e.jsx(vs,{currentPage:"approver-performance",onNavigate:g,onNewRequest:y,onLogout:t,children:e.jsx(Uk,{})})}),e.jsx(_t,{path:"/request/:requestId",element:e.jsx(vs,{currentPage:"request-detail",onNavigate:g,onNewRequest:y,onLogout:t,children:e.jsx(P5,{requestId:"",onBack:f,dynamicRequests:n})})}),e.jsx(_t,{path:"/work-notes/:requestId",element:e.jsx(F5,{})}),e.jsx(_t,{path:"/new-request",element:e.jsx(Xu,{onBack:f,onSubmit:v})}),e.jsx(_t,{path:"/edit-request/:requestId",element:e.jsx(Xu,{onBack:f,onSubmit:v,requestId:void 0,isEditMode:!0})}),e.jsx(_t,{path:"/claim-management",element:e.jsx(LT,{onBack:f,onSubmit:A})}),e.jsx(_t,{path:"/profile",element:e.jsx(vs,{currentPage:"profile",onNavigate:g,onNewRequest:y,onLogout:t,children:e.jsx(Bk,{})})}),e.jsx(_t,{path:"/settings",element:e.jsx(vs,{currentPage:"settings",onNavigate:g,onNewRequest:y,onLogout:t,children:e.jsx(s4,{})})}),e.jsx(_t,{path:"/settings/security",element:e.jsx(vs,{currentPage:"settings",onNavigate:g,onNewRequest:y,onLogout:t,children:e.jsx(o4,{})})}),e.jsx(_t,{path:"/notifications",element:e.jsx(vs,{currentPage:"notifications",onNavigate:g,onNewRequest:y,onLogout:t,children:e.jsx(c4,{onNavigate:g})})}),e.jsx(_t,{path:"/detailed-reports",element:e.jsx(vs,{currentPage:"detailed-reports",onNavigate:g,onNewRequest:y,onLogout:t,children:e.jsx(k4,{})})})]}),e.jsx($4,{position:"top-right",toastOptions:{style:{background:"var(--card)",color:"var(--card-foreground)",border:"1px solid var(--border)"}}}),e.jsx(O4,{open:m,onClose:()=>{h(!1),u(null)},onSelect:async N=>{x!=null&&x.pendingClaimData&&await A(x.pendingClaimData)},managers:x==null?void 0:x.managers,errorType:(x==null?void 0:x.errorType)||"NO_MANAGER_FOUND",message:x==null?void 0:x.message,isLoading:!1}),a&&e.jsx(E4,{isOpen:!!a,onClose:w,action:a,requestId:l,requestTitle:c,onSubmit:C})]})}function V4(t){const{onLogout:s}=t||{};return e.jsx(rb,{children:e.jsx(B4,{onLogout:s})})}function z4(){const{isAuthenticated:t,isLoading:s,error:a,user:r,logout:n}=Jt(),[i,l]=p.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(p.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"),h=d==null?void 0:d.get("error");if(!m&&!h){console.log("🚪 AuthenticatedApp: Logout redirect detected, redirecting to home");const u=new URLSearchParams;return u.set("tanflow_logged_out","true"),u.set("logout",Date.now().toString()),window.location.replace(`/?${u.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(Ty,{}):e.jsx(Qx,{})}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(V4,{onLogout:c}),i&&e.jsx(Ry,{isOpen:i,onClose:()=>l(!1)})]}):e.jsx(Ay,{})}const ti=()=>{try{return!0}catch{return!1}},H4=()=>{if(ti())return null;try{return localStorage.getItem("token")}catch{return null}},G4={user:null,token:H4(),isAuthenticated:!1,isLoading:!1,error:null},qg=Gr({name:"auth",initialState:G4,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,!ti())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,!ti())try{localStorage.removeItem("token")}catch{}},logout:t=>{if(t.isAuthenticated=!1,t.user=null,t.token=null,t.error=null,!ti())try{localStorage.removeItem("token")}catch{}},clearError:t=>{t.error=null},updateUser:(t,s)=>{t.user=s.payload}}}),{loginStart:rR,loginSuccess:nR,loginFailure:iR,logout:lR,clearError:oR,updateUser:cR}=qg.actions,W4=ab({reducer:{auth:qg.reducer,dashboard:ch.reducer,requests:Bg.reducer,myRequests:Mg.reducer,openRequests:jh.reducer,closedRequests:Fg.reducer},middleware:t=>t({serializableCheck:{ignoredActions:["persist/PERSIST"]}}),devTools:!1});_l.createRoot(document.getElementById("root")).render(e.jsx(lf.StrictMode,{children:e.jsx(Ab,{store:W4,children:e.jsx(Yb,{children:e.jsx(z4,{})})})}));export{ve as a};