76 lines
1.3 MiB
76 lines
1.3 MiB
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/conclusionApi-BIX8LEl5.js","assets/radix-vendor-DIkYAdWy.js","assets/charts-vendor-Bme4E5cb.js","assets/utils-vendor-DNMmNUQL.js","assets/ui-vendor-sjs6YRoy.js","assets/socket-vendor-TjCxX7sJ.js","assets/redux-vendor-tbZCm13o.js","assets/router-vendor-AvM4PHvP.js"])))=>i.map(i=>d[i]);
|
||
var jg=Object.defineProperty;var Ng=(t,s,a)=>s in t?jg(t,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[s]=a;var Gi=(t,s,a)=>Ng(t,typeof s!="symbol"?s+"":s,a);import{j as e,S as Pu,R as Iu,I as Eu,F as Fu,a as wg,T as Cg,P as Ag,C as Sg,b as Tg,O as Mu,c as _u,d as kg,e as Rg,f as Dg,D as Pg,g as Ig,A as Eg,h as Fg,i as Mg,k as _g,l as Lg,m as Og,n as $g,V as Ug,o as Bg,p as Vg,q as zg,r as Hg,s as Wg,t as Gg,u as Kg,v as Yg,w as Zg,x as Xg,y as Qg,z as Jg,B as qg,E as ef,G as tf,H as sf,J as af,K as rf,L as nf,M as lf,N as of,Q as Lu,U as Ou,W as cf,X as $u,Y as Uu,Z as df,_ as mf,$ as uf,a0 as xf,a1 as hf,a2 as pf,a3 as gf,a4 as ff,a5 as yf,a6 as bf,a7 as vf,a8 as jf,a9 as Nf,aa as wf,ab as Cf}from"./radix-vendor-DIkYAdWy.js";import{a as Af,r as h,c as Bu,d as Ir,B as Fl,C as ai,X as ri,Y as ni,T as Er,L as ii,e as ba,P as Vu,f as zu,g as Hu,h as Sf,i as Ed,j as vi,k as ji,b as Tf}from"./charts-vendor-Bme4E5cb.js";import{a as uo,f as Wu,s as Gs,e as xo,b as Fd,c as kf,d as Na,g as fn,i as ho,h as Gu,j as Os,k as zs,l as Ki,m as Ra,n as Rf,o as Ml,p as Df,q as Ye,r as _l,t as Pf,u as If,v as Ef,w as Ff,x as Yi,y as Md,z as Mf,A as Ku,B as Yu,C as po,D as go,E as _f,F as Lf,G as Zu,H as wr,I as Zi,J as Of,K as $f,L as Uf}from"./utils-vendor-DNMmNUQL.js";import{L as Bf,S as as,C as Ge,a as Ts,b as Ze,X as ft,H as Vf,c as Xu,U as _t,F as Pe,d as De,e as Br,P as vs,f as zf,g as Hf,B as ks,h as za,i as Xi,j as fo,k as yo,l as Vr,m as Qu,n as bo,o as Ju,p as it,q as Ya,R as Bt,I as Sn,T as Vt,r as Xe,s as pa,t as Wf,A as ds,u as os,M as Ds,v as Ni,w as Dt,x as Ll,D as Nt,Z as wi,y as $t,z as Gf,E as Kf,G as Yf,J as Zf,K as Xf,N as Qf,O as Jf,Q as qf,V as e0,W as qu,Y as t0,_ as s0,$ as Da,a0 as Ci,a1 as Ha,a2 as li,a3 as _d,a4 as $n,a5 as oi,a6 as ex,a7 as jt,a8 as a0,a9 as Q,aa as Ks,ab as Js,ac as Ai,ad as ls,ae as tx,af as ht,ag as r0,ah as n0,ai as sx,aj as Si,ak as ax,al as i0,am as vo,an as Bs,ao as Pa,ap as Ti,aq as ki,ar as As,as as l0,at as o0,au as rx,av as c0,aw as Kn,ax as yn,ay as jo,az as Ri,aA as ci,aB as nx,aC as ix,aD as No,aE as Di,aF as Pi,aG as d0,aH as Yn,aI as lx,aJ as di,aK as m0,aL as u0,aM as x0,aN as Ii,aO as Ei,aP as wo,aQ as h0,aR as Ld,aS as Za,aT as p0,aU as Fi,aV as g0,aW as Sr,aX as ox,aY as Od,aZ as f0,a_ as y0,a$ as cx,b0,b1 as v0,b2 as j0,b3 as N0}from"./ui-vendor-sjs6YRoy.js";import{l as w0}from"./socket-vendor-TjCxX7sJ.js";import{c as zr,a as C0}from"./redux-vendor-tbZCm13o.js";import{u as Fa,a as vr,b as dx,B as A0,R as S0,c as es}from"./router-vendor-AvM4PHvP.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 Ol={},$d=Af;Ol.createRoot=$d.createRoot,Ol.hydrateRoot=$d.hydrateRoot;var mx={exports:{}},ux={};/**
|
||
* @license React
|
||
* use-sync-external-store-with-selector.production.js
|
||
*
|
||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||
*
|
||
* This source code is licensed under the MIT license found in the
|
||
* LICENSE file in the root directory of this source tree.
|
||
*/var Tn=h;function T0(t,s){return t===s&&(t!==0||1/t===1/s)||t!==t&&s!==s}var k0=typeof Object.is=="function"?Object.is:T0,R0=Tn.useSyncExternalStore,D0=Tn.useRef,P0=Tn.useEffect,I0=Tn.useMemo,E0=Tn.useDebugValue;ux.useSyncExternalStoreWithSelector=function(t,s,a,r,n){var i=D0(null);if(i.current===null){var l={hasValue:!1,value:null};i.current=l}else l=i.current;i=I0(function(){function d(p){if(!c){if(c=!0,m=p,p=r(p),n!==void 0&&l.hasValue){var g=l.value;if(n(g,p))return u=g}return u=p}if(g=u,k0(m,p))return g;var y=r(p);return n!==void 0&&n(g,y)?(m=p,g):(m=p,u=y)}var c=!1,m,u,x=a===void 0?null:a;return[function(){return d(s())},x===null?void 0:function(){return d(x())}]},[s,a,r,n]);var o=R0(t,i[0],i[1]);return P0(function(){l.hasValue=!0,l.value=o},[o]),E0(o),o};mx.exports=ux;var F0=mx.exports;function M0(t){t()}function _0(){let t=null,s=null;return{clear(){t=null,s=null},notify(){M0(()=>{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 Ud={notify(){},get:()=>[]};function L0(t,s){let a,r=Ud,n=0,i=!1;function l(y){m();const f=r.subscribe(y);let b=!1;return()=>{b||(b=!0,f(),u())}}function o(){r.notify()}function d(){g.onStateChange&&g.onStateChange()}function c(){return i}function m(){n++,a||(a=t.subscribe(d),r=_0())}function u(){n--,a&&n===0&&(a(),a=void 0,r.clear(),r=Ud)}function x(){i||(i=!0,m())}function p(){i&&(i=!1,u())}const g={addNestedSub:l,notifyNestedSubs:o,handleChangeWrapper:d,isSubscribed:c,trySubscribe:x,tryUnsubscribe:p,getListeners:()=>r};return g}var O0=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",$0=O0(),U0=()=>typeof navigator<"u"&&navigator.product==="ReactNative",B0=U0(),V0=()=>$0||B0?h.useLayoutEffect:h.useEffect,z0=V0(),Qi=Symbol.for("react-redux-context"),Ji=typeof globalThis<"u"?globalThis:{};function H0(){if(!h.createContext)return{};const t=Ji[Qi]??(Ji[Qi]=new Map);let s=t.get(h.createContext);return s||(s=h.createContext(null),t.set(h.createContext,s)),s}var Wa=H0();function W0(t){const{children:s,context:a,serverState:r,store:n}=t,i=h.useMemo(()=>{const d=L0(n);return{store:n,subscription:d,getServerState:r?()=>r:void 0}},[n,r]),l=h.useMemo(()=>n.getState(),[n]);z0(()=>{const{subscription:d}=i;return d.onStateChange=d.notifyNestedSubs,d.trySubscribe(),l!==n.getState()&&d.notifyNestedSubs(),()=>{d.tryUnsubscribe(),d.onStateChange=void 0}},[i,l]);const o=a||Wa;return h.createElement(o.Provider,{value:i},s)}var G0=W0;function Co(t=Wa){return function(){return h.useContext(t)}}var xx=Co();function hx(t=Wa){const s=t===Wa?xx:Co(t),a=()=>{const{store:r}=s();return r};return Object.assign(a,{withTypes:()=>a}),a}var K0=hx();function Y0(t=Wa){const s=t===Wa?K0:hx(t),a=()=>s().dispatch;return Object.assign(a,{withTypes:()=>a}),a}var Z0=Y0(),X0=(t,s)=>t===s;function Q0(t=Wa){const s=t===Wa?xx:Co(t),a=(r,n={})=>{const{equalityFn:i=X0}=typeof n=="function"?{equalityFn:n}:n,l=s(),{store:o,subscription:d,getServerState:c}=l;h.useRef(!0);const m=h.useCallback({[r.name](x){return r(x)}}[r.name],[r]),u=F0.useSyncExternalStoreWithSelector(d.addNestedSub,o.getState,c||o.getState,m,i);return h.useDebugValue(u),u};return Object.assign(a,{withTypes:()=>a}),a}var J0=Q0(),$l=function(t,s){return $l=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])},$l(t,s)};function q0(t,s){if(typeof s!="function"&&s!==null)throw new TypeError("Class extends value "+String(s)+" is not a constructor or null");$l(t,s);function a(){this.constructor=t}t.prototype=s===null?Object.create(s):(a.prototype=s.prototype,new a)}var mi=function(){return mi=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},mi.apply(this,arguments)};var mr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Ao(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function So(t,s){return t(s={exports:{}},s.exports),s.exports}var or=So(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()}});Ao(or);var ey=Ao(So(function(t,s){var a=mr&&mr.__awaiter||function(m,u,x,p){return new(x||(x=Promise))(function(g,y){function f(A){try{v(p.next(A))}catch(w){y(w)}}function b(A){try{v(p.throw(A))}catch(w){y(w)}}function v(A){A.done?g(A.value):new x(function(w){w(A.value)}).then(f,b)}v((p=p.apply(m,u||[])).next())})},r=mr&&mr.__generator||function(m,u){var x,p,g,y,f={label:0,sent:function(){if(1&g[0])throw g[1];return g[1]},trys:[],ops:[]};return y={next:b(0),throw:b(1),return:b(2)},typeof Symbol=="function"&&(y[Symbol.iterator]=function(){return this}),y;function b(v){return function(A){return function(w){if(x)throw new TypeError("Generator is already executing.");for(;f;)try{if(x=1,p&&(g=2&w[0]?p.return:w[0]?p.throw||((g=p.return)&&g.call(p),0):p.next)&&!(g=g.call(p,w[1])).done)return g;switch(p=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++,p=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=u.call(m,f)}catch(T){w=[6,T],p=0}finally{x=g=0}if(5&w[0])throw w[1];return{value:w[0]?w[1]:void 0,done:!0}}([v,A])}}},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(u){throw new Error("Unsupported")})})},getItem:function(m){return a(n,void 0,void 0,function(){return r(this,function(u){throw new Error("Unsupported")})})},clear:function(){return a(n,void 0,void 0,function(){return r(this,function(m){return[2,window.localStorage.clear()]})})},removeItem:function(m){return a(n,void 0,void 0,function(){return r(this,function(u){throw new Error("Unsupported")})})},setItem:function(m,u){return a(n,void 0,void 0,function(){return r(this,function(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,u){return window.localStorage.setItem(m,u)}};function o(m){return new Promise(function(u){return setTimeout(u,m)})}function d(m){for(var u="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",x="",p=0;p<m;p++)x+=u[Math.floor(Math.random()*u.length)];return x}var c=function(){function m(u){this.acquiredIatSet=new Set,this.storageHandler=void 0,this.id=Date.now().toString()+d(15),this.acquireLock=this.acquireLock.bind(this),this.releaseLock=this.releaseLock.bind(this),this.releaseLock__private__=this.releaseLock__private__.bind(this),this.waitForSomethingToChange=this.waitForSomethingToChange.bind(this),this.refreshLockWhileAcquired=this.refreshLockWhileAcquired.bind(this),this.storageHandler=u,m.waiters===void 0&&(m.waiters=[])}return m.prototype.acquireLock=function(u,x){return x===void 0&&(x=5e3),a(this,void 0,void 0,function(){var p,g,y,f,b,v,A;return r(this,function(w){switch(w.label){case 0:p=Date.now()+d(4),g=Date.now()+x,y=i+"-"+u,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(y)!==null?[3,5]:(b=this.id+"-"+u+"-"+p,[4,o(Math.floor(25*Math.random()))]);case 3:return w.sent(),f.setItemSync(y,JSON.stringify({id:this.id,iat:p,timeoutKey:b,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,o(30)];case 4:return w.sent(),(v=f.getItemSync(y))!==null&&(A=JSON.parse(v)).id===this.id&&A.iat===p?(this.acquiredIatSet.add(p),this.refreshLockWhileAcquired(y,p),[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 p=Date.now()+d(4),[3,1];case 8:return[2,!1]}})})},m.prototype.refreshLockWhileAcquired=function(u,x){return a(this,void 0,void 0,function(){var p=this;return r(this,function(g){return setTimeout(function(){return a(p,void 0,void 0,function(){var y,f,b;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)?(y=this.storageHandler===void 0?l:this.storageHandler,(f=y.getItemSync(u))===null?(or.default().unlock(x),[2]):((b=JSON.parse(f)).timeRefreshed=Date.now(),y.setItemSync(u,JSON.stringify(b)),or.default().unlock(x),this.refreshLockWhileAcquired(u,x),[2])):(or.default().unlock(x),[2])}})})},1e3),[2]})})},m.prototype.waitForSomethingToChange=function(u){return a(this,void 0,void 0,function(){return r(this,function(x){switch(x.label){case 0:return[4,new Promise(function(p){var g=!1,y=Date.now(),f=!1;function b(){if(f||(window.removeEventListener("storage",b),m.removeFromWaiting(b),clearTimeout(v),f=!0),!g){g=!0;var A=50-(Date.now()-y);A>0?setTimeout(p,A):p(null)}}window.addEventListener("storage",b),m.addToWaiting(b);var v=setTimeout(b,Math.max(0,u-Date.now()))})];case 1:return x.sent(),[2]}})})},m.addToWaiting=function(u){this.removeFromWaiting(u),m.waiters!==void 0&&m.waiters.push(u)},m.removeFromWaiting=function(u){m.waiters!==void 0&&(m.waiters=m.waiters.filter(function(x){return x!==u}))},m.notifyWaiters=function(){m.waiters!==void 0&&m.waiters.slice().forEach(function(u){return u()})},m.prototype.releaseLock=function(u){return a(this,void 0,void 0,function(){return r(this,function(x){switch(x.label){case 0:return[4,this.releaseLock__private__(u)];case 1:return[2,x.sent()]}})})},m.prototype.releaseLock__private__=function(u){return a(this,void 0,void 0,function(){var x,p,g,y;return r(this,function(f){switch(f.label){case 0:return x=this.storageHandler===void 0?l:this.storageHandler,p=i+"-"+u,(g=x.getItemSync(p))===null?[2]:(y=JSON.parse(g)).id!==this.id?[3,2]:[4,or.default().lock(y.iat)];case 1:f.sent(),this.acquiredIatSet.delete(y.iat),x.removeItemSync(p),or.default().unlock(y.iat),m.notifyWaiters(),f.label=2;case 2:return[2]}})})},m.lockCorrector=function(u){for(var x=Date.now()-5e3,p=u,g=[],y=0;;){var f=p.keySync(y);if(f===null)break;g.push(f),y++}for(var b=!1,v=0;v<g.length;v++){var A=g[v];if(A.includes(i)){var w=p.getItemSync(A);if(w!==null){var T=JSON.parse(w);(T.timeRefreshed===void 0&&T.timeAcquired<x||T.timeRefreshed!==void 0&&T.timeRefreshed<x)&&(p.removeItemSync(A),b=!0)}}}b&&m.notifyWaiters()},m.waiters=void 0,m}();s.default=c}));new TextEncoder;new TextDecoder;var xr=So(function(t,s){var a=mr&&mr.__assign||function(){return a=Object.assign||function(d){for(var c,m=1,u=arguments.length;m<u;m++)for(var x in c=arguments[m])Object.prototype.hasOwnProperty.call(c,x)&&(d[x]=c[x]);return d},a.apply(this,arguments)};function r(d,c){if(!c)return"";var m="; "+d;return c===!0?m:m+"="+c}function n(d,c,m){return encodeURIComponent(d).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/\(/g,"%28").replace(/\)/g,"%29")+"="+encodeURIComponent(c).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent)+function(u){if(typeof u.expires=="number"){var x=new Date;x.setMilliseconds(x.getMilliseconds()+864e5*u.expires),u.expires=x}return r("Expires",u.expires?u.expires.toUTCString():"")+r("Domain",u.domain)+r("Path",u.path)+r("Secure",u.secure)+r("SameSite",u.sameSite)}(m)}function i(d){for(var c={},m=d?d.split("; "):[],u=/(%[\dA-F]{2})+/gi,x=0;x<m.length;x++){var p=m[x].split("="),g=p.slice(1).join("=");g.charAt(0)==='"'&&(g=g.slice(1,-1));try{c[p[0].replace(u,decodeURIComponent)]=g.replace(u,decodeURIComponent)}catch{}}return c}function l(){return i(document.cookie)}function o(d,c,m){document.cookie=n(d,c,a({path:"/"},m))}s.__esModule=!0,s.encode=n,s.parse=i,s.getAll=l,s.get=function(d){return l()[d]},s.set=o,s.remove=function(d,c){o(d,"",a(a({},c),{expires:-1}))}});Ao(xr),xr.encode,xr.parse,xr.getAll;xr.get;xr.set;xr.remove;var Bd;(function(t){t.Code="code",t.ConnectCode="connect_code"})(Bd||(Bd={}));var Vd;(function(t){t.Bearer="Bearer",t.DPoP="DPoP"})(Vd||(Vd={}));new ey;var ty={isAuthenticated:!1,isLoading:!0,error:void 0,user:void 0},_s=function(){throw new Error("You forgot to wrap your component in <Auth0Provider>.")},sy=mi(mi({},ty),{buildAuthorizeUrl:_s,buildLogoutUrl:_s,getAccessTokenSilently:_s,getAccessTokenWithPopup:_s,getIdTokenClaims:_s,loginWithRedirect:_s,loginWithPopup:_s,connectAccountWithRedirect:_s,logout:_s,handleRedirectCallback:_s,getDpopNonce:_s,setDpopNonce:_s,generateDpopProof:_s,createFetcher:_s}),ay=h.createContext(sy);(function(t){q0(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 ry=function(t){return t===void 0&&(t=ay),h.useContext(t)};const qi="idToken",el="userData",ny=()=>!0;class at{static setAccessToken(s){}static getAccessToken(){return null}static setRefreshToken(s){}static getRefreshToken(){return null}static setIdToken(s){sessionStorage.setItem(qi,s)}static getIdToken(){return sessionStorage.getItem(qi)}static setUserData(s){localStorage.setItem(el,JSON.stringify(s))}static getUserData(){const s=localStorage.getItem(el);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(el),sessionStorage.removeItem(qi)}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 ny()}}function tl(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 px="https://re-workflow-nt-dev.siplsolutions.com/api/v1",Ne=uo.create({baseURL:px,headers:{"Content-Type":"application/json"},withCredentials:!0});Ne.interceptors.request.use(t=>t,t=>Promise.reject(t));Ne.interceptors.response.use(t=>t,async t=>{var a,r;const s=t.config;if(t.code==="ERR_NETWORK"||t.code==="ECONNREFUSED"||(a=t.message)!=null&&a.includes("ERR_CONNECTION_REFUSED"),((r=t.response)==null?void 0:r.status)===401&&!s._retry){s._retry=!0;const n=!0;try{const i=at.getRefreshToken(),l=await uo.post(`${px}/auth/refresh`,n?{}:{refreshToken:i},{withCredentials:!0}),d=(l.data.data||l.data).accessToken;return Ne(s)}catch(i){return at.clearAll(),window.location.href="/",Promise.reject(i)}}return Promise.reject(t)});async function iy(t,s){var a,r;try{const n=await Ne.post("/auth/token-exchange",{code:t,redirectUri:s},{responseType:"json",headers:{"Content-Type":"application/json",Accept:"application/json"}});if(Array.isArray(n.data))throw console.error("❌ Response is an array (buffer issue):",{arrayLength:n.data.length,firstFew:n.data.slice(0,10),rawResponse:n}),new Error("Invalid response format: received array instead of JSON. Check Content-Type header.");const i=n.data,l=i.data||i;return l.user&&at.setUserData(l.user),l.idToken&&at.setIdToken(l.idToken),l.accessToken&&l.refreshToken&&(at.setAccessToken(l.accessToken),at.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 ly(){var r;const t={},a=(await Ne.post("/auth/refresh",t)).data;if((r=a.data)!=null&&r.accessToken||a.accessToken,a.success!==!1)return"cookie-based-auth";throw new Error("Failed to refresh token")}async function on(){const s=(await Ne.get("/auth/me")).data;return s.data||s}async function oy(){var t,s;try{await Ne.post("/auth/logout",{},{withCredentials:!0})}catch(a){console.error("📡 Logout API error:",a),console.error("📡 Error details:",{message:a.message,status:(t=a.response)==null?void 0:t.status,data:(s=a.response)==null?void 0:s.data})}}const Ul="https://ssodev.rebridge.co.in/realms/RE",gx="REFLOW",To=`${window.location.origin}/login/callback`;function cy(){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=`${Ul}/protocol/openid-connect/auth?client_id=${gx}&response_type=code&scope=openid&redirect_uri=${encodeURIComponent(To)}&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 dy(t,s){var r,n,i;const a="https://re-workflow-nt-dev.siplsolutions.com/api/v1";try{const l=await uo.post(`${a}/auth/tanflow/token-exchange`,{code:t,redirectUri:To,state:s},{withCredentials:!0,headers:{"Content-Type":"application/json"}}),o=((r=l.data)==null?void 0:r.data)||l.data;return o.accessToken&&at.setAccessToken(o.accessToken),o.refreshToken&&at.setRefreshToken(o.refreshToken),o.idToken&&at.setIdToken(o.idToken),o.user&&at.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 my(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=To,a=new URL(`${Ul}/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:`${Ul}/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 fx=h.createContext(void 0);function uy({children:t}){const[s,a]=h.useState(!1),[r,n]=h.useState(!0),[i,l]=h.useState(null),[o,d]=h.useState(null),[c,m]=h.useState(!1);h.useEffect(()=>{const v=sessionStorage.getItem("__logout_in_progress__"),A=sessionStorage.getItem("__force_logout__");if(v==="true"||A==="true"){sessionStorage.removeItem("__logout_in_progress__"),sessionStorage.removeItem("__force_logout__"),at.clearAll();try{localStorage.clear(),sessionStorage.clear()}catch(T){console.error("Error clearing storage:",T)}a(!1),l(null),n(!1),d(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"),at.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 T=new URLSearchParams;w.has("okta_logged_out")&&T.set("okta_logged_out","true"),w.has("tanflow_logged_out")&&T.set("tanflow_logged_out","true");const k=T.toString()?`/?${T.toString()}`:"/";window.history.replaceState({},document.title,k);return}window.location.pathname==="/login/callback"||window.location.pathname==="/login/tanflow/callback"||(at.getUserData(),c?n(!1):x())},[c]),h.useEffect(()=>{if(!s)return;const v=async()=>{try{await f()}catch(T){console.error("Silent refresh failed:",T)}},A=10*60*1e3,w=setInterval(v,A);return()=>clearInterval(w)},[s]);const u=h.useRef(!1);h.useEffect(()=>{if(u.current||window.location.pathname!=="/login/callback")return;(async()=>{const A=new URLSearchParams(window.location.search);if((A.has("logout")||A.has("tanflow_logged_out")||A.has("okta_logged_out"))&&!A.get("code")){console.log("🚪 Logout redirect detected in callback, redirecting to home");const L=new URLSearchParams;A.has("tanflow_logged_out")&&L.set("tanflow_logged_out","true"),A.has("okta_logged_out")&&L.set("okta_logged_out","true"),A.has("logout")&&L.set("logout",A.get("logout")||Date.now().toString());const D=L.toString()?`/?${L.toString()}`:"/?logout="+Date.now();window.location.replace(D);return}u.current=!0;const w=A.get("code"),T=A.get("error");if(window.history.replaceState({},document.title,"/login/callback"),sessionStorage.getItem("auth_provider")==="tanflow"){u.current=!1;return}if(T){d(new Error(`Authentication error: ${T}`)),n(!1),sessionStorage.removeItem("auth_provider");return}if(!w){n(!1),sessionStorage.removeItem("auth_provider");return}try{n(!0),a(!1),d(null);const L=`${window.location.origin}/login/callback`,D=await iy(w,L);l(D.user),a(!0),d(null),sessionStorage.removeItem("auth_provider"),window.history.replaceState({},document.title,"/")}catch(L){console.error("❌ Token exchange error in AuthContext:",L),d(L),a(!1),l(null),sessionStorage.removeItem("auth_provider"),u.current=!1}finally{n(!1)}})()},[]);const x=async()=>{var A;if(c){n(!1);return}const v=!0;try{if(n(!0),v){const k=at.getUserData();try{const L=await on();l(L),at.setUserData(L),a(!0)}catch(L){if(((A=L==null?void 0:L.response)==null?void 0:A.status)===401)try{await f();const D=await on();l(D),at.setUserData(D),a(!0)}catch{at.clearAll(),a(!1),l(null)}else L!=null&&L.isConnectionError?k?(l(k),a(!0)):(a(!1),l(null)):(at.clearAll(),a(!1),l(null))}return}const w=at.getAccessToken(),T=at.getUserData();if(!w){a(!1),l(null),n(!1);return}if(tl(w))try{await f();const k=at.getAccessToken();if(k&&!tl(k)){const L=at.getUserData();if(L)l(L),a(!0);else try{const D=await on();l(D),at.setUserData(D),a(!0)}catch{at.clearAll(),a(!1),l(null)}}else at.clearAll(),a(!1),l(null)}catch{at.clearAll(),a(!1),l(null)}else if(T)l(T),a(!0);else try{const k=await on();l(k),at.setUserData(k),a(!0)}catch{at.clearAll(),a(!1),l(null)}}catch(w){console.error("Error checking auth status:",w),d(w),at.clearAll(),a(!1),l(null)}finally{n(!1)}},p=async()=>{try{d(null);const v="https://royalenfield.okta.com",A="0oa18b98aari6I6eo2p8",w=`${window.location.origin}/login/callback`,T="code",k="openid profile email",L=Math.random().toString(36).substring(7);sessionStorage.setItem("auth_provider","okta");const D=new URLSearchParams(window.location.search),S=D.has("logout")||D.has("okta_logged_out")||D.has("tanflow_logged_out");let N=`${v}/oauth2/default/v1/authorize?client_id=${A}&redirect_uri=${encodeURIComponent(w)}&response_type=${T}&scope=${encodeURIComponent(k)}&state=${L}`;S&&(N+="&prompt=login"),window.location.href=N}catch(v){throw d(v),v}},g=async()=>{try{const v=at.getIdToken(),A=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),d(null),n(!0);try{await oy(),console.log("🚪 Backend logout API called successfully")}catch(D){console.error("🚪 Logout API error:",D),console.warn("🚪 Backend logout failed - httpOnly cookies may not be cleared")}const w=sessionStorage.getItem("__logout_in_progress__"),T=sessionStorage.getItem("__force_logout__"),k=sessionStorage.getItem("auth_provider");if(at.clearAll(),w&&sessionStorage.setItem("__logout_in_progress__",w),T&&sessionStorage.setItem("__force_logout__",T),v&&at.setIdToken(v),k&&sessionStorage.setItem("auth_provider",k),await new Promise(D=>setTimeout(D,100)),A==="tanflow"&&v){console.log("🚪 Initiating Tanflow logout...");try{my(v);return}catch(D){console.error("🚪 Tanflow logout error:",D)}}console.log("🚪 Using OKTA logout flow or fallback"),sessionStorage.removeItem("auth_provider"),v&&at.clearAll();const L=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(L)}catch(v){console.error("🚪 Logout error:",v);try{localStorage.clear(),sessionStorage.clear(),sessionStorage.setItem("__logout_in_progress__","true");const A=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(A)}catch{window.location.replace("/?logout="+Date.now())}}},y=async()=>{{if(s)return"cookie-based-auth";try{return await f(),s?"cookie-based-auth":null}catch{return null}}const v=at.getAccessToken();if(v&&!tl(v))return v;try{return await f(),at.getAccessToken()}catch{return null}},f=async()=>{try{const A=await ly();return}catch(A){throw at.clearAll(),a(!1),l(null),A}},b={isAuthenticated:s,isLoading:r,user:i,error:o,login:p,logout:g,getAccessTokenSilently:y,refreshTokenSilently:f};return e.jsx(fx.Provider,{value:b,children:t})}function xy({children:t}){return e.jsx(uy,{children:t})}function Jt(){const t=h.useContext(fx);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 Mi(t){return(t==null?void 0:t.role)==="MANAGEMENT"||(t==null?void 0:t.role)==="ADMIN"}const zd=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,Hd=Bu,yx=(t,s)=>a=>{var r;if((s==null?void 0:s.variants)==null)return Hd(t,a==null?void 0:a.class,a==null?void 0:a.className);const{variants:n,defaultVariants:i}=s,l=Object.keys(n).map(c=>{const m=a==null?void 0:a[c],u=i==null?void 0:i[c];if(m===null)return null;const x=zd(m)||zd(u);return n[c][x]}),o=a&&Object.entries(a).reduce((c,m)=>{let[u,x]=m;return x===void 0||(c[u]=x),c},{}),d=s==null||(r=s.compoundVariants)===null||r===void 0?void 0:r.reduce((c,m)=>{let{class:u,className:x,...p}=m;return Object.entries(p).every(g=>{let[y,f]=g;return Array.isArray(f)?f.includes({...i,...o}[y]):{...i,...o}[y]===f})?[...c,u,x]:c},[]);return Hd(t,l,d,a==null?void 0:a.class,a==null?void 0:a.className)},ko="-",hy=t=>{const s=gy(t),{conflictingClassGroups:a,conflictingClassGroupModifiers:r}=t;return{getClassGroupId:l=>{const o=l.split(ko);return o[0]===""&&o.length!==1&&o.shift(),bx(o,s)||py(l)},getConflictingClassGroupIds:(l,o)=>{const d=a[l]||[];return o&&r[l]?[...d,...r[l]]:d}}},bx=(t,s)=>{var l;if(t.length===0)return s.classGroupId;const a=t[0],r=s.nextPart.get(a),n=r?bx(t.slice(1),r):void 0;if(n)return n;if(s.validators.length===0)return;const i=t.join(ko);return(l=s.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},Wd=/^\[(.+)\]$/,py=t=>{if(Wd.test(t)){const s=Wd.exec(t)[1],a=s==null?void 0:s.substring(0,s.indexOf(":"));if(a)return"arbitrary.."+a}},gy=t=>{const{theme:s,prefix:a}=t,r={nextPart:new Map,validators:[]};return yy(Object.entries(t.classGroups),a).forEach(([i,l])=>{Bl(l,r,i,s)}),r},Bl=(t,s,a,r)=>{t.forEach(n=>{if(typeof n=="string"){const i=n===""?s:Gd(s,n);i.classGroupId=a;return}if(typeof n=="function"){if(fy(n)){Bl(n(r),s,a,r);return}s.validators.push({validator:n,classGroupId:a});return}Object.entries(n).forEach(([i,l])=>{Bl(l,Gd(s,i),a,r)})})},Gd=(t,s)=>{let a=t;return s.split(ko).forEach(r=>{a.nextPart.has(r)||a.nextPart.set(r,{nextPart:new Map,validators:[]}),a=a.nextPart.get(r)}),a},fy=t=>t.isThemeGetter,yy=(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,by=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)}}},vx="!",vy=t=>{const{separator:s,experimentalParseClassName:a}=t,r=s.length===1,n=s[0],i=s.length,l=o=>{const d=[];let c=0,m=0,u;for(let f=0;f<o.length;f++){let b=o[f];if(c===0){if(b===n&&(r||o.slice(f,f+i)===s)){d.push(o.slice(m,f)),m=f+i;continue}if(b==="/"){u=f;continue}}b==="["?c++:b==="]"&&c--}const x=d.length===0?o:o.substring(m),p=x.startsWith(vx),g=p?x.substring(1):x,y=u&&u>m?u-m:void 0;return{modifiers:d,hasImportantModifier:p,baseClassName:g,maybePostfixModifierPosition:y}};return a?o=>a({className:o,parseClassName:l}):l},jy=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},Ny=t=>({cache:by(t.cacheSize),parseClassName:vy(t),...hy(t)}),wy=/\s+/,Cy=(t,s)=>{const{parseClassName:a,getClassGroupId:r,getConflictingClassGroupIds:n}=s,i=[],l=t.trim().split(wy);let o="";for(let d=l.length-1;d>=0;d-=1){const c=l[d],{modifiers:m,hasImportantModifier:u,baseClassName:x,maybePostfixModifierPosition:p}=a(c);let g=!!p,y=r(g?x.substring(0,p):x);if(!y){if(!g){o=c+(o.length>0?" "+o:o);continue}if(y=r(x),!y){o=c+(o.length>0?" "+o:o);continue}g=!1}const f=jy(m).join(":"),b=u?f+vx:f,v=b+y;if(i.includes(v))continue;i.push(v);const A=n(y,g);for(let w=0;w<A.length;++w){const T=A[w];i.push(b+T)}o=c+(o.length>0?" "+o:o)}return o};function Ay(){let t=0,s,a,r="";for(;t<arguments.length;)(s=arguments[t++])&&(a=jx(s))&&(r&&(r+=" "),r+=a);return r}const jx=t=>{if(typeof t=="string")return t;let s,a="";for(let r=0;r<t.length;r++)t[r]&&(s=jx(t[r]))&&(a&&(a+=" "),a+=s);return a};function Sy(t,...s){let a,r,n,i=l;function l(d){const c=s.reduce((m,u)=>u(m),t());return a=Ny(c),r=a.cache.get,n=a.cache.set,i=o,o(d)}function o(d){const c=r(d);if(c)return c;const m=Cy(d,a);return n(d,m),m}return function(){return i(Ay.apply(null,arguments))}}const Mt=t=>{const s=a=>a[t]||[];return s.isThemeGetter=!0,s},Nx=/^\[(?:([a-z-]+):)?(.+)\]$/i,Ty=/^\d+\/\d+$/,ky=new Set(["px","full","screen"]),Ry=/^(\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$/,Py=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,Iy=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Ey=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Sa=t=>Fr(t)||ky.has(t)||Ty.test(t),$a=t=>Hr(t,"length",By),Fr=t=>!!t&&!Number.isNaN(Number(t)),sl=t=>Hr(t,"number",Fr),sn=t=>!!t&&Number.isInteger(Number(t)),Fy=t=>t.endsWith("%")&&Fr(t.slice(0,-1)),nt=t=>Nx.test(t),Ua=t=>Ry.test(t),My=new Set(["length","size","percentage"]),_y=t=>Hr(t,My,wx),Ly=t=>Hr(t,"position",wx),Oy=new Set(["image","url"]),$y=t=>Hr(t,Oy,zy),Uy=t=>Hr(t,"",Vy),an=()=>!0,Hr=(t,s,a)=>{const r=Nx.exec(t);return r?r[1]?typeof s=="string"?r[1]===s:s.has(r[1]):a(r[2]):!1},By=t=>Dy.test(t)&&!Py.test(t),wx=()=>!1,Vy=t=>Iy.test(t),zy=t=>Ey.test(t),Hy=()=>{const t=Mt("colors"),s=Mt("spacing"),a=Mt("blur"),r=Mt("brightness"),n=Mt("borderColor"),i=Mt("borderRadius"),l=Mt("borderSpacing"),o=Mt("borderWidth"),d=Mt("contrast"),c=Mt("grayscale"),m=Mt("hueRotate"),u=Mt("invert"),x=Mt("gap"),p=Mt("gradientColorStops"),g=Mt("gradientColorStopPositions"),y=Mt("inset"),f=Mt("margin"),b=Mt("opacity"),v=Mt("padding"),A=Mt("saturate"),w=Mt("scale"),T=Mt("sepia"),k=Mt("skew"),L=Mt("space"),D=Mt("translate"),S=()=>["auto","contain","none"],N=()=>["auto","hidden","clip","visible","scroll"],P=()=>["auto",nt,s],R=()=>[nt,s],O=()=>["",Sa,$a],E=()=>["auto",Fr,nt],M=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],B=()=>["solid","dashed","dotted","double","none"],C=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],j=()=>["start","end","center","between","around","evenly","stretch"],U=()=>["","0",nt],$=()=>["auto","avoid","all","avoid-page","page","left","right","column"],_=()=>[Fr,nt];return{cacheSize:500,separator:":",theme:{colors:[an],spacing:[Sa,$a],blur:["none","",Ua,nt],brightness:_(),borderColor:[t],borderRadius:["none","","full",Ua,nt],borderSpacing:R(),borderWidth:O(),contrast:_(),grayscale:U(),hueRotate:_(),invert:U(),gap:R(),gradientColorStops:[t],gradientColorStopPositions:[Fy,$a],inset:P(),margin:P(),opacity:_(),padding:R(),saturate:_(),scale:_(),sepia:U(),skew:_(),space:R(),translate:R()},classGroups:{aspect:[{aspect:["auto","square","video",nt]}],container:["container"],columns:[{columns:[Ua]}],"break-after":[{"break-after":$()}],"break-before":[{"break-before":$()}],"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:[...M(),nt]}],overflow:[{overflow:N()}],"overflow-x":[{"overflow-x":N()}],"overflow-y":[{"overflow-y":N()}],overscroll:[{overscroll:S()}],"overscroll-x":[{"overscroll-x":S()}],"overscroll-y":[{"overscroll-y":S()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[y]}],"inset-x":[{"inset-x":[y]}],"inset-y":[{"inset-y":[y]}],start:[{start:[y]}],end:[{end:[y]}],top:[{top:[y]}],right:[{right:[y]}],bottom:[{bottom:[y]}],left:[{left:[y]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",sn,nt]}],basis:[{basis:P()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",nt]}],grow:[{grow:U()}],shrink:[{shrink:U()}],order:[{order:["first","last","none",sn,nt]}],"grid-cols":[{"grid-cols":[an]}],"col-start-end":[{col:["auto",{span:["full",sn,nt]},nt]}],"col-start":[{"col-start":E()}],"col-end":[{"col-end":E()}],"grid-rows":[{"grid-rows":[an]}],"row-start-end":[{row:["auto",{span:[sn,nt]},nt]}],"row-start":[{"row-start":E()}],"row-end":[{"row-end":E()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",nt]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",nt]}],gap:[{gap:[x]}],"gap-x":[{"gap-x":[x]}],"gap-y":[{"gap-y":[x]}],"justify-content":[{justify:["normal",...j()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...j(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...j(),"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":[L]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[L]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",nt,s]}],"min-w":[{"min-w":[nt,s,"min","max","fit"]}],"max-w":[{"max-w":[nt,s,"none","full","min","max","fit","prose",{screen:[Ua]},Ua]}],h:[{h:[nt,s,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[nt,s,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[nt,s,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[nt,s,"auto","min","max","fit"]}],"font-size":[{text:["base",Ua,$a]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",sl]}],"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",nt]}],"line-clamp":[{"line-clamp":["none",Fr,sl]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Sa,nt]}],"list-image":[{"list-image":["none",nt]}],"list-style-type":[{list:["none","disc","decimal",nt]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[t]}],"placeholder-opacity":[{"placeholder-opacity":[b]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[t]}],"text-opacity":[{"text-opacity":[b]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...B(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Sa,$a]}],"underline-offset":[{"underline-offset":["auto",Sa,nt]}],"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:R()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",nt]}],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",nt]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[b]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...M(),Ly]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",_y]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},$y]}],"bg-color":[{bg:[t]}],"gradient-from-pos":[{from:[g]}],"gradient-via-pos":[{via:[g]}],"gradient-to-pos":[{to:[g]}],"gradient-from":[{from:[p]}],"gradient-via":[{via:[p]}],"gradient-to":[{to:[p]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[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":[b]}],"border-style":[{border:[...B(),"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":[b]}],"divide-style":[{divide:B()}],"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:["",...B()]}],"outline-offset":[{"outline-offset":[Sa,nt]}],"outline-w":[{outline:[Sa,$a]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:O()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[b]}],"ring-offset-w":[{"ring-offset":[Sa,$a]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",Ua,Uy]}],"shadow-color":[{shadow:[an]}],opacity:[{opacity:[b]}],"mix-blend":[{"mix-blend":[...C(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":C()}],filter:[{filter:["","none"]}],blur:[{blur:[a]}],brightness:[{brightness:[r]}],contrast:[{contrast:[d]}],"drop-shadow":[{"drop-shadow":["","none",Ua,nt]}],grayscale:[{grayscale:[c]}],"hue-rotate":[{"hue-rotate":[m]}],invert:[{invert:[u]}],saturate:[{saturate:[A]}],sepia:[{sepia:[T]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[a]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[d]}],"backdrop-grayscale":[{"backdrop-grayscale":[c]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[m]}],"backdrop-invert":[{"backdrop-invert":[u]}],"backdrop-opacity":[{"backdrop-opacity":[b]}],"backdrop-saturate":[{"backdrop-saturate":[A]}],"backdrop-sepia":[{"backdrop-sepia":[T]}],"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",nt]}],duration:[{duration:_()}],ease:[{ease:["linear","in","out","in-out",nt]}],delay:[{delay:_()}],animate:[{animate:["none","spin","ping","pulse","bounce",nt]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[w]}],"scale-x":[{"scale-x":[w]}],"scale-y":[{"scale-y":[w]}],rotate:[{rotate:[sn,nt]}],"translate-x":[{"translate-x":[D]}],"translate-y":[{"translate-y":[D]}],"skew-x":[{"skew-x":[k]}],"skew-y":[{"skew-y":[k]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",nt]}],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",nt]}],"caret-color":[{caret:[t]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":R()}],"scroll-mx":[{"scroll-mx":R()}],"scroll-my":[{"scroll-my":R()}],"scroll-ms":[{"scroll-ms":R()}],"scroll-me":[{"scroll-me":R()}],"scroll-mt":[{"scroll-mt":R()}],"scroll-mr":[{"scroll-mr":R()}],"scroll-mb":[{"scroll-mb":R()}],"scroll-ml":[{"scroll-ml":R()}],"scroll-p":[{"scroll-p":R()}],"scroll-px":[{"scroll-px":R()}],"scroll-py":[{"scroll-py":R()}],"scroll-ps":[{"scroll-ps":R()}],"scroll-pe":[{"scroll-pe":R()}],"scroll-pt":[{"scroll-pt":R()}],"scroll-pr":[{"scroll-pr":R()}],"scroll-pb":[{"scroll-pb":R()}],"scroll-pl":[{"scroll-pl":R()}],"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",nt]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[Sa,$a,sl]}],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"]}}},Wy=Sy(Hy);function Re(...t){return Wy(Bu(t))}const bn=yx("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=h.forwardRef(({className:t,variant:s,size:a,asChild:r=!1,...n},i)=>{const l=r?Pu:"button";return e.jsx(l,{"data-slot":"button",className:Re(bn({variant:s,size:a,className:t})),ref:i,...n})});F.displayName="Button";function te({className:t,...s}){return e.jsx("div",{"data-slot":"card",className:Re("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border",t),...s})}function ue({className:t,...s}){return e.jsx("div",{"data-slot":"card-header",className:Re("@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 xe({className:t,...s}){return e.jsx("h4",{"data-slot":"card-title",className:Re("leading-none",t),...s})}function ke({className:t,...s}){return e.jsx("p",{"data-slot":"card-description",className:Re("text-muted-foreground",t),...s})}function ae({className:t,...s}){return e.jsx("div",{"data-slot":"card-content",className:Re("px-6 [&:last-child]:pb-6",t),...s})}const _i="/assets/Re_Logo-By51taPS.png",Kd="/assets/landing_page_image-ClTD-4qZ.jpg";function Gy(){const{login:t,isLoading:s,error:a}=Jt(),[r,n]=h.useState(!1),[i,l]=h.useState(!1);h.useEffect(()=>{const c=new Image;c.src=Kd,c.onload=()=>{l(!0)},c.complete&&l(!0)},[]);const o=async()=>{localStorage.clear(),sessionStorage.clear();try{await t()}catch(c){console.error("========================================"),console.error("OKTA LOGIN ERROR"),console.error("Error details:",c),console.error("Error message:",c==null?void 0:c.message),console.error("Error stack:",c==null?void 0:c.stack),console.error("========================================")}},d=()=>{localStorage.clear(),sessionStorage.clear(),n(!0);try{cy()}catch(c){console.error("========================================"),console.error("TANFLOW LOGIN ERROR"),console.error("Error details:",c),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(${Kd})`:"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(te,{className:"w-full max-w-md shadow-xl relative z-10 bg-black backdrop-blur-sm border-gray-800",children:[e.jsx(ue,{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:_i,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(Bf,{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:d,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(as,{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 Cx(){const{isAuthenticated:t,isLoading:s,error:a,user:r}=Jt(),[n,i]=h.useState("exchanging");h.useEffect(()=>{if(a){i("error");return}if(s){const d=new URLSearchParams(window.location.search).get("code");i(d&&!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:_i,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(Ge,{className:"w-16 h-16 text-red-500"})}),e.jsx(Ge,{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(Ts,{className:"w-16 h-16 text-green-500"})}),e.jsx(Ts,{className:"w-16 h-16 text-green-500 relative"})]}):e.jsxs("div",{className:"relative",children:[e.jsx(Ze,{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 Ky(){const{isAuthenticated:t,isLoading:s,error:a,user:r}=Jt(),[n,i]=h.useState("exchanging"),[l,o]=h.useState(""),d=h.useRef(!1);h.useEffect(()=>{if(a){i("error");return}if(s){const u=new URLSearchParams(window.location.search).get("code");i(u&&!r?"exchanging":r&&!t?"fetching":"exchanging")}else r&&t&&(i("complete"),setTimeout(()=>{window.location.href="/"},1e3))},[t,s,a,r]),h.useEffect(()=>{if(d.current||window.location.pathname!=="/login/callback")return;const m=new URLSearchParams(window.location.search),u=m.get("code"),x=m.get("error");if(!u&&!x){console.log("🚪 Logout redirect detected: no code, no error - redirecting to home immediately"),d.current=!0;const y=new URLSearchParams;y.set("tanflow_logged_out","true"),y.set("logout",Date.now().toString());const f=`/?${y.toString()}`;console.log("🚪 Redirecting to:",f),window.location.replace(f);return}if(sessionStorage.getItem("auth_provider")!=="tanflow")return;(async()=>{d.current=!0;const y=new URLSearchParams(window.location.search),f=y.get("code"),b=y.get("state"),v=y.get("error");if(window.history.replaceState({},document.title,"/login/callback"),v){i("error"),sessionStorage.removeItem("auth_provider"),sessionStorage.removeItem("tanflow_auth_state");return}const A=sessionStorage.getItem("tanflow_auth_state");if(b&&b!==A){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 dy(f,b||"");sessionStorage.removeItem("tanflow_auth_state"),i("fetching");const T=w.user||await on();if(T)at.setUserData(T),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 c=()=>{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:_i,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(Ge,{className:"w-16 h-16 text-red-500"})}),e.jsx(Ge,{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(Ts,{className:"w-16 h-16 text-green-500"})}),e.jsx(Ts,{className:"w-16 h-16 text-green-500 relative"})]}):e.jsxs("div",{className:"relative",children:[e.jsx(Ze,{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:c()})]}),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 Yy=yx("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 ne({className:t,variant:s,asChild:a=!1,...r}){const n=a?Pu:"span";return e.jsx(n,{"data-slot":"badge",className:Re(Yy({variant:s}),t),...r})}function Zy({isOpen:t,onClose:s}){const{user:a,isAuthenticated:r,isLoading:n,error:i}=ry();return h.useEffect(()=>{},[a,r,n,i]),t?e.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4",children:e.jsxs(te,{className:"w-full max-w-2xl max-h-[90vh] overflow-auto",children:[e.jsx(ue,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(xe,{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(ne,{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 rs=h.forwardRef(({className:t,...s},a)=>e.jsx(Iu,{ref:a,"data-slot":"avatar",className:Re("relative flex size-10 shrink-0 overflow-hidden rounded-full",t),...s}));rs.displayName=Iu.displayName;const Li=h.forwardRef(({className:t,...s},a)=>e.jsx(Eu,{ref:a,"data-slot":"avatar-image",className:Re("aspect-square size-full",t),...s}));Li.displayName=Eu.displayName;const ns=h.forwardRef(({className:t,...s},a)=>e.jsx(Fu,{ref:a,"data-slot":"avatar-fallback",className:Re("bg-muted flex size-full items-center justify-center rounded-full",t),...s}));ns.displayName=Fu.displayName;function Yd({...t}){return e.jsx(wg,{"data-slot":"dropdown-menu",...t})}function Zd({...t}){return e.jsx(Cg,{"data-slot":"dropdown-menu-trigger",...t})}function Xd({className:t,sideOffset:s=4,...a}){return e.jsx(Ag,{children:e.jsx(Sg,{"data-slot":"dropdown-menu-content",sideOffset:s,className:Re("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 al({className:t,inset:s,variant:a="default",...r}){return e.jsx(Tg,{"data-slot":"dropdown-menu-item","data-inset":s,"data-variant":a,className:Re("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 Xy({...t}){return e.jsx(Rg,{"data-slot":"alert-dialog",...t})}function Qy({...t}){return e.jsx(kg,{"data-slot":"alert-dialog-portal",...t})}const Ax=h.forwardRef(({className:t,...s},a)=>e.jsx(Mu,{"data-slot":"alert-dialog-overlay",className:Re("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}));Ax.displayName=Mu.displayName;const Sx=h.forwardRef(({className:t,...s},a)=>e.jsxs(Qy,{children:[e.jsx(Ax,{}),e.jsx(_u,{"data-slot":"alert-dialog-content",ref:a,className:Re("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})]}));Sx.displayName=_u.displayName;function Jy({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-header",className:Re("flex flex-col gap-2 text-center sm:text-left",t),...s})}function qy({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-footer",className:Re("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s})}function eb({className:t,...s}){return e.jsx(Dg,{"data-slot":"alert-dialog-title",className:Re("text-lg font-semibold",t),...s})}function tb({className:t,...s}){return e.jsx(Pg,{"data-slot":"alert-dialog-description",className:Re("text-muted-foreground text-sm",t),...s})}function sb({className:t,...s}){return e.jsx(Eg,{className:Re(bn(),t),...s})}function ab({className:t,...s}){return e.jsx(Ig,{className:Re(bn({variant:"outline"}),t),...s})}const Va={async list(t){return(await Ne.get("/notifications",{params:t})).data},async getUnreadCount(){return(await Ne.get("/notifications/unread-count")).data},async markAsRead(t){return(await Ne.patch(`/notifications/${t}/read`)).data},async markAllAsRead(){return(await Ne.post("/notifications/mark-all-read")).data},async delete(t){return(await Ne.delete(`/notifications/${t}`)).data}},rb=async()=>(await Ne.get("/notifications/subscriptions")).data.data.subscriptions;let ir=null;function nb(){return"https://re-workflow-nt-dev.siplsolutions.com"}function Lr(t){const s=nb();return ir||(ir=w0(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 Vl(t,s,a){a?t.emit("join:request",{requestId:s,userId:a}):t.emit("join:request",s)}function Tx(t,s){t.emit("leave:request",s)}function kx(t,s){t.emit("join:user",{userId:s})}function Ns({children:t,currentPage:s="dashboard",onNavigate:a,onNewRequest:r,onLogout:n}){const[i,l]=h.useState(!1),[o,d]=h.useState(!1),[c,m]=h.useState([]),[u,x]=h.useState(0),[p,g]=h.useState(!1),{user:y}=Jt(),f=h.useMemo(()=>{try{const k=at.getUserData();return(k==null?void 0:k.jobTitle)==="Dealer"}catch(k){return console.error("[PageLayout] Error checking dealer status:",k),!1}},[]),b=()=>{var k,L;try{if(y!=null&&y.displayName&&typeof y.displayName=="string"){const D=y.displayName.split(" ").filter(Boolean);return D.length>=2?`${((k=D[0])==null?void 0:k[0])||""}${((L=D[D.length-1])==null?void 0:L[0])||""}`.toUpperCase():y.displayName.substring(0,2).toUpperCase()}return y!=null&&y.email&&typeof y.email=="string"?y.email.substring(0,2).toUpperCase():"U"}catch(D){return console.error("[PageLayout] Error getting user initials:",D),"U"}},v=h.useMemo(()=>{const k=[{id:"dashboard",label:"Dashboard",icon:Vf},{id:"requests",label:"All Requests",icon:Xu}];return f||k.push({id:"my-requests",label:"My Requests",icon:_t}),k.push({id:"open-requests",label:"Open Requests",icon:Pe},{id:"closed-requests",label:"Closed Requests",icon:De},{id:"shared-summaries",label:"Shared Summary",icon:Br}),k},[f]),A=()=>{l(!i)},w=async k=>{var L;try{if(k.isRead||(await Va.markAsRead(k.notificationId),m(D=>D.map(S=>S.notificationId===k.notificationId?{...S,isRead:!0}:S)),x(D=>Math.max(0,D-1))),k.actionUrl&&a){const D=(L=k.metadata)==null?void 0:L.requestNumber;if(D){let S=`request/${D}`;(k.notificationType==="mention"||k.notificationType==="comment"||k.notificationType==="worknote")&&(S+="?tab=worknotes"),a(S)}}g(!1)}catch(D){console.error("[PageLayout] Error handling notification click:",D)}},T=async()=>{try{await Va.markAllAsRead(),m(k=>k.map(L=>({...L,isRead:!0}))),x(0)}catch(k){console.error("[PageLayout] Error marking all as read:",k)}};return h.useEffect(()=>{const k=y==null?void 0:y.userId;if(!k)return;let L=!0;(async()=>{var N,P;try{const R=await Va.list({page:1,limit:4,unreadOnly:!1});if(!L)return;const O=((N=R.data)==null?void 0:N.notifications)||[];m(O),x(((P=R.data)==null?void 0:P.unreadCount)||0)}catch(R){console.error("[PageLayout] Failed to fetch notifications:",R)}})();const S=Lr();if(S){kx(S,k);const N=P=>{L&&(m(R=>[P.notification,...R].slice(0,4)),x(R=>R+1))};return S.on("notification:new",N),()=>{L=!1,S.off("notification:new",N)}}return()=>{L=!1}},[y]),h.useEffect(()=>{const k=()=>{window.innerWidth>=768?l(!0):l(!1)};return k(),window.addEventListener("resize",k),()=>window.removeEventListener("resize",k)},[]),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:_i,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.map(k=>e.jsxs("button",{onClick:()=>{a==null||a(k.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===k.id?"bg-re-green text-white font-medium":"text-gray-300 hover:bg-gray-900 hover:text-white"}`,children:[e.jsx(k.icon,{className:"w-4 h-4 shrink-0"}),e.jsx("span",{className:"truncate",children:k.label})]},k.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(vs,{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:A,className:"shrink-0 h-10 w-10 sidebar-toggle",children:i?e.jsx(zf,{className:"w-5 h-5 text-gray-600"}):e.jsx(Hf,{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(vs,{className:"w-4 h-4"}),"New Request"]}),e.jsxs(Yd,{open:p,onOpenChange:g,children:[e.jsx(Zd,{asChild:!0,children:e.jsxs(F,{variant:"ghost",size:"icon",className:"relative shrink-0 h-10 w-10",children:[e.jsx(ks,{className:"w-5 h-5"}),u>0&&e.jsx(ne,{className:"absolute -top-1 -right-1 w-5 h-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center p-0",children:u>9?"9+":u})]})}),e.jsxs(Xd,{align:"end",className:"w-96 max-h-[500px]",children:[e.jsxs("div",{className:"p-3 border-b flex items-center justify-between sticky top-0 bg-white z-10",children:[e.jsx("h4",{className:"font-semibold text-base",children:"Notifications"}),u>0&&e.jsx(F,{variant:"ghost",size:"sm",className:"text-xs text-blue-600 hover:text-blue-700 h-auto p-1",onClick:k=>{k.stopPropagation(),T()},children:"Mark all as read"})]}),e.jsx("div",{className:"max-h-[400px] overflow-y-auto",children:c.length===0?e.jsxs("div",{className:"p-6 text-center",children:[e.jsx(ks,{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:c.map(k=>e.jsx("div",{className:`p-3 hover:bg-gray-50 cursor-pointer transition-colors ${k.isRead?"":"bg-blue-50"}`,onClick:()=>w(k),children:e.jsxs("div",{className:"flex gap-2",children:[!k.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 ${k.isRead?"font-medium":"font-semibold"}`,children:k.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-2",children:k.message}),e.jsx("p",{className:"text-xs text-gray-400 mt-1",children:Wu(new Date(k.createdAt),{addSuffix:!0})})]})]})},k.notificationId))})}),c.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(Yd,{children:[e.jsx(Zd,{asChild:!0,children:e.jsxs(rs,{className:"cursor-pointer shrink-0 h-10 w-10",children:[e.jsx(Li,{src:(y==null?void 0:y.picture)||""}),e.jsx(ns,{className:"bg-re-green text-white text-sm",children:b()})]})}),e.jsxs(Xd,{align:"end",children:[e.jsxs(al,{onClick:()=>a==null?void 0:a("profile"),children:[e.jsx(_t,{className:"w-4 h-4 mr-2"}),"Profile"]}),e.jsxs(al,{onClick:()=>a==null?void 0:a("settings"),children:[e.jsx(za,{className:"w-4 h-4 mr-2"}),"Settings"]}),e.jsxs(al,{onClick:()=>d(!0),className:"text-red-600 focus:text-red-600",children:[e.jsx(Xi,{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(Xy,{open:o,onOpenChange:d,children:e.jsxs(Sx,{children:[e.jsxs(Jy,{children:[e.jsxs(eb,{className:"flex items-center gap-2",children:[e.jsx(Xi,{className:"w-5 h-5 text-red-600"}),"Confirm Logout"]}),e.jsx(tb,{className:"pt-2",children:"Are you sure you want to logout? You will need to sign in again to access your account."})]}),e.jsxs(qy,{children:[e.jsx(ab,{onClick:()=>d(!1),children:"Cancel"}),e.jsxs(sb,{onClick:async()=>{if(d(!1),n)try{await n()}catch(k){console.error("🔴 Error calling onLogout:",k)}else console.error("🔴 ERROR: onLogout is undefined!")},className:"bg-red-600 hover:bg-red-700 text-white focus:ring-red-600",children:[e.jsx(Xi,{className:"w-4 h-4 mr-2"}),"Logout"]})]})]})})]})}const kn=()=>Z0(),Wr=J0,ib=()=>{try{const t=localStorage.getItem("dashboard_viewAsUser");return t?JSON.parse(t):!1}catch{return!1}},lb={viewAsUser:ib()},Rx=zr({name:"dashboard",initialState:lb,reducers:{setViewAsUser:(t,s)=>{t.viewAsUser=s.payload,localStorage.setItem("dashboard_viewAsUser",JSON.stringify(s.payload))}}}),{setViewAsUser:ob}=Rx.actions;function cb(){const[t,s]=h.useState("all"),[a,r]=h.useState(void 0),[n,i]=h.useState(void 0),[l,o]=h.useState(!1),d=h.useCallback(u=>{const x=u;s(x),x!=="custom"?(r(void 0),i(void 0),o(!1)):o(!0)},[]),c=h.useCallback(u=>{if(a&&n){if(a>n){const x=a;r(n),i(x),u(n,x)}else u(a,n);o(!1)}},[a,n]),m=h.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:d,handleApplyCustomDate:c,resetCustomDates:m}}function db(){const[t,s]=h.useState({page:1,totalPages:1,totalRecords:0}),[a,r]=h.useState({page:1,totalPages:1,totalRecords:0}),[n,i]=h.useState({page:1,totalPages:1,totalRecords:0}),[l,o]=h.useState({page:1,totalPages:1,totalRecords:0}),d=h.useCallback((f,b,v)=>{s({page:f,totalPages:b,totalRecords:v})},[]),c=h.useCallback((f,b,v)=>{r({page:f,totalPages:b,totalRecords:v})},[]),m=h.useCallback((f,b,v)=>{i({page:f,totalPages:b,totalRecords:v})},[]),u=h.useCallback((f,b,v)=>{o({page:f,totalPages:b,totalRecords:v})},[]),x=h.useCallback((f,b)=>{f>=1&&f<=t.totalPages&&(s(v=>({...v,page:f})),b(f))},[t.totalPages]),p=h.useCallback((f,b)=>{f>=1&&f<=a.totalPages&&(r(v=>({...v,page:f})),b(f))},[a.totalPages]),g=h.useCallback((f,b)=>{f>=1&&f<=n.totalPages&&(i(v=>({...v,page:f})),b(f))},[n.totalPages]),y=h.useCallback((f,b)=>{f>=1&&f<=l.totalPages&&(o(v=>({...v,page:f})),b(f))},[l.totalPages]);return{activity:t,critical:a,deadlines:n,approver:l,updateActivityPagination:d,updateCriticalPagination:c,updateDeadlinesPagination:m,updateApproverPagination:u,handleActivityPageChange:x,handleCriticalPageChange:p,handleDeadlinesPageChange:g,handleApproverPageChange:y}}class mb{async getKPIs(s,a,r,n){try{const i={dateRange:s};return s==="custom"&&a&&r&&(i.startDate=a.toISOString(),i.endDate=r.toISOString()),n&&(i.viewAsUser="true"),(await Ne.get("/dashboard/kpis",{params:i})).data.data}catch(i){throw console.error("Failed to fetch KPIs:",i),i}}async getRequestStats(s,a,r,n,i,l,o,d,c,m,u,x,p){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),d&&d!=="all"&&(g.initiator=d),c&&c!=="all"&&(g.approver=c),m&&(g.approverType=m),u&&(g.search=u),x&&x!=="all"&&(g.slaCompliance=x),p&&(g.viewAsUser="true"),(await Ne.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 Ne.get("/dashboard/stats/tat-efficiency",{params:{dateRange:s}})).data.data}catch(a){throw console.error("Failed to fetch TAT efficiency:",a),a}}async getApproverLoad(s){try{return(await Ne.get("/dashboard/stats/approver-load",{params:{dateRange:s}})).data.data}catch(a){throw console.error("Failed to fetch approver load:",a),a}}async getEngagementStats(s){try{return(await Ne.get("/dashboard/stats/engagement",{params:{dateRange:s}})).data.data}catch(a){throw console.error("Failed to fetch engagement stats:",a),a}}async getAIInsights(s){try{return(await Ne.get("/dashboard/stats/ai-insights",{params:{dateRange:s}})).data.data}catch(a){throw console.error("Failed to fetch AI insights:",a),a}}async getRecentActivity(s=1,a=10,r){try{const n={page:s,limit:a};r&&(n.viewAsUser="true");const i=await Ne.get("/dashboard/activity/recent",{params:n});return{activities:i.data.data,pagination:i.data.pagination}}catch(n){throw console.error("Failed to fetch recent activity:",n),n}}async getCriticalRequests(s=1,a=10,r){try{const n={page:s,limit:a};r&&(n.viewAsUser="true");const i=await Ne.get("/dashboard/requests/critical",{params:n});return{criticalRequests:i.data.data,pagination:i.data.pagination}}catch(n){throw console.error("Failed to fetch critical requests:",n),n}}async getUpcomingDeadlines(s=1,a=10,r){try{const n={page:s,limit:a};r&&(n.viewAsUser="true");const i=await Ne.get("/dashboard/deadlines/upcoming",{params:n});return{deadlines:i.data.data,pagination:i.data.pagination}}catch(n){throw console.error("Failed to fetch upcoming deadlines:",n),n}}async getDepartmentStats(s,a,r){try{const n={dateRange:s};return s==="custom"&&a&&r&&(n.startDate=a.toISOString(),n.endDate=r.toISOString()),(await Ne.get("/dashboard/stats/by-department",{params:n})).data.data}catch(n){throw console.error("Failed to fetch department stats:",n),n}}async getPriorityDistribution(s,a,r){try{const n={dateRange:s};return s==="custom"&&a&&r&&(n.startDate=a.toISOString(),n.endDate=r.toISOString()),(await Ne.get("/dashboard/stats/priority-distribution",{params:n})).data.data}catch(n){throw console.error("Failed to fetch priority distribution:",n),n}}async getAIRemarkUtilization(s,a,r){try{const n={dateRange:s};return s==="custom"&&a&&r&&(n.startDate=a.toISOString(),n.endDate=r.toISOString()),(await Ne.get("/dashboard/stats/ai-remark-utilization",{params:n})).data.data}catch(n){throw console.error("Failed to fetch AI remark utilization:",n),n}}async getApproverPerformance(s,a=1,r=10,n,i,l,o){try{const d={dateRange:s,page:a,limit:r||10};s==="custom"&&n&&i&&(d.startDate=n.toISOString(),d.endDate=i.toISOString()),l&&l!=="all"&&(d.priority=l),o&&o!=="all"&&(d.slaCompliance=o),console.log("[Dashboard Service] Fetching approver performance with params:",d);const c=await Ne.get("/dashboard/stats/approver-performance",{params:d});return{performance:c.data.data,pagination:c.data.pagination}}catch(d){throw console.error("Failed to fetch approver performance:",d),d}}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 Ne.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,d,c){try{const m={page:s,limit:a,filterUserId:n,filterType:i,filterCategory:l,filterSeverity:o};r&&(m.dateRange=r),r==="custom"&&d&&c&&(m.startDate=d.toISOString(),m.endDate=c.toISOString());const u=await Ne.get("/dashboard/reports/activity-log",{params:m});return{activities:u.data.data,pagination:u.data.pagination}}catch(m){throw console.error("Failed to fetch activity log report:",m),m}}async getDepartments(){try{return(await Ne.get("/dashboard/metadata/departments")).data.data.departments||[]}catch(s){throw console.error("Failed to fetch departments:",s),s}}async getWorkflowAgingReport(s=7,a=1,r=50,n,i,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 d=await Ne.get("/dashboard/reports/workflow-aging",{params:o});return{agingData:d.data.data,pagination:d.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 Ne.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,d,c,m){try{const u={approverId:s,page:a,limit:r};n&&(u.dateRange=n),n==="custom"&&i&&l&&(u.startDate=i.toISOString(),u.endDate=l.toISOString()),o&&(u.status=o),d&&(u.priority=d),c&&(u.slaCompliance=c),m&&(u.search=m);const x=await Ne.get("/dashboard/requests/by-approver",{params:u});return{requests:x.data.data,pagination:x.data.pagination}}catch(u){throw console.error("Failed to fetch requests by approver:",u),u}}}const Ct=new mb;function ub({isAdmin:t,viewAsUser:s=!1,userId:a,dateRange:r,customStartDate:n,customEndDate:i,onPaginationUpdate:l}){const[o,d]=h.useState(null),[c,m]=h.useState([]),[u,x]=h.useState([]),[p,g]=h.useState([]),[y,f]=h.useState([]),[b,v]=h.useState([]),[A,w]=h.useState(null),[T,k]=h.useState([]),[L,D]=h.useState(!0),[S,N]=h.useState(!1),P=h.useRef(l);P.current=l;const R=h.useCallback(async(C=!1)=>{try{C?N(!0):D(!0);const j=[Ct.getKPIs(r,n,i,s),Ct.getRecentActivity(1,10,s),Ct.getCriticalRequests(1,10,s),Ct.getUpcomingDeadlines(1,10,s)],U=!t&&a?Ct.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,$=t?[Ct.getDepartmentStats(r,n,i),Ct.getPriorityDistribution(r,n,i),Ct.getAIRemarkUtilization(r,n,i),Ct.getApproverPerformance(r,1,10,n,i)]:[],[_,se,W]=await Promise.all([Promise.all(j),U,Promise.all($)]),ce=_[0],Z=_[1],I=_[2],V=_[3];if(!t&&se&&(ce.requestVolume=se),d(ce),m(Z.activities),P.current.activity(Z.pagination.currentPage,Z.pagination.totalPages,Z.pagination.totalRecords),x(I.criticalRequests),P.current.critical(I.pagination.currentPage,I.pagination.totalPages,I.pagination.totalRecords),v(V.deadlines),P.current.deadlines(V.pagination.currentPage,V.pagination.totalPages,V.pagination.totalRecords),t&&W.length>=4){const z=W[0],X=W[1],Y=W[2],G=W[3];g(z),f(X),w(Y),k(G.performance),P.current.approver(G.pagination.currentPage,G.pagination.totalPages,G.pagination.totalRecords)}else t||(g([]),f([]),w(null),k([]))}catch(j){console.error("Failed to fetch dashboard data:",j)}finally{D(!1),N(!1)}},[t,s,a,r,n,i]),O=h.useCallback(async(C=1)=>{try{const j=await Ct.getRecentActivity(C,10,s);m(j.activities),P.current.activity(j.pagination.currentPage,j.pagination.totalPages,j.pagination.totalRecords)}catch(j){console.error("Failed to fetch recent activities:",j)}},[s]),E=h.useCallback(async(C=1)=>{try{const j=await Ct.getCriticalRequests(C,10,s);x(j.criticalRequests),P.current.critical(j.pagination.currentPage,j.pagination.totalPages,j.pagination.totalRecords)}catch(j){console.error("Failed to fetch critical requests:",j)}},[s]),M=h.useCallback(async(C=1)=>{try{const j=await Ct.getUpcomingDeadlines(C,10,s);v(j.deadlines),P.current.deadlines(j.pagination.currentPage,j.pagination.totalPages,j.pagination.totalRecords)}catch(j){console.error("Failed to fetch upcoming deadlines:",j)}},[s]),B=h.useCallback(async(C=1)=>{try{const j=await Ct.getApproverPerformance(r,C,10,n,i);k(j.performance),P.current.approver(j.pagination.currentPage,j.pagination.totalPages,j.pagination.totalRecords)}catch(j){console.error("Failed to fetch approver performance:",j)}},[r,n,i]);return{kpis:o,recentActivity:c,criticalRequests:u,departmentStats:p,priorityDistribution:y,upcomingDeadlines:b,aiRemarkUtilization:A,approverPerformance:T,loading:L,refreshing:S,fetchDashboardData:R,fetchRecentActivities:O,fetchCriticalRequests:E,fetchUpcomingDeadlines:M,fetchApproverPerformance:B}}const Ta={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 xb{constructor(){Gi(this,"config",null);Gi(this,"loading",null)}async getConfig(){return this.config?this.config:this.loading?this.loading:(this.loading=this.fetchConfig(),this.config=await this.loading,this.loading=null,this.config)}async fetchConfig(){var s;try{const a=await Ne.get("/config"),r=((s=a.data)==null?void 0:s.data)||a.data;return{...Ta,...r,workingHours:{...Ta.workingHours,...r.workingHours},tat:{...Ta.tat,...r.tat},upload:{...Ta.upload,...r.upload},workflow:{...Ta.workflow,...r.workflow},workNotes:{...Ta.workNotes,...r.workNotes},features:{...Ta.features,...r.features},ui:{...Ta.ui,...r.ui}}}catch(a){return console.error("[ConfigService] ⚠️ Failed to fetch config from server, using defaults:",a),Ta}}async refreshConfig(){return this.config=null,this.loading=null,this.getConfig()}getCachedConfig(){return this.config}isLoaded(){return this.config!==null}}const hb=new xb;let pb=9,gb=18,fb=1,yb=5,Qd=!1;async function bb(){if(!Qd)try{const t=await hb.getConfig();pb=t.workingHours.START_HOUR,gb=t.workingHours.END_HOUR,fb=t.workingHours.START_DAY,yb=t.workingHours.END_DAY,Qd=!0}catch{console.warn("[SLA Tracker] ⚠️ Using default working hours (9 AM - 6 PM)")}}bb().catch(()=>{});function Lt(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",d=r===1?"hour":"hours",c=n===1?"min":"m";return n>0?`${a} ${o} ${r} ${d} ${n}${c}`:`${a} ${o} ${r} ${d}`}const i=r===1?"hour":"hours",l=n===1?"min":"m";return n>0?`${r} ${i} ${n}${l}`:`${r} ${i}`}async function vb(t,s,a){const r=[];let n=1,i=!0;const l=100;for(;i&&n<=l;){const x=await Ct.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 p=[`"${(x.approverName||"Unknown").replace(/"/g,'""')}"`,x.totalApproved||0,x.tatCompliancePercent||0,Lt(x.avgResponseHours),x.pendingCount||0];o.push(p.join(","))});const d=o.join(`
|
||
`),c=new Blob([d],{type:"text/csv;charset=utf-8;"}),m=document.createElement("a"),u=URL.createObjectURL(c);m.setAttribute("href",u),m.setAttribute("download",`approver-performance-report-${new Date().toISOString().split("T")[0]}.csv`),m.style.visibility="hidden",document.body.appendChild(m),m.click(),document.body.removeChild(m),URL.revokeObjectURL(u)}async function jb(t,s,a){const r=await Ct.getDepartmentStats(t,s,a),n=[["Department","Total Requests","Approved","Rejected","In Progress","Approval Rate (%)"].join(",")];r.forEach(c=>{const m=[`"${(c.department||"Unknown").replace(/"/g,'""')}"`,c.totalRequests||0,c.approved||0,c.rejected||0,c.inProgress||0,c.approvalRate||0];n.push(m.join(","))});const i=n.join(`
|
||
`),l=new Blob([i],{type:"text/csv;charset=utf-8;"}),o=document.createElement("a"),d=URL.createObjectURL(l);o.setAttribute("href",d),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(d)}function Nb(){const[t,s]=h.useState(!1),[a,r]=h.useState(!1),n=h.useCallback(async(l,o,d)=>{try{s(!0),await jb(l,o,d)}catch(c){console.error("Failed to export department stats:",c),alert("Failed to export department statistics. Please try again.")}finally{s(!1)}},[]),i=h.useCallback(async(l,o,d)=>{try{r(!0),await vb(l,o,d)}catch(c){console.error("Failed to export approver performance:",c),alert("Failed to export approver performance data. Please try again.")}finally{r(!1)}},[]);return{exportingDeptStats:t,exportingApproverPerformance:a,handleExportDepartmentStats:n,handleExportApproverPerformance:i}}function Ps({className:t,...s}){return e.jsx(Fg,{"data-slot":"switch",className:Re("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(Mg,{"data-slot":"switch-thumb",className:Re("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 le({className:t,...s}){return e.jsx(_g,{"data-slot":"label",className:Re("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 wb({isAdmin:t,effectiveIsAdmin:s,viewAsUser:a,onToggleView:r,quickActions:n,userDisplayName:i,userEmail:l}){const o=i||(l==null?void 0:l.split("@")[0])||"User";return e.jsxs(te,{className:"relative overflow-hidden shadow-xl border-0","data-testid":"dashboard-hero",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900"}),e.jsxs(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(fo,{className:`w-3 h-3 sm:w-3.5 sm:h-3.5 ${a?"text-gray-300":"text-red-600"}`}),e.jsx(le,{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(Ps,{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(_t,{className:`w-3 h-3 sm:w-3.5 sm:h-3.5 ${a?"text-red-600":"text-gray-300"}`}),e.jsx(le,{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((d,c)=>e.jsxs(F,{onClick:d.action,className:`${d.color} text-white border-0 shadow-lg hover:shadow-xl transition-all duration-200`,size:window.innerWidth<640?"sm":"lg","data-testid":`quick-action-${d.label.toLowerCase().replace(/\s+/g,"-")}`,children:[e.jsx(d.icon,{className:"w-4 h-4 sm:w-5 sm:h-5 mr-1 sm:mr-2"}),d.label]},c))})]})})]})]})}function Ve({...t}){return e.jsx(Lg,{"data-slot":"select",...t})}function ze({...t}){return e.jsx(Ug,{"data-slot":"select-value",...t})}function He({className:t,size:s="default",children:a,...r}){return e.jsxs(Og,{"data-slot":"select-trigger","data-size":s,className:Re("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($g,{asChild:!0,children:e.jsx(yo,{className:"size-4 opacity-50"})})]})}function We({className:t,children:s,position:a="popper",...r}){return e.jsx(Bg,{children:e.jsxs(Vg,{"data-slot":"select-content",className:Re("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(Cb,{}),e.jsx(zg,{className:Re("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(Ab,{})]})})}function K({className:t,children:s,...a}){return e.jsxs(Hg,{"data-slot":"select-item",className:Re("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(Wg,{children:e.jsx(Vr,{className:"size-4"})})}),e.jsx(Gg,{children:s})]})}function Cb({className:t,...s}){return e.jsx(Kg,{"data-slot":"select-scroll-up-button",className:Re("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(Qu,{className:"size-4"})})}function Ab({className:t,...s}){return e.jsx(Yg,{"data-slot":"select-scroll-down-button",className:Re("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(yo,{className:"size-4"})})}function Gt({className:t,orientation:s="horizontal",decorative:a=!0,...r}){return e.jsx(Zg,{"data-slot":"separator-root",decorative:a,orientation:s,className:Re("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 Ys({...t}){return e.jsx(Xg,{"data-slot":"popover",...t})}function Zs({...t}){return e.jsx(Qg,{"data-slot":"popover-trigger",...t})}function Xs({className:t,align:s="center",sideOffset:a=4,...r}){return e.jsx(Jg,{children:e.jsx(qg,{"data-slot":"popover-content",align:s,sideOffset:a,className:Re("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 et=function(){return et=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},et.apply(this,arguments)};function Sb(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 Dx(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 Rn(t){return t.mode==="multiple"}function Dn(t){return t.mode==="range"}function Oi(t){return t.mode==="single"}var Tb={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 kb(t,s){return Ye(t,"LLLL y",s)}function Rb(t,s){return Ye(t,"d",s)}function Db(t,s){return Ye(t,"LLLL",s)}function Pb(t){return"".concat(t)}function Ib(t,s){return Ye(t,"cccccc",s)}function Eb(t,s){return Ye(t,"yyyy",s)}var Fb=Object.freeze({__proto__:null,formatCaption:kb,formatDay:Rb,formatMonthCaption:Db,formatWeekNumber:Pb,formatWeekdayName:Ib,formatYearCaption:Eb}),Mb=function(t,s,a){return Ye(t,"do MMMM (EEEE)",a)},_b=function(){return"Month: "},Lb=function(){return"Go to next month"},Ob=function(){return"Go to previous month"},$b=function(t,s){return Ye(t,"cccc",s)},Ub=function(t){return"Week n. ".concat(t)},Bb=function(){return"Year: "},Vb=Object.freeze({__proto__:null,labelDay:Mb,labelMonthDropdown:_b,labelNext:Lb,labelPrevious:Ob,labelWeekNumber:Ub,labelWeekday:$b,labelYearDropdown:Bb});function zb(){var t="buttons",s=Tb,a=kf,r={},n={},i=1,l={},o=new Date;return{captionLayout:t,classNames:s,formatters:Fb,labels:Vb,locale:a,modifiersClassNames:r,modifiers:n,numberOfMonths:i,styles:l,today:o,mode:"default"}}function Hb(t){var s=t.fromYear,a=t.toYear,r=t.fromMonth,n=t.toMonth,i=t.fromDate,l=t.toDate;return r?i=Gs(r):s&&(i=new Date(s,0,1)),n?l=xo(n):a&&(l=new Date(a,11,31)),{fromDate:i?Fd(i):void 0,toDate:l?Fd(l):void 0}}var Px=h.createContext(void 0);function Wb(t){var s,a=t.initialProps,r=zb(),n=Hb(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 d;(Oi(a)||Rn(a)||Dn(a))&&(d=a.onSelect);var c=et(et(et({},r),a),{captionLayout:o,classNames:et(et({},r.classNames),a.classNames),components:et({},a.components),formatters:et(et({},r.formatters),a.formatters),fromDate:i,labels:et(et({},r.labels),a.labels),mode:a.mode||r.mode,modifiers:et(et({},r.modifiers),a.modifiers),modifiersClassNames:et(et({},r.modifiersClassNames),a.modifiersClassNames),onSelect:d,styles:et(et({},r.styles),a.styles),toDate:l});return e.jsx(Px.Provider,{value:c,children:t.children})}function Pt(){var t=h.useContext(Px);if(!t)throw new Error("useDayPicker must be used within a DayPickerProvider.");return t}function Ix(t){var s=Pt(),a=s.locale,r=s.classNames,n=s.styles,i=s.formatters.formatCaption;return e.jsx("div",{className:r.caption_label,style:n.caption_label,"aria-live":"polite",role:"presentation",id:t.id,children:i(t.displayMonth,{locale:a})})}function Gb(t){return e.jsx("svg",et({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 Ex(t){var s,a,r=t.onChange,n=t.value,i=t.children,l=t.caption,o=t.className,d=t.style,c=Pt(),m=(a=(s=c.components)===null||s===void 0?void 0:s.IconDropdown)!==null&&a!==void 0?a:Gb;return e.jsxs("div",{className:o,style:d,children:[e.jsx("span",{className:c.classNames.vhidden,children:t["aria-label"]}),e.jsx("select",{name:t.name,"aria-label":t["aria-label"],className:c.classNames.dropdown,style:c.styles.dropdown,value:n,onChange:r,children:i}),e.jsxs("div",{className:c.classNames.caption_label,style:c.styles.caption_label,"aria-hidden":"true",children:[l,e.jsx(m,{className:c.classNames.dropdown_icon,style:c.styles.dropdown_icon})]})]})}function Kb(t){var s,a=Pt(),r=a.fromDate,n=a.toDate,i=a.styles,l=a.locale,o=a.formatters.formatMonthCaption,d=a.classNames,c=a.components,m=a.labels.labelMonthDropdown;if(!r)return e.jsx(e.Fragment,{});if(!n)return e.jsx(e.Fragment,{});var u=[];if(Ff(r,n))for(var x=Gs(r),p=r.getMonth();p<=n.getMonth();p++)u.push(Yi(x,p));else for(var x=Gs(new Date),p=0;p<=11;p++)u.push(Yi(x,p));var g=function(f){var b=Number(f.target.value),v=Yi(Gs(t.displayMonth),b);t.onChange(v)},y=(s=c==null?void 0:c.Dropdown)!==null&&s!==void 0?s:Ex;return e.jsx(y,{name:"months","aria-label":m(),className:d.dropdown_month,style:i.dropdown_month,onChange:g,value:t.displayMonth.getMonth(),caption:o(t.displayMonth,{locale:l}),children:u.map(function(f){return e.jsx("option",{value:f.getMonth(),children:o(f,{locale:l})},f.getMonth())})})}function Yb(t){var s,a=t.displayMonth,r=Pt(),n=r.fromDate,i=r.toDate,l=r.locale,o=r.styles,d=r.classNames,c=r.components,m=r.formatters.formatYearCaption,u=r.labels.labelYearDropdown,x=[];if(!n)return e.jsx(e.Fragment,{});if(!i)return e.jsx(e.Fragment,{});for(var p=n.getFullYear(),g=i.getFullYear(),y=p;y<=g;y++)x.push(Md(Mf(new Date),y));var f=function(v){var A=Md(Gs(a),Number(v.target.value));t.onChange(A)},b=(s=c==null?void 0:c.Dropdown)!==null&&s!==void 0?s:Ex;return e.jsx(b,{name:"years","aria-label":u(),className:d.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 Zb(t,s){var a=h.useState(t),r=a[0],n=a[1],i=s===void 0?r:s;return[i,n]}function Xb(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,d=o===void 0?1:o;if(i&&fn(i,n)<0){var c=-1*(d-1);n=Na(i,c)}return l&&fn(n,l)<0&&(n=l),Gs(n)}function Qb(){var t=Pt(),s=Xb(t),a=Zb(s,t.month),r=a[0],n=a[1],i=function(l){var o;if(!t.disableNavigation){var d=Gs(l);n(d),(o=t.onMonthChange)===null||o===void 0||o.call(t,d)}};return[r,i]}function Jb(t,s){for(var a=s.reverseMonths,r=s.numberOfMonths,n=Gs(t),i=Gs(Na(n,r)),l=fn(i,n),o=[],d=0;d<l;d++){var c=Na(n,d);o.push(c)}return a&&(o=o.reverse()),o}function qb(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=Gs(t);if(!a)return Na(o,l);var d=fn(a,t);if(!(d<i))return Na(o,l)}}function ev(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=Gs(t);if(!a)return Na(o,-l);var d=fn(o,a);if(!(d<=0))return Na(o,-l)}}var Fx=h.createContext(void 0);function tv(t){var s=Pt(),a=Qb(),r=a[0],n=a[1],i=Jb(r,s),l=qb(r,s),o=ev(r,s),d=function(u){return i.some(function(x){return ho(u,x)})},c=function(u,x){d(u)||(x&&Gu(u,x)?n(Na(u,1+s.numberOfMonths*-1)):n(u))},m={currentMonth:r,displayMonths:i,goToMonth:n,goToDate:c,previousMonth:o,nextMonth:l,isDateDisplayed:d};return e.jsx(Fx.Provider,{value:m,children:t.children})}function Pn(){var t=h.useContext(Fx);if(!t)throw new Error("useNavigation must be used within a NavigationProvider");return t}function Jd(t){var s,a=Pt(),r=a.classNames,n=a.styles,i=a.components,l=Pn().goToMonth,o=function(m){l(Na(m,t.displayIndex?-t.displayIndex:0))},d=(s=i==null?void 0:i.CaptionLabel)!==null&&s!==void 0?s:Ix,c=e.jsx(d,{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:c}),e.jsx(Kb,{onChange:o,displayMonth:t.displayMonth}),e.jsx(Yb,{onChange:o,displayMonth:t.displayMonth})]})}function sv(t){return e.jsx("svg",et({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 av(t){return e.jsx("svg",et({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 ui=h.forwardRef(function(t,s){var a=Pt(),r=a.classNames,n=a.styles,i=[r.button_reset,r.button];t.className&&i.push(t.className);var l=i.join(" "),o=et(et({},n.button_reset),n.button);return t.style&&Object.assign(o,t.style),e.jsx("button",et({},t,{ref:s,type:"button",className:l,style:o}))});function rv(t){var s,a,r=Pt(),n=r.dir,i=r.locale,l=r.classNames,o=r.styles,d=r.labels,c=d.labelPrevious,m=d.labelNext,u=r.components;if(!t.nextMonth&&!t.previousMonth)return e.jsx(e.Fragment,{});var x=c(t.previousMonth,{locale:i}),p=[l.nav_button,l.nav_button_previous].join(" "),g=m(t.nextMonth,{locale:i}),y=[l.nav_button,l.nav_button_next].join(" "),f=(s=u==null?void 0:u.IconRight)!==null&&s!==void 0?s:av,b=(a=u==null?void 0:u.IconLeft)!==null&&a!==void 0?a:sv;return e.jsxs("div",{className:l.nav,style:o.nav,children:[!t.hidePrevious&&e.jsx(ui,{name:"previous-month","aria-label":x,className:p,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(b,{className:l.nav_icon,style:o.nav_icon})}),!t.hideNext&&e.jsx(ui,{name:"next-month","aria-label":g,className:y,style:o.nav_button_next,disabled:!t.nextMonth,onClick:t.onNextClick,children:n==="rtl"?e.jsx(b,{className:l.nav_icon,style:o.nav_icon}):e.jsx(f,{className:l.nav_icon,style:o.nav_icon})})]})}function qd(t){var s=Pt().numberOfMonths,a=Pn(),r=a.previousMonth,n=a.nextMonth,i=a.goToMonth,l=a.displayMonths,o=l.findIndex(function(g){return ho(t.displayMonth,g)}),d=o===0,c=o===l.length-1,m=s>1&&(d||!c),u=s>1&&(c||!d),x=function(){r&&i(r)},p=function(){n&&i(n)};return e.jsx(rv,{displayMonth:t.displayMonth,hideNext:m,hidePrevious:u,nextMonth:n,previousMonth:r,onPreviousClick:x,onNextClick:p})}function nv(t){var s,a=Pt(),r=a.classNames,n=a.disableNavigation,i=a.styles,l=a.captionLayout,o=a.components,d=(s=o==null?void 0:o.CaptionLabel)!==null&&s!==void 0?s:Ix,c;return n?c=e.jsx(d,{id:t.id,displayMonth:t.displayMonth}):l==="dropdown"?c=e.jsx(Jd,{displayMonth:t.displayMonth,id:t.id}):l==="dropdown-buttons"?c=e.jsxs(e.Fragment,{children:[e.jsx(Jd,{displayMonth:t.displayMonth,displayIndex:t.displayIndex,id:t.id}),e.jsx(qd,{displayMonth:t.displayMonth,displayIndex:t.displayIndex,id:t.id})]}):c=e.jsxs(e.Fragment,{children:[e.jsx(d,{id:t.id,displayMonth:t.displayMonth,displayIndex:t.displayIndex}),e.jsx(qd,{displayMonth:t.displayMonth,id:t.id})]}),e.jsx("div",{className:r.caption,style:i.caption,children:c})}function iv(t){var s=Pt(),a=s.footer,r=s.styles,n=s.classNames.tfoot;return a?e.jsx("tfoot",{className:n,style:r.tfoot,children:e.jsx("tr",{children:e.jsx("td",{colSpan:8,children:a})})}):e.jsx(e.Fragment,{})}function lv(t,s,a){for(var r=a?po(new Date):go(new Date,{locale:t,weekStartsOn:s}),n=[],i=0;i<7;i++){var l=zs(r,i);n.push(l)}return n}function ov(){var t=Pt(),s=t.classNames,a=t.styles,r=t.showWeekNumber,n=t.locale,i=t.weekStartsOn,l=t.ISOWeek,o=t.formatters.formatWeekdayName,d=t.labels.labelWeekday,c=lv(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}),c.map(function(m,u){return e.jsx("th",{scope:"col",className:s.head_cell,style:a.head_cell,"aria-label":d(m,{locale:n}),children:o(m,{locale:n})},u)})]})}function cv(){var t,s=Pt(),a=s.classNames,r=s.styles,n=s.components,i=(t=n==null?void 0:n.HeadRow)!==null&&t!==void 0?t:ov;return e.jsx("thead",{style:r.head,className:a.head,children:e.jsx(i,{})})}function dv(t){var s=Pt(),a=s.locale,r=s.formatters.formatDay;return e.jsx(e.Fragment,{children:r(t.date,{locale:a})})}var Ro=h.createContext(void 0);function mv(t){if(!Rn(t.initialProps)){var s={selected:void 0,modifiers:{disabled:[]}};return e.jsx(Ro.Provider,{value:s,children:t.children})}return e.jsx(uv,{initialProps:t.initialProps,children:t.children})}function uv(t){var s=t.initialProps,a=t.children,r=s.selected,n=s.min,i=s.max,l=function(c,m,u){var x,p;(x=s.onDayClick)===null||x===void 0||x.call(s,c,m,u);var g=!!(m.selected&&n&&(r==null?void 0:r.length)===n);if(!g){var y=!!(!m.selected&&i&&(r==null?void 0:r.length)===i);if(!y){var f=r?Dx([],r):[];if(m.selected){var b=f.findIndex(function(v){return Os(c,v)});f.splice(b,1)}else f.push(c);(p=s.onSelect)===null||p===void 0||p.call(s,f,c,m,u)}}},o={disabled:[]};r&&o.disabled.push(function(c){var m=i&&r.length>i-1,u=r.some(function(x){return Os(x,c)});return!!(m&&!u)});var d={selected:r,onDayClick:l,modifiers:o};return e.jsx(Ro.Provider,{value:d,children:a})}function Do(){var t=h.useContext(Ro);if(!t)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return t}function xv(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:_l(r,t)?{from:t,to:n}:{from:r,to:t}:n?_l(t,n)?{from:n,to:t}:{from:t,to:n}:r?Gu(t,r)?{from:t,to:r}:{from:r,to:t}:{from:t,to:void 0}}var Po=h.createContext(void 0);function hv(t){if(!Dn(t.initialProps)){var s={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(Po.Provider,{value:s,children:t.children})}return e.jsx(pv,{initialProps:t.initialProps,children:t.children})}function pv(t){var s=t.initialProps,a=t.children,r=s.selected,n=r||{},i=n.from,l=n.to,o=s.min,d=s.max,c=function(p,g,y){var f,b;(f=s.onDayClick)===null||f===void 0||f.call(s,p,g,y);var v=xv(p,r);(b=s.onSelect)===null||b===void 0||b.call(s,v,p,g,y)},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:Ki(i,o-1),before:zs(i,o-1)}),i&&l&&m.disabled.push({after:i,before:zs(i,o-1)}),!i&&l&&m.disabled.push({after:Ki(l,o-1),before:zs(l,o-1)})),d){if(i&&!l&&(m.disabled.push({before:zs(i,-d+1)}),m.disabled.push({after:zs(i,d-1)})),i&&l){var u=Ra(l,i)+1,x=d-u;m.disabled.push({before:Ki(i,x)}),m.disabled.push({after:zs(l,x)})}!i&&l&&(m.disabled.push({before:zs(l,-d+1)}),m.disabled.push({after:zs(l,d-1)}))}return e.jsx(Po.Provider,{value:{selected:r,onDayClick:c,modifiers:m},children:a})}function Io(){var t=h.useContext(Po);if(!t)throw new Error("useSelectRange must be used within a SelectRangeProvider");return t}function Zn(t){return Array.isArray(t)?Dx([],t):t!==void 0?[t]:[]}function gv(t){var s={};return Object.entries(t).forEach(function(a){var r=a[0],n=a[1];s[r]=Zn(n)}),s}var xa;(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"})(xa||(xa={}));var fv=xa.Selected,ka=xa.Disabled,yv=xa.Hidden,bv=xa.Today,rl=xa.RangeEnd,nl=xa.RangeMiddle,il=xa.RangeStart,vv=xa.Outside;function jv(t,s,a){var r,n=(r={},r[fv]=Zn(t.selected),r[ka]=Zn(t.disabled),r[yv]=Zn(t.hidden),r[bv]=[t.today],r[rl]=[],r[nl]=[],r[il]=[],r[vv]=[],r);return t.fromDate&&n[ka].push({before:t.fromDate}),t.toDate&&n[ka].push({after:t.toDate}),Rn(t)?n[ka]=n[ka].concat(s.modifiers[ka]):Dn(t)&&(n[ka]=n[ka].concat(a.modifiers[ka]),n[il]=a.modifiers[il],n[nl]=a.modifiers[nl],n[rl]=a.modifiers[rl]),n}var Mx=h.createContext(void 0);function Nv(t){var s=Pt(),a=Do(),r=Io(),n=jv(s,a,r),i=gv(s.modifiers),l=et(et({},n),i);return e.jsx(Mx.Provider,{value:l,children:t.children})}function _x(){var t=h.useContext(Mx);if(!t)throw new Error("useModifiers must be used within a ModifiersProvider");return t}function wv(t){return!!(t&&typeof t=="object"&&"before"in t&&"after"in t)}function Cv(t){return!!(t&&typeof t=="object"&&"from"in t)}function Av(t){return!!(t&&typeof t=="object"&&"after"in t)}function Sv(t){return!!(t&&typeof t=="object"&&"before"in t)}function Tv(t){return!!(t&&typeof t=="object"&&"dayOfWeek"in t)}function kv(t,s){var a,r=s.from,n=s.to;if(r&&n){var i=Ra(n,r)<0;i&&(a=[n,r],r=a[0],n=a[1]);var l=Ra(t,r)>=0&&Ra(n,t)>=0;return l}return n?Os(n,t):r?Os(r,t):!1}function Rv(t){return Zu(t)}function Dv(t){return Array.isArray(t)&&t.every(Zu)}function Pv(t,s){return s.some(function(a){if(typeof a=="boolean")return a;if(Rv(a))return Os(t,a);if(Dv(a))return a.includes(t);if(Cv(a))return kv(t,a);if(Tv(a))return a.dayOfWeek.includes(t.getDay());if(wv(a)){var r=Ra(a.before,t),n=Ra(a.after,t),i=r>0,l=n<0,o=_l(a.before,a.after);return o?l&&i:i||l}return Av(a)?Ra(t,a.after)>0:Sv(a)?Ra(a.before,t)>0:typeof a=="function"?a(t):!1})}function Eo(t,s,a){var r=Object.keys(s).reduce(function(i,l){var o=s[l];return Pv(t,o)&&i.push(l),i},[]),n={};return r.forEach(function(i){return n[i]=!0}),a&&!ho(t,a)&&(n.outside=!0),n}function Iv(t,s){for(var a=Gs(t[0]),r=xo(t[t.length-1]),n,i,l=a;l<=r;){var o=Eo(l,s),d=!o.disabled&&!o.hidden;if(!d){l=zs(l,1);continue}if(o.selected)return l;o.today&&!i&&(i=l),n||(n=l),l=zs(l,1)}return i||n}var Ev=365;function Lx(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,d=n.weekStartsOn,c=n.fromDate,m=n.toDate,u=n.locale,x={day:zs,week:Ml,month:Na,year:Pf,startOfWeek:function(f){return n.ISOWeek?po(f):go(f,{locale:u,weekStartsOn:d})},endOfWeek:function(f){return n.ISOWeek?Ku(f):Yu(f,{locale:u,weekStartsOn:d})}},p=x[a](t,r==="after"?1:-1);r==="before"&&c?p=If([c,p]):r==="after"&&m&&(p=Ef([m,p]));var g=!0;if(i){var y=Eo(p,i);g=!y.disabled&&!y.hidden}return g?p:o.count>Ev?o.lastFocused:Lx(p,{moveBy:a,direction:r,context:n,modifiers:i,retry:et(et({},o),{count:o.count+1})})}var Ox=h.createContext(void 0);function Fv(t){var s=Pn(),a=_x(),r=h.useState(),n=r[0],i=r[1],l=h.useState(),o=l[0],d=l[1],c=Iv(s.displayMonths,a),m=n??(o&&s.isDateDisplayed(o))?o:c,u=function(){d(n),i(void 0)},x=function(f){i(f)},p=Pt(),g=function(f,b){if(n){var v=Lx(n,{moveBy:f,direction:b,context:p,modifiers:a});Os(n,v)||(s.goToDate(v,n),x(v))}},y={focusedDay:n,focusTarget:m,blur:u,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(Ox.Provider,{value:y,children:t.children})}function Fo(){var t=h.useContext(Ox);if(!t)throw new Error("useFocusContext must be used within a FocusProvider");return t}function Mv(t,s){var a=_x(),r=Eo(t,a,s);return r}var Mo=h.createContext(void 0);function _v(t){if(!Oi(t.initialProps)){var s={selected:void 0};return e.jsx(Mo.Provider,{value:s,children:t.children})}return e.jsx(Lv,{initialProps:t.initialProps,children:t.children})}function Lv(t){var s=t.initialProps,a=t.children,r=function(i,l,o){var d,c,m;if((d=s.onDayClick)===null||d===void 0||d.call(s,i,l,o),l.selected&&!s.required){(c=s.onSelect)===null||c===void 0||c.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(Mo.Provider,{value:n,children:a})}function $x(){var t=h.useContext(Mo);if(!t)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return t}function Ov(t,s){var a=Pt(),r=$x(),n=Do(),i=Io(),l=Fo(),o=l.focusDayAfter,d=l.focusDayBefore,c=l.focusWeekAfter,m=l.focusWeekBefore,u=l.blur,x=l.focus,p=l.focusMonthBefore,g=l.focusMonthAfter,y=l.focusYearBefore,f=l.focusYearAfter,b=l.focusStartOfWeek,v=l.focusEndOfWeek,A=function(C){var j,U,$,_;Oi(a)?(j=r.onDayClick)===null||j===void 0||j.call(r,t,s,C):Rn(a)?(U=n.onDayClick)===null||U===void 0||U.call(n,t,s,C):Dn(a)?($=i.onDayClick)===null||$===void 0||$.call(i,t,s,C):(_=a.onDayClick)===null||_===void 0||_.call(a,t,s,C)},w=function(C){var j;x(t),(j=a.onDayFocus)===null||j===void 0||j.call(a,t,s,C)},T=function(C){var j;u(),(j=a.onDayBlur)===null||j===void 0||j.call(a,t,s,C)},k=function(C){var j;(j=a.onDayMouseEnter)===null||j===void 0||j.call(a,t,s,C)},L=function(C){var j;(j=a.onDayMouseLeave)===null||j===void 0||j.call(a,t,s,C)},D=function(C){var j;(j=a.onDayPointerEnter)===null||j===void 0||j.call(a,t,s,C)},S=function(C){var j;(j=a.onDayPointerLeave)===null||j===void 0||j.call(a,t,s,C)},N=function(C){var j;(j=a.onDayTouchCancel)===null||j===void 0||j.call(a,t,s,C)},P=function(C){var j;(j=a.onDayTouchEnd)===null||j===void 0||j.call(a,t,s,C)},R=function(C){var j;(j=a.onDayTouchMove)===null||j===void 0||j.call(a,t,s,C)},O=function(C){var j;(j=a.onDayTouchStart)===null||j===void 0||j.call(a,t,s,C)},E=function(C){var j;(j=a.onDayKeyUp)===null||j===void 0||j.call(a,t,s,C)},M=function(C){var j;switch(C.key){case"ArrowLeft":C.preventDefault(),C.stopPropagation(),a.dir==="rtl"?o():d();break;case"ArrowRight":C.preventDefault(),C.stopPropagation(),a.dir==="rtl"?d():o();break;case"ArrowDown":C.preventDefault(),C.stopPropagation(),c();break;case"ArrowUp":C.preventDefault(),C.stopPropagation(),m();break;case"PageUp":C.preventDefault(),C.stopPropagation(),C.shiftKey?y():p();break;case"PageDown":C.preventDefault(),C.stopPropagation(),C.shiftKey?f():g();break;case"Home":C.preventDefault(),C.stopPropagation(),b();break;case"End":C.preventDefault(),C.stopPropagation(),v();break}(j=a.onDayKeyDown)===null||j===void 0||j.call(a,t,s,C)},B={onClick:A,onFocus:w,onBlur:T,onKeyDown:M,onKeyUp:E,onMouseEnter:k,onMouseLeave:L,onPointerEnter:D,onPointerLeave:S,onTouchCancel:N,onTouchEnd:P,onTouchMove:R,onTouchStart:O};return B}function $v(){var t=Pt(),s=$x(),a=Do(),r=Io(),n=Oi(t)?s.selected:Rn(t)?a.selected:Dn(t)?r.selected:void 0;return n}function Uv(t){return Object.values(xa).includes(t)}function Bv(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(Uv(r)){var i=t.classNames["day_".concat(r)];i&&a.push(i)}}),a}function Vv(t,s){var a=et({},t.styles.day);return Object.keys(s).forEach(function(r){var n;a=et(et({},a),(n=t.modifiersStyles)===null||n===void 0?void 0:n[r])}),a}function zv(t,s,a){var r,n,i,l=Pt(),o=Fo(),d=Mv(t,s),c=Ov(t,d),m=$v(),u=!!(l.onDayClick||l.mode!=="default");h.useEffect(function(){var k;d.outside||o.focusedDay&&u&&Os(o.focusedDay,t)&&((k=a.current)===null||k===void 0||k.focus())},[o.focusedDay,t,a,u,d.outside]);var x=Bv(l,d).join(" "),p=Vv(l,d),g=!!(d.outside&&!l.showOutsideDays||d.hidden),y=(i=(n=l.components)===null||n===void 0?void 0:n.DayContent)!==null&&i!==void 0?i:dv,f=e.jsx(y,{date:t,displayMonth:s,activeModifiers:d}),b={style:p,className:x,children:f,role:"gridcell"},v=o.focusTarget&&Os(o.focusTarget,t)&&!d.outside,A=o.focusedDay&&Os(o.focusedDay,t),w=et(et(et({},b),(r={disabled:d.disabled,role:"gridcell"},r["aria-selected"]=d.selected,r.tabIndex=A||v?0:-1,r)),c),T={isButton:u,isHidden:g,activeModifiers:d,selectedDays:m,buttonProps:w,divProps:b};return T}function Hv(t){var s=h.useRef(null),a=zv(t.date,t.displayMonth,s);return a.isHidden?e.jsx("div",{role:"gridcell"}):a.isButton?e.jsx(ui,et({name:"day",ref:s},a.buttonProps)):e.jsx("div",et({},a.divProps))}function Wv(t){var s=t.number,a=t.dates,r=Pt(),n=r.onWeekNumberClick,i=r.styles,l=r.classNames,o=r.locale,d=r.labels.labelWeekNumber,c=r.formatters.formatWeekNumber,m=c(Number(s),{locale:o});if(!n)return e.jsx("span",{className:l.weeknumber,style:i.weeknumber,children:m});var u=d(Number(s),{locale:o}),x=function(p){n(s,a,p)};return e.jsx(ui,{name:"week-number","aria-label":u,className:l.weeknumber,style:i.weeknumber,onClick:x,children:m})}function Gv(t){var s,a,r=Pt(),n=r.styles,i=r.classNames,l=r.showWeekNumber,o=r.components,d=(s=o==null?void 0:o.Day)!==null&&s!==void 0?s:Hv,c=(a=o==null?void 0:o.WeekNumber)!==null&&a!==void 0?a:Wv,m;return l&&(m=e.jsx("td",{className:i.cell,style:n.cell,children:e.jsx(c,{number:t.weekNumber,dates:t.dates})})),e.jsxs("tr",{className:i.row,style:n.row,children:[m,t.dates.map(function(u){return e.jsx("td",{className:i.cell,style:n.cell,role:"presentation",children:e.jsx(d,{displayMonth:t.displayMonth,date:u})},Df(u))})]})}function em(t,s,a){for(var r=a!=null&&a.ISOWeek?Ku(s):Yu(s,a),n=a!=null&&a.ISOWeek?po(t):go(t,a),i=Ra(r,n),l=[],o=0;o<=i;o++)l.push(zs(n,o));var d=l.reduce(function(c,m){var u=a!=null&&a.ISOWeek?_f(m):Lf(m,a),x=c.find(function(p){return p.weekNumber===u});return x?(x.dates.push(m),c):(c.push({weekNumber:u,dates:[m]}),c)},[]);return d}function Kv(t,s){var a=em(Gs(t),xo(t),s);if(s!=null&&s.useFixedWeeks){var r=Rf(t,s);if(r<6){var n=a[a.length-1],i=n.dates[n.dates.length-1],l=Ml(i,6-r),o=em(Ml(i,1),l,s);a.push.apply(a,o)}}return a}function Yv(t){var s,a,r,n=Pt(),i=n.locale,l=n.classNames,o=n.styles,d=n.hideHead,c=n.fixedWeeks,m=n.components,u=n.weekStartsOn,x=n.firstWeekContainsDate,p=n.ISOWeek,g=Kv(t.displayMonth,{useFixedWeeks:!!c,ISOWeek:p,locale:i,weekStartsOn:u,firstWeekContainsDate:x}),y=(s=m==null?void 0:m.Head)!==null&&s!==void 0?s:cv,f=(a=m==null?void 0:m.Row)!==null&&a!==void 0?a:Gv,b=(r=m==null?void 0:m.Footer)!==null&&r!==void 0?r:iv;return e.jsxs("table",{id:t.id,className:l.table,style:o.table,role:"grid","aria-labelledby":t["aria-labelledby"],children:[!d&&e.jsx(y,{}),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(b,{displayMonth:t.displayMonth})]})}function Zv(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var Xv=Zv()?h.useLayoutEffect:h.useEffect,ll=!1,Qv=0;function tm(){return"react-day-picker-".concat(++Qv)}function Jv(t){var s,a=t??(ll?tm():null),r=h.useState(a),n=r[0],i=r[1];return Xv(function(){n===null&&i(tm())},[]),h.useEffect(function(){ll===!1&&(ll=!0)},[]),(s=t??n)!==null&&s!==void 0?s:void 0}function qv(t){var s,a,r=Pt(),n=r.dir,i=r.classNames,l=r.styles,o=r.components,d=Pn().displayMonths,c=Jv(r.id?"".concat(r.id,"-").concat(t.displayIndex):void 0),m=r.id?"".concat(r.id,"-grid-").concat(t.displayIndex):void 0,u=[i.month],x=l.month,p=t.displayIndex===0,g=t.displayIndex===d.length-1,y=!p&&!g;n==="rtl"&&(s=[p,g],g=s[0],p=s[1]),p&&(u.push(i.caption_start),x=et(et({},x),l.caption_start)),g&&(u.push(i.caption_end),x=et(et({},x),l.caption_end)),y&&(u.push(i.caption_between),x=et(et({},x),l.caption_between));var f=(a=o==null?void 0:o.Caption)!==null&&a!==void 0?a:nv;return e.jsxs("div",{className:u.join(" "),style:x,children:[e.jsx(f,{id:c,displayMonth:t.displayMonth,displayIndex:t.displayIndex}),e.jsx(Yv,{id:m,"aria-labelledby":c,displayMonth:t.displayMonth})]},t.displayIndex)}function ej(t){var s=Pt(),a=s.classNames,r=s.styles;return e.jsx("div",{className:a.months,style:r.months,children:t.children})}function tj(t){var s,a,r=t.initialProps,n=Pt(),i=Fo(),l=Pn(),o=h.useState(!1),d=o[0],c=o[1];h.useEffect(function(){n.initialFocus&&i.focusTarget&&(d||(i.focus(i.focusTarget),c(!0)))},[n.initialFocus,d,i.focus,i.focusTarget,i]);var m=[n.classNames.root,n.className];n.numberOfMonths>1&&m.push(n.classNames.multiple_months),n.showWeekNumber&&m.push(n.classNames.with_weeknumber);var u=et(et({},n.styles.root),n.style),x=Object.keys(r).filter(function(g){return g.startsWith("data-")}).reduce(function(g,y){var f;return et(et({},g),(f={},f[y]=r[y],f))},{}),p=(a=(s=r.components)===null||s===void 0?void 0:s.Months)!==null&&a!==void 0?a:ej;return e.jsx("div",et({className:m.join(" "),style:u,dir:n.dir,id:n.id,nonce:r.nonce,title:r.title,lang:r.lang},x,{children:e.jsx(p,{children:l.displayMonths.map(function(g,y){return e.jsx(qv,{displayIndex:y,displayMonth:g},y)})})}))}function sj(t){var s=t.children,a=Sb(t,["children"]);return e.jsx(Wb,{initialProps:a,children:e.jsx(tv,{children:e.jsx(_v,{initialProps:a,children:e.jsx(mv,{initialProps:a,children:e.jsx(hv,{initialProps:a,children:e.jsx(Nv,{children:e.jsx(Fv,{children:s})})})})})})})}function aj(t){return e.jsx(sj,et({},t,{children:e.jsx(tj,{initialProps:t})}))}function Xn({className:t,classNames:s,showOutsideDays:a=!0,...r}){return e.jsx(aj,{showOutsideDays:a,className:Re("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:Re(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:Re("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:Re(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(Ju,{className:Re("size-4",n),...i}),IconRight:({className:n,...i})=>e.jsx(bo,{className:Re("size-4",n),...i})},...r})}function $s({value:t,onChange:s,minDate:a,maxDate:r,placeholderText:n="dd/mm/yyyy",disabled:i=!1,className:l,wrapperClassName:o,error:d=!1,displayFormat:c="dd/MM/yyyy",id:m}){const[u,x]=h.useState(!1),p=h.useMemo(()=>{if(t){if(t instanceof Date)return wr(t)?t:void 0;if(typeof t=="string")try{const b=Zi(t,"yyyy-MM-dd",new Date);return wr(b)?b:void 0}catch{return}}},[t]),g=h.useMemo(()=>{if(a){if(a instanceof Date)return wr(a)?a:void 0;if(typeof a=="string"){const b=Zi(a,"yyyy-MM-dd",new Date);return wr(b)?b:void 0}}},[a]),y=h.useMemo(()=>{if(r){if(r instanceof Date)return wr(r)?r:void 0;if(typeof r=="string"){const b=Zi(r,"yyyy-MM-dd",new Date);return wr(b)?b:void 0}}},[r]),f=b=>{if(x(!1),!!s){if(!b){s(null);return}s(Ye(b,"yyyy-MM-dd"))}};return e.jsx("div",{className:Re("relative",o),children:e.jsxs(Ys,{open:u,onOpenChange:x,children:[e.jsx(Zs,{asChild:!0,children:e.jsxs(F,{id:m,disabled:i,variant:"outline",className:Re("w-full justify-start text-left font-normal",!p&&"text-muted-foreground",d&&"border-destructive ring-destructive/20",l),children:[e.jsx(it,{className:"mr-2 h-4 w-4"}),p?Ye(p,c):e.jsx("span",{children:n})]})}),e.jsx(Xs,{className:"w-auto p-0",align:"start",children:e.jsx(Xn,{mode:"single",selected:p,onSelect:f,disabled:b=>!!(g&&b<g||y&&b>y),initialFocus:!0})})]})})}function rj({isAdmin:t,dateRange:s,customStartDate:a,customEndDate:r,showCustomDatePicker:n,refreshing:i,onDateRangeChange:l,onCustomStartDateChange:o,onCustomEndDateChange:d,onShowCustomDatePickerChange:c,onApplyCustomDate:m,onResetCustomDates:u,onRefresh:x}){return e.jsx(te,{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(Ya,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Filters"}),t&&e.jsx(ne,{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(it,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ve,{value:s,onValueChange:l,"data-testid":"date-range-select",children:[e.jsx(He,{className:"w-[140px]",children:e.jsx(ze,{placeholder:"Select period"})}),e.jsxs(We,{children:[e.jsx(K,{value:"all",children:"All Time"}),e.jsx(K,{value:"today",children:"Today"}),e.jsx(K,{value:"week",children:"This Week"}),e.jsx(K,{value:"month",children:"This Month"}),e.jsx(K,{value:"last7days",children:"Last 7 Days"}),e.jsx(K,{value:"last30days",children:"Last 30 Days"}),e.jsx(K,{value:"custom",children:"Custom Range"})]})]}),s==="custom"&&e.jsxs(Ys,{open:n,onOpenChange:c,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(it,{className:"w-4 h-4"}),a&&r?`${Ye(a,"MMM d, yyyy")} - ${Ye(r,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Xs,{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(le,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx($s,{value:a||null,onChange:p=>{const g=p?new Date(p):void 0;g?(o(g),r&&g>r&&d(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(le,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx($s,{value:r||null,onChange:p=>{const g=p?new Date(p):void 0;g?(d(g),a&&g<a&&o(g)):d(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:u,"data-testid":"cancel-custom-date",children:"Cancel"})]})]})})]})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(it,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ve,{value:s,onValueChange:p=>l(p),"data-testid":"date-range-select-user",children:[e.jsx(He,{className:"w-[140px]",children:e.jsx(ze,{placeholder:"Select period"})}),e.jsxs(We,{children:[e.jsx(K,{value:"all",children:"All Time"}),e.jsx(K,{value:"today",children:"Today"}),e.jsx(K,{value:"week",children:"This Week"}),e.jsx(K,{value:"month",children:"This Month"}),e.jsx(K,{value:"last7days",children:"Last 7 Days"}),e.jsx(K,{value:"last30days",children:"Last 30 Days"}),e.jsx(K,{value:"custom",children:"Custom Range"})]})]}),s==="custom"&&e.jsxs(Ys,{open:n,onOpenChange:c,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(it,{className:"w-4 h-4"}),a&&r?`${Ye(a,"MMM d, yyyy")} - ${Ye(r,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Xs,{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(le,{htmlFor:"start-date-user",className:"text-sm font-medium",children:"Start Date"}),e.jsx($s,{value:a||null,onChange:p=>{const g=p?new Date(p):void 0;g?(o(g),r&&g>r&&d(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(le,{htmlFor:"end-date-user",className:"text-sm font-medium",children:"End Date"}),e.jsx($s,{value:r||null,onChange:p=>{const g=p?new Date(p):void 0;g?(d(g),a&&g<a&&o(g)):d(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:u,"data-testid":"cancel-custom-date-user",children:"Cancel"})]})]})})]})]}),e.jsx(Gt,{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(Bt,{className:`w-4 h-4 ${i?"animate-spin":""}`}),e.jsx("span",{className:"inline-block w-[60px] text-center",children:i?"Refreshing...":"Refresh"})]})]})]})})})}function hr({title:t,value:s,icon:a,iconBgColor:r,iconColor:n,subtitle:i,children:l,testId:o="kpi-card",onClick:d,onJustifyClick:c,showJustifyButton:m=!1}){const u=x=>{x.stopPropagation(),c==null||c()};return e.jsxs(te,{className:"hover:shadow-lg transition-all duration-200 shadow-md cursor-pointer h-full flex flex-col",onClick:d,"data-testid":o,children:[e.jsxs(ue,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(xe,{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&&c&&e.jsx("button",{type:"button",onClick:u,className:"p-1.5 rounded-md text-gray-500 hover:text-gray-700 hover:bg-gray-100 transition-colors","data-testid":`${o}-justify-button`,title:"View detailed breakdown of numbers","aria-label":"View detailed breakdown",children:e.jsx(Sn,{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 ps({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 la({className:t,value:s,indicatorClassName:a,...r}){return e.jsx(ef,{"data-slot":"progress",className:Re("bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",t),...r,children:e.jsx(tf,{"data-slot":"progress-indicator",className:Re("bg-primary h-full w-full flex-1 transition-all",a),style:{transform:`translateX(-${100-(s||0)}%)`}})})}function nj({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(hr,{title:"Total Requests",value:(t==null?void 0:t.requestVolume.totalRequests)||0,icon:Pe,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(ps,{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(ps,{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(ps,{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(ps,{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(ps,{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(hr,{title:"SLA Compliance",value:`${(t==null?void 0:t.tatEfficiency.avgTATCompliance)||0}%`,icon:Vt,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(la,{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(ps,{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(ps,{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(hr,{title:"Avg Cycle Time",value:t!=null&&t.tatEfficiency.avgCycleTimeHours?Lt(t.tatEfficiency.avgCycleTimeHours):"0 hours",icon:Xe,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(ps,{label:"Express",value:(()=>{const o=s.find(c=>c.priority==="express"),d=o?Number(o.avgCycleTimeHours):0;return d>0?Lt(d):"N/A"})(),bgColor:"bg-orange-50",textColor:"text-orange-600",testId:"stat-express-time",onClick:o=>{o.stopPropagation(),i({...l(),priority:"express"})}}),e.jsx(ps,{label:"Standard",value:(()=>{const o=s.find(c=>c.priority==="standard"),d=o?Number(o.avgCycleTimeHours):0;return d>0?Lt(d):"N/A"})(),bgColor:"bg-blue-50",textColor:"text-blue-600",testId:"stat-standard-time",onClick:o=>{o.stopPropagation(),i({...l(),priority:"standard"})}})]})})})]})}function ij({kpis:t,criticalRequests:s,dateRange:a,customStartDate:r,customEndDate:n,onKPIClick:i,onNavigate:l,userId:o,userDisplayName:d}){const c=()=>({dateRange:a,startDate:r,endDate:n}),m=()=>{if(!o)return;const x=new URLSearchParams;x.set("approverId",o),x.set("approverName",d||"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()}`)},u=t&&t.requestVolume.totalRequests>0?t.requestVolume.approvedRequests/t.requestVolume.totalRequests*100:0;return e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4 items-stretch","data-testid":"user-kpi-cards",children:[e.jsx(hr,{title:"My Requests (Submitted)",value:(t==null?void 0:t.requestVolume.totalRequests)||0,icon:Pe,iconBgColor:"bg-blue-50",iconColor:"text-blue-600",testId:"kpi-my-requests",onClick:()=>i(c()),children:e.jsxs("div",{className:"grid grid-cols-3 gap-1.5 sm:gap-2",children:[e.jsx(ps,{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({...c(),status:"approved"})}}),e.jsx(ps,{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({...c(),status:"pending"})}}),e.jsx(ps,{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({...c(),status:"paused"})}}),e.jsx(ps,{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({...c(),status:"rejected"})}}),e.jsx(ps,{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({...c(),status:"closed"})}})]})}),e.jsx(hr,{title:"Awaiting My Approval",value:(t==null?void 0:t.approverLoad.pendingActions)||0,icon:Xe,iconBgColor:"bg-orange-50",iconColor:"text-orange-600",subtitle:"at current level",testId:"kpi-pending-actions",onClick:()=>i({...c(),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(ps,{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({...c(),targetPage:"open-requests",status:"pending"})}}),e.jsx(ps,{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({...c(),targetPage:"open-requests",status:"pending"})}})]})}),e.jsx(hr,{title:"Critical Alerts",value:s.length,icon:pa,iconBgColor:"bg-red-50",iconColor:"text-red-600",testId:"kpi-user-critical",onClick:()=>i({...c(),targetPage:"open-requests"}),onJustifyClick:m,showJustifyButton:!!o,children:e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-auto",children:[e.jsx(ps,{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({...c(),targetPage:"open-requests"})}}),e.jsx(ps,{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({...c(),targetPage:"open-requests"})}})]})}),e.jsx(hr,{title:"Success Rate",value:`${u.toFixed(0)}%`,icon:De,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(la,{value:u,className:"h-4 bg-gray-200 [&>div]:bg-green-600","data-testid":"success-rate-progress"}),e.jsxs("div",{className:"flex justify-between items-center text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Rejected"}),e.jsx("span",{className:"font-semibold text-red-600",children:(t==null?void 0:t.requestVolume.rejectedRequests)||0})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-auto",children:[e.jsxs("div",{className:"bg-green-50 rounded-lg p-2 text-center",children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Approved"}),e.jsx("div",{className:"text-lg font-semibold text-green-600",children:(t==null?void 0:t.requestVolume.approvedRequests)||0})]}),e.jsxs("div",{className:"bg-red-50 rounded-lg p-2 text-center",children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Rejected"}),e.jsx("div",{className:"text-lg font-semibold text-red-600",children:(t==null?void 0:t.requestVolume.rejectedRequests)||0})]})]})]})})]})}const lj=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)))},oj=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 cj({alert:t,onNavigate:s,testId:a="critical-alert-card"}){const r=lj(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(Wf,{className:"h-3 w-3 text-red-500 flex-shrink-0","data-testid":`${a}-priority-icon`}),t.breachCount>0&&e.jsx(ne,{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(ne,{variant:"outline",className:"text-xs bg-white border-red-200 text-red-700 font-medium whitespace-nowrap","data-testid":`${a}-remaining-time`,children:oj(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(la,{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 dj(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 mj(t){return t.filter(s=>{const a=Number(s.tatPercentageUsed)||0;return(Number(s.remainingHours)||0)>0&&a<100})}function uj(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 xj(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 Ux(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 hj({isAdmin:t,breachedRequests:s,pagination:a,onPageChange:r,onNavigate:n}){return e.jsxs(te,{className:"lg:col-span-2 shadow-md hover:shadow-lg transition-shadow flex flex-col overflow-hidden",style:{height:"100%"},"data-testid":"critical-alerts-section",children:[e.jsx(ue,{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(pa,{className:"h-4 w-4 sm:h-5 sm:w-5 text-red-600"})}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-base sm:text-lg text-gray-900",children:"Critical Alerts"}),e.jsx(ke,{className:"text-xs sm:text-sm text-gray-600",children:t?"Organization-wide":"My requests"})]})]}),e.jsx(ne,{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",style:{maxHeight:a.totalPages>1?"calc(100% - 140px)":"calc(100% - 80px)"},children:e.jsx("div",{className:"space-y-3 sm:space-y-4",children:s.length===0?e.jsxs("div",{className:"text-center py-6 sm:py-8 text-muted-foreground","data-testid":"no-critical-alerts",children:[e.jsx(De,{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(cj,{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(ds,{className:"h-3 w-3 rotate-180"})}),Ux(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(ds,{className:"h-3 w-3"})})]})]})})]})}const pj=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"}},gj=t=>{const s=new Date,a=new Date(t),r=Of(s,a);if(r<1)return"just now";if(r<60)return`${r} minute${r>1?"s":""} ago`;const n=$f(s,a);if(n<24)return`${n} hour${n>1?"s":""} ago`;const i=Uf(s,a);return`${i} day${i>1?"s":""} ago`},fj=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()},yj=t=>{const s=t.toLowerCase();return s.includes("approv")?e.jsx(De,{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(pa,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-orange-600"}):s.includes("submit")?e.jsx(Pe,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-purple-600"}):s.includes("document")?e.jsx(Ni,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-indigo-600"}):e.jsx(Dt,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-gray-600"})};function bj({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",d=l?(a||r||"ME").split(" ").map(c=>c[0]).join("").toUpperCase().substring(0,2):t.userName?t.userName.split(" ").map(c=>c[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(rs,{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(Li,{src:""}),e.jsx(ns,{className:`text-white font-semibold text-xs sm:text-sm ${l?"bg-blue-600":"bg-slate-700"}`,children:d})]}),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:yj(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(ne,{variant:"outline",className:`text-xs ${pj(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:fj(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:gj(t.timestamp)})]})]}),e.jsx(ds,{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 vj({isAdmin:t,recentActivity:s,pagination:a,refreshing:r,onPageChange:n,onRefresh:i,onNavigate:l,currentUserId:o,currentUserDisplayName:d,currentUserEmail:c}){return e.jsxs(te,{className:"lg:col-span-1 shadow-md hover:shadow-lg transition-shadow flex flex-col overflow-hidden",style:{height:"100%"},"data-testid":"recent-activity-section",children:[e.jsx(ue,{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(Dt,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx(xe,{className:"text-base sm:text-lg text-gray-900",children:"Recent Activity"}),e.jsx(ke,{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(Bt,{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",style:{maxHeight:a.totalPages>1?"calc(100% - 140px)":"calc(100% - 80px)"},children:e.jsx("div",{className:"space-y-2 sm:space-y-3",children:s.length===0?e.jsxs("div",{className:"text-center py-6 sm:py-8 text-muted-foreground","data-testid":"no-recent-activity",children:[e.jsx(Dt,{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(bj,{activity:m,currentUserId:o,currentUserDisplayName:d,currentUserEmail:c,onNavigate:u=>l==null?void 0:l(`request/${u}`),testId:"dashboard-activity"},m.activityId))})}),a.totalPages>1&&s.length>0&&e.jsx("div",{className:"border-t bg-gray-50 px-4 py-2 flex-shrink-0",children:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["Page ",a.page," of ",a.totalPages," (",a.totalRecords," total)"]}),e.jsxs("div",{className:"flex items-center justify-center gap-1 flex-wrap",children:[e.jsx(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(ds,{className:"h-3 w-3 rotate-180"})}),Ux(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(ds,{className:"h-3 w-3"})})]})]})})]})}function jj({kpis:t,upcomingDeadlines:s,criticalRequests:a,departmentStats:r,dateRange:n,customStartDate:i,customEndDate:l,exportingDeptStats:o,onKPIClick:d,onExportDepartmentStats:c}){if(!t)return null;const m=()=>({dateRange:n,startDate:i,endDate:l});return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4 sm:gap-6","data-testid":"admin-analytics-section",children:[e.jsxs("div",{className:"flex flex-col gap-4 sm:gap-6 lg:col-span-1",children:[e.jsxs(te,{className:"shadow-md hover:shadow-lg transition-shadow flex-1","data-testid":"active-levels-card",children:[e.jsx(ue,{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(Dt,{className:"h-4 w-4 text-blue-600"})}),e.jsx(xe,{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(Gt,{}),e.jsxs("div",{className:"space-y-1 text-xs",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-muted-foreground",children:"Avg Time/Level"}),e.jsxs("span",{className:"font-semibold",children:[s.length>0?(t.tatEfficiency.avgCycleTimeHours/s.length).toFixed(1):"0","h"]})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-muted-foreground",children:"At Risk"}),e.jsx("span",{className:"font-semibold text-red-600",children:a.filter(u=>u.breachCount>0).length})]})]})]})})]}),e.jsxs(te,{className:"shadow-md hover:shadow-lg transition-shadow flex-1","data-testid":"collaboration-card",children:[e.jsx(ue,{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(xe,{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(Gt,{}),e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:[t.requestVolume.totalRequests>0?(t.engagement.workNotesAdded/t.requestVolume.totalRequests).toFixed(1):"0"," ","avg notes per request"]})]})})]})]}),r.length>0&&e.jsxs(te,{className:"shadow-md hover:shadow-lg transition-shadow lg:col-span-2","data-testid":"department-stats-card",children:[e.jsx(ue,{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(Ll,{className:"h-5 w-5 sm:h-6 sm:w-6 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-base sm:text-lg lg:text-xl",children:"Department-wise Workflow Summary"}),e.jsx(ke,{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:()=>c(n,i,l),disabled:o,"data-testid":"export-dept-stats-button",children:[e.jsx(Nt,{className:`w-3 h-3 sm:w-4 sm:h-4 ${o?"animate-pulse":""}`}),e.jsx("span",{className:"text-xs sm:text-sm",children:o?"Exporting...":"Export"})]})]})}),e.jsx(ae,{children:e.jsx(Ir,{width:"100%",height:400,children:e.jsxs(Fl,{data:r,children:[e.jsx(ai,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(ri,{dataKey:"department",stroke:"#999",tick:u=>{const{x,y:p,payload:g}=u;return e.jsx("g",{transform:`translate(${x},${p})`,children:e.jsx("text",{x:0,y:0,dy:16,textAnchor:"middle",fill:"#999",fontSize:11,className:"cursor-pointer hover:text-blue-600 hover:underline",onClick:()=>{d({...m(),department:g.value})},children:g.value})})}}),e.jsx(ni,{stroke:"#999",tick:{fontSize:11}}),e.jsx(Er,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(ii,{verticalAlign:"bottom",height:36,iconType:"square",wrapperStyle:{fontSize:"12px",paddingTop:"10px"}}),e.jsx(ba,{dataKey:"approved",fill:"#10b981",name:"Approved"}),e.jsx(ba,{dataKey:"inProgress",fill:"#f59e0b",name:"Pending"}),e.jsx(ba,{dataKey:"rejected",fill:"#ef4444",name:"Rejected"})]})})})]})]})}function Nj({kpis:t}){return t?e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-6","data-testid":"user-metrics-section",children:[e.jsxs(te,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"user-activity-card",children:[e.jsx(ue,{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(xe,{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(te,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"user-response-time-card",children:[e.jsx(ue,{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(Xe,{className:"h-4 w-4 text-purple-600"})}),e.jsx(xe,{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:Lt(t.tatEfficiency.avgCycleTimeHours)})}),e.jsx(Gt,{}),e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["≈ ",t.tatEfficiency.avgCycleTimeDays.toFixed(1)," working days"]})]})})]})]}):null}function wj({priorityDistribution:t,onNavigate:s}){return t.length===0?null:e.jsxs(te,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"priority-distribution-report",children:[e.jsx(ue,{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(Vt,{className:"h-5 w-5 sm:h-6 sm:w-6 text-green-600"})}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-base sm:text-lg lg:text-xl",children:"Priority Distribution Report"}),e.jsx(ke,{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: ",Lt(n)," cycle"]})]},r)})}),e.jsx("div",{className:"flex justify-center",children:e.jsx(Ir,{width:"100%",height:300,children:e.jsxs(Vu,{children:[e.jsx(zu,{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 d=Math.PI/180,c=i+35,m=a+c*Math.cos(-n*d),u=r+c*Math.sin(-n*d);return e.jsx("text",{x:m,y:u,fill:"#1f2937",textAnchor:m>a?"start":"end",dominantBaseline:"central",style:{fontSize:"14px",fontWeight:"600",pointerEvents:"none"},children:`${l}: ${o}%`})},outerRadius:90,fill:"#8884d8",dataKey:"value",onClick:a=>{a&&a.priority&&s&&s(`requests?priority=${a.priority}`)},style:{cursor:"pointer"},children:t.map((a,r)=>e.jsx(Hu,{fill:a.priority==="express"?"#ef4444":"#3b82f6",style:{cursor:"pointer"}},`cell-${r}`))}),e.jsx(Er,{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 d=()=>{const u=[];let p=Math.max(1,t-Math.floor(2.5)),g=Math.min(s,p+5-1);g-p<4&&(p=Math.max(1,g-5+1));for(let y=p;y<=g;y++)u.push(y);return u},c=r>0?(t-1)*a+1:0,m=Math.min(t*a,r);return s<=1?e.jsx(te,{className:"shadow-md border-gray-200","data-testid":`${o}-container`,children:e.jsx(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)}`:c===m?`Showing ${c} of ${r} ${l}`:`Showing ${c} to ${m} of ${r} ${l}`})})})}):e.jsx(te,{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 ",c," 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(ds,{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:"..."})]}),d().map(u=>e.jsx(F,{variant:u===t?"default":"outline",size:"sm",onClick:()=>n(u),className:`h-8 w-8 p-0 ${u===t?"bg-re-green text-white hover:bg-re-green/90":""}`,"data-testid":`${o}-page-${u}`,"aria-current":u===t?"page":void 0,children:u},u)),t<s-2&&s>5&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground","data-testid":`${o}-ellipsis-end`,children:"..."}),e.jsx(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(ds,{className:"h-4 w-4"})})]})]})})})}function Cj(t,s,a,r="for"){return t==="custom"&&s&&a?`${r} ${Ye(s,"MMM d, yyyy")} - ${Ye(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 Aj(t,s,a){return t==="all"?"All historical data":t==="custom"&&s&&a?`Data from ${Ye(s,"MMM d, yyyy")} to ${Ye(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 Sj({breachedRequests:t,pagination:s,dateRange:a,customStartDate:r,customEndDate:n,onPageChange:i,onKPIClick:l,onNavigate:o}){if(t.length===0)return null;const d=()=>({dateRange:a,startDate:r,endDate:n});return e.jsxs(te,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"tat-breach-report",children:[e.jsx(ue,{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(xe,{className:"text-base sm:text-lg lg:text-xl",children:"TAT Breach Report"}),e.jsxs(ke,{className:"text-xs sm:text-sm",children:["Requests that breached TAT - ",Aj(a,r,n)]})]})]}),e.jsxs(ne,{variant:"destructive",className:"text-sm font-medium self-start sm:self-auto",children:[t.length," ",t.length===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((c,m)=>{const u=c.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/${c.requestNumber}`),"data-testid":`breach-request-${c.requestNumber}`,children:c.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:c.title})}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-700 cursor-pointer hover:text-blue-600 hover:underline",onClick:()=>{c.department&&c.department!=="Unknown"&&l({...d(),department:c.department})},children:c.department||"Unknown"}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-700",children:c.approverId?e.jsx("span",{className:"cursor-pointer hover:text-blue-600 hover:underline",onClick:()=>{if(o){const x=new URLSearchParams;x.set("approver",c.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:c.approver||"N/A"}):c.approver||"N/A"}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-700",children:c.currentLevel&&c.totalLevels?e.jsxs("span",{className:"font-medium",children:[c.currentLevel,"/",c.totalLevels]}):c.currentLevel?e.jsxs("span",{className:"font-medium",children:[c.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:uj(u)})}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-700 w-[300px]",children:e.jsx("div",{className:"max-h-32 overflow-y-auto",children:e.jsx("p",{className:"whitespace-pre-line break-words leading-relaxed",children:c.breachReason||"TAT Exceeded"})})}),e.jsx("td",{className:"py-3 px-4",children:e.jsx(ne,{variant:"outline",className:`text-xs font-medium ${c.priority==="express"?"bg-orange-100 text-orange-800 border-orange-200":"bg-blue-100 text-blue-800 border-blue-200"}`,children:c.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 Tj({isAdmin:t,upcomingDeadlines:s,pagination:a,onPageChange:r,onNavigate:n}){return s.length===0?null:e.jsxs(te,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"upcoming-deadlines-section",children:[e.jsx(ue,{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(it,{className:"h-4 w-4 sm:h-5 sm:w-5 text-orange-600"}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-base sm:text-lg",children:"Upcoming Deadlines"}),e.jsx(ke,{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,d=Number(i.elapsedHours)||0,c=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(ne,{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(ne,{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(la,{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:[Lt(d)," elapsed"]}),e.jsxs("span",{children:[Lt(c)," 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 kj({aiRemarkUtilization:t}){return t?e.jsxs(te,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"ai-remark-utilization-report",children:[e.jsx(ue,{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(wi,{className:"h-5 w-5 sm:h-6 sm:w-6 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-base sm:text-lg lg:text-xl",children:"AI Remark Utilization Report"}),e.jsx(ke,{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(Ir,{width:"100%",height:250,children:e.jsxs(Sf,{data:t.monthlyTrends,children:[e.jsx(ai,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(ri,{dataKey:"month",stroke:"#999",tick:{fontSize:11}}),e.jsx(ni,{stroke:"#999",tick:{fontSize:11}}),e.jsx(Er,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(ii,{verticalAlign:"bottom",height:36,iconType:"circle",wrapperStyle:{fontSize:"12px",paddingTop:"10px"}}),e.jsx(Ed,{type:"monotone",dataKey:"aiUsage",stroke:"#8b5cf6",strokeWidth:2,name:"AI Usage",dot:{fill:"#8b5cf6",r:4}}),e.jsx(Ed,{type:"monotone",dataKey:"manualEdits",stroke:"#ec4899",strokeWidth:2,name:"Manual Edits",dot:{fill:"#ec4899",r:4}})]})})]})]}):null}function Rj({approverPerformance:t,pagination:s,dateRange:a,customStartDate:r,customEndDate:n,loading:i,exportingApproverPerformance:l,onPageChange:o,onExport:d,onNavigate:c}){return t.length===0?null:e.jsxs(te,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"approver-performance-report",children:[e.jsx(ue,{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($t,{className:"h-5 w-5 sm:h-6 sm:w-6 text-yellow-600"})}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-base sm:text-lg lg:text-xl",children:"Approver Performance Report"}),e.jsx(ke,{className:"text-xs sm:text-sm",children:"Response time & TAT compliance tracking"})]})]}),e.jsx(F,{onClick:()=>d(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(Bt,{className:"w-4 h-4 mr-2 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Nt,{className:"w-4 h-4 mr-2"}),"Export"]})})]})}),e.jsxs(ae,{children:[e.jsx("div",{className:"space-y-3",children:t.map((m,u)=>{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 p=new URLSearchParams;p.set("approverId",m.approverId),p.set("approverName",m.approverName),p.set("dateRange",a),a==="custom"&&r&&n&&(p.set("startDate",r.toISOString()),p.set("endDate",n.toISOString())),c==null||c(`/approver-performance?${p.toString()}`)},"data-testid":`approver-item-${m.approverId}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 bg-orange-500 rounded-full flex items-center justify-center text-white font-semibold text-sm flex-shrink-0",children:u+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium text-gray-900 truncate",children:m.approverName}),e.jsxs("div",{className:"text-xs text-gray-500",children:[m.totalApproved," requests approved"]})]})]}),e.jsxs("span",{className:`px-2 py-1 rounded text-xs font-medium ${xj(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:Lt(m.avgResponseHours)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"Pending"}),e.jsx("div",{className:"text-sm font-medium text-gray-900",children:e.jsx("span",{className:"bg-gray-500 text-white px-2 py-1 rounded text-xs",children:m.pendingCount})})]})]})]},u)})}),e.jsx("div",{className:"mt-4",children:e.jsx(jr,{currentPage:s.page,totalPages:s.totalPages,totalRecords:s.totalRecords,itemsPerPage:10,onPageChange:o,itemLabel:"approvers",testIdPrefix:"dashboard-approver-pagination"})})]})]})}function Dj(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 Pj(t,s,a,r){const n=[];return r||n.push({label:"New Request",icon:Pe,action:()=>s==null?void 0:s(),color:"bg-emerald-600 hover:bg-emerald-700"}),n.push({label:"View Pending",icon:Xe,action:()=>a==null?void 0:a("open-requests"),color:"bg-blue-600 hover:bg-blue-700"},{label:"Settings",icon:za,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:Dt,action:()=>a==null?void 0:a("detailed-reports"),color:"bg-purple-600 hover:bg-purple-700"}),n}function Ij({onNavigate:t,onNewRequest:s}){const{user:a}=Jt(),r=kn(),n=Wr(lt=>lt.dashboard.viewAsUser),i=h.useMemo(()=>Mi(a),[a]),l=i&&!n,o=h.useCallback(lt=>{r(ob(lt))},[r]),d=cb(),{dateRange:c,customStartDate:m,customEndDate:u,showCustomDatePicker:x,handleDateRangeChange:p,handleApplyCustomDate:g,resetCustomDates:y,setCustomStartDate:f,setCustomEndDate:b,setShowCustomDatePicker:v}=d,A=db(),{activity:w,critical:T,deadlines:k,approver:L,updateActivityPagination:D,updateCriticalPagination:S,updateDeadlinesPagination:N,updateApproverPagination:P,handleActivityPageChange:R,handleCriticalPageChange:O,handleDeadlinesPageChange:E,handleApproverPageChange:M}=A,B=ub({isAdmin:l,viewAsUser:i&&n,userId:a==null?void 0:a.userId,dateRange:c,customStartDate:m,customEndDate:u,onPaginationUpdate:{activity:D,critical:S,deadlines:N,approver:P}}),{kpis:C,recentActivity:j,criticalRequests:U,departmentStats:$,priorityDistribution:_,upcomingDeadlines:se,aiRemarkUtilization:W,approverPerformance:ce,loading:Z,refreshing:I,fetchDashboardData:V,fetchRecentActivities:z,fetchCriticalRequests:X,fetchUpcomingDeadlines:Y,fetchApproverPerformance:G}=B,ie=Nb(),{exportingDeptStats:me,exportingApproverPerformance:Te,handleExportDepartmentStats:Se,handleExportApproverPerformance:re}=ie,pe=h.useMemo(()=>dj(U),[U]),ve=h.useMemo(()=>mj(se),[se]),be=h.useCallback(()=>{V(!0)},[c,m,u,V]),Le=h.useCallback(()=>{g(()=>{m&&u&&V(!1)})},[m,u,g,V]),J=h.useCallback(lt=>{R(lt,z)},[R,z]),Oe=h.useCallback(lt=>{O(lt,X)},[O,X]),xt=h.useCallback(lt=>{E(lt,Y)},[E,Y]),je=h.useCallback(lt=>{M(lt,()=>G(lt))},[M,G]);h.useEffect(()=>{c==="custom"?m&&u&&V(!1):V(!1)},[c,m,u,n]);const $e=h.useMemo(()=>{try{const lt=at.getUserData();return(lt==null?void 0:lt.jobTitle)==="Dealer"}catch(lt){return console.error("[Dashboard] Error checking dealer status:",lt),!1}},[]),yt=h.useMemo(()=>Pj(i,s,t,$e),[i,s,t,$e]),kt=h.useCallback(lt=>{const Fs=Dj(lt);t==null||t(Fs)},[t]);return Z?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(Bt,{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(wb,{isAdmin:i,effectiveIsAdmin:l,viewAsUser:n,onToggleView:o,quickActions:yt,userDisplayName:a==null?void 0:a.displayName,userEmail:a==null?void 0:a.email}),e.jsx(rj,{isAdmin:l,dateRange:c,customStartDate:m,customEndDate:u,showCustomDatePicker:x,refreshing:I,onDateRangeChange:p,onCustomStartDateChange:f,onCustomEndDateChange:b,onShowCustomDatePickerChange:v,onApplyCustomDate:Le,onResetCustomDates:y,onRefresh:be}),l?e.jsx(nj,{kpis:C,priorityDistribution:_,dateRange:c,customStartDate:m,customEndDate:u,onKPIClick:kt}):e.jsx(ij,{kpis:C,criticalRequests:U,dateRange:c,customStartDate:m,customEndDate:u,onKPIClick:kt,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(hj,{isAdmin:l,breachedRequests:pe,pagination:T,onPageChange:Oe,onNavigate:t}),e.jsx(vj,{isAdmin:l,recentActivity:j,pagination:w,refreshing:I,onPageChange:J,onRefresh:be,onNavigate:t,currentUserId:a==null?void 0:a.userId,currentUserDisplayName:a==null?void 0:a.displayName,currentUserEmail:a==null?void 0:a.email})]}),l&&C&&e.jsx(jj,{kpis:C,upcomingDeadlines:se,criticalRequests:U,departmentStats:$,dateRange:c,customStartDate:m,customEndDate:u,exportingDeptStats:me,onKPIClick:kt,onExportDepartmentStats:Se}),!l&&C&&e.jsx(Nj,{kpis:C}),l&&_.length>0&&e.jsx(wj,{priorityDistribution:_,onNavigate:t}),l&&pe.length>0&&e.jsx(Sj,{breachedRequests:pe,pagination:T,dateRange:c,customStartDate:m,customEndDate:u,onPageChange:Oe,onKPIClick:kt,onNavigate:t}),ve.length>0&&e.jsx(Tj,{isAdmin:l,upcomingDeadlines:ve,pagination:k,onPageChange:xt,onNavigate:t}),l&&W&&e.jsx(kj,{aiRemarkUtilization:W}),l&&ce.length>0&&e.jsx(Rj,{approverPerformance:ce,pagination:L,dateRange:c,customStartDate:m,customEndDate:u,loading:Z,exportingApproverPerformance:Te,onPageChange:je,onExport:re,onNavigate:t})]})}const Ej={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",sortBy:"created",sortOrder:"desc",currentPage:1},Bx=zr({name:"openRequests",initialState:Ej,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:Fj,setStatusFilter:Mj,setPriorityFilter:_j,setTemplateTypeFilter:Lj,setSortBy:Oj,setSortOrder:$j,setCurrentPage:Uj,clearFilters:Bj}=Bx.actions;function Vj(){const t=kn(),{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,sortBy:i,sortOrder:l,currentPage:o}=Wr(b=>b.openRequests),d=h.useCallback(b=>t(Fj(b)),[t]),c=h.useCallback(b=>t(Mj(b)),[t]),m=h.useCallback(b=>t(_j(b)),[t]),u=h.useCallback(b=>t(Lj(b)),[t]),x=h.useCallback(b=>t(Oj(b)),[t]),p=h.useCallback(b=>t($j(b)),[t]),g=h.useCallback(b=>t(Uj(b)),[t]),y=h.useCallback(()=>t(Bj()),[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:d,setStatusFilter:c,setPriorityFilter:m,setTemplateTypeFilter:u,setSortBy:x,setSortOrder:p,setCurrentPage:g,clearFilters:y,activeFiltersCount:f}}function ol(){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 zj(t){var o;const s=t.priorityUi.toUpperCase()==="EXPRESS"?"EXPRESS":"STANDARD",a=Array.from({length:t.approverCount||1},(d,c)=>{const m=c,u=t.approvers[m]||{},x=m+1,p=u.tat??"";let g=0;typeof p=="number"&&(g=u.tatType==="days"?p*24:p);const y=u.email||"",f=u.name&&u.name.trim()||y.split("@")[0]||`Approver ${x}`;return{levelNumber:x,levelName:`Level ${x}`,approverId:ol(),approverEmail:y,approverName:f,tatHours:g>0?g:24,isFinalApprover:x===(t.approverCount||1)}}),r=[...(t.spectators||[]).map(d=>({userId:ol(),userEmail:d.email,userName:d.name||d.email.split("@")[0]||"Spectator",participantType:"SPECTATOR",canComment:!0,canViewDocuments:!0,canDownloadDocuments:!1,notificationEnabled:!0})),...(t.ccList||[]).map(d=>({userId:ol(),userEmail:d.email,userName:d.name||d.email.split("@")[0]||"CC",participantType:"CONSULTATION",canComment:!1,canViewDocuments:!0,canDownloadDocuments:!1,notificationEnabled:!0}))],n={templateType:t.templateType,title:t.title,description:t.description,priority:s,approvalLevels:a,participants:r.length?r:void 0},i=await Ne.post("/workflows",n),l=((o=i.data)==null?void 0:o.data)||i.data;return{id:l.id||l.workflowId||""}}async function Vx(t,s,a="SUPPORTING"){var o;const r={templateType:t.templateType,title:t.title,description:t.description,priority:t.priorityUi.toUpperCase()==="EXPRESS"?"EXPRESS":"STANDARD",approvers:Array.from({length:t.approverCount||1},(d,c)=>{const m=t.approvers[c]||{},u=typeof m.tat=="number"?m.tat:0;if(!m.email||!m.email.trim())throw new Error(`Email is required for approver at level ${c+1}.`);return{email:m.email,tat:u,tatType:m.tatType||"hours"}})};t.spectators&&t.spectators.length>0&&(r.spectators=t.spectators.filter(d=>d==null?void 0:d.email).map(d=>({email:d.email})));const n=new FormData;n.append("payload",JSON.stringify(r)),n.append("category",a),s.forEach(d=>n.append("files",d));const i=await Ne.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 Hj(t={}){var y;const{page:s=1,limit:a=20,search:r,status:n,priority:i,templateType:l,department:o,initiator:d,approver:c,slaCompliance:m,dateRange:u,startDate:x,endDate:p}=t,g=await Ne.get("/workflows",{params:{page:s,limit:a,search:r,status:n,priority:i,templateType:l,department:o,initiator:d,approver:c,slaCompliance:m,dateRange:u,startDate:x,endDate:p}});return((y=g.data)==null?void 0:y.data)||g.data}async function Wj(t={}){var f,b,v,A,w;const{page:s=1,limit:a=20,search:r,status:n,priority:i,templateType:l,department:o,initiator:d,approver:c,approverType:m,slaCompliance:u,dateRange:x,startDate:p,endDate:g}=t,y=await Ne.get("/workflows/participant-requests",{params:{page:s,limit:a,search:r,status:n,priority:i,templateType:l,department:o,initiator:d,approver:c,approverType:m,slaCompliance:u,dateRange:x,startDate:p,endDate:g}});return{data:((b=(f=y.data)==null?void 0:f.data)==null?void 0:b.data)||((v=y.data)==null?void 0:v.data)||[],pagination:((w=(A=y.data)==null?void 0:A.data)==null?void 0:w.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Gj(t={}){var g,y,f,b,v;const{page:s=1,limit:a=20,search:r,status:n,priority:i,department:l,initiator:o,approver:d,slaCompliance:c,dateRange:m,startDate:u,endDate:x}=t,p=await Ne.get("/workflows/my",{params:{page:s,limit:a,search:r,status:n,priority:i,department:l,initiator:o,approver:d,slaCompliance:c,dateRange:m,startDate:u,endDate:x}});return{data:((y=(g=p.data)==null?void 0:g.data)==null?void 0:y.data)||((f=p.data)==null?void 0:f.data)||[],pagination:((v=(b=p.data)==null?void 0:b.data)==null?void 0:v.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Kj(t={}){var p,g,y,f,b;const{page:s=1,limit:a=20,search:r,status:n,priority:i,templateType:l,department:o,slaCompliance:d,dateRange:c,startDate:m,endDate:u}=t,x=await Ne.get("/workflows/my-initiated",{params:{page:s,limit:a,search:r,status:n,priority:i,templateType:l,department:o,slaCompliance:d,dateRange:c,startDate:m,endDate:u}});return{data:((g=(p=x.data)==null?void 0:p.data)==null?void 0:g.data)||((y=x.data)==null?void 0:y.data)||[],pagination:((b=(f=x.data)==null?void 0:f.data)==null?void 0:b.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Yj(t={}){var m,u,x,p,g;const{page:s=1,limit:a=20,search:r,status:n,priority:i,templateType:l,sortBy:o,sortOrder:d}=t,c=await Ne.get("/workflows/open-for-me",{params:{page:s,limit:a,search:r,status:n,priority:i,templateType:l,sortBy:o,sortOrder:d}});return{data:((u=(m=c.data)==null?void 0:m.data)==null?void 0:u.data)||((x=c.data)==null?void 0:x.data)||[],pagination:((g=(p=c.data)==null?void 0:p.data)==null?void 0:g.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Zj(t={}){var m,u,x,p,g;const{page:s=1,limit:a=20,search:r,status:n,priority:i,templateType:l,sortBy:o,sortOrder:d}=t,c=await Ne.get("/workflows/closed-by-me",{params:{page:s,limit:a,search:r,status:n,priority:i,templateType:l,sortBy:o,sortOrder:d}});return{data:((u=(m=c.data)==null?void 0:m.data)==null?void 0:u.data)||((x=c.data)==null?void 0:x.data)||[],pagination:((g=(p=c.data)==null?void 0:p.data)==null?void 0:g.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function ws(t,s){var r;const a=await Ne.get(`/workflows/${t}/details`);return((r=a.data)==null?void 0:r.data)||a.data}async function Mr(t){var a;const s=await Ne.get(`/workflows/${t}/work-notes`);return((a=s.data)==null?void 0:a.data)||s.data}async function zx(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 Ne.post(`/workflows/${t}/work-notes`,r,{headers:{"Content-Type":"multipart/form-data"}});return((i=n.data)==null?void 0:i.data)||n.data}async function Hx(t,s,a,r){var i;const n=await Ne.post(`/workflows/${t}/approvers/at-level`,{email:s,tatHours:a,level:r});return((i=n.data)==null?void 0:i.data)||n.data}async function Xj(t,s,a){var n;const r=await Ne.post(`/workflows/${t}/approvals/${s}/skip`,{reason:a});return((n=r.data)==null?void 0:n.data)||r.data}async function Wx(t,s){var r;const a=await Ne.post(`/workflows/${t}/participants/spectator`,{email:s});return((r=a.data)==null?void 0:r.data)||a.data}async function Qj(t,s,a,r){var i;const n=await Ne.post(`/workflows/${t}/pause`,{levelId:s,reason:a,resumeDate:r.toISOString()});return((i=n.data)==null?void 0:i.data)||n.data}async function Jj(t,s){var r;const a=await Ne.post(`/workflows/${t}/resume`,{notes:s});return((r=a.data)==null?void 0:r.data)||a.data}async function qj(t){var a;const s=await Ne.post(`/workflows/${t}/pause/retrigger`);return((a=s.data)==null?void 0:a.data)||s.data}async function sm(t){var a;const s=await Ne.get(`/workflows/${t}/pause`);return((a=s.data)==null?void 0:a.data)||s.data}function eN(t){return`https://re-workflow-nt-dev.siplsolutions.com/api/v1/workflows/work-notes/attachments/${t}/preview`}function Gr(t){return`https://re-workflow-nt-dev.siplsolutions.com/api/v1/workflows/documents/${t}/preview`}function Gx(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 bs(t){const a=`https://re-workflow-nt-dev.siplsolutions.com/api/v1/workflows/documents/${t}/download`,r=!0;try{const i=await fetch(a,{credentials:"include"});if(!i.ok){const u=await i.text();throw new Error(`Download failed: ${i.status} - ${u}`)}const l=await i.blob(),o=window.URL.createObjectURL(l),d=i.headers.get("Content-Disposition"),c=Gx(d),m=document.createElement("a");m.href=o,m.download=c,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 am(t){const a=`https://re-workflow-nt-dev.siplsolutions.com/api/v1/workflows/work-notes/attachments/${t}/download`,r=!0;try{const i=await fetch(a,{credentials:"include"});if(!i.ok){const u=await i.text();throw new Error(`Download failed: ${i.status} - ${u}`)}const l=await i.blob(),o=window.URL.createObjectURL(l),d=i.headers.get("Content-Disposition"),c=Gx(d),m=document.createElement("a");m.href=o,m.download=c,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:zj,createWorkflowMultipart:Vx,listWorkflows:Hj,listParticipantRequests:Wj,listMyWorkflows:Gj,listMyInitiatedWorkflows:Kj,listOpenForMe:Yj,listClosedByMe:Zj,submitWorkflow:Kx,getWorkflowDetails:ws,getWorkNotes:Mr,createWorkNoteMultipart:zx,handleInitiatorAction:Yx};async function Kx(t){var a;const s=await Ne.patch(`/workflows/${t}/submit`);return((a=s.data)==null?void 0:a.data)||s.data}async function tN(t,s){var r;const a=await Ne.put(`/workflows/${t}`,s);return((r=a.data)==null?void 0:r.data)||a.data}async function sN(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(d=>i.append("files",d));const l=await Ne.put(`/workflows/${t}/multipart`,i,{headers:{"Content-Type":"multipart/form-data"}});return((o=l.data)==null?void 0:o.data)||l.data}async function cn(t,s,a){var n;const r=await Ne.patch(`/workflows/${t}/approvals/${s}/approve`,{action:"APPROVE",comments:a||""});return((n=r.data)==null?void 0:n.data)||r.data}async function Ar(t,s,a,r){var i;const n=await Ne.patch(`/workflows/${t}/approvals/${s}/reject`,{action:"REJECT",rejectionReason:a||"",comments:r||""});return((i=n.data)==null?void 0:i.data)||n.data}async function aN(t,s){const a=await Ne.put(`/tat/breach-reason/${t}`,{breachReason:s});if(!a.data.success)throw new Error(a.data.error||"Failed to update breach reason")}async function Yx(t,s,a){var n;const r=await Ne.post(`/workflows/${t}/initiator-action`,{action:s,...a});return((n=r.data)==null?void 0:n.data)||r.data}async function rN(t){var a;return((a=(await Ne.get(`/workflows/${t}/history`)).data)==null?void 0:a.data)||[]}function is(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 Zx(t){return is(t,{includeTime:!1,format:"short"})}function ha(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(),d=o%12||12,c=String(a.getMinutes()).padStart(2,"0"),m=String(a.getSeconds()).padStart(2,"0"),u=o>=12?"PM":"AM";return`${r} ${i} ${l}, ${d}:${c}:${m} ${u}`}return`${r} ${i} ${l}`}catch(a){return console.error("Error formatting date:",a),String(t)}}function nN(t){return t?t.jobTitle==="Dealer"||t.jobTitle==="DEALER":!1}function _o(t){return nN(t)?"DEALER":"STANDARD"}const Un=[{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 $i({value:t,onChange:s,placeholder:a="Enter text...",className:r,minHeight:n="120px",...i}){const l=h.useRef(null),[o,d]=h.useState(!1),[c,m]=h.useState(new Set),[u,x]=h.useState(!1),[p,g]=h.useState(null),[y,f]=h.useState("#FFEB3B"),[b,v]=h.useState(!1),[A,w]=h.useState(null),[T,k]=h.useState("#000000");h.useEffect(()=>{l.current&&l.current.innerHTML!==t&&l.current.innerHTML!==t&&(l.current.innerHTML=t||"")},[t]);const L=h.useCallback(C=>(C=C.replace(/<!--[\s\S]*?-->/g,""),C=C.replace(/<style[^>]*>[\s\S]*?<\/style>/gi,""),C=C.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,""),C=C.replace(/<meta[^>]*>/gi,""),C=C.replace(/\s*class="Mso[^"]*"/gi,""),C=C.replace(/\s*class="mso[^"]*"/gi,""),C=C.replace(/\s*style="[^"]*mso-[^"]*"/gi,""),C=C.replace(/\s*style="[^"]*font-family:[^"]*"/gi,""),C=C.replace(/\s*xmlns[^=]*="[^"]*"/gi,""),C=C.replace(/<\/?o:p[^>]*>/gi,""),C=C.replace(/<v:[^>]*>[\s\S]*?<\/v:[^>]*>/gi,""),C=C.replace(/<v:[^>]*\/>/gi,""),C=C.replace(/<p[^>]*>\s*<\/p>/gi,""),C=C.replace(/<div[^>]*>\s*<\/div>/gi,""),C=C.replace(/\s+/g," "),C=C.trim(),C),[]),D=h.useCallback(C=>{C.preventDefault();const j=C.clipboardData;let U=j.getData("text/html")||j.getData("text/plain");if((U.includes("<!--")||U.includes("<style")||U.includes("MsoNormal"))&&(U=L(U)),!l.current)return;const $=window.getSelection();if(!$||$.rangeCount===0)return;const _=$.getRangeAt(0);_.deleteContents();const se=document.createElement("div");se.innerHTML=U;const W=document.createDocumentFragment();Array.from(se.childNodes).forEach(ce=>{if(ce.nodeType===Node.ELEMENT_NODE){const Z=ce;if(Z.tagName==="UL"||Z.tagName==="OL"){const I=Z.cloneNode(!0);I.removeAttribute("style"),I.removeAttribute("class"),I.querySelectorAll("li").forEach(V=>{V.removeAttribute("style"),V.removeAttribute("class");const z=V.textContent||"";z.trim()&&(V.textContent=z.trim())}),W.appendChild(I)}else if(Z.tagName==="TABLE"){const I=Z.cloneNode(!0);I.removeAttribute("style"),I.removeAttribute("class"),I.querySelectorAll("td, th").forEach(z=>{z.removeAttribute("style"),z.removeAttribute("class")});const V=document.createElement("div");V.className="table-wrapper",V.style.overflowX="auto",V.style.maxWidth="100%",V.style.margin="8px 0",V.appendChild(I),W.appendChild(V)}else if(Z.tagName==="P"||Z.tagName==="DIV"){const I=document.createElement("p"),z=Z.innerHTML.replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<!--[\s\S]*?-->/g,"");I.innerHTML=z,I.removeAttribute("style"),I.removeAttribute("class"),W.appendChild(I)}else if(Z.tagName==="BR")W.appendChild(Z.cloneNode(!0));else{const I=Z.textContent||"";if(I.trim()){const V=document.createElement("p");V.textContent=I.trim(),W.appendChild(V)}}}else if(ce.nodeType===Node.TEXT_NODE){const Z=ce.textContent||"";if(Z.trim()){const I=document.createElement("p");I.textContent=Z.trim(),W.appendChild(I)}}}),W.childNodes.length===0&&j.getData("text/plain").split(`
|
||
`).forEach(I=>{if(I.trim()){const V=document.createElement("p");V.textContent=I.trim(),W.appendChild(V)}else W.appendChild(document.createElement("br"))}),_.insertNode(W),_.collapse(!1),$.removeAllRanges(),$.addRange(_),l.current&&s(l.current.innerHTML)},[s,L]),S=h.useCallback(()=>{if(!l.current||!o)return;const C=new Set,j=window.getSelection();if(j&&j.rangeCount>0){const $=j.getRangeAt(0).commonAncestorContainer;let _=null;for($.nodeType===Node.TEXT_NODE?_=$.parentElement:_=$;_&&_!==l.current;){const se=_.tagName.toLowerCase();(se==="strong"||se==="b")&&C.add("bold"),(se==="em"||se==="i")&&C.add("italic"),se==="u"&&C.add("underline"),se==="h1"&&C.add("h1"),se==="h2"&&C.add("h2"),se==="h3"&&C.add("h3"),se==="ul"&&C.add("ul"),se==="ol"&&C.add("ol");const W=window.getComputedStyle(_);W.textAlign==="center"&&C.add("center"),W.textAlign==="right"&&C.add("right"),W.textAlign==="left"&&C.add("left");const ce=z=>{if(z.startsWith("#"))return z.toUpperCase();const X=z.match(/\d+/g);if(!X||X.length<3)return null;const Y=X[0],G=X[1],ie=X[2];if(!Y||!G||!ie)return null;const me=parseInt(Y).toString(16).padStart(2,"0"),Te=parseInt(G).toString(16).padStart(2,"0"),Se=parseInt(ie).toString(16).padStart(2,"0");return`#${me}${Te}${Se}`.toUpperCase()},Z=W.backgroundColor;if(Z&&Z!=="rgba(0, 0, 0, 0)"&&Z!=="transparent"&&Z!=="rgb(255, 255, 255)"&&Z!=="#ffffff"&&Z!=="#FFFFFF"){C.add("highlight");const z=ce(Z);if(z){const X=Un.find(Y=>Y.value==="transparent"?!1:Y.value.toUpperCase()===z);g(X?X.value:z)}}else C.has("highlight")||g(null);const I=W.color,V=ce(I);if(I&&V&&I!=="rgba(0, 0, 0, 0)"&&V!=="#000000"){C.add("textColor");const z=Un.find(X=>X.value==="transparent"?!1:X.value.toUpperCase()===V);w(z?z.value:V)}else C.has("textColor")||w(V==="#000000"||!V?"#000000":null);_=_.parentElement}}m(C)},[o]),N=h.useCallback((C,j)=>{if(!l.current)return;o||l.current.focus();const U=window.getSelection();if(!U||U.rangeCount===0){l.current.focus();return}document.execCommand(C,!1,j),l.current&&s(l.current.innerHTML),setTimeout(S,10)},[o,s,S]),P=h.useCallback(C=>{if(!l.current)return;o||l.current.focus();const j=window.getSelection();if(!j||j.rangeCount===0){l.current.focus();return}let U=!1;if(j.rangeCount>0){const se=j.getRangeAt(0).commonAncestorContainer;let W=null;for(se.nodeType===Node.TEXT_NODE?W=se.parentElement:W=se;W&&W!==l.current;){const Z=window.getComputedStyle(W).backgroundColor;if(Z&&Z!=="rgba(0, 0, 0, 0)"&&Z!=="transparent"&&Z!=="rgb(255, 255, 255)"&&Z!=="#ffffff"&&Z!=="#FFFFFF"){const V=(z=>{if(z.startsWith("#"))return z.toUpperCase();const X=z.match(/\d+/g);if(!X||X.length<3)return null;const Y=X[0],G=X[1],ie=X[2];if(!Y||!G||!ie)return null;const me=parseInt(Y).toString(16).padStart(2,"0"),Te=parseInt(G).toString(16).padStart(2,"0"),Se=parseInt(ie).toString(16).padStart(2,"0");return`#${me}${Te}${Se}`.toUpperCase()})(Z);if(V&&V===C.toUpperCase()){U=!0;break}}W=W.parentElement}}if(C==="transparent"||U){const _=j.getRangeAt(0);if(_.collapsed)document.execCommand("removeFormat",!1);else{const se=_.extractContents(),W=document.createDocumentFragment(),ce=Z=>{if(Z.nodeType===Node.TEXT_NODE)return Z.cloneNode(!0);if(Z.nodeType===Node.ELEMENT_NODE){const I=Z,V=document.createElement(I.tagName.toLowerCase());return Array.from(I.attributes).forEach(z=>{z.name!=="style"&&z.name!=="class"&&V.setAttribute(z.name,z.value)}),Array.from(I.childNodes).forEach(z=>{const X=ce(z);X&&V.appendChild(X)}),I.style.backgroundColor&&(V.style.backgroundColor=""),V}return null};Array.from(se.childNodes).forEach(Z=>{const I=ce(Z);I&&W.appendChild(I)}),_.insertNode(W),document.execCommand("removeFormat",!1)}g(null),f("#FFEB3B")}else if(j.rangeCount>0&&!j.getRangeAt(0).collapsed)document.execCommand("backColor",!1,C),g(C),C!=="transparent"&&/^#[0-9A-Fa-f]{6}$/i.test(C)&&f(C);else return;const $=window.getSelection();$&&$.removeAllRanges(),l.current&&s(l.current.innerHTML),x(!1),setTimeout(()=>{l.current&&l.current.focus(),S()},50)},[o,s,S]),R=h.useCallback(C=>{if(!l.current)return;o||l.current.focus();const j=window.getSelection();if(!j||j.rangeCount===0){l.current.focus();return}let U=!1;if(j.rangeCount>0){const _=j.getRangeAt(0).commonAncestorContainer;let se=null;for(_.nodeType===Node.TEXT_NODE?se=_.parentElement:se=_;se&&se!==l.current;){const ce=window.getComputedStyle(se).color;if(ce){const I=(V=>{if(V.startsWith("#"))return V.toUpperCase();const z=V.match(/\d+/g);if(!z||z.length<3)return null;const X=z[0],Y=z[1],G=z[2];if(!X||!Y||!G)return null;const ie=parseInt(X).toString(16).padStart(2,"0"),me=parseInt(Y).toString(16).padStart(2,"0"),Te=parseInt(G).toString(16).padStart(2,"0");return`#${ie}${me}${Te}`.toUpperCase()})(ce);if(C==="#000000"){if(I==="#000000"||!I){U=!0;break}}else if(I&&I===C.toUpperCase()){U=!0;break}}se=se.parentElement}}if(C==="transparent"||C==="default"||U){if(C==="#000000"&&U){v(!1);return}document.execCommand("removeFormat",!1),w(null),k("#000000")}else document.execCommand("foreColor",!1,C),w(C),C!=="transparent"&&/^#[0-9A-Fa-f]{6}$/i.test(C)&&k(C);l.current&&s(l.current.innerHTML),v(!1),setTimeout(S,10)},[o,s,S]),O=h.useCallback(()=>{l.current&&s(l.current.innerHTML),S()},[s,S]),E=h.useCallback(C=>{if(C.ctrlKey&&C.key==="b"){C.preventDefault(),N("bold");return}if(C.ctrlKey&&C.key==="i"){C.preventDefault(),N("italic");return}if(C.ctrlKey&&C.key==="u"){C.preventDefault(),N("underline");return}},[N]),M=h.useCallback(()=>{d(!0)},[]),B=h.useCallback(()=>{d(!1),l.current&&s(l.current.innerHTML)},[s]);return h.useEffect(()=>{if(!o)return;const C=()=>{S()};return document.addEventListener("selectionchange",C),()=>{document.removeEventListener("selectionchange",C)}},[o,S]),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:Re("h-7 w-7 p-0",c.has("bold")&&"bg-blue-100 text-blue-700"),onClick:()=>N("bold"),title:"Bold (Ctrl+B)",children:e.jsx(Gf,{className:"h-4 w-4"})}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:Re("h-7 w-7 p-0",c.has("italic")&&"bg-blue-100 text-blue-700"),onClick:()=>N("italic"),title:"Italic (Ctrl+I)",children:e.jsx(Kf,{className:"h-4 w-4"})}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:Re("h-7 w-7 p-0",c.has("underline")&&"bg-blue-100 text-blue-700"),onClick:()=>N("underline"),title:"Underline (Ctrl+U)",children:e.jsx(Yf,{className:"h-4 w-4"})}),e.jsxs(Ys,{open:u,onOpenChange:x,children:[e.jsx(Zs,{asChild:!0,children:e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:Re("h-7 w-7 p-0",c.has("highlight")&&"bg-blue-100 text-blue-700"),title:"Text Highlight",children:e.jsx(Zf,{className:"h-4 w-4"})})}),e.jsx(Xs,{className:"w-auto p-2",align:"start",onPointerDownOutside:C=>{C.target.closest("[data-popover-content]")&&C.preventDefault()},children:e.jsxs("div",{className:"space-y-2 relative",onClick:C=>C.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:C=>{C.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:Un.map(C=>{const j=p===C.value,U=C.value==="transparent";return e.jsxs("button",{type:"button",onClick:$=>{$.preventDefault(),$.stopPropagation(),P(j&&!U?"transparent":C.value)},className:Re("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md relative",C.class,j&&"ring-2 ring-blue-600 ring-offset-1 border-blue-600",U&&"border-gray-400 bg-white",!U&&!j&&"border-gray-300"),title:j&&!U?`${C.name} (Click to remove)`:C.name,style:U?{}:{backgroundColor:C.value},children:[U&&e.jsx("span",{className:"text-[10px] text-gray-600 font-bold",children:"×"}),j&&!U&&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"})})]},C.value)})}),p&&p!=="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:C=>{C.stopPropagation(),P("transparent")},title:"Remove highlight color",children:"Remove Highlight"})}),e.jsxs("div",{className:"border-t border-gray-200 pt-2 mt-2",children:[e.jsx("div",{className:"text-xs font-semibold text-gray-700 mb-1.5",children:"Custom Color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:p&&p!=="transparent"?p:y,onChange:C=>{const j=C.target.value;f(j);const U=window.getSelection();U&&U.rangeCount>0&&!U.getRangeAt(0).collapsed&&P(j)},className:"w-8 h-8 rounded border border-gray-300 cursor-pointer",title:"Pick a custom color"}),e.jsx("input",{type:"text",value:p&&p!=="transparent"?p:y,onChange:C=>{C.stopPropagation();const j=C.target.value;f(j)},onKeyDown:C=>{if(C.stopPropagation(),C.key==="Enter"){C.preventDefault();const j=C.currentTarget.value.trim();/^#[0-9A-Fa-f]{6}$/i.test(j)&&P(j)}},onPaste:C=>{C.stopPropagation();const j=C.clipboardData.getData("text").trim();C.preventDefault(),setTimeout(()=>{if(/^#[0-9A-Fa-f]{6}$/i.test(j)){f(j);const U=window.getSelection();U&&U.rangeCount>0&&!U.getRangeAt(0).collapsed&&P(j)}else{const U=j.match(/^([0-9A-Fa-f]{6})$/);if(U){const $=`#${U[1]}`;f($);const _=window.getSelection();_&&_.rangeCount>0&&!_.getRangeAt(0).collapsed&&P($)}}},0)},onClick:C=>{C.stopPropagation()},onFocus:C=>{C.stopPropagation(),C.target.select()},onBlur:C=>{const j=C.target.value.trim();if(/^#[0-9A-Fa-f]{6}$/i.test(j)){const U=window.getSelection();U&&U.rangeCount>0&&!U.getRangeAt(0).collapsed&&P(j)}else f(j===""?p||"#FFEB3B":j)},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 C=y.trim();/^#[0-9A-Fa-f]{6}$/i.test(C)?P(C):f(p||"#FFEB3B")},title:"Apply custom color",children:"Apply"})]})]})]})})]}),e.jsxs(Ys,{open:b,onOpenChange:v,children:[e.jsx(Zs,{asChild:!0,children:e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:Re("h-7 w-7 p-0",c.has("textColor")&&"bg-blue-100 text-blue-700"),title:"Text Color",children:e.jsx(Xf,{className:"h-4 w-4"})})}),e.jsx(Xs,{className:"w-auto p-2",align:"start",onPointerDownOutside:C=>{C.target.closest("[data-popover-content]")&&C.preventDefault()},children:e.jsxs("div",{className:"space-y-2 relative",onClick:C=>C.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:C=>{C.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:C=>{C.preventDefault(),C.stopPropagation(),A==="#000000"||!A&&!c.has("textColor")||R("#000000")},className:Re("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md flex items-center justify-center bg-black",(A==="#000000"||!A&&!c.has("textColor"))&&"ring-2 ring-blue-600 ring-offset-1 border-blue-600",A!=="#000000"&&(A||c.has("textColor"))&&"border-gray-300"),title:"Default (Black)",children:[e.jsx("span",{className:"text-[10px] text-white font-bold",children:"A"}),(A==="#000000"||!A&&!c.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"})})]}),Un.filter(C=>C.value!=="transparent").map(C=>{const j=A===C.value;return e.jsxs("button",{type:"button",onClick:U=>{U.preventDefault(),U.stopPropagation(),R(j?"#000000":C.value)},className:Re("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md flex items-center justify-center relative",j&&"ring-2 ring-blue-600 ring-offset-1 border-blue-600",!j&&"border-gray-300"),title:j?`${C.name} (Click to reset to default)`:C.name,style:{color:C.value,borderColor:j?"#2563eb":C.value},children:[e.jsx("span",{className:"text-xs font-bold",children:"A"}),j&&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-${C.value}`)})]}),A&&A!=="#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:C=>{C.stopPropagation(),R("#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:A||T,onChange:C=>{const j=C.target.value;k(j),R(j)},className:"w-8 h-8 rounded border border-gray-300 cursor-pointer",title:"Pick a custom text color"}),e.jsx("input",{type:"text",value:A||T,onChange:C=>{const j=C.target.value;k(j)},onKeyDown:C=>{if(C.key==="Enter"){C.preventDefault();const j=C.currentTarget.value;/^#[0-9A-Fa-f]{6}$/.test(j)&&R(j)}},onBlur:C=>{const j=C.target.value;/^#[0-9A-Fa-f]{6}$/.test(j)?R(j):j===""&&k(A||"#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:()=>R(T),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:Re("h-7 w-7 p-0",c.has("h1")&&"bg-blue-100 text-blue-700"),onClick:()=>N("formatBlock","<h1>"),title:"Heading 1",children:e.jsx(Qf,{className:"h-4 w-4"})}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:Re("h-7 w-7 p-0",c.has("h2")&&"bg-blue-100 text-blue-700"),onClick:()=>N("formatBlock","<h2>"),title:"Heading 2",children:e.jsx(Jf,{className:"h-4 w-4"})}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:Re("h-7 w-7 p-0",c.has("h3")&&"bg-blue-100 text-blue-700"),onClick:()=>N("formatBlock","<h3>"),title:"Heading 3",children:e.jsx(qf,{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:Re("h-7 w-7 p-0",c.has("ul")&&"bg-blue-100 text-blue-700"),onClick:()=>N("insertUnorderedList"),title:"Bullet List",children:e.jsx(Xu,{className:"h-4 w-4"})}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:Re("h-7 w-7 p-0",c.has("ol")&&"bg-blue-100 text-blue-700"),onClick:()=>N("insertOrderedList"),title:"Numbered List",children:e.jsx(e0,{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:Re("h-7 w-7 p-0",c.has("left")&&"bg-blue-100 text-blue-700"),onClick:()=>N("justifyLeft"),title:"Align Left",children:e.jsx(qu,{className:"h-4 w-4"})}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:Re("h-7 w-7 p-0",c.has("center")&&"bg-blue-100 text-blue-700"),onClick:()=>N("justifyCenter"),title:"Align Center",children:e.jsx(t0,{className:"h-4 w-4"})}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:Re("h-7 w-7 p-0",c.has("right")&&"bg-blue-100 text-blue-700"),onClick:()=>N("justifyRight"),title:"Align Right",children:e.jsx(s0,{className:"h-4 w-4"})})]})]}),e.jsx("div",{ref:l,contentEditable:!0,onPaste:D,onInput:O,onFocus:M,onBlur:B,onKeyDown:E,onMouseUp:S,onKeyUp:S,"data-placeholder":a,className:Re("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 ra({content:t,className:s}){const a=h.useMemo(()=>{if(!t)return"";let r=t;const n=/<table[^>]*>[\s\S]*?<\/table>/gi;return r=r.replace(n,i=>i.includes("table-wrapper")?i:`<div class="table-wrapper" style="overflow-x: auto; max-width: 100%; margin: 8px 0;">${i}</div>`),r},[t]);return t?e.jsx("div",{className:Re("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 Xx={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(vi,function(){var a=1e3,r=6e4,n=36e5,i="millisecond",l="second",o="minute",d="hour",c="day",m="week",u="month",x="quarter",p="year",g="date",y="Invalid Date",f=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,b=/\[([^\]]+)]|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(E){var M=["th","st","nd","rd"],B=E%100;return"["+E+(M[(B-20)%10]||M[B]||M[0])+"]"}},A=function(E,M,B){var C=String(E);return!C||C.length>=M?E:""+Array(M+1-C.length).join(B)+E},w={s:A,z:function(E){var M=-E.utcOffset(),B=Math.abs(M),C=Math.floor(B/60),j=B%60;return(M<=0?"+":"-")+A(C,2,"0")+":"+A(j,2,"0")},m:function E(M,B){if(M.date()<B.date())return-E(B,M);var C=12*(B.year()-M.year())+(B.month()-M.month()),j=M.clone().add(C,u),U=B-j<0,$=M.clone().add(C+(U?-1:1),u);return+(-(C+(B-j)/(U?j-$:$-j))||0)},a:function(E){return E<0?Math.ceil(E)||0:Math.floor(E)},p:function(E){return{M:u,y:p,w:m,d:c,D:g,h:d,m:o,s:l,ms:i,Q:x}[E]||String(E||"").toLowerCase().replace(/s$/,"")},u:function(E){return E===void 0}},T="en",k={};k[T]=v;var L="$isDayjsObject",D=function(E){return E instanceof R||!(!E||!E[L])},S=function E(M,B,C){var j;if(!M)return T;if(typeof M=="string"){var U=M.toLowerCase();k[U]&&(j=U),B&&(k[U]=B,j=U);var $=M.split("-");if(!j&&$.length>1)return E($[0])}else{var _=M.name;k[_]=M,j=_}return!C&&j&&(T=j),j||!C&&T},N=function(E,M){if(D(E))return E.clone();var B=typeof M=="object"?M:{};return B.date=E,B.args=arguments,new R(B)},P=w;P.l=S,P.i=D,P.w=function(E,M){return N(E,{locale:M.$L,utc:M.$u,x:M.$x,$offset:M.$offset})};var R=function(){function E(B){this.$L=S(B.locale,null,!0),this.parse(B),this.$x=this.$x||B.x||{},this[L]=!0}var M=E.prototype;return M.parse=function(B){this.$d=function(C){var j=C.date,U=C.utc;if(j===null)return new Date(NaN);if(P.u(j))return new Date;if(j instanceof Date)return new Date(j);if(typeof j=="string"&&!/Z$/i.test(j)){var $=j.match(f);if($){var _=$[2]-1||0,se=($[7]||"0").substring(0,3);return U?new Date(Date.UTC($[1],_,$[3]||1,$[4]||0,$[5]||0,$[6]||0,se)):new Date($[1],_,$[3]||1,$[4]||0,$[5]||0,$[6]||0,se)}}return new Date(j)}(B),this.init()},M.init=function(){var B=this.$d;this.$y=B.getFullYear(),this.$M=B.getMonth(),this.$D=B.getDate(),this.$W=B.getDay(),this.$H=B.getHours(),this.$m=B.getMinutes(),this.$s=B.getSeconds(),this.$ms=B.getMilliseconds()},M.$utils=function(){return P},M.isValid=function(){return this.$d.toString()!==y},M.isSame=function(B,C){var j=N(B);return this.startOf(C)<=j&&j<=this.endOf(C)},M.isAfter=function(B,C){return N(B)<this.startOf(C)},M.isBefore=function(B,C){return this.endOf(C)<N(B)},M.$g=function(B,C,j){return P.u(B)?this[C]:this.set(j,B)},M.unix=function(){return Math.floor(this.valueOf()/1e3)},M.valueOf=function(){return this.$d.getTime()},M.startOf=function(B,C){var j=this,U=!!P.u(C)||C,$=P.p(B),_=function(X,Y){var G=P.w(j.$u?Date.UTC(j.$y,Y,X):new Date(j.$y,Y,X),j);return U?G:G.endOf(c)},se=function(X,Y){return P.w(j.toDate()[X].apply(j.toDate("s"),(U?[0,0,0,0]:[23,59,59,999]).slice(Y)),j)},W=this.$W,ce=this.$M,Z=this.$D,I="set"+(this.$u?"UTC":"");switch($){case p:return U?_(1,0):_(31,11);case u:return U?_(1,ce):_(0,ce+1);case m:var V=this.$locale().weekStart||0,z=(W<V?W+7:W)-V;return _(U?Z-z:Z+(6-z),ce);case c:case g:return se(I+"Hours",0);case d:return se(I+"Minutes",1);case o:return se(I+"Seconds",2);case l:return se(I+"Milliseconds",3);default:return this.clone()}},M.endOf=function(B){return this.startOf(B,!1)},M.$set=function(B,C){var j,U=P.p(B),$="set"+(this.$u?"UTC":""),_=(j={},j[c]=$+"Date",j[g]=$+"Date",j[u]=$+"Month",j[p]=$+"FullYear",j[d]=$+"Hours",j[o]=$+"Minutes",j[l]=$+"Seconds",j[i]=$+"Milliseconds",j)[U],se=U===c?this.$D+(C-this.$W):C;if(U===u||U===p){var W=this.clone().set(g,1);W.$d[_](se),W.init(),this.$d=W.set(g,Math.min(this.$D,W.daysInMonth())).$d}else _&&this.$d[_](se);return this.init(),this},M.set=function(B,C){return this.clone().$set(B,C)},M.get=function(B){return this[P.p(B)]()},M.add=function(B,C){var j,U=this;B=Number(B);var $=P.p(C),_=function(ce){var Z=N(U);return P.w(Z.date(Z.date()+Math.round(ce*B)),U)};if($===u)return this.set(u,this.$M+B);if($===p)return this.set(p,this.$y+B);if($===c)return _(1);if($===m)return _(7);var se=(j={},j[o]=r,j[d]=n,j[l]=a,j)[$]||1,W=this.$d.getTime()+B*se;return P.w(W,this)},M.subtract=function(B,C){return this.add(-1*B,C)},M.format=function(B){var C=this,j=this.$locale();if(!this.isValid())return j.invalidDate||y;var U=B||"YYYY-MM-DDTHH:mm:ssZ",$=P.z(this),_=this.$H,se=this.$m,W=this.$M,ce=j.weekdays,Z=j.months,I=j.meridiem,V=function(Y,G,ie,me){return Y&&(Y[G]||Y(C,U))||ie[G].slice(0,me)},z=function(Y){return P.s(_%12||12,Y,"0")},X=I||function(Y,G,ie){var me=Y<12?"AM":"PM";return ie?me.toLowerCase():me};return U.replace(b,function(Y,G){return G||function(ie){switch(ie){case"YY":return String(C.$y).slice(-2);case"YYYY":return P.s(C.$y,4,"0");case"M":return W+1;case"MM":return P.s(W+1,2,"0");case"MMM":return V(j.monthsShort,W,Z,3);case"MMMM":return V(Z,W);case"D":return C.$D;case"DD":return P.s(C.$D,2,"0");case"d":return String(C.$W);case"dd":return V(j.weekdaysMin,C.$W,ce,2);case"ddd":return V(j.weekdaysShort,C.$W,ce,3);case"dddd":return ce[C.$W];case"H":return String(_);case"HH":return P.s(_,2,"0");case"h":return z(1);case"hh":return z(2);case"a":return X(_,se,!0);case"A":return X(_,se,!1);case"m":return String(se);case"mm":return P.s(se,2,"0");case"s":return String(C.$s);case"ss":return P.s(C.$s,2,"0");case"SSS":return P.s(C.$ms,3,"0");case"Z":return $}return null}(Y)||$.replace(":","")})},M.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},M.diff=function(B,C,j){var U,$=this,_=P.p(C),se=N(B),W=(se.utcOffset()-this.utcOffset())*r,ce=this-se,Z=function(){return P.m($,se)};switch(_){case p:U=Z()/12;break;case u:U=Z();break;case x:U=Z()/3;break;case m:U=(ce-W)/6048e5;break;case c:U=(ce-W)/864e5;break;case d:U=ce/n;break;case o:U=ce/r;break;case l:U=ce/a;break;default:U=ce}return j?U:P.a(U)},M.daysInMonth=function(){return this.endOf(u).$D},M.$locale=function(){return k[this.$L]},M.locale=function(B,C){if(!B)return this.$L;var j=this.clone(),U=S(B,C,!0);return U&&(j.$L=U),j},M.clone=function(){return P.w(this.$d,this)},M.toDate=function(){return new Date(this.valueOf())},M.toJSON=function(){return this.isValid()?this.toISOString():null},M.toISOString=function(){return this.$d.toISOString()},M.toString=function(){return this.$d.toUTCString()},E}(),O=R.prototype;return N.prototype=O,[["$ms",i],["$s",l],["$m",o],["$H",d],["$W",c],["$M",u],["$y",p],["$D",g]].forEach(function(E){O[E[1]]=function(M){return this.$g(M,E[0],E[1])}}),N.extend=function(E,M){return E.$i||(E(M,R,N),E.$i=!0),N},N.locale=S,N.isDayjs=D,N.unix=function(E){return N(1e3*E)},N.en=k[T],N.Ls=k,N.p={},N})})(Xx);var iN=Xx.exports;const Ht=ji(iN);var Qx={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(vi,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(c,m,u,x){return i.fromToBase(c,m,u,x)}n.en.relativeTime=l,i.fromToBase=function(c,m,u,x,p){for(var g,y,f,b=u.$locale().relativeTime||l,v=a.thresholds||[{l:"s",r:44,d:"second"},{l:"m",r:89},{l:"mm",r:44,d:"minute"},{l:"h",r:89},{l:"hh",r:21,d:"hour"},{l:"d",r:35},{l:"dd",r:25,d:"day"},{l:"M",r:45},{l:"MM",r:10,d:"month"},{l:"y",r:17},{l:"yy",d:"year"}],A=v.length,w=0;w<A;w+=1){var T=v[w];T.d&&(g=x?n(c).diff(u,T.d,!0):u.diff(c,T.d,!0));var k=(a.rounding||Math.round)(Math.abs(g));if(f=g>0,k<=T.r||!T.r){k<=1&&w>0&&(T=v[w-1]);var L=b[T.l];p&&(k=p(""+k)),y=typeof L=="string"?L.replace("%d",k):L(k,m,T.l,f);break}}if(m)return y;var D=f?b.future:b.past;return typeof D=="function"?D(y):D.replace("%s",y)},i.to=function(c,m){return o(c,m,this,!0)},i.from=function(c,m){return o(c,m,this)};var d=function(c){return c.$u?n.utc():n()};i.toNow=function(c){return this.to(d(this),c)},i.fromNow=function(c){return this.from(d(this),c)}}})})(Qx);var lN=Qx.exports;const oN=ji(lN);Ht.extend(oN);function cN({request:t,isInitiator:s,needsClosure:a,conclusionRemark:r,setConclusionRemark:n,conclusionLoading:i,conclusionSubmitting:l,aiGenerated:o,handleGenerateConclusion:d,handleFinalizeConclusion:c,onPause:m,onResume:u,onRetrigger:x,currentUserIsApprover:p=!1,pausedByUserId:g,currentUserId:y,generationAttempts:f=0,generationFailed:b=!1,maxAttemptsReached:v=!1}){var N,P,R,O,E,M,B,C;const{user:A}=Jt(),w=t==null?void 0:t.pauseInfo,T=(w==null?void 0:w.isPaused)||!1,k=(N=w==null?void 0:w.pausedBy)==null?void 0:N.userId,L=(A==null?void 0:A.userId)||"",D=T&&u&&(p||s),S=T&&s&&k&&k!==L&&x;return e.jsxs("div",{className:"space-y-4 sm:space-y-6","data-testid":"overview-tab-content",children:[e.jsxs(te,{"data-testid":"initiator-card",children:[e.jsx(ue,{className:"pb-3 sm:pb-4",children:e.jsxs(xe,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(_t,{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(rs,{className:"h-10 w-10 sm:h-12 sm:w-12 ring-2 ring-white shadow-sm flex-shrink-0",children:e.jsx(ns,{className:"bg-gray-700 text-white font-semibold text-sm",children:((P=t.initiator)==null?void 0:P.avatar)||"U"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-gray-900 text-sm sm:text-base truncate",children:((R=t.initiator)==null?void 0:R.name)||"N/A"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 truncate",children:((O=t.initiator)==null?void 0:O.role)||"N/A"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-500 truncate",children:((E=t.initiator)==null?void 0:E.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:((M=t.initiator)==null?void 0:M.email)||"N/A"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs sm:text-sm text-gray-600",children:[e.jsx(Ci,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{children:((B=t.initiator)==null?void 0:B.phone)||"N/A"})]})]})]})]})})]}),e.jsxs(te,{"data-testid":"request-details-card",children:[e.jsx(ue,{className:"pb-3 sm:pb-4",children:e.jsxs(xe,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Pe,{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(ra,{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:is(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:is(t.updatedAt)})]})]})]})]}),T&&w&&e.jsxs(te,{className:"border-orange-300 bg-orange-50/50","data-testid":"pause-status-card",children:[e.jsx(ue,{className:"pb-3 sm:pb-4",children:e.jsxs(xe,{className:"flex items-center gap-2 text-sm sm:text-base text-orange-800",children:[e.jsx(Ha,{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("p",{className:"text-sm text-gray-900 mt-1",children:w.pauseReason})]}),w.pausedBy&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Paused By"}),e.jsx("p",{className:"text-sm text-gray-900 mt-1",children:w.pausedBy.name||w.pausedBy.email})]}),w.pauseResumeDate&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Auto-Resume Date"}),e.jsxs("p",{className:"text-sm text-gray-900 mt-1",children:[is(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:is(w.pausedAt)})]})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-2 border-t border-orange-200",children:[D&&u&&e.jsxs(F,{onClick:u,className:"bg-green-600 hover:bg-green-700 text-white text-xs sm:text-sm h-8 sm:h-9",size:"sm",children:[e.jsx(li,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-1.5"}),"Resume Now"]}),S&&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(Ge,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-1.5"}),"Request Resume"]})]})]})]}),t.claimDetails&&e.jsxs(te,{children:[e.jsx(ue,{className:"pb-4",children:e.jsxs(xe,{className:"flex items-center gap-2 text-base",children:[e.jsx(Pe,{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?Zx(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(ra,{content:t.claimDetails.requestDescription,className:"text-sm"})})]})]})]}),t.status==="closed"&&t.conclusionRemark&&e.jsxs(te,{children:[e.jsxs(ue,{className:"bg-gradient-to-r from-gray-50 to-slate-50 border-b border-gray-200",children:[e.jsxs(xe,{className:"flex items-center gap-2 text-base",children:[e.jsx(De,{className:"w-5 h-5 text-gray-600"}),"Conclusion Remark"]}),e.jsx(ke,{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(ra,{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 ",is(t.closureDate)]}),e.jsxs("span",{children:["By ",((C=t.initiator)==null?void 0:C.name)||"Initiator"]})]})]})]}),a&&e.jsxs(te,{"data-testid":"conclusion-remark-card",children:[e.jsx(ue,{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(xe,{className:`flex items-center gap-2 text-base sm:text-lg ${t.status==="rejected"?"text-red-700":"text-green-700"}`,children:[e.jsx(De,{className:`w-5 h-5 ${t.status==="rejected"?"text-red-600":"text-green-600"}`}),"Conclusion Remark - Final Step"]}),e.jsx(ke,{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:d,disabled:i||v,className:"gap-2 shrink-0 h-9","data-testid":"generate-ai-conclusion-button",children:[e.jsx(Bt,{className:`w-3.5 h-3.5 ${i?"animate-spin":""}`}),o?"Regenerate":"Generate with AI"]}),o&&!v&&!b&&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(Ze,{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($i,{value:r,onChange:j=>n(j),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:c,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(Ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Finalizing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(De,{className:"w-4 h-4 mr-2"}),"Finalize & Close Request"]})})})]})})]})]})}function Qn({delayDuration:t=0,...s}){return e.jsx(sf,{"data-slot":"tooltip-provider",delayDuration:t,...s})}function cl({...t}){return e.jsx(Qn,{children:e.jsx(af,{"data-slot":"tooltip",...t})})}function dl({...t}){return e.jsx(rf,{"data-slot":"tooltip-trigger",...t})}function ml({className:t,sideOffset:s=0,children:a,...r}){return e.jsx(nf,{children:e.jsxs(lf,{"data-slot":"tooltip-content",sideOffset:s,className:Re("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(of,{className:"bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function mt({...t}){return e.jsx(mf,{"data-slot":"dialog",...t})}function dN({...t}){return e.jsx(df,{"data-slot":"dialog-portal",...t})}const Jx=h.forwardRef(({className:t,...s},a)=>e.jsx(Lu,{ref:a,"data-slot":"dialog-overlay",className:Re("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}));Jx.displayName=Lu.displayName;const ot=h.forwardRef(({className:t,children:s,...a},r)=>e.jsxs(dN,{"data-slot":"dialog-portal",children:[e.jsx(Jx,{}),e.jsxs(Ou,{ref:r,"data-slot":"dialog-content",className:Re("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(cf,{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"})]})]})]}));ot.displayName=Ou.displayName;const ut=h.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,"data-slot":"dialog-header",className:Re("flex flex-col gap-2 text-center sm:text-left",t),...s}));ut.displayName="DialogHeader";const Tt=h.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,"data-slot":"dialog-footer",className:Re("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s}));Tt.displayName="DialogFooter";const ct=h.forwardRef(({className:t,...s},a)=>e.jsx($u,{ref:a,"data-slot":"dialog-title",className:Re("text-lg leading-none font-semibold",t),...s}));ct.displayName=$u.displayName;const It=h.forwardRef(({className:t,...s},a)=>e.jsx(Uu,{ref:a,"data-slot":"dialog-description",className:Re("text-muted-foreground text-sm",t),...s}));It.displayName=Uu.displayName;function Es({className:t,...s}){return e.jsx("textarea",{"data-slot":"textarea",className:Re("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 rm=t=>{if(t<8)return Lt(t);const a=Math.floor(t/8),r=t%8;return r>0?`${a}d ${Lt(r)}`:`${a}d`},mN=(t,s)=>{if(s)return e.jsx(Ge,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"});switch(t){case"approved":return e.jsx(De,{className:"w-4 h-4 sm:w-5 sm:w-5 text-green-600"});case"rejected":return e.jsx(jt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-red-600"});case"paused":return e.jsx(ex,{className:"w-4 h-4 sm:w-5 sm:h-5 text-yellow-600"});case"pending":case"in-review":return e.jsx(Xe,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"});case"waiting":return e.jsx(Xe,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400"});default:return e.jsx(Xe,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400"})}};function uN({step:t,index:s,approval:a,isCurrentUser:r=!1,isInitiator:n=!1,isCurrentLevel:i=!1,onSkipApprover:l,onRefresh:o,testId:d="approval-step"}){const{user:c}=Jt(),[m,u]=h.useState(!1),[x,p]=h.useState(""),[g,y]=h.useState(!1),f=(a==null?void 0:a.breachReason)||(t==null?void 0:t.breachReason)||"";h.useEffect(()=>{m||p("")},[m]);const b=t.status==="pending"||t.status==="in-review",v=t.status==="approved",A=t.status==="rejected",w=t.status==="waiting",T=t.status==="paused",k=Number(t.tatHours||0),L=t.actualHours??0,D=v&&L?Math.max(0,k-L):0,S=k>0?L/k*100:0,N=S>=100,P=(c==null?void 0:c.role)==="ADMIN",R=Mi(c),O=t.approverId===(c==null?void 0:c.userId),E=P||R||O,M=async()=>{var B,C;if(!x.trim()){Q.error("Breach Reason Required",{description:"Please enter a reason for the breach."});return}y(!0);try{await aN(t.levelId,x.trim()),u(!1),p(""),Q.success("Breach Reason Updated",{description:"The breach reason has been saved and will appear in the TAT Breach Report.",duration:5e3}),o?await o():setTimeout(()=>{window.location.reload()},1e3)}catch(j){console.error("Error updating breach reason:",j);const U=((C=(B=j==null?void 0:j.response)==null?void 0:B.data)==null?void 0:C.error)||(j==null?void 0:j.message)||"Failed to update breach reason. Please try again.";Q.error("Failed to Update Breach Reason",{description:U,duration:5e3})}finally{y(!1)}};return e.jsxs("div",{className:`relative p-3 sm:p-4 md:p-5 rounded-lg border-2 transition-all ${t.isSkipped?"border-orange-500 bg-orange-50":b?"border-blue-500 bg-blue-50 shadow-md":v?"border-green-500 bg-green-50":A?"border-red-500 bg-red-50":w?"border-gray-300 bg-gray-50":"border-gray-200 bg-white"}`,"data-testid":`${d}-${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":T?"bg-yellow-100":b?"bg-blue-100":v?"bg-green-100":A?"bg-red-100":w?"bg-gray-200":"bg-gray-100"}`,children:mN(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":`${d}-approver-label`,children:["Approver ",s+1]}),e.jsx(ne,{variant:"outline",className:`text-xs shrink-0 capitalize ${t.isSkipped?"bg-orange-100 text-orange-800 border-orange-200":b?"bg-yellow-100 text-yellow-800 border-yellow-200":v?"bg-green-100 text-green-800 border-green-200":A?"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":`${d}-status-badge`,children:t.isSkipped?"skipped":t.status}),t.isSkipped&&t.skipReason&&e.jsx(Qn,{delayDuration:200,children:e.jsxs(cl,{children:[e.jsx(dl,{asChild:!0,children:e.jsx("button",{type:"button",className:"inline-flex items-center justify-center cursor-pointer hover:opacity-80 transition-opacity",onClick:B=>B.stopPropagation(),children:e.jsx(Ge,{className:"w-4 h-4 text-orange-600"})})}),e.jsxs(ml,{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(_d,{className:"w-3 h-3"}),"Skip Reason:"]}),e.jsx("p",{className:"text-xs text-gray-700",children:t.skipReason})]})]})}),v&&L&&e.jsx(ne,{className:"bg-green-600 text-white text-xs","data-testid":`${d}-completion-time`,children:rm(L)})]}),e.jsx("p",{className:"text-sm font-semibold text-gray-900","data-testid":`${d}-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":`${d}-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":`${d}-tat-hours`,children:[k," hours"]})]})]}),v&&L!==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?is(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:rm(L)})]}),e.jsx("div",{className:"space-y-2",children:(()=>{const B=Math.min(100,S),C=()=>N?"bg-red-600":S>=75?"bg-orange-500":S>=50?"bg-amber-500":"bg-green-600",j=()=>N?"text-red-600":S>=75?"text-orange-600":S>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(la,{value:B,className:"h-2 bg-gray-200",indicatorClassName:C(),"data-testid":`${d}-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 ${j()}`,children:[Math.round(B),"% of TAT used"]}),N&&E&&e.jsx(Qn,{children:e.jsxs(cl,{children:[e.jsx(dl,{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:()=>{p(f),u(!0)},children:e.jsx($n,{className:"w-3 h-3"})})}),e.jsx(ml,{children:e.jsx("p",{children:f?"Edit breach reason":"Add breach reason"})})]})})]}),D>0&&e.jsxs("span",{className:"text-green-600 font-semibold",children:["Saved ",Lt(D)]})]})]})})()}),N&&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($n,{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&&(b||T)&&(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?ha(a.sla.deadline,!0):"Not set"})]}),e.jsxs("div",{className:`border rounded-lg p-3 ${T?"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(Xe,{className:"w-4 h-4"}),"Current Approver - Time Tracking ",T&&"(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," / ",Lt(k)," allocated"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[(()=>{const B=a.sla.percentageUsed||0,C=()=>T?"bg-gray-500":B>=100?"bg-red-600":B>=75?"bg-orange-500":B>=50?"bg-amber-500":"bg-green-600",j=()=>T?"text-gray-600":B>=100?"text-red-600":B>=75?"text-orange-600":B>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(la,{value:a.sla.percentageUsed,className:"h-3",indicatorClassName:C(),"data-testid":`${d}-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 ${j()}`,children:["Progress: ",Math.min(100,a.sla.percentageUsed),"% of TAT used"]}),a.sla.status==="breached"&&E&&e.jsx(Qn,{children:e.jsxs(cl,{children:[e.jsx(dl,{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:()=>{p(f),u(!0)},children:e.jsx($n,{className:"w-3 h-3"})})}),e.jsx(ml,{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(oi,{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($n,{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(ex,{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 ",k," hours for approval"]})]})}),A&&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(jt,{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(_d,{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 ",is(t.timestamp)]})]}),t.tatAlerts&&t.tatAlerts.length>0&&e.jsx("div",{className:"mt-2 sm:mt-3 space-y-2",children:t.tatAlerts.map((B,C)=>{var j,U,$,_,se,W;return e.jsx("div",{className:`p-2 sm:p-3 rounded-lg border ${B.isBreached?"bg-red-50 border-red-200":(B.thresholdPercentage||0)===75?"bg-orange-50 border-orange-200":"bg-yellow-50 border-yellow-200"}`,"data-testid":`${d}-tat-alert-${C}`,children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("div",{className:"flex-shrink-0 mt-0.5",children:[(B.thresholdPercentage||0)===50&&e.jsx(a0,{className:"w-5 h-5 text-yellow-600"}),(B.thresholdPercentage||0)===75&&e.jsx(os,{className:"w-5 h-5 text-orange-600"}),(B.thresholdPercentage||0)===100&&e.jsx(oi,{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 ",C+1," - ",B.thresholdPercentage||0,"% TAT"]}),e.jsx(ne,{variant:"outline",className:`text-[10px] sm:text-xs shrink-0 ${B.isBreached?"bg-red-100 text-red-800 border-red-300":"bg-amber-100 text-amber-800 border-amber-300"}`,children:B.isBreached?"BREACHED":"WARNING"})]}),e.jsxs("p",{className:"text-[10px] sm:text-xs md:text-sm text-gray-700 mt-1",children:[B.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:Lt(Number(B.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:[Lt(Number(B.tatHoursElapsed||0)),((j=B.metadata)==null?void 0:j.tatTestMode)&&e.jsxs("span",{className:"text-purple-600 ml-1",children:["(",(Number(B.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 ${(B.tatHoursRemaining||0)<2?"text-red-600":"text-gray-900"}`,children:[Lt(Number(B.tatHoursRemaining||0)),((U=B.metadata)==null?void 0:U.tatTestMode)&&e.jsxs("span",{className:"text-purple-600 ml-1",children:["(",(Number(B.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:B.expectedCompletionTime?ha(B.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"}),((($=B.metadata)==null?void 0:$.testMode)||((_=B.metadata)==null?void 0:_.tatTestMode))&&e.jsx(ne,{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: ",B.alertSentAt?is(B.alertSentAt):"N/A"]}),(((se=B.metadata)==null?void 0:se.testMode)||((W=B.metadata)==null?void 0:W.tatTestMode))&&e.jsx("p",{className:"text-[10px] text-purple-600 mt-1 italic",children:"Note: Test mode active (1 hour = 1 minute)"})]})]})]})},C)})}),t.timestamp&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:[v?"Approved":A?"Rejected":"Actioned"," on ",is(t.timestamp)]}),n&&!T&&(b||t.status==="pending")&&!v&&!A&&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":`${d}-skip-button`,children:[e.jsx(Ge,{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:T?"Skip this approver to resume the workflow and move to next level":"Skip if approver is unavailable and move to next level"})]})]})]}),e.jsx(mt,{open:m,onOpenChange:u,children:e.jsxs(ot,{className:"sm:max-w-[500px]",children:[e.jsxs(ut,{children:[e.jsx(ct,{children:f?"Edit Breach Reason":"Add Breach Reason"}),e.jsx(It,{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(Es,{placeholder:"Enter the reason for the breach...",value:x,onChange:B=>p(B.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(Tt,{children:[e.jsx(F,{variant:"outline",onClick:()=>{u(!1),p("")},disabled:g,children:"Cancel"}),e.jsx(F,{onClick:M,disabled:!x.trim()||g,className:"bg-red-600 hover:bg-red-700",children:g?"Saving...":"Save Reason"})]})]})})]})}function xN({request:t,user:s,isInitiator:a,onSkipApprover:r,onRefresh:n}){return e.jsxs(te,{children:[e.jsx(ue,{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(xe,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Ks,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Approval Workflow"]}),e.jsx(ke,{className:"mt-1 sm:mt-2 text-xs sm:text-sm",children:"Track the approval progress through each step"})]}),t.totalSteps&&(()=>{var p;const i=t.totalSteps||1,l=t.currentStepRaw!==void 0?t.currentStepRaw:t.currentStep||1,o=((p=t.approvalFlow)==null?void 0:p.filter(g=>{const y=(g.status||"").toLowerCase();return y==="approved"||y==="rejected"}).length)||0,d=o>=i,c=(t.status||"").toLowerCase(),m=c==="approved"||c==="rejected"||c==="closed",u=l>i,x=Math.min(Math.max(1,l),i);return u?e.jsxs(ne,{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||d?e.jsxs(ne,{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(ne,{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 p,g,y;const o=(p=t.approvals)==null?void 0:p.find(f=>f.levelId===i.levelId),d=(g=s==null?void 0:s.email)==null?void 0:g.toLowerCase(),c=(y=i.approverEmail)==null?void 0:y.toLowerCase(),m=d&&c&&d===c,u=t.currentStepRaw!==void 0?t.currentStepRaw:t.currentStep||1,x=i.step===u;return e.jsx(uN,{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 Lo=h.createContext({});function Oo(t){const s=h.useRef(null);return s.current===null&&(s.current=t()),s.current}const $o=typeof window<"u",qx=$o?h.useLayoutEffect:h.useEffect,Ui=h.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 th(t){return typeof t=="object"&&t!==null}const sh=t=>/^0[^.\s]+$/u.test(t);function zo(t){let s;return()=>(s===void 0&&(s=t()),s)}const na=t=>t,hN=(t,s)=>a=>s(t(a)),In=(...t)=>t.reduce(hN),vn=(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 va=t=>t*1e3,aa=t=>t/1e3;function ah(t,s){return s?t*(1e3/s):0}const rh=(t,s,a)=>(((1-3*a+3*s)*t+(3*a-6*s))*t+3*s)*t,pN=1e-7,gN=12;function fN(t,s,a,r,n){let i,l,o=0;do l=s+(a-s)/2,i=rh(l,r,n)-t,i>0?a=l:s=l;while(Math.abs(i)>pN&&++o<gN);return l}function En(t,s,a,r){if(t===s&&a===r)return na;const n=i=>fN(i,0,1,t,a);return i=>i===0||i===1?i:rh(n(i),s,r)}const nh=t=>s=>s<=.5?t(2*s)/2:(2-t(2*(1-s)))/2,ih=t=>s=>1-t(1-s),lh=En(.33,1.53,.69,.99),Wo=ih(lh),oh=nh(Wo),ch=t=>(t*=2)<1?.5*Wo(t):.5*(2-Math.pow(2,-10*(t-1))),Go=t=>1-Math.sin(Math.acos(t)),dh=ih(Go),mh=nh(Go),yN=En(.42,0,1,1),bN=En(0,0,.58,1),uh=En(.42,0,.58,1),vN=t=>Array.isArray(t)&&typeof t[0]!="number",xh=t=>Array.isArray(t)&&typeof t[0]=="number",jN={linear:na,easeIn:yN,easeInOut:uh,easeOut:bN,circIn:Go,circInOut:mh,circOut:dh,backIn:Wo,backInOut:oh,backOut:lh,anticipate:ch},NN=t=>typeof t=="string",nm=t=>{if(xh(t)){Vo(t.length===4);const[s,a,r,n]=t;return En(s,a,r,n)}else if(NN(t))return jN[t];return t},Bn=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function wN(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 d(m){l.has(m)&&(c.schedule(m),t()),m(o)}const c={schedule:(m,u=!1,x=!1)=>{const g=x&&n?a:r;return u&&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(d),a.clear(),n=!1,i&&(i=!1,c.process(m))}};return c}const CN=40;function hh(t,s){let a=!1,r=!0;const n={delta:0,timestamp:0,isProcessing:!1},i=()=>a=!0,l=Bn.reduce((A,w)=>(A[w]=wN(i),A),{}),{setup:o,read:d,resolveKeyframes:c,preUpdate:m,update:u,preRender:x,render:p,postRender:g}=l,y=()=>{const A=Ea.useManualTiming?n.timestamp:performance.now();a=!1,Ea.useManualTiming||(n.delta=r?1e3/60:Math.max(Math.min(A-n.timestamp,CN),1)),n.timestamp=A,n.isProcessing=!0,o.process(n),d.process(n),c.process(n),m.process(n),u.process(n),x.process(n),p.process(n),g.process(n),n.isProcessing=!1,a&&s&&(r=!1,t(y))},f=()=>{a=!0,r=!0,n.isProcessing||t(y)};return{schedule:Bn.reduce((A,w)=>{const T=l[w];return A[w]=(k,L=!1,D=!1)=>(a||f(),T.schedule(k,L,D)),A},{}),cancel:A=>{for(let w=0;w<Bn.length;w++)l[Bn[w]].cancel(A)},state:n,steps:l}}const{schedule:Ut,cancel:Ga,state:ys,steps:ul}=hh(typeof requestAnimationFrame<"u"?requestAnimationFrame:na,!0);let Jn;function AN(){Jn=void 0}const Us={now:()=>(Jn===void 0&&Us.set(ys.isProcessing||Ea.useManualTiming?ys.timestamp:performance.now()),Jn),set:t=>{Jn=t,queueMicrotask(AN)}},ph=t=>s=>typeof s=="string"&&s.startsWith(t),Ko=ph("--"),SN=ph("var(--"),Yo=t=>SN(t)?TN.test(t.split("/*")[0].trim()):!1,TN=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,Kr={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},jn={...Kr,transform:t=>Ia(0,1,t)},Vn={...Kr,default:1},un=t=>Math.round(t*1e5)/1e5,Zo=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function kN(t){return t==null}const RN=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Xo=(t,s)=>a=>!!(typeof a=="string"&&RN.test(a)&&a.startsWith(t)||s&&!kN(a)&&Object.prototype.hasOwnProperty.call(a,s)),gh=(t,s,a)=>r=>{if(typeof r!="string")return r;const[n,i,l,o]=r.match(Zo);return{[t]:parseFloat(n),[s]:parseFloat(i),[a]:parseFloat(l),alpha:o!==void 0?parseFloat(o):1}},DN=t=>Ia(0,255,t),xl={...Kr,transform:t=>Math.round(DN(t))},pr={test:Xo("rgb","red"),parse:gh("red","green","blue"),transform:({red:t,green:s,blue:a,alpha:r=1})=>"rgba("+xl.transform(t)+", "+xl.transform(s)+", "+xl.transform(a)+", "+un(jn.transform(r))+")"};function PN(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 zl={test:Xo("#"),parse:PN,transform:pr.transform},Fn=t=>({test:s=>typeof s=="string"&&s.endsWith(t)&&s.split(" ").length===1,parse:parseFloat,transform:s=>`${s}${t}`}),Ba=Fn("deg"),ja=Fn("%"),qe=Fn("px"),IN=Fn("vh"),EN=Fn("vw"),im={...ja,parse:t=>ja.parse(t)/100,transform:t=>ja.transform(t*100)},Tr={test:Xo("hsl","hue"),parse:gh("hue","saturation","lightness"),transform:({hue:t,saturation:s,lightness:a,alpha:r=1})=>"hsla("+Math.round(t)+", "+ja.transform(un(s))+", "+ja.transform(un(a))+", "+un(jn.transform(r))+")"},ts={test:t=>pr.test(t)||zl.test(t)||Tr.test(t),parse:t=>pr.test(t)?pr.parse(t):Tr.test(t)?Tr.parse(t):zl.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?pr.transform(t):Tr.transform(t),getAnimatableNone:t=>{const s=ts.parse(t);return s.alpha=0,ts.transform(s)}},FN=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function MN(t){var s,a;return isNaN(t)&&typeof t=="string"&&(((s=t.match(Zo))==null?void 0:s.length)||0)+(((a=t.match(FN))==null?void 0:a.length)||0)>0}const fh="number",yh="color",_N="var",LN="var(",lm="${}",ON=/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 Nn(t){const s=t.toString(),a=[],r={color:[],number:[],var:[]},n=[];let i=0;const o=s.replace(ON,d=>(ts.test(d)?(r.color.push(i),n.push(yh),a.push(ts.parse(d))):d.startsWith(LN)?(r.var.push(i),n.push(_N),a.push(d)):(r.number.push(i),n.push(fh),a.push(parseFloat(d))),++i,lm)).split(lm);return{values:a,split:o,indexes:r,types:n}}function bh(t){return Nn(t).values}function vh(t){const{split:s,types:a}=Nn(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===fh?i+=un(n[l]):o===yh?i+=ts.transform(n[l]):i+=n[l]}return i}}const $N=t=>typeof t=="number"?0:ts.test(t)?ts.getAnimatableNone(t):t;function UN(t){const s=bh(t);return vh(t)(s.map($N))}const Ka={test:MN,parse:bh,createTransformer:vh,getAnimatableNone:UN};function hl(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 BN({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,d=2*a-o;n=hl(d,o,t+1/3),i=hl(d,o,t),l=hl(d,o,t-1/3)}return{red:Math.round(n*255),green:Math.round(i*255),blue:Math.round(l*255),alpha:r}}function xi(t,s){return a=>a>0?s:t}const Wt=(t,s,a)=>t+(s-t)*a,pl=(t,s,a)=>{const r=t*t,n=a*(s*s-r)+r;return n<0?0:Math.sqrt(n)},VN=[zl,pr,Tr],zN=t=>VN.find(s=>s.test(t));function om(t){const s=zN(t);if(!s)return!1;let a=s.parse(t);return s===Tr&&(a=BN(a)),a}const cm=(t,s)=>{const a=om(t),r=om(s);if(!a||!r)return xi(t,s);const n={...a};return i=>(n.red=pl(a.red,r.red,i),n.green=pl(a.green,r.green,i),n.blue=pl(a.blue,r.blue,i),n.alpha=Wt(a.alpha,r.alpha,i),pr.transform(n))},Hl=new Set(["none","hidden"]);function HN(t,s){return Hl.has(t)?a=>a<=0?t:s:a=>a>=1?s:t}function WN(t,s){return a=>Wt(t,s,a)}function Qo(t){return typeof t=="number"?WN:typeof t=="string"?Yo(t)?xi:ts.test(t)?cm:YN:Array.isArray(t)?jh:typeof t=="object"?ts.test(t)?cm:GN:xi}function jh(t,s){const a=[...t],r=a.length,n=t.map((i,l)=>Qo(i)(i,s[l]));return i=>{for(let l=0;l<r;l++)a[l]=n[l](i);return a}}function GN(t,s){const a={...t,...s},r={};for(const n in a)t[n]!==void 0&&s[n]!==void 0&&(r[n]=Qo(t[n])(t[n],s[n]));return n=>{for(const i in r)a[i]=r[i](n);return a}}function KN(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 YN=(t,s)=>{const a=Ka.createTransformer(s),r=Nn(t),n=Nn(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?Hl.has(t)&&!n.values.length||Hl.has(s)&&!r.values.length?HN(t,s):In(jh(KN(r,n),n.values),a):xi(t,s)};function Nh(t,s,a){return typeof t=="number"&&typeof s=="number"&&typeof a=="number"?Wt(t,s,a):Qo(t)(t,s)}const ZN=t=>{const s=({timestamp:a})=>t(a);return{start:(a=!0)=>Ut.update(s,a),stop:()=>Ga(s),now:()=>ys.isProcessing?ys.timestamp:Us.now()}},wh=(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)})`},hi=2e4;function Jo(t){let s=0;const a=50;let r=t.next(s);for(;!r.done&&s<hi;)s+=a,r=t.next(s);return s>=hi?1/0:s}function XN(t,s=100,a){const r=a({...t,keyframes:[0,s]}),n=Math.min(Jo(r),hi);return{type:"keyframes",ease:i=>r.next(n*i).value/s,duration:aa(n)}}const QN=5;function Ch(t,s,a){const r=Math.max(s-QN,0);return ah(a-t(r),s-r)}const Zt={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},gl=.001;function JN({duration:t=Zt.duration,bounce:s=Zt.bounce,velocity:a=Zt.velocity,mass:r=Zt.mass}){let n,i,l=1-s;l=Ia(Zt.minDamping,Zt.maxDamping,l),t=Ia(Zt.minDuration,Zt.maxDuration,aa(t)),l<1?(n=c=>{const m=c*l,u=m*t,x=m-a,p=Wl(c,l),g=Math.exp(-u);return gl-x/p*g},i=c=>{const u=c*l*t,x=u*a+a,p=Math.pow(l,2)*Math.pow(c,2)*t,g=Math.exp(-u),y=Wl(Math.pow(c,2),l);return(-n(c)+gl>0?-1:1)*((x-p)*g)/y}):(n=c=>{const m=Math.exp(-c*t),u=(c-a)*t+1;return-gl+m*u},i=c=>{const m=Math.exp(-c*t),u=(a-c)*(t*t);return m*u});const o=5/t,d=ew(n,i,o);if(t=va(t),isNaN(d))return{stiffness:Zt.stiffness,damping:Zt.damping,duration:t};{const c=Math.pow(d,2)*r;return{stiffness:c,damping:l*2*Math.sqrt(r*c),duration:t}}}const qN=12;function ew(t,s,a){let r=a;for(let n=1;n<qN;n++)r=r-t(r)/s(r);return r}function Wl(t,s){return t*Math.sqrt(1-s*s)}const tw=["duration","bounce"],sw=["stiffness","damping","mass"];function dm(t,s){return s.some(a=>t[a]!==void 0)}function aw(t){let s={velocity:Zt.velocity,stiffness:Zt.stiffness,damping:Zt.damping,mass:Zt.mass,isResolvedFromDuration:!1,...t};if(!dm(t,sw)&&dm(t,tw))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:Zt.mass,stiffness:n,damping:i}}else{const a=JN(t);s={...s,...a,mass:Zt.mass},s.isResolvedFromDuration=!0}return s}function pi(t=Zt.visualDuration,s=Zt.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:d,damping:c,mass:m,duration:u,velocity:x,isResolvedFromDuration:p}=aw({...a,velocity:-aa(a.velocity||0)}),g=x||0,y=c/(2*Math.sqrt(d*m)),f=l-i,b=aa(Math.sqrt(d/m)),v=Math.abs(f)<5;r||(r=v?Zt.restSpeed.granular:Zt.restSpeed.default),n||(n=v?Zt.restDelta.granular:Zt.restDelta.default);let A;if(y<1){const T=Wl(b,y);A=k=>{const L=Math.exp(-y*b*k);return l-L*((g+y*b*f)/T*Math.sin(T*k)+f*Math.cos(T*k))}}else if(y===1)A=T=>l-Math.exp(-b*T)*(f+(g+b*f)*T);else{const T=b*Math.sqrt(y*y-1);A=k=>{const L=Math.exp(-y*b*k),D=Math.min(T*k,300);return l-L*((g+y*b*f)*Math.sinh(D)+T*f*Math.cosh(D))/T}}const w={calculatedDuration:p&&u||null,next:T=>{const k=A(T);if(p)o.done=T>=u;else{let L=T===0?g:0;y<1&&(L=T===0?va(g):Ch(A,T,k));const D=Math.abs(L)<=r,S=Math.abs(l-k)<=n;o.done=D&&S}return o.value=o.done?l:k,o},toString:()=>{const T=Math.min(Jo(w),hi),k=wh(L=>w.next(T*L).value,T,30);return T+"ms "+k},toTransition:()=>{}};return w}pi.applyToOptions=t=>{const s=XN(t,100,pi);return t.ease=s.ease,t.duration=va(s.duration),t.type="keyframes",t};function Gl({keyframes:t,velocity:s=0,power:a=.8,timeConstant:r=325,bounceDamping:n=10,bounceStiffness:i=500,modifyTarget:l,min:o,max:d,restDelta:c=.5,restSpeed:m}){const u=t[0],x={done:!1,value:u},p=D=>o!==void 0&&D<o||d!==void 0&&D>d,g=D=>o===void 0?d:d===void 0||Math.abs(o-D)<Math.abs(d-D)?o:d;let y=a*s;const f=u+y,b=l===void 0?f:l(f);b!==f&&(y=b-u);const v=D=>-y*Math.exp(-D/r),A=D=>b+v(D),w=D=>{const S=v(D),N=A(D);x.done=Math.abs(S)<=c,x.value=x.done?b:N};let T,k;const L=D=>{p(x.value)&&(T=D,k=pi({keyframes:[x.value,g(x.value)],velocity:Ch(A,D,x.value),damping:n,stiffness:i,restDelta:c,restSpeed:m}))};return L(0),{calculatedDuration:null,next:D=>{let S=!1;return!k&&T===void 0&&(S=!0,w(D),L(D)),T!==void 0&&D>=T?k.next(D-T):(!S&&w(D),x)}}}function rw(t,s,a){const r=[],n=a||Ea.mix||Nh,i=t.length-1;for(let l=0;l<i;l++){let o=n(t[l],t[l+1]);if(s){const d=Array.isArray(s)?s[l]||na:s;o=In(d,o)}r.push(o)}return r}function nw(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=rw(s,r,n),d=o.length,c=m=>{if(l&&m<t[0])return s[0];let u=0;if(d>1)for(;u<t.length-2&&!(m<t[u+1]);u++);const x=vn(t[u],t[u+1],m);return o[u](x)};return a?m=>c(Ia(t[0],t[i-1],m)):c}function iw(t,s){const a=t[t.length-1];for(let r=1;r<=s;r++){const n=vn(0,s,r);t.push(Wt(a,1,n))}}function lw(t){const s=[0];return iw(s,t.length-1),s}function ow(t,s){return t.map(a=>a*s)}function cw(t,s){return t.map(()=>s||uh).splice(0,t.length-1)}function xn({duration:t=300,keyframes:s,times:a,ease:r="easeInOut"}){const n=vN(r)?r.map(nm):nm(r),i={done:!1,value:s[0]},l=ow(a&&a.length===s.length?a:lw(s),t),o=nw(l,s,{ease:Array.isArray(n)?n:cw(s,n)});return{calculatedDuration:t,next:d=>(i.value=o(d),i.done=d>=t,i)}}const dw=t=>t!==null;function qo(t,{repeat:s,repeatType:a="loop"},r,n=1){const i=t.filter(dw),o=n<0||s&&a!=="loop"&&s%2===1?0:i.length-1;return!o||r===void 0?i[o]:r}const mw={decay:Gl,inertia:Gl,tween:xn,keyframes:xn,spring:pi};function Ah(t){typeof t.type=="string"&&(t.type=mw[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 uw=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!==Us.now()&&this.tick(Us.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),(n=(r=this.options).onStop)==null||n.call(r))},this.options=s,this.initAnimation(),this.play(),s.autoplay===!1&&this.pause()}initAnimation(){const{options:s}=this;Ah(s);const{type:a=xn,repeat:r=0,repeatDelay:n=0,repeatType:i,velocity:l=0}=s;let{keyframes:o}=s;const d=a||xn;d!==xn&&typeof o[0]!="number"&&(this.mixKeyframes=In(uw,Nh(o[0],o[1])),o=[0,100]);const c=d({...s,keyframes:o});i==="mirror"&&(this.mirroredGenerator=d({...s,keyframes:[...o].reverse(),velocity:-l})),c.calculatedDuration===null&&(c.calculatedDuration=Jo(c));const{calculatedDuration:m}=c;this.calculatedDuration=m,this.resolvedDuration=m+n,this.totalDuration=this.resolvedDuration*(r+1)-n,this.generator=c}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:d}=this;if(this.startTime===null)return r.next(0);const{delay:c=0,keyframes:m,repeat:u,repeatType:x,repeatDelay:p,type:g,onUpdate:y,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 b=this.currentTime-c*(this.playbackSpeed>=0?1:-1),v=this.playbackSpeed>=0?b<0:b>n;this.currentTime=Math.max(b,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=n);let A=this.currentTime,w=r;if(u){const D=Math.min(this.currentTime,n)/o;let S=Math.floor(D),N=D%1;!N&&D>=1&&(N=1),N===1&&S--,S=Math.min(S,u+1),!!(S%2)&&(x==="reverse"?(N=1-N,p&&(N-=p/o)):x==="mirror"&&(w=l)),A=Ia(0,1,N)*o}const T=v?{done:!1,value:m[0]}:w.next(A);i&&(T.value=i(T.value));let{done:k}=T;!v&&d!==null&&(k=this.playbackSpeed>=0?this.currentTime>=n:this.currentTime<=0);const L=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&k);return L&&g!==Gl&&(T.value=qo(m,this.options,f,this.speed)),y&&y(T.value),L&&this.finish(),T}then(s,a){return this.finished.then(s,a)}get duration(){return aa(this.calculatedDuration)}get iterationDuration(){const{delay:s=0}=this.options||{};return this.duration+aa(s)}get time(){return aa(this.currentTime)}set time(s){var a;s=va(s),this.currentTime=s,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=s:this.driver&&(this.startTime=this.driver.now()-s/this.playbackSpeed),(a=this.driver)==null||a.start(!1)}get speed(){return this.playbackSpeed}set speed(s){this.updateTime(Us.now());const a=this.playbackSpeed!==s;this.playbackSpeed=s,a&&(this.time=aa(this.currentTime))}play(){var n,i;if(this.isStopped)return;const{driver:s=ZN,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(Us.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){var s,a;this.notifyFinished(),this.teardown(),this.state="finished",(a=(s=this.options).onComplete)==null||a.call(s)}cancel(){var s,a;this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),(a=(s=this.options).onCancel)==null||a.call(s)}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(s){return this.startTime=0,this.tick(s,!0)}attachTimeline(s){var a;return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),(a=this.driver)==null||a.stop(),s.observe(this)}}function xw(t){for(let s=1;s<t.length;s++)t[s]??(t[s]=t[s-1])}const gr=t=>t*180/Math.PI,Kl=t=>{const s=gr(Math.atan2(t[1],t[0]));return Yl(s)},hw={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:Kl,rotateZ:Kl,skewX:t=>gr(Math.atan(t[1])),skewY:t=>gr(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},Yl=t=>(t=t%360,t<0&&(t+=360),t),mm=Kl,um=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),xm=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),pw={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:um,scaleY:xm,scale:t=>(um(t)+xm(t))/2,rotateX:t=>Yl(gr(Math.atan2(t[6],t[5]))),rotateY:t=>Yl(gr(Math.atan2(-t[2],t[0]))),rotateZ:mm,rotate:mm,skewX:t=>gr(Math.atan(t[4])),skewY:t=>gr(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function Zl(t){return t.includes("scale")?1:0}function Xl(t,s){if(!t||t==="none")return Zl(s);const a=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,n;if(a)r=pw,n=a;else{const o=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=hw,n=o}if(!n)return Zl(s);const i=r[s],l=n[1].split(",").map(fw);return typeof i=="function"?i(l):l[i]}const gw=(t,s)=>{const{transform:a="none"}=getComputedStyle(t);return Xl(a,s)};function fw(t){return parseFloat(t.trim())}const Yr=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Zr=new Set(Yr),hm=t=>t===Kr||t===qe,yw=new Set(["x","y","z"]),bw=Yr.filter(t=>!yw.has(t));function vw(t){const s=[];return bw.forEach(a=>{const r=t.getValue(a);r!==void 0&&(s.push([a,r.get()]),r.set(a.startsWith("scale")?1:0))}),s}const fr={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})=>Xl(s,"x"),y:(t,{transform:s})=>Xl(s,"y")};fr.translateX=fr.x;fr.translateY=fr.y;const yr=new Set;let Ql=!1,Jl=!1,ql=!1;function Sh(){if(Jl){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=vw(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)})}Jl=!1,Ql=!1,yr.forEach(t=>t.complete(ql)),yr.clear()}function Th(){yr.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(Jl=!0)})}function jw(){ql=!0,Th(),Sh(),ql=!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),Ql||(Ql=!0,Ut.read(Th),Ut.resolveKeyframes(Sh))):(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])}xw(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 Nw=t=>t.startsWith("--");function ww(t,s,a){Nw(s)?t.style.setProperty(s,a):t.style[s]=a}const Cw=zo(()=>window.ScrollTimeline!==void 0),Aw={};function Sw(t,s){const a=zo(t);return()=>Aw[s]??a()}const kh=Sw(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),dn=([t,s,a,r])=>`cubic-bezier(${t}, ${s}, ${a}, ${r})`,pm={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:dn([0,.65,.55,1]),circOut:dn([.55,0,1,.45]),backIn:dn([.31,.01,.66,-.59]),backOut:dn([.33,1.53,.69,.99])};function Rh(t,s){if(t)return typeof t=="function"?kh()?wh(t,s):"ease-out":xh(t)?dn(t):Array.isArray(t)?t.map(a=>Rh(a,s)||pm.easeOut):pm[t]}function Tw(t,s,a,{delay:r=0,duration:n=300,repeat:i=0,repeatType:l="loop",ease:o="easeOut",times:d}={},c=void 0){const m={[s]:a};d&&(m.offset=d);const u=Rh(o,n);Array.isArray(u)&&(m.easing=u);const x={delay:r,duration:n,easing:Array.isArray(u)?"linear":u,fill:"both",iterations:i+1,direction:l==="reverse"?"alternate":"normal"};return c&&(x.pseudoElement=c),t.animate(m,x)}function Dh(t){return typeof t=="function"&&"applyToOptions"in t}function kw({type:t,...s}){return Dh(t)&&kh()?t.applyToOptions(s):(s.duration??(s.duration=300),s.ease??(s.ease="easeOut"),s)}class Rw 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:d}=s;this.isPseudoElement=!!i,this.allowFlatten=l,this.options=s,Vo(typeof s.type!="string");const c=kw(s);this.animation=Tw(a,r,n,c,i),c.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):ww(a,r,m),this.animation.cancel()}d==null||d(),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 aa(Number(s))}get iterationDuration(){const{delay:s=0}=this.options||{};return this.duration+aa(s)}get time(){return aa(Number(this.animation.currentTime)||0)}set time(s){this.finishedTime=null,this.animation.currentTime=va(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&&Cw()?(this.animation.timeline=s,na):a(this)}}const Ph={anticipate:ch,backInOut:oh,circInOut:mh};function Dw(t){return t in Ph}function Pw(t){typeof t.ease=="string"&&Dw(t.ease)&&(t.ease=Ph[t.ease])}const gm=10;class Iw extends Rw{constructor(s){Pw(s),Ah(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}),d=va(this.finishedTime??this.time);a.setWithVelocity(o.sample(d-gm).value,o.sample(d).value,gm),o.stop()}}const fm=(t,s)=>s==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(Ka.test(t)||t==="0")&&!t.startsWith("url("));function Ew(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 Fw(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=fm(n,s),o=fm(i,s);return!l||!o?!1:Ew(t)||(a==="spring"||Dh(a))&&r}function eo(t){t.duration=0,t.type="keyframes"}const Mw=new Set(["opacity","clipPath","filter","transform"]),_w=zo(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function Lw(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:d,transformTemplate:c}=s.owner.getProps();return _w()&&a&&Mw.has(a)&&(a!=="transform"||!c)&&!d&&!r&&n!=="mirror"&&i!==0&&l!=="inertia"}const Ow=40;class $w extends ec{constructor({autoplay:s=!0,delay:a=0,type:r="keyframes",repeat:n=0,repeatDelay:i=0,repeatType:l="loop",keyframes:o,name:d,motionValue:c,element:m,...u}){var g;super(),this.stop=()=>{var y,f;this._animation&&(this._animation.stop(),(y=this.stopTimeline)==null||y.call(this)),(f=this.keyframeResolver)==null||f.cancel()},this.createdAt=Us.now();const x={autoplay:s,delay:a,type:r,repeat:n,repeatDelay:i,repeatType:l,name:d,motionValue:c,element:m,...u},p=(m==null?void 0:m.KeyframeResolver)||sc;this.keyframeResolver=new p(o,(y,f,b)=>this.onKeyframesResolved(y,f,x,!b),d,c,m),(g=this.keyframeResolver)==null||g.scheduleResolve()}onKeyframesResolved(s,a,r,n){this.keyframeResolver=void 0;const{name:i,type:l,velocity:o,delay:d,isHandoff:c,onUpdate:m}=r;this.resolvedAt=Us.now(),Fw(s,i,l,o)||((Ea.instantAnimations||!d)&&(m==null||m(qo(s,r,a))),s[0]=s[s.length-1],eo(r),r.repeat=0);const x={startTime:n?this.resolvedAt?this.resolvedAt-this.createdAt>Ow?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:a,...r,keyframes:s},p=!c&&Lw(x)?new Iw({...x,element:x.motionValue.owner.current}):new tc(x);p.finished.then(()=>this.notifyFinished()).catch(na),this.pendingTimeline&&(this.stopTimeline=p.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=p}get finished(){return this._animation?this.animation.finished:this._finished}then(s,a){return this.finished.finally(s).then(()=>{})}get animation(){var s;return this._animation||((s=this.keyframeResolver)==null||s.resume(),jw()),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 Uw=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function Bw(t){const s=Uw.exec(t);if(!s)return[,];const[,a,r,n]=s;return[`--${a??r}`,n]}function Ih(t,s,a=1){const[r,n]=Bw(t);if(!r)return;const i=window.getComputedStyle(s).getPropertyValue(r);if(i){const l=i.trim();return eh(l)?parseFloat(l):l}return Yo(n)?Ih(n,s,a+1):n}function ac(t,s){return(t==null?void 0:t[s])??(t==null?void 0:t.default)??t}const Eh=new Set(["width","height","top","left","right","bottom",...Yr]),Vw={test:t=>t==="auto",parse:t=>t},Fh=t=>s=>s.test(t),Mh=[Kr,qe,ja,Ba,EN,IN,Vw],ym=t=>Mh.find(Fh(t));function zw(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||sh(t):!0}const Hw=new Set(["brightness","contrast","saturate","opacity"]);function Ww(t){const[s,a]=t.slice(0,-1).split("(");if(s==="drop-shadow")return t;const[r]=a.match(Zo)||[];if(!r)return t;const n=a.replace(r,"");let i=Hw.has(s)?1:0;return r!==a&&(i*=100),s+"("+i+n+")"}const Gw=/\b([a-z-]*)\(.*?\)/gu,to={...Ka,getAnimatableNone:t=>{const s=t.match(Gw);return s?s.map(Ww).join(" "):t}},bm={...Kr,transform:Math.round},Kw={rotate:Ba,rotateX:Ba,rotateY:Ba,rotateZ:Ba,scale:Vn,scaleX:Vn,scaleY:Vn,scaleZ:Vn,skew:Ba,skewX:Ba,skewY:Ba,distance:qe,translateX:qe,translateY:qe,translateZ:qe,x:qe,y:qe,z:qe,perspective:qe,transformPerspective:qe,opacity:jn,originX:im,originY:im,originZ:qe},rc={borderWidth:qe,borderTopWidth:qe,borderRightWidth:qe,borderBottomWidth:qe,borderLeftWidth:qe,borderRadius:qe,radius:qe,borderTopLeftRadius:qe,borderTopRightRadius:qe,borderBottomRightRadius:qe,borderBottomLeftRadius:qe,width:qe,maxWidth:qe,height:qe,maxHeight:qe,top:qe,right:qe,bottom:qe,left:qe,padding:qe,paddingTop:qe,paddingRight:qe,paddingBottom:qe,paddingLeft:qe,margin:qe,marginTop:qe,marginRight:qe,marginBottom:qe,marginLeft:qe,backgroundPositionX:qe,backgroundPositionY:qe,...Kw,zIndex:bm,fillOpacity:jn,strokeOpacity:jn,numOctaves:bm},Yw={...rc,color:ts,backgroundColor:ts,outlineColor:ts,fill:ts,stroke:ts,borderColor:ts,borderTopColor:ts,borderRightColor:ts,borderBottomColor:ts,borderLeftColor:ts,filter:to,WebkitFilter:to},_h=t=>Yw[t];function Lh(t,s){let a=_h(t);return a!==to&&(a=Ka),a.getAnimatableNone?a.getAnimatableNone(s):void 0}const Zw=new Set(["auto","none","0"]);function Xw(t,s,a){let r=0,n;for(;r<t.length&&!n;){const i=t[r];typeof i=="string"&&!Zw.has(i)&&Nn(i).values.length&&(n=t[r]),r++}if(n&&a)for(const i of s)t[i]=Lh(a,n)}class Qw 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 d=0;d<s.length;d++){let c=s[d];if(typeof c=="string"&&(c=c.trim(),Yo(c))){const m=Ih(c,a.current);m!==void 0&&(s[d]=m),d===s.length-1&&(this.finalKeyframe=c)}}if(this.resolveNoneKeyframes(),!Eh.has(r)||s.length!==2)return;const[n,i]=s,l=ym(n),o=ym(i);if(l!==o)if(hm(l)&&hm(o))for(let d=0;d<s.length;d++){const c=s[d];typeof c=="string"&&(s[d]=parseFloat(c))}else fr[r]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:s,name:a}=this,r=[];for(let n=0;n<s.length;n++)(s[n]===null||zw(s[n]))&&r.push(n);r.length&&Xw(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=fr[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]=fr[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(([d,c])=>{s.getValue(d).set(c)}),this.resolveNoneKeyframes()}}function Jw(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 Oh=(t,s)=>s&&typeof t=="number"?s.transform(t):t;function $h(t){return th(t)&&"offsetHeight"in t}const vm=30,qw=t=>!isNaN(parseFloat(t));class e1{constructor(s,a={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=r=>{var i;const n=Us.now();if(this.updatedAt!==n&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(r),this.current!==this.prev&&((i=this.events.change)==null||i.notify(this.current),this.dependents))for(const l of this.dependents)l.dirty()},this.hasAnimated=!1,this.setCurrent(s),this.owner=a.owner}setCurrent(s){this.current=s,this.updatedAt=Us.now(),this.canTrackVelocity===null&&s!==void 0&&(this.canTrackVelocity=qw(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(),Ut.read(()=>{this.events.change.getSize()||this.stop()})}:r}clearListeners(){for(const s in this.events)this.events[s].clear()}attach(s,a){this.passiveEffect=s,this.stopPassiveEffect=a}set(s){this.passiveEffect?this.passiveEffect(s,this.updateAndNotify):this.updateAndNotify(s)}setWithVelocity(s,a,r){this.set(a),this.prev=void 0,this.prevFrameValue=s,this.prevUpdatedAt=this.updatedAt-r}jump(s,a=!0){this.updateAndNotify(s),this.prev=s,this.prevUpdatedAt=this.prevFrameValue=void 0,a&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){var s;(s=this.events.change)==null||s.notify(this.current)}addDependent(s){this.dependents||(this.dependents=new Set),this.dependents.add(s)}removeDependent(s){this.dependents&&this.dependents.delete(s)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const s=Us.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||s-this.updatedAt>vm)return 0;const a=Math.min(this.updatedAt-this.prevUpdatedAt,vm);return ah(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 Or(t,s){return new e1(t,s)}const{schedule:nc}=hh(queueMicrotask,!1),ua={x:!1,y:!1};function Uh(){return ua.x||ua.y}function t1(t){return t==="x"||t==="y"?ua[t]?null:(ua[t]=!0,()=>{ua[t]=!1}):ua.x||ua.y?null:(ua.x=ua.y=!0,()=>{ua.x=ua.y=!1})}function Bh(t,s){const a=Jw(t),r=new AbortController,n={passive:!0,...s,signal:r.signal};return[a,n,()=>r.abort()]}function jm(t){return!(t.pointerType==="touch"||Uh())}function s1(t,s,a={}){const[r,n,i]=Bh(t,a),l=o=>{if(!jm(o))return;const{target:d}=o,c=s(d,o);if(typeof c!="function"||!d)return;const m=u=>{jm(u)&&(c(u),d.removeEventListener("pointerleave",m))};d.addEventListener("pointerleave",m,n)};return r.forEach(o=>{o.addEventListener("pointerenter",l,n)}),i}const Vh=(t,s)=>s?t===s?!0:Vh(t,s.parentElement):!1,ic=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,a1=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function r1(t){return a1.has(t.tagName)||t.tabIndex!==-1}const qn=new WeakSet;function Nm(t){return s=>{s.key==="Enter"&&t(s)}}function fl(t,s){t.dispatchEvent(new PointerEvent("pointer"+s,{isPrimary:!0,bubbles:!0}))}const n1=(t,s)=>{const a=t.currentTarget;if(!a)return;const r=Nm(()=>{if(qn.has(a))return;fl(a,"down");const n=Nm(()=>{fl(a,"up")}),i=()=>fl(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 wm(t){return ic(t)&&!Uh()}function i1(t,s,a={}){const[r,n,i]=Bh(t,a),l=o=>{const d=o.currentTarget;if(!wm(o))return;qn.add(d);const c=s(d,o),m=(p,g)=>{window.removeEventListener("pointerup",u),window.removeEventListener("pointercancel",x),qn.has(d)&&qn.delete(d),wm(p)&&typeof c=="function"&&c(p,{success:g})},u=p=>{m(p,d===window||d===document||a.useGlobalTarget||Vh(d,p.target))},x=p=>{m(p,!1)};window.addEventListener("pointerup",u,n),window.addEventListener("pointercancel",x,n)};return r.forEach(o=>{(a.useGlobalTarget?window:o).addEventListener("pointerdown",l,n),$h(o)&&(o.addEventListener("focus",c=>n1(c,n)),!r1(o)&&!o.hasAttribute("tabindex")&&(o.tabIndex=0))}),i}function zh(t){return th(t)&&"ownerSVGElement"in t}function l1(t){return zh(t)&&t.tagName==="svg"}const Cs=t=>!!(t&&t.getVelocity),o1=[...Mh,ts,Ka],c1=t=>o1.find(Fh(t)),lc=h.createContext({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});function Cm(t,s){if(typeof t=="function")return t(s);t!=null&&(t.current=s)}function d1(...t){return s=>{let a=!1;const r=t.map(n=>{const i=Cm(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():Cm(t[n],null)}}}}function m1(...t){return h.useCallback(d1(...t),t)}class u1 extends h.Component{getSnapshotBeforeUpdate(s){const a=this.props.childRef.current;if(a&&s.isPresent&&!this.props.isPresent){const r=a.offsetParent,n=$h(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 x1({children:t,isPresent:s,anchorX:a,root:r}){const n=h.useId(),i=h.useRef(null),l=h.useRef({width:0,height:0,top:0,left:0,right:0}),{nonce:o}=h.useContext(lc),d=m1(i,t==null?void 0:t.ref);return h.useInsertionEffect(()=>{const{width:c,height:m,top:u,left:x,right:p}=l.current;if(s||!i.current||!c||!m)return;const g=a==="left"?`left: ${x}`:`right: ${p}`;i.current.dataset.motionPopId=n;const y=document.createElement("style");o&&(y.nonce=o);const f=r??document.head;return f.appendChild(y),y.sheet&&y.sheet.insertRule(`
|
||
[data-motion-pop-id="${n}"] {
|
||
position: absolute !important;
|
||
width: ${c}px !important;
|
||
height: ${m}px !important;
|
||
${g}px !important;
|
||
top: ${u}px !important;
|
||
}
|
||
`),()=>{f.contains(y)&&f.removeChild(y)}},[s]),e.jsx(u1,{isPresent:s,childRef:i,sizeRef:l,children:h.cloneElement(t,{ref:d})})}const h1=({children:t,initial:s,isPresent:a,onExitComplete:r,custom:n,presenceAffectsLayout:i,mode:l,anchorX:o,root:d})=>{const c=Oo(p1),m=h.useId();let u=!0,x=h.useMemo(()=>(u=!1,{id:m,initial:s,isPresent:a,custom:n,onExitComplete:p=>{c.set(p,!0);for(const g of c.values())if(!g)return;r&&r()},register:p=>(c.set(p,!1),()=>c.delete(p))}),[a,c,r]);return i&&u&&(x={...x}),h.useMemo(()=>{c.forEach((p,g)=>c.set(g,!1))},[a]),h.useEffect(()=>{!a&&!c.size&&r&&r()},[a]),l==="popLayout"&&(t=e.jsx(x1,{isPresent:a,anchorX:o,root:d,children:t})),e.jsx(Ui.Provider,{value:x,children:t})};function p1(){return new Map}function Hh(t=!0){const s=h.useContext(Ui);if(s===null)return[!0,null];const{isPresent:a,onExitComplete:r,register:n}=s,i=h.useId();h.useEffect(()=>{if(t)return n(i)},[t]);const l=h.useCallback(()=>t&&r&&r(i),[i,r,t]);return!a&&r?[!1,l]:[!0]}const zn=t=>t.key||"";function Am(t){const s=[];return h.Children.forEach(t,a=>{h.isValidElement(a)&&s.push(a)}),s}const oc=({children:t,custom:s,initial:a=!0,onExitComplete:r,presenceAffectsLayout:n=!0,mode:i="sync",propagate:l=!1,anchorX:o="left",root:d})=>{const[c,m]=Hh(l),u=h.useMemo(()=>Am(t),[t]),x=l&&!c?[]:u.map(zn),p=h.useRef(!0),g=h.useRef(u),y=Oo(()=>new Map),[f,b]=h.useState(u),[v,A]=h.useState(u);qx(()=>{p.current=!1,g.current=u;for(let k=0;k<v.length;k++){const L=zn(v[k]);x.includes(L)?y.delete(L):y.get(L)!==!0&&y.set(L,!1)}},[v,x.length,x.join("-")]);const w=[];if(u!==f){let k=[...u];for(let L=0;L<v.length;L++){const D=v[L],S=zn(D);x.includes(S)||(k.splice(L,0,D),w.push(D))}return i==="wait"&&w.length&&(k=w),A(Am(k)),b(u),null}const{forceRender:T}=h.useContext(Lo);return e.jsx(e.Fragment,{children:v.map(k=>{const L=zn(k),D=l&&!c?!1:u===v||x.includes(L),S=()=>{if(y.has(L))y.set(L,!0);else return;let N=!0;y.forEach(P=>{P||(N=!1)}),N&&(T==null||T(),A(g.current),l&&(m==null||m()),r&&r())};return e.jsx(h1,{isPresent:D,initial:!p.current||a?void 0:!1,custom:s,presenceAffectsLayout:n,mode:i,root:d,onExitComplete:D?void 0:S,anchorX:o,children:k},L)})})},Wh=h.createContext({strict:!1}),Sm={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"]},$r={};for(const t in Sm)$r[t]={isEnabled:s=>Sm[t].some(a=>!!s[a])};function g1(t){for(const s in t)$r[s]={...$r[s],...t[s]}}const f1=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 gi(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||f1.has(t)}let Gh=t=>!gi(t);function y1(t){typeof t=="function"&&(Gh=s=>s.startsWith("on")?!gi(s):t(s))}try{y1(require("@emotion/is-prop-valid").default)}catch{}function b1(t,s,a){const r={};for(const n in t)n==="values"&&typeof t.values=="object"||(Gh(n)||a===!0&&gi(n)||!s&&!gi(n)||t.draggable&&n.startsWith("onDrag"))&&(r[n]=t[n]);return r}const Bi=h.createContext({});function Vi(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function wn(t){return typeof t=="string"||Array.isArray(t)}const cc=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],dc=["initial",...cc];function zi(t){return Vi(t.animate)||dc.some(s=>wn(t[s]))}function Kh(t){return!!(zi(t)||t.variants)}function v1(t,s){if(zi(t)){const{initial:a,animate:r}=t;return{initial:a===!1||wn(a)?a:void 0,animate:wn(r)?r:void 0}}return t.inherit!==!1?s:{}}function j1(t){const{initial:s,animate:a}=v1(t,h.useContext(Bi));return h.useMemo(()=>({initial:s,animate:a}),[Tm(s),Tm(a)])}function Tm(t){return Array.isArray(t)?t.join(" "):t}const Cn={};function N1(t){for(const s in t)Cn[s]=t[s],Ko(s)&&(Cn[s].isCSSVariable=!0)}function Yh(t,{layout:s,layoutId:a}){return Zr.has(t)||t.startsWith("origin")||(s||a!==void 0)&&(!!Cn[t]||t==="opacity")}const w1={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},C1=Yr.length;function A1(t,s,a){let r="",n=!0;for(let i=0;i<C1;i++){const l=Yr[i],o=t[l];if(o===void 0)continue;let d=!0;if(typeof o=="number"?d=o===(l.startsWith("scale")?1:0):d=parseFloat(o)===0,!d||a){const c=Oh(o,rc[l]);if(!d){n=!1;const m=w1[l]||l;r+=`${m}(${c}) `}a&&(s[l]=c)}}return r=r.trim(),a?r=a(s,n?"":r):n&&(r="none"),r}function mc(t,s,a){const{style:r,vars:n,transformOrigin:i}=t;let l=!1,o=!1;for(const d in s){const c=s[d];if(Zr.has(d)){l=!0;continue}else if(Ko(d)){n[d]=c;continue}else{const m=Oh(c,rc[d]);d.startsWith("origin")?(o=!0,i[d]=m):r[d]=m}}if(s.transform||(l||a?r.transform=A1(s,t.transform,a):r.transform&&(r.transform="none")),o){const{originX:d="50%",originY:c="50%",originZ:m=0}=i;r.transformOrigin=`${d} ${c} ${m}`}}const uc=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Zh(t,s,a){for(const r in s)!Cs(s[r])&&!Yh(r,a)&&(t[r]=s[r])}function S1({transformTemplate:t},s){return h.useMemo(()=>{const a=uc();return mc(a,s,t),Object.assign({},a.vars,a.style)},[s])}function T1(t,s){const a=t.style||{},r={};return Zh(r,a,t),Object.assign(r,S1(t,s)),r}function k1(t,s){const a={},r=T1(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 R1={offset:"stroke-dashoffset",array:"stroke-dasharray"},D1={offset:"strokeDashoffset",array:"strokeDasharray"};function P1(t,s,a=1,r=0,n=!0){t.pathLength=1;const i=n?R1:D1;t[i.offset]=qe.transform(-r);const l=qe.transform(s),o=qe.transform(a);t[i.array]=`${l} ${o}`}function Xh(t,{attrX:s,attrY:a,attrScale:r,pathLength:n,pathSpacing:i=1,pathOffset:l=0,...o},d,c,m){if(mc(t,o,c),d){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:u,style:x}=t;u.transform&&(x.transform=u.transform,delete u.transform),(x.transform||u.transformOrigin)&&(x.transformOrigin=u.transformOrigin??"50% 50%",delete u.transformOrigin),x.transform&&(x.transformBox=(m==null?void 0:m.transformBox)??"fill-box",delete u.transformBox),s!==void 0&&(u.x=s),a!==void 0&&(u.y=a),r!==void 0&&(u.scale=r),n!==void 0&&P1(u,n,i,l,!1)}const Qh=()=>({...uc(),attrs:{}}),Jh=t=>typeof t=="string"&&t.toLowerCase()==="svg";function I1(t,s,a,r){const n=h.useMemo(()=>{const i=Qh();return Xh(i,s,Jh(r),t.transformTemplate,t.style),{...i.attrs,style:{...i.style}}},[s]);if(t.style){const i={};Zh(i,t.style,t),n.style={...i,...n.style}}return n}const E1=["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 xc(t){return typeof t!="string"||t.includes("-")?!1:!!(E1.indexOf(t)>-1||/[A-Z]/u.test(t))}function F1(t,s,a,{latestValues:r},n,i=!1){const o=(xc(t)?I1:k1)(s,r,n,t),d=b1(s,typeof t=="string",i),c=t!==h.Fragment?{...d,...o,ref:a}:{},{children:m}=s,u=h.useMemo(()=>Cs(m)?m.get():m,[m]);return h.createElement(t,{...c,children:u})}function km(t){const s=[{},{}];return t==null||t.values.forEach((a,r)=>{s[0][r]=a.get(),s[1][r]=a.getVelocity()}),s}function hc(t,s,a,r){if(typeof s=="function"){const[n,i]=km(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]=km(r);s=s(a!==void 0?a:t.custom,n,i)}return s}function ei(t){return Cs(t)?t.get():t}function M1({scrapeMotionValuesFromProps:t,createRenderState:s},a,r,n){return{latestValues:_1(a,r,n,t),renderState:s()}}function _1(t,s,a,r){const n={},i=r(t,{});for(const x in i)n[x]=ei(i[x]);let{initial:l,animate:o}=t;const d=zi(t),c=Kh(t);s&&c&&!d&&t.inherit!==!1&&(l===void 0&&(l=s.initial),o===void 0&&(o=s.animate));let m=a?a.initial===!1:!1;m=m||l===!1;const u=m?o:l;if(u&&typeof u!="boolean"&&!Vi(u)){const x=Array.isArray(u)?u:[u];for(let p=0;p<x.length;p++){const g=hc(t,x[p]);if(g){const{transitionEnd:y,transition:f,...b}=g;for(const v in b){let A=b[v];if(Array.isArray(A)){const w=m?A.length-1:0;A=A[w]}A!==null&&(n[v]=A)}for(const v in y)n[v]=y[v]}}}return n}const qh=t=>(s,a)=>{const r=h.useContext(Bi),n=h.useContext(Ui),i=()=>M1(t,s,r,n);return a?i():Oo(i)};function pc(t,s,a){var i;const{style:r}=t,n={};for(const l in r)(Cs(r[l])||s.style&&Cs(s.style[l])||Yh(l,t)||((i=a==null?void 0:a.getValue(l))==null?void 0:i.liveStyle)!==void 0)&&(n[l]=r[l]);return n}const L1=qh({scrapeMotionValuesFromProps:pc,createRenderState:uc});function ep(t,s,a){const r=pc(t,s,a);for(const n in t)if(Cs(t[n])||Cs(s[n])){const i=Yr.indexOf(n)!==-1?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n;r[i]=t[n]}return r}const O1=qh({scrapeMotionValuesFromProps:ep,createRenderState:Qh}),$1=Symbol.for("motionComponentSymbol");function kr(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function U1(t,s,a){return h.useCallback(r=>{r&&t.onMount&&t.onMount(r),s&&(r?s.mount(r):s.unmount()),a&&(typeof a=="function"?a(r):kr(a)&&(a.current=r))},[s])}const gc=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),B1="framerAppearId",tp="data-"+gc(B1),sp=h.createContext({});function V1(t,s,a,r,n){var y,f;const{visualElement:i}=h.useContext(Bi),l=h.useContext(Wh),o=h.useContext(Ui),d=h.useContext(lc).reducedMotion,c=h.useRef(null);r=r||l.renderer,!c.current&&r&&(c.current=r(t,{visualState:s,parent:i,props:a,presenceContext:o,blockInitialAnimation:o?o.initial===!1:!1,reducedMotionConfig:d}));const m=c.current,u=h.useContext(sp);m&&!m.projection&&n&&(m.type==="html"||m.type==="svg")&&z1(c.current,a,n,u);const x=h.useRef(!1);h.useInsertionEffect(()=>{m&&x.current&&m.update(a,o)});const p=a[tp],g=h.useRef(!!p&&!((y=window.MotionHandoffIsComplete)!=null&&y.call(window,p))&&((f=window.MotionHasOptimisedAnimation)==null?void 0:f.call(window,p)));return qx(()=>{m&&(x.current=!0,window.MotionIsMounted=!0,m.updateFeatures(),m.scheduleRenderMicrotask(),g.current&&m.animationState&&m.animationState.animateChanges())}),h.useEffect(()=>{m&&(!g.current&&m.animationState&&m.animationState.animateChanges(),g.current&&(queueMicrotask(()=>{var b;(b=window.MotionHandoffMarkAsComplete)==null||b.call(window,p)}),g.current=!1),m.enteringChildren=void 0)}),m}function z1(t,s,a,r){const{layoutId:n,layout:i,drag:l,dragConstraints:o,layoutScroll:d,layoutRoot:c,layoutCrossfade:m}=s;t.projection=new a(t.latestValues,s["data-framer-portal-id"]?void 0:ap(t.parent)),t.projection.setOptions({layoutId:n,layout:i,alwaysMeasureLayout:!!l||o&&kr(o),visualElement:t,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:m,layoutScroll:d,layoutRoot:c})}function ap(t){if(t)return t.options.allowProjection!==!1?t.projection:ap(t.parent)}function yl(t,{forwardMotionProps:s=!1}={},a,r){a&&g1(a);const n=xc(t)?O1:L1;function i(o,d){let c;const m={...h.useContext(lc),...o,layoutId:H1(o)},{isStatic:u}=m,x=j1(o),p=n(o,u);if(!u&&$o){W1();const g=G1(m);c=g.MeasureLayout,x.visualElement=V1(t,p,m,r,g.ProjectionNode)}return e.jsxs(Bi.Provider,{value:x,children:[c&&x.visualElement?e.jsx(c,{visualElement:x.visualElement,...m}):null,F1(t,o,U1(p,x.visualElement,d),p,u,s)]})}i.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const l=h.forwardRef(i);return l[$1]=t,l}function H1({layoutId:t}){const s=h.useContext(Lo).id;return s&&t!==void 0?s+"-"+t:t}function W1(t,s){h.useContext(Wh).strict}function G1(t){const{drag:s,layout:a}=$r;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 K1(t,s){if(typeof Proxy>"u")return yl;const a=new Map,r=(i,l)=>yl(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,yl(l,void 0,t,s)),a.get(l))})}function rp({top:t,left:s,right:a,bottom:r}){return{x:{min:s,max:a},y:{min:t,max:r}}}function Y1({x:t,y:s}){return{top:s.min,right:t.max,bottom:s.max,left:t.min}}function Z1(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 bl(t){return t===void 0||t===1}function so({scale:t,scaleX:s,scaleY:a}){return!bl(t)||!bl(s)||!bl(a)}function dr(t){return so(t)||np(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function np(t){return Rm(t.x)||Rm(t.y)}function Rm(t){return t&&t!=="0%"}function fi(t,s,a){const r=t-a,n=s*r;return a+n}function Dm(t,s,a,r,n){return n!==void 0&&(t=fi(t,n,r)),fi(t,a,r)+s}function ao(t,s=0,a=1,r,n){t.min=Dm(t.min,s,a,r,n),t.max=Dm(t.max,s,a,r,n)}function ip(t,{x:s,y:a}){ao(t.x,s.translate,s.scale,s.originPoint),ao(t.y,a.translate,a.scale,a.originPoint)}const Pm=.999999999999,Im=1.0000000000001;function X1(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:d}=i.options;d&&d.props.style&&d.props.style.display==="contents"||(r&&i.options.layoutScroll&&i.scroll&&i!==i.root&&Dr(t,{x:-i.scroll.offset.x,y:-i.scroll.offset.y}),l&&(s.x*=l.x.scale,s.y*=l.y.scale,ip(t,l)),r&&dr(i.latestValues)&&Dr(t,i.latestValues))}s.x<Im&&s.x>Pm&&(s.x=1),s.y<Im&&s.y>Pm&&(s.y=1)}function Rr(t,s){t.min=t.min+s,t.max=t.max+s}function Em(t,s,a,r,n=.5){const i=Wt(t.min,t.max,n);ao(t,s,a,i,r)}function Dr(t,s){Em(t.x,s.x,s.scaleX,s.scale,s.originX),Em(t.y,s.y,s.scaleY,s.scale,s.originY)}function lp(t,s){return rp(Z1(t.getBoundingClientRect(),s))}function Q1(t,s,a){const r=lp(t,a),{scroll:n}=s;return n&&(Rr(r.x,n.offset.x),Rr(r.y,n.offset.y)),r}const Fm=()=>({translate:0,scale:1,origin:0,originPoint:0}),Pr=()=>({x:Fm(),y:Fm()}),Mm=()=>({min:0,max:0}),Xt=()=>({x:Mm(),y:Mm()}),ro={current:null},op={current:!1};function J1(){if(op.current=!0,!!$o)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),s=()=>ro.current=t.matches;t.addEventListener("change",s),s()}else ro.current=!1}const q1=new WeakMap;function e2(t,s,a){for(const r in s){const n=s[r],i=a[r];if(Cs(n))t.addValue(r,n);else if(Cs(i))t.addValue(r,Or(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,Or(l!==void 0?l:n,{owner:t}))}}for(const r in a)s[r]===void 0&&t.removeValue(r);return s}const _m=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class t2{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=Us.now();this.renderScheduledAt<x&&(this.renderScheduledAt=x,Ut.render(this.render,!1,!0))};const{latestValues:d,renderState:c}=l;this.latestValues=d,this.baseTarget={...d},this.initialValues=a.initial?{...d}:{},this.renderState=c,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=zi(a),this.isVariantNode=Kh(a),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(s&&s.current);const{willChange:m,...u}=this.scrapeMotionValuesFromProps(a,{},this);for(const x in u){const p=u[x];d[x]!==void 0&&Cs(p)&&p.set(d[x])}}mount(s){var a;this.current=s,q1.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)),op.current||J1(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:ro.current,(a=this.parent)==null||a.addChild(this),this.update(this.props,this.presenceContext)}unmount(){var s;this.projection&&this.projection.unmount(),Ga(this.notifyUpdate),Ga(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=Zr.has(s);r&&this.onBindTransform&&this.onBindTransform();const n=a.on("change",l=>{this.latestValues[s]=l,this.props.onUpdate&&Ut.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 $r){const a=$r[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):Xt()}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<_m.length;r++){const n=_m[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=e2(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=Or(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)||sh(r))?r=parseFloat(r):!c1(r)&&Ka.test(a)&&(r=Lh(s,a)),this.setBaseTarget(s,Cs(r)?r.get():r)),Cs(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=hc(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&&!Cs(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 cp extends t2{constructor(){super(...arguments),this.KeyframeResolver=Qw}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;Cs(s)&&(this.childSubscription=s.on("change",a=>{this.current&&(this.current.textContent=`${a}`)}))}}function dp(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 s2(t){return window.getComputedStyle(t)}class a2 extends cp{constructor(){super(...arguments),this.type="html",this.renderInstance=dp}readValueFromInstance(s,a){var r;if(Zr.has(a))return(r=this.projection)!=null&&r.isProjecting?Zl(a):gw(s,a);{const n=s2(s),i=(Ko(a)?n.getPropertyValue(a):n[a])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(s,{transformPagePoint:a}){return lp(s,a)}build(s,a,r){mc(s,a,r.transformTemplate)}scrapeMotionValuesFromProps(s,a,r){return pc(s,a,r)}}const mp=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 r2(t,s,a,r){dp(t,s,void 0,r);for(const n in s.attrs)t.setAttribute(mp.has(n)?n:gc(n),s.attrs[n])}class n2 extends cp{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Xt}getBaseTargetFromProps(s,a){return s[a]}readValueFromInstance(s,a){if(Zr.has(a)){const r=_h(a);return r&&r.default||0}return a=mp.has(a)?a:gc(a),s.getAttribute(a)}scrapeMotionValuesFromProps(s,a,r){return ep(s,a,r)}build(s,a,r){Xh(s,a,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(s,a,r,n){r2(s,a,r,n)}mount(s){this.isSVGTag=Jh(s.tagName),super.mount(s)}}const i2=(t,s)=>xc(t)?new n2(s):new a2(s,{allowProjection:t!==h.Fragment});function _r(t,s,a){const r=t.getProps();return hc(r,s,a!==void 0?a:r.custom,t)}const no=t=>Array.isArray(t);function l2(t,s,a){t.hasValue(s)?t.getValue(s).set(a):t.addValue(s,Or(a))}function o2(t){return no(t)?t[t.length-1]||0:t}function c2(t,s){const a=_r(t,s);let{transitionEnd:r={},transition:n={},...i}=a||{};i={...i,...r};for(const l in i){const o=o2(i[l]);l2(t,l,o)}}function d2(t){return!!(Cs(t)&&t.add)}function io(t,s){const a=t.getValue("willChange");if(d2(a))return a.add(s);if(!a&&Ea.WillChange){const r=new Ea.WillChange("auto");t.addValue("willChange",r),r.add(s)}}function up(t){return t.props[tp]}const m2=t=>t!==null;function u2(t,{repeat:s,repeatType:a="loop"},r){const n=t.filter(m2),i=s&&a!=="loop"&&s%2===1?0:n.length-1;return n[i]}const x2={type:"spring",stiffness:500,damping:25,restSpeed:10},h2=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),p2={type:"keyframes",duration:.8},g2={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},f2=(t,{keyframes:s})=>s.length>2?p2:Zr.has(t)?t.startsWith("scale")?h2(s[1]):x2:g2;function y2({when:t,delay:s,delayChildren:a,staggerChildren:r,staggerDirection:n,repeat:i,repeatType:l,repeatDelay:o,from:d,elapsed:c,...m}){return!!Object.keys(m).length}const fc=(t,s,a,r={},n,i)=>l=>{const o=ac(r,t)||{},d=o.delay||r.delay||0;let{elapsed:c=0}=r;c=c-va(d);const m={keyframes:Array.isArray(a)?a:[null,a],ease:"easeOut",velocity:s.getVelocity(),...o,delay:-c,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};y2(o)||Object.assign(m,f2(t,m)),m.duration&&(m.duration=va(m.duration)),m.repeatDelay&&(m.repeatDelay=va(m.repeatDelay)),m.from!==void 0&&(m.keyframes[0]=m.from);let u=!1;if((m.type===!1||m.duration===0&&!m.repeatDelay)&&(eo(m),m.delay===0&&(u=!0)),(Ea.instantAnimations||Ea.skipAnimations)&&(u=!0,eo(m),m.delay=0),m.allowFlatten=!o.type&&!o.ease,u&&!i&&s.get()!==void 0){const x=u2(m.keyframes,o);if(x!==void 0){Ut.update(()=>{m.onUpdate(x),m.onComplete()});return}}return o.isSync?new tc(m):new $w(m)};function b2({protectedKeys:t,needsAnimating:s},a){const r=t.hasOwnProperty(a)&&s[a]!==!0;return s[a]=!1,r}function xp(t,s,{delay:a=0,transitionOverride:r,type:n}={}){let{transition:i=t.getDefaultTransition(),transitionEnd:l,...o}=s;r&&(i=r);const d=[],c=n&&t.animationState&&t.animationState.getState()[n];for(const m in o){const u=t.getValue(m,t.latestValues[m]??null),x=o[m];if(x===void 0||c&&b2(c,m))continue;const p={delay:a,...ac(i||{},m)},g=u.get();if(g!==void 0&&!u.isAnimating&&!Array.isArray(x)&&x===g&&!p.velocity)continue;let y=!1;if(window.MotionHandoffAnimation){const b=up(t);if(b){const v=window.MotionHandoffAnimation(b,m,Ut);v!==null&&(p.startTime=v,y=!0)}}io(t,m),u.start(fc(m,u,x,t.shouldReduceMotion&&Eh.has(m)?{type:!1}:p,t,y));const f=u.animation;f&&d.push(f)}return l&&Promise.all(d).then(()=>{Ut.update(()=>{l&&c2(t,l)})}),d}function hp(t,s,a,r=0,n=1){const i=Array.from(t).sort((c,m)=>c.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 lo(t,s,a={}){var d;const r=_r(t,s,a.type==="exit"?(d=t.presenceContext)==null?void 0:d.custom:void 0);let{transition:n=t.getDefaultTransition()||{}}=r||{};a.transitionOverride&&(n=a.transitionOverride);const i=r?()=>Promise.all(xp(t,r,a)):()=>Promise.resolve(),l=t.variantChildren&&t.variantChildren.size?(c=0)=>{const{delayChildren:m=0,staggerChildren:u,staggerDirection:x}=n;return v2(t,s,c,m,u,x,a)}:()=>Promise.resolve(),{when:o}=n;if(o){const[c,m]=o==="beforeChildren"?[i,l]:[l,i];return c().then(()=>m())}else return Promise.all([i(),l(a.delay)])}function v2(t,s,a=0,r=0,n=0,i=1,l){const o=[];for(const d of t.variantChildren)d.notify("AnimationStart",s),o.push(lo(d,s,{...l,delay:a+(typeof r=="function"?0:r)+hp(t.variantChildren,d,r,n,i)}).then(()=>d.notify("AnimationComplete",s)));return Promise.all(o)}function j2(t,s,a={}){t.notify("AnimationStart",s);let r;if(Array.isArray(s)){const n=s.map(i=>lo(t,i,a));r=Promise.all(n)}else if(typeof s=="string")r=lo(t,s,a);else{const n=typeof s=="function"?_r(t,s,a.custom):s;r=Promise.all(xp(t,n,a))}return r.then(()=>{t.notify("AnimationComplete",s)})}function pp(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 N2=dc.length;function gp(t){if(!t)return;if(!t.isControllingVariants){const a=t.parent?gp(t.parent)||{}:{};return t.props.initial!==void 0&&(a.initial=t.props.initial),a}const s={};for(let a=0;a<N2;a++){const r=dc[a],n=t.props[r];(wn(n)||n===!1)&&(s[r]=n)}return s}const w2=[...cc].reverse(),C2=cc.length;function A2(t){return s=>Promise.all(s.map(({animation:a,options:r})=>j2(t,a,r)))}function S2(t){let s=A2(t),a=Lm(),r=!0;const n=d=>(c,m)=>{var x;const u=_r(t,m,d==="exit"?(x=t.presenceContext)==null?void 0:x.custom:void 0);if(u){const{transition:p,transitionEnd:g,...y}=u;c={...c,...y,...g}}return c};function i(d){s=d(t)}function l(d){const{props:c}=t,m=gp(t.parent)||{},u=[],x=new Set;let p={},g=1/0;for(let f=0;f<C2;f++){const b=w2[f],v=a[b],A=c[b]!==void 0?c[b]:m[b],w=wn(A),T=b===d?v.isActive:null;T===!1&&(g=f);let k=A===m[b]&&A!==c[b]&&w;if(k&&r&&t.manuallyAnimateOnMount&&(k=!1),v.protectedKeys={...p},!v.isActive&&T===null||!A&&!v.prevProp||Vi(A)||typeof A=="boolean")continue;const L=T2(v.prevProp,A);let D=L||b===d&&v.isActive&&!k&&w||f>g&&w,S=!1;const N=Array.isArray(A)?A:[A];let P=N.reduce(n(b),{});T===!1&&(P={});const{prevResolvedValues:R={}}=v,O={...R,...P},E=C=>{D=!0,x.has(C)&&(S=!0,x.delete(C)),v.needsAnimating[C]=!0;const j=t.getValue(C);j&&(j.liveStyle=!1)};for(const C in O){const j=P[C],U=R[C];if(p.hasOwnProperty(C))continue;let $=!1;no(j)&&no(U)?$=!pp(j,U):$=j!==U,$?j!=null?E(C):x.add(C):j!==void 0&&x.has(C)?E(C):v.protectedKeys[C]=!0}v.prevProp=A,v.prevResolvedValues=P,v.isActive&&(p={...p,...P}),r&&t.blockInitialAnimation&&(D=!1);const M=k&&L;D&&(!M||S)&&u.push(...N.map(C=>{const j={type:b};if(typeof C=="string"&&r&&!M&&t.manuallyAnimateOnMount&&t.parent){const{parent:U}=t,$=_r(U,C);if(U.enteringChildren&&$){const{delayChildren:_}=$.transition||{};j.delay=hp(U.enteringChildren,t,_)}}return{animation:C,options:j}}))}if(x.size){const f={};if(typeof c.initial!="boolean"){const b=_r(t,Array.isArray(c.initial)?c.initial[0]:c.initial);b&&b.transition&&(f.transition=b.transition)}x.forEach(b=>{const v=t.getBaseTarget(b),A=t.getValue(b);A&&(A.liveStyle=!0),f[b]=v??null}),u.push({animation:f})}let y=!!u.length;return r&&(c.initial===!1||c.initial===c.animate)&&!t.manuallyAnimateOnMount&&(y=!1),r=!1,y?s(u):Promise.resolve()}function o(d,c){var u;if(a[d].isActive===c)return Promise.resolve();(u=t.variantChildren)==null||u.forEach(x=>{var p;return(p=x.animationState)==null?void 0:p.setActive(d,c)}),a[d].isActive=c;const m=l(d);for(const x in a)a[x].protectedKeys={};return m}return{animateChanges:l,setActive:o,setAnimateFunction:i,getState:()=>a,reset:()=>{a=Lm()}}}function T2(t,s){return typeof s=="string"?s!==t:Array.isArray(s)?!pp(s,t):!1}function lr(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Lm(){return{animate:lr(!0),whileInView:lr(),whileHover:lr(),whileTap:lr(),whileDrag:lr(),whileFocus:lr(),exit:lr()}}class Xa{constructor(s){this.isMounted=!1,this.node=s}update(){}}class k2 extends Xa{constructor(s){super(s),s.animationState||(s.animationState=S2(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();Vi(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 R2=0;class D2 extends Xa{constructor(){super(...arguments),this.id=R2++}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 P2={animation:{Feature:k2},exit:{Feature:D2}};function An(t,s,a,r={passive:!0}){return t.addEventListener(s,a,r),()=>t.removeEventListener(s,a)}function Mn(t){return{point:{x:t.pageX,y:t.pageY}}}const I2=t=>s=>ic(s)&&t(s,Mn(s));function hn(t,s,a,r){return An(t,s,I2(a),r)}const fp=1e-4,E2=1-fp,F2=1+fp,yp=.01,M2=0-yp,_2=0+yp;function Rs(t){return t.max-t.min}function L2(t,s,a){return Math.abs(t-s)<=a}function Om(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>=E2&&t.scale<=F2||isNaN(t.scale))&&(t.scale=1),(t.translate>=M2&&t.translate<=_2||isNaN(t.translate))&&(t.translate=0)}function pn(t,s,a,r){Om(t.x,s.x,a.x,r?r.originX:void 0),Om(t.y,s.y,a.y,r?r.originY:void 0)}function $m(t,s,a){t.min=a.min+s.min,t.max=t.min+Rs(s)}function O2(t,s,a){$m(t.x,s.x,a.x),$m(t.y,s.y,a.y)}function Um(t,s,a){t.min=s.min-a.min,t.max=t.min+Rs(s)}function gn(t,s,a){Um(t.x,s.x,a.x),Um(t.y,s.y,a.y)}function sa(t){return[t("x"),t("y")]}const bp=({current:t})=>t?t.ownerDocument.defaultView:null,Bm=(t,s)=>Math.abs(t-s);function $2(t,s){const a=Bm(t.x,s.x),r=Bm(t.y,s.y);return Math.sqrt(a**2+r**2)}class vp{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=jl(this.lastMoveEventInfo,this.history),p=this.startEvent!==null,g=$2(x.offset,{x:0,y:0})>=this.distanceThreshold;if(!p&&!g)return;const{point:y}=x,{timestamp:f}=ys;this.history.push({...y,timestamp:f});const{onStart:b,onMove:v}=this.handlers;p||(b&&b(this.lastMoveEvent,x),this.startEvent=this.lastMoveEvent),v&&v(this.lastMoveEvent,x)},this.handlePointerMove=(x,p)=>{this.lastMoveEvent=x,this.lastMoveEventInfo=vl(p,this.transformPagePoint),Ut.update(this.updatePoint,!0)},this.handlePointerUp=(x,p)=>{this.end();const{onEnd:g,onSessionEnd:y,resumeAnimation:f}=this.handlers;if(this.dragSnapToOrigin&&f&&f(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const b=jl(x.type==="pointercancel"?this.lastMoveEventInfo:vl(p,this.transformPagePoint),this.history);this.startEvent&&g&&g(x,b),y&&y(x,b)},!ic(s))return;this.dragSnapToOrigin=i,this.handlers=a,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=n||window;const o=Mn(s),d=vl(o,this.transformPagePoint),{point:c}=d,{timestamp:m}=ys;this.history=[{...c,timestamp:m}];const{onSessionStart:u}=a;u&&u(s,jl(d,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(),Ga(this.updatePoint)}}function vl(t,s){return s?{point:s(t.point)}:t}function Vm(t,s){return{x:t.x-s.x,y:t.y-s.y}}function jl({point:t},s){return{point:t,delta:Vm(t,jp(s)),offset:Vm(t,U2(s)),velocity:B2(s,.1)}}function U2(t){return t[0]}function jp(t){return t[t.length-1]}function B2(t,s){if(t.length<2)return{x:0,y:0};let a=t.length-1,r=null;const n=jp(t);for(;a>=0&&(r=t[a],!(n.timestamp-r.timestamp>va(s)));)a--;if(!r)return{x:0,y:0};const i=aa(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 V2(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 zm(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 z2(t,{top:s,left:a,bottom:r,right:n}){return{x:zm(t.x,a,n),y:zm(t.y,s,r)}}function Hm(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 H2(t,s){return{x:Hm(t.x,s.x),y:Hm(t.y,s.y)}}function W2(t,s){let a=.5;const r=Rs(t),n=Rs(s);return n>r?a=vn(s.min,s.max-r,t.min):r>n&&(a=vn(t.min,t.max-n,s.min)),Ia(0,1,a)}function G2(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 oo=.35;function K2(t=oo){return t===!1?t=0:t===!0&&(t=oo),{x:Wm(t,"left","right"),y:Wm(t,"top","bottom")}}function Wm(t,s,a){return{min:Gm(t,s),max:Gm(t,a)}}function Gm(t,s){return typeof t=="number"?t:t[s]||0}const Y2=new WeakMap;class Z2{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=Xt(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=s}start(s,{snapToCursor:a=!1,distanceThreshold:r}={}){const{presenceContext:n}=this.visualElement;if(n&&n.isPresent===!1)return;const i=u=>{const{dragSnapToOrigin:x}=this.getProps();x?this.pauseAnimation():this.stopAnimation(),a&&this.snapToCursor(Mn(u).point)},l=(u,x)=>{const{drag:p,dragPropagation:g,onDragStart:y}=this.getProps();if(p&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=t1(p),!this.openDragLock))return;this.latestPointerEvent=u,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(b=>{let v=this.getAxisMotionValue(b).get()||0;if(ja.test(v)){const{projection:A}=this.visualElement;if(A&&A.layout){const w=A.layout.layoutBox[b];w&&(v=Rs(w)*(parseFloat(v)/100))}}this.originPoint[b]=v}),y&&Ut.postRender(()=>y(u,x)),io(this.visualElement,"transform");const{animationState:f}=this.visualElement;f&&f.setActive("whileDrag",!0)},o=(u,x)=>{this.latestPointerEvent=u,this.latestPanInfo=x;const{dragPropagation:p,dragDirectionLock:g,onDirectionLock:y,onDrag:f}=this.getProps();if(!p&&!this.openDragLock)return;const{offset:b}=x;if(g&&this.currentDirection===null){this.currentDirection=X2(b),this.currentDirection!==null&&y&&y(this.currentDirection);return}this.updateAxis("x",x.point,b),this.updateAxis("y",x.point,b),this.visualElement.render(),f&&f(u,x)},d=(u,x)=>{this.latestPointerEvent=u,this.latestPanInfo=x,this.stop(u,x),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>sa(u=>{var x;return this.getAnimationState(u)==="paused"&&((x=this.getAxisMotionValue(u).animation)==null?void 0:x.play())}),{dragSnapToOrigin:m}=this.getProps();this.panSession=new vp(s,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:d,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:m,distanceThreshold:r,contextWindow:bp(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&&Ut.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||!Hn(s,n,this.currentDirection))return;const i=this.getAxisMotionValue(s);let l=this.originPoint[s]+r[s];this.constraints&&this.constraints[s]&&(l=V2(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&&kr(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&r?this.constraints=z2(r.layoutBox,s):this.constraints=!1,this.elastic=K2(a),n!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&sa(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=G2(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:s,onMeasureDragConstraints:a}=this.getProps();if(!s||!kr(s))return!1;const r=s.current,{projection:n}=this.visualElement;if(!n||!n.layout)return!1;const i=Q1(r,n.root,this.visualElement.getTransformPagePoint());let l=H2(n.layout.layoutBox,i);if(a){const o=a(Y1(l));this.hasMutatedConstraints=!!o,o&&(l=rp(o))}return l}startAnimation(s){const{drag:a,dragMomentum:r,dragElastic:n,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),d=this.constraints||{},c=sa(m=>{if(!Hn(m,a,this.currentDirection))return;let u=d&&d[m]||{};l&&(u={min:0,max:0});const x=n?200:1e6,p=n?40:1e7,g={type:"inertia",velocity:r?s[m]:0,bounceStiffness:x,bounceDamping:p,timeConstant:750,restDelta:1,restSpeed:10,...i,...u};return this.startAxisValueAnimation(m,g)});return Promise.all(c).then(o)}startAxisValueAnimation(s,a){const r=this.getAxisMotionValue(s);return io(this.visualElement,s),r.start(fc(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(!Hn(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(!kr(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 d=o.get();n[l]=W2({min:d,max:d},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(!Hn(l,s,null))return;const o=this.getAxisMotionValue(l),{min:d,max:c}=this.constraints[l];o.set(Wt(d,c,n[l]))})}addListeners(){if(!this.visualElement.current)return;Y2.set(this.visualElement,this);const s=this.visualElement.current,a=hn(s,"pointerdown",d=>{const{drag:c,dragListener:m=!0}=this.getProps();c&&m&&this.start(d)}),r=()=>{const{dragConstraints:d}=this.getProps();kr(d)&&d.current&&(this.constraints=this.resolveRefConstraints())},{projection:n}=this.visualElement,i=n.addEventListener("measure",r);n&&!n.layout&&(n.root&&n.root.updateScroll(),n.updateLayout()),Ut.read(r);const l=An(window,"resize",()=>this.scalePositionWithinConstraints()),o=n.addEventListener("didUpdate",({delta:d,hasLayoutChanged:c})=>{this.isDragging&&c&&(sa(m=>{const u=this.getAxisMotionValue(m);u&&(this.originPoint[m]+=d[m].translate,u.set(u.get()+d[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=oo,dragMomentum:o=!0}=s;return{...s,drag:a,dragDirectionLock:r,dragPropagation:n,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function Hn(t,s,a){return(s===!0||s===t)&&(a===null||a===t)}function X2(t,s=10){let a=null;return Math.abs(t.y)>s?a="y":Math.abs(t.x)>s&&(a="x"),a}class Q2 extends Xa{constructor(s){super(s),this.removeGroupControls=na,this.removeListeners=na,this.controls=new Z2(s)}mount(){const{dragControls:s}=this.node.getProps();s&&(this.removeGroupControls=s.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||na}unmount(){this.removeGroupControls(),this.removeListeners()}}const Km=t=>(s,a)=>{t&&Ut.postRender(()=>t(s,a))};class J2 extends Xa{constructor(){super(...arguments),this.removePointerDownListener=na}onPointerDown(s){this.session=new vp(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:bp(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:a,onPan:r,onPanEnd:n}=this.node.getProps();return{onSessionStart:Km(s),onStart:Km(a),onMove:r,onEnd:(i,l)=>{delete this.session,n&&Ut.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 ti={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Ym(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(qe.test(t))t=parseFloat(t);else return t;const a=Ym(t,s.target.x),r=Ym(t,s.target.y);return`${a}% ${r}%`}},q2={correct:(t,{treeScale:s,projectionDelta:a})=>{const r=t,n=Ka.parse(t);if(n.length>5)return r;const i=Ka.createTransformer(t),l=typeof n[0]!="number"?1:0,o=a.x.scale*s.x,d=a.y.scale*s.y;n[0+l]/=o,n[1+l]/=d;const c=Wt(o,d,.5);return typeof n[2+l]=="number"&&(n[2+l]/=c),typeof n[3+l]=="number"&&(n[3+l]/=c),i(n)}};let Nl=!1;class eC extends h.Component{componentDidMount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r,layoutId:n}=this.props,{projection:i}=s;N1(tC),i&&(a.group&&a.group.add(i),r&&r.register&&n&&r.register(i),Nl&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,onExitComplete:()=>this.safeToRemove()})),ti.hasEverUpdated=!0}getSnapshotBeforeUpdate(s){const{layoutDependency:a,visualElement:r,drag:n,isPresent:i}=this.props,{projection:l}=r;return l&&(l.isPresent=i,Nl=!0,n||s.layoutDependency!==a||a===void 0||s.isPresent!==i?l.willUpdate():this.safeToRemove(),s.isPresent!==i&&(i?l.promote():l.relegate()||Ut.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;Nl=!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 Np(t){const[s,a]=Hh(),r=h.useContext(Lo);return e.jsx(eC,{...t,layoutGroup:r,switchLayoutGroup:h.useContext(sp),isPresent:s,safeToRemove:a})}const tC={borderRadius:{...rn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:rn,borderTopRightRadius:rn,borderBottomLeftRadius:rn,borderBottomRightRadius:rn,boxShadow:q2};function sC(t,s,a){const r=Cs(t)?t:Or(t);return r.start(fc("",r,s,a)),r.animation}const aC=(t,s)=>t.depth-s.depth;class rC{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(aC),this.isDirty=!1,this.children.forEach(s)}}function nC(t,s){const a=Us.now(),r=({timestamp:n})=>{const i=n-a;i>=s&&(Ga(r),t(i-s))};return Ut.setup(r,!0),()=>Ga(r)}const wp=["TopLeft","TopRight","BottomLeft","BottomRight"],iC=wp.length,Zm=t=>typeof t=="string"?parseFloat(t):t,Xm=t=>typeof t=="number"||qe.test(t);function lC(t,s,a,r,n,i){n?(t.opacity=Wt(0,a.opacity??1,oC(r)),t.opacityExit=Wt(s.opacity??1,0,cC(r))):i&&(t.opacity=Wt(s.opacity??1,a.opacity??1,r));for(let l=0;l<iC;l++){const o=`border${wp[l]}Radius`;let d=Qm(s,o),c=Qm(a,o);if(d===void 0&&c===void 0)continue;d||(d=0),c||(c=0),d===0||c===0||Xm(d)===Xm(c)?(t[o]=Math.max(Wt(Zm(d),Zm(c),r),0),(ja.test(c)||ja.test(d))&&(t[o]+="%")):t[o]=c}(s.rotate||a.rotate)&&(t.rotate=Wt(s.rotate||0,a.rotate||0,r))}function Qm(t,s){return t[s]!==void 0?t[s]:t.borderRadius}const oC=Cp(0,.5,dh),cC=Cp(.5,.95,na);function Cp(t,s,a){return r=>r<t?0:r>s?1:a(vn(t,s,r))}function Jm(t,s){t.min=s.min,t.max=s.max}function ta(t,s){Jm(t.x,s.x),Jm(t.y,s.y)}function qm(t,s){t.translate=s.translate,t.scale=s.scale,t.originPoint=s.originPoint,t.origin=s.origin}function eu(t,s,a,r,n){return t-=s,t=fi(t,1/a,r),n!==void 0&&(t=fi(t,1/n,r)),t}function dC(t,s=0,a=1,r=.5,n,i=t,l=t){if(ja.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=eu(t.min,s,a,o,n),t.max=eu(t.max,s,a,o,n)}function tu(t,s,[a,r,n],i,l){dC(t,s[a],s[r],s[n],s.scale,i,l)}const mC=["x","scaleX","originX"],uC=["y","scaleY","originY"];function su(t,s,a,r){tu(t.x,s,mC,a?a.x:void 0,r?r.x:void 0),tu(t.y,s,uC,a?a.y:void 0,r?r.y:void 0)}function au(t){return t.translate===0&&t.scale===1}function Ap(t){return au(t.x)&&au(t.y)}function ru(t,s){return t.min===s.min&&t.max===s.max}function xC(t,s){return ru(t.x,s.x)&&ru(t.y,s.y)}function nu(t,s){return Math.round(t.min)===Math.round(s.min)&&Math.round(t.max)===Math.round(s.max)}function Sp(t,s){return nu(t.x,s.x)&&nu(t.y,s.y)}function iu(t){return Rs(t.x)/Rs(t.y)}function lu(t,s){return t.translate===s.translate&&t.scale===s.scale&&t.originPoint===s.originPoint}class hC{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 pC(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:c,rotate:m,rotateX:u,rotateY:x,skewX:p,skewY:g}=a;c&&(r=`perspective(${c}px) ${r}`),m&&(r+=`rotate(${m}deg) `),u&&(r+=`rotateX(${u}deg) `),x&&(r+=`rotateY(${x}deg) `),p&&(r+=`skewX(${p}deg) `),g&&(r+=`skewY(${g}deg) `)}const o=t.x.scale*s.x,d=t.y.scale*s.y;return(o!==1||d!==1)&&(r+=`scale(${o}, ${d})`),r||"none"}const wl=["","X","Y","Z"],gC=1e3;let fC=0;function Cl(t,s,a,r){const{latestValues:n}=s;n[t]&&(a[t]=n[t],s.setStaticValue(t,0),r&&(r[t]=0))}function Tp(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:s}=t.options;if(!s)return;const a=up(s);if(window.MotionHasOptimisedAnimation(a,"transform")){const{layout:n,layoutId:i}=t.options;window.MotionCancelOptimisedAnimation(a,"transform",Ut,!(n||i))}const{parent:r}=t;r&&!r.hasCheckedOptimisedAppear&&Tp(r)}function kp({attachResizeListener:t,defaultParent:s,measureScroll:a,checkIsScrollRoot:r,resetTransform:n}){return class{constructor(l={},o=s==null?void 0:s()){this.id=fC++,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(vC),this.nodes.forEach(CC),this.nodes.forEach(AC),this.nodes.forEach(jC)},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 d=0;d<this.path.length;d++)this.path[d].shouldResetTransform=!0;this.root===this&&(this.nodes=new rC)}addEventListener(l,o){return this.eventHandlers.has(l)||this.eventHandlers.set(l,new Ho),this.eventHandlers.get(l).add(o)}notifyListeners(l,...o){const d=this.eventHandlers.get(l);d&&d.notify(...o)}hasListeners(l){return this.eventHandlers.has(l)}mount(l){if(this.instance)return;this.isSVG=zh(l)&&!l1(l),this.instance=l;const{layoutId:o,layout:d,visualElement:c}=this.options;if(c&&!c.current&&c.mount(l),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(d||o)&&(this.isLayoutDirty=!0),t){let m,u=0;const x=()=>this.root.updateBlockedByResize=!1;Ut.read(()=>{u=window.innerWidth}),t(l,()=>{const p=window.innerWidth;p!==u&&(u=p,this.root.updateBlockedByResize=!0,m&&m(),m=nC(x,250),ti.hasAnimatedSinceResize&&(ti.hasAnimatedSinceResize=!1,this.nodes.forEach(du)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&c&&(o||d)&&this.addEventListener("didUpdate",({delta:m,hasLayoutChanged:u,hasRelativeLayoutChanged:x,layout:p})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const g=this.options.transition||c.getDefaultTransition()||DC,{onLayoutAnimationStart:y,onLayoutAnimationComplete:f}=c.getProps(),b=!this.targetLayout||!Sp(this.targetLayout,p),v=!u&&x;if(this.options.layoutRoot||this.resumeFrom||v||u&&(b||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const A={...ac(g,"layout"),onPlay:y,onComplete:f};(c.shouldReduceMotion||this.options.layoutRoot)&&(A.delay=0,A.type=!1),this.startAnimation(A),this.setAnimationOrigin(m,v)}else u||du(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=p})}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(),Ga(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(SC),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&&Tp(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let m=0;m<this.path.length;m++){const u=this.path[m];u.shouldResetTransform=!0,u.updateScroll("snapshot"),u.options.layoutRoot&&u.willUpdate(!1)}const{layoutId:o,layout:d}=this.options;if(o===void 0&&!d)return;const c=this.getTransformTemplate();this.prevTransformTemplateValue=c?c(this.latestValues,""):void 0,this.updateSnapshot(),l&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(ou);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(cu);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(wC),this.nodes.forEach(yC),this.nodes.forEach(bC)):this.nodes.forEach(cu),this.clearAllSnapshots();const o=Us.now();ys.delta=Ia(0,1e3/60,o-ys.timestamp),ys.timestamp=o,ys.isProcessing=!0,ul.update.process(ys),ul.preRender.process(ys),ul.render.process(ys),ys.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,nc.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(NC),this.sharedNodes.forEach(TC)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,Ut.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){Ut.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 d=0;d<this.path.length;d++)this.path[d].updateScroll();const l=this.layout;this.layout=this.measure(!1),this.layoutCorrected=Xt(),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 d=r(this.instance);this.scroll={animationId:this.root.animationId,phase:l,isRoot:d,offset:a(this.instance),wasRoot:this.scroll?this.scroll.isRoot:d}}}resetTransform(){if(!n)return;const l=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,o=this.projectionDelta&&!Ap(this.projectionDelta),d=this.getTransformTemplate(),c=d?d(this.latestValues,""):void 0,m=c!==this.prevTransformTemplateValue;l&&this.instance&&(o||dr(this.latestValues)||m)&&(n(this.instance,c),this.shouldResetTransform=!1,this.scheduleRender())}measure(l=!0){const o=this.measurePageBox();let d=this.removeElementScroll(o);return l&&(d=this.removeTransform(d)),PC(d),{animationId:this.root.animationId,measuredBox:o,layoutBox:d,latestValues:{},source:this.id}}measurePageBox(){var c;const{visualElement:l}=this.options;if(!l)return Xt();const o=l.measureViewportBox();if(!(((c=this.scroll)==null?void 0:c.wasRoot)||this.path.some(IC))){const{scroll:m}=this.root;m&&(Rr(o.x,m.offset.x),Rr(o.y,m.offset.y))}return o}removeElementScroll(l){var d;const o=Xt();if(ta(o,l),(d=this.scroll)!=null&&d.wasRoot)return o;for(let c=0;c<this.path.length;c++){const m=this.path[c],{scroll:u,options:x}=m;m!==this.root&&u&&x.layoutScroll&&(u.wasRoot&&ta(o,l),Rr(o.x,u.offset.x),Rr(o.y,u.offset.y))}return o}applyTransform(l,o=!1){const d=Xt();ta(d,l);for(let c=0;c<this.path.length;c++){const m=this.path[c];!o&&m.options.layoutScroll&&m.scroll&&m!==m.root&&Dr(d,{x:-m.scroll.offset.x,y:-m.scroll.offset.y}),dr(m.latestValues)&&Dr(d,m.latestValues)}return dr(this.latestValues)&&Dr(d,this.latestValues),d}removeTransform(l){const o=Xt();ta(o,l);for(let d=0;d<this.path.length;d++){const c=this.path[d];if(!c.instance||!dr(c.latestValues))continue;so(c.latestValues)&&c.updateSnapshot();const m=Xt(),u=c.measurePageBox();ta(m,u),su(o,c.latestValues,c.snapshot?c.snapshot.layoutBox:void 0,m)}return dr(this.latestValues)&&su(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!==ys.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 d=!!this.resumingFrom||this!==o;if(!(l||d&&this.isSharedProjectionDirty||this.isProjectionDirty||(x=this.parent)!=null&&x.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:m,layoutId:u}=this.options;if(!(!this.layout||!(m||u))){if(this.resolvedRelativeTargetAt=ys.timestamp,!this.targetDelta&&!this.relativeTarget){const p=this.getClosestProjectingParent();p&&p.layout&&this.animationProgress!==1?(this.relativeParent=p,this.forceRelativeParentToResolveTarget(),this.relativeTarget=Xt(),this.relativeTargetOrigin=Xt(),gn(this.relativeTargetOrigin,this.layout.layoutBox,p.layout.layoutBox),ta(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=Xt(),this.targetWithTransforms=Xt()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),O2(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):ta(this.target,this.layout.layoutBox),ip(this.target,this.targetDelta)):ta(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const p=this.getClosestProjectingParent();p&&!!p.resumingFrom==!!this.resumingFrom&&!p.options.layoutScroll&&p.target&&this.animationProgress!==1?(this.relativeParent=p,this.forceRelativeParentToResolveTarget(),this.relativeTarget=Xt(),this.relativeTargetOrigin=Xt(),gn(this.relativeTargetOrigin,this.target,p.target),ta(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||so(this.parent.latestValues)||np(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 d=!0;if((this.isProjectionDirty||(g=this.parent)!=null&&g.isProjectionDirty)&&(d=!1),o&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(d=!1),this.resolvedRelativeTargetAt===ys.timestamp&&(d=!1),d)return;const{layout:c,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||!(c||m))return;ta(this.layoutCorrected,this.layout.layoutBox);const u=this.treeScale.x,x=this.treeScale.y;X1(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=Xt());const{target:p}=l;if(!p){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(qm(this.prevProjectionDelta.x,this.projectionDelta.x),qm(this.prevProjectionDelta.y,this.projectionDelta.y)),pn(this.projectionDelta,this.layoutCorrected,p,this.latestValues),(this.treeScale.x!==u||this.treeScale.y!==x||!lu(this.projectionDelta.x,this.prevProjectionDelta.x)||!lu(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",p))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(l=!0){var o;if((o=this.options.visualElement)==null||o.scheduleRender(),l){const d=this.getStack();d&&d.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=Pr(),this.projectionDelta=Pr(),this.projectionDeltaWithTransform=Pr()}setAnimationOrigin(l,o=!1){const d=this.snapshot,c=d?d.latestValues:{},m={...this.latestValues},u=Pr();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!o;const x=Xt(),p=d?d.source:void 0,g=this.layout?this.layout.source:void 0,y=p!==g,f=this.getStack(),b=!f||f.members.length<=1,v=!!(y&&!b&&this.options.crossfade===!0&&!this.path.some(RC));this.animationProgress=0;let A;this.mixTargetDelta=w=>{const T=w/1e3;mu(u.x,l.x,T),mu(u.y,l.y,T),this.setTargetDelta(u),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(gn(x,this.layout.layoutBox,this.relativeParent.layout.layoutBox),kC(this.relativeTarget,this.relativeTargetOrigin,x,T),A&&xC(this.relativeTarget,A)&&(this.isProjectionDirty=!1),A||(A=Xt()),ta(A,this.relativeTarget)),y&&(this.animationValues=m,lC(m,c,this.latestValues,T,v,b)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=T},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(l){var o,d,c;this.notifyListeners("animationStart"),(o=this.currentAnimation)==null||o.stop(),(c=(d=this.resumingFrom)==null?void 0:d.currentAnimation)==null||c.stop(),this.pendingAnimation&&(Ga(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Ut.update(()=>{ti.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=Or(0)),this.currentAnimation=sC(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(gC),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const l=this.getLead();let{targetWithTransforms:o,target:d,layout:c,latestValues:m}=l;if(!(!o||!d||!c)){if(this!==l&&this.layout&&c&&Rp(this.options.animationType,this.layout.layoutBox,c.layoutBox)){d=this.target||Xt();const u=Rs(this.layout.layoutBox.x);d.x.min=l.target.x.min,d.x.max=d.x.min+u;const x=Rs(this.layout.layoutBox.y);d.y.min=l.target.y.min,d.y.max=d.y.min+x}ta(o,d),Dr(o,m),pn(this.projectionDeltaWithTransform,this.layoutCorrected,o,m)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new hC),this.sharedNodes.get(l).add(o);const c=o.options.initialPromotionConfig;o.promote({transition:c?c.transition:void 0,preserveFollowOpacity:c&&c.shouldPreserveFollowOpacity?c.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:d}={}){const c=this.getStack();c&&c.promote(this,d),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:d}=l;if((d.z||d.rotate||d.rotateX||d.rotateY||d.rotateZ||d.skewX||d.skewY)&&(o=!0),!o)return;const c={};d.z&&Cl("z",l,c,this.animationValues);for(let m=0;m<wl.length;m++)Cl(`rotate${wl[m]}`,l,c,this.animationValues),Cl(`skew${wl[m]}`,l,c,this.animationValues);l.render();for(const m in c)l.setStaticValue(m,c[m]),this.animationValues&&(this.animationValues[m]=c[m]);l.scheduleRender()}applyProjectionStyles(l,o){if(!this.instance||this.isSVG)return;if(!this.isVisible){l.visibility="hidden";return}const d=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,l.visibility="",l.opacity="",l.pointerEvents=ei(o==null?void 0:o.pointerEvents)||"",l.transform=d?d(this.latestValues,""):"none";return}const c=this.getLead();if(!this.projectionDelta||!this.layout||!c.target){this.options.layoutId&&(l.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,l.pointerEvents=ei(o==null?void 0:o.pointerEvents)||""),this.hasProjected&&!dr(this.latestValues)&&(l.transform=d?d({},""):"none",this.hasProjected=!1);return}l.visibility="";const m=c.animationValues||c.latestValues;this.applyTransformsToTarget();let u=pC(this.projectionDeltaWithTransform,this.treeScale,m);d&&(u=d(m,u)),l.transform=u;const{x,y:p}=this.projectionDelta;l.transformOrigin=`${x.origin*100}% ${p.origin*100}% 0`,c.animationValues?l.opacity=c===this?m.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:m.opacityExit:l.opacity=c===this?m.opacity!==void 0?m.opacity:"":m.opacityExit!==void 0?m.opacityExit:0;for(const g in Cn){if(m[g]===void 0)continue;const{correct:y,applyTo:f,isCSSVariable:b}=Cn[g],v=u==="none"?m[g]:y(m[g],c);if(f){const A=f.length;for(let w=0;w<A;w++)l[f[w]]=v}else b?this.options.visualElement.renderState.vars[g]=v:l[g]=v}this.options.layoutId&&(l.pointerEvents=c===this?ei(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(ou),this.root.sharedNodes.clear()}}}function yC(t){t.updateLayout()}function bC(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(u=>{const x=l?s.measuredBox[u]:s.layoutBox[u],p=Rs(x);x.min=r[u].min,x.max=x.min+p}):Rp(i,s.layoutBox,r)&&sa(u=>{const x=l?s.measuredBox[u]:s.layoutBox[u],p=Rs(r[u]);x.max=x.min+p,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[u].max=t.relativeTarget[u].min+p)});const o=Pr();pn(o,r,s.layoutBox);const d=Pr();l?pn(d,t.applyTransform(n,!0),s.measuredBox):pn(d,r,s.layoutBox);const c=!Ap(o);let m=!1;if(!t.resumeFrom){const u=t.getClosestProjectingParent();if(u&&!u.resumeFrom){const{snapshot:x,layout:p}=u;if(x&&p){const g=Xt();gn(g,s.layoutBox,x.layoutBox);const y=Xt();gn(y,r,p.layoutBox),Sp(g,y)||(m=!0),u.options.layoutRoot&&(t.relativeTarget=y,t.relativeTargetOrigin=g,t.relativeParent=u)}}}t.notifyListeners("didUpdate",{layout:r,snapshot:s,delta:d,layoutDelta:o,hasLayoutChanged:c,hasRelativeLayoutChanged:m})}else if(t.isLead()){const{onExitComplete:r}=t.options;r&&r()}t.options.transition=void 0}function vC(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 jC(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function NC(t){t.clearSnapshot()}function ou(t){t.clearMeasurements()}function cu(t){t.isLayoutDirty=!1}function wC(t){const{visualElement:s}=t.options;s&&s.getProps().onBeforeLayoutMeasure&&s.notify("BeforeLayoutMeasure"),t.resetTransform()}function du(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function CC(t){t.resolveTargetDelta()}function AC(t){t.calcProjection()}function SC(t){t.resetSkewAndRotation()}function TC(t){t.removeLeadSnapshot()}function mu(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 uu(t,s,a,r){t.min=Wt(s.min,a.min,r),t.max=Wt(s.max,a.max,r)}function kC(t,s,a,r){uu(t.x,s.x,a.x,r),uu(t.y,s.y,a.y,r)}function RC(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const DC={duration:.45,ease:[.4,0,.1,1]},xu=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),hu=xu("applewebkit/")&&!xu("chrome/")?Math.round:na;function pu(t){t.min=hu(t.min),t.max=hu(t.max)}function PC(t){pu(t.x),pu(t.y)}function Rp(t,s,a){return t==="position"||t==="preserve-aspect"&&!L2(iu(s),iu(a),.2)}function IC(t){var s;return t!==t.root&&((s=t.scroll)==null?void 0:s.wasRoot)}const EC=kp({attachResizeListener:(t,s)=>An(t,"resize",s),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Al={current:void 0},Dp=kp({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!Al.current){const t=new EC({});t.mount(window),t.setOptions({layoutScroll:!0}),Al.current=t}return Al.current},resetTransform:(t,s)=>{t.style.transform=s!==void 0?s:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),FC={pan:{Feature:J2},drag:{Feature:Q2,ProjectionNode:Dp,MeasureLayout:Np}};function gu(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&&Ut.postRender(()=>i(s,Mn(s)))}class MC extends Xa{mount(){const{current:s}=this.node;s&&(this.unmount=s1(s,(a,r)=>(gu(this.node,r,"Start"),n=>gu(this.node,n,"End"))))}unmount(){}}class _C extends Xa{constructor(){super(...arguments),this.isActive=!1}onFocus(){let s=!1;try{s=this.node.current.matches(":focus-visible")}catch{s=!0}!s||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=In(An(this.node.current,"focus",()=>this.onFocus()),An(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function fu(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&&Ut.postRender(()=>i(s,Mn(s)))}class LC extends Xa{mount(){const{current:s}=this.node;s&&(this.unmount=i1(s,(a,r)=>(fu(this.node,r,"Start"),(n,{success:i})=>fu(this.node,n,i?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const co=new WeakMap,Sl=new WeakMap,OC=t=>{const s=co.get(t.target);s&&s(t)},$C=t=>{t.forEach(OC)};function UC({root:t,...s}){const a=t||document;Sl.has(a)||Sl.set(a,{});const r=Sl.get(a),n=JSON.stringify(s);return r[n]||(r[n]=new IntersectionObserver($C,{root:t,...s})),r[n]}function BC(t,s,a){const r=UC(s);return co.set(t,a),r.observe(t),()=>{co.delete(t),r.unobserve(t)}}const VC={some:0,all:1};class zC extends Xa{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:s={}}=this.node.getProps(),{root:a,margin:r,amount:n="some",once:i}=s,l={root:a?a.current:void 0,rootMargin:r,threshold:typeof n=="number"?n:VC[n]},o=d=>{const{isIntersecting:c}=d;if(this.isInView===c||(this.isInView=c,i&&!c&&this.hasEnteredView))return;c&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",c);const{onViewportEnter:m,onViewportLeave:u}=this.node.getProps(),x=c?m:u;x&&x(d)};return BC(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(HC(s,a))&&this.startObserver()}unmount(){}}function HC({viewport:t={}},{viewport:s={}}={}){return a=>t[a]!==s[a]}const WC={inView:{Feature:zC},tap:{Feature:LC},focus:{Feature:_C},hover:{Feature:MC}},GC={layout:{ProjectionNode:Dp,MeasureLayout:Np}},KC={...P2,...WC,...FC,...GC},gs=K1(KC,i2),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:ls,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:tx,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 YC({open:t,onClose:s,onSelectTemplate:a}){var c,m,u;const[r,n]=h.useState(null),[i,l]=h.useState(!1);h.useEffect(()=>{const x=at.getUserData();l((x==null?void 0:x.jobTitle)==="Dealer")},[]);const o=x=>{if(i)return;const p=nn.find(g=>g.id===x);p!=null&&p.disabled||n(x)},d=()=>{r&&(a(r),s())};return e.jsx(mt,{open:t,onOpenChange:s,children:e.jsxs(ot,{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(ct,{className:"sr-only",children:"Select a Template"}),e.jsx(It,{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(Js,{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(gs.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(Ai,{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,p)=>{const g=x.icon,y=r===x.id,f=i||x.disabled;return e.jsx(gs.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:p*.1},whileHover:f?{}:{scale:1.03},whileTap:f?{}:{scale:.98},children:e.jsxs(te,{className:`h-full transition-all duration-300 border-2 ${f?"opacity-50 cursor-not-allowed border-gray-200":y?"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(ue,{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"})}),y&&e.jsx(gs.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(Vr,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsx(xe,{className:"text-xl mb-2",children:x.name}),e.jsx(ke,{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(Ge,{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(Ge,{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(ne,{variant:"secondary",className:"text-xs",children:x.category})}),e.jsx(Gt,{}),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(Xe,{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(Vt,{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((b,v)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-600",children:[e.jsx(De,{className:"w-3 h-3 text-green-600 flex-shrink-0"}),e.jsx("span",{children:b})]},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(gs.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:d,disabled:!r||i||((c=nn.find(x=>x.id===r))==null?void 0:c.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(ds,{className:"w-4 h-4"})]})]}),e.jsx(oc,{children:r&&e.jsx(gs.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:(u=nn.find(x=>x.id===r))==null?void 0:u.name})]})})})]})})]})})}function Xr({fileName:t,fileType:s,fileUrl:a,fileSize:r,attachmentId:n,onDownload:i,open:l,onClose:o}){const[d,c]=h.useState(100),[m,u]=h.useState(0),[x,p]=h.useState(null),[g,y]=h.useState(!1),[f,b]=h.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"),A=s.toLowerCase().includes("pdf"),w=v||A;h.useEffect(()=>{if(!l||!w||!a){p(null);return}return(async()=>{y(!0),b(null);try{let R=a;a.startsWith("/")&&!a.startsWith("//")&&(R=`${window.location.origin}${a}`);const E=await fetch(R,{headers:{Accept:A?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!E.ok){const C=await E.text().catch(()=>"");throw new Error(`Failed to load file: ${E.status} ${E.statusText}. ${C}`)}const M=await E.blob();if(M.size===0)throw new Error("File is empty or could not be loaded");A&&!M.type.includes("pdf")&&M.type!=="application/octet-stream"&&console.warn(`Expected PDF but got ${M.type}`);const B=window.URL.createObjectURL(M);p(B)}catch(N){console.error("Failed to load file for preview:",N),b(N instanceof Error?N.message:"Failed to load file for preview")}finally{y(!1)}})(),()=>{x&&(window.URL.revokeObjectURL(x),p(null))}},[l,a,w,A]);const T=async()=>{if(i&&n)try{await i(n)}catch{alert("Failed to download file")}},k=()=>c(S=>Math.min(S+25,200)),L=()=>c(S=>Math.max(S-25,50)),D=()=>u(S=>(S+90)%360);return e.jsx(mt,{open:l,onOpenChange:o,children:e.jsx(ot,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(ut,{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(ht,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(ct,{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:L,disabled:d<=50,title:"Zoom out",className:"h-8 w-8 p-0",children:e.jsx(r0,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs sm:text-sm text-gray-600 min-w-[3rem] text-center",children:[d,"%"]}),e.jsx(F,{variant:"ghost",size:"sm",onClick:k,disabled:d>=200,title:"Zoom in",className:"h-8 w-8 p-0",children:e.jsx(n0,{className:"h-4 w-4"})}),e.jsx(F,{variant:"ghost",size:"sm",onClick:D,title:"Rotate",className:"h-8 w-8 p-0",children:e.jsx(sx,{className:"h-4 w-4"})})]}),i&&n&&e.jsxs(F,{variant:"outline",size:"sm",onClick:T,className:"gap-2 h-9",children:[e.jsx(Nt,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Download"})]})]})]})}),e.jsx("div",{className:"file-preview-body bg-gray-100 rounded-lg p-2 sm:p-4",children:g?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full",children:[e.jsx(Ze,{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:T,className:"gap-2",children:[e.jsx(Nt,{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(${d/100}) rotate(${m}deg)`,transition:"transform 0.2s ease-in-out",maxWidth:"100%",maxHeight:"100%",objectFit:"contain"},className:"rounded-lg shadow-lg"})}),A&&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:()=>{b("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(ht,{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:T,className:"gap-2",children:[e.jsx(Nt,{className:"h-4 w-4"}),"Download ",t]})]})})]})})})}function _n({open:t,onClose:s,violations:a,policyDetails:r}){return e.jsx(mt,{open:t,onOpenChange:s,children:e.jsxs(ot,{className:"sm:max-w-lg",children:[e.jsxs(ut,{children:[e.jsxs(ct,{className:"flex items-center gap-2",children:[e.jsx(Ge,{className:"w-5 h-5 text-red-600"}),"Policy Violation"]}),e.jsx(It,{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(Tt,{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 Ne.get("/users/configurations",{params:s})).data.data},Hi=async t=>{const s=t?{category:t}:{};return(await Ne.get("/admin/configurations",{params:s})).data.data},Ss=async(t,s)=>{await Ne.put(`/admin/configurations/${t}`,{configValue:s})},ZC=async t=>{await Ne.post(`/admin/configurations/${t}/reset`)},XC=async t=>{const s=t?{year:t}:{};return(await Ne.get("/admin/holidays",{params:s})).data.data},QC=async t=>(await Ne.post("/admin/holidays",t)).data.data,JC=async(t,s)=>(await Ne.put(`/admin/holidays/${t}`,s)).data.data,qC=async t=>{await Ne.delete(`/admin/holidays/${t}`)},eA=async()=>(await Ne.get("/config/activity-types")).data.data,tA=async t=>{const s={activeOnly:t.toString()};return(await Ne.get("/admin/activity-types",{params:s})).data.data},sA=async t=>(await Ne.post("/admin/activity-types",t)).data.data,aA=async(t,s)=>(await Ne.put(`/admin/activity-types/${t}`,s)).data.data,rA=async t=>{await Ne.delete(`/admin/activity-types/${t}`)},nA={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 iA(t,s,a){const[r,n]=h.useState(nA),[i,l]=h.useState(null),[o,d]=h.useState(t),[c,m]=h.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[u,x]=h.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[p,g]=h.useState([]);return h.useEffect(()=>{(async()=>{var b;try{const v=await Qs("DOCUMENT_POLICY"),A={};v.forEach(P=>{A[P.configKey]=P.configValue});const w=parseInt(A.MAX_FILE_SIZE_MB||"10"),k=(A.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(P=>P.trim().toLowerCase());x({maxFileSizeMB:w,allowedFileTypes:k});const L=await Qs("SYSTEM_SETTINGS"),D=await Qs("WORKFLOW_SHARING"),S=[...L,...D],N={};S.forEach(P=>{N[P.configKey]=P.configValue}),m({maxApprovalLevels:parseInt(N.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(N.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((b=N.ALLOW_ADD_SPECTATOR)==null?void 0:b.toLowerCase())==="true",maxSpectators:parseInt(N.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(v){console.error("Failed to load policies:",v)}})()},[]),h.useEffect(()=>{if(!t||!s)return;let f=!0;return(async()=>{try{d(!0);const b=await ws(s);if(!f||!b)return;const v=b.workflow||{},A=Array.isArray(b.approvals)?b.approvals:[],w=Array.isArray(b.participants)?b.participants:[],T=Array.isArray(b.documents)?b.documents.filter(R=>!R.isDeleted):[];g(T);const k=(v.priority||"").toString().toLowerCase(),L={standard:"standard",express:"express"},D=v.templateType==="TEMPLATE"?"existing-template":"custom",S=a.find(R=>R.id===D)||a[0]||null;l(S);const N=A.sort((R,O)=>(R.levelNumber||0)-(O.levelNumber||0)).map(R=>{const O=Number(R.tatHours||24),E=Math.floor(O/24),M=O%24;return{id:R.approverId||`temp-${R.levelNumber}`,name:R.approverName||R.approverEmail||"",email:R.approverEmail||"",role:R.levelName||`Level ${R.levelNumber}`,department:"",avatar:(R.approverName||R.approverEmail||"XX").substring(0,2).toUpperCase(),level:R.levelNumber||1,canClose:!1,tat:E>0?E:M,tatType:E>0?"days":"hours",userId:R.approverId}}),P=w.filter(R=>(R.participantType||R.participant_type||"").toString().toUpperCase().trim()==="SPECTATOR"?!!(R.userEmail||R.user_email||R.email):!1).map((R,O)=>{const E=R.userId||R.user_id||R.id,M=R.userName||R.user_name||R.name||"",B=R.userEmail||R.user_email||R.email||"",j=(M||B||"XX").split(" ").map(U=>U[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{id:E||`spectator-${s}-${O}-${Date.now()}`,userId:E,name:M||B||"Spectator",email:B,role:"Spectator",department:R.department||"",avatar:j,level:1,canClose:!1}});n(R=>({...R,template:D,title:v.title||"",description:v.description||"",priority:L[k]||"standard",approvers:N,approverCount:N.length||1,spectators:P,maxLevel:Math.max(...N.map(O=>O.level||1),1)}))}catch(b){console.error("Failed to load draft:",b)}finally{f&&d(!1)}})(),()=>{f=!1}},[t,s,a]),{formData:r,setFormData:n,updateFormData:(f,b)=>{n(v=>({...v,[f]:b}))},selectedTemplate:i,setSelectedTemplate:l,loadingDraft:o,systemPolicy:c,documentPolicy:u,existingDocuments:p,setExistingDocuments:g}}const yu=["Template Selection","Basic Information","Approval Workflow","Participants & Access","Documents & Attachments","Review & Submit"];function lA(t,s,a){const[r,n]=h.useState(t?2:1),i=yu.length,l=u=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(u),o=()=>{switch(r){case 1:return s!==null;case 2:return a.title.trim()!==""&&a.description.trim()!==""&&a.priority!=="";case 3:return(a.approverCount||1)>0&&a.approvers.length===(a.approverCount||1)&&a.approvers.every(u=>{if(!u||!u.email||!l(u.email))return!1;if(!u.userId)return!0;const x=u.tatType||"hours";return x==="hours"?u.tat&&u.tat>0&&u.tat<=720:x==="days"?u.tat&&u.tat>0&&u.tat<=30:!1});case 4:return!0;case 5:return!0;case 6:return!0;default:return!1}};return{currentStep:r,setCurrentStep:n,totalSteps:i,stepNames:yu,isStepValid:o,nextStep:()=>{o()&&(window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}),r<i&&n(r+1))},prevStep:()=>{r>1&&(n(r-1),window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}))},goToStep:u=>{u>=1&&u<=i&&n(u)},validateEmail:l}}function oA(){const[t,s]=h.useState({open:!1,type:"error",email:"",message:""}),[a,r]=h.useState({open:!1,violations:[]}),[n,i]=h.useState({open:!1,errors:[]});return{validationModal:t,policyViolationModal:a,documentErrorModal:n,openValidationModal:(x,p,g="")=>{s({open:!0,type:x,email:p,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 cA(t,s){const a=typeof t=="number"?t:parseInt(String(t))||0;return s==="days"?a*24:a||24}function dA(t,s,a){var n;const r=cA(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 mA(t,s){return t.slice(0,s).map((a,r)=>{const n=r+1;return dA(a,n,n===s)})}function bu(t,s,a){const r=new Set((t.approvers||[]).map(i=>{var l;return(l=i==null?void 0:i.email)==null?void 0:l.toLowerCase()}).filter(Boolean)),n=(t.spectators||[]).filter(i=>(i==null?void 0:i.email)&&!r.has(i.email.toLowerCase()));return{templateId:(s==null?void 0:s.id)||null,templateType:(s==null?void 0:s.id)==="custom"?"CUSTOM":"TEMPLATE",title:t.title,description:t.description,priorityUi:t.priority==="express"?"express":"standard",approverCount:t.approverCount||1,approvers:(t.approvers||[]).map(i=>({userId:(i==null?void 0:i.userId)||"",email:(i==null?void 0:i.email)||"",name:i==null?void 0:i.name,tat:(i==null?void 0:i.tat)||"",tatType:(i==null?void 0:i.tatType)||"hours"})),spectators:n.map(i=>({userId:(i==null?void 0:i.userId)||"",name:(i==null?void 0:i.name)||"",email:(i==null?void 0:i.email)||""})),ccList:[],participants:[]}}function vu(t,s,a){const r=mA(t.approvers||[],t.approverCount||1);return{title:t.title,description:t.description,priority:t.priority==="express"?"EXPRESS":"STANDARD",approvalLevels:r,participants:[],deleteDocumentIds:a.length>0?a:void 0}}function uA(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 Pp(t,s){return{id:(await Vx(t,s||[],"SUPPORTING")).id}}async function Ip(t,s,a,r){const n=a&&a.length>0,i=r.length>0;n||i?await sN(t,s,a||[],r):await tN(t,s)}async function Ep(t){await Kx(t)}async function xA(t,s){const a=await Pp(t,s);return await Ep(a.id),a}async function hA(t,s,a,r){await Ip(t,s,a,r),await Ep(t)}function pA({formData:t,selectedTemplate:s,documents:a,documentsToDelete:r,user:n,isEditing:i,editRequestId:l,onSubmit:o}){const[d,c]=h.useState(!1),[m,u]=h.useState(!1);return{submitting:d,savingDraft:m,handleSubmit:async()=>{var y,f;if(d||m)return;const g=uA(t.approvers||[],t.approverCount||1);if(!g.valid){alert(g.message);return}c(!0);try{if(i&&l){const b=vu(t,n,r);await hA(l,b,a,r),Q.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 b=bu(t,s,n),v=await xA(b,a);Q.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(b){console.error("Failed to submit workflow:",b),Q.error("Failed to Submit Request",{description:((f=(y=b==null?void 0:b.response)==null?void 0:y.data)==null?void 0:f.message)||(b==null?void 0:b.message)||"An error occurred while submitting the request.",duration:5e3}),c(!1)}},handleSaveDraft:async()=>{var g,y;if(!(!s||!t.title.trim()||!t.description.trim()||!t.priority)&&!(d||m)){u(!0);try{if(i&&l){const f=vu(t,n,r);await Ip(l,f,a,r),Q.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),b=await Pp(f,a);Q.success("Draft Saved Successfully!",{description:`Your request "${t.title}" has been saved as draft.`,duration:5e3}),o==null||o({...t,backendId:b.id,template:s})}}catch(f){console.error("Failed to save draft:",f),Q.error("Failed to Save Draft",{description:((y=(g=f==null?void 0:f.response)==null?void 0:g.data)==null?void 0:y.message)||(f==null?void 0:f.message)||"An error occurred while saving the draft.",duration:5e3}),u(!1)}}}}}async function oa(t,s=10){return await Ne.get("/users/search",{params:{q:t,limit:s}})}async function ia(t){var a;const s=await Ne.post("/users/ensure",t);return((a=s.data)==null?void 0:a.data)||s.data}async function gA(t,s){return await Ne.post("/admin/users/assign-role",{email:t,role:s})}async function fA(t,s){return await Ne.put(`/admin/users/${t}/role`,{role:s})}async function yA(t,s=1,a=10){return await Ne.get("/admin/users/by-role",{params:{role:t||"ELEVATED",page:s,limit:a}})}async function bA(){return await Ne.get("/admin/users/role-statistics")}async function vA(){var s,a;return((a=(s=(await Ne.get("/users")).data)==null?void 0:s.data)==null?void 0:a.users)||[]}const Ws={searchUsers:oa,ensureUserExists:ia,assignRole:gA,updateUserRole:fA,getUsersByRole:yA,getRoleStatistics:bA,getAllUsers:vA};async function jA(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 oa(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 ia({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 NA(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 jA(l,s);if(!o.success)return{success:!1,error:o.error};try{const m=(((n=(await oa(l.email,1)).data)==null?void 0:n.data)||[])[0];if(m){const u=await ia({userId:m.userId,email:m.email,displayName:m.displayName,firstName:m.firstName,lastName:m.lastName,department:m.department,phone:m.phone,mobilePhone:m.mobilePhone,designation:m.designation,jobTitle:m.jobTitle,manager:m.manager,employeeId:m.employeeId,employeeNumber:m.employeeNumber,secondEmail:m.secondEmail,location:m.location});r[i]={...l,userId:u.userId,name:u.displayName||l.name,department:u.department||l.department,avatar:(u.displayName||u.email).substring(0,2).toUpperCase()}}}catch(d){console.error(`Failed to update approver ${l.email}:`,d)}}return{success:!0,validatedApprovers:r}}function wA({selectedTemplate:t,setSelectedTemplate:s,updateFormData:a,formData:r,currentStep:n,isStepValid:i,wizardNextStep:l,wizardPrevStep:o,user:d,openValidationModal:c,systemPolicy:m,onPolicyViolation:u,onSubmit:x}){const p=Fa(),[g,y]=h.useState(!1),[f,b]=h.useState(null);return{showTemplateModal:g,setShowTemplateModal:y,previewDocument:f,selectTemplate:D=>{s(D),a("template",D.id),a("category",D.category),a("priority",D.priority);const S=new Date;S.setDate(S.getDate()+D.suggestedSLA),a("slaEndDate",S)},handleTemplateSelection:D=>{D==="claim-management"?p("/claim-management"):D==="vendor-payment"?p("/vendor-payment"):x&&x({templateType:D})},nextStep:async()=>{var D;if(i()){if(n===1&&(t==null?void 0:t.id)==="existing-template"){y(!0);return}if(window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}),n===3){if(m&&u){const P=r.approverCount||1;if(P>m.maxApprovalLevels){u([{type:"Maximum Approval Levels Exceeded",message:`The request has ${P} approval levels, which exceeds the maximum allowed (${m.maxApprovalLevels}). Please reduce the number of approvers.`,currentValue:P,maxValue:m.maxApprovalLevels}]);return}}const S=((D=d==null?void 0:d.email)==null?void 0:D.toLowerCase())||"",N=await NA(r.approvers,S);if(!N.success&&N.error){c(N.error.type,N.error.email,N.error.message);return}N.validatedApprovers&&a("approvers",N.validatedApprovers)}l()}},prevStep:()=>{o(),window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"})},handlePreviewDocument:(D,S)=>{if(S){const N=D.documentId||D.document_id||"";b({fileName:D.originalFileName||D.fileName||"Document",fileType:D.fileType||D.file_type||"application/octet-stream",fileUrl:Gr(N),fileSize:Number(D.fileSize||D.file_size||0),documentId:N})}else{const N=URL.createObjectURL(D);b({fileName:D.name,fileType:D.type||"application/octet-stream",fileUrl:N,fileSize:D.size,file:D})}},closePreview:()=>{f!=null&&f.fileUrl&&(f!=null&&f.file)&&URL.revokeObjectURL(f.fileUrl),b(null)}}}const ju=[{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:Si,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:Pe,estimatedTime:"1-2 days",commonApprovers:["Department Head","Manager"],suggestedSLA:2,priority:"medium",fields:{timeline:!0}}];function CA({currentStep:t,totalSteps:s,stepNames:a}){const r=Math.round(t/s*100);return e.jsx("div",{className:"bg-white border-b border-gray-200 px-3 sm:px-6 py-2 sm:py-3 flex-shrink-0","data-testid":"wizard-stepper",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"block sm:hidden","data-testid":"wizard-stepper-mobile",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-green-600 text-white flex items-center justify-center text-xs font-semibold","data-testid":"wizard-stepper-mobile-current-step",children:t}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-900","data-testid":"wizard-stepper-mobile-step-name",children:a[t-1]}),e.jsxs("p",{className:"text-xs text-gray-600","data-testid":"wizard-stepper-mobile-step-info",children:["Step ",t," of ",s]})]})]}),e.jsx("div",{className:"text-right",children:e.jsxs("p",{className:"text-xs font-medium text-green-600","data-testid":"wizard-stepper-mobile-progress",children:[r,"%"]})})]}),e.jsx("div",{className:"w-full bg-gray-200 h-1.5 rounded-full overflow-hidden","data-testid":"wizard-stepper-mobile-progress-bar",children:e.jsx("div",{className:"bg-green-600 h-full transition-all duration-300",style:{width:`${r}%`},"data-testid":"wizard-stepper-mobile-progress-fill"})})]}),e.jsxs("div",{className:"hidden sm:block","data-testid":"wizard-stepper-desktop",children:[e.jsx("div",{className:"flex items-center justify-between mb-2","data-testid":"wizard-stepper-desktop-steps",children:a.map((n,i)=>e.jsxs("div",{className:"flex items-center","data-testid":`wizard-stepper-desktop-step-${i+1}`,children:[e.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center text-xs font-semibold ${i+1<t?"bg-green-600 text-white":i+1===t?"bg-blue-600 text-white":"bg-gray-200 text-gray-600"}`,"data-testid":`wizard-stepper-desktop-step-${i+1}-indicator`,children:i+1<t?e.jsx(Vr,{className:"w-4 h-4"}):i+1}),i<a.length-1&&e.jsx("div",{className:`w-8 md:w-12 lg:w-16 h-1 mx-1 md:mx-2 ${i+1<t?"bg-green-600":"bg-gray-200"}`,"data-testid":`wizard-stepper-desktop-step-${i+1}-connector`})]},i))}),e.jsx("div",{className:"hidden lg:flex justify-between text-xs text-gray-600 mt-2","data-testid":"wizard-stepper-desktop-labels",children:a.map((n,i)=>e.jsx("span",{className:`${i+1===t?"font-semibold text-blue-600":""}`,"data-testid":`wizard-stepper-desktop-label-${i+1}`,children:n},i))})]})]})})}function AA({currentStep:t,totalSteps:s,isStepValid:a,onPrev:r,onNext:n,onSubmit:i,onSaveDraft:l,submitting:o,savingDraft:d,loadingDraft:c,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(Js,{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:c||o||d,"data-testid":"wizard-footer-save-draft-button",children:d?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{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||c||o||d,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(Ze,{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(ax,{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(ds,{className:"h-3 w-3 sm:h-4 sm:w-4 ml-1 sm:ml-2"})]})]})]})})}const SA=t=>{switch(t){case"high":return e.jsx(pa,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(Vt,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(Ks,{className:"w-4 h-4 text-green-600"});default:return e.jsx(Vt,{className:"w-4 h-4 text-gray-600"})}};function TA({templates:t,selectedTemplate:s,onSelectTemplate:a}){return e.jsxs(gs.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"min-h-full flex flex-col items-center justify-center py-8","data-testid":"template-selection-step",children:[e.jsxs("div",{className:"text-center mb-12 max-w-3xl","data-testid":"template-selection-header",children:[e.jsx("h1",{className:"text-4xl lg:text-5xl font-bold text-gray-900 mb-4","data-testid":"template-selection-title",children:"Choose Your Request Type"}),e.jsx("p",{className:"text-lg text-gray-600","data-testid":"template-selection-description",children:"Start with a pre-built template for faster approvals, or create a custom request tailored to your needs."})]}),e.jsx("div",{className:"w-full max-w-6xl grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8","data-testid":"template-selection-grid",children:t.map(r=>e.jsx(gs.div,{whileHover:{scale:1.03},whileTap:{scale:.98},transition:{type:"spring",stiffness:300,damping:20},"data-testid":`template-card-${r.id}`,children:e.jsxs(te,{className:`cursor-pointer h-full transition-all duration-300 border-2 ${(s==null?void 0:s.id)===r.id?"border-blue-500 shadow-xl bg-blue-50/50 ring-2 ring-blue-200":"border-gray-200 hover:border-blue-300 hover:shadow-lg"}`,onClick:()=>a(r),"data-testid":`template-card-${r.id}-clickable`,children:[e.jsxs(ue,{className:"space-y-4 pb-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("div",{className:`w-14 h-14 rounded-xl flex items-center justify-center ${(s==null?void 0:s.id)===r.id?"bg-blue-100":"bg-gray-100"}`,"data-testid":`template-card-${r.id}-icon`,children:e.jsx(r.icon,{className:`w-7 h-7 ${(s==null?void 0:s.id)===r.id?"text-blue-600":"text-gray-600"}`})}),(s==null?void 0:s.id)===r.id&&e.jsx(gs.div,{initial:{scale:0},animate:{scale:1},transition:{type:"spring",stiffness:500,damping:15},"data-testid":`template-card-${r.id}-selected-indicator`,children:e.jsx("div",{className:"w-8 h-8 rounded-full bg-blue-600 flex items-center justify-center",children:e.jsx(Vr,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsx(xe,{className:"text-xl mb-2","data-testid":`template-card-${r.id}-name`,children:r.name}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ne,{variant:"secondary",className:"text-xs","data-testid":`template-card-${r.id}-category`,children:r.category}),SA(r.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-${r.id}-description`,children:r.description}),e.jsx(Gt,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1.5","data-testid":`template-card-${r.id}-estimated-time`,children:[e.jsx(Xe,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:r.estimatedTime})]}),e.jsxs("div",{className:"flex items-center gap-1.5","data-testid":`template-card-${r.id}-approvers-count`,children:[e.jsx($t,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[r.commonApprovers.length," approvers"]})]})]})]})]})},r.id))})]})}function _e({className:t,type:s,...a}){return e.jsx("input",{type:s,"data-slot":"input",className:Re("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 kA({className:t,...s}){return e.jsx(uf,{"data-slot":"radio-group",className:Re("grid gap-3",t),...s})}function Nu({className:t,...s}){return e.jsx(xf,{"data-slot":"radio-group-item",className:Re("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(hf,{"data-slot":"radio-group-indicator",className:"relative flex items-center justify-center",children:e.jsx(i0,{className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}function RA({formData:t,selectedTemplate:s,updateFormData:a}){return e.jsxs(gs.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(Pe,{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(le,{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(_e,{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(le,{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($i,{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(le,{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(kA,{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(Nu,{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(wi,{className:"w-4 h-4 text-red-600"}),e.jsx(le,{htmlFor:"express",className:"font-medium text-red-900 cursor-pointer",children:"Express"}),e.jsx(ne,{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(Nu,{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(Xe,{className:"w-4 h-4 text-blue-600"}),e.jsx(le,{htmlFor:"standard",className:"font-medium text-blue-900 cursor-pointer",children:"Standard"}),e.jsx(ne,{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(le,{htmlFor:"amount",className:"text-base font-semibold",children:"Budget Amount"}),e.jsx(_e,{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(le,{className:"text-base font-semibold",children:"Currency"}),e.jsxs(Ve,{value:t.currency,onValueChange:r=>a("currency",r),"data-testid":"basic-information-currency-select",children:[e.jsx(He,{className:"h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm",children:e.jsx(ze,{})}),e.jsxs(We,{children:[e.jsx(K,{value:"USD",children:"USD ($)"}),e.jsx(K,{value:"EUR",children:"EUR (€)"}),e.jsx(K,{value:"GBP",children:"GBP (£)"}),e.jsx(K,{value:"INR",children:"INR (₹)"})]})]})]})]}),(s==null?void 0:s.fields.vendor)&&e.jsxs("div",{"data-testid":"basic-information-vendor-field",children:[e.jsx(le,{htmlFor:"vendor",className:"text-base font-semibold",children:"Vendor/Supplier"}),e.jsx(_e,{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(le,{htmlFor:"costCenter",className:"text-base font-semibold",children:"Cost Center"}),e.jsx(_e,{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(le,{htmlFor:"project",className:"text-base font-semibold",children:"Related Project"}),e.jsx(_e,{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 DA(){const[t,s]=h.useState([]),[a,r]=h.useState(!1),n=h.useRef(null);return{searchResults:t,searchLoading:a,searchUsersDebounced:async(d,c=10)=>{if(n.current&&clearTimeout(n.current),!d||!d.startsWith("@")||d.length<2){s([]),r(!1);return}r(!0),n.current=setTimeout(async()=>{var m;try{const u=d.slice(1),p=((m=(await oa(u,c)).data)==null?void 0:m.data)||[];s(p)}catch(u){console.error("User search failed:",u),s([])}finally{r(!1)}},300)},clearSearch:()=>{n.current&&clearTimeout(n.current),s([]),r(!1)},ensureUser:async d=>{try{return await ia({userId:d.userId,email:d.email,displayName:d.displayName,firstName:d.firstName,lastName:d.lastName,department:d.department,phone:d.phone,mobilePhone:d.mobilePhone,designation:d.designation,jobTitle:d.jobTitle,manager:d.manager,employeeId:d.employeeId,employeeNumber:d.employeeNumber,secondEmail:d.secondEmail,location:d.location})}catch(c){throw console.error("Failed to ensure user exists:",c),c}}}}function Fp(){const[t,s]=h.useState({}),[a,r]=h.useState({}),n=h.useRef({});return{userSearchResults:t,userSearchLoading:a,searchUsersForIndex:async(o,d,c=10)=>{if(n.current[o]&&clearTimeout(n.current[o]),!d||!d.startsWith("@")||d.length<2){s(m=>({...m,[o]:[]})),r(m=>({...m,[o]:!1}));return}r(m=>({...m,[o]:!0})),n.current[o]=setTimeout(async()=>{var m;try{const u=d.slice(1),p=((m=(await oa(u,c)).data)==null?void 0:m.data)||[];s(g=>({...g,[o]:p}))}catch(u){console.error(`User search failed for index ${o}:`,u),s(x=>({...x,[o]:[]}))}finally{r(u=>({...u,[o]:!1}))}},300)},clearSearchForIndex:o=>{n.current[o]&&clearTimeout(n.current[o]),s(d=>({...d,[o]:[]})),r(d=>({...d,[o]:!1}))}}}function PA({formData:t,updateFormData:s,onValidationError:a,systemPolicy:r,onPolicyViolation:n}){var u;const{userSearchResults:i,userSearchLoading:l,searchUsersForIndex:o,clearSearchForIndex:d}=Fp();h.useEffect(()=>{const x=t.approverCount||1,p=t.approvers||[];if(p.length<x){const g=[...p];for(let y=p.length;y<x;y++)g[y]||(g[y]={email:"",name:"",level:y+1,tat:""});s("approvers",g)}else p.length>x&&s("approvers",p.slice(0,x))},[t.approverCount,s]);const c=(x,p)=>{var b,v,A,w,T;const g=[...t.approvers],f=((b=g[x])==null?void 0:b.email)!==p;if(g[x]={...g[x],email:p,level:x+1,userId:f||(v=g[x])==null?void 0:v.userId,name:f||(A=g[x])==null?void 0:A.name,department:f||(w=g[x])==null?void 0:w.department,avatar:f||(T=g[x])==null?void 0:T.avatar},s("approvers",g),!p||!p.startsWith("@")||p.length<2){d(x);return}o(x,p,10)},m=async(x,p)=>{var g,y;try{if((g=t.approvers)==null?void 0:g.some((w,T)=>{var k,L;return T!==x&&(w.userId===p.userId||((k=w.email)==null?void 0:k.toLowerCase())===((L=p.email)==null?void 0:L.toLowerCase()))})){a({type:"error",email:p.email,message:"This user is already added as an approver in another level."});return}if((y=t.spectators)==null?void 0:y.some(w=>{var T,k;return w.userId===p.userId||((T=w.email)==null?void 0:T.toLowerCase())===((k=p.email)==null?void 0:k.toLowerCase())})){a({type:"error",email:p.email,message:"This user is already added as a spectator. A user cannot be both an approver and a spectator."});return}const v=await ia({userId:p.userId,email:p.email,displayName:p.displayName,firstName:p.firstName,lastName:p.lastName,department:p.department,phone:p.phone,mobilePhone:p.mobilePhone,designation:p.designation,jobTitle:p.jobTitle,manager:p.manager,employeeId:p.employeeId,employeeNumber:p.employeeNumber,secondEmail:p.secondEmail,location:p.location}),A=[...t.approvers];A[x]={...A[x],email:p.email,name:p.displayName||[p.firstName,p.lastName].filter(Boolean).join(" "),userId:v.userId,level:x+1},s("approvers",A),d(x)}catch(f){console.error("Failed to ensure user exists:",f),a({type:"error",email:p.email,message:"Failed to validate user. Please try again."})}};return e.jsxs(gs.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($t,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"approval-workflow-title",children:"Approval Workflow"}),e.jsx("p",{className:"text-gray-600","data-testid":"approval-workflow-description",children:"Define the approval hierarchy and assign approvers by email ID."})]}),e.jsxs("div",{className:"max-w-4xl mx-auto space-y-8","data-testid":"approval-workflow-content",children:[e.jsxs(te,{"data-testid":"approval-workflow-config-card",children:[e.jsxs(ue,{children:[e.jsxs(xe,{className:"flex items-center gap-2","data-testid":"approval-workflow-config-title",children:[e.jsx(za,{className:"w-5 h-5"}),"Approval Configuration"]}),e.jsx(ke,{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(le,{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,p=Math.max(1,x-1);s("approverCount",p),t.approvers.length>p&&s("approvers",t.approvers.slice(0,p))},disabled:(t.approverCount||1)<=1,"data-testid":"approval-workflow-decrease-count",children:e.jsx(vo,{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 p=(t.approverCount||1)+1;if(p>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:p,maxValue:r.maxApprovalLevels}]);return}s("approverCount",p)},disabled:(t.approverCount||1)>=r.maxApprovalLevels,"data-testid":"approval-workflow-increase-count",children:e.jsx(vs,{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(te,{"data-testid":"approval-workflow-hierarchy-card",children:[e.jsxs(ue,{children:[e.jsxs(xe,{className:"flex items-center gap-2","data-testid":"approval-workflow-hierarchy-title",children:[e.jsx(as,{className:"w-5 h-5"}),"Approval Hierarchy *"]}),e.jsxs(ke,{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(_t,{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(ne,{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,p)=>{var b,v;const g=p+1,y=g===(t.approverCount||1),f=t.approvers[p]||{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]}),y&&e.jsx(ne,{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(le,{htmlFor:`approver-${g}`,className:"text-sm font-medium",children:"Email Address *"}),f.email&&f.userId&&e.jsxs(ne,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(De,{className:"w-3 h-3 mr-1"}),"Verified"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(_e,{id:`approver-${g}`,type:"email",placeholder:"approver@royalenfield.com",value:f.email||"",onChange:A=>c(p,A.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[p]||(((b=i[p])==null?void 0:b.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[p]?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[p])==null?void 0:v.map(A=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>m(p,A),"data-testid":`approval-workflow-approver-${g}-search-result-${A.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:A.displayName||A.email}),e.jsx("div",{className:"text-xs text-gray-600",children:A.email})]},A.userId))})})]})]}),e.jsxs("div",{"data-testid":`approval-workflow-approver-${g}-tat-field`,children:[e.jsx(le,{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(_e,{id:`tat-${g}`,type:"number",placeholder:f.tatType==="days"?"7":"24",min:"1",max:f.tatType==="days"?"30":"720",value:f.tat||"",onChange:A=>{const w=[...t.approvers];w[p]={...w[p],tat:parseInt(A.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(Ve,{value:f.tatType||"hours",onValueChange:A=>{const w=[...t.approvers];w[p]={...w[p],tatType:A,level:g,tat:""},s("approvers",w)},"data-testid":`approval-workflow-approver-${g}-tat-type-select`,children:[e.jsx(He,{className:"w-20 h-10 border-2 border-gray-300",children:e.jsx(ze,{})}),e.jsxs(We,{children:[e.jsx(K,{value:"hours",children:"Hours"}),e.jsx(K,{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(Sn,{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,p)=>`Level ${p+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(Xe,{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((y,f)=>{const b=Number(f.tat||0);return(f.tatType||"hours")==="days"?y+b:y+b/24},0))||0,p=Math.ceil(x);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-lg font-bold text-emerald-800",children:[p," ",p===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=t.approvers)==null?void 0:u.map((x,p)=>{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 ",p+1]}),e.jsxs("span",{className:"text-sm text-emerald-700",children:[f," ",f===1?"hour":"hours"]})]})},p):null})}),(()=>{var g;const x=((g=t.approvers)==null?void 0:g.reduce((y,f)=>{const b=Number(f.tat||0);return(f.tatType||"hours")==="days"?y+b*24:y+b},0))||0,p=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:p}),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 IA({formData:t,updateFormData:s,onValidationError:a,initiatorEmail:r}){const[n,i]=h.useState(""),{searchResults:l,searchLoading:o,searchUsersDebounced:d,clearSearch:c,ensureUser:m}=DA(),u=g=>{if(i(g),!g||!g.startsWith("@")||g.length<2){c();return}d(g,10)},x=async g=>{var y,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 b=t.spectators.some(A=>{var w,T;return A.userId===g.userId||((w=A.email)==null?void 0:w.toLowerCase())===((T=g.email)==null?void 0:T.toLowerCase())}),v=(y=t.approvers)==null?void 0:y.some(A=>{var w,T;return A.userId===g.userId||((w=A.email)==null?void 0:w.toLowerCase())===((T=g.email)==null?void 0:T.toLowerCase())});if(b){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 A=await m(g),w={id:A.userId,userId:A.userId,name:A.displayName||g.email.split("@")[0],email:A.email,avatar:(A.displayName||A.email).substring(0,2).toUpperCase(),role:"Spectator",department:A.department||"",level:1,canClose:!1},T=[...t.spectators,w];s("spectators",T),i(""),c()}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 b=t.spectators.some(A=>{var w;return((w=A.email)==null?void 0:w.toLowerCase())===n.toLowerCase()}),v=(f=t.approvers)==null?void 0:f.some(A=>{var w;return((w=A.email)==null?void 0:w.toLowerCase())===n.toLowerCase()});if(b){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}}},p=g=>{const y=t.spectators.filter(f=>f.id!==g);s("spectators",y)};return e.jsxs(gs.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(ht,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"participants-title",children:"Participants & Access"}),e.jsx("p",{className:"text-gray-600","data-testid":"participants-description",children:"Configure additional participants and visibility settings for your request."})]}),e.jsx("div",{className:"max-w-3xl mx-auto space-y-8","data-testid":"participants-content",children:e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:e.jsxs(te,{"data-testid":"participants-spectators-card",children:[e.jsxs(ue,{children:[e.jsxs(xe,{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(ht,{className:"w-4 h-4"}),"Spectators"]}),e.jsx(ne,{variant:"outline",className:"text-xs","data-testid":"participants-spectators-count",children:t.spectators.length})]}),e.jsx(ke,{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(_e,{placeholder:"Use @ sign to add a user",value:n,onChange:g=>u(g.target.value),onKeyPress:async g=>{g.key==="Enter"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)&&(g.preventDefault(),await 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(Sn,{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(rs,{className:"h-6 w-6",children:e.jsx(ns,{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:()=>p(g.id),"data-testid":`participants-spectator-${g.id}-remove`,children:e.jsx(ft,{className:"h-3 w-3"})})]},g.id))})]})]})})})]})}function EA({documentPolicy:t,isEditing:s,documents:a,existingDocuments:r,documentsToDelete:n,onDocumentsChange:i,onExistingDocumentsChange:l,onDocumentsToDeleteChange:o,onPreviewDocument:d,onDocumentErrors:c,fileInputRef:m}){const u=y=>{const f=Array.from(y.target.files||[]);if(f.length===0)return;const b=t.maxFileSizeMB*1024*1024,v=[],A=[];f.forEach(w=>{if(w.size>b){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 T=w.name.toLowerCase(),k=T.substring(T.lastIndexOf(".")+1);if(!t.allowedFileTypes.includes(k)){v.push({fileName:w.name,reason:`File type "${k}" is not allowed. Allowed types: ${t.allowedFileTypes.join(", ")}`});return}A.push(w)}),A.length>0&&i([...a,...A]),v.length>0&&c&&c(v),y.target&&(y.target.value="")},x=y=>{const f=a.filter((b,v)=>v!==y);i(f)},p=y=>{o([...n,y])},g=(y,f=!1)=>{if(f){const b=(y.fileType||y.file_type||"").toLowerCase(),v=(y.originalFileName||y.fileName||"").toLowerCase();return b.includes("image")||b.includes("pdf")||v.endsWith(".jpg")||v.endsWith(".jpeg")||v.endsWith(".png")||v.endsWith(".gif")||v.endsWith(".pdf")}else{const b=(y.type||"").toLowerCase(),v=(y.name||"").toLowerCase();return b.includes("image")||b.includes("pdf")||v.endsWith(".jpg")||v.endsWith(".jpeg")||v.endsWith(".png")||v.endsWith(".gif")||v.endsWith(".pdf")}};return e.jsxs(gs.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(Bs,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"documents-title",children:"Documents & Attachments"}),e.jsx("p",{className:"text-gray-600","data-testid":"documents-description",children:"Upload supporting documents, files, and any additional materials for your request."})]}),e.jsxs("div",{className:"max-w-2xl mx-auto space-y-6","data-testid":"documents-content",children:[e.jsxs(te,{"data-testid":"documents-upload-card",children:[e.jsxs(ue,{children:[e.jsxs(xe,{className:"flex items-center gap-2","data-testid":"documents-upload-title",children:[e.jsx(Pe,{className:"w-5 h-5"}),"File Upload"]}),e.jsxs(ke,{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(Bs,{className:"h-12 w-12 mx-auto mb-4 text-gray-400"}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Upload Files"}),e.jsx("p",{className:"text-gray-600 mb-4",children:"Drag and drop files here, or click to browse"}),e.jsx("input",{type:"file",multiple:!0,accept:t.allowedFileTypes.map(y=>`.${y}`).join(","),onChange:u,className:"hidden",id:"file-upload",ref:m,"data-testid":"documents-file-input"}),e.jsxs(F,{variant:"outline",size:"lg",type:"button",onClick:()=>{var y;return(y=m.current)==null?void 0:y.click()},"data-testid":"documents-browse-button",children:[e.jsx(vs,{className:"w-4 h-4 mr-2"}),"Browse Files"]}),e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Supported formats: ",t.allowedFileTypes.map(y=>y.toUpperCase()).join(", ")," (Max ",t.maxFileSizeMB,"MB per file)"]})]})})]}),s&&r.length>0&&e.jsxs(te,{"data-testid":"documents-existing-card",children:[e.jsx(ue,{children:e.jsxs(xe,{className:"flex items-center justify-between","data-testid":"documents-existing-title",children:[e.jsx("span",{children:"Existing Documents"}),e.jsxs(ne,{variant:"secondary","data-testid":"documents-existing-count",children:[r.filter(y=>!n.includes(y.documentId||y.document_id||"")).length," file",r.filter(y=>!n.includes(y.documentId||y.document_id||"")).length!==1?"s":""]})]})}),e.jsx(ae,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-existing-list",children:r.map(y=>{const f=y.documentId||y.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(Pe,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:y.originalFileName||y.fileName||"Document"}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsx("span",{children:y.fileSize?(Number(y.fileSize)/(1024*1024)).toFixed(2)+" MB":"Unknown size"})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g(y,!0)&&e.jsx(F,{variant:"ghost",size:"sm",onClick:()=>d(y,!0),"data-testid":`documents-existing-${f}-preview`,children:e.jsx(ht,{className:"h-4 w-4"})}),e.jsx(F,{variant:"ghost",size:"sm",onClick:()=>p(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(te,{"data-testid":"documents-new-card",children:[e.jsx(ue,{children:e.jsxs(xe,{className:"flex items-center justify-between","data-testid":"documents-new-title",children:[e.jsx("span",{children:"New Files to Upload"}),e.jsxs(ne,{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((y,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(Pe,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:y.name}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsxs("span",{children:[(y.size/(1024*1024)).toFixed(2)," MB"]})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g(y,!1)&&e.jsx(F,{variant:"ghost",size:"sm",onClick:()=>d(y,!1),"data-testid":`documents-new-${f}-preview`,children:e.jsx(ht,{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 FA=t=>{switch(t){case"high":return e.jsx(pa,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(Vt,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(Ks,{className:"w-4 h-4 text-green-600"});default:return e.jsx(Vt,{className:"w-4 h-4 text-gray-600"})}};function MA({formData:t,selectedTemplate:s}){return e.jsxs(gs.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(De,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"review-submit-title",children:"Review & Submit"}),e.jsx("p",{className:"text-gray-600","data-testid":"review-submit-description",children:"Please review all details before submitting your request for approval."})]}),e.jsxs("div",{className:"max-w-5xl mx-auto space-y-8","data-testid":"review-submit-content",children:[e.jsxs(te,{className:"border-2 border-green-200 bg-green-50/50","data-testid":"review-submit-overview-card",children:[e.jsx(ue,{children:e.jsxs(xe,{className:"flex items-center gap-2 text-green-900","data-testid":"review-submit-overview-title",children:[e.jsx(ax,{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(le,{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(ne,{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(le,{className:"text-green-900 font-semibold",children:"Priority"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[FA(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(le,{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(le,{className:"text-green-900 font-semibold",children:"Request Title"}),e.jsx("p",{className:"text-green-800 font-medium mt-1 text-lg",children:t.title})]})]})]}),e.jsxs(te,{"data-testid":"review-submit-basic-info-card",children:[e.jsx(ue,{children:e.jsxs(xe,{className:"flex items-center gap-2","data-testid":"review-submit-basic-info-title",children:[e.jsx(Pe,{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(le,{className:"font-semibold",children:"Description"}),e.jsx("div",{className:"mt-1 p-3 bg-gray-50 rounded-lg border",children:e.jsx(ra,{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(le,{className:"font-semibold text-blue-900",children:"Financial Details"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-blue-700",children:"Amount"}),e.jsxs("p",{className:"font-semibold text-blue-900",children:[t.amount," ",t.currency]})]}),t.costCenter&&e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-blue-700",children:"Cost Center"}),e.jsx("p",{className:"font-medium text-blue-900",children:t.costCenter})]})]})]})]})]}),e.jsxs(te,{className:"border-2 border-orange-200 bg-orange-50/50","data-testid":"review-submit-approval-card",children:[e.jsxs(ue,{children:[e.jsxs(xe,{className:"flex items-center gap-2 text-orange-900","data-testid":"review-submit-approval-title",children:[e.jsx($t,{className:"w-5 h-5"}),"Approval Workflow"]}),e.jsx(ke,{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(ne,{variant:"destructive",className:"text-xs",children:"FINAL APPROVER"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Email Address"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:(l==null?void 0:l.email)||"Not assigned"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-gray-600",children:"TAT (Turn Around Time)"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:l!=null&&l.tat?`${l.tat} ${l.tatType==="days"?"day":"hour"}${l.tat!==1?"s":""}`:"Not set"})]})]})]})]})},n)})})})]}),e.jsxs(te,{"data-testid":"review-submit-participants-card",children:[e.jsx(ue,{children:e.jsxs(xe,{className:"flex items-center gap-2","data-testid":"review-submit-participants-title",children:[e.jsx(ht,{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(le,{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(ne,{variant:"outline",className:"text-xs","data-testid":`review-submit-spectator-${a.id}`,children:[a.name," (",a.email,")"]},a.id))})]})})]}),t.documents.length>0&&e.jsxs(te,{"data-testid":"review-submit-documents-card",children:[e.jsxs(ue,{children:[e.jsxs(xe,{className:"flex items-center gap-2","data-testid":"review-submit-documents-title",children:[e.jsx(Bs,{className:"w-5 h-5"}),"Documents & Attachments"]}),e.jsxs(ke,{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(Pe,{className:"w-5 h-5 text-gray-500 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:a.name}),e.jsx("div",{className:"flex items-center gap-3 text-xs text-gray-500 mt-1",children:e.jsxs("span",{children:[(a.size/(1024*1024)).toFixed(2)," MB"]})})]})]},r))})})]}),e.jsx(te,{className:"border-2 border-blue-200 bg-blue-50/50","data-testid":"review-submit-confirmation-card",children:e.jsx(ae,{className:"pt-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(De,{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 _A({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(Js,{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 LA({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(oc,{mode:"wait",children:t})})})}function OA({modal:t,onClose:s}){return e.jsx(mt,{open:t.open,onOpenChange:a=>!a&&s(),"data-testid":"create-request-validation-modal",children:e.jsxs(ot,{className:"sm:max-w-md",children:[e.jsxs(ut,{children:[e.jsxs(ct,{className:"flex items-center gap-2","data-testid":"validation-modal-title",children:[t.type==="self-assign"&&e.jsxs(e.Fragment,{children:[e.jsx(Ge,{className:"w-5 h-5 text-amber-600"}),"Cannot Add Yourself"]}),t.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsx(Ge,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}),t.type==="error"&&e.jsxs(e.Fragment,{children:[e.jsx(Ge,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})]}),e.jsx(It,{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(Si,{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(Tt,{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 $A({modal:t,documentPolicy:s,onClose:a}){return e.jsx(mt,{open:t.open,onOpenChange:r=>!r&&a(),"data-testid":"create-request-document-error-modal",children:e.jsxs(ot,{className:"sm:max-w-lg",children:[e.jsxs(ut,{children:[e.jsxs(ct,{className:"flex items-center gap-2","data-testid":"document-error-modal-title",children:[e.jsx(Ge,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(It,{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(Tt,{children:e.jsx(F,{onClick:a,className:"w-full sm:w-auto","data-testid":"document-error-modal-ok-button",children:"OK"})})]})})}function wu({onBack:t,onSubmit:s,requestId:a,isEditMode:r=!1}){const n=vr(),i=Fa(),l=n.requestId||a||"",o=r&&!!l,{user:d}=Jt(),{formData:c,updateFormData:m,selectedTemplate:u,setSelectedTemplate:x,loadingDraft:p,systemPolicy:g,documentPolicy:y,existingDocuments:f,setExistingDocuments:b}=iA(o,l,ju),{currentStep:v,totalSteps:A,stepNames:w,isStepValid:T,nextStep:k,prevStep:L}=lA(o,u,c),[D,S]=h.useState([]),[N,P]=h.useState([]),R=h.useRef(null),{validationModal:O,policyViolationModal:E,documentErrorModal:M,openValidationModal:B,closeValidationModal:C,openPolicyViolationModal:j,closePolicyViolationModal:U,openDocumentErrorModal:$,closeDocumentErrorModal:_}=oA(),{submitting:se,savingDraft:W,handleSubmit:ce,handleSaveDraft:Z}=pA({formData:c,selectedTemplate:u,documents:D,documentsToDelete:N,user:d,isEditing:o,editRequestId:l,onSubmit:s}),{showTemplateModal:I,setShowTemplateModal:V,previewDocument:z,selectTemplate:X,handleTemplateSelection:Y,nextStep:G,prevStep:ie,handlePreviewDocument:me,closePreview:Te}=wA({selectedTemplate:u,setSelectedTemplate:x,updateFormData:m,formData:c,currentStep:v,isStepValid:T,wizardNextStep:k,wizardPrevStep:L,user:d,openValidationModal:B,systemPolicy:g,onPolicyViolation:j,onSubmit:s}),Se=h.useCallback(()=>{v===1||v===3||v===4?t?t():window.history.length>1?window.history.back():i("/dashboard",{replace:!0}):ie()},[v,t,i,ie]),re=h.useRef(!0),pe=h.useRef(!1);h.useEffect(()=>{re.current&&c.documents&&c.documents.length>0&&!pe.current&&(S(c.documents),pe.current=!0),re.current=!1},[c.documents]);const ve=h.useRef(!1),be=h.useRef(D);h.useEffect(()=>{if(ve.current){ve.current=!1,be.current=D;return}be.current!==D&&(m("documents",D),be.current=D)},[D]);const Le=()=>{switch(v){case 1:return e.jsx(TA,{templates:ju,selectedTemplate:u,onSelectTemplate:X});case 2:return e.jsx(RA,{formData:c,selectedTemplate:u,updateFormData:m});case 3:return e.jsx(PA,{formData:c,updateFormData:m,systemPolicy:g,onValidationError:J=>B(J.type,J.email,J.message),onPolicyViolation:j});case 4:return e.jsx(IA,{formData:c,updateFormData:m,onValidationError:J=>B(J.type,J.email,J.message),initiatorEmail:(d==null?void 0:d.email)||""});case 5:return e.jsx(EA,{documentPolicy:y,isEditing:o,documents:D,existingDocuments:f,documentsToDelete:N,onDocumentsChange:S,onExistingDocumentsChange:b,onDocumentsToDeleteChange:P,onPreviewDocument:me,onDocumentErrors:J=>$(J),fileInputRef:R});case 6:return e.jsx(MA,{formData:c,selectedTemplate:u});default:return null}};return p?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center","data-testid":"create-request-loading",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading draft..."})]})}):e.jsxs("div",{className:"h-full flex flex-col bg-gradient-to-br from-gray-50 to-white","data-testid":"create-request",children:[e.jsx(_A,{isEditing:o,currentStep:v,totalSteps:A,stepNames:w,onBack:Se}),e.jsx(CA,{currentStep:v,totalSteps:A,stepNames:w}),e.jsx(LA,{children:Le()}),e.jsx(AA,{currentStep:v,totalSteps:A,isStepValid:T(),onPrev:ie,onNext:G,onSubmit:ce,onSaveDraft:Z,submitting:se,savingDraft:W,loadingDraft:p,isEditing:o}),e.jsx(YC,{open:I,onClose:()=>V(!1),onSelectTemplate:Y}),z&&e.jsx(Xr,{fileName:z.fileName,fileType:z.fileType,fileUrl:z.fileUrl,fileSize:z.fileSize,open:!!z,onClose:Te,onDownload:async()=>{if(z.file){const J=document.createElement("a");J.href=z.fileUrl,J.download=z.fileName,document.body.appendChild(J),J.click(),document.body.removeChild(J)}else z.documentId&&await bs(z.documentId)},attachmentId:z.documentId}),e.jsx(OA,{modal:O,onClose:C}),e.jsx($A,{modal:M,documentPolicy:y,onClose:_}),e.jsx(_n,{open:E.open,onClose:U,violations:E.violations,policyDetails:{maxApprovalLevels:g.maxApprovalLevels,maxParticipants:g.maxParticipants,allowSpectators:g.allowSpectators,maxSpectators:g.maxSpectators}})]})}function Ln({className:t,...s}){return e.jsx(pf,{"data-slot":"tabs",className:Re("flex flex-col gap-2",t),...s})}function On({className:t,...s}){return e.jsx(gf,{"data-slot":"tabs-list",className:Re("bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-xl p-[3px] flex",t),...s})}function At({className:t,...s}){return e.jsx(ff,{"data-slot":"tabs-trigger",className:Re("data-[state=active]:bg-card dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-xl border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...s})}function St({className:t,...s}){return e.jsx(yf,{"data-slot":"tabs-content",className:Re("flex-1 outline-none",t),...s})}const Mp={"RE-REQ-2024-001":{id:"RE-REQ-2024-001",title:"Himalayan 450 Launch Campaign - Digital Media Blitz",description:`Comprehensive digital marketing campaign for Himalayan 450 adventure motorcycle launch. Includes social media campaigns, influencer partnerships, performance marketing, content creation, and digital advertising across platforms. Target: Reach 10M adventure enthusiasts across India.
|
||
|
||
Equipment Specifications:
|
||
• 10x MacBook Pro 16-inch (M2 Pro chip)
|
||
• 5x Professional Camera Kits (Canon EOS R5)
|
||
• Video Editing Workstations
|
||
• Social Media Management Tools`,category:"Marketing & Campaigns",subcategory:"Digital Marketing",status:"pending",priority:"express",amount:"₹3,75,00,000",slaProgress:65,slaRemaining:"8 hours 45 minutes",slaEndDate:"Oct 9, 2024 5:00 PM",currentStep:1,totalSteps:3,template:"custom",initiator:{name:"Priya Sharma",role:"Senior Digital Marketing Manager",department:"Marketing",email:"priya.sharma@royalenfield.com",phone:"+91 98765 43210",avatar:"PS"},department:"Marketing",createdAt:"Oct 6, 2024 10:30 AM",updatedAt:"Oct 7, 2024 2:15 PM",dueDate:"2024-10-09T17:00:00Z",conclusionRemark:"",approvalFlow:[{step:1,approver:"Rajesh Kumar",role:"Marketing Director - India",status:"pending",tatHours:24,elapsedHours:22,assignedAt:"2024-10-06T10:30:00Z",comment:null,timestamp:null},{step:2,approver:"Amit Desai",role:"VP Product Marketing",status:"waiting",tatHours:48,elapsedHours:0,assignedAt:null,comment:null,timestamp:null},{step:3,approver:"Deepika Sharma",role:"VP Sales & Marketing",status:"waiting",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null}],documents:[{name:"Himalayan_450_Digital_Strategy.pdf",size:"5.2 MB",type:"PDF",uploadedBy:"Priya Sharma",uploadedAt:"Oct 6, 2024 10:45 AM"},{name:"Budget_Breakdown_Q4_2024.xlsx",size:"980 KB",type:"Excel",uploadedBy:"Priya Sharma",uploadedAt:"Oct 6, 2024 11:15 AM"},{name:"Influencer_Partnership_List.xlsx",size:"450 KB",type:"Excel",uploadedBy:"Marketing Team",uploadedAt:"Oct 6, 2024 2:30 PM"},{name:"Creative_Campaign_Assets.zip",size:"125 MB",type:"ZIP",uploadedBy:"Creative Team",uploadedAt:"Oct 6, 2024 4:15 PM"}],spectators:[{name:"Sarah Khan",role:"Brand Strategy Lead",avatar:"SK"},{name:"Finance Team",role:"Budget Approval",avatar:"FT"}],auditTrail:[{type:"created",action:"Request Created",details:"New digital marketing campaign request submitted",user:"Priya Sharma",timestamp:"Oct 6, 2024 10:30 AM"},{type:"assignment",action:"Assigned to Rajesh Kumar",details:"Forwarded to Marketing Director for review",user:"System",timestamp:"Oct 6, 2024 10:31 AM"},{type:"comment",action:"Work Note Added",details:"Reviewed budget allocation and target metrics",user:"Rajesh Kumar",timestamp:"Oct 7, 2024 2:15 PM"},{type:"reminder",action:"SLA Reminder",details:"TAT approaching - 8 hours remaining",user:"System",timestamp:"Oct 7, 2024 8:15 AM"}],tags:["digital-marketing","launch-campaign","himalayan-450","high-priority"]},"RE-REQ-2024-002":{id:"RE-REQ-2024-002",title:"New Laptop Procurement - Design Team Expansion",description:"Purchase of 10 high-performance laptops for the newly expanded Product Design team. Required specifications: Latest generation processor, 32GB RAM, dedicated graphics card for 3D modeling and rendering work.",category:"IT & Infrastructure",subcategory:"Hardware Procurement",status:"in-review",priority:"standard",amount:"₹12,50,000",slaProgress:45,slaRemaining:"2 days 8 hours",slaEndDate:"Oct 11, 2024 5:00 PM",currentStep:2,totalSteps:3,template:"custom",initiator:{name:"Vikram Singh",role:"Head - IT Operations",department:"Information Technology",email:"vikram.singh@royalenfield.com",phone:"+91 98765 43221",avatar:"VS"},department:"Information Technology",createdAt:"Oct 5, 2024 9:15 AM",updatedAt:"Oct 7, 2024 3:45 PM",dueDate:"2024-10-11T17:00:00Z",conclusionRemark:"",approvalFlow:[{step:1,approver:"Meera Patel",role:"IT Manager",status:"approved",tatHours:24,actualHours:18,assignedAt:"2024-10-05T09:15:00Z",comment:"Technical specifications verified. Hardware meets design team requirements.",timestamp:"2024-10-06T03:15:00Z"},{step:2,approver:"Anil Kapoor",role:"Finance Manager",status:"in-review",tatHours:48,elapsedHours:32,assignedAt:"2024-10-06T03:15:00Z",comment:null,timestamp:null},{step:3,approver:"Ramesh Kulkarni",role:"VP Operations",status:"waiting",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null}],documents:[{name:"Laptop_Specifications.pdf",size:"850 KB",type:"PDF",uploadedBy:"Vikram Singh",uploadedAt:"Oct 5, 2024 9:20 AM"},{name:"Vendor_Quotations.xlsx",size:"1.2 MB",type:"Excel",uploadedBy:"Procurement Team",uploadedAt:"Oct 5, 2024 11:45 AM"},{name:"Team_Expansion_Plan.pdf",size:"620 KB",type:"PDF",uploadedBy:"Design Team",uploadedAt:"Oct 5, 2024 2:30 PM"}],spectators:[{name:"Design Team Lead",role:"End Users",avatar:"DT"},{name:"Procurement Team",role:"Vendor Management",avatar:"PT"}],auditTrail:[{type:"created",action:"Request Created",details:"Laptop procurement request for design team",user:"Vikram Singh",timestamp:"Oct 5, 2024 9:15 AM"},{type:"assignment",action:"Assigned to Meera Patel",details:"IT Manager to verify specifications",user:"System",timestamp:"Oct 5, 2024 9:16 AM"},{type:"approval",action:"Approved by Meera Patel",details:"Technical specifications approved",user:"Meera Patel",timestamp:"Oct 6, 2024 3:15 AM"},{type:"assignment",action:"Assigned to Anil Kapoor",details:"Forwarded to Finance for budget approval",user:"System",timestamp:"Oct 6, 2024 3:15 AM"}],tags:["hardware","procurement","design-team","laptops"]},"RE-REQ-2024-003":{id:"RE-REQ-2024-003",title:"Annual Service Center Expansion - Western Region",description:"Proposal for opening 15 new authorized service centers across tier-2 cities in Western region. Includes infrastructure setup, technician training, spare parts inventory, and marketing support. Expected to improve service accessibility by 35% in the target region.",category:"Operations & Expansion",subcategory:"Service Network",status:"pending",priority:"standard",amount:"₹8,75,00,000",slaProgress:78,slaRemaining:"1 day 4 hours",slaEndDate:"Oct 10, 2024 5:00 PM",currentStep:1,totalSteps:4,template:"custom",initiator:{name:"Sanjay Reddy",role:"Regional Service Manager - West",department:"After Sales Service",email:"sanjay.reddy@royalenfield.com",phone:"+91 98765 43232",avatar:"SR"},department:"After Sales Service",createdAt:"Oct 3, 2024 8:45 AM",updatedAt:"Oct 6, 2024 5:45 PM",dueDate:"2024-10-10T17:00:00Z",conclusionRemark:"",approvalFlow:[{step:1,approver:"Ramesh Kulkarni",role:"Head - After Sales Service",status:"pending",tatHours:72,elapsedHours:85,assignedAt:"2024-10-03T08:45:00Z",comment:null,timestamp:null},{step:2,approver:"Finance Team",role:"Budget Allocation",status:"waiting",tatHours:96,elapsedHours:0,assignedAt:null,comment:null,timestamp:null},{step:3,approver:"Legal Team",role:"Compliance Review",status:"waiting",tatHours:120,elapsedHours:0,assignedAt:null,comment:null,timestamp:null},{step:4,approver:"Deepika Sharma",role:"VP Sales & Marketing",status:"waiting",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null}],documents:[{name:"Western_Region_Expansion_Plan.pdf",size:"7.5 MB",type:"PDF",uploadedBy:"Sanjay Reddy",uploadedAt:"Oct 3, 2024 9:00 AM"},{name:"Service_Center_Requirements.xlsx",size:"2.8 MB",type:"Excel",uploadedBy:"Planning Team",uploadedAt:"Oct 3, 2024 11:30 AM"},{name:"Customer_Demand_Analysis.pptx",size:"4.2 MB",type:"PowerPoint",uploadedBy:"Analytics Team",uploadedAt:"Oct 4, 2024 2:15 PM"},{name:"ROI_Projections_Service_Network.xlsx",size:"1.9 MB",type:"Excel",uploadedBy:"Finance Team",uploadedAt:"Oct 5, 2024 10:45 AM"}],spectators:[{name:"Regional Managers",role:"Service Operations",avatar:"RM"},{name:"Training Team",role:"Technician Development",avatar:"TT"}],auditTrail:[{type:"created",action:"Request Created",details:"Service center expansion proposal submitted",user:"Sanjay Reddy",timestamp:"Oct 3, 2024 8:45 AM"},{type:"assignment",action:"Assigned to Ramesh Kulkarni",details:"Forwarded to Head of After Sales Service",user:"System",timestamp:"Oct 3, 2024 8:46 AM"},{type:"reminder",action:"Reminder Sent",details:"TAT breach reminder sent to approver",user:"System",timestamp:"Oct 6, 2024 5:45 PM"},{type:"updated",action:"Additional Documents",details:"ROI projections added by finance team",user:"Finance Team",timestamp:"Oct 5, 2024 10:45 AM"}],tags:["service-expansion","western-region","tier2-cities","overdue"]},"RE-REQ-2024-004":{id:"RE-REQ-2024-004",title:"Employee Training Program - Advanced Motorcycle Mechanics",description:"Comprehensive training program for 50 service center technicians covering advanced diagnostics, electrical systems, fuel injection troubleshooting, and customer service excellence. Program duration: 3 weeks. Includes certification upon completion.",category:"Human Resources",subcategory:"Training & Development",status:"approved",priority:"standard",amount:"₹18,50,000",slaProgress:100,slaRemaining:"Completed",slaEndDate:"Oct 5, 2024 5:00 PM",currentStep:3,totalSteps:3,template:"custom",initiator:{name:"Kavita Menon",role:"Training Manager",department:"Human Resources",email:"kavita.menon@royalenfield.com",phone:"+91 98765 43243",avatar:"KM"},department:"Human Resources",createdAt:"Sep 28, 2024 11:00 AM",updatedAt:"Oct 5, 2024 4:30 PM",dueDate:"2024-10-05T17:00:00Z",submittedDate:"2024-09-28T11:00:00Z",estimatedCompletion:"Oct 5, 2024",currentApprover:"Completed",approverLevel:"3 of 3",conclusionRemark:"All approvals completed. Training program scheduled for November 2024.",approvalFlow:[{step:1,approver:"Ramesh Kulkarni",role:"Head - After Sales Service",status:"approved",tatHours:48,actualHours:36,assignedAt:"2024-09-28T11:00:00Z",comment:"Excellent initiative. Training content approved.",timestamp:"Sep 29, 2024 11:00 PM"},{step:2,approver:"Anil Kapoor",role:"Finance Manager",status:"approved",tatHours:72,actualHours:48,assignedAt:"2024-09-29T23:00:00Z",comment:"Budget approved. Cost per participant is reasonable.",timestamp:"Oct 1, 2024 11:00 PM"},{step:3,approver:"Deepika Sharma",role:"VP Sales & Marketing",status:"approved",tatHours:96,actualHours:72,assignedAt:"2024-10-01T23:00:00Z",comment:"Final approval granted. Proceed with program execution.",timestamp:"Oct 5, 2024 4:30 PM"}],documents:[{name:"Training_Curriculum.pdf",size:"3.2 MB",type:"PDF",uploadedBy:"Kavita Menon",uploadedAt:"Sep 28, 2024 11:15 AM"},{name:"Trainer_Profiles.pdf",size:"1.8 MB",type:"PDF",uploadedBy:"HR Team",uploadedAt:"Sep 28, 2024 2:45 PM"},{name:"Budget_Training_Program.xlsx",size:"680 KB",type:"Excel",uploadedBy:"Finance Team",uploadedAt:"Sep 29, 2024 10:30 AM"}],spectators:[{name:"Service Center Managers",role:"Participant Coordination",avatar:"SC"},{name:"Quality Assurance",role:"Training Quality",avatar:"QA"}],auditTrail:[{type:"created",action:"Request Created",details:"Training program proposal submitted",user:"Kavita Menon",timestamp:"Sep 28, 2024 11:00 AM"},{type:"assignment",action:"Assigned to Ramesh Kulkarni",details:"Forwarded to After Sales Service Head",user:"System",timestamp:"Sep 28, 2024 11:01 AM"},{type:"approval",action:"Approved by Ramesh Kulkarni",details:"Level 1 approval completed",user:"Ramesh Kulkarni",timestamp:"Sep 29, 2024 11:00 PM"},{type:"assignment",action:"Assigned to Anil Kapoor",details:"Forwarded to Finance Manager",user:"System",timestamp:"Sep 29, 2024 11:01 PM"},{type:"approval",action:"Approved by Anil Kapoor",details:"Budget approval completed",user:"Anil Kapoor",timestamp:"Oct 1, 2024 11:00 PM"},{type:"assignment",action:"Assigned to Deepika Sharma",details:"Forwarded to VP for final approval",user:"System",timestamp:"Oct 1, 2024 11:01 PM"},{type:"approval",action:"Approved by Deepika Sharma",details:"Final approval - Request completed",user:"Deepika Sharma",timestamp:"Oct 5, 2024 4:30 PM"},{type:"completed",action:"Request Completed",details:"All approvals obtained. Training scheduled.",user:"System",timestamp:"Oct 5, 2024 4:31 PM"}],tags:["training","technicians","approved","completed"]},"RE-REQ-2024-005":{id:"RE-REQ-2024-005",title:"Showroom Renovation - Chennai Flagship Store",description:"Complete renovation of Chennai flagship showroom including modern interior design, interactive display zones, customer lounge upgrade, motorcycle test ride facility, and digital experience center. Project timeline: 8 weeks.",category:"Infrastructure",subcategory:"Retail & Showroom",status:"rejected",priority:"standard",amount:"₹65,00,000",slaProgress:100,slaRemaining:"Rejected",slaEndDate:"Oct 4, 2024 5:00 PM",currentStep:2,totalSteps:4,template:"custom",initiator:{name:"Arjun Nair",role:"Showroom Manager - South",department:"Retail Operations",email:"arjun.nair@royalenfield.com",phone:"+91 98765 43254",avatar:"AN"},department:"Retail Operations",createdAt:"Oct 1, 2024 9:30 AM",updatedAt:"Oct 4, 2024 3:15 PM",dueDate:"2024-10-04T17:00:00Z",submittedDate:"2024-10-01T09:30:00Z",estimatedCompletion:"N/A",currentApprover:"Rejected by Anil Kapoor",approverLevel:"2 of 4",conclusionRemark:"Request rejected due to insufficient budget justification. Please revise with detailed ROI analysis.",approvalFlow:[{step:1,approver:"Suresh Iyer",role:"Regional Manager - South",status:"approved",tatHours:48,actualHours:24,assignedAt:"2024-10-01T09:30:00Z",comment:"Renovation is necessary. Current showroom needs upgrade.",timestamp:"Oct 2, 2024 9:30 AM"},{step:2,approver:"Anil Kapoor",role:"Finance Manager",status:"rejected",tatHours:72,actualHours:48,assignedAt:"2024-10-02T09:30:00Z",comment:"Budget allocation not justified. Need detailed ROI analysis and comparison with alternative renovation options. Please revise and resubmit with comprehensive financial projections.",timestamp:"Oct 4, 2024 3:15 PM"},{step:3,approver:"Legal Team",role:"Compliance & Contracts",status:"cancelled",tatHours:96,elapsedHours:0,assignedAt:null,comment:null,timestamp:null},{step:4,approver:"Ramesh Kulkarni",role:"VP Operations",status:"cancelled",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null}],documents:[{name:"Showroom_Renovation_Plan.pdf",size:"12.5 MB",type:"PDF",uploadedBy:"Arjun Nair",uploadedAt:"Oct 1, 2024 9:45 AM"},{name:"Interior_Design_Mockups.zip",size:"85 MB",type:"ZIP",uploadedBy:"Design Team",uploadedAt:"Oct 1, 2024 2:30 PM"},{name:"Contractor_Quotations.xlsx",size:"2.1 MB",type:"Excel",uploadedBy:"Procurement Team",uploadedAt:"Oct 2, 2024 11:15 AM"}],spectators:[{name:"Marketing Team",role:"Brand Experience",avatar:"MT"},{name:"Customer Experience",role:"Feedback & Analysis",avatar:"CX"}],auditTrail:[{type:"created",action:"Request Created",details:"Showroom renovation request submitted",user:"Arjun Nair",timestamp:"Oct 1, 2024 9:30 AM"},{type:"assignment",action:"Assigned to Suresh Iyer",details:"Forwarded to Regional Manager",user:"System",timestamp:"Oct 1, 2024 9:31 AM"},{type:"approval",action:"Approved by Suresh Iyer",details:"Level 1 approval completed",user:"Suresh Iyer",timestamp:"Oct 2, 2024 9:30 AM"},{type:"assignment",action:"Assigned to Anil Kapoor",details:"Forwarded to Finance Manager",user:"System",timestamp:"Oct 2, 2024 9:31 AM"},{type:"rejection",action:"Rejected by Anil Kapoor",details:"Budget justification insufficient",user:"Anil Kapoor",timestamp:"Oct 4, 2024 3:15 PM"},{type:"completed",action:"Request Rejected",details:"Workflow terminated. Requires resubmission with revisions.",user:"System",timestamp:"Oct 4, 2024 3:16 PM"}],tags:["showroom","renovation","rejected","south-region"]},"RE-REQ-2024-006":{id:"RE-REQ-2024-006",title:"Spare Parts Inventory Optimization System",description:"Implementation of AI-powered inventory management system for spare parts across all service centers. Features include demand forecasting, automated reordering, stock level optimization, and real-time tracking. Expected to reduce inventory costs by 20% and improve part availability.",category:"Technology & Innovation",subcategory:"Software Implementation",status:"pending",priority:"express",amount:"₹42,00,000",slaProgress:35,slaRemaining:"1 day 16 hours",slaEndDate:"Oct 12, 2024 5:00 PM",currentStep:1,totalSteps:4,template:"custom",initiator:{name:"Rahul Deshmukh",role:"Head - Supply Chain Technology",department:"Supply Chain",email:"rahul.deshmukh@royalenfield.com",phone:"+91 98765 43265",avatar:"RD"},department:"Supply Chain",createdAt:"Oct 7, 2024 10:00 AM",updatedAt:"Oct 8, 2024 9:15 AM",dueDate:"2024-10-12T17:00:00Z",submittedDate:"2024-10-07T10:00:00Z",estimatedCompletion:"Oct 12, 2024",currentApprover:"Vikram Singh",approverLevel:"1 of 4",conclusionRemark:"",approvalFlow:[{step:1,approver:"Vikram Singh",role:"Head - IT Operations",status:"pending",tatHours:48,elapsedHours:23,assignedAt:"2024-10-07T10:00:00Z",comment:null,timestamp:null},{step:2,approver:"Supply Chain Director",role:"Operations Approval",status:"waiting",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null},{step:3,approver:"Anil Kapoor",role:"Finance Manager",status:"waiting",tatHours:96,elapsedHours:0,assignedAt:null,comment:null,timestamp:null},{step:4,approver:"Ramesh Kulkarni",role:"VP Operations",status:"waiting",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null}],documents:[{name:"AI_Inventory_System_Proposal.pdf",size:"8.9 MB",type:"PDF",uploadedBy:"Rahul Deshmukh",uploadedAt:"Oct 7, 2024 10:15 AM"},{name:"Vendor_Comparison_Analysis.xlsx",size:"3.4 MB",type:"Excel",uploadedBy:"IT Procurement",uploadedAt:"Oct 7, 2024 2:45 PM"},{name:"Cost_Benefit_Analysis.pptx",size:"6.2 MB",type:"PowerPoint",uploadedBy:"Analytics Team",uploadedAt:"Oct 7, 2024 4:30 PM"},{name:"Implementation_Timeline.pdf",size:"1.5 MB",type:"PDF",uploadedBy:"Project Management",uploadedAt:"Oct 8, 2024 9:15 AM"}],spectators:[{name:"Service Center Network",role:"End Users",avatar:"SN"},{name:"Data Analytics Team",role:"System Integration",avatar:"DA"}],auditTrail:[{type:"created",action:"Request Created",details:"AI inventory system proposal submitted",user:"Rahul Deshmukh",timestamp:"Oct 7, 2024 10:00 AM"},{type:"assignment",action:"Assigned to Vikram Singh",details:"Forwarded to IT Operations Head",user:"System",timestamp:"Oct 7, 2024 10:01 AM"},{type:"updated",action:"Documents Added",details:"Implementation timeline document uploaded",user:"Project Management",timestamp:"Oct 8, 2024 9:15 AM"}],tags:["technology","ai","inventory","supply-chain","high-priority"]},"RE-REQ-2024-007":{id:"RE-REQ-2024-007",title:"Dealer Network Meeting - Q4 Business Review",description:"Quarterly business review meeting for all authorized dealers across India. Venue: Bangalore. Topics include Q3 performance review, Q4 targets, new model launches, marketing initiatives, service excellence programs, and dealer support policies. Expected attendance: 250 dealers.",category:"Events & Conferences",subcategory:"Dealer Meetings",status:"in-review",priority:"standard",amount:"₹28,50,000",slaProgress:58,slaRemaining:"1 day 12 hours",slaEndDate:"Oct 11, 2024 5:00 PM",currentStep:2,totalSteps:3,template:"custom",initiator:{name:"Neha Kapoor",role:"Dealer Network Manager",department:"Sales & Distribution",email:"neha.kapoor@royalenfield.com",phone:"+91 98765 43276",avatar:"NK"},department:"Sales & Distribution",createdAt:"Oct 6, 2024 2:00 PM",updatedAt:"Oct 8, 2024 11:30 AM",dueDate:"2024-10-11T17:00:00Z",submittedDate:"2024-10-06T14:00:00Z",estimatedCompletion:"Oct 11, 2024",currentApprover:"Anil Kapoor",approverLevel:"2 of 3",conclusionRemark:"",approvalFlow:[{step:1,approver:"Suresh Mehta",role:"Sales Director",status:"approved",tatHours:48,actualHours:36,assignedAt:"2024-10-06T14:00:00Z",comment:"Dealer meeting approved. Agenda looks comprehensive.",timestamp:"Oct 8, 2024 2:00 AM"},{step:2,approver:"Anil Kapoor",role:"Finance Manager",status:"in-review",tatHours:72,elapsedHours:33,assignedAt:"2024-10-08T02:00:00Z",comment:null,timestamp:null},{step:3,approver:"Deepika Sharma",role:"VP Sales & Marketing",status:"waiting",tatHours:48,elapsedHours:0,assignedAt:null,comment:null,timestamp:null}],documents:[{name:"Q4_Dealer_Meeting_Agenda.pdf",size:"2.8 MB",type:"PDF",uploadedBy:"Neha Kapoor",uploadedAt:"Oct 6, 2024 2:15 PM"},{name:"Venue_Booking_Confirmation.pdf",size:"980 KB",type:"PDF",uploadedBy:"Events Team",uploadedAt:"Oct 6, 2024 4:45 PM"},{name:"Event_Budget_Breakdown.xlsx",size:"1.2 MB",type:"Excel",uploadedBy:"Finance Team",uploadedAt:"Oct 7, 2024 10:30 AM"},{name:"Dealer_Invitations_List.xlsx",size:"580 KB",type:"Excel",uploadedBy:"Sales Team",uploadedAt:"Oct 7, 2024 3:15 PM"}],spectators:[{name:"Marketing Team",role:"Presentation Support",avatar:"MT"},{name:"Events Management",role:"Logistics Coordination",avatar:"EM"}],auditTrail:[{type:"created",action:"Request Created",details:"Dealer meeting proposal submitted",user:"Neha Kapoor",timestamp:"Oct 6, 2024 2:00 PM"},{type:"assignment",action:"Assigned to Suresh Mehta",details:"Forwarded to Sales Director",user:"System",timestamp:"Oct 6, 2024 2:01 PM"},{type:"approval",action:"Approved by Suresh Mehta",details:"Sales approval completed",user:"Suresh Mehta",timestamp:"Oct 8, 2024 2:00 AM"},{type:"assignment",action:"Assigned to Anil Kapoor",details:"Forwarded to Finance Manager",user:"System",timestamp:"Oct 8, 2024 2:01 AM"},{type:"updated",action:"Documents Added",details:"Dealer invitations list uploaded",user:"Sales Team",timestamp:"Oct 7, 2024 3:15 PM"}],tags:["dealer-meeting","q4-review","event","bangalore"]},"RE-REQ-2024-008":{id:"RE-REQ-2024-008",title:"Cybersecurity Infrastructure Upgrade",description:"Comprehensive upgrade of cybersecurity infrastructure including next-gen firewall, intrusion detection system, endpoint protection for 500+ devices, security information and event management (SIEM) system, and employee security awareness training. Critical for protecting customer data and business operations.",category:"IT & Infrastructure",subcategory:"Security & Compliance",status:"pending",priority:"urgent",amount:"₹52,00,000",slaProgress:82,slaRemaining:"4 hours 20 minutes",slaEndDate:"Oct 8, 2024 6:00 PM",currentStep:2,totalSteps:3,template:"custom",initiator:{name:"Sameer Joshi",role:"Chief Information Security Officer",department:"Information Technology",email:"sameer.joshi@royalenfield.com",phone:"+91 98765 43287",avatar:"SJ"},department:"Information Technology",createdAt:"Oct 5, 2024 11:30 AM",updatedAt:"Oct 8, 2024 12:45 PM",dueDate:"2024-10-08T18:00:00Z",submittedDate:"2024-10-05T11:30:00Z",estimatedCompletion:"Oct 8, 2024",currentApprover:"Anil Kapoor",approverLevel:"2 of 3",conclusionRemark:"",approvalFlow:[{step:1,approver:"Vikram Singh",role:"Head - IT Operations",status:"approved",tatHours:24,actualHours:18,assignedAt:"2024-10-05T11:30:00Z",comment:"Critical security upgrade. Approve immediately.",timestamp:"Oct 6, 2024 5:30 AM"},{step:2,approver:"Anil Kapoor",role:"Finance Manager",status:"pending",tatHours:48,elapsedHours:55,assignedAt:"2024-10-06T05:30:00Z",comment:null,timestamp:null},{step:3,approver:"Ramesh Kulkarni",role:"VP Operations",status:"waiting",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null}],documents:[{name:"Security_Assessment_Report.pdf",size:"15.3 MB",type:"PDF",uploadedBy:"Sameer Joshi",uploadedAt:"Oct 5, 2024 11:45 AM"},{name:"Vendor_Solutions_Comparison.xlsx",size:"4.8 MB",type:"Excel",uploadedBy:"IT Security Team",uploadedAt:"Oct 5, 2024 3:30 PM"},{name:"Implementation_Roadmap.pptx",size:"7.6 MB",type:"PowerPoint",uploadedBy:"Project Management",uploadedAt:"Oct 6, 2024 10:15 AM"},{name:"Risk_Analysis_Report.pdf",size:"5.9 MB",type:"PDF",uploadedBy:"Security Consultant",uploadedAt:"Oct 6, 2024 4:45 PM"}],spectators:[{name:"Legal & Compliance",role:"Data Protection",avatar:"LC"},{name:"IT Infrastructure",role:"System Integration",avatar:"IT"}],auditTrail:[{type:"created",action:"Request Created",details:"Cybersecurity upgrade proposal submitted",user:"Sameer Joshi",timestamp:"Oct 5, 2024 11:30 AM"},{type:"assignment",action:"Assigned to Vikram Singh",details:"Forwarded to IT Operations Head",user:"System",timestamp:"Oct 5, 2024 11:31 AM"},{type:"approval",action:"Approved by Vikram Singh",details:"IT approval - marked as critical",user:"Vikram Singh",timestamp:"Oct 6, 2024 5:30 AM"},{type:"assignment",action:"Assigned to Anil Kapoor",details:"Forwarded to Finance Manager",user:"System",timestamp:"Oct 6, 2024 5:31 AM"},{type:"reminder",action:"Urgent Reminder",details:"TAT breach warning - 4 hours remaining",user:"System",timestamp:"Oct 8, 2024 12:45 PM"}],tags:["cybersecurity","urgent","critical","infrastructure","overdue"]}},UA={"RE-REQ-2024-CM-001":{id:"RE-REQ-2024-CM-001",title:"Dealer Marketing Activity Claim - Diwali Festival Campaign",description:"Claim request for dealer-led Diwali festival marketing campaign including showroom decoration, test ride events, customer engagement activities, and promotional merchandise distribution. Activity conducted at Royal Motors Mumbai dealership.",category:"Dealer Operations",subcategory:"Claim Management",status:"pending",priority:"standard",amount:"TBD",slaProgress:35,slaRemaining:"4 days 12 hours",slaEndDate:"Oct 16, 2024 5:00 PM",currentStep:1,totalSteps:8,template:"claim-management",templateName:"Claim Management",initiator:{name:"Sneha Patil",role:"Regional Marketing Coordinator",department:"Marketing - West Zone",email:"sneha.patil@royalenfield.com",phone:"+91 98765 43250",avatar:"SP"},department:"Marketing - West Zone",createdAt:"Oct 7, 2024 9:30 AM",updatedAt:"Oct 7, 2024 9:30 AM",dueDate:"2024-10-16T17:00:00Z",conclusionRemark:"",claimDetails:{activityName:"Diwali Festival Campaign 2024",activityType:"Marketing Activity",activityDate:"Oct 5, 2024",location:"Mumbai, Maharashtra",dealerCode:"RE-MH-001",dealerName:"Royal Motors Mumbai",dealerEmail:"dealer@royalmotorsmumbai.com",dealerPhone:"+91 98765 12345",dealerAddress:"123 Main Street, Andheri West, Mumbai, Maharashtra 400053",requestDescription:"Marketing campaign for Diwali festival including showroom decoration, test ride events, customer engagement activities, and promotional merchandise distribution at Royal Motors Mumbai dealership.",estimatedBudget:"₹2,45,000",periodStart:"Oct 1, 2024",periodEnd:"Oct 10, 2024"},approvalFlow:[{step:1,approver:"Royal Motors Mumbai (Dealer)",role:"Dealer - Document Upload",status:"pending",tatHours:72,elapsedHours:12,assignedAt:"2024-10-07T09:30:00Z",comment:null,timestamp:null,description:"Dealer uploads proposal document, cost breakup, timeline for closure, and other supporting documents"},{step:2,approver:"Sneha Patil (Initiator)",role:"Initiator Evaluation",status:"waiting",tatHours:48,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Initiator reviews dealer documents and approves or requests modifications"},{step:3,approver:"System Auto-Process",role:"IO Confirmation",status:"waiting",tatHours:1,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Automatic IO (Internal Order) confirmation generated upon initiator approval"},{step:4,approver:"Rajesh Kumar",role:"Department Lead Approval",status:"waiting",tatHours:72,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Department head approves and blocks budget in IO for this activity"},{step:5,approver:"Royal Motors Mumbai (Dealer)",role:"Dealer - Completion Documents",status:"waiting",tatHours:120,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Dealer submits activity completion documents and description"},{step:6,approver:"Sneha Patil (Initiator)",role:"Initiator Verification",status:"waiting",tatHours:48,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Initiator verifies completion documents and can modify approved amount"},{step:7,approver:"System Auto-Process",role:"E-Invoice Generation",status:"waiting",tatHours:1,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Auto-generate e-invoice based on final approved amount"},{step:8,approver:"Meera Patel",role:"Finance - Credit Note Issuance",status:"waiting",tatHours:48,elapsedHours:0,assignedAt:null,comment:null,timestamp:null,description:"Finance team issues credit note to dealer"}],documents:[{name:"Claim_Proposal_Diwali_2024.pdf",size:"1.8 MB",type:"PDF",uploadedBy:"Sneha Patil",uploadedAt:"Oct 7, 2024 9:35 AM"},{name:"Cost_Breakup_Detailed.xlsx",size:"450 KB",type:"Excel",uploadedBy:"Sneha Patil",uploadedAt:"Oct 7, 2024 9:38 AM"},{name:"Activity_Timeline.pdf",size:"320 KB",type:"PDF",uploadedBy:"Sneha Patil",uploadedAt:"Oct 7, 2024 9:40 AM"}],spectators:[{name:"Arjun Menon",role:"Brand Manager",avatar:"AM"},{name:"Finance Team",role:"Budget Monitoring",avatar:"FT"}],auditTrail:[{type:"created",action:"Claim Request Created",details:"Diwali festival campaign claim initiated using Claim Management template",user:"Sneha Patil",timestamp:"Oct 7, 2024 9:30 AM"},{type:"assignment",action:"Assigned to Dealer",details:"Dealer Royal Motors Mumbai assigned for document upload",user:"System",timestamp:"Oct 7, 2024 9:31 AM"},{type:"status_change",action:"Workflow Started",details:"Step 1: Dealer document upload phase initiated",user:"System",timestamp:"Oct 7, 2024 9:31 AM"}],tags:["claim-management","dealer-activity","marketing","diwali-campaign","template"]}};function yc(t,s=[],a){const[r,n]=h.useState(null),[i,l]=h.useState(!1),[o,d]=h.useState(!0),[c,m]=h.useState(null),[u,x]=h.useState(null),[p,g]=h.useState(!1),y=(T,k)=>(T||k||"NA").toString().split(" ").map(D=>D[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),f=T=>{const k=(T||"").toUpperCase();return k==="IN_PROGRESS"?"in-review":k==="PENDING"?"pending":k==="APPROVED"?"approved":k==="REJECTED"?"rejected":k==="CLOSED"?"closed":k==="SKIPPED"?"skipped":(T||"").toLowerCase()},b=h.useCallback(async()=>{var T,k,L,D,S,N,P,R,O,E,M,B,C;l(!0);try{const j=await Is.getWorkflowDetails(t);if(!j){console.warn("[useRequestDetails] No details returned from API");return}const U=j.workflow||{},$=Array.isArray(j.approvals)?j.approvals:[],_=Array.isArray(j.participants)?j.participants:[],se=Array.isArray(j.documents)?j.documents:[],W=j.summary||{},ce=Array.isArray(j.tatAlerts)?j.tatAlerts:[];ce.length>0;const Z=(W==null?void 0:W.currentLevel)||U.currentLevel||1,I=$.map(J=>{const Oe=J.levelNumber||0,xt=(J.status||"").toString().toUpperCase(),je=J.levelId||J.level_id;let $e=f(J.status);Oe>Z&&xt!=="APPROVED"&&xt!=="REJECTED"?$e="waiting":Oe===Z&&xt==="PENDING"&&($e="pending");const yt=ce.filter(kt=>kt.levelId===je);return{step:Oe,levelId:je,role:J.levelName||J.approverName||"Approver",status:$e,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.levelEndTime&&J.levelStartTime?Math.max(0,(new Date(J.levelEndTime).getTime()-new Date(J.levelStartTime).getTime())/(1e3*60*60)):void 0,comment:J.comments||void 0,timestamp:J.actionDate||void 0,levelStartTime:J.levelStartTime||J.tatStartTime,tatAlerts:yt,skipReason:J.skipReason||void 0,isSkipped:xt==="SKIPPED"||J.isSkipped||!1}}),V=_.filter(J=>(J.participantType||J.participant_type||"").toUpperCase()==="SPECTATOR").map(J=>({name:J.userName||J.user_name||J.userEmail||J.user_email,role:"Spectator",email:J.userEmail||J.user_email,avatar:y(J.userName||J.user_name,J.userEmail||J.user_email)})),z=J=>{var xt,je;if(!J)return;const Oe=_.find($e=>$e.userId===J||$e.user_id===J);return Oe!=null&&Oe.userName||Oe!=null&&Oe.user_name?Oe.userName||Oe.user_name:U.initiatorId===J?((xt=U.initiator)==null?void 0:xt.displayName)||((je=U.initiator)==null?void 0:je.email):J},X=se.map(J=>{const Oe=Number(J.fileSize||J.file_size||0),xt=(Oe/(1024*1024)).toFixed(2)+" MB";return{documentId:J.documentId||J.document_id,name:J.originalFileName||J.fileName||J.file_name,fileType:J.fileType||J.file_type||"",size:xt,sizeBytes:Oe,uploadedBy:z(J.uploadedBy||J.uploaded_by),uploadedAt:J.uploadedAt||J.uploaded_at}}),Y=Array.isArray(j.activities)?j.activities.filter(J=>(J.type||"").toLowerCase()!=="sla_warning"):[];let G=null;if(U.isPaused||!1)try{G=await sm(U.requestId)}catch{}let me=null,Te=null,Se=null,re=null;if(U.workflowType==="CLAIM_MANAGEMENT"||U.templateType==="claim-management")try{const J=await Ne.get(`/dealer-claims/${U.requestId}`),Oe=((T=J.data)==null?void 0:T.data)||J.data;if(Oe){me=Oe.claimDetails||Oe.claim_details,Te=Oe.proposalDetails||Oe.proposal_details,Se=Oe.completionDetails||Oe.completion_details,re=Oe.internalOrder||Oe.internal_order||null;const xt=Oe.budgetTracking||Oe.budget_tracking||null,je=Oe.invoice||null,$e=Oe.creditNote||Oe.credit_note||null,yt=Oe.completionExpenses||Oe.completion_expenses||null;me&&(me.budgetTracking=xt,me.invoice=je,me.creditNote=$e,me.completionExpenses=yt)}else console.warn("[useRequestDetails] No claimData found in response")}catch(J){console.error("[useRequestDetails] Error fetching claim details:",{error:(J==null?void 0:J.message)||J,status:(k=J==null?void 0:J.response)==null?void 0:k.status,statusText:(L=J==null?void 0:J.response)==null?void 0:L.statusText,responseData:(D=J==null?void 0:J.response)==null?void 0:D.data,requestId:U.requestId})}const pe={...U,id:U.requestNumber||U.requestId,requestId:U.requestId,requestNumber:U.requestNumber,title:U.title,description:U.description,status:f(U.status),priority:(U.priority||"").toString().toLowerCase(),workflowType:U.workflowType||(U.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),approvalFlow:I,approvals:$,participants:_,documents:X,spectators:V,summary:W,sla:(W==null?void 0:W.sla)||U.sla||null,initiator:{name:((S=U.initiator)==null?void 0:S.displayName)||((N=U.initiator)==null?void 0:N.email),role:((P=U.initiator)==null?void 0:P.designation)||void 0,department:((R=U.initiator)==null?void 0:R.department)||void 0,email:((O=U.initiator)==null?void 0:O.email)||void 0,phone:((E=U.initiator)==null?void 0:E.phone)||void 0,avatar:y((M=U.initiator)==null?void 0:M.displayName,(B=U.initiator)==null?void 0:B.email)},createdAt:U.createdAt,updatedAt:U.updatedAt,totalSteps:U.totalLevels||1,currentStepRaw:(W==null?void 0:W.currentLevel)||U.currentLevel||1,currentStep:Math.min(Math.max(1,(W==null?void 0:W.currentLevel)||U.currentLevel||1),U.totalLevels||1),auditTrail:Y,conclusionRemark:U.conclusionRemark||null,closureDate:U.closureDate||null,pauseInfo:G||null,claimDetails:me||null,proposalDetails:Te||null,completionDetails:Se||null,internalOrder:re||null,budgetTracking:(me==null?void 0:me.budgetTracking)||null,invoice:(me==null?void 0:me.invoice)||null,creditNote:(me==null?void 0:me.creditNote)||null,completionExpenses:(me==null?void 0:me.completionExpenses)||null};n(pe);const ve=(C=a==null?void 0:a.email)==null?void 0:C.toLowerCase(),be=$.find(J=>{const Oe=(J.status||"").toString().toUpperCase(),xt=(J.approverEmail||"").toLowerCase(),je=J.levelNumber||0;return(Oe==="PENDING"||Oe==="IN_PROGRESS"||Oe==="PAUSED")&&xt===ve&&je===Z});x(be||null);const Le=a==null?void 0:a.userId;if(Le){const J=_.some(Oe=>(Oe.participantType||Oe.participant_type||"").toUpperCase()==="SPECTATOR"&&(Oe.userId||Oe.user_id)===Le);g(J)}else g(!1)}catch(j){console.error("[useRequestDetails] Error refreshing details:",j),alert("Failed to refresh request details. Please try again.")}finally{l(!1)}},[t,a]);h.useEffect(()=>{if(!t){d(!1);return}let T=!0;return d(!0),m(null),(async()=>{var k,L,D,S,N,P,R,O,E,M,B,C,j,U;try{const $=await Is.getWorkflowDetails(t);if(!T||!$){T&&d(!1);return}const _=$.workflow||{},se=Array.isArray($.approvals)?$.approvals:[],W=Array.isArray($.participants)?$.participants:[],ce=Array.isArray($.documents)?$.documents:[],Z=$.summary||{},I=Array.isArray($.tatAlerts)?$.tatAlerts:[],V=(_.priority||"").toString().toLowerCase(),z=(Z==null?void 0:Z.currentLevel)||_.currentLevel||1,X=se.map(je=>{const $e=je.levelNumber||0,yt=(je.status||"").toString().toUpperCase(),kt=je.levelId||je.level_id;let lt=f(je.status);yt==="PAUSED"?lt="paused":$e>z&&yt!=="APPROVED"&&yt!=="REJECTED"?lt="waiting":$e===z&&(yt==="PENDING"||yt==="IN_PROGRESS")&&(lt=yt==="IN_PROGRESS"?"in-review":"pending");const Fs=I.filter(qs=>qs.levelId===kt);return{step:$e,levelId:kt,role:je.levelName||je.approverName||"Approver",status:lt,approver:je.approverName||je.approverEmail,approverId:je.approverId||je.approver_id,approverEmail:je.approverEmail,tatHours:Number(je.tatHours||0),elapsedHours:Number(je.elapsedHours||0),remainingHours:Number(je.remainingHours||0),tatPercentageUsed:Number(je.tatPercentageUsed||0),actualHours:je.elapsedHours!==void 0&&je.elapsedHours!==null?Number(je.elapsedHours):void 0,comment:je.comments||void 0,timestamp:je.actionDate||void 0,levelStartTime:je.levelStartTime||je.tatStartTime,tatAlerts:Fs}}),Y=W.filter(je=>(je.participantType||"").toUpperCase()==="SPECTATOR").map(je=>({name:je.userName||je.userEmail,role:"Spectator",avatar:y(je.userName,je.userEmail)})),G=je=>{var yt,kt;if(!je)return;const $e=W.find(lt=>lt.userId===je);return $e!=null&&$e.userName?$e.userName:_.initiatorId===je?((yt=_.initiator)==null?void 0:yt.displayName)||((kt=_.initiator)==null?void 0:kt.email):je},ie=ce.map(je=>{const $e=Number(je.fileSize||0),yt=($e/(1024*1024)).toFixed(2)+" MB";return{documentId:je.documentId||je.document_id,name:je.originalFileName||je.fileName,fileType:je.fileType||je.file_type||"",size:yt,sizeBytes:$e,uploadedBy:G(je.uploadedBy),uploadedAt:je.uploadedAt}}),me=Array.isArray($.activities)?$.activities.filter(je=>(je.type||"").toLowerCase()!=="sla_warning"):[];let Te=null;if(_.isPaused||!1)try{Te=await sm(_.requestId)}catch{}let re=null,pe=null,ve=null,be=null;if(_.workflowType==="CLAIM_MANAGEMENT"||_.templateType==="claim-management")try{const je=await Ne.get(`/dealer-claims/${_.requestId}`),$e=((k=je.data)==null?void 0:k.data)||je.data;if($e){re=$e.claimDetails||$e.claim_details,pe=$e.proposalDetails||$e.proposal_details,ve=$e.completionDetails||$e.completion_details,be=$e.internalOrder||$e.internal_order||null;const yt=$e.budgetTracking||$e.budget_tracking||null,kt=$e.invoice||null,lt=$e.creditNote||$e.credit_note||null,Fs=$e.completionExpenses||$e.completion_expenses||null;re&&(re.budgetTracking=yt,re.invoice=kt,re.creditNote=lt,re.completionExpenses=Fs)}}catch(je){console.error("[useRequestDetails] Initial load - Error fetching claim details:",{error:(je==null?void 0:je.message)||je,status:(L=je==null?void 0:je.response)==null?void 0:L.status,requestId:_.requestId})}const Le={id:_.requestNumber||_.requestId,requestId:_.requestId,title:_.title,description:_.description,priority:V,status:f(_.status),workflowType:_.workflowType||(_.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),summary:Z,initiator:{name:((D=_.initiator)==null?void 0:D.displayName)||((S=_.initiator)==null?void 0:S.email),role:((N=_.initiator)==null?void 0:N.designation)||void 0,department:((P=_.initiator)==null?void 0:P.department)||void 0,email:((R=_.initiator)==null?void 0:R.email)||void 0,phone:((O=_.initiator)==null?void 0:O.phone)||void 0,avatar:y((E=_.initiator)==null?void 0:E.displayName,(M=_.initiator)==null?void 0:M.email)},createdAt:_.createdAt,updatedAt:_.updatedAt,totalSteps:_.totalLevels||1,currentStepRaw:(Z==null?void 0:Z.currentLevel)||_.currentLevel||1,currentStep:Math.min(Math.max(1,(Z==null?void 0:Z.currentLevel)||_.currentLevel||1),_.totalLevels||1),approvalFlow:X,approvals:se,documents:ie,spectators:Y,auditTrail:me,conclusionRemark:_.conclusionRemark||null,closureDate:_.closureDate||null,pauseInfo:Te||null,claimDetails:re||null,proposalDetails:pe||null,completionDetails:ve||null,internalOrder:be||null,budgetTracking:(re==null?void 0:re.budgetTracking)||null,invoice:(re==null?void 0:re.invoice)||null,creditNote:(re==null?void 0:re.creditNote)||null,completionExpenses:(re==null?void 0:re.completionExpenses)||null};n(Le);const J=(B=a==null?void 0:a.email)==null?void 0:B.toLowerCase(),Oe=se.find(je=>{const $e=(je.status||"").toString().toUpperCase(),yt=(je.approverEmail||"").toLowerCase(),kt=je.levelNumber||0;return($e==="PENDING"||$e==="IN_PROGRESS"||$e==="PAUSED")&&yt===J&&kt===z});x(Oe||null);const xt=a==null?void 0:a.userId;if(xt){const je=W.some($e=>($e.participantType||"").toUpperCase()==="SPECTATOR"&&$e.userId===xt);g(je)}else g(!1)}catch($){if(console.error("[useRequestDetails] Error loading request details:",$),T){if(((C=$==null?void 0:$.response)==null?void 0:C.status)===403){const _=((U=(j=$==null?void 0:$.response)==null?void 0:j.data)==null?void 0:U.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:_})}n(null)}}finally{T&&d(!1)}})(),()=>{T=!1}},[t,a]);const v=h.useMemo(()=>{if(r)return r;const T=Mp[t];if(T)return T;const k=UA[t];if(k)return k;const L=s.find(D=>D.id===t||D.requestNumber===t||D.request_number===t);return L||null},[t,s,r]),A=h.useMemo(()=>{var L,D,S;if(!v||!a)return!1;const T=(L=a==null?void 0:a.email)==null?void 0:L.toLowerCase(),k=(S=(D=v.initiator)==null?void 0:D.email)==null?void 0:S.toLowerCase();return T===k},[v,a]),w=h.useMemo(()=>{var k;if(!v)return[];const T=[];return(k=v.initiator)!=null&&k.email&&T.push({email:v.initiator.email.toLowerCase(),participantType:"INITIATOR",name:v.initiator.name}),v.approvalFlow&&Array.isArray(v.approvalFlow)&&v.approvalFlow.forEach(L=>{L.approverEmail&&T.push({email:L.approverEmail.toLowerCase(),participantType:"APPROVER",name:L.approver})}),v.spectators&&Array.isArray(v.spectators)&&v.spectators.forEach(L=>{L.email&&T.push({email:L.email.toLowerCase(),participantType:"SPECTATOR",name:L.name})}),v.participants&&Array.isArray(v.participants)&&v.participants.forEach(L=>{const D=(L.userEmail||L.email||"").toLowerCase(),S=(L.participantType||L.participant_type||"").toUpperCase(),N=L.userName||L.user_name||L.name;D&&S&&!T.find(P=>P.email===D)&&T.push({email:D,participantType:S,name:N})}),T},[v]);return h.useEffect(()=>{if(!t||!r)return;const T=Lr();if(!T)return;const k=L=>{((L==null?void 0:L.requestId)===r.requestId||(L==null?void 0:L.requestNumber)===t)&&b()};return T.on("request:updated",k),()=>{T.off("request:updated",k)}},[t,r,b]),{request:v,apiRequest:r,loading:o,refreshing:i,refreshDetails:b,currentApprovalLevel:u,isSpectator:p,isInitiator:A,existingParticipants:w,accessDenied:c}}function _p(t,s,a,r){const[n,i]=h.useState([]),[l,o]=h.useState(0),[d,c]=h.useState([]);return h.useEffect(()=>{if(!t){console.warn("[useRequestSocket] No requestIdentifier, cannot join socket room");return}let m=!0,u=t;return(async()=>{var y;try{const f=await Is.getWorkflowDetails(t);(y=f==null?void 0:f.workflow)!=null&&y.requestId&&m&&(u=f.workflow.requestId)}catch(f){console.error("[useRequestSocket] Failed to resolve UUID:",f)}if(!m)return;const x=Lr();if(!x){console.error("[useRequestSocket] Socket not available");return}const p=r==null?void 0:r.userId,g=()=>{Vl(x,u,p)};return x.connected?g():x.on("connect",g),()=>{m&&(x.off("connect",g),Tx(x,u))}})(),()=>{m=!1}},[t,r]),h.useEffect(()=>{!t||!s||(async()=>{try{const m=await Mr(t),u=s.auditTrail||[],x=[...m,...u];x.sort((p,g)=>{const y=new Date(p.createdAt||p.created_at||p.timestamp||0).getTime(),f=new Date(g.createdAt||g.created_at||g.timestamp||0).getTime();return y-f}),i(x)}catch(m){console.error("[useRequestSocket] Failed to fetch and merge messages:",m)}})()},[t,s]),h.useEffect(()=>{if(!t)return;const m=Lr();if(!m)return;const u=p=>{a!=="worknotes"&&o(g=>g+1),(async()=>{try{const g=await Mr(t),y=(s==null?void 0:s.auditTrail)||[],f=[...g,...y].sort((b,v)=>{const A=new Date(b.createdAt||b.created_at||b.timestamp||0).getTime(),w=new Date(v.createdAt||v.created_at||v.timestamp||0).getTime();return A-w});i(f)}catch(g){console.error("[useRequestSocket] Failed to refresh messages:",g)}})()},x=p=>{const g=p.type==="breach"?"⏰":p.type==="threshold2"?"⚠️":"⏳";(async()=>{try{const y=await Is.getWorkflowDetails(t);y&&(Array.isArray(y.tatAlerts)&&y.tatAlerts,"Notification"in window&&Notification.permission==="granted"&&new Notification(`${g} TAT Alert`,{body:p.message,icon:"/favicon.ico",tag:`tat-${p.requestId}-${p.type}`,requireInteraction:!1}))}catch(y){console.error("[useRequestSocket] Failed to refresh after TAT alert:",y)}})()};return m.on("noteHandler",u),m.on("worknote:new",u),m.on("tat:alert",x),()=>{m.off("noteHandler",u),m.off("worknote:new",u),m.off("tat:alert",x)}},[t,a,s]),h.useEffect(()=>{a==="worknotes"&&o(0)},[a]),{mergedMessages:n,unreadWorkNotes:l,workNoteAttachments:d,setWorkNoteAttachments:c}}async function mn(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 Ne.post("/documents",r,{headers:{"Content-Type":"multipart/form-data"}}),i=((l=n.data)==null?void 0:l.data)||n.data;return{documentId:(i==null?void 0:i.documentId)||(i==null?void 0:i.document_id)||"",storageUrl:(i==null?void 0:i.storageUrl)||(i==null?void 0:i.storage_url),fileName:(i==null?void 0:i.fileName)||(i==null?void 0:i.file_name)||t.name,originalFileName:(i==null?void 0:i.originalFileName)||(i==null?void 0:i.original_file_name)||t.name}}function Lp(t,s){const[a,r]=h.useState(!1),[n,i]=h.useState(null),[l,o]=h.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[d,c]=h.useState({show:!1,errors:[]});h.useEffect(()=>{(async()=>{try{const g=await Qs("DOCUMENT_POLICY"),y={};g.forEach(A=>{y[A.configKey]=A.configValue});const f=parseInt(y.MAX_FILE_SIZE_MB||"10"),v=(y.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(A=>A.trim().toLowerCase());o({maxFileSizeMB:f,allowedFileTypes:v})}catch(g){console.error("Failed to load document policy:",g)}})()},[]);const m=p=>{const g=l.maxFileSizeMB*1024*1024;if(p.size>g)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${l.maxFileSizeMB}MB. Current size: ${(p.size/(1024*1024)).toFixed(2)}MB`};const y=p.name.toLowerCase(),f=y.substring(y.lastIndexOf(".")+1);return l.allowedFileTypes.includes(f)?{valid:!0}:{valid:!1,reason:`File type "${f}" is not allowed. Allowed types: ${l.allowedFileTypes.join(", ")}`}},u=async p=>{var v,A;const g=p.target.files;if(!g||g.length===0)return;const y=Array.from(g),f=[],b=[];if(y.forEach(w=>{const T=m(w);T.valid?b.push(w):f.push({fileName:w.name,reason:T.reason||"Unknown validation error"})}),f.length>0&&c({show:!0,errors:f}),b.length===0){p.target&&(p.target.value="");return}r(!0);try{const w=b[0],T=t==null?void 0:t.requestId;if(!T){Q.error("Request ID not found");return}w&&await mn(w,T,"SUPPORTING"),await s(),b.length<y.length?Q.warning(`${b.length} of ${y.length} file(s) were uploaded. ${f.length} file(s) were rejected.`):Q.success("Document uploaded successfully")}catch(w){console.error("[useDocumentUpload] Upload error:",w),Q.error(((A=(v=w==null?void 0:w.response)==null?void 0:v.data)==null?void 0:A.error)||"Failed to upload document")}finally{r(!1),p.target&&(p.target.value="")}};return{uploadingDocument:a,handleDocumentUpload:u,triggerFileInput:()=>{const p=document.createElement("input");p.type="file",p.accept=l.allowedFileTypes.map(g=>`.${g}`).join(","),p.onchange=u,p.click()},previewDocument:n,setPreviewDocument:i,documentPolicy:l,documentError:d,setDocumentError:c}}const BA="modulepreload",VA=function(t){return"/"+t},Cu={},Tl=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(d=>{if(d=VA(d),d in Cu)return;Cu[d]=!0;const c=d.endsWith(".css"),m=c?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${m}`))return;const u=document.createElement("link");if(u.rel=c?"stylesheet":BA,c||(u.as="script"),u.crossOrigin="",u.href=d,o&&u.setAttribute("nonce",o),document.head.appendChild(u),c)return new Promise((x,p)=>{u.addEventListener("load",x),u.addEventListener("error",()=>p(new Error(`Unable to preload CSS for ${d}`)))})}))}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 Op(t,s,a,r,n,i,l){const[o,d]=h.useState(""),[c,m]=h.useState(!1),[u,x]=h.useState(!1),[p,g]=h.useState(!1),[y,f]=h.useState(0),[b,v]=h.useState(!1),[A,w]=h.useState(!1),[T,k]=h.useState(0),L=async()=>{var R;const N=(t==null?void 0:t.conclusionRemark)||(t==null?void 0:t.conclusion_remark),P=(t==null?void 0:t.aiGeneratedConclusion)||(t==null?void 0:t.ai_generated_conclusion);if(N||P){d(N||P),g(!!P);return}try{const{getConclusion:O}=await Tl(async()=>{const{getConclusion:M}=await import("./conclusionApi-BIX8LEl5.js");return{getConclusion:M}},__vite__mapDeps([0,1,2,3,4,5,6,7])),E=await O(t.requestId||s);E&&(E.aiGeneratedRemark||E.finalRemark)&&(d(E.finalRemark||E.aiGeneratedRemark||""),g(!!E.aiGeneratedRemark))}catch(O){((R=O==null?void 0:O.response)==null?void 0:R.status)!==404&&console.error("[useConclusionRemark] Error fetching conclusion:",O)}},D=async()=>{if(!A)try{m(!0),v(!1);const{generateConclusion:N}=await Tl(async()=>{const{generateConclusion:E}=await import("./conclusionApi-BIX8LEl5.js");return{generateConclusion:E}},__vite__mapDeps([0,1,2,3,4,5,6,7])),P=await N(t.requestId||s),R=y+1;if(f(R),!(P!=null&&P.aiGeneratedRemark)||P.aiGeneratedRemark.toLowerCase().includes("unable to generate")||P.aiGeneratedRemark.toLowerCase().includes("sorry")){const E=T+1;k(E),E>=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),d((P==null?void 0:P.aiGeneratedRemark)||""),g(!1);return}d(P.aiGeneratedRemark),g(!0),k(0),R>=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(N){console.error("[useConclusionRemark] AI generation failed:",N);const P=T+1;k(P),g(!1),P>=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)}},S=async()=>{var P,R;const N=o.replace(/<[^>]*>/g,"").trim();if(!N){i==null||i({success:!1,title:"Validation Error",message:"Conclusion remark cannot be empty"}),l==null||l(!0);return}if(N.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:O}=await Tl(async()=>{const{finalizeConclusion:E}=await import("./conclusionApi-BIX8LEl5.js");return{finalizeConclusion:E}},__vite__mapDeps([0,1,2,3,4,5,6,7]));await O(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(O){i==null||i({success:!1,title:"Error",message:((R=(P=O.response)==null?void 0:P.data)==null?void 0:R.error)||"Failed to finalize conclusion"}),l==null||l(!0)}finally{x(!1)}};return h.useEffect(()=>{var E;const N=(E=t==null?void 0:t.status)==null?void 0:E.toLowerCase();if(!((N==="approved"||N==="rejected"||N==="closed")&&a&&!o))return;const R=(t==null?void 0:t.conclusionRemark)||(t==null?void 0:t.conclusion_remark),O=(t==null?void 0:t.aiGeneratedConclusion)||(t==null?void 0:t.ai_generated_conclusion);R||O?(d(R||O),g(!!O)):L()},[t==null?void 0:t.status,t==null?void 0:t.conclusionRemark,t==null?void 0:t.aiGeneratedConclusion,a,o]),{conclusionRemark:o,setConclusionRemark:d,conclusionLoading:c,conclusionSubmitting:u,aiGenerated:p,handleGenerateConclusion:D,handleFinalizeConclusion:S,generationAttempts:y,generationFailed:b,maxAttemptsReached:A}}function $p(t,s,a){const[r,n]=h.useState(!1),[i,l]=h.useState(!1),[o,d]=h.useState(!1),[c,m]=h.useState(!1),[u,x]=h.useState(!1),[p,g]=h.useState(!1),[y,f]=h.useState(null),[b,v]=h.useState(null);return{showApproveModal:r,setShowApproveModal:n,showRejectModal:i,setShowRejectModal:l,showAddApproverModal:o,setShowAddApproverModal:d,showAddSpectatorModal:c,setShowAddSpectatorModal:m,showSkipApproverModal:u,setShowSkipApproverModal:x,showActionStatusModal:p,setShowActionStatusModal:g,skipApproverData:y,setSkipApproverData:f,actionStatus:b,setActionStatus:v,handleApproveConfirm:async D=>{var N,P;const S=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!S){alert("Approval level not found");return}await cn(t,S,D||""),await new Promise(R=>setTimeout(R,500)),await a(),(N=window==null?void 0:window.closeModal)==null||N.call(window),(P=window==null?void 0:window.toast)==null||P.call(window,"Approved successfully")},handleRejectConfirm:async D=>{var N,P;if(!(D!=null&&D.trim())){alert("Comments & remarks are required");return}const S=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!S){alert("Approval level not found");return}await Ar(t,S,D.trim(),D.trim()),await a(),(N=window==null?void 0:window.closeModal)==null||N.call(window),(P=window==null?void 0:window.toast)==null||P.call(window,"Rejected successfully")},handleAddApprover:async(D,S,N)=>{var P,R;try{await Hx(t,D,S,N),await a(),d(!1),v==null||v({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${N} with ${S}h TAT`}),g==null||g(!0)}catch(O){throw v==null||v({success:!1,title:"Failed to Add Approver",message:((R=(P=O==null?void 0:O.response)==null?void 0:P.data)==null?void 0:R.error)||"Failed to add approver. Please try again."}),g==null||g(!0),O}},handleSkipApprover:async D=>{var S,N;if(y)try{await Xj(t,y.levelId,D),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(P){throw v==null||v({success:!1,title:"Failed to Skip Approver",message:((N=(S=P==null?void 0:P.response)==null?void 0:S.data)==null?void 0:N.error)||"Failed to skip approver. Please try again."}),g==null||g(!0),P}},handleAddSpectator:async D=>{var S,N;try{await Wx(t,D),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(P){throw v==null||v({success:!1,title:"Failed to Add Spectator",message:((N=(S=P==null?void 0:P.response)==null?void 0:S.data)==null?void 0:N.error)||"Failed to add spectator. Please try again."}),g==null||g(!0),P}}}}const zA=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 Ur({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(Pe,{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 "]}),is(t.uploadedAt)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&zA(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(ht,{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(Nt,{className:"w-4 h-4"})})]})]})}function HA({request:t,workNoteAttachments:s,uploadingDocument:a,documentPolicy:r,triggerFileInput:n,setPreviewDocument:i,downloadDocument:l}){return e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[e.jsxs(te,{children:[e.jsx(ue,{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(xe,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Pe,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Documents"]}),e.jsx(ke,{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(Bs,{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,d)=>e.jsx(Ur,{document:o,onPreview:c=>i(c),onDownload:l,testId:"request-document"},d))}):e.jsx("p",{className:"text-sm text-gray-500 text-center py-8","data-testid":"no-documents",children:"No documents uploaded yet"})})]}),e.jsxs(te,{children:[e.jsxs(ue,{children:[e.jsxs(xe,{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(ke,{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,d)=>e.jsx(Ur,{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:c=>i(c),onDownload:async c=>{const{downloadWorkNoteAttachment:m}=require("@/services/workflowApi");await m(c)},testId:"worknote-attachment"},o.attachmentId||d))}):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 WA=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"}}},GA=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}}},KA=t=>{switch(t){case"approval":case"approved":return e.jsx(De,{className:"w-5 h-5 text-green-600"});case"rejection":case"rejected":return e.jsx(jt,{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(Bt,{className:"w-5 h-5 text-orange-600"});case"assignment":return e.jsx(Ti,{className:"w-5 h-5 text-purple-600"});case"created":return e.jsx(Pe,{className:"w-5 h-5 text-blue-600"});case"reminder":return e.jsx(Xe,{className:"w-5 h-5 text-yellow-600"});case"document_added":return e.jsx(Ni,{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(Dt,{className:"w-5 h-5 text-gray-600"})}};function YA({request:t}){return e.jsxs(te,{children:[e.jsxs(ue,{children:[e.jsxs(xe,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Dt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Activity Timeline"]}),e.jsx(ke,{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:KA(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:is(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(Dt,{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 Up({open:t,onClose:s,success:a,title:r,message:n}){return e.jsx(mt,{open:t,onOpenChange:s,children:e.jsxs(ot,{className:"sm:max-w-md",children:[e.jsx(ut,{children:e.jsxs(ct,{className:"flex items-center gap-2",children:[a?e.jsx(De,{className:"w-5 h-5 text-green-600"}):e.jsx(Ge,{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(De,{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(jt,{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(Tt,{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 Bp({open:t,onClose:s,onConfirm:a,existingParticipants:r=[]}){const[n,i]=h.useState(""),[l,o]=h.useState(!1),[d,c]=h.useState([]),[m,u]=h.useState(!1),[x,p]=h.useState(null),g=h.useRef(null),y=h.useRef(null),[f,b]=h.useState({open:!1,type:"error",email:"",message:""}),[v,A]=h.useState({open:!1,violations:[]}),[w,T]=h.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20});h.useEffect(()=>{t&&(async()=>{var P;try{const R=await Qs("WORKFLOW_SHARING"),O=await Qs("TAT_SETTINGS"),E=[...R,...O],M={};E.forEach(B=>{M[B.configKey]=B.configValue}),T({maxApprovalLevels:parseInt(M.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(M.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((P=M.ALLOW_ADD_SPECTATOR)==null?void 0:P.toLowerCase())==="true",maxSpectators:parseInt(M.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(R){console.error("Failed to load system policy:",R)}})()},[t]);const k=async()=>{var C,j;const N=n.trim().toLowerCase();if(!N){b({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(N)){b({open:!0,type:"error",email:N,message:"Please enter a valid email address"});return}const R=r.find(U=>(U.email||"").toLowerCase()===N);if(R){const U=((C=R.participantType)==null?void 0:C.toUpperCase())||"PARTICIPANT",$=R.name||N;if(U==="INITIATOR"){b({open:!0,type:"error",email:N,message:`${$} is the request initiator and cannot be added as a spectator.`});return}else if(U==="APPROVER"){b({open:!0,type:"error",email:N,message:`${$} is already an approver on this request and cannot be added as a spectator.`});return}else if(U==="SPECTATOR"){b({open:!0,type:"error",email:N,message:`${$} is already a spectator on this request.`});return}else{b({open:!0,type:"error",email:N,message:`${$} is already a participant on this request.`});return}}const O=[];w.allowSpectators||O.push({type:"Spectators Not Allowed",message:"Adding spectators is not allowed by system policy."});const M=r.filter(U=>(U.participantType||"").toUpperCase()==="SPECTATOR").length;M>=w.maxSpectators&&O.push({type:"Maximum Spectators Exceeded",message:"This request has reached the maximum number of spectators allowed.",currentValue:M,maxValue:w.maxSpectators});const B=r.length+1;if(B>w.maxParticipants&&O.push({type:"Maximum Participants Exceeded",message:"Adding this spectator would exceed the maximum participants limit.",currentValue:B,maxValue:w.maxParticipants}),O.length>0){A({open:!0,violations:O});return}if(!x||x.email.toLowerCase()!==N)try{const $=((j=(await oa(N,1)).data)==null?void 0:j.data)||[];if($.length===0){b({open:!0,type:"not-found",email:N,message:""});return}const _=$[0];await ia({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})}catch(U){console.error("Failed to validate spectator:",U),b({open:!0,type:"error",email:N,message:"Failed to validate user. Please try again."});return}try{o(!0),await a(N),i(""),p(null),s()}catch(U){console.error("Failed to add spectator:",U)}finally{o(!1)}},L=()=>{l||(i(""),p(null),c([]),u(!1),s())};h.useEffect(()=>{d.length>0&&y.current&&y.current.scrollTo({top:y.current.scrollHeight,behavior:"smooth"})},[d.length]),h.useEffect(()=>()=>{g.current&&clearTimeout(g.current)},[]);const D=N=>{if(i(N),x&&x.email.toLowerCase()!==N.toLowerCase()&&p(null),g.current&&clearTimeout(g.current),!N||!N.startsWith("@")||N.length<2){c([]),u(!1);return}u(!0),g.current=setTimeout(async()=>{var P;try{const R=N.slice(1),E=((P=(await oa(R,10)).data)==null?void 0:P.data)||[];c(E)}catch(R){console.error("Search failed:",R),c([])}finally{u(!1)}},300)},S=async N=>{try{await ia({userId:N.userId,email:N.email,displayName:N.displayName,firstName:N.firstName,lastName:N.lastName,department:N.department,phone:N.phone,mobilePhone:N.mobilePhone,designation:N.designation,jobTitle:N.jobTitle,manager:N.manager,employeeId:N.employeeId,employeeNumber:N.employeeNumber,secondEmail:N.secondEmail,location:N.location}),i(N.email),p(N),c([]),u(!1)}catch(P){console.error("Failed to ensure user exists:",P),b({open:!0,type:"error",email:N.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(mt,{open:t,onOpenChange:L,children:[e.jsxs(ot,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:L,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(ut,{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(ht,{className:"w-5 h-5 text-purple-600"})}),e.jsx(ct,{className:"text-xl font-bold text-gray-900",children:"Add Spectator"})]})}),e.jsxs("div",{ref:y,className:"space-y-4 px-6 py-4 pb-8 overflow-y-auto flex-1",children:[e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed",children:"Add a spectator to this request. They will receive notifications but cannot approve or reject."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Email Address"}),e.jsxs("div",{className:"relative",children:[e.jsx(ki,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(_e,{type:"text",placeholder:"@username or user@example.com",value:n,onChange:N=>D(N.target.value),className:"pl-10 h-11 border-gray-300",disabled:l,autoFocus:!0}),(m||d.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..."}):d.length>0?e.jsx("ul",{className:"divide-y",children:d.map(N=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>S(N),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(rs,{className:"h-8 w-8",children:e.jsx(ns,{className:"bg-purple-100 text-purple-800 text-xs font-semibold",children:(N.displayName||N.email).split(" ").map(P=>P[0]).join("").slice(0,2).toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:N.displayName||[N.firstName,N.lastName].filter(Boolean).join(" ")||N.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:N.email}),N.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:N.designation})]})]})},N.userId))}):null})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Type ",e.jsx("span",{className:"font-semibold",children:"@username"})," to search for users, or enter email directly."]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(F,{type:"button",variant:"outline",onClick:L,className:"flex-1 h-11 border-gray-300",disabled:l,children:"Cancel"}),e.jsxs(F,{type:"button",onClick:k,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:l||!n.trim(),children:[e.jsx(ht,{className:"w-4 h-4 mr-2"}),l?"Adding...":"Add Spectator"]})]})]}),e.jsx(mt,{open:f.open,onOpenChange:N=>b(P=>({...P,open:N})),children:e.jsxs(ot,{className:"sm:max-w-md",children:[e.jsxs(ut,{children:[e.jsx(ct,{className:"flex items-center gap-2",children:f.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(Ge,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ge,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(It,{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(Si,{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(Tt,{children:e.jsx(F,{onClick:()=>b(N=>({...N,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(_n,{open:v.open,onClose:()=>A({open:!1,violations:[]}),violations:v.violations,policyDetails:{maxApprovalLevels:w.maxApprovalLevels,maxParticipants:w.maxParticipants,allowSpectators:w.allowSpectators,maxSpectators:w.maxSpectators}})]})}function Vp({open:t,onClose:s,onConfirm:a,existingParticipants:r=[],currentLevels:n=[],maxApprovalLevels:i,onPolicyViolation:l}){const[o,d]=h.useState(""),[c,m]=h.useState(24),[u,x]=h.useState(null),[p,g]=h.useState(!1),[y,f]=h.useState([]),[b,v]=h.useState(!1),[A,w]=h.useState(null),T=h.useRef(null),k=h.useRef(null),[L,D]=h.useState({open:!1,type:"error",email:"",message:""}),S=n.filter(j=>j&&(j.status==="approved"||j.status==="rejected"||j.status==="skipped")),N=Math.max(1,S.length+1),P=Math.max(1,n.length+1),R=P>=N?Array.from({length:P-N+1},(j,U)=>N+U):[N];h.useEffect(()=>{R.length>0&&u===null&&x(R[0]||null)},[R.length,u]);const O=async()=>{var W,ce;const j=o.trim().toLowerCase();if(!j){D({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(j)){D({open:!0,type:"error",email:j,message:"Please enter a valid email address"});return}if(!c||c<=0){D({open:!0,type:"error",email:"",message:"Please enter valid TAT hours (minimum 1 hour)"});return}if(c>720){D({open:!0,type:"error",email:"",message:"TAT hours cannot exceed 720 hours (30 days)"});return}if(!u){D({open:!0,type:"error",email:"",message:"Please select an approval level"});return}if(u<N){D({open:!0,type:"error",email:"",message:`Cannot add approver at level ${u}. Minimum allowed level is ${N} (after completed levels)`});return}const $=n.length>0?Math.max(...n.map(Z=>Z.levelNumber),0):0,_=u>$?u:$+1;if(i&&_>i){l?l([{type:"Maximum Approval Levels Exceeded",message:`Adding an approver at level ${u} would result in ${_} approval levels, which exceeds the maximum allowed (${i}). Please remove an approver or contact your administrator.`,currentValue:_,maxValue:i}]):D({open:!0,type:"error",email:"",message:`Cannot add approver. This would exceed the maximum allowed approval levels (${i}). Current request has ${$} level(s).`});return}const se=r.find(Z=>(Z.email||"").toLowerCase()===j);if(se){const Z=((W=se.participantType)==null?void 0:W.toUpperCase())||"PARTICIPANT",I=se.name||j;if(Z==="INITIATOR"){D({open:!0,type:"error",email:j,message:`${I} is the request initiator and cannot be added as an approver.`});return}else if(Z==="APPROVER"){D({open:!0,type:"error",email:j,message:`${I} is already an approver on this request.`});return}else if(Z==="SPECTATOR"){D({open:!0,type:"error",email:j,message:`${I} is currently a spectator on this request and cannot be added as an approver. Please remove them as spectator first.`});return}else{D({open:!0,type:"error",email:j,message:`${I} is already a participant on this request.`});return}}if(!A||A.email.toLowerCase()!==j)try{const I=((ce=(await oa(j,1)).data)==null?void 0:ce.data)||[];if(I.length===0){D({open:!0,type:"not-found",email:j,message:""});return}const V=I[0];await ia({userId:V.userId,email:V.email,displayName:V.displayName,firstName:V.firstName,lastName:V.lastName,department:V.department,phone:V.phone,mobilePhone:V.mobilePhone,designation:V.designation,jobTitle:V.jobTitle,manager:V.manager,employeeId:V.employeeId,employeeNumber:V.employeeNumber,secondEmail:V.secondEmail,location:V.location})}catch(Z){console.error("Failed to validate approver:",Z),D({open:!0,type:"error",email:j,message:"Failed to validate user. Please try again."});return}try{g(!0),await a(j,c,u),d(""),m(24),x(null),w(null),s()}catch(Z){console.error("Failed to add approver:",Z)}finally{g(!1)}},E=()=>{p||(d(""),m(24),x(null),w(null),f([]),v(!1),s())},M=j=>{const U=j.toLowerCase();return U==="approved"?e.jsx(De,{className:"w-4 h-4 text-green-600"}):U==="rejected"?e.jsx(jt,{className:"w-4 h-4 text-red-600"}):U==="skipped"?e.jsx(Ge,{className:"w-4 h-4 text-orange-600"}):U==="in-review"||U==="pending"?e.jsx(Xe,{className:"w-4 h-4 text-blue-600"}):e.jsx(Xe,{className:"w-4 h-4 text-gray-400"})};h.useEffect(()=>{y.length>0&&k.current&&k.current.scrollTo({top:k.current.scrollHeight,behavior:"smooth"})},[y.length]),h.useEffect(()=>()=>{T.current&&clearTimeout(T.current)},[]);const B=j=>{if(d(j),A&&A.email.toLowerCase()!==j.toLowerCase()&&w(null),T.current&&clearTimeout(T.current),!j||!j.startsWith("@")||j.length<2){f([]),v(!1);return}v(!0),T.current=setTimeout(async()=>{var U;try{const $=j.slice(1),se=((U=(await oa($,10)).data)==null?void 0:U.data)||[];f(se)}catch($){console.error("Search failed:",$),f([])}finally{v(!1)}},300)},C=async j=>{try{await ia({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}),d(j.email),w(j),f([]),v(!1)}catch(U){console.error("Failed to ensure user exists:",U),D({open:!0,type:"error",email:j.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(mt,{open:t,onOpenChange:E,children:[e.jsxs(ot,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:E,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:p,children:[e.jsx(ft,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(ut,{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($t,{className:"w-5 h-5 text-blue-600"})}),e.jsx(ct,{className:"text-xl font-bold text-gray-900",children:"Add Approver"})]})}),e.jsxs("div",{ref:k,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(j=>j.levelNumber),0),"/",i,")"]})]})}),n.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{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(j=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-md ${j.status==="approved"?"bg-green-100 border border-green-200":j.status==="rejected"?"bg-red-100 border border-red-200":j.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:j.levelNumber}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:j.approverName}),e.jsxs("p",{className:"text-xs text-gray-500",children:[j.tatHours,"h TAT"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[M(j.status),e.jsx(ne,{variant:"outline",className:`text-xs ${j.status==="approved"?"bg-green-50 text-green-700 border-green-300":j.status==="rejected"?"bg-red-50 text-red-700 border-red-300":j.status==="skipped"?"bg-orange-50 text-orange-700 border-orange-300":"bg-blue-50 text-blue-700 border-blue-300"}`,children:j.status})]})]},j.levelNumber))}),e.jsxs("p",{className:"text-xs text-gray-500",children:["ℹ️ New approver can only be added at level ",N," or higher (after completed levels)"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{className:"text-sm font-medium text-gray-700",children:"Approval Level *"}),e.jsxs(Ve,{value:(u==null?void 0:u.toString())||"",onValueChange:j=>x(Number(j)),disabled:p,children:[e.jsx(He,{className:"h-11 border-gray-300",children:e.jsx(ze,{placeholder:"Select level"})}),e.jsx(We,{children:R.map(j=>e.jsx(K,{value:j.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(as,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Level ",j]}),j<=n.length&&e.jsxs("span",{className:"text-xs text-gray-500",children:["(will shift existing Level ",j,")"]})]})},j))})]}),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(le,{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(_e,{type:"number",min:"1",max:"720",value:c,onChange:j=>m(Number(j.target.value)),className:"h-11 border-gray-300 flex-1",disabled:p,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(Xe,{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(ki,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(_e,{type:"text",placeholder:"@username or user@example.com",value:o,onChange:j=>B(j.target.value),className:"pl-10 h-11 border-gray-300",disabled:p,autoFocus:!0}),(b||y.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:b?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):y.length>0?e.jsx("ul",{className:"divide-y",children:y.map(j=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>C(j),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(rs,{className:"h-8 w-8",children:e.jsx(ns,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:(j.displayName||j.email).split(" ").map(U=>U[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:E,className:"flex-1 h-11 border-gray-300",disabled:p,children:"Cancel"}),e.jsxs(F,{type:"button",onClick:O,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:p||!o.trim()||!u||!c,children:[e.jsx($t,{className:"w-4 h-4 mr-2"}),p?"Adding...":`Add at Level ${u||"?"}`]})]})]}),e.jsx(mt,{open:L.open,onOpenChange:j=>D(U=>({...U,open:j})),children:e.jsxs(ot,{className:"sm:max-w-md",children:[e.jsxs(ut,{children:[e.jsx(ct,{className:"flex items-center gap-2",children:L.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(Ge,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ge,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(It,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[L.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:L.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(Si,{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."]})})]}),L.type==="error"&&e.jsxs(e.Fragment,{children:[L.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:L.email}),"."]}),L.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:L.message})})]})]})})]}),e.jsx(Tt,{children:e.jsx(F,{onClick:()=>D(j=>({...j,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const ZA=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"}},XA=t=>{switch(t){case"online":return"Online";case"away":return"Away";case"offline":return"Offline";default:return"Unknown"}},QA=t=>t.replace(/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,(s,a,r,n)=>{const i=r+s.length,l=n[i];return!l||/\s|[.,!?;:]|@/.test(l)?'<span class="inline-flex items-center px-2.5 py-0.5 rounded-md bg-blue-50 text-blue-800 font-black text-base border-2 border-blue-400 shadow-sm">@'+a+"</span>":s}).replace(/\n/g,"<br />"),JA=t=>t<1024?t+" B":t<1024*1024?(t/1024).toFixed(1)+" KB":(t/(1024*1024)).toFixed(1)+" MB",Au=({type:t})=>{const s="w-4 h-4",a=t.toLowerCase();return a.includes("pdf")?e.jsx(Pe,{className:`${s} text-red-600`}):a.includes("excel")||a.includes("spreadsheet")||a.includes("xlsx")?e.jsx(c0,{className:`${s} text-green-600`}):a.includes("powerpoint")||a.includes("presentation")||a.includes("pptx")?e.jsx(Pe,{className:`${s} text-orange-600`}):a.includes("word")||a.includes("document")||a.includes("docx")?e.jsx(Pe,{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(Kn,{className:`${s} text-purple-600`}):e.jsx(Ni,{className:`${s} text-gray-600`})};function zp({requestId:t,messages:s,onSend:a,skipSocketJoin:r=!1,requestTitle:n,onAttachmentsExtracted:i,isInitiator:l=!1,isSpectator:o=!1,currentLevels:d=[],onAddApprover:c,maxApprovalLevels:m,onPolicyViolation:u}){const x=vr(),p=t||x.requestId||"",[g,y]=h.useState(""),[f,b]=h.useState(""),[v,A]=h.useState(!1),[w,T]=h.useState([]),[k,L]=h.useState(!1),[D,S]=h.useState([]),[N,P]=h.useState(null),[R,O]=h.useState(null),[E,M]=h.useState(!1),[B,C]=h.useState(!1),[j,U]=h.useState(!1),[$,_]=h.useState({success:!0,title:"",message:""}),se=h.useRef(null),W=h.useRef(null),ce=h.useRef(null),Z=h.useRef(!1),[I,V]=h.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[z,X]=h.useState({open:!1,errors:[]}),Y=h.useMemo(()=>({id:p,title:n||"Request Details"}),[p,n]),[G,ie]=h.useState([]),me=G.filter(q=>q.status==="online"),Te=w.filter(q=>q.content.toLowerCase().includes(f.toLowerCase())||q.user.name.toLowerCase().includes(f.toLowerCase())),Se=h.useMemo(()=>o!==void 0?o:!N||G.length===0?!1:G.some(q=>{const we=q.userId||q.user_id,ee=(q.role||"").toString().toUpperCase(),Fe=(q.participantType||q.participant_type||"").toString().toUpperCase();return we===N&&(ee==="SPECTATOR"||Fe==="SPECTATOR")}),[o,N,G]);h.useEffect(()=>{},[G]),h.useEffect(()=>{!p||!N||s||(async()=>{try{const q=await Mr(p),we=Array.isArray(q)?q.map(ee=>{const Fe=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:Fe===N,attachments:Array.isArray(ee.attachments)?ee.attachments.map(Ee=>({attachmentId:Ee.attachmentId||Ee.attachment_id,name:Ee.fileName||Ee.file_name||Ee.name,fileName:Ee.fileName||Ee.file_name||Ee.name,url:Ee.storageUrl||Ee.storage_url||Ee.url||"#",type:Ee.fileType||Ee.file_type||Ee.type||"file",fileType:Ee.fileType||Ee.file_type||Ee.type||"file",fileSize:Ee.fileSize||Ee.file_size})):void 0}}):[];T(we)}catch(q){console.error("[WorkNoteChat] Failed to load messages:",q)}})()},[p,N,s]);const re=h.useMemo(()=>{const q=[];return w.forEach(we=>{we.attachments&&we.attachments.length>0&&we.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:we.user.name,uploadedAt:we.timestamp,url:ee.storageUrl||ee.storage_url||ee.url||"#"})})}),q},[w]);h.useEffect(()=>{i&&re.length>=0&&i(re)},[re,i]);const pe=h.useMemo(()=>G.map(q=>({email:(q.email||"").toLowerCase(),participantType:q.role==="Initiator"?"INITIATOR":q.role==="Approver"?"APPROVER":q.role==="Spectator"?"SPECTATOR":"PARTICIPANT",name:q.name})),[G]),ve=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()}},be=()=>{var q;(q=se.current)==null||q.scrollIntoView({behavior:"smooth"})};h.useEffect(()=>{be()},[w]);const Le=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()}};h.useEffect(()=>{Z.current||p&&(async()=>{try{const q=await ws(p),we=Array.isArray(q==null?void 0:q.participants)?q.participants:[];if(we.length===0)return;const ee=we.map(Me=>{const Je=Me.participantType||Me.participant_type||"participant",Be=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(tt=>tt[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Le(Je.toString()),status:"offline",email:Me.userEmail||Me.user_email||"",permissions:["read","write","mention"],userId:Be}});Z.current=!0,ie(ee);let Fe=0;const Ee=3,Ke=()=>{ce.current&&ce.current.connected?(ce.current.emit("request:online-users",{requestId:p}),Fe++,Fe<Ee&&setTimeout(Ke,500)):(Fe++,Fe<Ee&&setTimeout(Ke,200))};setTimeout(Ke,100)}catch(q){console.error("[WorkNoteChat] ❌ Failed to load participants:",q)}})()},[p]),h.useEffect(()=>()=>{p&&(Z.current=!1)},[p]),h.useEffect(()=>{const q=localStorage.getItem("userData");if(q)try{const we=JSON.parse(q),ee=(we==null?void 0:we.id)||(we==null?void 0:we.userId)||(we==null?void 0:we.user_id)||null;P(ee)}catch(we){console.error("[WorkNoteChat] Failed to parse userData:",we)}},[]),h.useEffect(()=>{(async()=>{try{const we=await Qs("DOCUMENT_POLICY"),ee={};we.forEach(Me=>{ee[Me.configKey]=Me.configValue});const Fe=parseInt(ee.MAX_FILE_SIZE_MB||"10"),Ke=(ee.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(Me=>Me.trim().toLowerCase());V({maxFileSizeMB:Fe,allowedFileTypes:Ke})}catch(we){console.error("Failed to load document policy:",we)}})()},[]),h.useEffect(()=>{if(!N)return;let q=p;return(async()=>{var we;try{const ee=await ws(p);(we=ee==null?void 0:ee.workflow)!=null&&we.requestId&&(q=ee.workflow.requestId)}catch{}try{const ee=Lr();r?ie(rt=>rt.map(gt=>gt.userId===N?{...gt,status:"online"}:gt)):(Vl(ee,q,N),ie(rt=>rt.map(gt=>gt.userId===N?{...gt,status:"online"}:gt)));const Fe=rt=>{const st=(rt==null?void 0:rt.note)||rt;if(!st)return;const gt=st.noteId||st.id;T(qt=>{if(qt.some(wt=>wt.id===gt))return qt;const Et=st.userName||st.user_name||"User",ga=st.userRole||st.user_role,fa=ve(ga),Ma=st.userId||st.user_id,Ca={id:gt||String(Date.now()),user:{name:Et,avatar:Et.split(" ").map(wt=>wt[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:fa},content:st.message||"",timestamp:st.createdAt||new Date().toISOString(),isCurrentUser:Ma===N,attachments:Array.isArray(st.attachments)?st.attachments.map(wt=>({attachmentId:wt.attachmentId||wt.attachment_id,name:wt.fileName||wt.file_name||wt.name,fileName:wt.fileName||wt.file_name||wt.name,url:wt.storageUrl||wt.storage_url||wt.url||"#",type:wt.fileType||wt.file_type||wt.type||"file",fileType:wt.fileType||wt.file_type||wt.type||"file",fileSize:wt.fileSize||wt.file_size})):void 0};return[...qt,Ca]})},Ee=rt=>{ie(st=>st.length===0||!st.find(Et=>Et.userId===rt.userId)?st:st.map(Et=>Et.userId===rt.userId?{...Et,status:"online"}:Et))},Ke=rt=>{rt.userId!==N&&ie(st=>st.length===0||!st.find(Et=>Et.userId===rt.userId)?st:st.map(Et=>Et.userId===rt.userId?{...Et,status:"offline"}:Et))},Me=rt=>{ie(st=>st.length===0?st:st.map(qt=>{const Et=qt.userId||"";if(Et===N)return{...qt,status:"online"};const fa=rt.userIds.includes(Et);return{...qt,status:fa?"online":"offline"}}))},Je=()=>{ie(rt=>rt.map(gt=>gt.userId===N?{...gt,status:"online"}:gt)),r||Vl(ee,q,N),Z.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))},Be=rt=>{console.error("[WorkNoteChat] ❌ Socket error:",rt)},tt=rt=>{console.warn("[WorkNoteChat] ⚠️ Socket disconnected:",rt),ie(st=>st.map(gt=>gt.userId===N?gt:{...gt,status:"offline"}))},js=rt=>{rt.includes("presence")||rt.includes("worknote")||rt.includes("request")};ee.on("connect",Je),ee.on("disconnect",tt),ee.on("error",Be),ee.on("worknote:new",Fe),ee.on("presence:join",Ee),ee.on("presence:leave",Ke),ee.on("presence:online",Me),ee.onAny(js),ce.current=ee,ee.connected&&Z.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",Je),ee.off("disconnect",tt),ee.off("error",Be),ee.off("worknote:new",Fe),ee.off("presence:join",Ee),ee.off("presence:leave",Ke),ee.off("presence:online",Me),ee.offAny(js),r||Tx(ee,q),ce.current=null};window.__wn_cleanup=Kt}catch{}})(),()=>{var we;try{(we=window.__wn_cleanup)==null||we.call(window)}catch{}}},[p,N,r]);const J=async()=>{if(g.trim()||D.length>0){const q=qs(g),we=q.map(Ee=>{const Ke=G.find(Me=>Me.name.toLowerCase().includes(Ee.toLowerCase()));return Ke==null?void 0:Ke.userId}).filter(Boolean),ee=D.map(Ee=>({name:Ee.name,url:URL.createObjectURL(Ee),type:Ee.type.split("/")[1]||"file"})),Fe={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,D)}catch{}else try{await zx(p,{message:g,mentions:we},D);const Ee=await Mr(p),Ke=Array.isArray(Ee)?Ee.map(Me=>{const Je=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:Je===N,attachments:Array.isArray(Me.attachments)?Me.attachments.map(Be=>({attachmentId:Be.attachmentId||Be.attachment_id,name:Be.fileName||Be.file_name||Be.name,fileName:Be.fileName||Be.file_name||Be.name,url:Be.storageUrl||Be.storage_url||Be.url||"#",type:Be.fileType||Be.file_type||Be.type||"file",fileType:Be.fileType||Be.file_type||Be.type||"file",fileSize:Be.fileSize||Be.file_size})):void 0}}):[];T(Ke)}catch{T(Ee=>[...Ee,Fe])}y(""),S([])}};h.useEffect(()=>{if(s&&Array.isArray(s))try{const we=s.filter(ee=>(ee.type||"").toLowerCase()!=="sla_warning").map(ee=>{var Ee;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 Ke=ee.userName||ee.user_name||((Ee=ee.user)==null?void 0:Ee.name)||"User",Me=ee.userRole||ee.user_role,Je=ve(Me),Be=ee.userId||ee.user_id;return{id:ee.noteId||ee.note_id||ee.id||String(Math.random()),user:{name:Ke,avatar:Ke.split(" ").map(tt=>tt[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Je},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(tt=>({attachmentId:tt.attachmentId||tt.attachment_id,name:tt.fileName||tt.file_name||tt.name,fileName:tt.fileName||tt.file_name||tt.name,url:tt.storageUrl||tt.storage_url||tt.url||"#",type:tt.fileType||tt.file_type||tt.type||"file",fileType:tt.fileType||tt.file_type||tt.type||"file",fileSize:tt.fileSize||tt.file_size})):void 0,isCurrentUser:Be===N}}}).sort((ee,Fe)=>new Date(ee.timestamp).getTime()-new Date(Fe.timestamp).getTime());T(we)}catch(q){console.error("[WorkNoteChat] Error mapping messages:",q)}else(async()=>{try{const q=await Mr(p),we=Array.isArray(q)?q.map(ee=>{const Fe=ee.userName||ee.user_name||"User",Ee=ee.userRole||ee.user_role,Ke=ve(Ee),Me=ee.userId||ee.user_id;return{id:ee.noteId||ee.note_id||ee.id||String(Math.random()),user:{name:Fe,avatar:Fe.split(" ").map(Je=>Je[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ke},content:ee.message||"",timestamp:ee.createdAt||ee.created_at||new Date().toISOString(),attachments:Array.isArray(ee.attachments)?ee.attachments.map(Je=>({attachmentId:Je.attachmentId||Je.attachment_id,name:Je.fileName||Je.file_name||Je.name,fileName:Je.fileName||Je.file_name||Je.name,url:Je.storageUrl||Je.storage_url||Je.url||"#",type:Je.fileType||Je.file_type||Je.type||"file",fileType:Je.fileType||Je.file_type||Je.type||"file",fileSize:Je.fileSize||Je.file_size})):void 0,isCurrentUser:Me===N}}):[];T(we)}catch(q){console.error("[WorkNoteChat] Error loading work notes:",q)}})()},[s,p,G]);const Oe=q=>{const we=I.maxFileSizeMB*1024*1024;if(q.size>we)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${I.maxFileSizeMB}MB. Current size: ${(q.size/(1024*1024)).toFixed(2)}MB`};const ee=q.name.toLowerCase(),Fe=ee.substring(ee.lastIndexOf(".")+1);return I.allowedFileTypes.includes(Fe)?{valid:!0}:{valid:!1,reason:`File type "${Fe}" is not allowed. Allowed types: ${I.allowedFileTypes.join(", ")}`}},xt=q=>{if(!q.target.files||q.target.files.length===0)return;const we=Array.from(q.target.files),ee=[],Fe=[];we.forEach(Ee=>{const Ke=Oe(Ee);Ke.valid?Fe.push(Ee):ee.push({fileName:Ee.name,reason:Ke.reason||"Unknown validation error"})}),ee.length>0&&X({open:!0,errors:ee}),Fe.length>0&&(S(Ee=>[...Ee,...Fe]),Fe.length<we.length?Q.warning(`${Fe.length} of ${we.length} file(s) were added. ${ee.length} file(s) were rejected.`):Q.success(`${Fe.length} file(s) added successfully`)),q.target&&(q.target.value="")},je=q=>{S(we=>we.filter((ee,Fe)=>Fe!==q)),W.current&&(W.current.value="")},$e=q=>{y(we=>we+q),A(!1)},yt=()=>{var q;(q=W.current)==null||q.click()},kt=async q=>{var we,ee;try{await Wx(p,q);const Fe=await ws(p),Ee=Array.isArray(Fe==null?void 0:Fe.participants)?Fe.participants:[];if(Ee.length){const Ke=Ee.map(Me=>{const Je=Me.participantType||Me.participant_type||"participant",Be=Me.userId||Me.user_id||"",tt=Me.userName||Me.user_name||Me.userEmail||Me.user_email||"User",js=Me.userEmail||Me.user_email||"",Kt=tt.split(" ").map(rt=>rt[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:tt,avatar:Kt,role:Le(Je),status:"offline",email:js,lastSeen:void 0,permissions:["read"],userId:Be}});ie(Ke),ce.current&&ce.current.connected&&ce.current.emit("request:online-users",{requestId:p})}M(!1),_({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),U(!0)}catch(Fe){throw console.error("Failed to add spectator:",Fe),_({success:!1,title:"Failed to Add Spectator",message:((ee=(we=Fe==null?void 0:Fe.response)==null?void 0:we.data)==null?void 0:ee.error)||"Failed to add spectator. Please try again."}),U(!0),Fe}},lt=async(q,we,ee)=>{var Fe,Ee;if(c)await c(q,we,ee),C(!1);else try{await Hx(p,q,we,ee);const Ke=await ws(p),Me=Array.isArray(Ke==null?void 0:Ke.participants)?Ke.participants:[];if(Me.length){const Je=Me.map(Be=>{const tt=Be.participantType||Be.participant_type||"participant",js=Be.userId||Be.user_id||"",Kt=Be.userName||Be.user_name||Be.userEmail||Be.user_email||"User",rt=Be.userEmail||Be.user_email||"",st=Kt.split(" ").map(gt=>gt[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:Kt,avatar:st,role:Le(tt),status:"offline",email:rt,lastSeen:void 0,permissions:["read"],userId:js}});ie(Je),ce.current&&ce.current.connected&&ce.current.emit("request:online-users",{requestId:p})}C(!1),_({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${ee} with ${we}h TAT`}),U(!0)}catch(Ke){throw console.error("Failed to add approver:",Ke),_({success:!1,title:"Failed to Add Approver",message:((Ee=(Fe=Ke==null?void 0:Ke.response)==null?void 0:Fe.data)==null?void 0:Ee.error)||"Failed to add approver. Please try again."}),U(!0),Ke}},Fs=["😊","😂","🤣","😁","😃","😄","😅","😆","😉","😌","😍","🥰","😘","😗","😙","😚","🙂","🤗","🤩","🤔","🤨","😐","😑","😶","🙄","😏","😒","🙃","😬","🤐","😴","😪","😵","🤯","🤪","😜","😝","😛","🤤","😋","😎","🤓","🧐","😕","😟","🙁","☹️","😮","😯","😲","😳","🥺","😦","😧","😨","😰","😥","😢","😭","😱","😖","😣","😞","😓","😩","😫","🥱","😤","😡","😠","🤬","😈","👿","💀","☠️","💩","🤡","👹","👺","👻","👋","🤚","🖐️","✋","🖖","👌","🤌","🤏","✌️","🤞","🤟","🤘","🤙","👈","👉","👆","🖕","👇","☝️","👍","👎","✊","👊","🤛","🤜","👏","🙌","👐","🤲","🤝","🙏","💪","🦾","🦿","🦵","🦶","👂","🦻","👃","🧠","❤️","🧡","💛","💚","💙","💜","🖤","🤍","🤎","💔","❣️","💕","💞","💓","💗","💖","💘","💝","💟","❤️🔥","💼","📊","📈","📉","💻","⌨️","🖥️","🖨️","🖱️","💾","💿","📱","☎️","📞","📟","📠","📧","✉️","📨","📩","📮","📪","📫","📬","📭","📄","📃","📑","📝","✏️","✒️","🖊️","🖋️","📏","📐","📌","📍","🗂️","📁","📂","✅","✔️","☑️","🎯","🎖️","🏆","🥇","🥈","🥉","⭐","🌟","✨","💫","🔥","💥","⚡","💯","🎉","🎊","🎈","⚠️","🚫","❌","⛔","🚷","🚯","🚱","🚳","🔞","📵","❗","❓","❕","❔","‼️","⁉️","💢","💬","💭","🗯️","⏰","⏱️","⏲️","⏳","⌛","📅","📆","🗓️","📇","🕐","🕑","🕒","🕓","🕔","🕕","🕖","🕗","🕘","🕙","🕚","🚀","🎯","🎲","🎰","🧩","🔍","🔎","🔑","🗝️","🔒","🔓","🔐","🔏","🔔","🔕","📣","📢","💡","🔦","🏮","➕","➖","✖️","➗","♾️","‼️","⁉️","❓","❔","❕","🔄","🔃","🔂","▶️","⏸️","⏯️","⏹️","⏺️","⏭️","⏮️","⏩","⏪","⏫","⏬","◀️","🔼","🔽","➡️","⬅️","⬆️","⬇️","↗️","↘️","↙️","↖️","↕️","↔️","↪️","↩️","⤴️"],qs=q=>{const we=/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,ee=[];let Fe;for(;(Fe=we.exec(q))!==null;)if(Fe[1]){const Ee=Fe.index+Fe[0].length,Ke=q.slice(Ee),Me=q[Ee];(Ke.startsWith("@")||!Me||/\s|[.,!?;:]|@/.test(Me))&&ee.push(Fe[1].trim())}return ee},wa=q=>{q.key==="Enter"&&!q.shiftKey&&(q.preventDefault(),J())},Qa=(q,we)=>{T(ee=>ee.map(Fe=>{if(Fe.id===q){const Ee=Fe.reactions||[],Ke=Ee.find(Me=>Me.emoji===we);if(Ke)if(Ke.users.includes("You")){if(Ke.users=Ke.users.filter(Me=>Me!=="You"),Ke.users.length===0)return{...Fe,reactions:Ee.filter(Me=>Me.emoji!==we)}}else Ke.users.push("You");else Ee.push({emoji:we,users:["You"]});return{...Fe,reactions:Ee}}return Fe}))};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:Y.title}),e.jsx(ne,{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:[me.slice(0,3).map((q,we)=>e.jsx(rs,{className:"h-8 w-8 ring-2 ring-white shadow-sm",children:e.jsx(ns,{className:"bg-blue-500 text-white text-xs font-semibold",children:q.avatar})},we)),me.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:["+",me.length-3]})]})}),e.jsx(F,{variant:"outline",size:"sm",onClick:()=>L(!k),className:"lg:hidden",children:e.jsx($t,{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(As,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(_e,{placeholder:"Search messages...",value:f,onChange:q=>b(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:[Te.map(q=>{const we=q.isCurrentUser||!1;return e.jsxs("div",{className:`flex gap-2 sm:gap-3 lg:gap-4 ${q.isSystem?"justify-center":we?"justify-end":""}`,children:[!q.isSystem&&!we&&e.jsx(rs,{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(ns,{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:`${we?"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(Dt,{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:is(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 ${we?"justify-end":""}`,children:[e.jsxs("span",{className:"font-semibold text-gray-900 text-sm sm:text-base truncate",children:[q.user.name," ",we&&e.jsx("span",{className:"text-xs text-gray-500 font-normal",children:"(you)"})]}),e.jsx(ne,{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(Xe,{className:"w-3 h-3"}),is(q.timestamp)]}),q.isHighPriority&&e.jsxs(ne,{variant:"destructive",className:"text-xs flex-shrink-0",children:[e.jsx(l0,{className:"w-3 h-3 mr-1"}),"Priority"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 sm:p-4 shadow-sm ${we?"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:QA(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,Fe)=>{const Ee=ee.fileSize||ee.file_size,Ke=ee.fileName||ee.file_name||ee.name,Me=ee.fileType||ee.file_type||ee.type||"",Je=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(Au,{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:Ke}),Ee&&e.jsx("p",{className:"text-xs text-gray-500",children:JA(Ee)})]}),Je&&(()=>{const Be=(Me||"").toLowerCase();return Be.includes("image")||Be.includes("pdf")||Be.includes("jpg")||Be.includes("jpeg")||Be.includes("png")||Be.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:Be=>{Be.preventDefault(),Be.stopPropagation();const tt=eN(Je);O({fileName:Ke,fileType:Me,fileUrl:tt,fileSize:Ee,attachmentId:Je})},title:"Preview file",children:e.jsx(ht,{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 Be=>{if(Be.preventDefault(),Be.stopPropagation(),!Je){Q.error("Cannot download: Attachment ID missing");return}try{await am(Je)}catch{Q.error("Failed to download file")}},title:"Download file",children:e.jsx(Nt,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]},Fe)})})}),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,Fe)=>e.jsxs("button",{onClick:()=>Qa(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})]},Fe)),e.jsx(F,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-7 sm:w-7 p-0 flex-shrink-0",onClick:()=>A(!v),children:e.jsx(vs,{className:"w-2 h-2 sm:w-3 sm:h-3"})})]})]})]})}),!q.isSystem&&we&&e.jsx(rs,{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(ns,{className:"bg-blue-500 text-white font-semibold text-xs sm:text-sm",children:q.user.avatar})})]},q.id)}),e.jsx("div",{ref:se})]})}),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:W,onChange:xt,className:"hidden",multiple:!0,accept:I.allowedFileTypes.map(q=>`.${q}`).join(",")}),D.length>0&&e.jsx("div",{className:"mb-3 space-y-2 max-h-32 overflow-y-auto pr-2",children:D.map((q,we)=>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(Au,{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:()=>je(we),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"})})]},we))}),e.jsxs("div",{className:"relative mb-2",children:[(()=>{const q=g.lastIndexOf("@"),we=q>=0;if(!we)return null;const ee=g.slice(q+1),Fe=ee.trim(),Ee=ee.endsWith(" "),Ke=Fe.length>0,Me=Fe.includes(" ")&&!Ee,Je=Ee&&Ke;if(!(we&&ee.length<=20&&!Me&&!Je))return null;const tt=Fe.toLowerCase(),js=G.filter(Kt=>Kt.userId===N?!1:tt?Kt.name.toLowerCase().includes(tt):!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:js.length>0?js.map((Kt,rt)=>e.jsxs("button",{type:"button",onClick:st=>{st.preventDefault(),st.stopPropagation();const gt=g.lastIndexOf("@"),qt=g.slice(0,gt);y(qt+"@"+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(rs,{className:"h-10 w-10",children:e.jsx(ns,{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})]})]},rt)):e.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:tt?`No participants found matching "${tt}"`:"No other participants available"})})]})})(),e.jsx(Es,{placeholder:"Type your message... Use @username to mention someone",value:g,onChange:q=>y(q.target.value),onKeyPress:wa,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:()=>A(!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:Fs.map((q,we)=>e.jsx("button",{onClick:()=>$e(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},we))})]})]}),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:yt,title:"Attach file",children:e.jsx(Ni,{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:()=>A(!v),title:"Add emoji",children:e.jsx(o0,{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:()=>y(q=>q+"@"),title:"Mention someone",children:e.jsx(ki,{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:J,disabled:!g.trim()&&D.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(rx,{className:"h-4 w-4 sm:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Send"})]})]})]})]})})]}),k&&e.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 z-40 lg:hidden",onClick:()=>L(!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
|
||
${k?"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:()=>L(!1),className:"lg:hidden h-8 w-8 p-0",children:e.jsx(ft,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-3 sm:space-y-4 overflow-y-auto flex-1 pr-2",children:G.map((q,we)=>{const ee=q.userId===N;return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(rs,{className:"h-9 w-9 sm:h-10 sm:w-10",children:e.jsx(ns,{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 ${ZA(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:XA(q.status)})]}),q.lastSeen&&q.status==="offline"&&e.jsx("p",{className:"text-xs text-gray-400",children:q.lastSeen})]})]},we)})})]}),!Se&&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:()=>C(!0),children:[e.jsx(Ti,{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:()=>M(!0),children:[e.jsx(ht,{className:"h-4 w-4"}),"Add Spectator"]})]})]})]})]}),R&&e.jsx(Xr,{fileName:R.fileName,fileType:R.fileType,fileUrl:R.fileUrl,fileSize:R.fileSize,attachmentId:R.attachmentId,onDownload:am,open:!!R,onClose:()=>O(null)}),!Se&&e.jsx(Bp,{open:E,onClose:()=>M(!1),onConfirm:kt,requestIdDisplay:p,requestTitle:Y.title,existingParticipants:pe}),!Se&&l&&e.jsx(Vp,{open:B,onClose:()=>C(!1),onConfirm:lt,requestIdDisplay:p,requestTitle:Y.title,existingParticipants:pe,currentLevels:d,maxApprovalLevels:m,onPolicyViolation:u}),e.jsx(mt,{open:z.open,onOpenChange:q=>X(we=>({...we,open:q})),children:e.jsxs(ot,{className:"sm:max-w-lg",children:[e.jsxs(ut,{children:[e.jsxs(ct,{className:"flex items-center gap-2",children:[e.jsx(Ge,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(It,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-gray-700",children:"The following file(s) could not be uploaded due to policy violations:"}),e.jsx("div",{className:"space-y-2 max-h-60 overflow-y-auto",children:z.errors.map((q,we)=>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})]},we))}),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: ",I.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",I.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(Tt,{children:e.jsx(F,{onClick:()=>X({open:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(Up,{open:j,onClose:()=>U(!1),success:$.success,title:$.title,message:$.message})]})}function qA({requestId:t,requestTitle:s,mergedMessages:a,setWorkNoteAttachments:r,isInitiator:n,isSpectator:i,currentLevels:l,onAddApprover:o,maxApprovalLevels:d,onPolicyViolation:c}){return e.jsx("div",{className:"h-[calc(100vh-300px)] min-h-[600px]",children:e.jsx(zp,{requestId:t,requestTitle:s,skipSocketJoin:!0,messages:a,onAttachmentsExtracted:r,isInitiator:n,isSpectator:i,currentLevels:l,onAddApprover:o,maxApprovalLevels:d,onPolicyViolation:c})})}function eS({summary:t,loading:s,onShare:a,isInitiator:r}){const n=o=>{const d=o.toLowerCase();return d==="approved"?e.jsx(De,{className:"h-4 w-4 text-green-600"}):d==="rejected"?e.jsx(jt,{className:"h-4 w-4 text-red-600"}):d==="pending"||d==="in progress"?e.jsx(Xe,{className:"h-4 w-4 text-orange-600"}):e.jsx(Pe,{className:"h-4 w-4 text-gray-600"})},i=o=>{const d=o.toLowerCase();return d==="approved"?"bg-green-100 text-green-700 border-green-300":d==="rejected"?"bg-red-100 text-red-700 border-red-300":d==="pending"||d==="in progress"?"bg-orange-100 text-orange-700 border-orange-300":"bg-gray-100 text-gray-700 border-gray-300"},l=(o,d)=>o&&o.trim()&&o.trim().toUpperCase()!=="N/A"?o:d&&d.trim()&&d.trim().toUpperCase()!=="N/A"?d:"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(Ze,{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(Br,{className:"w-4 h-4"}),e.jsx("span",{children:"Share"})]}):e.jsxs(ne,{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(ra,{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:Ye(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,d)=>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:Ye(new Date(o.timestamp),"MMM dd, yy, HH:mm")})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Remarks"}),e.jsx("p",{className:"text-sm text-gray-700",children:o.remarks||"—"})]})]},d))]}),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(ne,{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(ra,{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(Pe,{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 tS({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(yn,{className:"h-4 w-4 text-gray-600"}):s==="approved"?e.jsx(De,{className:"h-4 w-4 text-green-600"}):s==="rejected"?e.jsx(jt,{className:"h-4 w-4 text-red-600"}):e.jsx(Xe,{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",d=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"},c=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(yn,{className:`h-4 w-4 ${d.icon}`}):e.jsx(Xe,{className:`h-4 w-4 ${d.icon}`}),e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:a?"SLA Progress (Paused)":"SLA Progress"})]}),e.jsxs(ne,{className:`text-xs ${d.badge}`,"data-testid":`${r}-badge`,children:[i,"% elapsed ",a&&"(frozen)"]})]}),e.jsx(la,{value:i,className:"h-3 mb-2",indicatorClassName:d.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:[Lt(t.elapsedHours||0)," elapsed"]}),e.jsxs("span",{className:`font-semibold ${c==="breached"||c==="critical"?d.text:"text-gray-700"}`,"data-testid":`${r}-remaining`,children:[Lt(t.remainingHours||0)," remaining"]})]}),t.deadline&&e.jsxs("p",{className:"text-xs text-gray-500","data-testid":`${r}-deadline`,children:["Due: ",ha(t.deadline,!0)," • ",i,"% elapsed"]}),c==="critical"&&e.jsxs("p",{className:"text-xs text-orange-600 font-semibold mt-1 flex items-center gap-1.5","data-testid":`${r}-warning-critical`,children:[e.jsx(os,{className:"h-3.5 w-3.5"}),"Approaching Deadline"]}),c==="breached"&&e.jsxs("p",{className:"text-xs text-red-600 font-semibold mt-1 flex items-center gap-1.5","data-testid":`${r}-warning-breached`,children:[e.jsx(oi,{className:"h-3.5 w-3.5"}),"URGENT - Deadline Passed"]})]})}function sS({request:t,refreshing:s,onBack:a,onRefresh:r,onShareSummary:n,isInitiator:i,slaData:l,isPaused:o=!1}){var m;const d=WA((t==null?void 0:t.priority)||"standard"),c=GA((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(Js,{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(Pe,{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(ne,{className:`${d.color} rounded-full px-2 sm:px-3 text-xs capitalize shrink-0`,variant:"outline","data-testid":"priority-badge",children:d.label}),e.jsx(ne,{className:`${c.color} rounded-full px-2 sm:px-3 text-xs capitalize shrink-0`,variant:"outline","data-testid":"status-badge",children:c.label}),(()=>{const u=(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)||"",p=(x==null?void 0:x.toUpperCase())||"",g=u==="CLAIM_MANAGEMENT"||u==="DEALER_CLAIM"||x==="claim-management"||p==="DEALER CLAIM"||p==="DEALER_CLAIM";let y="Non-Templatized",f="bg-purple-100 !text-purple-600 border-purple-200";return g?(y="Dealer Claim",f="bg-blue-100 !text-blue-700 border-blue-200"):p==="TEMPLATE"&&(y="Template"),e.jsx(ne,{className:`${f} rounded-full px-2 sm:px-3 text-xs shrink-0`,variant:"outline","data-testid":"template-type-badge",children:y})})()]})]})]})]}),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(Br,{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(Bt,{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(tS,{sla:l,requestStatus:t.status,isPaused:o,testId:"request-sla"})})]})}async function bc(t){return(await Ne.get(`/summaries/${t}`)).data.data}async function aS(t,s){return(await Ne.post(`/summaries/${t}/share`,{userIds:s})).data.data}async function rS(t={}){var n,i;const{page:s=1,limit:a=20}=t,r=await Ne.get("/summaries/shared",{params:{page:s,limit:a}});return{data:((n=r.data.data)==null?void 0:n.data)||r.data.data||[],pagination:((i=r.data.data)==null?void 0:i.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Hp(t){await Ne.patch(`/summaries/shared/${t}/view`)}async function Wp(t){var s;try{return(await Ne.get(`/summaries/request/${t}`)).data.data}catch(a){return((s=a==null?void 0:a.response)==null?void 0:s.status)===404,null}}async function nS(t){return(await Ne.get(`/summaries/${t}/recipients`)).data.data||[]}function iS({activityInfo:t,className:s,createdAt:a,updatedAt:r}){if(!t)return console.warn("[ActivityInformationCard] activityInfo is missing"),e.jsx(te,{className:s,children:e.jsx(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 Ye(new Date(l),"MMM d, yyyy")}catch{return l}};return e.jsxs(te,{className:s,children:[e.jsx(ue,{children:e.jsxs(xe,{className:"flex items-center gap-2 text-base",children:[e.jsx(it,{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(jo,{className:"w-4 h-4 text-gray-400"}),t.location]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Requested Date"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:i(t.requestedDate)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Estimated Budget"}),e.jsxs("p",{className:"text-sm text-gray-900 font-medium mt-1 flex items-center gap-2",children:[e.jsx(Pa,{className:"w-4 h-4 text-green-600"}),t.estimatedBudget?n(t.estimatedBudget):"TBD"]})]}),t.closedExpenses!==void 0&&t.closedExpenses!==null&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Closed Expenses"}),e.jsxs("p",{className:"text-sm text-gray-900 font-medium mt-1 flex items-center gap-2",children:[e.jsx(ls,{className:"w-4 h-4 text-blue-600"}),n(t.closedExpenses)]})]}),t.period&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Period"}),e.jsxs("p",{className:"text-sm text-gray-900 font-medium mt-1",children:[i(t.period.startDate)," - ",i(t.period.endDate)]})]})]}),t.closedExpensesBreakdown&&t.closedExpensesBreakdown.length>0&&e.jsxs("div",{className:"pt-4 border-t",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide mb-3 block",children:"Closed Expenses Breakdown"}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3 space-y-2",children:[t.closedExpensesBreakdown.map((l,o)=>e.jsxs("div",{className:"flex justify-between items-center text-sm",children:[e.jsx("span",{className:"text-gray-700",children:l.description}),e.jsx("span",{className:"font-medium text-gray-900",children:n(l.amount)})]},o)),e.jsxs("div",{className:"pt-2 border-t border-blue-300 flex justify-between items-center",children:[e.jsx("span",{className:"font-semibold text-gray-900",children:"Total"}),e.jsx("span",{className:"font-bold text-blue-600",children:n(t.closedExpensesBreakdown.reduce((l,o)=>l+o.amount,0))})]})]})]}),t.description&&e.jsxs("div",{className:"pt-4 border-t",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Description"}),e.jsx("div",{className:"mt-2 bg-gray-50 p-3 rounded-lg border border-gray-200",children:e.jsx(ra,{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:is(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:is(r)})]})]})]})]})}function lS({dealerInfo:t,className:s}){return t?!t.dealerCode&&!t.dealerName?(console.warn("[DealerInformationCard] Dealer info missing essential fields:",t),e.jsx(te,{className:s,children:e.jsx(ae,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Dealer information incomplete"})})})):e.jsxs(te,{className:s,children:[e.jsx(ue,{children:e.jsxs(xe,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ri,{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(Ci,{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(jo,{className:"w-4 h-4 text-gray-400 mt-0.5"}),e.jsx("span",{children:t.address})]})]})]})]})]}):(console.warn("[DealerInformationCard] dealerInfo is missing"),e.jsx(te,{className:s,children:e.jsx(ae,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Dealer information not available"})})}))}function oS({ioDetails:t,dmsDetails:s,claimAmount:a,estimatedBudgetBreakdown:r,closedExpensesBreakdown:n,visibility:i,onEditClaimAmount:l,className:o}){const d=x=>x==null||Number.isNaN(x)?"₹0.00":`₹${x.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,c=x=>{if(!x)return"";try{return Ye(new Date(x),"MMM d, yyyy, h:mm a")}catch{return x||""}},m=x=>!x||x.length===0?0:x.reduce((p,g)=>p+(g.amount??0),0);return i.showIODetails&&t||i.showDMSDetails&&s||i.showClaimAmount&&a&&a.amount!==void 0&&a.amount!==null||r&&r.length>0||n&&n.length>0?e.jsxs(te,{className:`bg-gradient-to-br from-blue-50 to-purple-50 border-2 border-blue-200 ${o}`,children:[e.jsxs(ue,{children:[e.jsxs(xe,{className:"text-base flex items-center gap-2",children:[e.jsx(Dt,{className:"w-4 h-4 text-blue-600"}),"Process Details"]}),e.jsx(ke,{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(ls,{className:"w-4 h-4 text-blue-600"}),e.jsx(le,{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:d(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:d(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:d(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:c(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(Dt,{className:"w-4 h-4 text-purple-600"}),e.jsx(le,{className:"text-xs font-semibold text-purple-900 uppercase tracking-wide",children:"DMS Number"})]}),e.jsx("p",{className:"font-bold text-gray-900 mb-2",children:s.dmsNumber}),s.remarks&&e.jsxs("div",{className:"pt-2 border-t border-purple-100",children:[e.jsx("p",{className:"text-xs text-gray-600 mb-1",children:"Remarks:"}),e.jsx("p",{className:"text-xs text-gray-900",children:s.remarks})]}),e.jsxs("div",{className:"pt-2 border-t border-purple-100 mt-2",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:["By ",s.createdByName]}),e.jsx("p",{className:"text-xs text-gray-500",children:c(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(le,{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(ci,{className:"w-3 h-3 mr-1 text-green-700"}),"Edit"]})]}),e.jsx("p",{className:"text-2xl font-bold text-green-700",children:d(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:c(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(ls,{className:"w-4 h-4 text-amber-600"}),e.jsx(le,{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,p)=>e.jsxs("div",{className:"flex justify-between items-center text-xs",children:[e.jsx("span",{className:"text-gray-700",children:x.description}),e.jsx("span",{className:"font-medium text-gray-900",children:d(x.amount)})]},p)),e.jsxs("div",{className:"pt-2 border-t border-amber-200 flex justify-between items-center",children:[e.jsx("span",{className:"font-semibold text-gray-900 text-xs",children:"Total"}),e.jsx("span",{className:"font-bold text-amber-700",children:d(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(ls,{className:"w-4 h-4 text-indigo-600"}),e.jsx(le,{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,p)=>e.jsxs("div",{className:"flex justify-between items-center text-xs",children:[e.jsx("span",{className:"text-gray-700",children:x.description}),e.jsx("span",{className:"font-medium text-gray-900",children:d(x.amount)})]},p)),e.jsxs("div",{className:"pt-2 border-t border-indigo-200 flex justify-between items-center",children:[e.jsx("span",{className:"font-semibold text-gray-900 text-xs",children:"Total"}),e.jsx("span",{className:"font-bold text-indigo-700",children:d(m(n))})]})]})]})]})]}):null}function cS({proposalDetails:t,className:s}){const r=t.estimatedBudgetTotal!==void 0&&t.estimatedBudgetTotal!==null?t.estimatedBudgetTotal:t.costBreakup&&t.costBreakup.length>0?t.costBreakup.reduce((d,c)=>{const m=c.amount||0;return d+(Number.isNaN(m)?0:m)},0):0,n=o=>o==null||Number.isNaN(o)?"₹0.00":`₹${o.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,i=o=>{if(!o)return"";try{return Ye(new Date(o),"MMM d, yyyy, h:mm a")}catch{return o||""}},l=o=>{if(!o)return"-";try{return Ye(new Date(o),"MMM d, yyyy")}catch{return o||"-"}};return e.jsxs(te,{className:s,children:[e.jsxs(ue,{children:[e.jsxs(xe,{className:"flex items-center gap-2 text-base",children:[e.jsx(ls,{className:"w-5 h-5 text-green-600"}),"Proposal Details"]}),t.submittedOn&&e.jsxs(ke,{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:"Amount"})]})}),e.jsxs("tbody",{className:"divide-y divide-gray-200",children:[(t.costBreakup||[]).map((o,d)=>e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 text-sm text-gray-900",children:o.description}),e.jsx("td",{className:"px-4 py-3 text-sm text-gray-900 text-right font-medium",children:n(o.amount)})]},d)),e.jsxs("tr",{className:"bg-green-50 font-semibold",children:[e.jsx("td",{className:"px-4 py-3 text-sm text-gray-900",children:"Estimated Budget (Total)"}),e.jsx("td",{className:"px-4 py-3 text-sm text-green-700 text-right",children:n(r)})]})]})]})})]}),e.jsxs("div",{className:"pt-2",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Timeline for Closure"}),e.jsx("div",{className:"mt-2 bg-blue-50 border border-blue-200 rounded-lg p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(it,{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 dS({initiatorInfo:t,className:s}){const a=r=>r.split(" ").map(n=>n[0]).join("").toUpperCase().slice(0,2);return e.jsxs(te,{className:s,children:[e.jsx(ue,{children:e.jsx(xe,{className:"text-base",children:"Request Initiator"})}),e.jsx(ae,{children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(rs,{className:"h-14 w-14 ring-2 ring-white shadow-md",children:e.jsx(ns,{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(Ci,{className:"w-4 h-4"}),e.jsx("span",{children:t.phone})]})]})]})]})})]})}function Wi(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 Gp(t,s){var a,r;try{if(!Wi(t))return null;const n=t.claimDetails||{},i=t.proposalDetails||{},l=t.completionDetails||{},o=t.internalOrder||t.internal_order||{},d=t.budgetTracking||t.budget_tracking||{},c=t.invoice||{},m=t.creditNote||t.credit_note||{},u=t.completionExpenses||t.completion_expenses||[],x=n.periodStartDate||n.period_start_date,p=n.periodEndDate||n.period_end_date,g=n.activityName||n.activity_name||"",y=n.activityType||n.activity_type||"",f=n.location||"",b=d.proposalEstimatedBudget||d.proposal_estimated_budget||d.initialEstimatedBudget||d.initial_estimated_budget||n.estimatedBudget||n.estimated_budget,v=(d==null?void 0:d.closedExpenses)||(d==null?void 0:d.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),A=v!=null?Number(v):void 0,w=Array.isArray(u)&&u.length>0?u.map(R=>({description:R.description||R.itemDescription||"",amount:Number(R.amount)||0})):(l==null?void 0:l.closedExpenses)||(l==null?void 0:l.closed_expenses)||(l==null?void 0:l.closedExpensesBreakdown)||[],T={activityName:g,activityType:y,requestedDate:n.activityDate||n.activity_date||t.createdAt,location:f,period:x&&p?{startDate:x,endDate:p}:void 0,estimatedBudget:b,closedExpenses:A,closedExpensesBreakdown:w,description:t.description||""},k={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)||""};(!k.dealerCode||!k.dealerName)&&console.warn("[claimDataMapper] Dealer information is missing from claimDetails:",{hasClaimDetails:!!n,dealerCode:k.dealerCode,dealerName:k.dealerName,rawClaimDetails:n,availableKeys:n?Object.keys(n):[]});const L=(i==null?void 0:i.expectedCompletionDate)||(i==null?void 0:i.expected_completion_date),D=i?{proposalDocumentUrl:i.proposalDocumentUrl||i.proposal_document_url,costBreakup:i.costBreakup||i.cost_breakup||[],totalEstimatedBudget:i.totalEstimatedBudget||i.total_estimated_budget||0,timelineMode:i.timelineMode||i.timeline_mode,expectedCompletionDate:L,expectedCompletionDays:i.expectedCompletionDays||i.expected_completion_days,timelineForClosure:L,dealerComments:i.dealerComments||i.dealer_comments,submittedOn:i.submittedAt||i.submitted_at||i.submittedOn}:void 0,S={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||""},N={eInvoiceNumber:c.invoiceNumber||c.invoice_number||n.eInvoiceNumber||n.e_invoice_number,eInvoiceDate:c.invoiceDate||c.invoice_date||n.eInvoiceDate||n.e_invoice_date,dmsNumber:c.dmsNumber||c.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},P={estimated:T.estimatedBudget||0,closed:T.closedExpenses||0};return{activityInfo:T,dealerInfo:k,proposalDetails:D,ioDetails:Object.keys(S).some(R=>S[R])?S:void 0,dmsDetails:Object.keys(N).some(R=>N[R])?N:void 0,claimAmount:P}}catch(n){return console.error("[claimDataMapper] Error mapping claim data:",n),null}}function Kp(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(c=>{var m;return(c.userId===s||((m=c.user)==null?void 0:m.userId)===s)&&(c.participantType==="DEALER"||c.type==="DEALER")}))return"DEALER";const l=t.approvalLevels||[];return l.find(c=>{var m;return c.levelNumber===3&&(c.approverId===s||((m=c.approver)==null?void 0:m.userId)===s)})?"DEPARTMENT_LEAD":l.find(c=>{var m;return(c.approverId===s||((m=c.approver)==null?void 0:m.userId)===s)&&c.status==="PENDING"})?"APPROVER":"SPECTATOR"}catch(n){return console.error("[claimDataMapper] Error determining user role:",n),"SPECTATOR"}}function Yp(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 mS({request:t,isInitiator:s,isSpectator:a,currentApprovalLevel:r,onAddApprover:n,onAddSpectator:i,onApprove:l,onReject:o,onPause:d,onResume:c,onRetrigger:m,summaryId:u,refreshTrigger:x,pausedByUserId:p,currentUserId:g,apiRequest:y,onEditClaimAmount:f}){var B,C,j,U,$;const{user:b}=Jt(),[v,A]=h.useState([]),[w,T]=h.useState(!1),[k,L]=h.useState(!1),D=(t==null?void 0:t.status)==="closed",S=((B=t==null?void 0:t.pauseInfo)==null?void 0:B.isPaused)||!1,N=p||((j=(C=t==null?void 0:t.pauseInfo)==null?void 0:C.pausedBy)==null?void 0:j.userId),P=g||(b==null?void 0:b.userId)||"",R=!S&&!D&&(r||s),O=S&&c&&(r||s),E=S&&s&&N&&N!==P&&m;h.useEffect(()=>{if(!S||!r||!(t!=null&&t.requestId)){L(!1);return}(async()=>{var se;try{const Z=(((se=(await Va.list({page:1,limit:50,unreadOnly:!0})).data)==null?void 0:se.notifications)||[]).some(I=>I.requestId===t.requestId&&I.notificationType==="pause_retrigger_request");L(Z)}catch(W){console.error("Failed to check retrigger notifications:",W),L(!1)}})()},[S,r,t==null?void 0:t.requestId,x]),h.useEffect(()=>{(async()=>{if(!D||!u||!s){A([]);return}try{T(!0);const se=await nS(u);A(se)}catch(se){console.error("Failed to fetch shared recipients:",se),A([])}finally{T(!1)}})()},[D,u,s,x]);const M=h.useMemo(()=>{if(!y||!Wi(y))return null;const _=Gp(y);if(!_)return null;const se=Kp(y,P),W=Yp(se);return{claimRequest:_,visibility:W}},[y,P]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[!a&&t.status!=="closed"&&e.jsxs(te,{"data-testid":"quick-actions-card",children:[e.jsx(ue,{className:"pb-2",children:e.jsx(xe,{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(Ti,{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(ht,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Add Spectator"]}),R&&d&&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:d,"data-testid":"pause-workflow-button",children:[e.jsx(Ha,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Pause Workflow"]}),O&&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:c,"data-testid":"resume-workflow-button",children:[e.jsx(li,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Resume Workflow"]}),E&&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(Ge,{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&&!S&&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(De,{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(jt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Reject Request"]})]}),S&&e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-3 text-center",children:N===P?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:[k&&e.jsx(Ge,{className:"w-3.5 h-3.5"}),k?"Initiator has requested you to resume":"You paused this workflow"]}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:k?"Please review and resume if appropriate":'Click "Resume Workflow" to continue'})]}):r&&N!==P&&k?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(Ge,{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&&N!==P?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&&N&&N!==P?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:E?'Click "Request Resume" to notify approver':"Resume request sent - Waiting for approver"})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-orange-800 font-medium",children:"Workflow is paused"}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:"Actions are disabled until resumed"})]})})]})]})]}),e.jsxs(te,{"data-testid":"spectators-card",children:[e.jsx(ue,{className:"pb-2",children:e.jsx(xe,{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((_,se)=>e.jsxs("div",{className:"flex items-center gap-3","data-testid":`spectator-${se}`,children:[e.jsx(rs,{className:"h-8 w-8",children:e.jsx(ns,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:_.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:_.name}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:_.role})]})]},se)):e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"No spectators added"})})})]}),D&&s&&e.jsxs(te,{"data-testid":"shared-recipients-card",children:[e.jsx(ue,{className:"pb-2",children:e.jsxs(xe,{className:"text-sm sm:text-base flex items-center gap-2",children:[e.jsx(Br,{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((_,se)=>{const W=(_.displayName||"NA").split(" ").map(ce=>ce[0]).join("").slice(0,2).toUpperCase();return e.jsxs("div",{className:"flex items-center gap-3","data-testid":`shared-recipient-${se}`,children:[e.jsx(rs,{className:"h-8 w-8",children:e.jsx(ns,{className:"bg-green-100 text-green-800 text-xs font-semibold",children:W})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:_.displayName}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:_.email}),_.isRead&&e.jsx("p",{className:"text-xs text-green-600 mt-0.5",children:"Viewed"})]})]},_.userId||se)}):e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Summary not shared yet"})})})]}),M&&e.jsx(oS,{ioDetails:M.claimRequest.ioDetails,dmsDetails:M.claimRequest.dmsDetails,claimAmount:{amount:M.claimRequest.claimAmount.closed||M.claimRequest.claimAmount.estimated||0},estimatedBudgetBreakdown:(U=M.claimRequest.proposalDetails)==null?void 0:U.costBreakup,closedExpensesBreakdown:($=M.claimRequest.activityInfo)==null?void 0:$.closedExpensesBreakdown,visibility:M.visibility,onEditClaimAmount:f})]})}function uS({open:t,onClose:s,onConfirm:a,defaultDescription:r="",title:n="Approve Request",requestIdDisplay:i,requestTitle:l}){const[o,d]=h.useState(r),[c,m]=h.useState(!1),u=(o==null?void 0:o.length)||0,x=h.useMemo(()=>o.slice(0,500),[o]),p=async()=>{try{m(!0),await a(x),s()}finally{m(!1)}};return e.jsx(mt,{open:t,onOpenChange:g=>!g&&s(),children:e.jsxs(ot,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(ut,{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(De,{className:"w-7 h-7 text-green-600"})}),e.jsxs("div",{children:[e.jsx(ct,{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(ne,{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(Es,{value:x,onChange:g=>d(g.target.value),rows:5,placeholder:"Enter your approval comments and any conditions or notes...",className:"border-gray-300"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsx("span",{children:"Comments are required and will be visible to all participants"}),e.jsxs("span",{children:[Math.min(u,500),"/500"]})]})]}),e.jsxs("div",{className:"mt-4 border rounded-lg p-3 bg-green-50 border-green-200 text-green-900 flex items-start gap-2",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx(De,{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(Tt,{className:"mt-4",children:[e.jsx(F,{variant:"outline",onClick:s,disabled:c,children:"Cancel"}),e.jsxs(F,{onClick:p,disabled:c,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(De,{className:"w-4 h-4 mr-2"}),c?"Approving...":"Approve Request"]})]})]})})}function xS({open:t,onClose:s,onConfirm:a,defaultDescription:r="",title:n="Reject Request",requestIdDisplay:i,requestTitle:l}){const[o,d]=h.useState(r),[c,m]=h.useState(!1),u=(o==null?void 0:o.length)||0,x=h.useMemo(()=>o.slice(0,500),[o]),p=async()=>{if(!x.trim()){alert("Comments & remarks are required");return}try{m(!0),await a(x),s()}finally{m(!1)}};return e.jsx(mt,{open:t,onOpenChange:g=>!g&&s(),children:e.jsxs(ot,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(ut,{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(jt,{className:"w-7 h-7 text-red-600"})}),e.jsxs("div",{children:[e.jsx(ct,{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(ne,{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(Es,{value:x,onChange:g=>d(g.target.value),rows:5,placeholder:"Enter detailed reasons for rejection and any suggestions for improvement...",className:"border-gray-300"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsx("span",{children:"Comments are required and will be visible to all participants"}),e.jsxs("span",{children:[Math.min(u,500),"/500"]})]})]}),e.jsxs("div",{className:"mt-4 border rounded-lg p-3 bg-red-50 border-red-200 text-red-900 flex items-start gap-2",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx(Ge,{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(Tt,{className:"mt-4",children:[e.jsx(F,{variant:"outline",onClick:s,disabled:c,children:"Cancel"}),e.jsxs(F,{variant:"destructive",onClick:p,disabled:c,children:[e.jsx(jt,{className:"w-4 h-4 mr-2"}),c?"Rejecting...":"Reject Request"]})]})]})})}function hS({open:t,onClose:s,onConfirm:a,approverName:r,levelNumber:n,requestIdDisplay:i,requestTitle:l}){const[o,d]=h.useState(""),[c,m]=h.useState(!1),u=async()=>{if(o.trim())try{m(!0),await a(o.trim()),d(""),s()}catch(p){console.error("Failed to skip approver:",p)}finally{m(!1)}},x=()=>{c||(d(""),s())};return e.jsx(mt,{open:t,onOpenChange:x,children:e.jsxs(ot,{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:c,children:[e.jsx(ft,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(ut,{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(Ge,{className:"w-5 h-5 text-orange-600"})}),e.jsx(ct,{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(Ge,{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(le,{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(le,{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(le,{htmlFor:"skip-reason",className:"text-sm font-semibold text-gray-700",children:"Reason for Skipping *"}),e.jsx(Es,{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:p=>d(p.target.value),className:"min-h-[100px] border-2 border-gray-300 focus:border-orange-500",disabled:c,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:c,children:"Cancel"}),e.jsxs(F,{type:"button",onClick:u,className:"flex-1 h-11 bg-orange-600 hover:bg-orange-700 text-white",disabled:c||!o.trim(),children:[e.jsx(Ge,{className:"w-4 h-4 mr-2"}),c?"Skipping...":"Skip Approver"]})]})]})})}function pS({showApproveModal:t,showRejectModal:s,showAddApproverModal:a,showAddSpectatorModal:r,showSkipApproverModal:n,showActionStatusModal:i,previewDocument:l,documentError:o,request:d,skipApproverData:c,actionStatus:m,existingParticipants:u,currentLevels:x,maxApprovalLevels:p,onPolicyViolation:g,setShowApproveModal:y,setShowRejectModal:f,setShowAddApproverModal:b,setShowAddSpectatorModal:v,setShowSkipApproverModal:A,setShowActionStatusModal:w,setPreviewDocument:T,setDocumentError:k,setSkipApproverData:L,setActionStatus:D,handleApproveConfirm:S,handleRejectConfirm:N,handleAddApprover:P,handleAddSpectator:R,handleSkipApprover:O,downloadDocument:E,documentPolicy:M}){return e.jsxs(e.Fragment,{children:[e.jsx(uS,{open:t,onClose:()=>y(!1),onConfirm:S,requestIdDisplay:d.id,requestTitle:d.title}),e.jsx(xS,{open:s,onClose:()=>f(!1),onConfirm:N,requestIdDisplay:d.id,requestTitle:d.title}),e.jsx(Vp,{open:a,onClose:()=>b(!1),onConfirm:P,requestIdDisplay:d.id,requestTitle:d.title,existingParticipants:u,currentLevels:x,maxApprovalLevels:p,onPolicyViolation:g}),e.jsx(Bp,{open:r,onClose:()=>v(!1),onConfirm:R,requestIdDisplay:d.id,requestTitle:d.title,existingParticipants:u}),e.jsx(hS,{open:n,onClose:()=>{A(!1),L(null)},onConfirm:O,approverName:c==null?void 0:c.approverName,levelNumber:c==null?void 0:c.levelNumber,requestIdDisplay:d.id,requestTitle:d.title}),l&&e.jsx(Xr,{fileName:l.fileName,fileType:l.fileType,fileUrl:Gr(l.documentId),fileSize:l.fileSize,attachmentId:l.documentId,onDownload:E,open:!!l,onClose:()=>T(null)}),m&&e.jsx(Up,{open:i,onClose:()=>{w(!1),D(null)},success:m.success,title:m.title,message:m.message}),e.jsx(mt,{open:o.show,onOpenChange:B=>k(C=>({...C,show:B})),children:e.jsxs(ot,{className:"sm:max-w-lg",children:[e.jsxs(ut,{children:[e.jsxs(ct,{className:"flex items-center gap-2",children:[e.jsx(Ge,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(It,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-gray-700",children:"The following file(s) could not be uploaded due to policy violations:"}),e.jsx("div",{className:"space-y-2 max-h-60 overflow-y-auto",children:o.errors.map((B,C)=>e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3",children:[e.jsx("p",{className:"font-medium text-red-900 text-sm",children:B.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:B.reason})]},C))}),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: ",M.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",M.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(Tt,{children:e.jsx(F,{onClick:()=>k({show:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const Zp={DocumentsTab:HA,ActivityTab:YA,WorkNotesTab:qA,SummaryTab:eS,RequestDetailHeader:sS,QuickActionsSidebar:mS,RequestDetailModals:pS};function vc({className:t,...s}){return e.jsx(bf,{"data-slot":"checkbox",className:Re("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(vf,{"data-slot":"checkbox-indicator",className:"flex items-center justify-center text-current transition-none",children:e.jsx(Vr,{className:"size-3.5"})})})}function Xp({isOpen:t,onClose:s,summaryId:a,requestTitle:r,onSuccess:n}){const[i,l]=h.useState(""),[o,d]=h.useState([]),[c,m]=h.useState(new Set),[u,x]=h.useState(!1),[p,g]=h.useState(!1);h.useEffect(()=>{if(!t){d([]);return}if(!i||!i.startsWith("@")||i.length<2){d([]),x(!1);return}const v=setTimeout(async()=>{var A;try{x(!0);const w=i.slice(1),T=await oa(w,10),k=((A=T==null?void 0:T.data)==null?void 0:A.data)||(T==null?void 0:T.data)||[];d(Array.isArray(k)?k:[])}catch(w){console.error("Failed to search users:",w),Q.error("Failed to search users")}finally{x(!1)}},300);return()=>clearTimeout(v)},[i,t]);const y=v=>{m(A=>{const w=new Set(A);return w.has(v)?w.delete(v):w.add(v),w})},f=async()=>{var v,A;if(c.size===0){Q.error("Please select at least one user to share with");return}try{g(!0),await aS(a,Array.from(c)),Q.success(`Summary shared with ${c.size} user(s)`),m(new Set),l(""),d([]),n==null||n(),s()}catch(w){console.error("Failed to share summary:",w),Q.error(((A=(v=w==null?void 0:w.response)==null?void 0:v.data)==null?void 0:A.message)||"Failed to share summary")}finally{g(!1)}},b=()=>{m(new Set),l(""),d([]),s()};return e.jsx(mt,{open:t,onOpenChange:b,children:e.jsxs(ot,{className:"sm:max-w-[500px]",children:[e.jsx(ut,{children:e.jsx(ct,{children:"Share Summary"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{children:[e.jsx(le,{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(le,{htmlFor:"user-search",className:"text-sm font-medium text-gray-700",children:"Search Users"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(As,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(_e,{id:"user-search",placeholder:"Type @ to search users...",value:i,onChange:v=>l(v.target.value),className:"pl-10"})]}),i&&!i.startsWith("@")&&e.jsx("p",{className:"text-xs text-gray-500 mt-1 ml-1",children:"Start with @ to search users (e.g., @john)"})]}),u&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Ze,{className:"h-5 w-5 animate-spin text-blue-600"})}),!u&&o.length>0&&e.jsx("div",{className:"border rounded-lg max-h-[300px] overflow-y-auto",children:o.map(v=>{const A=c.has(v.userId);return e.jsxs("div",{className:"flex items-center gap-3 p-3 hover:bg-gray-50 border-b last:border-b-0 cursor-pointer",onClick:()=>y(v.userId),children:[e.jsx("div",{onClick:w=>w.stopPropagation(),onMouseDown:w=>w.stopPropagation(),className:"flex items-center",children:e.jsx(vc,{checked:A,onCheckedChange:()=>y(v.userId)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_t,{className:"h-4 w-4 text-gray-400 flex-shrink-0"}),e.jsx("p",{className:"text-sm font-medium text-gray-900 truncate",children:v.displayName||v.email})]}),(v.designation||v.department)&&e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:v.designation||v.department}),e.jsx("p",{className:"text-xs text-gray-400 truncate",children:v.email})]})]},v.userId)})}),!u&&i&&i.startsWith("@")&&o.length===0&&e.jsx("div",{className:"text-center py-8 text-gray-500 text-sm",children:"No users found"}),!u&&i&&!i.startsWith("@")&&e.jsx("div",{className:"text-center py-8 text-gray-500 text-sm",children:"Start typing with @ to search users"}),c.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 (",c.size,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(c).map(v=>{const A=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:(A==null?void 0:A.displayName)||(A==null?void 0:A.email)||v}),e.jsx("button",{onClick:()=>y(v),className:"ml-1 hover:text-red-600",children:e.jsx(ft,{className:"h-3 w-3"})})]},v)})})]})]}),e.jsxs(Tt,{children:[e.jsx(F,{variant:"outline",onClick:b,disabled:p,children:"Cancel"}),e.jsx(F,{onClick:f,disabled:p||c.size===0,children:p?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):`Share with ${c.size} user(s)`})]})]})})}function Qp({isOpen:t,onClose:s,requestId:a,levelId:r,onSuccess:n}){const[i,l]=h.useState(""),[o,d]=h.useState(""),[c,m]=h.useState(!1),u=()=>Ht().add(1,"month").format("YYYY-MM-DD"),x=()=>Ht().add(1,"month").format("YYYY-MM-DD"),p=()=>Ht().add(1,"day").format("YYYY-MM-DD");h.useEffect(()=>{t&&!o&&d(u())},[t]);const g=async()=>{var A,w,T,k;if(!i.trim()){Q.error("Please provide a reason for pausing");return}if(!o){Q.error("Please select a resume date");return}const f=Ht(o),b=Ht().add(1,"month"),v=Ht().add(1,"day");if(f.isAfter(b)){Q.error("Resume date cannot be more than 1 month from now");return}if(f.isBefore(v,"day")){Q.error("Resume date must be at least 1 day from now");return}try{m(!0),await Qj(a,r,i.trim(),f.toDate()),Q.success("Workflow paused successfully"),n&&await n(),l(""),d(u()),s()}catch(L){console.error("Failed to pause workflow:",L),Q.error(((w=(A=L==null?void 0:L.response)==null?void 0:A.data)==null?void 0:w.error)||((k=(T=L==null?void 0:L.response)==null?void 0:T.data)==null?void 0:k.message)||"Failed to pause workflow")}finally{m(!1)}},y=()=>{c||(l(""),d(u()),s())};return e.jsx(mt,{open:t,onOpenChange:y,children:e.jsxs(ot,{className:"sm:max-w-[500px]",children:[e.jsx(ut,{children:e.jsxs(ct,{className:"flex items-center gap-2",children:[e.jsx(Ha,{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(le,{htmlFor:"pause-reason",className:"text-sm font-medium",children:["Reason for Pausing ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Es,{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:c}),e.jsxs("p",{className:"text-xs text-gray-500",children:[i.length," / 1000 characters"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(le,{htmlFor:"resume-date",className:"text-sm font-medium",children:["Resume Date ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(_e,{id:"resume-date",type:"date",value:o,onChange:f=>d(f.target.value),min:p(),max:x(),className:"text-sm",disabled:c}),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(Tt,{children:[e.jsx(F,{variant:"outline",onClick:y,disabled:c,children:"Cancel"}),e.jsx(F,{onClick:g,disabled:c||!i.trim()||!o,className:"bg-orange-600 hover:bg-orange-700 text-white",children:c?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Pausing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ha,{className:"w-4 h-4 mr-2"}),"Pause Workflow"]})})]})]})})}function Jp({isOpen:t,onClose:s,requestId:a,onSuccess:r}){const[n,i]=h.useState(""),[l,o]=h.useState(!1),d=async()=>{var m,u,x,p;try{o(!0),await Jj(a,n.trim()||void 0),Q.success("Workflow resumed successfully"),r&&await r(),i(""),s()}catch(g){console.error("Failed to resume workflow:",g),Q.error(((u=(m=g==null?void 0:g.response)==null?void 0:m.data)==null?void 0:u.error)||((p=(x=g==null?void 0:g.response)==null?void 0:x.data)==null?void 0:p.message)||"Failed to resume workflow")}finally{o(!1)}},c=()=>{l||(i(""),s())};return e.jsx(mt,{open:t,onOpenChange:c,children:e.jsxs(ot,{className:"sm:max-w-[500px]",children:[e.jsx(ut,{children:e.jsxs(ct,{className:"flex items-center gap-2",children:[e.jsx(li,{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(le,{htmlFor:"resume-notes",className:"text-sm font-medium",children:"Notes (Optional)"}),e.jsx(Es,{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(Tt,{children:[e.jsx(F,{variant:"outline",onClick:c,disabled:l,children:"Cancel"}),e.jsx(F,{onClick:d,disabled:l,className:"bg-green-600 hover:bg-green-700 text-white",children:l?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Resuming..."]}):e.jsxs(e.Fragment,{children:[e.jsx(li,{className:"w-4 h-4 mr-2"}),"Resume Workflow"]})})]})]})})}function qp({isOpen:t,onClose:s,requestId:a,approverName:r,onSuccess:n}){const[i,l]=h.useState(!1),o=async()=>{var d,c,m,u;try{l(!0),await qj(a),Q.success("Retrigger request sent to approver"),n&&await n(),s()}catch(x){console.error("Failed to retrigger pause:",x),Q.error(((c=(d=x==null?void 0:x.response)==null?void 0:d.data)==null?void 0:c.error)||((u=(m=x==null?void 0:x.response)==null?void 0:m.data)==null?void 0:u.message)||"Failed to send retrigger request")}finally{l(!1)}};return e.jsx(mt,{open:t,onOpenChange:s,children:e.jsxs(ot,{className:"sm:max-w-[450px]",children:[e.jsx(ut,{children:e.jsxs(ct,{className:"flex items-center gap-2",children:[e.jsx(Ge,{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(Tt,{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(Ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ge,{className:"w-4 h-4 mr-2"}),"Send Request"]})})]})]})})}const{DocumentsTab:gS,ActivityTab:fS,WorkNotesTab:yS,SummaryTab:bS,RequestDetailHeader:vS,QuickActionsSidebar:jS,RequestDetailModals:NS}=Zp;let wS=class extends h.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 CS({requestId:t,onBack:s,dynamicRequests:a=[]}){var qa,er,tr,sr,ar,_a,ya,La;const n=vr().requestId||t||"",l=new URLSearchParams(window.location.search).get("tab")||"overview",[o,d]=h.useState(l),[c,m]=h.useState(!1),[u,x]=h.useState(null),[p,g]=h.useState(null),[y,f]=h.useState(!1),[b,v]=h.useState(0),[A,w]=h.useState(!1),[T,k]=h.useState(!1),[L,D]=h.useState(!1),[S,N]=h.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[P,R]=h.useState({open:!1,violations:[]}),{user:O}=Jt(),{request:E,apiRequest:M,loading:B,refreshing:C,refreshDetails:j,currentApprovalLevel:U,isSpectator:$,isInitiator:_,existingParticipants:se,accessDenied:W}=yc(n,a,O),{mergedMessages:ce,unreadWorkNotes:Z,workNoteAttachments:I,setWorkNoteAttachments:V}=_p(n,M,o,O),{uploadingDocument:z,triggerFileInput:X,previewDocument:Y,setPreviewDocument:G,documentPolicy:ie,documentError:me,setDocumentError:Te}=Lp(M,j),{showApproveModal:Se,setShowApproveModal:re,showRejectModal:pe,setShowRejectModal:ve,showAddApproverModal:be,setShowAddApproverModal:Le,showAddSpectatorModal:J,setShowAddSpectatorModal:Oe,showSkipApproverModal:xt,setShowSkipApproverModal:je,showActionStatusModal:$e,setShowActionStatusModal:yt,skipApproverData:kt,setSkipApproverData:lt,actionStatus:Fs,setActionStatus:qs,handleApproveConfirm:wa,handleRejectConfirm:Qa,handleAddApprover:q,handleSkipApprover:we,handleAddSpectator:ee}=$p(n,U,j),{conclusionRemark:Fe,setConclusionRemark:Ee,conclusionLoading:Ke,conclusionSubmitting:Me,aiGenerated:Je,handleGenerateConclusion:Be,handleFinalizeConclusion:tt,generationAttempts:js,generationFailed:Kt,maxAttemptsReached:rt}=Op(E,n,_,j,s,qs,yt);h.useEffect(()=>{(async()=>{var ms;try{const Vs=await Qs("SYSTEM_SETTINGS"),rr=await Qs("WORKFLOW_SHARING"),nr=[...Vs,...rr],ca={};nr.forEach(bt=>{ca[bt.configKey]=bt.configValue}),N({maxApprovalLevels:parseInt(ca.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(ca.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((ms=ca.ALLOW_ADD_SPECTATOR)==null?void 0:ms.toLowerCase())==="true",maxSpectators:parseInt(ca.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(Vs){console.error("Failed to load system policy:",Vs)}})()},[]),h.useEffect(()=>{const ms=new URLSearchParams(window.location.search).get("tab");ms&&d(ms)},[n]);const st=()=>{j()},gt=()=>{w(!0)},qt=()=>{k(!0)},Et=async()=>{await j()},ga=()=>{D(!0)},fa=async()=>{await j()},Ma=async()=>{await j()},Ca=async()=>{if(!(M!=null&&M.requestId)){Q.error("Request ID not found");return}if(!u){Q.error("Summary not available. Please ensure the request is closed and the summary has been generated.");return}m(!0)},wt=((E==null?void 0:E.status)==="approved"||(E==null?void 0:E.status)==="rejected")&&_,Aa=(E==null?void 0:E.status)==="closed";h.useEffect(()=>{(async()=>{if(!Aa||!(M!=null&&M.requestId)){g(null),x(null);return}try{f(!0);const ms=await Wp(M.requestId);if(ms!=null&&ms.summaryId){x(ms.summaryId);try{const Vs=await bc(ms.summaryId);g(Vs)}catch(Vs){console.error("Failed to fetch summary details:",Vs),g(null),x(null)}}else g(null),x(null)}catch{g(null),x(null)}finally{f(!1)}})()},[Aa,M==null?void 0:M.requestId]);const Ja=((E==null?void 0:E.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 B&&!E&&!M?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(Bt,{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..."})]})}):W!=null&&W.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(nx,{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:W.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(Js,{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"})]})]})}):E?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(vS,{request:E,refreshing:C,onBack:s||(()=>window.history.back()),onRefresh:st,onShareSummary:Ca,isInitiator:_,slaData:((qa=E==null?void 0:E.summary)==null?void 0:qa.sla)||(E==null?void 0:E.sla)||null,isPaused:((er=E==null?void 0:E.pauseInfo)==null?void 0:er.isPaused)||!1}),e.jsxs(Ln,{value:o,onValueChange:d,className:"w-full","data-testid":"custom-request-detail-tabs",children:[e.jsx("div",{className:"mb-4 sm:mb-6",children:e.jsxs(On,{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(At,{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(ix,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Overview"})]}),Aa&&p&&e.jsxs(At,{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(No,{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(At,{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(Ks,{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(At,{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(Pe,{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(At,{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(Dt,{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(At,{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(ne,{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(St,{value:"overview",className:"mt-0","data-testid":"overview-tab-content",children:e.jsx(cN,{request:E,isInitiator:_,needsClosure:wt,conclusionRemark:Fe,setConclusionRemark:Ee,conclusionLoading:Ke,conclusionSubmitting:Me,aiGenerated:Je,handleGenerateConclusion:Be,handleFinalizeConclusion:tt,onPause:gt,onResume:qt,onRetrigger:ga,currentUserIsApprover:!!U,pausedByUserId:(sr=(tr=E==null?void 0:E.pauseInfo)==null?void 0:tr.pausedBy)==null?void 0:sr.userId,currentUserId:O==null?void 0:O.userId,generationAttempts:js,generationFailed:Kt,maxAttemptsReached:rt})}),Aa&&e.jsx(St,{value:"summary",className:"mt-0","data-testid":"summary-tab-content",children:e.jsx(bS,{summary:p,loading:y,onShare:Ca,isInitiator:_})}),e.jsx(St,{value:"workflow",className:"mt-0",children:e.jsx(xN,{request:E,user:O,isInitiator:_,onSkipApprover:Ft=>{if(!Ft.levelId){alert("Level ID not available");return}lt(Ft),je(!0)},onRefresh:j})}),e.jsx(St,{value:"documents",className:"mt-0",children:e.jsx(gS,{request:E,workNoteAttachments:I,uploadingDocument:z,documentPolicy:ie,triggerFileInput:X,setPreviewDocument:G,downloadDocument:bs})}),e.jsx(St,{value:"activity",className:"mt-0",children:e.jsx(fS,{request:E})}),e.jsx(St,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:o!=="worknotes",children:e.jsx(yS,{requestId:n,requestTitle:E.title,mergedMessages:ce,setWorkNoteAttachments:V,isInitiator:_,isSpectator:$,currentLevels:Ja,onAddApprover:q,maxApprovalLevels:S.maxApprovalLevels,onPolicyViolation:Ft=>R({open:!0,violations:Ft})})})]}),o!=="worknotes"&&e.jsx(jS,{request:E,isInitiator:_,isSpectator:$,currentApprovalLevel:U,onAddApprover:()=>Le(!0),onAddSpectator:()=>Oe(!0),onApprove:()=>re(!0),onReject:()=>ve(!0),onPause:gt,onResume:qt,onRetrigger:ga,summaryId:u,refreshTrigger:b,pausedByUserId:(_a=(ar=E==null?void 0:E.pauseInfo)==null?void 0:ar.pausedBy)==null?void 0:_a.userId,currentUserId:O==null?void 0:O.userId,apiRequest:M})]})]})]})}),c&&u&&e.jsx(Xp,{isOpen:c,onClose:()=>m(!1),summaryId:u,requestTitle:(E==null?void 0:E.title)||"N/A",onSuccess:()=>{j(),v(Ft=>Ft+1)}}),A&&(M==null?void 0:M.requestId)&&e.jsx(Qp,{isOpen:A,onClose:()=>w(!1),requestId:M.requestId,levelId:(U==null?void 0:U.levelId)||null,onSuccess:fa}),T&&(M==null?void 0:M.requestId)&&e.jsx(Jp,{isOpen:T,onClose:()=>k(!1),requestId:M.requestId,onSuccess:Et}),L&&(M==null?void 0:M.requestId)&&e.jsx(qp,{isOpen:L,onClose:()=>D(!1),requestId:M.requestId,approverName:(La=(ya=E==null?void 0:E.pauseInfo)==null?void 0:ya.pausedBy)==null?void 0:La.name,onSuccess:Ma}),e.jsx(NS,{showApproveModal:Se,showRejectModal:pe,showAddApproverModal:be,showAddSpectatorModal:J,showSkipApproverModal:xt,showActionStatusModal:$e,previewDocument:Y,documentError:me,request:E,skipApproverData:kt,actionStatus:Fs,existingParticipants:se,currentLevels:Ja,maxApprovalLevels:S.maxApprovalLevels,onPolicyViolation:Ft=>R({open:!0,violations:Ft}),setShowApproveModal:re,setShowRejectModal:ve,setShowAddApproverModal:Le,setShowAddSpectatorModal:Oe,setShowSkipApproverModal:je,setShowActionStatusModal:yt,setPreviewDocument:G,setDocumentError:Te,setSkipApproverData:lt,setActionStatus:qs,handleApproveConfirm:wa,handleRejectConfirm:Qa,handleAddApprover:q,handleAddSpectator:ee,handleSkipApprover:we,downloadDocument:bs,documentPolicy:ie}),e.jsx(_n,{open:P.open,onClose:()=>R({open:!1,violations:[]}),violations:P.violations,policyDetails:{maxApprovalLevels:S.maxApprovalLevels,maxParticipants:S.maxParticipants,allowSpectators:S.allowSpectators,maxSpectators:S.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(Pe,{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(Js,{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 AS(t){return e.jsx(wS,{children:e.jsx(CS,{...t})})}function SS({searchTerm:t,statusFilter:s,priorityFilter:a,templateTypeFilter:r,sortBy:n,sortOrder:i,onSearchChange:l,onStatusFilterChange:o,onPriorityFilterChange:d,onTemplateTypeFilterChange:c,onSortByChange:m,onSortOrderChange:u,onClearFilters:x,activeFiltersCount:p}){return e.jsxs(te,{className:"shadow-lg border-0",children:[e.jsx(ue,{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(Ya,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(ke,{className:"text-xs sm:text-sm",children:p>0&&e.jsxs("span",{className:"text-blue-600 font-medium",children:[p," filter",p>1?"s":""," active"]})})]})]}),p>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-5 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(As,{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(_e,{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(Ve,{value:a,onValueChange:d,children:[e.jsx(He,{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(ze,{placeholder:"All Priorities"})}),e.jsxs(We,{children:[e.jsx(K,{value:"all",children:"All Priorities"}),e.jsx(K,{value:"express",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pa,{className:"w-4 h-4 text-orange-600"}),e.jsx("span",{children:"Express"})]})}),e.jsx(K,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vt,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(Ve,{value:s,onValueChange:o,children:[e.jsx(He,{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(ze,{placeholder:"All Statuses"})}),e.jsxs(We,{children:[e.jsx(K,{value:"all",children:"All Statuses"}),e.jsx(K,{value:"pending",children:"Pending (In Approval)"}),e.jsx(K,{value:"approved",children:"Approved (Needs Closure)"})]})]}),e.jsxs(Ve,{value:r,onValueChange:c,children:[e.jsx(He,{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(ze,{placeholder:"All Templates"})}),e.jsxs(We,{children:[e.jsx(K,{value:"all",children:"All Templates"}),e.jsx(K,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(K,{value:"DEALER CLAIM",children:"Dealer Claim"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ve,{value:n,onValueChange:g=>m(g),children:[e.jsx(He,{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(ze,{placeholder:"Sort by"})}),e.jsxs(We,{children:[e.jsx(K,{value:"due",children:"Due Date"}),e.jsx(K,{value:"created",children:"Date Created"}),e.jsx(K,{value:"priority",children:"Priority"}),e.jsx(K,{value:"sla",children:"SLA Progress"})]})]}),e.jsx(F,{variant:"outline",size:"sm",onClick:()=>u(i==="asc"?"desc":"asc"),className:"px-2 sm:px-3 h-9 sm:h-10 md:h-11",children:i==="asc"?e.jsx(Di,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(Pi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function TS({searchTerm:t,priorityFilter:s,statusFilter:a,templateTypeFilter:r,sortBy:n,sortOrder:i,activeFiltersCount:l,onSearchChange:o,onPriorityChange:d,onStatusChange:c,onTemplateTypeChange:m,onSortByChange:u,onSortOrderChange:x,onClearFilters:p}){return e.jsxs(te,{className:"shadow-lg border-0","data-testid":"closed-requests-filters",children:[e.jsx(ue,{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(Ya,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(ke,{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:p,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-5 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(As,{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(_e,{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(Ve,{value:s,onValueChange:d,children:[e.jsx(He,{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(ze,{placeholder:"All Priorities"})}),e.jsxs(We,{children:[e.jsx(K,{value:"all",children:"All Priorities"}),e.jsx(K,{value:"express",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pa,{className:"w-4 h-4 text-orange-600"}),e.jsx("span",{children:"Express"})]})}),e.jsx(K,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vt,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(Ve,{value:a,onValueChange:c,children:[e.jsx(He,{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(ze,{placeholder:"Closure Type"})}),e.jsxs(We,{children:[e.jsx(K,{value:"all",children:"All Closures"}),e.jsx(K,{value:"approved",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(De,{className:"w-4 h-4 text-green-600"}),e.jsx("span",{children:"Closed After Approval"})]})}),e.jsx(K,{value:"rejected",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jt,{className:"w-4 h-4 text-red-600"}),e.jsx("span",{children:"Closed After Rejection"})]})})]})]}),e.jsxs(Ve,{value:r,onValueChange:m,children:[e.jsx(He,{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(ze,{placeholder:"All Templates"})}),e.jsxs(We,{children:[e.jsx(K,{value:"all",children:"All Templates"}),e.jsx(K,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(K,{value:"DEALER CLAIM",children:"Dealer Claim"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ve,{value:n,onValueChange:g=>u(g),children:[e.jsx(He,{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(ze,{placeholder:"Sort by"})}),e.jsxs(We,{children:[e.jsx(K,{value:"due",children:"Due Date"}),e.jsx(K,{value:"created",children:"Date Created"}),e.jsx(K,{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(Di,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(Pi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function kS({searchTerm:t,statusFilter:s,priorityFilter:a,templateTypeFilter:r,departmentFilter:n,slaComplianceFilter:i,initiatorFilter:l,approverFilter:o,approverFilterType:d,dateRange:c,customStartDate:m,customEndDate:u,showCustomDatePicker:x,departments:p,loadingDepartments:g,initiatorSearch:y,approverSearch:f,onSearchChange:b,onStatusChange:v,onPriorityChange:A,onTemplateTypeChange:w,onDepartmentChange:T,onSlaComplianceChange:k,onInitiatorChange:L,onApproverChange:D,onApproverTypeChange:S,onDateRangeChange:N,onCustomStartDateChange:P,onCustomEndDateChange:R,onShowCustomDatePickerChange:O,onApplyCustomDate:E,onClearFilters:M,hasActiveFilters:B}){return e.jsx(te,{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(Ya,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),B&&e.jsx(ne,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),B&&e.jsxs(F,{variant:"ghost",size:"sm",onClick:M,className:"gap-2",children:[e.jsx(Bt,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Gt,{}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 lg:grid-cols-6 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative md:col-span-3 lg:col-span-1",children:[e.jsx(As,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(_e,{placeholder:"Search requests...",value:t,onChange:C=>b(C.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(Ve,{value:s,onValueChange:v,children:[e.jsx(He,{className:"h-10","data-testid":"status-filter",children:e.jsx(ze,{placeholder:"All Status"})}),e.jsxs(We,{children:[e.jsx(K,{value:"all",children:"All Status"}),e.jsx(K,{value:"pending",children:"Pending"}),e.jsx(K,{value:"paused",children:"Paused"}),e.jsx(K,{value:"approved",children:"Approved"}),e.jsx(K,{value:"rejected",children:"Rejected"}),e.jsx(K,{value:"closed",children:"Closed"})]})]}),e.jsxs(Ve,{value:a,onValueChange:A,children:[e.jsx(He,{className:"h-10","data-testid":"priority-filter",children:e.jsx(ze,{placeholder:"All Priority"})}),e.jsxs(We,{children:[e.jsx(K,{value:"all",children:"All Priority"}),e.jsx(K,{value:"express",children:"Express"}),e.jsx(K,{value:"standard",children:"Standard"})]})]}),e.jsxs(Ve,{value:r,onValueChange:w,children:[e.jsx(He,{className:"h-10","data-testid":"template-type-filter",children:e.jsx(ze,{placeholder:"All Templates"})}),e.jsxs(We,{children:[e.jsx(K,{value:"all",children:"All Templates"}),e.jsx(K,{value:"CUSTOM",children:"Custom"}),e.jsx(K,{value:"DEALER CLAIM",children:"Dealer Claim"})]})]}),e.jsxs(Ve,{value:n,onValueChange:T,disabled:g||p.length===0,children:[e.jsx(He,{className:"h-10","data-testid":"department-filter",children:e.jsx(ze,{placeholder:g?"Loading...":"All Departments"})}),e.jsxs(We,{children:[e.jsx(K,{value:"all",children:"All Departments"}),p.map(C=>e.jsx(K,{value:C,children:C},C))]})]}),e.jsxs(Ve,{value:i,onValueChange:k,children:[e.jsx(He,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(ze,{placeholder:"All SLA Status"})}),e.jsxs(We,{children:[e.jsx(K,{value:"all",children:"All SLA Status"}),e.jsx(K,{value:"compliant",children:"Compliant"}),e.jsx(K,{value:"on-track",children:"On Track"}),e.jsx(K,{value:"approaching",children:"Approaching"}),e.jsx(K,{value:"critical",children:"Critical"}),e.jsx(K,{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(le,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:y.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:y.selectedUser.displayName||y.selectedUser.email}),e.jsx(F,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:y.handleClear,children:e.jsx(ft,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(_e,{placeholder:"Search initiator...",value:y.searchQuery,onChange:C=>y.handleSearch(C.target.value),onFocus:()=>{y.searchResults.length>0&&y.setShowResults(!0)},onBlur:()=>setTimeout(()=>y.setShowResults(!1),200),className:"h-10","data-testid":"initiator-search-input"}),y.showResults&&y.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:y.searchResults.map(C=>e.jsx("button",{type:"button",onClick:()=>y.handleSelect(C),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:C.displayName||C.email}),C.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:C.email})]})},C.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(le,{className:"text-sm font-medium text-gray-700",children:"Approver"}),o!=="all"&&S&&e.jsxs(Ve,{value:d,onValueChange:C=>S(C),children:[e.jsx(He,{className:"h-7 w-32 text-xs",children:e.jsx(ze,{})}),e.jsxs(We,{children:[e.jsx(K,{value:"current",children:"Current Only"}),e.jsx(K,{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(_e,{placeholder:"Search approver...",value:f.searchQuery,onChange:C=>f.handleSearch(C.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(C=>e.jsx("button",{type:"button",onClick:()=>f.handleSelect(C),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:C.displayName||C.email}),C.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:C.email})]})},C.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(it,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ve,{value:c,onValueChange:C=>N(C),children:[e.jsx(He,{className:"w-[160px] h-10",children:e.jsx(ze,{placeholder:"Date Range"})}),e.jsxs(We,{children:[e.jsx(K,{value:"all",children:"All Time"}),e.jsx(K,{value:"today",children:"Today"}),e.jsx(K,{value:"week",children:"This Week"}),e.jsx(K,{value:"month",children:"This Month"}),e.jsx(K,{value:"last7days",children:"Last 7 Days"}),e.jsx(K,{value:"last30days",children:"Last 30 Days"}),e.jsx(K,{value:"custom",children:"Custom Range"})]})]}),c==="custom"&&e.jsxs(Ys,{open:x,onOpenChange:O,children:[e.jsx(Zs,{asChild:!0,children:e.jsxs(F,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(it,{className:"w-4 h-4"}),m&&u?`${Ye(m,"MMM d, yyyy")} - ${Ye(u,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Xs,{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(le,{htmlFor:"start-date",children:"Start Date"}),e.jsx($s,{value:m||null,onChange:C=>{const j=C?new Date(C):void 0;j?(P==null||P(j),u&&j>u&&(R==null||R(j))):P==null||P(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{htmlFor:"end-date",children:"End Date"}),e.jsx($s,{value:u||null,onChange:C=>{const j=C?new Date(C):void 0;j?(R==null||R(j),m&&j<m&&(P==null||P(j))):R==null||R(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:E,disabled:!m||!u,className:"flex-1 bg-re-green hover:bg-re-green/90",children:"Apply Range"}),e.jsx(F,{size:"sm",variant:"outline",onClick:()=>{O==null||O(!1),P==null||P(void 0),R==null||R(void 0),N("month")},children:"Cancel"})]})]})})]})]})]})})})}function RS({request:t,apiRequest:s,currentUserId:a,isInitiator:r,onEditClaimAmount:n,className:i="",needsClosure:l=!1,conclusionRemark:o="",setConclusionRemark:d,conclusionLoading:c=!1,conclusionSubmitting:m=!1,aiGenerated:u=!1,handleGenerateConclusion:x,handleFinalizeConclusion:p,generationAttempts:g=0,generationFailed:y=!1,maxAttemptsReached:f=!1}){var T,k,L,D,S,N,P,R,O;if(!Wi(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 b=Gp(s);if(!b)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=Kp(s,a),A=Yp(v),w={name:((T=s.initiator)==null?void 0:T.name)||((k=s.initiator)==null?void 0:k.displayName)||((L=s.initiator)==null?void 0:L.email)||"Unknown",role:((D=s.initiator)==null?void 0:D.role)||((S=s.initiator)==null?void 0:S.designation)||"Initiator",department:((N=s.initiator)==null?void 0:N.department)||s.department||"",email:((P=s.initiator)==null?void 0:P.email)||"N/A",phone:((R=s.initiator)==null?void 0:R.phone)||((O=s.initiator)==null?void 0:O.mobile)};return e.jsxs("div",{className:`space-y-6 ${i}`,children:[e.jsx(iS,{activityInfo:b.activityInfo,createdAt:s==null?void 0:s.createdAt,updatedAt:s==null?void 0:s.updatedAt}),e.jsx(lS,{dealerInfo:b.dealerInfo}),A.showProposalDetails&&b.proposalDetails&&e.jsx(cS,{proposalDetails:b.proposalDetails}),e.jsx(dS,{initiatorInfo:w}),(s==null?void 0:s.status)==="closed"&&(s==null?void 0:s.conclusionRemark)&&e.jsxs(te,{children:[e.jsxs(ue,{children:[e.jsxs(xe,{className:"flex items-center gap-2 text-base",children:[e.jsx(De,{className:"w-5 h-5 text-gray-600"}),"Conclusion Remark"]}),e.jsx(ke,{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(ra,{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 ",is(s.closureDate)]}),e.jsxs("span",{children:["By ",w.name]})]})]})]}),l&&e.jsxs(te,{"data-testid":"conclusion-remark-card",children:[e.jsx(ue,{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(xe,{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(De,{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(ke,{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:c||f,className:"gap-2 shrink-0 h-9","data-testid":"generate-ai-conclusion-button",children:[e.jsx(Bt,{className:`w-3.5 h-3.5 ${c?"animate-spin":""}`}),u?"Regenerate":"Generate with AI"]}),u&&!f&&!y&&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:c?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(Ze,{className:"w-8 h-8 text-blue-600 animate-spin mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Preparing conclusion remark..."})]})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Conclusion Remark"}),u&&e.jsx("span",{className:"text-xs text-blue-600","data-testid":"ai-generated-label",children:"✓ System-generated suggestion (editable)"})]}),d&&e.jsx($i,{value:o,onChange:E=>d(E),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"})]})]}),p&&e.jsx("div",{className:"flex gap-3 justify-end pt-3 border-t",children:e.jsx(F,{onClick:p,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(Ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Finalizing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(De,{className:"w-4 h-4 mr-2"}),"Finalize & Close Request"]})})})]})})]})]})}function DS({isOpen:t,onClose:s,onApprove:a,onReject:r,requestTitle:n="Request",requestDescription:i="",requestId:l,levelName:o="Approval Level",approverName:d="Approver"}){const[c,m]=h.useState(""),[u,x]=h.useState(!1),[p,g]=h.useState(null),y=async()=>{if(!c.trim()){Q.error("Please provide approval comments");return}try{x(!0),g("approve"),await a(c),b(),s()}catch(A){console.error("Failed to approve request:",A),Q.error("Failed to approve request. Please try again.")}finally{x(!1),g(null)}},f=async()=>{if(!c.trim()){Q.error("Please provide rejection reason");return}try{x(!0),g("reject"),await r(c),b(),s()}catch(A){console.error("Failed to reject request:",A),Q.error("Failed to reject request. Please try again.")}finally{x(!1),g(null)}},b=()=>{m(""),g(null)},v=()=>{u||(b(),s())};return t?e.jsx(mt,{open:t,onOpenChange:v,children:e.jsxs(ot,{className:"dealer-proposal-modal overflow-hidden flex flex-col max-w-3xl",children:[e.jsxs(ut,{className:"flex-shrink-0 pb-3 lg:pb-4 px-6 pt-4 lg:pt-6 border-b",children:[e.jsxs(ct,{className:"flex items-center gap-2 text-lg lg:text-xl",children:[e.jsx(De,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"}),"Review Request"]}),e.jsxs(It,{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:"})," ",d]})]})})]}),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(Pe,{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(ra,{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(Es,{placeholder:"Provide your evaluation comments, approval conditions, or rejection reasons...",value:c,onChange:A=>m(A.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:[c.length," characters"]})]}),!c.trim()&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-2 flex items-start gap-2",children:[e.jsx(jt,{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(Tt,{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:u,className:"border-2",children:"Cancel"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(F,{onClick:f,disabled:!c.trim()||u,variant:"destructive",className:"bg-red-600 hover:bg-red-700",children:u&&p==="reject"?"Rejecting...":e.jsxs(e.Fragment,{children:[e.jsx(jt,{className:"w-4 h-4 mr-2"}),"Reject"]})}),e.jsx(F,{onClick:y,disabled:!c.trim()||u,className:"bg-green-600 hover:bg-green-700 text-white",children:u&&p==="approve"?"Approving...":e.jsxs(e.Fragment,{children:[e.jsx(De,{className:"w-4 h-4 mr-2"}),"Approve"]})})]})]})]})}):null}function PS({isOpen:t,onClose:s,onDownload:a,onSendToDealer:r,creditNoteData:n,dealerInfo:i,activityName:l,requestNumber:o,requestId:d,dueDate:c}){const[m,u]=h.useState(!1),[x,p]=h.useState(!1),g=(n==null?void 0:n.creditNoteNumber)&&(n==null?void 0:n.creditNoteNumber)!=="",y=(n==null?void 0:n.creditNoteNumber)||"",f=n!=null&&n.creditNoteDate?is(n.creditNoteDate,{includeTime:!1,format:"short"}):"",b=(n==null?void 0:n.creditNoteAmount)||0,v=(n==null?void 0:n.status)||"PENDING",A=(i==null?void 0:i.dealerName)||"Jaipur Royal Enfield",w=(i==null?void 0:i.dealerCode)||"RE-JP-009",T=l||"Activity",k=o||"RE-REQ-2024-CM-101",L=c?is(c,{includeTime:!1,format:"short"}):"Jan 4, 2026",D=async()=>{if(a)try{u(!0),await a(),Q.success("Credit note downloaded successfully")}catch(P){console.error("Failed to download credit note:",P),Q.error("Failed to download credit note. Please try again.")}finally{u(!1)}else Q.info("Credit note will be automatically saved to Documents tab")},S=async()=>{if(r)try{p(!0),await r(),Q.success("Credit note sent to dealer successfully"),s()}catch(P){console.error("Failed to send credit note to dealer:",P),Q.error("Failed to send credit note. Please try again.")}finally{p(!1)}else Q.info("Email notification will be sent to dealer with credit note attachment")},N=P=>`₹${P.toLocaleString("en-IN",{minimumFractionDigits:0,maximumFractionDigits:0})}`;return e.jsx(mt,{open:t,onOpenChange:s,children:e.jsxs(ot,{className:"sm:max-w-lg lg:max-w-[1000px] max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ut,{children:[e.jsxs(ct,{className:"font-semibold flex items-center gap-2 text-2xl",children:[e.jsx(ls,{className:"w-6 h-6 text-[--re-green]"}),"Credit Note from SAP"]}),e.jsx(It,{className:"text-base",children:"Review and send credit note to dealer"})]}),e.jsxs("div",{className:"space-y-5 py-4",children:[g?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(ne,{className:"bg-green-600 text-white px-4 py-2 text-base",children:[e.jsx(De,{className:"w-4 h-4 mr-2"}),v==="APPROVED"?"Approved":v==="ISSUED"?"Issued":v==="SENT"?"Sent":"Pending"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 mt-4",children:[e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-green-100",children:[e.jsxs(le,{className:"font-medium text-xs text-gray-600 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(d0,{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(le,{className:"font-medium text-xs text-gray-600 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(it,{className:"w-3 h-3"}),"Issue Date"]}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:f})]})]})]}),e.jsxs("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-5",children:[e.jsxs(le,{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:N(b)})]})]}):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(ls,{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(Ri,{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(le,{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(le,{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:w})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(le,{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:T})]})]})]}),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(Pe,{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(le,{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:k})]}),e.jsxs("div",{children:[e.jsx(le,{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:L})]})]})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start gap-3",children:[e.jsx(Pe,{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(Tt,{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:m||x,className:"border-2",children:"Close"}),e.jsx("div",{className:"flex gap-2",children:g&&e.jsxs(e.Fragment,{children:[e.jsxs(F,{variant:"outline",onClick:D,disabled:m||x,className:"border-blue-600 text-blue-600 hover:bg-blue-50",children:[e.jsx(Nt,{className:"w-4 h-4 mr-2"}),m?"Downloading...":"Download"]}),e.jsxs(F,{onClick:S,disabled:m||x,className:"bg-green-600 hover:bg-green-700 text-white shadow-md",children:[e.jsx(rx,{className:"w-4 h-4 mr-2"}),x?"Sending...":"Send to Dealer"]})]})})]})]})})}function IS({isOpen:t,onClose:s,onSubmit:a,dealerName:r="Jaipur Royal Enfield",activityName:n="Activity",requestId:i,documentPolicy:l}){var Te,Se;const[o,d]=h.useState(""),[c,m]=h.useState(""),[u,x]=h.useState([]),[p,g]=h.useState([]),[y,f]=h.useState([]),[b,v]=h.useState([]),[A,w]=h.useState(null),[T,k]=h.useState(""),[L,D]=h.useState(!1),[S,N]=h.useState(null),P=h.useRef(null),R=h.useRef(null),O=h.useRef(null),E=h.useRef(null),M=re=>{const pe=re.type.toLowerCase(),ve=re.name.toLowerCase();return pe.includes("image")||pe.includes("pdf")||ve.endsWith(".pdf")||ve.endsWith(".jpg")||ve.endsWith(".jpeg")||ve.endsWith(".png")||ve.endsWith(".gif")||ve.endsWith(".webp")};h.useEffect(()=>()=>{S!=null&&S.url&&URL.revokeObjectURL(S.url)},[S]);const B=re=>{if(!M(re)){Q.error("Preview is only available for images and PDF files");return}S!=null&&S.url&&URL.revokeObjectURL(S.url);const pe=URL.createObjectURL(re);N({file:re,url:pe})},C=re=>{const pe=URL.createObjectURL(re),ve=document.createElement("a");ve.href=pe,ve.download=re.name,document.body.appendChild(ve),ve.click(),document.body.removeChild(ve),URL.revokeObjectURL(pe)},j=h.useMemo(()=>u.reduce((re,pe)=>re+(pe.amount||0),0),[u]),U=h.useMemo(()=>{const re=o!=="",pe=p.length>0,ve=y.length>0,be=T.trim().length>0;return re&&pe&&ve&&be},[o,p,y,T]),$=new Date().toISOString().split("T")[0],_=()=>{x([...u,{id:Date.now().toString(),description:"",amount:0}])},se=(re,pe,ve)=>{x(u.map(be=>be.id===re?{...be,[pe]:ve}:be))},W=re=>{x(u.filter(pe=>pe.id!==re))},ce=re=>{const pe=Array.from(re.target.files||[]);if(pe.length>0){const ve=[],be=l.maxFileSizeMB*1024*1024,Le=[".pdf",".doc",".docx",".zip",".rar"];pe.forEach(J=>{var je,$e;const Oe="."+((je=J.name.split(".").pop())==null?void 0:je.toLowerCase()),xt=(($e=J.name.split(".").pop())==null?void 0:$e.toLowerCase())||"";if(J.size>be){Q.error(`"${J.name}" exceeds ${l.maxFileSizeMB}MB limit and was not added.`);return}if(!Le.includes(Oe)){Q.error(`"${J.name}" is not a supported document type (PDF, DOC, ZIP).`);return}if(!l.allowedFileTypes.includes(xt)){Q.error(`"${J.name}" has an unallowed file type according to system policy.`);return}ve.push(J)}),ve.length>0&&g([...p,...ve]),P.current&&(P.current.value="")}},Z=re=>{g(p.filter((pe,ve)=>ve!==re))},I=re=>{const pe=Array.from(re.target.files||[]);if(pe.length>0){const ve=[],be=l.maxFileSizeMB*1024*1024;pe.forEach(Le=>{var Oe;const J=((Oe=Le.name.split(".").pop())==null?void 0:Oe.toLowerCase())||"";if(Le.size>be){Q.error(`Photo "${Le.name}" exceeds ${l.maxFileSizeMB}MB limit.`);return}if(!Le.type.startsWith("image/")){Q.error(`"${Le.name}" is not an image file.`);return}if(!l.allowedFileTypes.includes(J)){Q.error(`"${Le.name}" has an unsupported image format.`);return}ve.push(Le)}),ve.length>0&&f([...y,...ve]),R.current&&(R.current.value="")}},V=re=>{f(y.filter((pe,ve)=>ve!==re))},z=re=>{const pe=Array.from(re.target.files||[]);if(pe.length>0){const ve=[],be=l.maxFileSizeMB*1024*1024,Le=[".pdf",".jpg",".jpeg",".png"];pe.forEach(J=>{var je,$e;const Oe="."+((je=J.name.split(".").pop())==null?void 0:je.toLowerCase()),xt=(($e=J.name.split(".").pop())==null?void 0:$e.toLowerCase())||"";if(J.size>be){Q.error(`Invoice "${J.name}" exceeds ${l.maxFileSizeMB}MB limit.`);return}if(!Le.includes(Oe)){Q.error(`"${J.name}" is not a supported type (PDF, JPG, PNG).`);return}if(!l.allowedFileTypes.includes(xt)){Q.error(`"${J.name}" format is not allowed by system policy.`);return}ve.push(J)}),ve.length>0&&v([...b,...ve]),O.current&&(O.current.value="")}},X=re=>{v(b.filter((pe,ve)=>ve!==re))},Y=re=>{var ve,be,Le;const pe=(ve=re.target.files)==null?void 0:ve[0];if(pe){const J=l.maxFileSizeMB*1024*1024,Oe=[".pdf",".xlsx",".xls",".csv"],xt="."+((be=pe.name.split(".").pop())==null?void 0:be.toLowerCase()),je=((Le=pe.name.split(".").pop())==null?void 0:Le.toLowerCase())||"";if(pe.size>J){Q.error(`Attendance file exceeds ${l.maxFileSizeMB}MB limit.`),E.current&&(E.current.value="");return}if(!Oe.includes(xt)){Q.error("Please upload PDF, Excel, or CSV files only"),E.current&&(E.current.value="");return}if(!l.allowedFileTypes.includes(je)){Q.error(`"${pe.name}" format is not allowed by system policy.`),E.current&&(E.current.value="");return}w(pe)}},G=async()=>{if(!U){Q.error("Please fill all required fields");return}const re=u.filter(pe=>pe.description.trim()!==""&&pe.amount>0);try{D(!0),await a({activityCompletionDate:o,numberOfParticipants:c?parseInt(c):void 0,closedExpenses:re,totalClosedExpenses:j,completionDocuments:p,activityPhotos:y,invoicesReceipts:b.length>0?b:void 0,attendanceSheet:A||void 0,completionDescription:T}),ie(),s()}catch(pe){console.error("Failed to submit completion documents:",pe),Q.error("Failed to submit completion documents. Please try again.")}finally{D(!1)}},ie=()=>{S!=null&&S.url&&URL.revokeObjectURL(S.url),N(null),d(""),m(""),x([]),g([]),f([]),v([]),w(null),k(""),P.current&&(P.current.value=""),R.current&&(R.current.value=""),O.current&&(O.current.value=""),E.current&&(E.current.value="")},me=()=>{L||(ie(),s())};return e.jsxs(mt,{open:t,onOpenChange:me,children:[e.jsxs(ot,{className:"dealer-completion-documents-modal overflow-hidden flex flex-col",children:[e.jsxs(ut,{className:"px-6 pt-6 pb-3 flex-shrink-0",children:[e.jsxs(ct,{className:"font-semibold flex items-center gap-2 text-xl sm:text-2xl",children:[e.jsx(Bs,{className:"w-5 h-5 sm:w-6 sm:h-6 text-[--re-green]"}),"Activity Completion Documents"]}),e.jsx(It,{className:"text-sm sm:text-base",children:"Step 5: Upload completion proof and final documents"}),e.jsxs("div",{className:"space-y-1 mt-2 text-xs sm:text-sm text-gray-600",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Dealer:"})," ",r]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Activity:"})," ",n]}),e.jsx("div",{className:"mt-2",children:"Please upload completion documents, photos, and provide details about the completed activity."})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto overflow-x-hidden px-6 py-3",children:e.jsxs("div",{className:"space-y-5 sm:space-y-6 max-w-4xl mx-auto",children:[e.jsxs("div",{className:"space-y-1.5 sm:space-y-2",children:[e.jsxs(le,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",htmlFor:"completionDate",children:[e.jsx(it,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Activity Completion Date *"]}),e.jsx($s,{value:o||null,onChange:re=>d(re||""),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(ne,{className:"bg-secondary text-secondary-foreground text-xs",children:"Optional"})]}),e.jsxs(F,{type:"button",onClick:_,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white",size:"sm",children:[e.jsx(vs,{className:"w-4 h-4 mr-1"}),"Add Expense"]})]}),e.jsxs("div",{className:"space-y-2 sm:space-y-3",children:[u.map(re=>e.jsxs("div",{className:"flex gap-2 items-start",children:[e.jsx("div",{className:"flex-1",children:e.jsx(_e,{placeholder:"Item name (e.g., Venue rental, Refreshments, Printing)",value:re.description,onChange:pe=>se(re.id,"description",pe.target.value),className:"text-sm"})}),e.jsx("div",{className:"w-32 sm:w-40",children:e.jsx(_e,{type:"number",placeholder:"Amount",min:"0",step:"0.01",value:re.amount||"",onChange:pe=>se(re.id,"amount",parseFloat(pe.target.value)||0),className:"text-sm"})}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:"mt-0.5 hover:bg-red-100 hover:text-red-700 h-9 w-9 p-0",onClick:()=>W(re.id),children:e.jsx(ft,{className:"w-4 h-4"})})]},re.id)),u.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.'}),u.length>0&&j>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:["₹",j.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(ne,{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(le,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",children:[e.jsx(Pe,{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 ${p.length>0?"border-green-500 bg-green-50 hover:border-green-600":"border-gray-300 hover:border-blue-500 bg-white"}`,children:[e.jsx("input",{ref:P,type:"file",multiple:!0,accept:[".pdf",".doc",".docx",".zip",".rar"].filter(re=>l.allowedFileTypes.includes(re.replace(".",""))).join(","),className:"hidden",id:"completionDocs",onChange:ce}),e.jsx("label",{htmlFor:"completionDocs",className:"cursor-pointer flex flex-col items-center gap-2",children:p.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Ts,{className:"w-8 h-8 text-green-600"}),e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsxs("span",{className:"text-sm font-semibold text-green-700",children:[p.length," document",p.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(Bs,{className:"w-8 h-8 text-gray-400"}),e.jsxs("span",{className:"text-sm text-gray-600",children:["Click to upload documents (Max ",l.maxFileSizeMB,"MB)"]}),e.jsx("p",{className:"text-[10px] text-gray-400",children:"PDF, DOC, ZIP allowed"})]})})]}),p.length>0&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("p",{className:"text-xs font-medium text-gray-600 mb-1",children:["Selected Documents (",p.length,"):"]}),p.map((re,pe)=>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(Pe,{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:re.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[M(re)&&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:()=>B(re),title:"Preview file",children:e.jsx(ht,{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:()=>C(re),title:"Download file",children:e.jsx(Nt,{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:()=>Z(pe),title:"Remove document",children:e.jsx(ft,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},pe))]})]}),e.jsxs("div",{children:[e.jsxs(le,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",children:[e.jsx(Kn,{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 ${y.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:R,type:"file",multiple:!0,accept:[".jpg",".jpeg",".png",".gif",".webp"].filter(re=>l.allowedFileTypes.includes(re.replace(".",""))).join(","),className:"hidden",id:"completionPhotos",onChange:I}),e.jsx("label",{htmlFor:"completionPhotos",className:"cursor-pointer flex flex-col items-center gap-2",children:y.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Ts,{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:[y.length," photo",y.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(Kn,{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)"})]})})]}),y.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 (",y.length,"):"]}),y.map((re,pe)=>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(Kn,{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:re.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[M(re)&&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:()=>B(re),title:"Preview photo",children:e.jsx(ht,{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:()=>C(re),title:"Download photo",children:e.jsx(Nt,{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:()=>V(pe),title:"Remove photo",children:e.jsx(ft,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},pe))]})]})]})]}),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(ne,{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(le,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",children:[e.jsx(ls,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Invoices / Receipts"]}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 mb-2",children:"Upload invoices and receipts for expenses incurred"}),e.jsxs("div",{className:`border-2 border-dashed rounded-lg p-3 sm:p-4 transition-all duration-200 ${b.length>0?"border-blue-500 bg-blue-50 hover:border-blue-600":"border-gray-300 hover:border-blue-500 bg-white"}`,children:[e.jsx("input",{ref:O,type:"file",multiple:!0,accept:[".pdf",".jpg",".jpeg",".png"].filter(re=>l.allowedFileTypes.includes(re.replace(".",""))).join(","),className:"hidden",id:"invoiceReceipts",onChange:z}),e.jsx("label",{htmlFor:"invoiceReceipts",className:"cursor-pointer flex flex-col items-center gap-2",children:b.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Ts,{className:"w-8 h-8 text-blue-600"}),e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsxs("span",{className:"text-sm font-semibold text-blue-700",children:[b.length," document",b.length!==1?"s":""," selected"]}),e.jsx("span",{className:"text-xs text-blue-600",children:"Click to add more documents"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600",children:"Click to upload invoices/receipts (PDF, JPG, PNG)"})]})})]}),b.length>0&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("p",{className:"text-xs font-medium text-gray-600 mb-1",children:["Selected Documents (",b.length,"):"]}),b.map((re,pe)=>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(ls,{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:re.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[M(re)&&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:()=>B(re),title:"Preview file",children:e.jsx(ht,{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:()=>C(re),title:"Download file",children:e.jsx(Nt,{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:()=>X(pe),title:"Remove document",children:e.jsx(ft,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},pe))]})]}),e.jsxs("div",{children:[e.jsx(le,{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 ${A?"border-blue-500 bg-blue-50 hover:border-blue-600":"border-gray-300 hover:border-blue-500 bg-white"}`,children:[e.jsx("input",{ref:E,type:"file",accept:[".pdf",".xlsx",".xls",".csv"].filter(re=>l.allowedFileTypes.includes(re.replace(".",""))).join(","),className:"hidden",id:"attendanceDoc",onChange:Y}),e.jsx("label",{htmlFor:"attendanceDoc",className:"cursor-pointer flex flex-col items-center gap-2",children:A?e.jsxs(e.Fragment,{children:[e.jsx(Ts,{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:A.name}),e.jsx("span",{className:"text-xs text-blue-600",children:"Document selected"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Bs,{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)"})]})})]}),A&&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(Pe,{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:A.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[M(A)&&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:()=>B(A),title:"Preview file",children:e.jsx(ht,{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:()=>C(A),title:"Download file",children:e.jsx(Nt,{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:()=>{w(null),E.current&&(E.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(le,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",htmlFor:"completionDescription",children:"Brief Description of Completion *"}),e.jsx(Es,{id:"completionDescription",placeholder:"Provide a brief description of the completed activity, including key highlights, outcomes, challenges faced, and any relevant observations...",value:T,onChange:re=>k(re.target.value),className:"min-h-[100px] sm:min-h-[120px] text-sm"}),e.jsxs("p",{className:"text-xs text-gray-500",children:[T.length," characters"]})]}),!U&&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(Ge,{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(Tt,{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:me,disabled:L,className:"border-2",children:"Cancel"}),e.jsx(F,{onClick:G,disabled:L||!U,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white disabled:bg-gray-300 disabled:text-gray-500",children:L?"Submitting...":"Submit Documents"})]})]}),S&&e.jsx(mt,{open:!!S,onOpenChange:()=>{S!=null&&S.url&&URL.revokeObjectURL(S.url),N(null)},children:e.jsx(ot,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(ut,{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(ht,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(ct,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:S.file.name}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[S.file.type||"Unknown type"," • ",(S.file.size/1024).toFixed(1)," KB"]})]})]}),e.jsx("div",{className:"flex items-center gap-2 flex-wrap mr-2",children:e.jsxs(F,{variant:"outline",size:"sm",onClick:()=>C(S.file),className:"gap-2 h-9",children:[e.jsx(Nt,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Download"})]})})]})}),e.jsx("div",{className:"file-preview-body bg-gray-100 rounded-lg p-2 sm:p-4",children:(Te=S.file.type)!=null&&Te.includes("image")?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("img",{src:S.url,alt:S.file.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"},className:"rounded-lg shadow-lg"})}):(Se=S.file.type)!=null&&Se.includes("pdf")||S.file.name.toLowerCase().endsWith(".pdf")?e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("iframe",{src:S.url,className:"w-full h-full rounded-lg border-0",title:S.file.name,style:{minHeight:"70vh",height:"100%"}})}):e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-gray-200 rounded-full flex items-center justify-center mb-4",children:e.jsx(ht,{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:()=>C(S.file),className:"gap-2",children:[e.jsx(Nt,{className:"h-4 w-4"}),"Download ",S.file.name]})]})})]})})})]})}function ES({isOpen:t,onClose:s,onSubmit:a,dealerName:r="Jaipur Royal Enfield",activityName:n="Activity",requestId:i,previousProposalData:l,documentPolicy:o}){const[d,c]=h.useState(null),[m,u]=h.useState([{id:"1",description:"",amount:0}]),[x,p]=h.useState("date"),[g,y]=h.useState(""),[f,b]=h.useState(""),[v,A]=h.useState([]),[w,T]=h.useState(""),[k,L]=h.useState(!1),[D,S]=h.useState(null),[N,P]=h.useState(!1),R=h.useRef(null),O=h.useRef(null),E=G=>{if(!G)return!1;const ie=G.toLowerCase();return ie.endsWith(".pdf")||!!ie.match(/\.(jpg|jpeg|png|gif|webp)$/i)},M=G=>E(G.name);h.useEffect(()=>()=>{D!=null&&D.fileUrl&&D.fileUrl.startsWith("blob:")&&URL.revokeObjectURL(D.fileUrl)},[D]);const B=G=>{if(!M(G)){Q.error("Preview is only available for images and PDF files");return}D!=null&&D.fileUrl&&D.fileUrl.startsWith("blob:")&&URL.revokeObjectURL(D.fileUrl);const ie=URL.createObjectURL(G);S({fileName:G.name,fileType:G.type,documentId:"",fileUrl:ie,fileSize:G.size})},C=G=>{const ie=G.originalFileName||G.fileName||G.name||"Document",me=G.documentId||G.id||"",Te=ie.toLowerCase().endsWith(".pdf")?"application/pdf":"image/jpeg";let Se="";if(me)Se=Gr(me);else if(Se=G.storageUrl||G.documentUrl||"",Se&&!Se.startsWith("http")){const re="https://re-workflow-nt-dev.siplsolutions.com",pe=re.endsWith("/")?re.slice(0,-1):re,ve=Se.startsWith("/")?Se:`/${Se}`;Se=`${pe}${ve}`}S({fileName:ie,fileType:Te,documentId:me,fileUrl:Se})},j=G=>{const ie=URL.createObjectURL(G),me=document.createElement("a");me.href=ie,me.download=G.name,document.body.appendChild(me),me.click(),document.body.removeChild(me),URL.revokeObjectURL(ie)},U=h.useMemo(()=>m.reduce((G,ie)=>G+(ie.amount||0),0),[m]),$=h.useMemo(()=>{const G=d!==null,ie=m.length>0&&m.every(Se=>Se.description.trim()!==""&&Se.amount>0),me=x==="date"?g!=="":f!==""&&parseInt(f)>0,Te=w.trim().length>0;return G&&ie&&me&&Te},[d,m,x,g,f,w]),_=G=>{var me,Te,Se;const ie=(me=G.target.files)==null?void 0:me[0];if(ie){const re=o.maxFileSizeMB*1024*1024;if(ie.size>re){Q.error(`File size exceeds the maximum allowed size of ${o.maxFileSizeMB}MB. Current size: ${(ie.size/(1024*1024)).toFixed(2)}MB`),R.current&&(R.current.value="");return}const pe=[".pdf",".doc",".docx"],ve="."+((Te=ie.name.split(".").pop())==null?void 0:Te.toLowerCase()),be=((Se=ie.name.split(".").pop())==null?void 0:Se.toLowerCase())||"";if(!pe.includes(ve)||!o.allowedFileTypes.includes(be)){Q.error("Please upload a valid PDF, DOC, or DOCX file as per system policy"),R.current&&(R.current.value="");return}c(ie)}},se=G=>{const ie=Array.from(G.target.files||[]),me=[],Te=o.maxFileSizeMB*1024*1024;ie.forEach(Se=>{var pe;if(Se.size>Te){Q.error(`"${Se.name}" exceeds ${o.maxFileSizeMB}MB limit and was not added.`);return}const re=((pe=Se.name.split(".").pop())==null?void 0:pe.toLowerCase())||"";if(!o.allowedFileTypes.includes(re)){Q.error(`"${Se.name}" has an unsupported file type and was not added.`);return}me.push(Se)}),me.length>0&&A(Se=>[...Se,...me]),O.current&&(O.current.value="")},W=()=>{u(G=>[...G,{id:Date.now().toString(),description:"",amount:0}])},ce=G=>{m.length>1&&u(ie=>ie.filter(me=>me.id!==G))},Z=(G,ie,me)=>{u(Te=>Te.map(Se=>Se.id===G?{...Se,[ie]:ie==="amount"?parseFloat(me.toString())||0:me}:Se))},I=G=>{A(ie=>ie.filter((me,Te)=>Te!==G))},V=async()=>{if(!$){Q.error("Please fill all required fields");return}let G=g||"";if(x==="days"&&f){const ie=parseInt(f),me=new Date;me.setDate(me.getDate()+ie),G=me.toISOString().split("T")[0]}try{L(!0),await a({proposalDocument:d,costBreakup:m.filter(ie=>ie.description.trim()!==""&&ie.amount>0),expectedCompletionDate:G,otherDocuments:v,dealerComments:w}),z(),s()}catch(ie){console.error("Failed to submit proposal:",ie),Q.error("Failed to submit proposal. Please try again.")}finally{L(!1)}},z=()=>{D!=null&&D.fileUrl&&D.fileUrl.startsWith("blob:")&&URL.revokeObjectURL(D.fileUrl),S(null),c(null),u([{id:"1",description:"",amount:0}]),p("date"),y(""),b(""),A([]),T(""),R.current&&(R.current.value=""),O.current&&(O.current.value="")},X=()=>{k||(z(),s())},Y=new Date().toISOString().split("T")[0];return e.jsxs(mt,{open:t,onOpenChange:X,children:[e.jsxs(ot,{className:"dealer-proposal-modal overflow-hidden flex flex-col",children:[e.jsxs(ut,{className:"flex-shrink-0 pb-3 lg:pb-4",children:[e.jsxs(ct,{className:"flex items-center gap-2 text-xl lg:text-2xl",children:[e.jsx(Bs,{className:"w-5 h-5 lg:w-6 lg:h-6 text-[--re-green]"}),"Dealer Proposal Submission"]}),e.jsx(It,{className:"text-sm lg:text-base",children:"Step 1: Upload proposal and planning details"}),e.jsxs("div",{className:"space-y-1 mt-2 text-xs lg:text-sm text-gray-600",children:[e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Dealer:"})," ",r]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Activity:"})," ",n]})]}),e.jsx("div",{className:"mt-1",children:"Please upload proposal document, provide cost breakdown, timeline, and detailed comments."})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto overflow-x-hidden min-h-0 py-3 lg:py-4",children:[l&&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:()=>P(!N),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(Pe,{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(ne,{variant:"secondary",className:"bg-amber-200 text-amber-800 text-[10px]",children:["₹",Number(l.totalEstimatedBudget||l.totalBudget||0).toLocaleString("en-IN")]})]}),e.jsx(F,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-amber-700",children:N?e.jsx(vo,{className:"w-4 h-4"}):e.jsx(vs,{className:"w-4 h-4"})})]}),N&&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:[l.expectedCompletionDate&&e.jsxs("div",{className:"flex items-center gap-1.5 text-gray-700",children:[e.jsx(it,{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(l.expectedCompletionDate).toLocaleDateString("en-IN")})]}),l.documentUrl&&e.jsx("div",{className:"flex items-center gap-1.5",children:E(l.documentUrl)?e.jsxs(e.Fragment,{children:[e.jsx(ht,{className:"w-3.5 h-3.5 text-blue-500"}),e.jsx("a",{href:l.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(Nt,{className:"w-3.5 h-3.5 text-blue-500"}),e.jsx("a",{href:l.documentUrl,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline font-medium flex items-center gap-1",children:"Download Previous Document"})]})}),l.otherDocuments&&l.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(Pe,{className:"w-3 h-3"}),"Supporting Documents"]}),e.jsx("div",{className:"space-y-2 max-h-[150px] overflow-y-auto",children:l.otherDocuments.map((G,ie)=>e.jsx(Ur,{document:{documentId:G.documentId||G.id||"",name:G.originalFileName||G.fileName||G.name||"Supporting Document",fileType:(G.originalFileName||G.fileName||G.name||"").split(".").pop()||"file",uploadedAt:G.uploadedAt||new Date().toISOString()},onPreview:E(G.originalFileName||G.fileName||G.name||"")?()=>C(G):void 0,onDownload:async me=>{if(me)await bs(me);else{let Te=G.storageUrl||G.documentUrl;if(Te&&!Te.startsWith("http")){const Se="https://re-workflow-nt-dev.siplsolutions.com",re=Se.endsWith("/")?Se.slice(0,-1):Se,pe=Te.startsWith("/")?Te:`/${Te}`;Te=`${re}${pe}`}Te&&window.open(Te,"_blank")}}},ie))})]})]}),(l.costItems||l.costBreakup)&&(l.costItems||l.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:"Amount"})]})}),e.jsxs("tbody",{className:"divide-y",children:[(l.costItems||l.costBreakup).map((G,ie)=>e.jsxs("tr",{className:"bg-white",children:[e.jsx("td",{className:"p-2 text-gray-800",children:G.description}),e.jsxs("td",{className:"p-2 text-right text-gray-800 font-medium",children:["₹",Number(G.amount).toLocaleString("en-IN")]})]},ie)),e.jsxs("tr",{className:"bg-gray-50 font-bold",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(l.totalEstimatedBudget||l.totalBudget||0).toLocaleString("en-IN")]})]})]})]})})]}),(l.comments||l.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:['"',l.comments||l.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 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(ne,{variant:"outline",className:"text-xs border-red-500 text-red-700 bg-red-50 font-medium",children:"Required"})]}),e.jsxs("div",{children:[e.jsx(le,{className:"text-sm lg:text-base font-semibold flex items-center gap-2",children:"Proposal Document *"}),e.jsx("p",{className:"text-xs lg:text-sm text-gray-600 mb-2",children:"Detailed proposal with activity details and requested information"}),e.jsxs("div",{className:`border-2 border-dashed rounded-lg p-3 lg:p-4 transition-all duration-200 ${d?"border-green-500 bg-green-50 hover:border-green-600":"border-gray-300 hover:border-blue-500 bg-white"}`,children:[e.jsx("input",{ref:R,type:"file",accept:[".pdf",".doc",".docx"].filter(G=>o.allowedFileTypes.includes(G.replace(".",""))).join(","),className:"hidden",id:"proposalDoc",onChange:_}),e.jsx("label",{htmlFor:"proposalDoc",className:"cursor-pointer flex flex-col items-center gap-2",children:d?e.jsxs("div",{className:"flex flex-col items-center gap-2 w-full",children:[e.jsx(Ts,{className:"w-8 h-8 text-green-600"}),e.jsxs("div",{className:"flex flex-col items-center gap-1 w-full max-w-full px-2",children:[e.jsx("span",{className:"text-sm font-semibold text-green-700 break-words text-center w-full max-w-full",children:d.name}),e.jsx("span",{className:"text-xs text-green-600 mb-2",children:"Document selected"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[M(d)&&e.jsxs(F,{type:"button",variant:"outline",size:"sm",onClick:()=>B(d),className:"h-8 text-xs",children:[e.jsx(ht,{className:"w-3.5 h-3.5 mr-1"}),"Preview"]}),e.jsxs(F,{type:"button",variant:"outline",size:"sm",onClick:()=>j(d),className:"h-8 text-xs",children:[e.jsx(Nt,{className:"w-3.5 h-3.5 mr-1"}),"Download"]})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Bs,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600",children:"Click to upload proposal (PDF, DOC, DOCX)"})]})})]})]})]}),e.jsxs("div",{className:"space-y-2 lg:space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-base lg:text-lg",children:"Other Supporting Documents"}),e.jsx(ne,{variant:"outline",className:"text-xs border-gray-300 text-gray-600 bg-gray-50 font-medium",children:"Optional"})]}),e.jsxs("div",{children:[e.jsx(le,{className:"flex items-center gap-2 text-sm lg:text-base font-semibold",children:"Additional Documents"}),e.jsx("p",{className:"text-xs lg:text-sm text-gray-600 mb-2",children:"Any other supporting documents (invoices, receipts, photos, etc.)"}),e.jsxs("div",{className:`border-2 border-dashed rounded-lg p-3 lg:p-4 transition-all duration-200 ${v.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:O,type:"file",multiple:!0,accept:o.allowedFileTypes.map(G=>`.${G}`).join(","),className:"hidden",id:"otherDocs",onChange:se}),e.jsx("label",{htmlFor:"otherDocs",className:"cursor-pointer flex flex-col items-center gap-2",children:v.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Ts,{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:[v.length," document",v.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(Bs,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600 text-center",children:"Click to upload additional documents"}),e.jsxs("span",{className:"text-[10px] text-gray-400",children:["Max ",o.maxFileSizeMB,"MB | ",o.allowedFileTypes.join(", ").toUpperCase()]})]})})]}),v.length>0&&e.jsxs("div",{className:"mt-2 lg:mt-3 space-y-2 max-h-[150px] lg:max-h-[140px] overflow-y-auto",children:[e.jsxs("p",{className:"text-xs font-medium text-gray-600 mb-1",children:["Selected Documents (",v.length,"):"]}),v.map((G,ie)=>e.jsxs("div",{className:"flex items-start justify-between bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 p-2 lg:p-3 rounded-lg text-xs lg:text-sm shadow-sm hover:shadow-md transition-shadow w-full",children:[e.jsxs("div",{className:"flex items-start gap-2 flex-1 min-w-0 pr-2",children:[e.jsx(Pe,{className:"w-4 h-4 text-blue-600 flex-shrink-0 mt-0.5"}),e.jsx("span",{className:"text-gray-800 font-medium break-words break-all",children:G.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[M(G)&&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:()=>B(G),title:"Preview file",children:e.jsx(ht,{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:()=>j(G),title:"Download file",children:e.jsx(Nt,{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:()=>I(ie),title:"Remove document",children:e.jsx(ft,{className:"w-4 h-4"})})]})]},ie))]})]})]})]}),e.jsxs("div",{className:"space-y-4 lg:space-y-4 flex flex-col",children:[e.jsxs("div",{className:"space-y-2 lg:space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-base lg:text-lg",children:"Cost Breakup"}),e.jsx(ne,{variant:"outline",className:"text-xs border-red-500 text-red-700 bg-red-50 font-medium",children:"Required"})]}),e.jsxs(F,{type:"button",onClick:W,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white",size:"sm",children:[e.jsx(vs,{className:"w-3 h-3 lg:w-4 lg:h-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Add Item"}),e.jsx("span",{className:"sm:hidden",children:"Add"})]})]}),e.jsx("div",{className:"space-y-2 lg:space-y-2 max-h-[200px] lg:max-h-[180px] overflow-y-auto",children:m.map(G=>e.jsxs("div",{className:"flex gap-2 items-start w-full",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(_e,{placeholder:"Item description (e.g., Banner printing, Event setup)",value:G.description,onChange:ie=>Z(G.id,"description",ie.target.value),className:"w-full"})}),e.jsx("div",{className:"w-32 lg:w-36 flex-shrink-0",children:e.jsx(_e,{type:"number",placeholder:"Amount",min:"0",step:"0.01",value:G.amount||"",onChange:ie=>Z(G.id,"amount",ie.target.value),className:"w-full"})}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",className:"mt-0.5 hover:bg-red-100 hover:text-red-700 flex-shrink-0",onClick:()=>ce(G.id),disabled:m.length===1,children:e.jsx(ft,{className:"w-4 h-4"})})]},G.id))}),e.jsx("div",{className:"border-2 border-gray-300 rounded-lg p-3 lg:p-4 bg-white",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"w-4 h-4 lg:w-5 lg:h-5 text-gray-700"}),e.jsx("span",{className:"font-semibold text-sm lg:text-base text-gray-900",children:"Estimated Budget"})]}),e.jsxs("div",{className:"text-xl lg:text-2xl font-bold text-gray-900",children:["₹",U.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})})]}),e.jsxs("div",{className:"space-y-2 lg:space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-base lg:text-lg",children:"Timeline for Closure"}),e.jsx(ne,{variant:"outline",className:"text-xs border-red-500 text-red-700 bg-red-50 font-medium",children:"Required"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(F,{type:"button",onClick:()=>p("date"),className:x==="date"?"bg-[#2d4a3e] hover:bg-[#1f3329] text-white":"border-2 hover:bg-gray-50",size:"sm",children:[e.jsx(it,{className:"w-4 h-4 mr-1"}),"Specific Date"]}),e.jsx(F,{type:"button",onClick:()=>p("days"),className:x==="days"?"bg-[#2d4a3e] hover:bg-[#1f3329] text-white":"border-2 hover:bg-gray-50",size:"sm",children:"Number of Days"})]}),x==="date"?e.jsxs("div",{className:"w-full",children:[e.jsx(le,{className:"text-xs lg:text-sm font-medium mb-1.5 lg:mb-2 block",children:"Expected Completion Date"}),e.jsx($s,{value:g||null,onChange:G=>y(G||""),minDate:Y,placeholderText:"dd/mm/yyyy",className:"w-full"})]}):e.jsxs("div",{className:"w-full",children:[e.jsx(le,{className:"text-xs lg:text-sm font-medium mb-1.5 lg:mb-2 block",children:"Number of Days"}),e.jsx(_e,{type:"number",placeholder:"Enter number of days",min:"1",value:f,onChange:G=>b(G.target.value),className:"h-9 lg:h-10 w-full"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{htmlFor:"dealerComments",className:"text-sm lg:text-base font-semibold flex items-center gap-2",children:"Dealer Comments / Details *"}),e.jsx(Es,{id:"dealerComments",placeholder:"Provide detailed comments about this claim request, including any special considerations, execution details, or additional information...",value:w,onChange:G=>T(G.target.value),className:"min-h-[80px] lg:min-h-[100px] text-sm w-full"}),e.jsxs("p",{className:"text-xs text-gray-500",children:[w.length," characters"]})]})]}),!$&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-3 lg:p-4 flex items-start gap-2 lg:gap-3 lg:col-span-2",children:[e.jsx(Ge,{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(Tt,{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:X,disabled:k,className:"border-2",children:"Cancel"}),e.jsx(F,{onClick:V,disabled:!$||k,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white disabled:bg-gray-300 disabled:text-gray-500",children:k?"Submitting...":"Submit Documents"})]})]}),D&&e.jsx(Xr,{fileName:D.fileName,fileType:D.fileType,fileUrl:D.fileUrl,fileSize:D.fileSize,attachmentId:D.documentId,onDownload:bs,open:!!D,onClose:()=>S(null)})]})}function FS({isOpen:t,onClose:s,onApprove:a,onReject:r,requestTitle:n,requestId:i,preFilledIONumber:l,preFilledBlockedAmount:o,preFilledRemainingBalance:d}){const[c,m]=h.useState("approve"),[u,x]=h.useState(""),[p,g]=h.useState(!1),y=l||"";h.useEffect(()=>{t&&(x(""),m("approve"))},[t]);const f=u.length,b=500,v=h.useMemo(()=>(c==="reject"||y.trim().length>0)&&u.trim().length>0,[c,y,u]),A=async()=>{if(!v){if(c==="approve"&&!y.trim()){Q.error("IO number is required. Please block amount from IO tab first.");return}if(!u.trim()){Q.error("Please provide comments");return}return}try{g(!0),c==="approve"?await a({ioNumber:y.trim(),comments:u.trim()}):await r(u.trim()),w(),s()}catch(k){console.error(`Failed to ${c} request:`,k),Q.error(`Failed to ${c} request. Please try again.`)}finally{g(!1)}},w=()=>{m("approve"),x("")},T=()=>{p||(w(),s())};return e.jsx(mt,{open:t,onOpenChange:T,children:e.jsxs(ot,{className:"dept-lead-io-modal overflow-hidden flex flex-col",children:[e.jsxs(ut,{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(De,{className:"w-5 h-5 lg:w-6 lg:h-6 text-green-600"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ct,{className:"font-semibold text-lg lg:text-xl",children:"Review and Approve"}),e.jsx(It,{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(ne,{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(ne,{className:"bg-green-100 text-green-800 border-green-200 text-xs",children:[e.jsx(De,{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:()=>m("approve"),className:`flex-1 text-sm lg:text-base ${c==="approve"?"bg-green-600 text-white shadow-sm":"text-gray-700 hover:bg-gray-200"}`,variant:c==="approve"?"default":"ghost",children:[e.jsx(De,{className:"w-4 h-4 mr-1"}),"Approve"]}),e.jsxs(F,{type:"button",onClick:()=>m("reject"),className:`flex-1 text-sm lg:text-base ${c==="reject"?"bg-red-600 text-white shadow-sm":"text-gray-700 hover:bg-gray-200"}`,variant:c==="reject"?"destructive":"ghost",children:[e.jsx(jt,{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:[c==="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(ls,{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(le,{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(_e,{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})]})]})}),d!=null&&e.jsx("div",{className:"p-2 bg-blue-50 border border-blue-200 rounded",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-xs font-semibold text-gray-700",children:"Remaining Balance:"}),e.jsxs("span",{className:"text-xs lg:text-sm font-bold text-blue-700 mt-1",children:["₹",d.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})})]})]}),e.jsxs("div",{className:`space-y-1.5 ${c==="approve"?"":"lg:col-span-2"}`,children:[e.jsxs(le,{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(Es,{id:"comment",placeholder:c==="approve"?"Enter your approval comments and any conditions or notes...":"Enter detailed reasons for rejection...",value:u,onChange:k=>{const L=k.target.value;L.length<=b&&x(L)},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:[f,"/",b]})]})]})]})]})}),e.jsxs(Tt,{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:T,disabled:p,className:"text-sm lg:text-base",children:"Cancel"}),e.jsx(F,{onClick:A,disabled:!v||p,className:`text-sm lg:text-base ${c==="approve"?"bg-green-600 hover:bg-green-700":"bg-red-600 hover:bg-red-700"} text-white`,children:p?`${c==="approve"?"Approving":"Rejecting"}...`:e.jsxs(e.Fragment,{children:[e.jsx(De,{className:"w-4 h-4 mr-2"}),c==="approve"?"Approve Request":"Reject Request"]})})]})]})})}function MS({isOpen:t,onClose:s,onPush:a,completionDetails:r,ioDetails:n,completionDocuments:i,requestTitle:l,requestNumber:o}){var N,P;const[d,c]=h.useState(""),[m,u]=h.useState(!1),[x,p]=h.useState(null),[g,y]=h.useState(!1),f=d.length,b=500,v=h.useMemo(()=>r!=null&&r.totalClosedExpenses?r.totalClosedExpenses:r!=null&&r.closedExpenses&&Array.isArray(r.closedExpenses)?r.closedExpenses.reduce((R,O)=>{const E=typeof O=="object"&&O.amount||0;return R+(Number(E)||0)},0):0,[r]),A=R=>{if(!R)return"—";try{return new Date(R).toLocaleDateString("en-IN",{year:"numeric",month:"long",day:"numeric"})}catch{return R}},w=R=>`₹${R.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,T=R=>{if(!R.name)return!1;const O=R.name.toLowerCase();return O.endsWith(".pdf")||O.endsWith(".jpg")||O.endsWith(".jpeg")||O.endsWith(".png")||O.endsWith(".gif")||O.endsWith(".webp")},k=async R=>{if(!R.id){Q.error("Document preview not available - document ID missing");return}y(!0);try{const O=Gr(R.id),E=R.name.toLowerCase(),M=E.endsWith(".pdf"),B=E.match(/\.(jpg|jpeg|png|gif|webp)$/i),C=!0,j=C?null:localStorage.getItem("accessToken"),$=await fetch(O,{headers:{Accept:M?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!$.ok)throw new Error(`Failed to load file: ${$.status} ${$.statusText}`);const _=await $.blob();if(_.size===0)throw new Error("File is empty or could not be loaded");const se=window.URL.createObjectURL(_);p({name:R.name,url:se,type:_.type||(M?"application/pdf":B?"image":void 0),size:_.size})}catch(O){console.error("Failed to load document preview:",O),Q.error("Failed to load document preview")}finally{y(!1)}};h.useEffect(()=>()=>{x!=null&&x.url&&x.url.startsWith("blob:")&&window.URL.revokeObjectURL(x.url)},[x]);const L=async()=>{if(!d.trim()){Q.error("Please provide comments before pushing to DMS");return}try{u(!0),await a(d.trim()),D(),s()}catch(R){console.error("Failed to push to DMS:",R),Q.error("Failed to push to DMS. Please try again.")}finally{u(!1)}},D=()=>{c("")},S=()=>{m||(D(),s())};return e.jsxs(mt,{open:t,onOpenChange:S,children:[e.jsxs(ot,{className:"dms-push-modal overflow-hidden flex flex-col",children:[e.jsxs(ut,{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(Dt,{className:"w-4 h-4 sm:w-5 sm:h-5 sm:w-6 sm:h-6 text-indigo-600"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ct,{className:"font-semibold text-lg sm:text-xl",children:"Push to DMS - Verification"}),e.jsx(It,{className:"text-xs sm:text-sm mt-1",children:"Review completion details and expenses before pushing to DMS for e-invoice generation"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4 p-3 sm:p-4 bg-gray-50 rounded-lg border",children:[e.jsxs("div",{className:"flex items-center justify-between sm:flex-col sm:items-start sm:gap-1",children:[e.jsx("span",{className:"font-medium text-xs sm:text-sm text-gray-600",children:"Workflow Step:"}),e.jsx(ne,{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(ne,{className:"bg-indigo-100 text-indigo-800 border-indigo-200 text-xs",children:[e.jsx(Dt,{className:"w-3 h-3 mr-1"}),"PUSH TO DMS"]})]})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto overflow-x-hidden px-6 py-3",children:e.jsxs("div",{className:"space-y-3 sm:space-y-4 max-w-7xl mx-auto",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6",children:[r&&e.jsxs(te,{children:[e.jsxs(ue,{className:"pb-3",children:[e.jsxs(xe,{className:"flex items-center gap-2 text-base sm:text-lg",children:[e.jsx(Ts,{className:"w-4 h-4 sm:w-5 sm:h-5 text-green-600"}),"Completion Details"]}),e.jsx(ke,{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(te,{children:[e.jsxs(ue,{className:"pb-3",children:[e.jsxs(xe,{className:"flex items-center gap-2 text-base sm:text-lg",children:[e.jsx(ls,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"IO Details"]}),e.jsx(ke,{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:w(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:w(n.remainingBalance)})]})]})]}),(r==null?void 0:r.closedExpenses)&&r.closedExpenses.length>0&&e.jsxs(te,{children:[e.jsxs(ue,{className:"pb-3",children:[e.jsxs(xe,{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(ke,{className:"text-xs sm:text-sm",children:"Review closed expenses before pushing to DMS"})]}),e.jsxs(ae,{children:[e.jsx("div",{className:"space-y-1.5 sm:space-y-2 max-h-[200px] overflow-y-auto",children:r.closedExpenses.map((R,O)=>e.jsxs("div",{className:"flex items-center justify-between py-1.5 sm:py-2 px-2 sm:px-3 bg-gray-50 rounded border",children:[e.jsx("div",{className:"flex-1 min-w-0 pr-2",children:e.jsx("p",{className:"text-xs sm:text-sm font-medium text-gray-900 truncate",children:R.description||`Expense ${O+1}`})}),e.jsx("div",{className:"ml-2 flex-shrink-0",children:e.jsx("p",{className:"text-xs sm:text-sm font-semibold text-gray-900",children:w(typeof R=="object"&&R.amount||0)})})]},O))}),e.jsxs("div",{className:"flex items-center justify-between py-2 sm:py-3 px-2 sm:px-3 bg-blue-50 rounded border-2 border-blue-200 mt-2 sm:mt-3",children:[e.jsx("span",{className:"text-xs sm:text-sm font-semibold text-gray-900",children:"Total:"}),e.jsx("span",{className:"text-sm sm:text-base font-bold text-blue-700",children:w(v)})]})]})]})]}),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(Ts,{className:"w-4 h-4 sm:w-5 sm:h-5 text-green-600"}),"Completion Documents"]}),e.jsxs(ne,{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((R,O)=>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(Ts,{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:R.name,children:R.name})})]}),R.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[T(R)&&e.jsx("button",{type:"button",onClick:()=>k(R),disabled:g,className:"p-2 hover:bg-gray-200 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Preview document",children:g?e.jsx(Ze,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600 animate-spin"}):e.jsx(ht,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{try{R.id&&await bs(R.id)}catch(E){console.error("Failed to download document:",E),Q.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(Nt,{className:"w-4 h-4 lg:w-5 lg:h-5 text-gray-600"})})]})]},O))})]}),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(Dt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Activity Photos"]}),e.jsxs(ne,{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((R,O)=>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(Dt,{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:R.name,children:R.name})})]}),R.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[T(R)&&e.jsx("button",{type:"button",onClick:()=>k(R),disabled:g,className:"p-2 hover:bg-gray-200 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Preview photo",children:g?e.jsx(Ze,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600 animate-spin"}):e.jsx(ht,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{try{R.id&&await bs(R.id)}catch(E){console.error("Failed to download document:",E),Q.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download photo",children:e.jsx(Nt,{className:"w-4 h-4 lg:w-5 lg:h-5 text-gray-600"})})]})]},O))})]}),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(ls,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"Invoices / Receipts"]}),e.jsxs(ne,{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((R,O)=>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(ls,{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:R.name,children:R.name})})]}),R.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[T(R)&&e.jsx("button",{type:"button",onClick:()=>k(R),disabled:g,className:"p-2 hover:bg-gray-200 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Preview document",children:g?e.jsx(Ze,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600 animate-spin"}):e.jsx(ht,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{try{R.id&&await bs(R.id)}catch(E){console.error("Failed to download document:",E),Q.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(Nt,{className:"w-4 h-4 lg:w-5 lg:h-5 text-gray-600"})})]})]},O))})]}),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(Dt,{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(Dt,{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:[T(i.attendanceSheet)&&e.jsx("button",{type:"button",onClick:()=>k(i.attendanceSheet),disabled:g,className:"p-2 hover:bg-gray-200 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Preview document",children:g?e.jsx(Ze,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600 animate-spin"}):e.jsx(ht,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{var R;try{(R=i.attendanceSheet)!=null&&R.id&&await bs(i.attendanceSheet.id)}catch(O){console.error("Failed to download document:",O),Q.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(Nt,{className:"w-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 pushing to DMS"}),e.jsx("p",{className:"text-xs text-yellow-700 mt-1",children:"Once pushed, the system will automatically generate an e-invoice and log it as an activity."})]})]})}),e.jsxs("div",{className:"space-y-1.5 max-w-2xl",children:[e.jsxs(le,{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(Es,{id:"comment",placeholder:"Enter your comments about pushing to DMS (e.g., verified expenses, ready for invoice generation)...",value:d,onChange:R=>{const O=R.target.value;O.length<=b&&c(O)},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:[f,"/",b]})]})]})]})}),e.jsxs(Tt,{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:S,disabled:m,children:"Cancel"}),e.jsx(F,{onClick:L,disabled:!d.trim()||m,className:"bg-indigo-600 hover:bg-indigo-700 text-white",children:m?"Pushing to DMS...":e.jsxs(e.Fragment,{children:[e.jsx(Dt,{className:"w-4 h-4 mr-2"}),"Push to DMS"]})})]})]}),x&&e.jsx(mt,{open:!!x,onOpenChange:()=>p(null),children:e.jsx(ot,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(ut,{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(ht,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(ct,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:x.name}),x.type&&e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[x.type," ",x.size&&`• ${(x.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 R=document.createElement("a");R.href=x.url,R.download=x.name,R.click()},className:"gap-2 h-9",children:[e.jsx(Nt,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Download"})]})})]})}),e.jsx("div",{className:"file-preview-body bg-gray-100 rounded-lg p-2 sm:p-4",children:g?e.jsx("div",{className:"flex items-center justify-center h-full min-h-[70vh]",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Ze,{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..."})]})}):x.name.toLowerCase().endsWith(".pdf")||(N=x.type)!=null&&N.includes("pdf")?e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("iframe",{src:x.url,className:"w-full h-full rounded-lg border-0",title:x.name,style:{minHeight:"70vh",height:"100%"}})}):x.name.match(/\.(jpg|jpeg|png|gif|webp)$/i)||(P=x.type)!=null&&P.includes("image")?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("img",{src:x.url,alt:x.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(ht,{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 R=document.createElement("a");R.href=x.url,R.download=x.name,R.click()},className:"gap-2",children:[e.jsx(Nt,{className:"h-4 w-4"}),"Download ",x.name]})]})})]})})})]})}function _S({isOpen:t,onClose:s,stepNumber:a,stepName:r,requestNumber:n="RE-REQ-2024-CM-101",recipientEmail:i="system@royalenfield.com",subject:l,emailBody:o}){const d=`System Notification: Activity Created - ${n}`,c=l||d,m=`System Notification
|
||
|
||
Activity has been automatically created for claim ${n}.
|
||
|
||
All stakeholders have been notified.
|
||
|
||
This is an automated message.`,u=o||m;return e.jsx(mt,{open:t,onOpenChange:s,children:e.jsxs(ot,{className:"sm:max-w-2xl lg:max-w-[1000px] max-w-2xl",children:[e.jsx(ut,{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(ct,{className:"text-lg leading-none font-semibold",children:"Email Notification Template"}),e.jsxs(It,{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(_t,{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:c})]})]})]})}),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(Ri,{className:"w-5 h-5 text-purple-600"}),e.jsx("span",{className:"font-semibold text-gray-900",children:"Royal Enfield"})]}),e.jsx("div",{className:"prose prose-sm max-w-none",children:e.jsx("pre",{className:"whitespace-pre-wrap font-sans text-sm text-gray-700 leading-relaxed bg-transparent p-0 border-0",children:u})}),e.jsx("div",{className:"pt-3 border-t border-gray-200",children:e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:[e.jsx(it,{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(ne,{className:"bg-blue-50 text-blue-700 border-blue-200",children:["Step ",a]}),e.jsx(ne,{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 LS({isOpen:t,onClose:s,onApprove:a,onReject:r,onRequestRevision:n,proposalData:i,dealerName:l="Dealer",activityName:o="Activity",requestId:d,request:c,previousProposalData:m}){const[u,x]=h.useState(""),[p,g]=h.useState(!1),[y,f]=h.useState(null),[b,v]=h.useState(!1),A=(c==null?void 0:c.internalOrder)||(c==null?void 0:c.internal_order),T=((A==null?void 0:A.ioBlockedAmount)||(A==null?void 0:A.io_blocked_amount)||0)>0,[k,L]=h.useState(null),D=h.useMemo(()=>{if(!(i!=null&&i.costBreakup))return 0;const C=Array.isArray(i.costBreakup)?i.costBreakup:typeof i.costBreakup=="string"?JSON.parse(i.costBreakup):[];return Array.isArray(C)?C.reduce((j,U)=>{const $=typeof U=="object"&&U.amount||0;return j+(Number($)||0)},0):0},[i]),S=C=>{if(!C)return"—";try{return new Date(C).toLocaleDateString("en-IN",{year:"numeric",month:"long",day:"numeric"})}catch{return C}},N=C=>{if(!C.name)return!1;const j=C.name.toLowerCase();return j.endsWith(".pdf")||j.endsWith(".jpg")||j.endsWith(".jpeg")||j.endsWith(".png")||j.endsWith(".gif")||j.endsWith(".webp")},P=C=>{let j=C.url||C.storageUrl||"";const U=C.id||C.documentId||"";if(!U&&!j){Q.error("Document preview not available");return}if(j&&!j.startsWith("http")&&!j.startsWith("blob:")){const $="https://re-workflow-nt-dev.siplsolutions.com",_=$.endsWith("/")?$.slice(0,-1):$,se=j.startsWith("/")?j:`/${j}`;j=`${_}${se}`}L({name:C.name||"Document",url:j||(U?Gr(U):""),type:(C.name||"").toLowerCase().endsWith(".pdf")?"application/pdf":"image/jpeg",id:U})};h.useEffect(()=>()=>{k!=null&&k.url&&k.url.startsWith("blob:")&&window.URL.revokeObjectURL(k.url)},[k]);const R=async()=>{if(!u.trim()){Q.error("Please provide approval comments");return}try{g(!0),f("approve"),await a(u),M(),s()}catch(C){console.error("Failed to approve proposal:",C),Q.error("Failed to approve proposal. Please try again.")}finally{g(!1),f(null)}},O=async()=>{if(!u.trim()){Q.error("Please provide rejection reason");return}try{g(!0),f("reject"),await r(u),M(),s()}catch(C){console.error("Failed to reject proposal:",C),Q.error("Failed to reject proposal. Please try again.")}finally{g(!1),f(null)}},E=async()=>{if(!u.trim()){Q.error("Please provide reasons for requesting a revision");return}if(!n){Q.error("Revision feature is not available");return}try{g(!0),f("revision"),await n(u),M(),s()}catch(C){console.error("Failed to request revision:",C),Q.error("Failed to request revision. Please try again.")}finally{g(!1),f(null)}},M=()=>{x(""),f(null)},B=()=>{p||(M(),s())};return t?e.jsxs(mt,{open:t,onOpenChange:B,children:[e.jsxs(ot,{className:"dealer-proposal-modal overflow-hidden flex flex-col",children:[e.jsxs(ut,{className:"flex-shrink-0 pb-3 lg:pb-4 px-6 pt-4 lg:pt-6 border-b",children:[e.jsxs(ct,{className:"flex items-center gap-2 text-lg lg:text-xl",children:[e.jsx(De,{className:"w-4 h-4 lg:w-5 lg:h-5 text-green-600"}),"Requestor Evaluation & Confirmation"]}),e.jsx(It,{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:()=>v(!b),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(Pe,{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(ne,{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:b?e.jsx(vo,{className:"w-4 h-4"}):e.jsx(vs,{className:"w-4 h-4"})})]}),b&&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(it,{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:N({name:m.documentUrl})?e.jsxs(e.Fragment,{children:[e.jsx(ht,{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(Nt,{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(Yn,{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((C,j)=>e.jsxs("tr",{className:"bg-white",children:[e.jsx("td",{className:"p-2 text-gray-800",children:C.description}),e.jsxs("td",{className:"p-2 text-right text-gray-800 font-medium",children:["₹",Number(C.amount).toLocaleString("en-IN")]})]},j)),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(Pe,{className:"w-3 h-3"}),"Supporting Documents"]}),e.jsx("div",{className:"space-y-2 max-h-[150px] overflow-y-auto",children:m.otherDocuments.map((C,j)=>e.jsx(Ur,{document:{documentId:C.documentId||C.id||"",name:C.originalFileName||C.fileName||C.name||"Supporting Document",fileType:(C.originalFileName||C.fileName||C.name||"").split(".").pop()||"file",uploadedAt:C.uploadedAt||new Date().toISOString()},onPreview:N({name:C.originalFileName||C.fileName||C.name||""})?()=>P(C):void 0,onDownload:async U=>{if(U)await bs(U);else{let $=C.storageUrl||C.documentUrl;if($&&!$.startsWith("http")){const _="https://re-workflow-nt-dev.siplsolutions.com",se=_.endsWith("/")?_.slice(0,-1):_,W=$.startsWith("/")?$:`/${$}`;$=`${se}${W}`}$&&window.open($,"_blank")}}},j))})]}),(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(Pe,{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(Pe,{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 ",S(i.submittedAt)]})]})]}),e.jsx("div",{className:"flex items-center gap-2 flex-shrink-0",children:i.proposalDocument.id&&e.jsxs(e.Fragment,{children:[N(i.proposalDocument)&&e.jsx("button",{type:"button",onClick:()=>P(i.proposalDocument),className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Preview document",children:e.jsx(ht,{className:"w-5 h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{var C;try{(C=i.proposalDocument)!=null&&C.id&&await bs(i.proposalDocument.id)}catch(j){console.error("Failed to download document:",j),Q.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(Nt,{className:"w-5 h-5 text-gray-600"})})]})})]}):e.jsx("p",{className:"text-xs text-gray-500 italic",children:"No proposal document available"})]}),(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(Pe,{className:"w-4 h-4 text-gray-600"}),"Other Supporting Documents"]}),e.jsxs(ne,{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((C,j)=>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(Pe,{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:C.name,children:C.name})]}),C.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[N(C)&&e.jsx("button",{type:"button",onClick:()=>P(C),className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Preview document",children:e.jsx(ht,{className:"w-5 h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{try{C.id&&await bs(C.id)}catch(U){console.error("Failed to download document:",U),Q.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(Nt,{className:"w-5 h-5 text-gray-600"})})]})]},j))})]})]}),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(Yn,{className:"w-4 h-4 text-green-600"}),"Cost Breakup"]})}),(()=>{const C=i!=null&&i.costBreakup?Array.isArray(i.costBreakup)?i.costBreakup:typeof i.costBreakup=="string"?JSON.parse(i.costBreakup):[]:[];return C&&Array.isArray(C)&&C.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"border rounded-lg overflow-hidden max-h-[200px] lg:max-h-[180px] overflow-y-auto",children:[e.jsx("div",{className:"bg-gray-50 px-3 lg:px-4 py-2 border-b sticky top-0",children:e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-xs lg:text-sm font-semibold text-gray-700",children:[e.jsx("div",{children:"Item Description"}),e.jsx("div",{className:"text-right",children:"Amount"})]})}),e.jsx("div",{className:"divide-y",children:C.map((j,U)=>e.jsxs("div",{className:"px-3 lg:px-4 py-2 lg:py-3 grid grid-cols-2 gap-4",children:[e.jsx("div",{className:"text-xs lg:text-sm text-gray-700",children:(j==null?void 0:j.description)||"N/A"}),e.jsxs("div",{className:"text-xs lg:text-sm font-semibold text-gray-900 text-right",children:["₹",(Number(j==null?void 0:j.amount)||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]},(j==null?void 0:j.id)||(j==null?void 0:j.description)||U))})]}),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(Yn,{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:["₹",D.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(it,{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?S(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(Es,{placeholder:"Provide your evaluation comments, approval conditions, or rejection reasons...",value:u,onChange:C=>x(C.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(jt,{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(Tt,{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:B,disabled:p,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:E,disabled:!u.trim()||p,variant:"secondary",className:"bg-amber-100 hover:bg-amber-200 text-amber-900 border border-amber-200 w-full sm:w-auto",children:p&&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:O,disabled:!u.trim()||p,variant:"destructive",className:"bg-red-600 hover:bg-red-700 w-full sm:w-auto",children:p&&y==="reject"?"Rejecting...":e.jsxs(e.Fragment,{children:[e.jsx(jt,{className:"w-4 h-4 mr-2"}),"Reject (Cancel Request)"]})}),e.jsx(F,{onClick:R,disabled:!u.trim()||!T||p,className:"bg-green-600 hover:bg-green-700 text-white disabled:opacity-50 disabled:cursor-not-allowed w-full sm:w-auto",title:T?"":"Please block IO budget before approving",children:p&&y==="approve"?"Approving...":e.jsxs(e.Fragment,{children:[e.jsx(De,{className:"w-4 h-4 mr-2"}),"Approve (Continue to Dept Lead)"]})})]}),!T&&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"})]})]})]}),k&&e.jsx(Xr,{fileName:k.name,fileType:k.type||"",fileUrl:k.url,fileSize:k.size,attachmentId:k.id,onDownload:bs,open:!!k,onClose:()=>L(null)})]}):null}function OS({isOpen:t,onClose:s,snapshot:a,type:r,title:n}){const[i,l]=h.useState(null);if(!a)return null;const o=r==="PROPOSAL",d=p=>Number(p||0).toLocaleString("en-IN",{maximumFractionDigits:2,style:"currency",currency:"INR"}),c=p=>{if(!p)return null;try{return new Date(p).toLocaleDateString("en-IN",{day:"numeric",month:"short",year:"numeric"})}catch{return p}},m=p=>{if(!p)return!1;const g=p.toLowerCase();return g.endsWith(".pdf")||!!g.match(/\.(jpg|jpeg|png|gif|webp)$/i)},u=p=>{var y;const g=(y=(p||"").split(".").pop())==null?void 0:y.toLowerCase();return g==="pdf"?"pdf":["jpg","jpeg","png","gif","webp"].includes(g||"")?"image":"file"},x=p=>{const g=p.fileName||p.originalFileName||(o?"Proposal Document":"Completion Document"),y=p.documentId||"",f=g.toLowerCase().endsWith(".pdf")?"application/pdf":"image/jpeg";let b="";if(y)b=Gr(y);else if(b=p.storageUrl||p.documentUrl||"",b&&!b.startsWith("http")){const v="https://re-workflow-nt-dev.siplsolutions.com",A=v.endsWith("/")?v.slice(0,-1):v,w=b.startsWith("/")?b:`/${b}`;b=`${A}${w}`}l({fileName:g,fileType:f,documentId:y,fileUrl:b,fileSize:p.sizeBytes})};return e.jsxs(e.Fragment,{children:[e.jsx(mt,{open:t,onOpenChange:s,children:e.jsxs(ot,{className:"max-w-2xl max-h-[90vh] flex flex-col p-0 gap-0 overflow-hidden",children:[e.jsxs(ut,{className:"px-6 py-4 border-b",children:[e.jsxs(ct,{className:"flex items-center gap-2",children:[o?e.jsx(Pe,{className:"w-5 h-5 text-blue-600"}):e.jsx(ls,{className:"w-5 h-5 text-green-600"}),n||(o?"Proposal Snapshot Details":"Completion Snapshot Details")]}),e.jsxs(It,{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:d(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(it,{className:"w-3 h-3"}),"Expected Completion"]}),e.jsx("p",{className:"text-sm font-semibold text-gray-700",children:c(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(Ur,{document:{documentId:"",name:o?"Proposal Document":"Completion Document",fileType:u(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 p=a.documentUrl;if(!p.startsWith("http")){const g="https://re-workflow-nt-dev.siplsolutions.com",y=g.endsWith("/")?g.slice(0,-1):g,f=p.startsWith("/")?p:`/${p}`;p=`${y}${f}`}window.open(p,"_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(ne,{variant:"secondary",className:"text-[10px] h-5",children:[a.otherDocuments.length," Files"]})]}),e.jsx("div",{className:"space-y-2",children:a.otherDocuments.map((p,g)=>e.jsx(Ur,{document:{documentId:p.documentId||"",name:p.originalFileName||p.fileName||"Supporting Document",fileType:u(p.originalFileName||p.fileName||""),uploadedAt:p.uploadedAt||new Date().toISOString()},onPreview:m(p.originalFileName||p.fileName||"")?()=>x(p):void 0,onDownload:p.documentId?bs:async()=>{let y=p.storageUrl||p.documentUrl;if(y&&!y.startsWith("http")){const f="https://re-workflow-nt-dev.siplsolutions.com",b=f.endsWith("/")?f.slice(0,-1):f,v=y.startsWith("/")?y:`/${y}`;y=`${b}${v}`}y&&window.open(y,"_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((p,g)=>e.jsxs("tr",{className:"bg-white hover:bg-gray-50/50",children:[e.jsx("td",{className:"p-3 text-gray-800",children:p.description}),e.jsx("td",{className:"p-3 text-right text-gray-900 font-medium tabular-nums",children:d(p.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:d(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(qu,{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(Xr,{fileName:i.fileName,fileType:i.fileType,fileUrl:i.fileUrl,fileSize:i.fileSize,attachmentId:i.documentId,onDownload:bs,open:!!i,onClose:()=>l(null)})]})}async function $S(t){var s;try{const a=await Ne.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 US(t){var s;try{const a=await Ne.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 BS(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 Ne.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 VS(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 Ne.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 zS(t,s){var a;try{const r=await Ne.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 Ne.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 HS(t,s){var a;try{const r=await Ne.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 WS(t){var s;try{const a=await Ne.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 GS(t,s,a){var r;try{const n={};t&&(n.dateRange=t),s&&(n.startDate=s),a&&(n.endDate=a);const i=await Ne.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 Cr=t=>{if(!t)return"";try{return is(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}}},KS=t=>{switch(t){case"approved":return e.jsx(De,{className:"w-5 h-5 text-green-600"});case"pending":return e.jsx(Xe,{className:"w-5 h-5 text-blue-600"});case"rejected":return e.jsx(De,{className:"w-5 h-5 text-red-600"});default:return e.jsx(Xe,{className:"w-5 h-5 text-gray-400"})}},YS=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"}},ZS=(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",XS=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 QS({request:t,user:s,isInitiator:a,onSkipApprover:r,onRefresh:n,documentPolicy:i}){var ga,fa,Ma,Ca,wt,Aa,Ja,qa,er,tr,sr,ar,_a,ya,La,Ft,ms,Vs,rr,nr,ca,bt,us,Ms,ea,Nr,da,Oa,Qr,Jr,qr,Sc,Tc,kc,Rc,Dc,Pc,Ic,Ec,Fc,Mc,_c,Lc,Oc,$c,Uc,Bc,Vc,zc,Hc,Wc,Gc,Kc,Yc,Zc,Xc,Qc,Jc,qc,ed,td,sd,ad,rd,nd,id,ld,od,cd,dd,md,ud,xd,hd,pd,gd,fd,yd,bd,vd,jd,Nd,wd,Cd,Ad,Sd,Td,kd,Rd,Dd,Pd,Id;const[l,o]=h.useState(!1),[d,c]=h.useState(!1),[m,u]=h.useState(!1),[x,p]=h.useState(!1),[g,y]=h.useState(!1),[f,b]=h.useState(!1),[v,A]=h.useState(!1),[w,T]=h.useState(null),[k,L]=h.useState(!1),[D,S]=h.useState(null),[N,P]=h.useState([]),[R,O]=h.useState(!1),[E,M]=h.useState(new Set),[B,C]=h.useState(null),[j,U]=h.useState([]),[$,_]=h.useState(0);h.useEffect(()=>{(async()=>{if(t!=null&&t.id||t!=null&&t.requestId){const Ie=t.id||t.requestId;try{const ge=await ws(Ie),oe=(ge==null?void 0:ge.approvalLevels)||(ge==null?void 0:ge.approvals)||[];if(oe&&oe.length>0){const fe=oe.map(he=>{var Ce;return{step:he.levelNumber||he.level_number||0,levelNumber:he.levelNumber||he.level_number||0,levelName:he.levelName||he.level_name,approver:he.approverName||he.approver_name||"",approverEmail:(he.approverEmail||he.approver_email||"").toLowerCase(),status:((Ce=he.status)==null?void 0:Ce.toLowerCase())||"waiting",tatHours:he.tatHours||he.tat_hours||24,elapsedHours:he.elapsedHours||he.elapsed_hours,approvedAt:he.actionDate||he.action_date,comment:he.comments||he.comment,levelId:he.levelId||he.level_id}}).sort((he,Ce)=>(he.levelNumber||0)-(Ce.levelNumber||0));U(he=>he.length!==fe.length||he.some((Ue,ye)=>{const pt=fe[ye];return!pt||Ue.levelNumber!==pt.levelNumber||Ue.levelName!==pt.levelName||Ue.approverEmail!==pt.approverEmail||Ue.status!==pt.status})?fe:he)}else U([])}catch(ge){console.warn("Failed to load approval flows from API:",ge),t!=null&&t.approvalFlow&&t.approvalFlow.length>0&&U(t.approvalFlow)}}else t!=null&&t.approvalFlow&&t.approvalFlow.length>0&&U(t.approvalFlow)})()},[t==null?void 0:t.id,t==null?void 0:t.requestId,t==null?void 0:t.totalLevels,$]),h.useEffect(()=>{if(t!=null&&t.id||t!=null&&t.requestId){const H=t.id||t.requestId;(async()=>{try{const ge=await ws(H),oe=(ge==null?void 0:ge.approvalLevels)||(ge==null?void 0:ge.approvals)||[];if(oe&&oe.length>0){const fe=oe.map(he=>{var Ce;return{step:he.levelNumber||he.level_number||0,levelNumber:he.levelNumber||he.level_number||0,levelName:he.levelName||he.level_name,approver:he.approverName||he.approver_name||"",approverEmail:(he.approverEmail||he.approver_email||"").toLowerCase(),status:((Ce=he.status)==null?void 0:Ce.toLowerCase())||"waiting",tatHours:he.tatHours||he.tat_hours||24,elapsedHours:he.elapsedHours||he.elapsed_hours,approvedAt:he.actionDate||he.action_date,comment:he.comments||he.comment,levelId:he.levelId||he.level_id}}).sort((he,Ce)=>(he.levelNumber||0)-(Ce.levelNumber||0));U(fe)}}catch(ge){console.warn("Failed to load approval flows from API:",ge)}})()}},[t==null?void 0:t.currentStep,t==null?void 0:t.totalLevels]);const se=async()=>{_(H=>H+1),await new Promise(H=>setTimeout(H,500)),n==null||n(),W()},W=async()=>{if(t!=null&&t.id||t!=null&&t.requestId)try{const Ie=[...await rN(t.id||t.requestId)||[]].sort((ge,oe)=>new Date(oe.createdAt).getTime()-new Date(ge.createdAt).getTime());P(Ie)}catch(H){console.warn("Failed to load version history:",H)}};h.useEffect(()=>{W()},[t==null?void 0:t.id,t==null?void 0:t.requestId,$]);const ce=(H,Ie,ge)=>{if(Ie&&Ie.trim())return Ie.toLowerCase().includes("additional approver"),Ie;const oe={1:"Dealer - Proposal Submission",2:"Requestor Evaluation & Confirmation",3:"Department Lead Approval",4:"Activity Creation",5:"Dealer - Completion Documents",6:"Requestor - Claim Approval",7:"E-Invoice Generation",8:"Credit Note from SAP"};return oe[H]?oe[H]:ge&&ge!=="Unknown"&&ge!=="System"?`Additional Approver - ${ge}`:`Additional Approver - Step ${H}`},Z=(H,Ie,ge)=>{if(Ie&&Ie.toLowerCase().includes("additional approver"))return ge&&ge!=="Unknown"&&ge!=="System"?`${ge} will review and approve this request as an additional approver.`:"Additional approver will review and approve this request.";if(Ie&&Ie.trim()){const he=Ie.toLowerCase();if(he.includes("dealer")&&he.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(he.includes("requestor")&&(he.includes("evaluation")||he.includes("confirmation")))return"Requestor evaluates the request and confirms with comments. Decision point: Confirms? (YES → Continue to Dept Lead / NO → Request is cancelled)";if(he.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(he.includes("activity creation"))return"Activity is created. Activity confirmation email is auto-triggered to dealer / requestor / Lead. IO confirmation to be made.";if(he.includes("dealer")&&(he.includes("completion")||he.includes("documents")))return"Dealer submits the necessary documents upon completion of the activity including document attachments (Zip Folder) and brief description";if(he.includes("requestor")&&(he.includes("claim")||he.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(he.includes("e-invoice")||he.includes("invoice generation"))return"E-invoice will be generated through DMS.";if(he.includes("credit note")||he.includes("sap"))return"Got credit note from SAP. Review and send to dealer to complete the claim management process."}const fe={1:"Dealer submits the proposal for the activity with comments including proposal document with requested details, cost break-up, timeline for closure, and other requests",2:"Requestor evaluates the request and confirms with comments. Decision point: Confirms? (YES → Continue to Dept Lead / NO → Request is cancelled)",3:"Department Lead approval. Decision point: Approved? (YES → Budget is blocked in the respective IO for the activity / NO → More clarification required → Request is cancelled)",4:"Activity is created. Activity confirmation email is auto-triggered to dealer / requestor / Lead. IO confirmation to be made.",5:"Dealer submits the necessary documents upon completion of the activity including document attachments (Zip Folder) and brief description",6:"Requestor approves the claim in full or can modify the amount. If more information is required, can request additional details from dealer.",7:"E-invoice will be generated through DMS.",8:"Got credit note from SAP. Review and send to dealer to complete the claim management process."};return fe[H]?fe[H]:ge&&ge!=="Unknown"&&ge!=="System"?`${ge} will review and approve this request.`:`Step ${H} approval required.`},I=H=>{if(!N||N.length===0||!H)return{current:null,previous:null};const oe=[...N.filter(Ce=>{var Ue;return!!(Ce.levelName&&Ce.levelName.trim()===H.trim()||(Ue=Ce.snapshotData)!=null&&Ue.levelName&&Ce.snapshotData.levelName.trim()===H.trim())})].sort((Ce,Ue)=>{if(Ue.version!==Ce.version)return Ue.version-Ce.version;const ye=Ce.snapshotType==="APPROVE"?1:Ce.snapshotType==="PROPOSAL"||Ce.snapshotType==="COMPLETION"?2:3,pt=Ue.snapshotType==="APPROVE"?1:Ue.snapshotType==="PROPOSAL"||Ue.snapshotType==="COMPLETION"?2:3;return ye-pt}).filter((Ce,Ue,ye)=>Ce.snapshotType==="WORKFLOW"?!ye.some(dt=>dt.snapshotType==="APPROVE"&&dt.levelName===Ce.levelName&&dt.version>=Ce.version):!0),fe=oe.length>0?oe[0]:null,he=oe.length>1?oe[1]:null;return{current:fe,previous:he,all:oe}},V=(t==null?void 0:t.currentLevel)||(t==null?void 0:t.current_level)||(t==null?void 0:t.currentStep),z=V!=null?Number(V):null,X=((t==null?void 0:t.status)||"").toUpperCase(),Y=X==="REJECTED",G=X==="CLOSED",ie=!Y&&!G&&(X==="PENDING"||X==="IN_PROGRESS"||X==="IN-PROGRESS"),me=j.find(H=>{var oe,fe;const Ie=H.levelId||H.level_id,ge=(oe=t==null?void 0:t.approvals)==null?void 0:oe.find(he=>he.levelId===Ie);return((fe=ge==null?void 0:ge.status)==null?void 0:fe.toLowerCase())==="rejected"}),Te=me?Number(me.levelNumber||me.level_number||me.step||0):null,Se=j.map((H,Ie)=>{var ma,fs,de,Ot,Yt,hs,Qe;const ge=Number(H.levelNumber||H.level_number||H.step||Ie+1),oe=H.levelName||H.level_name,fe=(ma=t==null?void 0:t.approvals)==null?void 0:ma.find(Ae=>Ae.levelId===H.levelId);let he;if(oe&&oe.toLowerCase().includes("department lead")||ge===3){const Ae=(t==null?void 0:t.internalOrder)||(t==null?void 0:t.internal_order);(Ae!=null&&Ae.ioNumber||Ae!=null&&Ae.io_number)&&(he={ioNumber:Ae.ioNumber||Ae.io_number||"",blockedAmount:Ae.ioBlockedAmount||Ae.io_blocked_amount||0,availableBalance:Ae.ioAvailableBalance||Ae.io_available_balance||0,remainingBalance:Ae.ioRemainingBalance||Ae.io_remaining_balance||0,organizedBy:((fs=Ae.organizer)==null?void 0:fs.displayName)||((de=Ae.organizer)==null?void 0:de.name)||Ae.organizedBy||H.approver||"N/A",organizedAt:Ae.organizedAt||Ae.organized_at||H.approvedAt||(t==null?void 0:t.updatedAt)||""})}let Ue;ge===6&&(fe!=null&&fe.dmsDetails?Ue={dmsNumber:fe.dmsDetails.dmsNumber||"",dmsRemarks:fe.dmsDetails.dmsRemarks||"",pushedBy:fe.dmsDetails.pushedBy||H.approver,pushedAt:fe.dmsDetails.pushedAt||H.approvedAt||""}:t!=null&&t.dmsNumber&&(Ue={dmsNumber:t.dmsNumber||"",dmsRemarks:t.dmsRemarks||((Ot=t.dmsDetails)==null?void 0:Ot.dmsRemarks)||"",pushedBy:H.approver,pushedAt:H.approvedAt||t.updatedAt||""}));let ye;if(Y||G)((Yt=fe==null?void 0:fe.status)==null?void 0:Yt.toLowerCase())==="rejected"?ye="rejected":Te!==null&&ge>Te?ye="waiting":((hs=fe==null?void 0:fe.status)==null?void 0:hs.toLowerCase())==="approved"?ye="approved":Te!==null&&ge<Te?((Qe=fe==null?void 0:fe.status)==null?void 0:Qe.toLowerCase())==="approved"?ye="approved":ye="waiting":(z!==null&&ge>z,ye="waiting");else if(ie&&z!==null&&z>0)if(ge>z)ye="waiting";else if(ge<z)if(fe!=null&&fe.status){const Ae=fe.status.toLowerCase();Ae==="approved"?ye="approved":Ae==="rejected"?ye="rejected":ye="waiting"}else ye="waiting";else if(fe!=null&&fe.status){const Ae=fe.status.toLowerCase();Ae==="approved"?ye="approved":Ae==="rejected"?ye="rejected":ye="in_progress"}else{const Ae=(H.status||"pending").toLowerCase();Ae==="in-review"||Ae==="in_review"||Ae==="in review"||Ae==="pending"?ye="in_progress":ye=Ae}else if(fe!=null&&fe.status){const Ae=fe.status.toLowerCase();Ae==="approved"?ye="approved":Ae==="rejected"?ye="rejected":Ae==="pending"||Ae==="in_progress"||Ae==="in-progress"?ye="in_progress":ye=(H.status||"waiting").toLowerCase()}else{const Ae=(H.status||"waiting").toLowerCase();Ae==="in-review"||Ae==="in_review"||Ae==="in review"||Ae==="pending"?ye="in_progress":ye=Ae}const dt=ye==="waiting"?0:H.elapsedHours||0,xs=H.approver||H.approverName||"Unknown",vt=oe?I(oe):{current:null,previous:null};return{step:ge,title:ce(ge,oe,xs),approver:xs,description:Z(ge,oe,xs)||H.description||"",tatHours:H.tatHours||24,status:ye,comment:H.comment||(fe==null?void 0:fe.comment),approvedAt:H.approvedAt||(fe==null?void 0:fe.timestamp),elapsedHours:dt,ioDetails:he,dmsDetails:Ue,einvoiceUrl:ge===7?fe==null?void 0:fe.einvoiceUrl:void 0,emailTemplateUrl:(fe==null?void 0:fe.emailTemplateUrl)||void 0,versionHistory:vt}});let re=null,pe=1;if(Y||G)Te!==null?pe=Te:z!==null?pe=z:pe=(t==null?void 0:t.currentStep)||1;else if(ie){const H=z!==null?Se.find(Ie=>Ie.step===z):null;re=H&&(H.status==="pending"||H.status==="in_progress")?H:Se.find(Ie=>{var oe;const ge=((oe=Ie.status)==null?void 0:oe.toLowerCase())||"";return ge==="pending"||ge==="in_progress"||ge==="in-review"||ge==="in_review"}),pe=re?re.step:z||(t==null?void 0:t.currentStep)||1}else pe=z||(t==null?void 0:t.currentStep)||1;const ve=((ga=s==null?void 0:s.email)==null?void 0:ga.toLowerCase())||"",be=((fa=t==null?void 0:t.dealerEmail)==null?void 0:fa.toLowerCase())||((Ca=(Ma=t==null?void 0:t.dealer)==null?void 0:Ma.email)==null?void 0:Ca.toLowerCase())||((Aa=(wt=t==null?void 0:t.claimDetails)==null?void 0:wt.dealerEmail)==null?void 0:Aa.toLowerCase())||((qa=(Ja=t==null?void 0:t.claimDetails)==null?void 0:Ja.dealer_email)==null?void 0:qa.toLowerCase())||"",Le=be&&ve===be,J=j.find(H=>(H.step||H.levelNumber||H.level_number)===pe),Oe=((J==null?void 0:J.approverEmail)||"").toLowerCase(),xt=Oe&&ve===Oe,je=((tr=(er=t==null?void 0:t.initiator)==null?void 0:er.email)==null?void 0:tr.toLowerCase())||((sr=t==null?void 0:t.initiatorEmail)==null?void 0:sr.toLowerCase())||"",$e=j.find(H=>{const Ie=(H.approverEmail||"").toLowerCase(),ge=(H.levelName||"").toLowerCase();return je&&Ie===je||ge.includes("requestor evaluation")||ge.includes("requestor")&&ge.includes("confirmation")}),yt=$e&&($e.step||$e.levelNumber||$e.level_number)||2,kt=$e||j.find(H=>(H.step||H.levelNumber||H.level_number)===2),lt=((kt==null?void 0:kt.approverEmail)||"").toLowerCase(),Fs=lt&&ve===lt,qs=j.find(H=>(H.step||H.levelNumber||H.level_number)===1),wa=((qs==null?void 0:qs.approverEmail)||"").toLowerCase(),Qa=wa&&ve===wa,q=j.find(H=>(H.levelName||"").toLowerCase().includes("department lead")),we=((q==null?void 0:q.approverEmail)||"").toLowerCase(),ee=we&&ve===we,Fe=async H=>{var Ie,ge;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const oe=t.id||t.requestId;H.proposalDocument&&await mn(H.proposalDocument,oe,"APPROVAL");for(const he of H.otherDocuments)await mn(he,oe,"SUPPORTING");const fe=H.costBreakup.reduce((he,Ce)=>he+Ce.amount,0);await BS(oe,{proposalDocument:H.proposalDocument||void 0,costBreakup:H.costBreakup.map(he=>({description:he.description,amount:he.amount})),totalEstimatedBudget:fe,expectedCompletionDate:H.expectedCompletionDate,dealerComments:H.dealerComments}),Q.success("Proposal submitted successfully"),se()}catch(oe){console.error("Failed to submit proposal:",oe);const fe=((ge=(Ie=oe==null?void 0:oe.response)==null?void 0:Ie.data)==null?void 0:ge.message)||(oe==null?void 0:oe.message)||"Failed to submit proposal. Please try again.";throw Q.error(fe),oe}},Ee=async H=>{var Ie,ge,oe,fe,he;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Ce=t.id||t.requestId,Ue=await ws(Ce),ye=(Ue==null?void 0:Ue.approvalLevels)||(Ue==null?void 0:Ue.approvals)||[],pt=((ge=(Ie=t==null?void 0:t.initiator)==null?void 0:Ie.email)==null?void 0:ge.toLowerCase())||((oe=t==null?void 0:t.initiatorEmail)==null?void 0:oe.toLowerCase())||"",dt=ye.find(vt=>{const ma=(vt.approverEmail||vt.approver_email||"").toLowerCase(),fs=(vt.levelName||vt.level_name||"").toLowerCase(),de=vt.levelNumber||vt.level_number;return pt&&ma===pt||fs.includes("requestor evaluation")||fs.includes("requestor")&&fs.includes("confirmation")||de===yt})||ye.find(vt=>(vt.levelNumber||vt.level_number)===2);if(!(dt!=null&&dt.levelId)&&!(dt!=null&&dt.level_id))throw new Error("Initiator approval level not found");const xs=dt.levelId||dt.level_id;await cn(Ce,xs,H),Q.success("Proposal approved successfully"),se()}catch(Ce){console.error("Failed to approve proposal:",Ce);const Ue=((he=(fe=Ce==null?void 0:Ce.response)==null?void 0:fe.data)==null?void 0:he.message)||(Ce==null?void 0:Ce.message)||"Failed to approve proposal. Please try again.";throw Q.error(Ue),Ce}},Ke=async H=>{var Ie,ge,oe,fe,he;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Ce=t.id||t.requestId,Ue=await ws(Ce),ye=(Ue==null?void 0:Ue.approvalLevels)||(Ue==null?void 0:Ue.approvals)||[],pt=((ge=(Ie=t==null?void 0:t.initiator)==null?void 0:Ie.email)==null?void 0:ge.toLowerCase())||((oe=t==null?void 0:t.initiatorEmail)==null?void 0:oe.toLowerCase())||"",dt=ye.find(vt=>{const ma=(vt.approverEmail||vt.approver_email||"").toLowerCase(),fs=(vt.levelName||vt.level_name||"").toLowerCase(),de=vt.levelNumber||vt.level_number;return pt&&ma===pt||fs.includes("requestor evaluation")||fs.includes("requestor")&&fs.includes("confirmation")||de===yt})||ye.find(vt=>(vt.levelNumber||vt.level_number)===2);if(!(dt!=null&&dt.levelId)&&!(dt!=null&&dt.level_id))throw new Error("Initiator approval level not found");const xs=dt.levelId||dt.level_id;await Ar(Ce,xs,"Proposal rejected by requestor",H),Q.success("Proposal rejected. Request has been cancelled."),se()}catch(Ce){console.error("Failed to reject proposal:",Ce);const Ue=((he=(fe=Ce==null?void 0:Ce.response)==null?void 0:fe.data)==null?void 0:he.message)||(Ce==null?void 0:Ce.message)||"Failed to reject proposal. Please try again.";throw Q.error(Ue),Ce}},Me=async H=>{var Ie,ge,oe,fe,he;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Ce=t.id||t.requestId,Ue=await ws(Ce),ye=(Ue==null?void 0:Ue.approvalLevels)||(Ue==null?void 0:Ue.approvals)||[],pt=((ge=(Ie=t==null?void 0:t.initiator)==null?void 0:Ie.email)==null?void 0:ge.toLowerCase())||((oe=t==null?void 0:t.initiatorEmail)==null?void 0:oe.toLowerCase())||"",dt=ye.find(vt=>{const ma=(vt.approverEmail||vt.approver_email||"").toLowerCase(),fs=(vt.levelName||vt.level_name||"").toLowerCase(),de=vt.levelNumber||vt.level_number;return pt&&ma===pt||fs.includes("requestor evaluation")||fs.includes("requestor")&&fs.includes("confirmation")||de===yt})||ye.find(vt=>(vt.levelNumber||vt.level_number)===2);if(!(dt!=null&&dt.levelId)&&!(dt!=null&&dt.level_id))throw new Error("Initiator approval level not found");const xs=dt.levelId||dt.level_id;await Ar(Ce,xs,"Revised Quotation Requested",H),Q.success("Revision requested. Request returned to dealer."),se()}catch(Ce){console.error("Failed to request revision:",Ce);const Ue=((he=(fe=Ce==null?void 0:Ce.response)==null?void 0:fe.data)==null?void 0:he.message)||(Ce==null?void 0:Ce.message)||"Failed to request revision. Please try again.";throw Q.error(Ue),Ce}},Je=async H=>{var Ie,ge;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const oe=t.id||t.requestId,fe=await ws(oe),he=(fe==null?void 0:fe.approvalLevels)||(fe==null?void 0:fe.approvals)||[],Ce=he.find(ye=>(ye.levelName||ye.level_name||"").toLowerCase().includes("department lead"))||he.find(ye=>(ye.levelNumber||ye.level_number)===3);if(!(Ce!=null&&Ce.levelId)&&!(Ce!=null&&Ce.level_id))throw new Error("Department Lead approval level not found");const Ue=Ce.levelId||Ce.level_id;await eg(oe,{ioNumber:H.ioNumber}),await cn(oe,Ue,H.comments),Q.success("Request approved and IO organized successfully"),se()}catch(oe){console.error("Failed to approve and organize IO:",oe);const fe=((ge=(Ie=oe==null?void 0:oe.response)==null?void 0:Ie.data)==null?void 0:ge.message)||(oe==null?void 0:oe.message)||"Failed to approve request. Please try again.";throw Q.error(fe),oe}},Be=async H=>{var Ie,ge;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const oe=t.id||t.requestId,fe=H.closedExpenses.map(he=>({description:he.description,amount:he.amount}));if(await VS(oe,{activityCompletionDate:H.activityCompletionDate,numberOfParticipants:H.numberOfParticipants,closedExpenses:fe,totalClosedExpenses:H.totalClosedExpenses,completionDocuments:H.completionDocuments,activityPhotos:H.activityPhotos,completionDescription:H.completionDescription}),H.invoicesReceipts&&H.invoicesReceipts.length>0)for(const he of H.invoicesReceipts)await mn(he,oe,"SUPPORTING");H.attendanceSheet&&await mn(H.attendanceSheet,oe,"SUPPORTING"),Q.success("Completion documents submitted successfully"),se()}catch(oe){console.error("Failed to submit completion documents:",oe);const fe=((ge=(Ie=oe==null?void 0:oe.response)==null?void 0:Ie.data)==null?void 0:ge.message)||(oe==null?void 0:oe.message)||"Failed to submit completion documents. Please try again.";throw Q.error(fe),oe}},tt=async H=>{var Ie,ge;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const oe=t.id||t.requestId,fe=new Date().toISOString().slice(0,10);await HS(oe,{eInvoiceDate:fe}),Q.success("Pushed to DMS successfully. E-invoice will be generated automatically."),se()}catch(oe){console.error("[DealerClaimWorkflowTab] Error pushing to DMS:",oe);const fe=((ge=(Ie=oe==null?void 0:oe.response)==null?void 0:Ie.data)==null?void 0:ge.message)||(oe==null?void 0:oe.message)||"Failed to push to DMS. Please try again.";throw Q.error(fe),oe}},js=async H=>{var Ie,ge;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const oe=t.id||t.requestId,fe=await ws(oe),he=(fe==null?void 0:fe.approvalLevels)||(fe==null?void 0:fe.approvals)||[],Ce=he.find(ye=>(ye.levelName||ye.level_name||"").toLowerCase().includes("department lead"))||he.find(ye=>(ye.levelNumber||ye.level_number)===3);if(!(Ce!=null&&Ce.levelId)&&!(Ce!=null&&Ce.level_id))throw new Error("Department Lead approval level not found");const Ue=Ce.levelId||Ce.level_id;await Ar(oe,Ue,"Dept Lead rejected - More clarification required",H),Q.success("Request rejected. Request has been cancelled."),se()}catch(oe){console.error("Failed to reject request:",oe);const fe=((ge=(Ie=oe==null?void 0:oe.response)==null?void 0:Ie.data)==null?void 0:ge.message)||(oe==null?void 0:oe.message)||"Failed to reject request. Please try again.";throw Q.error(fe),oe}},[Kt,rt]=h.useState(null);h.useEffect(()=>{if(!t){rt(null);return}(async()=>{try{const Ie=t.id||t.requestId;if(!Ie){rt(null);return}const ge=await ws(Ie),oe=(ge==null?void 0:ge.documents)||[],fe=t.proposalDetails||(ge==null?void 0:ge.proposalDetails)||{},he=oe.find(ye=>ye.category==="APPROVAL"||ye.type==="proposal"||ye.documentCategory==="APPROVAL"),Ce=oe.filter(ye=>ye.category==="SUPPORTING"||ye.type==="supporting"||ye.documentCategory==="SUPPORTING");let Ue=fe.costBreakup||[];if(typeof Ue=="string")try{Ue=JSON.parse(Ue)}catch(ye){console.warn("Failed to parse costBreakup JSON:",ye),Ue=[]}Array.isArray(Ue)||(Ue=[]),rt({proposalDocument:he?{name:he.fileName||he.file_name||he.name,id:he.documentId||he.document_id||he.id}:void 0,costBreakup:Ue,expectedCompletionDate:fe.expectedCompletionDate||"",otherDocuments:Ce.map(ye=>({name:ye.fileName||ye.file_name||ye.name,id:ye.documentId||ye.document_id||ye.id})),dealerComments:fe.dealerComments||"",submittedAt:fe.submittedAt})}catch(Ie){console.warn("Failed to load proposal data:",Ie);const ge=t.proposalDetails||{};let oe=ge.costBreakup||[];if(typeof oe=="string")try{oe=JSON.parse(oe)}catch(fe){console.warn("Failed to parse costBreakup JSON:",fe),oe=[]}Array.isArray(oe)||(oe=[]),rt({proposalDocument:void 0,costBreakup:oe,expectedCompletionDate:ge.expectedCompletionDate||"",otherDocuments:[],dealerComments:ge.dealerComments||"",submittedAt:ge.submittedAt})}})()},[t]);const[st,gt]=h.useState(null);h.useEffect(()=>{if(!t){gt(null);return}(async()=>{try{const Ie=t.id||t.requestId;if(!Ie){gt(null);return}const ge=await ws(Ie),oe=(ge==null?void 0:ge.documents)||[],fe=[],he=[],Ce=[];let Ue=null;oe.forEach(ye=>{const pt=(ye.category||ye.documentCategory||ye.type||"").toUpperCase(),dt=(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};pt==="COMPLETION"||pt==="COMPLETION_DOCUMENT"?fe.push(xs):pt==="ACTIVITY_PHOTO"||pt==="PHOTO"||pt==="IMAGE"?he.push(xs):pt==="ATTENDANCE"||pt==="ATTENDANCE_SHEET"?Ue=xs:(pt==="SUPPORTING"||pt==="INVOICE"||pt==="RECEIPT")&&(!Ue&&(dt.includes("attendance")||dt.includes("participant"))?Ue=xs:Ce.push(xs))}),fe.length===0&&he.length===0&&t.completionDetails,gt({completionDocuments:fe,activityPhotos:he,invoicesReceipts:Ce,attendanceSheet:Ue})}catch(Ie){console.warn("Failed to load completion documents:",Ie),gt(null)}})()},[t]);const qt=((ar=t==null?void 0:t.claimDetails)==null?void 0:ar.dealerName)||((_a=t==null?void 0:t.dealerInfo)==null?void 0:_a.name)||"Dealer",Et=((ya=t==null?void 0:t.claimDetails)==null?void 0:ya.activityName)||((La=t==null?void 0:t.activityInfo)==null?void 0:La.activityName)||(t==null?void 0:t.title)||"Activity";return e.jsxs(e.Fragment,{children:[e.jsxs(te,{children:[e.jsx(ue,{children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsxs(xe,{className:"flex items-center gap-2",children:[e.jsx(Ks,{className:"w-5 h-5 text-purple-600"}),"Claim Management Workflow"]}),e.jsx(ke,{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:Se.map((H,Ie)=>{var dt,xs,vt,ma,fs;const oe=(((dt=H.status)==null?void 0:dt.toLowerCase())||"")==="in_progress",fe=H.step===pe,he=ie&&oe&&fe,Ce=H.status==="approved",Ue=j.find(de=>(de.step||de.levelNumber||de.level_number)===H.step),ye=Ue!=null&&Ue.levelId?(xs=t==null?void 0:t.approvals)==null?void 0:xs.find(de=>de.levelId===Ue.levelId||de.level_id===Ue.levelId):null,pt=(ye==null?void 0:ye.status)==="PAUSED"||((vt=t==null?void 0:t.pauseInfo)==null?void 0:vt.isPaused)&&(((ma=t==null?void 0:t.pauseInfo)==null?void 0:ma.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 ${ZS(H.status,he)}`,children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:`p-3 rounded-xl ${XS(H.status)}`,children:KS(H.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:H.title}),e.jsx(ne,{className:YS(H.status),children:H.status.toLowerCase()}),H.emailTemplateUrl&&H.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:()=>{T({stepNumber:H.step,stepName:H.title}),A(!0)},children:e.jsx(Da,{className:"w-3.5 h-3.5 text-blue-600"})}),H.step===7&&H.einvoiceUrl&&Ce&&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(H.einvoiceUrl,"_blank"),children:e.jsx(Nt,{className:"w-3.5 h-3.5 text-green-600"})})]}),e.jsx("p",{className:"text-sm text-gray-600",children:H.approver}),e.jsx("p",{className:"text-sm text-gray-500 mt-2 italic",children:H.description})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:["TAT: ",Lt(H.tatHours)]}),H.elapsedHours&&(he||Ce)&&e.jsxs("p",{className:"text-xs text-gray-600 font-medium",children:["Elapsed: ",Lt(H.elapsedHours)]})]})]}),H.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:H.comment})}),H.versionHistory&&H.versionHistory.all&&H.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(E);de.has(H.step)?de.delete(H.step):de.add(H.step),M(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"}),H.versionHistory.all&&H.versionHistory.all.length>0&&e.jsxs(ne,{className:"bg-amber-100 text-amber-800 text-[10px] px-1.5 py-0",children:[H.versionHistory.all.length," Versions"]})]}),E.has(H.step)?e.jsx(Qu,{className:"w-4 h-4"}):e.jsx(yo,{className:"w-4 h-4"})]}),E.has(H.step)&&H.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:H.versionHistory.all.map((de,Ot)=>{var Yt,hs,Qe,Ae;return e.jsxs("div",{className:`space-y-2 ${Ot>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(ne,{className:`${Ot===0?"bg-amber-500":"bg-gray-400"} text-white text-[10px] px-2 py-0.5`,children:[Ot===0?"Current":"Previous",": v",de.version]}),e.jsx("span",{className:"text-[10px] text-gray-600 font-medium",children:Cr(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 ${Ot===0?"bg-blue-100":"bg-gray-100"} flex items-center justify-center`,children:e.jsx("span",{className:`text-[8px] font-bold ${Ot===0?"text-blue-600":"text-gray-600"}`,children:((hs=(Yt=de.changer)==null?void 0:Yt.displayName)==null?void 0:hs.charAt(0))||"U"})}),e.jsxs("span",{className:"text-[10px] text-gray-600",children:["By ",((Qe=de.changer)==null?void 0:Qe.displayName)||((Ae=de.changer)==null?void 0:Ae.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:()=>C({data:de.snapshotData,type:"PROPOSAL",title:`Proposal (v${de.version})`}),children:[e.jsx(ht,{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:()=>C({data:de.snapshotData,type:"COMPLETION",title:`Completion (v${de.version})`}),children:[e.jsx(ht,{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?"...":""]})]})]},Ot)})})]}),he&&(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?ha(ye.sla.deadline,!0):"Not set"})]}),e.jsxs("div",{className:`border rounded-lg p-3 ${pt?"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(Xe,{className:"w-4 h-4"}),"Current Approver - Time Tracking ",pt&&"(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"," / ",Lt(H.tatHours)," allocated"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[(()=>{const de=ye.sla.percentageUsed||0,Ot=()=>pt?"bg-gray-500":de>=100?"bg-red-600":de>=75?"bg-orange-500":de>=50?"bg-amber-500":"bg-green-600",Yt=()=>pt?"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(la,{value:de,className:"h-3",indicatorClassName:Ot()}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:`text-xs font-semibold ${Yt()}`,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(oi,{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=H.levelName||H.level_name;return(de&&de.toLowerCase().includes("department lead")||H.title&&H.title.toLowerCase().includes("department lead"))&&H.status==="approved"&&H.ioDetails&&H.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(ls,{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:H.ioDetails.ioNumber})]}),H.ioDetails.blockedAmount!==void 0&&H.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:["₹",H.ioDetails.blockedAmount.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),H.ioDetails.remainingBalance!==void 0&&H.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:["₹",H.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 ",H.ioDetails.organizedBy||H.approver||"N/A"," on"," ",H.ioDetails.organizedAt?Cr(H.ioDetails.organizedAt):H.approvedAt?Cr(H.approvedAt):"N/A"]})]})]})})(),H.step===6&&H.dmsDetails&&H.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(Dt,{className:"w-4 h-4 text-purple-600"}),e.jsx("p",{className:"text-xs font-semibold text-purple-900 uppercase tracking-wide",children:"DMS Processing Details"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs text-gray-600",children:"DMS Number:"}),e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:H.dmsDetails.dmsNumber})]}),H.dmsDetails.dmsRemarks&&e.jsxs("div",{className:"pt-1.5 border-t border-purple-100",children:[e.jsx("p",{className:"text-xs text-gray-600 mb-1",children:"DMS Remarks:"}),e.jsx("p",{className:"text-sm text-gray-900",children:H.dmsDetails.dmsRemarks})]}),H.dmsDetails.pushedAt&&e.jsxs("div",{className:"pt-1.5 border-t border-purple-100 text-xs text-gray-500",children:["Pushed by ",H.dmsDetails.pushedBy," on"," ",Cr(H.dmsDetails.pushedAt)]})]})]}),(()=>{const de=j.find(Ae=>(Ae.step||Ae.levelNumber||Ae.level_number)===H.step),Ot=((de==null?void 0:de.approverEmail)||"").toLowerCase(),Yt=Ot&&ve===Ot,hs=H.step===1||(de==null?void 0:de.levelName)&&de.levelName.toLowerCase().includes("dealer");return he&&(Yt||hs&&Le)})()&&e.jsxs("div",{className:"mt-4 flex gap-2",children:[H.step===1&&(Le||Qa)&&e.jsxs(F,{className:"bg-purple-600 hover:bg-purple-700",onClick:()=>{o(!0)},children:[e.jsx(Bs,{className:"w-4 h-4 mr-2"}),"Submit Proposal"]}),H.step===yt&&(a||Fs)&&e.jsxs(F,{className:"bg-blue-600 hover:bg-blue-700",onClick:()=>{c(!0)},children:[e.jsx(De,{className:"w-4 h-4 mr-2"}),"Review Request"]}),(()=>{const de=j.find(Ae=>(Ae.step||Ae.levelNumber||Ae.level_number)===H.step);if(!((de==null?void 0:de.levelName)||H.title||"").toLowerCase().includes("initiator action")||!(a||ve===je))return null;const Qe=async Ae=>{var zt,Rt;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const cs=t.requestId||t.id;await Yx(cs,Ae,{reason:""}),Q.success(`Action "${Ae==="REVISE"?"Revision Requested":"Request Reopened"}" performed successfully`),se()}catch(cs){console.error("Failed to perform initiator action:",cs);const en=((Rt=(zt=cs==null?void 0:cs.response)==null?void 0:zt.data)==null?void 0:Rt.message)||(cs==null?void 0:cs.message)||"Failed to perform action";Q.error(en)}};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:()=>Qe("REVISE"),children:[e.jsx(Bt,{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:()=>Qe("REOPEN"),children:[e.jsx(sx,{className:"w-4 h-4 mr-2"}),"Reopen"]})]})})(),(()=>{const de=j.find(Rt=>(Rt.levelName||"").toLowerCase().includes("department lead"));if(!(de&&H.step===(de.step||de.levelNumber||de.level_number)))return null;const Yt=((de==null?void 0:de.approverEmail)||"").toLowerCase();if(!(Yt&&ve===Yt||ee||xt))return null;const Qe=(t==null?void 0:t.internalOrder)||(t==null?void 0:t.internal_order),Ae=(Qe==null?void 0:Qe.ioNumber)||(Qe==null?void 0:Qe.io_number)||(t==null?void 0:t.ioNumber)||"",zt=Ae&&Ae.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:()=>{u(!0)},disabled:!zt,children:[e.jsx(De,{className:"w-4 h-4 mr-2"}),"Review and Approve"]}),!zt&&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=j.find(Ae=>(Ae.step||Ae.levelNumber||Ae.level_number)===H.step),Ot=((de==null?void 0:de.approverEmail)||"").toLowerCase(),Yt=Le&&Ot===be,hs=((de==null?void 0:de.levelName)||H.title||"").toLowerCase(),Qe=hs.includes("dealer completion")||hs.includes("completion documents");return Yt&&Qe})()&&e.jsxs(F,{className:"bg-purple-600 hover:bg-purple-700",onClick:()=>{p(!0)},children:[e.jsx(Bs,{className:"w-4 h-4 mr-2"}),"Upload Completion Docs"]}),(()=>{const de=j.find(Qe=>{const Ae=(Qe.levelName||"").toLowerCase();return Ae.includes("requestor claim")||Ae.includes("requestor - claim")});if(!(de&&H.step===(de.step||de.levelNumber||de.level_number)))return null;const Yt=((de==null?void 0:de.approverEmail)||"").toLowerCase();return a||Yt&&ve===Yt?e.jsxs(F,{className:"bg-indigo-600 hover:bg-indigo-700",onClick:()=>{y(!0)},children:[e.jsx(Dt,{className:"w-4 h-4 mr-2"}),"Push to DMS"]}):null})(),H.step===8&&(()=>{var Ae;const de=j.find(zt=>(zt.step||zt.levelNumber||zt.level_number)===8),Ot=((de==null?void 0:de.approverEmail)||"").toLowerCase(),Yt=Ot&&ve===Ot,hs=((Ae=s==null?void 0:s.role)==null?void 0:Ae.toUpperCase())||"";return Yt||(hs==="FINANCE"||hs==="ADMIN")})()&&e.jsxs(F,{className:"bg-green-600 hover:bg-green-700",onClick:()=>{b(!0)},children:[e.jsx(ls,{className:"w-4 h-4 mr-2"}),"View & Send Credit Note"]}),(()=>{const de=j.find(Qe=>(Qe.step||Qe.levelNumber||Qe.level_number)===H.step),Yt=((de==null?void 0:de.levelName)||H.title||"").toLowerCase().includes("additional approver"),hs=H.step===1||H.step===yt||(()=>{const Qe=j.find(Ae=>(Ae.levelName||"").toLowerCase().includes("department lead"));return Qe&&H.step===(Qe.step||Qe.levelNumber||Qe.level_number)})()||(()=>{const Qe=j.find(en=>(en.step||en.levelNumber||en.level_number)===H.step),Ae=((Qe==null?void 0:Qe.approverEmail)||"").toLowerCase(),zt=Le&&Ae===be,Rt=((Qe==null?void 0:Qe.levelName)||H.title||"").toLowerCase(),cs=Rt.includes("dealer completion")||Rt.includes("completion documents");return zt&&cs})()||(()=>{const Qe=j.find(Ae=>{const zt=(Ae.levelName||"").toLowerCase();return zt.includes("requestor claim")||zt.includes("requestor - claim")});return Qe&&H.step===(Qe.step||Qe.levelNumber||Qe.level_number)})()||H.step===8;if(Yt||!hs){const Qe=(de==null?void 0:de.levelId)||(de==null?void 0:de.level_id);if(Qe){const Ae=(de==null?void 0:de.levelName)||(de==null?void 0:de.level_name)||H.title||"Approval Level",zt=(de==null?void 0:de.approverName)||(de==null?void 0:de.approver_name)||H.approver||"Approver";return e.jsxs(F,{className:"bg-blue-600 hover:bg-blue-700",onClick:()=>{S({levelId:Qe,levelName:Ae,approverName:zt}),L(!0)},children:[e.jsx(De,{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 Ae,zt;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Rt=t.id||t.requestId;if(!Qe){Q.error("Approval level not found");return}await cn(Rt,Qe,""),Q.success("Request approved successfully"),se()}catch(Rt){console.error("Failed to approve:",Rt);const cs=((zt=(Ae=Rt==null?void 0:Rt.response)==null?void 0:Ae.data)==null?void 0:zt.message)||(Rt==null?void 0:Rt.message)||"Failed to approve request. Please try again.";Q.error(cs)}},children:[e.jsx(De,{className:"w-4 h-4 mr-2"}),"Approve"]}),e.jsxs(F,{variant:"destructive",onClick:async()=>{var Ae,zt;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Rt=t.id||t.requestId;if(!Qe){Q.error("Approval level not found");return}const cs=prompt("Please provide a reason for rejection:");if(cs===null)return;await Ar(Rt,Qe,"Request rejected",cs),Q.success("Request rejected successfully"),se()}catch(Rt){console.error("Failed to reject:",Rt);const cs=((zt=(Ae=Rt==null?void 0:Rt.response)==null?void 0:Ae.data)==null?void 0:zt.message)||(Rt==null?void 0:Rt.message)||"Failed to reject request. Please try again.";Q.error(cs)}},children:[e.jsx(jt,{className:"w-4 h-4 mr-2"}),"Reject"]})]})}return null})()]}),H.approvedAt&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Approved on ",Cr(H.approvedAt)]})]})]})},Ie)})})]})]}),e.jsx(ES,{isOpen:l,onClose:()=>o(!1),onSubmit:Fe,dealerName:qt,activityName:Et,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),previousProposalData:(Ft=N==null?void 0:N.find(H=>H.snapshotType==="PROPOSAL"))==null?void 0:Ft.snapshotData,documentPolicy:i}),e.jsx(LS,{isOpen:d,onClose:()=>{c(!1)},onApprove:Ee,onReject:Ke,onRequestRevision:Me,proposalData:Kt,dealerName:qt,activityName:Et,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),request:t,previousProposalData:(()=>{const H=(N==null?void 0:N.filter(Ie=>Ie.snapshotType==="PROPOSAL"))||[];return H.length>1?H[1].snapshotData:null})()}),e.jsx(FS,{isOpen:m,onClose:()=>u(!1),onApprove:Je,onReject:js,requestTitle:t==null?void 0:t.title,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),preFilledIONumber:((ms=t==null?void 0:t.internalOrder)==null?void 0:ms.ioNumber)||((Vs=t==null?void 0:t.internalOrder)==null?void 0:Vs.io_number)||((rr=t==null?void 0:t.internal_order)==null?void 0:rr.ioNumber)||((nr=t==null?void 0:t.internal_order)==null?void 0:nr.io_number)||void 0,preFilledBlockedAmount:((ca=t==null?void 0:t.internalOrder)==null?void 0:ca.ioBlockedAmount)||((bt=t==null?void 0:t.internalOrder)==null?void 0:bt.io_blocked_amount)||((us=t==null?void 0:t.internal_order)==null?void 0:us.ioBlockedAmount)||((Ms=t==null?void 0:t.internal_order)==null?void 0:Ms.io_blocked_amount)||void 0,preFilledRemainingBalance:((ea=t==null?void 0:t.internalOrder)==null?void 0:ea.ioRemainingBalance)||((Nr=t==null?void 0:t.internalOrder)==null?void 0:Nr.io_remaining_balance)||((da=t==null?void 0:t.internal_order)==null?void 0:da.ioRemainingBalance)||((Oa=t==null?void 0:t.internal_order)==null?void 0:Oa.io_remaining_balance)||void 0}),e.jsx(IS,{isOpen:x,onClose:()=>p(!1),onSubmit:Be,dealerName:qt,activityName:Et,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),documentPolicy:i}),e.jsx(MS,{isOpen:g,onClose:()=>y(!1),onPush:tt,completionDetails:{activityCompletionDate:((Qr=t==null?void 0:t.completionDetails)==null?void 0:Qr.activityCompletionDate)||((Jr=t==null?void 0:t.completionDetails)==null?void 0:Jr.activity_completion_date),numberOfParticipants:((qr=t==null?void 0:t.completionDetails)==null?void 0:qr.numberOfParticipants)||((Sc=t==null?void 0:t.completionDetails)==null?void 0:Sc.number_of_participants),closedExpenses:(t==null?void 0:t.completionExpenses)||(t==null?void 0:t.completion_expenses)||((Tc=t==null?void 0:t.completionDetails)==null?void 0:Tc.closedExpenses)||((kc=t==null?void 0:t.completionDetails)==null?void 0:kc.closed_expenses),totalClosedExpenses:((Rc=t==null?void 0:t.budgetTracking)==null?void 0:Rc.closedExpenses)||((Dc=t==null?void 0:t.budgetTracking)==null?void 0:Dc.closed_expenses)||((Pc=t==null?void 0:t.completionDetails)==null?void 0:Pc.totalClosedExpenses)||((Ic=t==null?void 0:t.completionDetails)==null?void 0:Ic.total_closed_expenses),completionDescription:((Ec=t==null?void 0:t.completionDetails)==null?void 0:Ec.completionDescription)||((Fc=t==null?void 0:t.completionDetails)==null?void 0:Fc.completion_description)},ioDetails:{ioNumber:((Mc=t==null?void 0:t.internalOrder)==null?void 0:Mc.ioNumber)||((_c=t==null?void 0:t.internalOrder)==null?void 0:_c.io_number)||((Lc=t==null?void 0:t.internal_order)==null?void 0:Lc.ioNumber)||((Oc=t==null?void 0:t.internal_order)==null?void 0:Oc.io_number),blockedAmount:(($c=t==null?void 0:t.internalOrder)==null?void 0:$c.ioBlockedAmount)||((Uc=t==null?void 0:t.internalOrder)==null?void 0:Uc.io_blocked_amount)||((Bc=t==null?void 0:t.internal_order)==null?void 0:Bc.ioBlockedAmount)||((Vc=t==null?void 0:t.internal_order)==null?void 0:Vc.io_blocked_amount),availableBalance:((zc=t==null?void 0:t.internalOrder)==null?void 0:zc.ioAvailableBalance)||((Hc=t==null?void 0:t.internalOrder)==null?void 0:Hc.io_available_balance)||((Wc=t==null?void 0:t.internal_order)==null?void 0:Wc.ioAvailableBalance)||((Gc=t==null?void 0:t.internal_order)==null?void 0:Gc.io_available_balance),remainingBalance:((Kc=t==null?void 0:t.internalOrder)==null?void 0:Kc.ioRemainingBalance)||((Yc=t==null?void 0:t.internalOrder)==null?void 0:Yc.io_remaining_balance)||((Zc=t==null?void 0:t.internal_order)==null?void 0:Zc.ioRemainingBalance)||((Xc=t==null?void 0:t.internal_order)==null?void 0:Xc.io_remaining_balance)},completionDocuments:st,requestTitle:t==null?void 0:t.title,requestNumber:(t==null?void 0:t.requestNumber)||(t==null?void 0:t.request_number)||(t==null?void 0:t.id)}),e.jsx(PS,{isOpen:f,onClose:()=>b(!1),onDownload:async()=>{Q.info("Download functionality will be implemented")},onSendToDealer:async()=>{var H,Ie;try{const ge=(t==null?void 0:t.requestId)||(t==null?void 0:t.id);if(!ge){Q.error("Request ID not found");return}await WS(ge),Q.success("Credit note sent to dealer successfully. Step 8 has been approved."),n&&n()}catch(ge){console.error("Failed to send credit note to dealer:",ge);const oe=((Ie=(H=ge==null?void 0:ge.response)==null?void 0:H.data)==null?void 0:Ie.message)||(ge==null?void 0:ge.message)||"Failed to send credit note to dealer";Q.error(oe)}},creditNoteData:{creditNoteNumber:((Qc=t==null?void 0:t.creditNote)==null?void 0:Qc.creditNoteNumber)||((Jc=t==null?void 0:t.creditNote)==null?void 0:Jc.credit_note_number)||((ed=(qc=t==null?void 0:t.claimDetails)==null?void 0:qc.creditNote)==null?void 0:ed.creditNoteNumber)||((td=t==null?void 0:t.claimDetails)==null?void 0:td.creditNoteNumber)||((sd=t==null?void 0:t.claimDetails)==null?void 0:sd.credit_note_number),creditNoteDate:((ad=t==null?void 0:t.creditNote)==null?void 0:ad.creditNoteDate)||((rd=t==null?void 0:t.creditNote)==null?void 0:rd.credit_note_date)||((id=(nd=t==null?void 0:t.claimDetails)==null?void 0:nd.creditNote)==null?void 0:id.creditNoteDate)||((ld=t==null?void 0:t.claimDetails)==null?void 0:ld.creditNoteDate)||((od=t==null?void 0:t.claimDetails)==null?void 0:od.credit_note_date),creditNoteAmount:(cd=t==null?void 0:t.creditNote)!=null&&cd.creditNoteAmount?Number((dd=t==null?void 0:t.creditNote)==null?void 0:dd.creditNoteAmount):(md=t==null?void 0:t.creditNote)!=null&&md.credit_note_amount?Number((ud=t==null?void 0:t.creditNote)==null?void 0:ud.credit_note_amount):(hd=(xd=t==null?void 0:t.claimDetails)==null?void 0:xd.creditNote)!=null&&hd.creditNoteAmount?Number((gd=(pd=t==null?void 0:t.claimDetails)==null?void 0:pd.creditNote)==null?void 0:gd.creditNoteAmount):(fd=t==null?void 0:t.claimDetails)!=null&&fd.creditNoteAmount?Number((yd=t==null?void 0:t.claimDetails)==null?void 0:yd.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:((jd=t==null?void 0:t.creditNote)==null?void 0:jd.status)||((wd=(Nd=t==null?void 0:t.claimDetails)==null?void 0:Nd.creditNote)==null?void 0:wd.status)||((Cd=t==null?void 0:t.creditNote)!=null&&Cd.creditNoteNumber?"CONFIRMED":"PENDING")},dealerInfo:{dealerName:((Ad=t==null?void 0:t.claimDetails)==null?void 0:Ad.dealerName)||((Sd=t==null?void 0:t.claimDetails)==null?void 0:Sd.dealer_name),dealerCode:((Td=t==null?void 0:t.claimDetails)==null?void 0:Td.dealerCode)||((kd=t==null?void 0:t.claimDetails)==null?void 0:kd.dealer_code),dealerEmail:((Rd=t==null?void 0:t.claimDetails)==null?void 0:Rd.dealerEmail)||((Dd=t==null?void 0:t.claimDetails)==null?void 0:Dd.dealer_email)},activityName:((Pd=t==null?void 0:t.claimDetails)==null?void 0:Pd.activityName)||((Id=t==null?void 0:t.claimDetails)==null?void 0:Id.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(_S,{isOpen:v,onClose:()=>{A(!1),T(null)},stepNumber:(w==null?void 0:w.stepNumber)||4,stepName:(w==null?void 0:w.stepName)||"Activity Creation",requestNumber:(t==null?void 0:t.requestNumber)||(t==null?void 0:t.id)||(t==null?void 0:t.request_number),recipientEmail:"system@royalenfield.com"}),D&&e.jsx(DS,{isOpen:k,onClose:()=>{L(!1),S(null)},onApprove:async H=>{var Ie,ge;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const oe=t.id||t.requestId,fe=D.levelId;if(!fe){Q.error("Approval level not found");return}await cn(oe,fe,H),Q.success("Request approved successfully"),se(),L(!1),S(null)}catch(oe){console.error("Failed to approve:",oe);const fe=((ge=(Ie=oe==null?void 0:oe.response)==null?void 0:Ie.data)==null?void 0:ge.message)||(oe==null?void 0:oe.message)||"Failed to approve request. Please try again.";throw Q.error(fe),oe}},onReject:async H=>{var Ie,ge;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const oe=t.id||t.requestId,fe=D.levelId;if(!fe){Q.error("Approval level not found");return}await Ar(oe,fe,"Request rejected",H),Q.success("Request rejected successfully"),se(),L(!1),S(null)}catch(oe){console.error("Failed to reject:",oe);const fe=((ge=(Ie=oe==null?void 0:oe.response)==null?void 0:Ie.data)==null?void 0:ge.message)||(oe==null?void 0:oe.message)||"Failed to reject request. Please try again.";throw Q.error(fe),oe}},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:D.levelName,approverName:D.approverName}),N&&N.length>0&&e.jsxs(te,{className:"mt-6 border-amber-100 bg-amber-50/30",children:[e.jsxs(ue,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(xe,{className:"text-sm font-bold flex items-center gap-2 text-amber-900",children:[e.jsx(Dt,{className:"w-4 h-4"}),"Revision History & Audit Trail"]}),e.jsx(F,{variant:"ghost",size:"sm",onClick:()=>O(!R),className:"text-amber-700 hover:text-amber-800 hover:bg-amber-100",children:R?"Hide History":"View History"})]}),e.jsx(ke,{className:"text-xs text-amber-700",children:"Records of all revisions and actions taken on this request"})]}),R&&e.jsx(ae,{children:e.jsx("div",{className:"space-y-4",children:N.map((H,Ie)=>{var ge,oe,fe,he;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 ",H.version]}),H.snapshotType&&e.jsx(ne,{className:"bg-blue-100 text-blue-700 text-[9px] px-1.5 py-0",children:H.snapshotType}),H.levelNumber&&e.jsxs(ne,{className:"bg-gray-100 text-gray-600 text-[9px] px-1.5 py-0",children:["Step ",H.levelNumber]})]}),e.jsx("span",{className:"text-[10px] text-amber-600 font-medium bg-amber-100 px-2 py-0.5 rounded-full",children:Cr(H.createdAt)})]}),e.jsx("p",{className:"text-xs font-medium text-gray-800",children:H.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:((oe=(ge=H.changer)==null?void 0:ge.displayName)==null?void 0:oe.charAt(0))||"U"})}),e.jsxs("span",{className:"text-xs text-gray-500",children:["By ",((fe=H.changer)==null?void 0:fe.displayName)||((he=H.changer)==null?void 0:he.email)||"Unknown User"]})]}),H.snapshotType==="PROPOSAL"&&H.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:"}),H.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:()=>C({data:H.snapshotData,type:"PROPOSAL",title:`Historical Proposal (Version ${H.version})`}),children:["View Details",e.jsx(ht,{className:"w-2 h-2"})]})}),e.jsxs("p",{className:"text-gray-600",children:["Budget: ₹",Number(H.snapshotData.totalBudget||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),H.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",H.snapshotData.comments.substring(0,80),H.snapshotData.comments.length>80?"...":""]})]}),H.snapshotType==="COMPLETION"&&H.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:"}),H.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:()=>C({data:H.snapshotData,type:"COMPLETION",title:`Historical Completion (Version ${H.version})`}),children:["View Details",e.jsx(ht,{className:"w-3 h-3"})]})}),e.jsxs("p",{className:"text-gray-600",children:["Total Expenses: ₹",Number(H.snapshotData.totalExpenses||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),H.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",H.snapshotData.comments.substring(0,80),H.snapshotData.comments.length>80?"...":""]})]}),H.snapshotType==="INTERNAL_ORDER"&&H.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: ",H.snapshotData.ioNumber||"N/A"]}),e.jsxs("p",{className:"text-gray-600",children:["Blocked: ₹",Number(H.snapshotData.blockedAmount||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),H.snapshotData.sapDocumentNumber&&e.jsxs("p",{className:"text-gray-600",children:["SAP Doc: ",H.snapshotData.sapDocumentNumber]})]}),H.snapshotType==="APPROVE"&&H.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:[H.snapshotData.action==="APPROVE"?"Approval":"Rejection",":"]}),e.jsxs("p",{className:"text-gray-600",children:["By: ",H.snapshotData.approverName||H.snapshotData.approverEmail||"Unknown"]}),H.snapshotData.levelName&&e.jsxs("p",{className:"text-gray-600",children:["Level: ",H.snapshotData.levelName]}),H.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",H.snapshotData.comments.substring(0,80),H.snapshotData.comments.length>80?"...":""]}),H.snapshotData.rejectionReason&&e.jsxs("p",{className:"text-red-600 mt-1",children:["Rejection Reason: ",H.snapshotData.rejectionReason.substring(0,80),H.snapshotData.rejectionReason.length>80?"...":""]})]}),H.snapshotType==="WORKFLOW"&&H.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: ",H.snapshotData.status||"N/A"]}),H.snapshotData.currentLevel&&e.jsxs("p",{className:"text-gray-600",children:["Current Level: ",H.snapshotData.currentLevel]})]})]})]},H.historyId||Ie)})})})]}),e.jsx(OS,{isOpen:!!B,onClose:()=>C(null),snapshot:B==null?void 0:B.data,type:(B==null?void 0:B.type)||"PROPOSAL",title:B==null?void 0:B.title})]})}function JS({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,d=(i==null?void 0:i.ioAvailableBalance)||(i==null?void 0:i.io_available_balance)||0,c=(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)||"",u=(i==null?void 0:i.organizer)||null,x=(s==null?void 0:s.proposalDetails)||{},p=Number((x==null?void 0:x.totalEstimatedBudget)||(x==null?void 0:x.total_estimated_budget)||0),[g,y]=h.useState(l),[f,b]=h.useState(!1),[v,A]=h.useState(null),[w,T]=h.useState(""),[k,L]=h.useState(null),[D,S]=h.useState(!1);h.useEffect(()=>{if(i&&l){const R=Number(d)||0,O=(u==null?void 0:u.displayName)||(u==null?void 0:u.display_name)||(u==null?void 0:u.name)||(u!=null&&u.firstName&&(u!=null&&u.lastName)?`${u.firstName} ${u.lastName}`.trim():null)||(u==null?void 0:u.email)||"Unknown User";if(y(l),o>0){const E=Number(o)||0,M=Number(c)||0,B=R-E;Math.abs(M-B)>.01&&console.warn("[IOTab] ⚠️ Remaining balance calculation issue detected!",{availableBalance:R,blockedAmount:E,expectedRemaining:B,backendRemaining:M,difference:M-B}),L({ioNumber:l,blockedAmount:E,availableBalance:R,remainingBalance:M,blockedDate:i.organizedAt||i.organized_at||new Date().toISOString(),blockedBy:O,sapDocumentNumber:m,status:i.status==="BLOCKED"?"blocked":i.status==="RELEASED"?"released":"blocked"}),R>0&&A(R)}}},[i,l,o,d,c,m,u]);const N=async()=>{var R,O;if(!g.trim()){Q.error("Please enter an IO number");return}if(!n){Q.error("Request ID not found");return}b(!0);try{const E=await zS(n,g.trim());E.isValid&&E.availableBalance>0?(A(E.availableBalance),p>0?T(String(p)):T(String(E.availableBalance)),Q.success(`IO fetched from SAP. Available balance: ₹${E.availableBalance.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`)):(Q.error("Invalid IO number or no available balance found"),A(null),T(""))}catch(E){console.error("Failed to fetch IO budget:",E);const M=((O=(R=E==null?void 0:E.response)==null?void 0:R.data)==null?void 0:O.message)||(E==null?void 0:E.message)||"Failed to validate IO number or fetch budget from SAP";Q.error(M),A(null)}finally{b(!1)}},P=async()=>{var E,M;if(!g.trim()||v===null){Q.error("Please fetch IO amount first");return}if(!n){Q.error("Request ID not found");return}const R=parseFloat(w);if(!w||isNaN(R)||R<=0){Q.error("Please enter a valid amount to block");return}const O=parseFloat(R.toFixed(2));if(O>v){Q.error("Amount to block exceeds available IO budget");return}if(p>0){const B=parseFloat(p.toFixed(2));if(Math.abs(O-B)>.01){Q.error(`Amount to block must be exactly equal to the estimated budget (₹${B.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})})`);return}}S(!0);try{const B=parseFloat(v.toFixed(2)),C=parseFloat((B-O).toFixed(2)),j={ioNumber:g.trim(),ioAvailableBalance:B,ioBlockedAmount:O,ioRemainingBalance:C};await eg(n,j);const U=await US(n),$=(U==null?void 0:U.internalOrder)||(U==null?void 0:U.internal_order);if($){const _=Number($.ioBlockedAmount||$.io_blocked_amount||O),se=Number($.ioRemainingBalance||$.io_remaining_balance||0),W=v-_;Math.abs(_-O)>.01&&console.warn("[IOTab] ⚠️ Amount mismatch! Sent:",O,"Saved:",_),Math.abs(se-W)>.01&&console.warn("[IOTab] ⚠️ Remaining balance calculation issue detected!",{availableBalance:v,blockedAmount:_,expectedRemaining:W,backendRemaining:se,difference:se-W});const ce=r,Z=(ce==null?void 0:ce.displayName)||(ce==null?void 0:ce.display_name)||(ce==null?void 0:ce.name)||(ce!=null&&ce.firstName&&(ce!=null&&ce.lastName)?`${ce.firstName} ${ce.lastName}`.trim():null)||(ce==null?void 0:ce.email)||"Current User",I={ioNumber:$.ioNumber||$.io_number||g,blockedAmount:_,availableBalance:v,remainingBalance:se,blockedDate:$.organizedAt||$.organized_at||new Date().toISOString(),blockedBy:Z,sapDocumentNumber:$.sapDocumentNumber||$.sap_document_number||"",status:"blocked"};L(I),T(""),Q.success("IO budget blocked successfully in SAP"),a==null||a()}else Q.error("IO blocked but failed to fetch updated details"),a==null||a()}catch(B){console.error("Failed to block IO budget:",B);const C=((M=(E=B==null?void 0:B.response)==null?void 0:E.data)==null?void 0:M.message)||(B==null?void 0:B.message)||"Failed to block IO budget in SAP";Q.error(C)}finally{S(!1)}};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(te,{children:[e.jsxs(ue,{children:[e.jsxs(xe,{className:"flex items-center gap-2",children:[e.jsx(Pa,{className:"w-5 h-5 text-[#2d4a3e]"}),"IO Budget Management"]}),e.jsx(ke,{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(le,{htmlFor:"ioNumber",children:"IO Number *"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(_e,{id:"ioNumber",placeholder:"Enter IO number (e.g., IO-2024-12345)",value:g,onChange:R=>y(R.target.value),disabled:f||!!k,className:"flex-1"}),e.jsxs(F,{onClick:N,disabled:!g.trim()||f||!!k,className:"bg-[#2d4a3e] hover:bg-[#1f3329]",children:[e.jsx(Nt,{className:"w-4 h-4 mr-2"}),f?"Fetching...":"Fetch Amount"]})]})]}),!v&&!k&&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&&!k&&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(De,{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(le,{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(_e,{type:"number",id:"blockAmount",placeholder:"Enter amount to block",min:"0",step:"0.01",value:w,onChange:R=>T(R.target.value),className:"pl-8"})]}),p>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:["₹",p.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})})]}),e.jsxs(F,{onClick:P,disabled:D||!w||parseFloat(w)<=0||parseFloat(w)>v||p>0&&Math.abs(parseFloat(w)-p)>.01,className:"w-full bg-[#2d4a3e] hover:bg-[#1f3329]",children:[e.jsx(Vt,{className:"w-4 h-4 mr-2"}),D?"Blocking in SAP...":"Block IO in SAP"]})]})]})]}),e.jsxs(te,{children:[e.jsxs(ue,{children:[e.jsxs(xe,{className:"flex items-center gap-2",children:[e.jsx(De,{className:"w-5 h-5 text-green-600"}),"IO Blocked Details"]}),e.jsx(ke,{children:"Details of IO blocked in SAP system"})]}),e.jsx(ae,{children:k?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(De,{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:k.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:k.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:["₹",k.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:["₹",k.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:["₹",k.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:k.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(k.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(ne,{className:"bg-green-100 text-green-800 border-green-200",children:[e.jsx(De,{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 qS(t,s=10){var a;try{const r={limit:s};t&&(r.q=t);const n=await Ne.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 eT(t){var s,a,r;try{const n=await Ne.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 Ls=[{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 tT({formData:t,updateFormData:s,onValidationError:a,currentUserEmail:r="",currentUserId:n="",currentUserName:i="",onValidate:l,maxApprovalLevels:o,onPolicyViolation:d}){const{userSearchResults:c,userSearchLoading:m,searchUsersForIndex:u,clearSearchForIndex:x}=Fp(),[p,g]=h.useState(!1),[y,f]=h.useState(""),[b,v]=h.useState(24),[A,w]=h.useState("hours"),[T,k]=h.useState(3),[L,D]=h.useState([]),[S,N]=h.useState(!1),[P,R]=h.useState(null),O=h.useRef(null),E=()=>{const I=t.approvers||[],V=[];return Ls.forEach(z=>{if(z.isAuto||z.approverType==="dealer"||z.approverType==="initiator")return;const X=I.find(Y=>Y.level===z.level);(!X||!X.email||!X.userId||!X.tat)&&V.push(`${z.name}`)}),{isValid:V.length===0,missingSteps:V}};h.useEffect(()=>{if(l){const I=E();l(I.isValid)}},[t.approvers]),h.useEffect(()=>{const I=t.approvers||[];if(I.length>0){const V=[],z=I.filter(Y=>Y.isAdditional);Ls.forEach(Y=>{const G=I.find(ie=>ie.originalStepLevel===Y.level||!ie.originalStepLevel&&!ie.isAdditional&&ie.level===Y.level);if(G)V.push(G);else if(Y.isAuto){const ie=Y.level===8?"finance@royalenfield.com":"system@royalenfield.com",me=Y.level===8?"System/Finance":"System";V.push({email:ie,name:me,level:Y.level,tat:Y.defaultTat,tatType:"hours",originalStepLevel:Y.level})}else Y.approverType==="dealer"?V.push({email:t.dealerEmail||"",name:t.dealerName||"",level:Y.level,tat:Y.defaultTat,tatType:"hours",originalStepLevel:Y.level}):Y.approverType==="initiator"?V.push({email:r||"",name:i||r||"User",userId:n,level:Y.level,tat:Y.defaultTat,tatType:"hours",originalStepLevel:Y.level}):V.push({email:"",name:"",level:Y.level,tat:Y.defaultTat,tatType:"hours",originalStepLevel:Y.level})}),z.forEach(Y=>{V.push(Y)}),V.sort((Y,G)=>Y.level-G.level),JSON.stringify(I.map(Y=>({level:Y.level,originalStepLevel:Y.originalStepLevel})))!==JSON.stringify(V.map(Y=>({level:Y.level,originalStepLevel:Y.originalStepLevel})))&&s("approvers",V)}else{const V=[];Ls.forEach(z=>{z.isAuto||(z.approverType==="dealer"?V.push({email:t.dealerEmail||"",name:t.dealerName||"",level:z.level,tat:z.defaultTat,tatType:"hours",originalStepLevel:z.level}):z.approverType==="initiator"?V.push({email:r||"",name:i||r||"User",userId:n,level:z.level,tat:z.defaultTat,tatType:"hours",originalStepLevel:z.level}):V.push({email:"",name:"",level:z.level,tat:z.defaultTat,tatType:"hours",originalStepLevel:z.level}))}),s("approvers",V)}},[t.dealerEmail,t.dealerName,r,n,i]);const M=(I,V)=>{const z=[...t.approvers||[]],X=z.findIndex(Y=>Y.originalStepLevel===I||!Y.originalStepLevel&&Y.level===I&&!Y.isAdditional);if(X===-1){const Y=Ls.find(G=>G.level===I);z.push({email:V,name:"",level:I,tat:(Y==null?void 0:Y.defaultTat)||48,tatType:"hours",originalStepLevel:I})}else{const Y=z[X];if(Y){const G=Y.email;z[X]={...Y,email:V,name:V!==G?"":Y.name,userId:V!==G?void 0:Y.userId}}}if(s("approvers",z),!V||!V.startsWith("@")||V.length<2){x(I-1);return}u(I-1,V,10)},B=async(I,V)=>{var z,X;try{const Y=Ls.find(re=>re.level===I);if(Y&&!Y.isAuto&&Y.approverType!=="initiator"&&((z=V.email)==null?void 0:z.toLowerCase())===(r==null?void 0:r.toLowerCase())){Q.error(`You cannot assign yourself as ${Y.name} approver.`),a&&a({type:"self-assign",email:V.email,message:`You cannot assign yourself as ${Y.name} approver.`});return}if((t.approvers||[]).some(re=>{var pe,ve;return re.level!==I&&(re.userId===V.userId||((pe=re.email)==null?void 0:pe.toLowerCase())===((ve=V.email)==null?void 0:ve.toLowerCase()))})){Q.error("This user is already assigned to another step."),a&&a({type:"error",email:V.email,message:"This user is already assigned to another step."});return}const me=await ia({userId:V.userId,email:V.email,displayName:V.displayName,firstName:V.firstName,lastName:V.lastName,department:V.department,phone:V.phone,mobilePhone:V.mobilePhone,designation:V.designation,jobTitle:V.jobTitle,manager:V.manager,employeeId:V.employeeId,employeeNumber:V.employeeNumber,secondEmail:V.secondEmail,location:V.location}),Te=[...t.approvers||[]],Se=Te.findIndex(re=>re.originalStepLevel===I||!re.originalStepLevel&&re.level===I&&!re.isAdditional);if(Se===-1){const re=Ls.find(pe=>pe.level===I);Te.push({email:V.email,name:V.displayName||[V.firstName,V.lastName].filter(Boolean).join(" "),userId:me.userId,level:I,tat:(re==null?void 0:re.defaultTat)||48,tatType:"hours",originalStepLevel:I})}else{const re=Te[Se];re&&(Te[Se]={...re,email:V.email,name:V.displayName||[V.firstName,V.lastName].filter(Boolean).join(" "),userId:me.userId,originalStepLevel:re.originalStepLevel||I})}s("approvers",Te),x(I-1),Q.success(`Approver for ${(X=Ls.find(re=>re.level===I))==null?void 0:X.name} selected successfully.`)}catch(Y){console.error("Failed to ensure user exists:",Y),Q.error("Failed to validate user. Please try again."),a&&a({type:"error",email:V.email,message:"Failed to validate user. Please try again."})}},C=(I,V)=>{const z=[...t.approvers||[]],X=z.findIndex(Y=>Y.originalStepLevel===I||!Y.originalStepLevel&&Y.level===I&&!Y.isAdditional);if(X!==-1){const Y=z[X];Y&&(z[X]={...Y,tat:V},s("approvers",z))}},j=(I,V)=>{const z=[...t.approvers||[]],X=z.findIndex(Y=>Y.originalStepLevel===I||!Y.originalStepLevel&&Y.level===I&&!Y.isAdditional);if(X!==-1){const Y=z[X];Y&&(z[X]={...Y,tatType:V,tat:""},s("approvers",z))}},U=I=>{if(f(I),P&&P.email.toLowerCase()!==I.toLowerCase()&&R(null),O.current&&clearTimeout(O.current),!I||!I.startsWith("@")||I.length<2){D([]),N(!1);return}N(!0),O.current=setTimeout(async()=>{var V;try{const z=I.slice(1),Y=((V=(await oa(z,10)).data)==null?void 0:V.data)||[];D(Y)}catch(z){console.error("Search failed:",z),D([])}finally{N(!1)}},300)},$=async I=>{try{await ia({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}),f(I.email),R(I),D([]),N(!1)}catch(V){console.error("Failed to ensure user exists:",V),Q.error("Failed to verify user. Please try again.")}},_=async()=>{var pe,ve;const I=y.trim().toLowerCase();if(!I){Q.error("Please enter an email address");return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(I)){Q.error("Please enter a valid email address");return}const z=typeof b=="string"?Number(b):b;if(!z||z<=0||isNaN(z)){Q.error("Please enter valid TAT (minimum 1)");return}const X=A==="days"?30:720;if((A==="days"?z*24:z)>720){Q.error(`TAT cannot exceed ${X} ${A==="days"?"days":"hours"}`);return}const G=Ls.find(be=>be.name==="Requestor Claim Approval");if(G&&T>=G.level){Q.error('Additional approvers cannot be added after "Requestor Claim Approval" as it is considered final.');return}if(I===(r==null?void 0:r.toLowerCase())){Q.error("You cannot add yourself as an additional approver.");return}const ie=t.approvers||[];if(ie.some(be=>{var Le;return be.userId&&(P==null?void 0:P.userId)&&be.userId===P.userId||((Le=be.email)==null?void 0:Le.toLowerCase())===I})){Q.error("This user is already assigned as an approver.");return}const Te=ie.find(be=>be.originalStepLevel===T||!be.originalStepLevel&&!be.isAdditional&&be.level===T),re=(Te?Te.level:T)+1;if(o){const Le=new Set(ie.map(J=>J.level)).size+1;if(Le>o){const J=[{type:"max_approval_levels",message:`Adding this approver would create ${Le} approval levels, which exceeds the maximum allowed (${o}). Please remove some approvers before adding a new one.`,currentValue:Le,maxValue:o}];d?d(J):Q.error(((pe=J[0])==null?void 0:pe.message)||"Maximum approval levels exceeded");return}}if(!P||P.email.toLowerCase()!==I)try{const Le=((ve=(await oa(I,1)).data)==null?void 0:ve.data)||[];if(Le.length===0){Q.error("User not found in organization directory. Please use @ to search for users.");return}const J=Le[0];await ia({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});const Oe={email:J.email,name:J.displayName||[J.firstName,J.lastName].filter(Boolean).join(" "),userId:J.userId,level:re,tat:typeof b=="string"?Number(b):b,tatType:A,isAdditional:!0,insertAfterLevel:T,stepName:`Additional Approver - ${J.displayName||J.email}`},xt=ie.map(je=>je.level>=re?{...je,level:je.level+1}:je);xt.push(Oe),xt.sort((je,$e)=>je.level-$e.level),s("approvers",xt),Q.success("Additional approver added and subsequent steps shifted")}catch(be){console.error("Failed to validate approver:",be),Q.error("Failed to validate user. Please try again.");return}else{const be={email:P.email,name:P.displayName||[P.firstName,P.lastName].filter(Boolean).join(" "),userId:P.userId,level:re,tat:b,tatType:A,isAdditional:!0,insertAfterLevel:T,stepName:`Additional Approver - ${P.displayName||P.email}`},Le=ie.map(J=>J.level>=re?{...J,level:J.level+1}:J);Le.push(be),Le.sort((J,Oe)=>J.level-Oe.level),s("approvers",Le),Q.success("Additional approver added and subsequent steps shifted")}f(""),v(24),w("hours"),k(3),R(null),D([]),g(!1)},se=I=>{const V=[...t.approvers||[]];if(!V.find(G=>G.level===I))return;const Y=V.filter(G=>G.level!==I).map(G=>G.level>I&&!G.isAdditional?{...G,level:G.level-1}:G);Y.sort((G,ie)=>G.level-ie.level),s("approvers",Y),Q.success("Additional approver removed and subsequent steps shifted back")},W=()=>[...t.approvers||[]].sort((V,z)=>V.level-z.level),ce=t.approvers||[],Z=W();return e.jsxs(gs.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($t,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Approver Selection"}),e.jsx("p",{className:"text-gray-600",children:"Assign approvers for workflow steps with TAT (Turn Around Time)"})]}),e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsx(te,{className:"border-2 border-blue-200 bg-blue-50",children:e.jsxs(ue,{children:[e.jsxs(xe,{className:"flex items-center gap-2 text-blue-900",children:[e.jsx(Sn,{className:"w-5 h-5"}),"Workflow Steps Information"]}),e.jsxs(ke,{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 I=t.approvers||[],z=new Set(I.map(X=>X.level)).size;return z>0?e.jsxs("span",{children:[" (",z,"/",o,")"]}):null})()]})]})]})}),e.jsxs(te,{className:"border-2",children:[e.jsxs(ue,{children:[e.jsxs(xe,{className:"flex items-center gap-2",children:[e.jsx(as,{className:"w-5 h-5"}),"Approval Hierarchy"]}),e.jsx(ke,{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 I=t.approvers||[],z=new Set(I.map(X=>X.level)).size;return z>0?e.jsxs("span",{children:[" (",z,"/",o,")"]}):null})()]}),e.jsxs(F,{type:"button",variant:"outline",onClick:()=>g(!0),className:"flex items-center gap-2",children:[e.jsx(vs,{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(_t,{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(ne,{variant:"secondary",className:"text-xs",children:"YOU"})]}),e.jsx("p",{className:"text-xs text-blue-700",children:"Creates and submits the request"})]})]})}),(()=>{const I=Z.filter(z=>z.isAdditional&&z.insertAfterLevel===0);let V=I.length;return Ls.filter(z=>!z.isAuto).map((z,X,Y)=>{var pe,ve;const G=ce.find(be=>be.originalStepLevel===z.level||!be.originalStepLevel&&be.level===z.level&&!be.isAdditional)||{email:"",name:"",level:z.level,tat:z.defaultTat,tatType:"hours",originalStepLevel:z.level},ie=X===Y.length-1,me=z.isAuto||z.approverType==="dealer"||z.approverType==="initiator",Te=!z.isAuto,Se=Z.filter(be=>be.isAdditional&&be.insertAfterLevel===z.level).sort((be,Le)=>be.level-Le.level),re=V+1;return V++,V+=Se.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"})}),X===0&&I.map((be,Le)=>{const J=Le+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:J})}),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(ne,{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:()=>se(be.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:be.name||be.email}),e.jsxs("div",{className:"text-xs text-gray-500",children:[e.jsxs("div",{children:["Email: ",be.email]}),e.jsxs("div",{children:["TAT: ",be.tat," ",be.tatType]})]})]})]})})]},`additional-${be.level}`)}),e.jsx("div",{className:`p-3 rounded-lg border-2 transition-all ${G.email&&G.userId?"border-green-200 bg-green-50":me?"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 ${G.email&&G.userId?"bg-green-600":me?"bg-blue-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold text-sm",children:re})}),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:z.name}),ie&&e.jsx(ne,{variant:"destructive",className:"text-xs",children:"FINAL"}),me&&e.jsx(ne,{variant:"outline",className:"text-xs",children:"PRE-FILLED"})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:z.description}),Te&&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(le,{htmlFor:`approver-${z.level}`,className:"text-xs font-medium",children:["Email Address ",!me&&"*"]}),G.email&&G.userId&&e.jsxs(ne,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(De,{className:"w-3 h-3 mr-1"}),"Verified"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(_e,{id:`approver-${z.level}`,type:"text",placeholder:me?G.email:"@approver@royalenfield.com",value:G.email||"",onChange:be=>{const Le=be.target.value;me||M(z.level,Le)},disabled:me||z.isAuto,className:"h-9 border-2 border-gray-300 focus:border-blue-500 mt-1 w-full text-sm"}),!me&&!z.isAuto&&(m[z.level-1]||(((pe=c[z.level-1])==null?void 0:pe.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[z.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:(ve=c[z.level-1])==null?void 0:ve.map(be=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>B(z.level,be),children:[e.jsx("div",{className:"font-medium text-gray-900",children:be.displayName||be.email}),e.jsx("div",{className:"text-xs text-gray-600",children:be.email}),be.department&&e.jsx("div",{className:"text-xs text-gray-500",children:be.department})]},be.userId))})})]}),G.name&&e.jsxs("p",{className:"text-xs text-green-600 mt-1",children:["Selected: ",e.jsx("span",{className:"font-semibold",children:G.name})]})]}),e.jsxs("div",{children:[e.jsx(le,{htmlFor:`tat-${z.level}`,className:"text-xs font-medium",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(_e,{id:`tat-${z.level}`,type:"number",placeholder:G.tatType==="days"?"7":"24",min:"1",max:G.tatType==="days"?"30":"720",value:G.tat||"",onChange:be=>C(z.level,parseInt(be.target.value)||""),disabled:z.isAuto,className:"h-9 border-2 border-gray-300 focus:border-blue-500 flex-1 text-sm"}),e.jsxs(Ve,{value:G.tatType||"hours",onValueChange:be=>j(z.level,be),disabled:z.isAuto,children:[e.jsx(He,{className:"w-20 h-9 border-2 border-gray-300 text-sm",children:e.jsx(ze,{})}),e.jsxs(We,{children:[e.jsx(K,{value:"hours",children:"Hours"}),e.jsx(K,{value:"days",children:"Days"})]})]})]})]})]})]})]})}),Se.map((be,Le)=>{const J=re+Le+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:J})}),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:be.stepName||"Additional Approver"}),e.jsx(ne,{variant:"outline",className:"text-xs bg-purple-50 text-purple-700 border-purple-300",children:"ADDITIONAL"}),be.email&&be.userId&&e.jsxs(ne,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(De,{className:"w-3 h-3 mr-1"}),"Verified"]}),e.jsx(F,{type:"button",variant:"ghost",size:"sm",onClick:()=>se(be.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:be.name||be.email||"No approver assigned"}),be.email&&e.jsxs("div",{className:"text-xs text-gray-500 space-y-1",children:[e.jsxs("div",{children:["Email: ",be.email]}),be.tat&&e.jsxs("div",{children:["TAT: ",be.tat," ",be.tatType]})]})]})]})})]},`additional-${be.level}`)})]},z.level)})})()]})]}),e.jsxs(te,{className:"border-2",children:[e.jsx(ue,{children:e.jsxs(xe,{className:"flex items-center gap-2",children:[e.jsx(Xe,{className:"w-5 h-5"}),"TAT Summary"]})}),e.jsx(ae,{children:e.jsx("div",{className:"space-y-3",children:Z.map(I=>{const V=I.originalStepLevel?Ls.find(G=>G.level===I.originalStepLevel):Ls.find(G=>G.level===I.level&&!I.isAdditional);if(V!=null&&V.isAuto)return null;const z=Number(I.tat||0),Y=(I.tatType||"hours")==="days"?z*24:z;if(!z)return null;if(I.isAdditional){const G=Ls.find(ie=>ie.level===I.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:I.stepName||`Additional Approver (after "${(G==null?void 0:G.name)||"Unknown"}")`}),e.jsxs("span",{className:"text-sm text-gray-600",children:[Y," hours"]})]},I.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:(V==null?void 0:V.name)||"Unknown"}),e.jsxs("span",{className:"text-sm text-gray-600",children:[Y," hours"]})]},I.level)})})})]})]}),e.jsx(mt,{open:p,onOpenChange:g,children:e.jsxs(ot,{className:"sm:max-w-md",children:[e.jsxs(ut,{children:[e.jsxs(ct,{className:"flex items-center gap-2",children:[e.jsx(vs,{className:"w-5 h-5 text-blue-600"}),"Add Additional Approver"]}),e.jsx(It,{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(le,{className:"text-sm font-medium",children:"Insert After Step *"}),e.jsxs(Ve,{value:T.toString(),onValueChange:I=>k(Number(I)),children:[e.jsx(He,{className:"h-11 border-gray-300",children:e.jsx(ze,{placeholder:"Select step"})}),e.jsx(We,{children:Ls.filter(I=>{if(I.isAuto)return!1;const V=Ls.find(z=>z.name==="Requestor Claim Approval");return!(V&&I.level>=V.level)}).map(I=>e.jsx(K,{value:I.level.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(as,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:I.name})]})},I.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 I=t.approvers||[],z=new Set(I.map(X=>X.level)).size;return z>0?e.jsxs("span",{children:[" (",z,"/",o,")"]}):null})()]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{className:"text-sm font-medium",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_e,{type:"number",min:"1",max:A==="days"?"30":"720",value:b,onChange:I=>{const V=I.target.value;if(V==="")v("");else{const z=Number(V);!isNaN(z)&&z>=0&&v(z)}},onBlur:I=>{const V=I.target.value;(!V||V===""||Number(V)<=0)&&v(24)},className:"h-11 border-gray-300 flex-1",placeholder:"24"}),e.jsxs(Ve,{value:A,onValueChange:I=>w(I),children:[e.jsx(He,{className:"w-24 h-11 border-gray-300",children:e.jsx(ze,{})}),e.jsxs(We,{children:[e.jsx(K,{value:"hours",children:"Hours"}),e.jsx(K,{value:"days",children:"Days"})]})]})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Maximum time for this approver to respond (1-",A==="days"?"30 days":"720 hours",")"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{className:"text-sm font-medium",children:"Email Address *"}),e.jsxs("div",{className:"relative",children:[e.jsx(ki,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(_e,{type:"text",placeholder:"@username or user@example.com",value:y,onChange:I=>U(I.target.value),className:"pl-10 h-11 border-gray-300",autoFocus:!0}),(S||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 max-h-60 overflow-auto",children:S?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):L.length>0?e.jsx("ul",{className:"divide-y",children:L.map(I=>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:I.displayName||[I.firstName,I.lastName].filter(Boolean).join(" ")||I.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:I.email}),I.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:I.designation})]})})},I.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(Tt,{children:[e.jsx(F,{type:"button",variant:"outline",onClick:()=>{g(!1),f(""),v(24),w("hours"),k(3),R(null),D([])},className:"flex-1",children:"Cancel"}),e.jsxs(F,{type:"button",onClick:_,className:"flex-1 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:!y.trim()||!b,children:[e.jsx(vs,{className:"w-4 h-4 mr-2"}),"Add Approver"]})]})]})})]})}const kl=[{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"}],Rl=["Claim Details","Approver Selection","Review & Submit"];function sT({onBack:t,onSubmit:s}){const{user:a}=Jt(),[r,n]=h.useState(1),[i,l]=h.useState(!1),[o,d]=h.useState([]),[c,m]=h.useState(!1),[u,x]=h.useState(""),p=h.useRef(null),[g,y]=h.useState(!1),f=h.useRef(null),[b,v]=h.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[A,w]=h.useState({open:!1,violations:[]}),[T,k]=h.useState([]),[L,D]=h.useState(!0);h.useEffect(()=>{(async()=>{try{D(!0);const _=await eA();k(_)}catch(_){console.error("Failed to load activity types:",_),Q.error("Failed to load activity types. Please refresh the page.")}finally{D(!1)}})()},[]),h.useEffect(()=>{(async()=>{var _;try{const se=await Qs("SYSTEM_SETTINGS"),W=await Qs("WORKFLOW_SHARING"),ce=[...se,...W],Z={};ce.forEach(I=>{Z[I.configKey]=I.configValue}),v({maxApprovalLevels:parseInt(Z.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(Z.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((_=Z.ALLOW_ADD_SPECTATOR)==null?void 0:_.toLowerCase())==="true",maxSpectators:parseInt(Z.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(se){console.error("Failed to load system policy:",se)}})()},[]),h.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const[S,N]=h.useState({activityName:"",activityType:"",dealerCode:"",dealerName:"",dealerEmail:"",dealerPhone:"",dealerAddress:"",activityDate:void 0,location:"",requestDescription:"",periodStartDate:void 0,periodEndDate:void 0,estimatedBudget:"",approvers:[]}),P=Rl.length,R=$=>{if(x($),p.current&&clearTimeout(p.current),!$||$.trim().length<2){d([]),m(!1);return}m(!0),p.current=setTimeout(async()=>{try{const _=await qS($,10);d(_)}catch(_){console.error("Error searching dealers:",_),d([])}finally{m(!1)}},300)},O=($,_)=>{N(se=>{const W={...se,[$]:_};if($==="periodStartDate")_&&W.periodEndDate&&_>W.periodEndDate&&(W.periodEndDate=void 0,Q.error("End date must be on or after the start date. End date has been cleared."));else if($==="periodEndDate"&&_&&W.periodStartDate&&_<W.periodStartDate)return Q.error("End date must be on or after the start date."),se;return W})},E=()=>{switch(r){case 1:return S.activityName&&S.activityType&&S.dealerCode&&S.dealerName&&S.activityDate&&S.location&&S.requestDescription;case 2:const _=(S.approvers||[]).find(se=>se.originalStepLevel===3||!se.originalStepLevel&&se.level===3&&!se.isAdditional);return(_==null?void 0:_.email)&&(_==null?void 0:_.userId)&&(_==null?void 0:_.tat);case 3:return!0;default:return!1}},M=()=>{if(r<P){if(!E()){if(r===2){const _=(S.approvers||[]).find(W=>W.originalStepLevel===3||!W.originalStepLevel&&W.level===3&&!W.isAdditional),se=[];(!(_!=null&&_.email)||!(_!=null&&_.userId)||!(_!=null&&_.tat))&&se.push("Department Lead Approval"),se.length>0?Q.error(`Please add missing approvers: ${se.join(", ")}`):Q.error("Please complete all required approver selections (email, user verification, and TAT) before proceeding.")}else Q.error("Please complete all required fields before proceeding.");return}n(r+1)}},B=()=>{r>1&&n(r-1)},C=async $=>{l(!0);try{const _=await eT($.dealerCode);if(!_.isLoggedIn){Q.error(`Dealer "${_.dealerName||_.displayName}" (${_.dealerCode}) is not mapped to the system.`,{duration:5e3}),x(""),d([]),O("dealerCode",""),O("dealerName",""),O("dealerEmail",""),O("dealerPhone",""),O("dealerAddress",""),l(!1);return}O("dealerCode",_.dealerCode),O("dealerName",_.dealerName||_.displayName),O("dealerEmail",_.email||""),O("dealerPhone",_.phone||""),O("dealerAddress",""),x(_.dealerName||_.displayName),d([]),Q.success(`Dealer "${_.dealerName||_.displayName}" verified and mapped to the System`)}catch{Q.error("Dealer is not mapped to the system",{duration:5e3}),x(""),d([]),O("dealerCode",""),O("dealerName",""),O("dealerEmail",""),O("dealerPhone",""),O("dealerAddress","")}finally{l(!1)}},j=()=>{if(g)return;const _=[...S.approvers||[]].sort((I,V)=>I.level-V.level),se=new Map,W=[];if(_.forEach(I=>{se.has(I.level)?W.push(I.level):se.set(I.level,I)}),W.length>0){Q.error(`Duplicate approver levels detected: ${W.join(", ")}. Please refresh and try again.`),console.error("Duplicate levels found:",W,_);return}const ce=_.map(I=>{const V={email:I.email,name:I.name,userId:I.userId,level:I.level,tat:I.tat,tatType:I.tatType};return I.isAdditional&&I.stepName&&(V.stepName=I.stepName,V.isAdditional=!0),I.originalStepLevel&&(V.originalStepLevel=I.originalStepLevel),V}),Z={...S,templateType:"claim-management",submittedAt:new Date().toISOString(),status:"pending",currentStep:"initiator-review",approvers:ce};if(y(!0),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{y(!1),f.current=null},3e4),s)try{s(Z)}catch(I){f.current&&(clearTimeout(f.current),f.current=null),y(!1),console.error("Error submitting claim:",I)}else f.current&&(clearTimeout(f.current),f.current=null),y(!1)},U=()=>{switch(r){case 1:return e.jsxs(gs.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(ls,{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(le,{htmlFor:"activityName",className:"text-base font-semibold",children:"Activity Name *"}),e.jsx(_e,{id:"activityName",placeholder:"e.g., Himalayan Adventure Fest 2024",value:S.activityName,onChange:$=>O("activityName",$.target.value),className:"mt-2 h-12"})]}),e.jsxs("div",{children:[e.jsx(le,{htmlFor:"activityType",className:"text-base font-semibold",children:"Activity Type *"}),e.jsxs(Ve,{value:S.activityType,onValueChange:$=>O("activityType",$),disabled:L,children:[e.jsx(He,{className:"mt-2 !h-12 data-[size=default]:!h-12",id:"activityType",children:e.jsx(ze,{placeholder:L?"Loading activity types...":"Select activity type"})}),e.jsx(We,{children:T.length>0?T.map($=>e.jsx(K,{value:$.title,children:$.title},$.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(le,{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(_e,{placeholder:"Type dealer code, name, or email to search...",value:S.dealerCode?`${S.dealerName} (${S.dealerCode})`:u,onChange:$=>{S.dealerCode?(O("dealerCode",""),O("dealerName",""),O("dealerEmail",""),O("dealerPhone",""),O("dealerAddress",""),x($.target.value)):R($.target.value)},onFocus:()=>{u&&u.length>=2&&R(u)},className:"h-12 border-2 border-gray-300 focus:border-blue-500",disabled:i}),S.dealerCode&&e.jsx("div",{className:"absolute right-3 top-1/2 -translate-y-1/2",children:e.jsxs(ne,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(De,{className:"w-3 h-3 mr-1"}),"Verified"]})}),(c||o.length>0)&&!S.dealerCode&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg",children:c?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($=>e.jsx("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>C($),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:$.dealerName||$.displayName}),e.jsxs("div",{className:"text-xs text-gray-600",children:[e.jsx("span",{className:"font-mono",children:$.dealerCode}),$.email&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1",children:"•"}),e.jsx("span",{children:$.email})]})]}),$.city&&$.state&&e.jsxs("div",{className:"text-xs text-gray-500",children:[$.city,", ",$.state]})]}),e.jsx("div",{className:"ml-2 flex-shrink-0",children:$.isLoggedIn?e.jsx(De,{className:"w-4 h-4 text-green-600"}):e.jsx(jt,{className:"w-4 h-4 text-red-500"})})]})},$.dealerId))})})]})}),S.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:S.dealerName})," (",S.dealerCode,")"]}),S.dealerEmail&&e.jsxs("p",{className:"text-xs text-gray-500",children:["Email: ",S.dealerEmail]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(le,{className:"text-base font-semibold",children:"Date *"}),e.jsxs(Ys,{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(it,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:S.activityDate?Ye(S.activityDate,"d MMM yyyy"):"Select date"})]})}),e.jsx(Xs,{className:"w-auto p-0",align:"start",children:e.jsx(Xn,{mode:"single",selected:S.activityDate,onSelect:$=>O("activityDate",$),initialFocus:!0})})]})]}),e.jsxs("div",{children:[e.jsx(le,{htmlFor:"location",className:"text-base font-semibold",children:"Location *"}),e.jsx(_e,{id:"location",placeholder:"e.g., Mumbai, Maharashtra",value:S.location,onChange:$=>O("location",$.target.value),className:"mt-2 h-12"})]})]}),e.jsxs("div",{children:[e.jsx(le,{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($i,{value:S.requestDescription||"",onChange:$=>O("requestDescription",$),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(le,{className:"text-base font-semibold",children:"Period (If Any)"}),e.jsx(ne,{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(le,{className:"text-sm text-gray-600",children:"Start Date"}),e.jsxs(Ys,{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(it,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:S.periodStartDate?Ye(S.periodStartDate,"d MMM yyyy"):"Start date"})]})}),e.jsx(Xs,{className:"w-auto p-0",align:"start",children:e.jsx(Xn,{mode:"single",selected:S.periodStartDate,onSelect:$=>O("periodStartDate",$),initialFocus:!0,toDate:S.periodEndDate||void 0})})]})]}),e.jsxs("div",{children:[e.jsx(le,{className:"text-sm text-gray-600",children:"End Date"}),e.jsxs(Ys,{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:!S.periodStartDate,children:[e.jsx(it,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:S.periodEndDate?Ye(S.periodEndDate,"d MMM yyyy"):"End date"})]})}),e.jsx(Xs,{className:"w-auto p-0",align:"start",children:e.jsx(Xn,{mode:"single",selected:S.periodEndDate,onSelect:$=>O("periodEndDate",$),initialFocus:!0,fromDate:S.periodStartDate||void 0})})]}),!S.periodStartDate&&e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Please select start date first"})]})]}),(S.periodStartDate||S.periodEndDate)&&e.jsx("div",{className:"mt-2",children:S.periodStartDate&&S.periodEndDate?e.jsxs("p",{className:"text-xs text-gray-600",children:["Period: ",Ye(S.periodStartDate,"d MMM yyyy")," - ",Ye(S.periodEndDate,"d MMM yyyy")]}):e.jsx("p",{className:"text-xs text-gray-500",children:S.periodStartDate?"Please select end date for the period":"Please select start date first"})})]})]})]});case 2:return e.jsx(tT,{formData:S,updateFormData:O,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:b.maxApprovalLevels,onPolicyViolation:$=>w({open:!0,violations:$})});case 3:return e.jsxs(gs.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(De,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Review & Submit"}),e.jsx("p",{className:"text-gray-600",children:"Review your claim details before submission"})]}),e.jsxs("div",{className:"max-w-3xl mx-auto space-y-6",children:[e.jsxs(te,{className:"border-2",children:[e.jsx(ue,{className:"bg-gradient-to-br from-blue-50 to-indigo-50",children:e.jsxs(xe,{className:"flex items-center gap-2",children:[e.jsx(ls,{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(le,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:S.activityName})]}),e.jsxs("div",{children:[e.jsx(le,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Type"}),e.jsx(ne,{variant:"secondary",className:"mt-1",children:S.activityType})]})]})})]}),e.jsxs(te,{className:"border-2",children:[e.jsx(ue,{className:"bg-gradient-to-br from-green-50 to-emerald-50",children:e.jsxs(xe,{className:"flex items-center gap-2",children:[e.jsx(Ri,{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(le,{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:S.dealerCode})]}),e.jsxs("div",{children:[e.jsx(le,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:S.dealerName})]}),e.jsxs("div",{children:[e.jsx(le,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Email"}),e.jsx("p",{className:"text-gray-900 mt-1",children:S.dealerEmail})]}),e.jsxs("div",{children:[e.jsx(le,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Phone"}),e.jsx("p",{className:"text-gray-900 mt-1",children:S.dealerPhone})]}),S.dealerAddress&&e.jsxs("div",{className:"col-span-2",children:[e.jsx(le,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Address"}),e.jsx("p",{className:"text-gray-900 mt-1",children:S.dealerAddress})]})]})})]}),e.jsxs(te,{className:"border-2",children:[e.jsx(ue,{className:"bg-gradient-to-br from-purple-50 to-indigo-50",children:e.jsxs(xe,{className:"flex items-center gap-2",children:[e.jsx($t,{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:[...S.approvers||[]].filter(_=>{var se,W;return!((se=_.email)!=null&&se.includes("system@"))&&!((W=_.email)!=null&&W.includes("finance@"))}).sort((_,se)=>_.level-se.level).map(_=>{const se=Number(_.tat||0),ce=(_.tatType||"hours")==="days"?se*24:se;let Z="Unknown",I="";if(_.isAdditional){Z=_.stepName||"Additional Approver";const V=kl.find(z=>z.level===_.insertAfterLevel);I=_.stepName||`Additional Approver (after "${(V==null?void 0:V.name)||"Unknown"}")`}else{const V=_.originalStepLevel?kl.find(z=>z.level===_.originalStepLevel):kl.find(z=>z.level===_.level&&!z.isAuto);Z=(V==null?void 0:V.name)||"Unknown",I=Z}return e.jsx("div",{className:`p-3 rounded-lg border ${_.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(le,{className:"text-xs text-gray-600 uppercase tracking-wider",children:I}),_.isAdditional&&e.jsx(ne,{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:_.name||_.email||"Not selected"}),_.email&&e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:_.email})]}),e.jsxs("div",{className:"text-right ml-4",children:[e.jsxs("p",{className:"text-sm font-semibold text-gray-900",children:[ce," hours"]}),e.jsx("p",{className:"text-xs text-gray-500",children:"TAT"})]})]})},`${_.level}-${_.email}`)})})})]}),e.jsxs(te,{className:"border-2",children:[e.jsx(ue,{className:"bg-gradient-to-br from-purple-50 to-pink-50",children:e.jsxs(xe,{className:"flex items-center gap-2",children:[e.jsx(it,{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(le,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:S.activityDate?Ye(S.activityDate,"PPP"):"N/A"})]}),e.jsxs("div",{children:[e.jsx(le,{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(jo,{className:"w-4 h-4 text-gray-500"}),e.jsx("p",{className:"font-semibold text-gray-900",children:S.location})]})]}),S.estimatedBudget&&e.jsxs("div",{className:"col-span-2",children:[e.jsx(le,{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:S.estimatedBudget})]})]})})]}),e.jsxs(te,{className:"border-2",children:[e.jsx(ue,{className:"bg-gradient-to-br from-orange-50 to-amber-50",children:e.jsxs(xe,{className:"flex items-center gap-2",children:[e.jsx(Pe,{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(le,{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(ra,{content:S.requestDescription||"",className:"text-sm"})})]})})]}),(S.periodStartDate||S.periodEndDate)&&e.jsxs(te,{className:"border-2",children:[e.jsx(ue,{className:"bg-gradient-to-br from-cyan-50 to-blue-50",children:e.jsxs(xe,{className:"flex items-center gap-2",children:[e.jsx(Xe,{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(le,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Start Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:S.periodStartDate?Ye(S.periodStartDate,"PPP"):"Not specified"})]}),e.jsxs("div",{children:[e.jsx(le,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"End Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:S.periodEndDate?Ye(S.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(Sn,{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(Js,{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(ne,{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 ",P,": ",e.jsx("span",{className:"hidden sm:inline",children:Rl[r-1]})]})]})}),e.jsxs("div",{className:"mt-4 sm:mt-6",children:[e.jsx(la,{value:r/P*100,className:"h-2"}),e.jsx("div",{className:"flex justify-between mt-2 px-1",children:Rl.map(($,_)=>e.jsx("span",{className:`text-xs sm:text-sm ${_+1<=r?"text-blue-600 font-medium":"text-gray-400"}`,children:_+1},_))})]})]}),e.jsx(te,{className:"mb-6 sm:mb-8",children:e.jsx(ae,{className:"p-4 sm:p-6 lg:p-8",children:e.jsx(oc,{mode:"wait",children:U()})})}),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:B,disabled:r===1,className:"gap-2 w-full sm:w-auto order-2 sm:order-1",children:[e.jsx(Js,{className:"w-4 h-4"}),"Previous"]}),r<P?e.jsxs(F,{onClick:M,className:`gap-2 w-full sm:w-auto order-1 sm:order-2 ${E()?"":"opacity-50 cursor-pointer hover:opacity-60"}`,children:["Next",e.jsx(ds,{className:"w-4 h-4"})]}):e.jsx(F,{onClick:j,disabled:!E()||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(Ze,{className:"w-4 h-4 animate-spin"}),"Submitting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Vr,{className:"w-4 h-4"}),"Submit Claim Request"]})})]})]}),e.jsx(_n,{open:A.open,onClose:()=>w({open:!1,violations:[]}),violations:A.violations,policyDetails:{maxApprovalLevels:b.maxApprovalLevels,maxParticipants:b.maxParticipants,allowSpectators:b.allowSpectators,maxSpectators:b.maxSpectators}})]})}const{DocumentsTab:aT,ActivityTab:rT,WorkNotesTab:nT,SummaryTab:iT,RequestDetailHeader:lT,QuickActionsSidebar:oT,RequestDetailModals:cT}=Zp;let dT=class extends h.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 mT({requestId:t,onBack:s,dynamicRequests:a=[]}){var Ft,ms,Vs,rr,nr,ca;const n=vr().requestId||t||"",l=new URLSearchParams(window.location.search).get("tab")||"overview",[o,d]=h.useState(l),[c,m]=h.useState(!1),[u,x]=h.useState(null),[p,g]=h.useState(null),[y,f]=h.useState(!1),[b,v]=h.useState(0),[A,w]=h.useState(!1),[T,k]=h.useState(!1),[L,D]=h.useState(!1),[S,N]=h.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[P,R]=h.useState({open:!1,violations:[]}),{user:O}=Jt(),{request:E,apiRequest:M,loading:B,refreshing:C,refreshDetails:j,currentApprovalLevel:U,isSpectator:$,isInitiator:_,existingParticipants:se,accessDenied:W}=yc(n,a,O),ce=(O==null?void 0:O.userId)||"",Z=_,{mergedMessages:I,unreadWorkNotes:V,workNoteAttachments:z,setWorkNoteAttachments:X}=_p(n,M,o,O),{uploadingDocument:Y,triggerFileInput:G,previewDocument:ie,setPreviewDocument:me,documentPolicy:Te,documentError:Se,setDocumentError:re}=Lp(M,j),[pe,ve]=h.useState(null),be=pe||U,{showApproveModal:Le,setShowApproveModal:J,showRejectModal:Oe,setShowRejectModal:xt,showAddApproverModal:je,setShowAddApproverModal:$e,showAddSpectatorModal:yt,setShowAddSpectatorModal:kt,showSkipApproverModal:lt,setShowSkipApproverModal:Fs,showActionStatusModal:qs,setShowActionStatusModal:wa,skipApproverData:Qa,setSkipApproverData:q,actionStatus:we,setActionStatus:ee,handleApproveConfirm:Fe,handleRejectConfirm:Ee,handleAddApprover:Ke,handleSkipApprover:Me,handleAddSpectator:Je}=$p(n,be,j),Be=async bt=>{await Fe(bt),ve(null)},tt=async bt=>{await Ee(bt),ve(null)},js=((E==null?void 0:E.status)||(M==null?void 0:M.status)||"").toLowerCase(),Kt=(js==="approved"||js==="rejected")&&_,{conclusionRemark:rt,setConclusionRemark:st,conclusionLoading:gt,conclusionSubmitting:qt,aiGenerated:Et,handleGenerateConclusion:ga,handleFinalizeConclusion:fa,generationAttempts:Ma,generationFailed:Ca,maxAttemptsReached:wt}=Op(E,n,_,j,s,ee,wa);h.useEffect(()=>{(async()=>{var us;try{const Ms=await Qs("SYSTEM_SETTINGS"),ea=await Qs("WORKFLOW_SHARING"),Nr=[...Ms,...ea],da={};Nr.forEach(Oa=>{da[Oa.configKey]=Oa.configValue}),N({maxApprovalLevels:parseInt(da.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(da.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((us=da.ALLOW_ADD_SPECTATOR)==null?void 0:us.toLowerCase())==="true",maxSpectators:parseInt(da.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(Ms){console.error("Failed to load system policy:",Ms)}})()},[]),h.useEffect(()=>{const us=new URLSearchParams(window.location.search).get("tab");us&&d(us)},[n]);const Aa=()=>{j()},Ja=()=>{w(!0)},qa=()=>{k(!0)},er=async()=>{await j()},tr=()=>{D(!0)},sr=async()=>{await j()},ar=async()=>{await j()},_a=async()=>{if(!(M!=null&&M.requestId)){Q.error("Request ID not found");return}if(!u){Q.error("Summary not available. Please ensure the request is closed and the summary has been generated.");return}m(!0)},ya=(E==null?void 0:E.status)==="closed";h.useEffect(()=>{(async()=>{if(!ya||!(M!=null&&M.requestId)){g(null),x(null);return}try{f(!0);const us=await Wp(M.requestId);if(us!=null&&us.summaryId){x(us.summaryId);try{const Ms=await bc(us.summaryId);g(Ms)}catch(Ms){console.error("Failed to fetch summary details:",Ms),g(null),x(null)}}else g(null),x(null)}catch{g(null),x(null)}finally{f(!1)}})()},[ya,M==null?void 0:M.requestId]),h.useEffect(()=>{if(!ce||!(M!=null&&M.requestId))return;const bt=Lr();if(!bt)return;kx(bt,ce);const us=Ms=>{var Oa,Qr,Jr,qr;const ea=Ms==null?void 0:Ms.notification;if(!ea)return;const Nr=ea.requestId||ea.request_id,da=((Oa=ea.metadata)==null?void 0:Oa.requestNumber)||((Qr=ea.metadata)==null?void 0:Qr.request_number);Nr!==M.requestId&&da!==n&&da!==M.requestNumber||((Jr=ea.metadata)!=null&&Jr.creditNoteNumber||(qr=ea.metadata)!=null&&qr.credit_note_number)&&j()};return bt.on("notification:new",us),()=>{bt.off("notification:new",us)}},[ce,M==null?void 0:M.requestId,n,j]);const La=((E==null?void 0:E.approvalFlow)||[]).filter(bt=>bt&&typeof bt.step=="number").map(bt=>({levelNumber:bt.step||0,approverName:bt.approver||"Unknown",status:bt.status||"pending",tatHours:bt.tatHours||24}));return B&&!E&&!M?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(Bt,{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..."})]})}):W!=null&&W.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(nx,{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:W.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(Js,{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"})]})]})}):E?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(lT,{request:E,refreshing:C,onBack:s||(()=>window.history.back()),onRefresh:Aa,onShareSummary:_a,isInitiator:_,slaData:((Ft=E==null?void 0:E.summary)==null?void 0:Ft.sla)||(E==null?void 0:E.sla)||null,isPaused:((ms=E==null?void 0:E.pauseInfo)==null?void 0:ms.isPaused)||!1}),e.jsxs(Ln,{value:o,onValueChange:d,className:"w-full","data-testid":"dealer-claim-request-detail-tabs",children:[e.jsx("div",{className:"mb-4 sm:mb-6",children:e.jsxs(On,{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(At,{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(ix,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Overview"})]}),ya&&p&&e.jsxs(At,{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(No,{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(At,{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(Ks,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Workflow"})]}),Z&&e.jsxs(At,{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(At,{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(Pe,{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(At,{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(Dt,{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(At,{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"}),V>0&&e.jsx(ne,{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:V>9?"9+":V})]})]})}),e.jsxs("div",{className:o==="worknotes"?"":"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs("div",{className:o==="worknotes"?"":"lg:col-span-2",children:[e.jsx(St,{value:"overview",className:"mt-0","data-testid":"overview-tab-content",children:e.jsx(RS,{request:E,apiRequest:M,currentUserId:ce,isInitiator:_,needsClosure:Kt,conclusionRemark:rt,setConclusionRemark:st,conclusionLoading:gt,conclusionSubmitting:qt,aiGenerated:Et,handleGenerateConclusion:ga,handleFinalizeConclusion:fa,generationAttempts:Ma,generationFailed:Ca,maxAttemptsReached:wt})}),ya&&e.jsx(St,{value:"summary",className:"mt-0","data-testid":"summary-tab-content",children:e.jsx(iT,{summary:p,loading:y,onShare:_a,isInitiator:_})}),e.jsx(St,{value:"workflow",className:"mt-0",children:e.jsx(QS,{request:E,user:O,isInitiator:_,onSkipApprover:bt=>{if(!bt.levelId){alert("Level ID not available");return}q(bt),Fs(!0)},onRefresh:j,documentPolicy:Te})}),Z&&e.jsx(St,{value:"io",className:"mt-0",children:e.jsx(JS,{request:E,apiRequest:M,onRefresh:j})}),e.jsx(St,{value:"documents",className:"mt-0",children:e.jsx(aT,{request:E,workNoteAttachments:z,uploadingDocument:Y,documentPolicy:Te,triggerFileInput:G,setPreviewDocument:me,downloadDocument:bs})}),e.jsx(St,{value:"activity",className:"mt-0",children:e.jsx(rT,{request:E})}),e.jsx(St,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:o!=="worknotes",children:e.jsx(nT,{requestId:n,requestTitle:E.title,mergedMessages:I,setWorkNoteAttachments:X,isInitiator:_,isSpectator:$,currentLevels:La,onAddApprover:Ke,maxApprovalLevels:S.maxApprovalLevels,onPolicyViolation:bt=>R({open:!0,violations:bt})})})]}),o!=="worknotes"&&e.jsx(oT,{request:E,isInitiator:_,isSpectator:$,currentApprovalLevel:Wi(M)?null:U,onAddApprover:()=>$e(!0),onAddSpectator:()=>kt(!0),onApprove:()=>J(!0),onReject:()=>xt(!0),onPause:Ja,onResume:qa,onRetrigger:tr,summaryId:u,refreshTrigger:b,pausedByUserId:(rr=(Vs=E==null?void 0:E.pauseInfo)==null?void 0:Vs.pausedBy)==null?void 0:rr.userId,currentUserId:ce,apiRequest:M})]})]})]})}),c&&u&&e.jsx(Xp,{isOpen:c,onClose:()=>m(!1),summaryId:u,requestTitle:(E==null?void 0:E.title)||"N/A",onSuccess:()=>{j(),v(bt=>bt+1)}}),A&&(M==null?void 0:M.requestId)&&e.jsx(Qp,{isOpen:A,onClose:()=>w(!1),requestId:M.requestId,levelId:(U==null?void 0:U.levelId)||null,onSuccess:sr}),T&&(M==null?void 0:M.requestId)&&e.jsx(Jp,{isOpen:T,onClose:()=>k(!1),requestId:M.requestId,onSuccess:er}),L&&(M==null?void 0:M.requestId)&&e.jsx(qp,{isOpen:L,onClose:()=>D(!1),requestId:M.requestId,approverName:(ca=(nr=E==null?void 0:E.pauseInfo)==null?void 0:nr.pausedBy)==null?void 0:ca.name,onSuccess:ar}),e.jsx(cT,{showApproveModal:Le,showRejectModal:Oe,showAddApproverModal:je,showAddSpectatorModal:yt,showSkipApproverModal:lt,showActionStatusModal:qs,previewDocument:ie,documentError:Se,request:E,skipApproverData:Qa,actionStatus:we,existingParticipants:se,currentLevels:La,maxApprovalLevels:S.maxApprovalLevels,onPolicyViolation:bt=>R({open:!0,violations:bt}),setShowApproveModal:J,setShowRejectModal:xt,setShowAddApproverModal:$e,setShowAddSpectatorModal:kt,setShowSkipApproverModal:Fs,setShowActionStatusModal:wa,setPreviewDocument:me,setDocumentError:re,setSkipApproverData:q,setActionStatus:ee,handleApproveConfirm:Be,handleRejectConfirm:tt,handleAddApprover:Ke,handleAddSpectator:Je,handleSkipApprover:Me,downloadDocument:bs,documentPolicy:Te}),e.jsx(_n,{open:P.open,onClose:()=>R({open:!1,violations:[]}),violations:P.violations,policyDetails:{maxApprovalLevels:S.maxApprovalLevels,maxParticipants:S.maxParticipants,allowSpectators:S.allowSpectators,maxSpectators:S.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(Pe,{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(Js,{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 uT(t){return e.jsx(dT,{children:e.jsx(mT,{...t})})}function xT({onNavigate:t,onNewRequest:s}){const[a,r]=h.useState(!0),[n,i]=h.useState(!1),[l,o]=h.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}),[d,c]=h.useState([]),[m,u]=h.useState("all"),[x,p]=h.useState(),[g,y]=h.useState(),f=async(R=!1)=>{try{R?i(!0):r(!0);const O=await GS(m||"all",x,g);o(O.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}),c(O.categoryData||[])}catch(O){console.error("[DealerDashboard] Error fetching data:",O),Q.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}),c([])}finally{r(!1),i(!1)}};h.useEffect(()=>{f()},[]);const b=(R,O=!1)=>{if(R==null||isNaN(R))return"₹0";const E=typeof R=="string"?parseFloat(R):Number(R);return E<=0?"₹0":O||E<1e4?`₹${Math.round(E).toLocaleString("en-IN")}`:E>=1e5?`₹${(E/1e5).toFixed(1)}L`:E>=1e3?`₹${(E/1e3).toFixed(1)}K`:`₹${Math.round(E).toLocaleString("en-IN")}`},v=R=>R.toLocaleString("en-IN"),A=()=>l.totalClaims===0?0:(l.approved/l.totalClaims*100).toFixed(1),w=()=>l.approved===0?0:(l.credited/l.approved*100).toFixed(1),T=h.useMemo(()=>{const R=d.reduce((O,E)=>O+E.raised,0);return R===0?[]:d.map(O=>({name:O.activityType.length>20?O.activityType.substring(0,20)+"...":O.activityType,value:O.raised,fullName:O.activityType,percentage:(O.raised/R*100).toFixed(0)}))},[d]),k=h.useMemo(()=>d.map(R=>({name:R.activityType.length>15?R.activityType.substring(0,15)+"...":R.activityType,fullName:R.activityType,Raised:R.raised,Approved:R.approved,Rejected:R.rejected,Pending:R.pending})),[d]),L=h.useMemo(()=>d.map(R=>({name:R.activityType.length>15?R.activityType.substring(0,15)+"...":R.activityType,fullName:R.activityType,Raised:R.raisedValue,Approved:R.approvedValue,Credited:R.creditedValue})),[d]),D=["#166534","#15803d","#16a34a","#22c55e","#4ade80","#86efac","#bbf7d0"],S=h.useMemo(()=>d.length===0?null:d.reduce((R,O)=>O.approvalRate>((R==null?void 0:R.approvalRate)||0)?O:R),[d]),N=h.useMemo(()=>d.length===0?null:d.reduce((R,O)=>O.raisedValue>((R==null?void 0:R.raisedValue)||0)?O:R),[d]);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(Bt,{className:"w-8 h-8 animate-spin text-blue-600"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading dashboard..."})]})}):l.totalClaims===0&&d.length===0?e.jsxs("div",{className:"space-y-6 max-w-[1600px] mx-auto p-4",children:[e.jsxs(te,{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(as,{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(Pe,{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(Bt,{className:`w-5 h-5 mr-2 ${n?"animate-spin":""}`}),"Refresh"]})]})]})})})]}),e.jsx(te,{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(Ll,{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(Pe,{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(Bt,{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(te,{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(as,{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(Xe,{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(Pe,{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(di,{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(te,{className:"border-l-4 border-l-blue-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(ue,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(xe,{className:"text-sm text-muted-foreground",children:"Raised Claims"}),e.jsx("div",{className:"p-2 rounded-lg bg-blue-50",children:e.jsx(Pe,{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:b(l.totalValue,!0)})]})]}),e.jsxs(te,{className:"border-l-4 border-l-green-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(ue,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(xe,{className:"text-sm text-muted-foreground",children:"Approved"}),e.jsx("div",{className:"p-2 rounded-lg bg-green-50",children:e.jsx(De,{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(Ks,{className:"h-3 w-3 text-green-600"}),e.jsxs("p",{className:"text-xs text-green-600",children:[A(),"% approval rate"]})]})]})]}),e.jsxs(te,{className:"border-l-4 border-l-red-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(ue,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(xe,{className:"text-sm text-muted-foreground",children:"Rejected"}),e.jsx("div",{className:"p-2 rounded-lg bg-red-50",children:e.jsx(jt,{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(m0,{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(te,{className:"border-l-4 border-l-orange-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(ue,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(xe,{className:"text-sm text-muted-foreground",children:"Pending"}),e.jsx("div",{className:"p-2 rounded-lg bg-orange-50",children:e.jsx(Xe,{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:b(l.pendingValue)})]})]}),e.jsxs(te,{className:"border-l-4 border-l-emerald-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(ue,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(xe,{className:"text-sm text-muted-foreground",children:"Credited"}),e.jsx("div",{className:"p-2 rounded-lg bg-emerald-50",children:e.jsx(u0,{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(Ks,{className:"h-3 w-3 text-emerald-600"}),e.jsxs("p",{className:"text-xs text-emerald-600",children:[w(),"% credit rate"]})]})]})]}),e.jsxs(te,{className:"border-l-4 border-l-amber-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(ue,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(xe,{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:b(l.pendingCreditValue)})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(te,{className:"shadow-lg",children:[e.jsx(ue,{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(Ll,{className:"h-5 w-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(xe,{children:"Claims Distribution by Activity Type"}),e.jsx(ke,{children:"Total claims raised across activity types"})]})]})}),e.jsxs(ae,{children:[e.jsx(Ir,{width:"100%",height:300,children:e.jsxs(Vu,{children:[e.jsx(zu,{data:T,cx:"50%",cy:"50%",labelLine:!1,label:({name:R,percentage:O})=>`${R}: ${O}%`,outerRadius:80,fill:"#8884d8",dataKey:"value",children:T.map((R,O)=>e.jsx(Hu,{fill:D[O%D.length]},`cell-${O}`))}),e.jsx(Er,{})]})}),e.jsx("div",{className:"grid grid-cols-3 gap-2 mt-4",children:T.slice(0,3).map((R,O)=>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:D[O%D.length]}}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-600",children:R.name}),e.jsx("p",{className:"text-sm text-gray-900",children:v(R.value)})]})]},O))})]})]}),e.jsxs(te,{className:"shadow-lg",children:[e.jsx(ue,{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(di,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(xe,{children:"Claims Status by Activity Type"}),e.jsx(ke,{children:"Count comparison across workflow stages"})]})]})}),e.jsx(ae,{children:e.jsx(Ir,{width:"100%",height:300,children:e.jsxs(Fl,{data:k,children:[e.jsx(ai,{strokeDasharray:"3 3"}),e.jsx(ri,{dataKey:"name"}),e.jsx(ni,{}),e.jsx(Er,{}),e.jsx(ii,{}),e.jsx(ba,{dataKey:"Raised",fill:"#3b82f6"}),e.jsx(ba,{dataKey:"Approved",fill:"#22c55e"}),e.jsx(ba,{dataKey:"Rejected",fill:"#ef4444"}),e.jsx(ba,{dataKey:"Pending",fill:"#f59e0b"})]})})})]})]}),e.jsxs(te,{className:"shadow-lg",children:[e.jsx(ue,{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(Dt,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsx(xe,{children:"Detailed Activity Type Breakdown"}),e.jsx(ke,{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(Ir,{width:"100%",height:350,children:e.jsxs(Fl,{data:L,children:[e.jsx(ai,{strokeDasharray:"3 3"}),e.jsx(ri,{dataKey:"name"}),e.jsx(ni,{tickFormatter:R=>b(R)}),e.jsx(Er,{formatter:R=>b(R),labelFormatter:R=>R}),e.jsx(ii,{}),e.jsx(ba,{dataKey:"Raised",fill:"#3b82f6"}),e.jsx(ba,{dataKey:"Approved",fill:"#22c55e"}),e.jsx(ba,{dataKey:"Credited",fill:"#10b981"})]})})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mt-6",children:d.slice(0,3).map((R,O)=>e.jsxs(te,{className:"shadow-md hover:shadow-lg transition-shadow",children:[e.jsx(ue,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(xe,{className:"text-base",children:R.activityType}),e.jsxs(ne,{className:"bg-emerald-50 text-emerald-700 border-emerald-200",children:[R.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(R.raised)," (",b(R.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(R.approved)," (",b(R.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(R.rejected)," (",b(R.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(R.pending)," (",b(R.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(R.credited)," (",b(R.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(R.pendingCredit)," (",b(R.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:[R.creditRate.toFixed(1),"%"]})]}),e.jsx(la,{value:R.creditRate,className:"h-2"})]})]})]},O))})]})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsx(te,{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(Vt,{className:"h-6 w-6 text-green-600"})}),e.jsx(Ks,{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:(S==null?void 0:S.activityType)||"N/A"}),e.jsxs("p",{className:"text-sm text-green-600",children:[(S==null?void 0:S.approvalRate.toFixed(2))||0,"% approval rate"]})]})}),e.jsx(te,{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(Dt,{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:(N==null?void 0:N.activityType)||"N/A"}),e.jsxs("p",{className:"text-sm text-blue-600",children:[N?b(N.raisedValue,!0):"₹0"," raised"]})]})}),e.jsx(te,{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(wi,{className:"h-6 w-6 text-emerald-600"})}),e.jsx(De,{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(te,{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(tx,{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:[b(l.pendingCreditValue)," awaiting credit"]})]})})]})]})}function hT({searchTerm:t,sortBy:s,sortOrder:a,onSearchChange:r,onSortByChange:n,onSortOrderChange:i,onClearFilters:l,activeFiltersCount:o,...d}){return e.jsxs(te,{className:"shadow-lg border-0",children:[e.jsx(ue,{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(Ya,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(ke,{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(As,{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(_e,{placeholder:"Search requests, IDs...",value:t,onChange:c=>r(c.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(Ve,{value:s,onValueChange:c=>n(c),children:[e.jsx(He,{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(ze,{placeholder:"Sort by"})}),e.jsxs(We,{children:[e.jsx(K,{value:"due",children:"Due Date"}),e.jsx(K,{value:"created",children:"Date Created"}),e.jsx(K,{value:"priority",children:"Priority"}),e.jsx(K,{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(Di,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(Pi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function pT({searchTerm:t,statusFilter:s="all",sortBy:a,sortOrder:r,onSearchChange:n,onStatusChange:i,onSortByChange:l,onSortOrderChange:o,onClearFilters:d,activeFiltersCount:c,...m}){return e.jsxs(te,{className:"shadow-lg border-0","data-testid":"dealer-closed-requests-filters",children:[e.jsx(ue,{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(Ya,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(ke,{className:"text-xs sm:text-sm",children:c>0&&e.jsxs("span",{className:"text-blue-600 font-medium",children:[c," filter",c>1?"s":""," active"]})})]})]}),c>0&&e.jsxs(F,{variant:"ghost",size:"sm",onClick:d,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(As,{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(_e,{placeholder:"Search requests, IDs...",value:t,onChange:u=>n(u.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(Ve,{value:s,onValueChange:i,children:[e.jsx(He,{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(ze,{placeholder:"Closure Type"})}),e.jsxs(We,{children:[e.jsx(K,{value:"all",children:"All Closures"}),e.jsx(K,{value:"approved",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(De,{className:"w-4 h-4 text-green-600"}),e.jsx("span",{children:"Closed After Approval"})]})}),e.jsx(K,{value:"rejected",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jt,{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(Ve,{value:a,onValueChange:u=>l(u),children:[e.jsx(He,{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(ze,{placeholder:"Sort by"})}),e.jsxs(We,{children:[e.jsx(K,{value:"due",children:"Due Date"}),e.jsx(K,{value:"created",children:"Date Created"}),e.jsx(K,{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(Di,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(Pi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function gT({searchTerm:t,statusFilter:s,initiatorFilter:a,approverFilter:r,approverFilterType:n,dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:d,initiatorSearch:c,approverSearch:m,onSearchChange:u,onStatusChange:x,onInitiatorChange:p,onApproverChange:g,onApproverTypeChange:y,onDateRangeChange:f,onCustomStartDateChange:b,onCustomEndDateChange:v,onShowCustomDatePickerChange:A,onApplyCustomDate:w,onClearFilters:T,hasActiveFilters:k,...L}){return e.jsx(te,{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(Ya,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Filters"}),k&&e.jsx(ne,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),k&&e.jsxs(F,{variant:"ghost",size:"sm",onClick:T,className:"gap-2",children:[e.jsx(Bt,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Gt,{}),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(As,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(_e,{placeholder:"Search requests...",value:t,onChange:D=>u(D.target.value),className:"pl-10 h-10","data-testid":"dealer-search-input"})]}),e.jsxs(Ve,{value:s,onValueChange:x,children:[e.jsx(He,{className:"h-10","data-testid":"dealer-status-filter",children:e.jsx(ze,{placeholder:"All Status"})}),e.jsxs(We,{children:[e.jsx(K,{value:"all",children:"All Status"}),e.jsx(K,{value:"pending",children:"Pending"}),e.jsx(K,{value:"paused",children:"Paused"}),e.jsx(K,{value:"approved",children:"Approved"}),e.jsx(K,{value:"rejected",children:"Rejected"}),e.jsx(K,{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(le,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:c.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:c.selectedUser.displayName||c.selectedUser.email}),e.jsx(F,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:c.handleClear,children:e.jsx(ft,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(_e,{placeholder:"Search initiator...",value:c.searchQuery,onChange:D=>c.handleSearch(D.target.value),onFocus:()=>{c.searchResults.length>0&&c.setShowResults(!0)},onBlur:()=>setTimeout(()=>c.setShowResults(!1),200),className:"h-10","data-testid":"dealer-initiator-search-input"}),c.showResults&&c.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:c.searchResults.map(D=>e.jsx("button",{type:"button",onClick:()=>c.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(le,{className:"text-sm font-medium text-gray-700",children:"Approver"}),r!=="all"&&y&&e.jsxs(Ve,{value:n,onValueChange:D=>y(D),children:[e.jsx(He,{className:"h-7 w-32 text-xs",children:e.jsx(ze,{})}),e.jsxs(We,{children:[e.jsx(K,{value:"current",children:"Current Only"}),e.jsx(K,{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(_e,{placeholder:"Search approver...",value:m.searchQuery,onChange:D=>m.handleSearch(D.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(D=>e.jsx("button",{type:"button",onClick:()=>m.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(it,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ve,{value:i,onValueChange:D=>f(D),children:[e.jsx(He,{className:"w-[160px] h-10",children:e.jsx(ze,{placeholder:"Date Range"})}),e.jsxs(We,{children:[e.jsx(K,{value:"all",children:"All Time"}),e.jsx(K,{value:"today",children:"Today"}),e.jsx(K,{value:"week",children:"This Week"}),e.jsx(K,{value:"month",children:"This Month"}),e.jsx(K,{value:"last7days",children:"Last 7 Days"}),e.jsx(K,{value:"last30days",children:"Last 30 Days"}),e.jsx(K,{value:"custom",children:"Custom Range"})]})]}),i==="custom"&&e.jsxs(Ys,{open:d,onOpenChange:A,children:[e.jsx(Zs,{asChild:!0,children:e.jsxs(F,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(it,{className:"w-4 h-4"}),l&&o?`${Ye(l,"MMM d, yyyy")} - ${Ye(o,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Xs,{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(le,{htmlFor:"start-date",children:"Start Date"}),e.jsx($s,{value:l||null,onChange:D=>{const S=D?new Date(D):void 0;S?(b==null||b(S),o&&S>o&&(v==null||v(S))):b==null||b(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{htmlFor:"end-date",children:"End Date"}),e.jsx($s,{value:o||null,onChange:D=>{const S=D?new Date(D):void 0;S?(v==null||v(S),l&&S<l&&(b==null||b(S))):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:()=>{A==null||A(!1),b==null||b(void 0),v==null||v(void 0),f("month")},children:"Cancel"})]})]})})]})]})]})})})}function fT(t){switch(t){case"DEALER_CLAIM":return uT;case"CUSTOM":default:return AS}}function yT(t){switch(t){case"DEALER":return hT;case"STANDARD":default:return SS}}function bT(t){switch(t){case"DEALER":return pT;case"STANDARD":default:return TS}}function vT(t){switch(t){case"DEALER":return gT;case"STANDARD":default:return kS}}const jT=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:pa,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Vt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Vt,iconColor:"text-gray-600"}}},NT=t=>{switch(t){case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:Xe,iconColor:"text-yellow-600",label:"Pending"};case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:Ge,iconColor:"text-green-600",label:"Needs Closure"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:jt,iconColor:"text-red-600",label:"Rejected"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:De,iconColor:"text-gray-600",label:"Closed"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ge,iconColor:"text-gray-600",label:t}}};function wT({onViewRequest:t}){const[s,a]=h.useState([]),[r,n]=h.useState(!1),[i,l]=h.useState(!1),[o,d]=h.useState(1),[c,m]=h.useState(0),[u]=h.useState(10),x=h.useRef(null),p=Vj(),g=h.useMemo(()=>{try{const S=at.getUserData();return _o(S)}catch(S){return console.error("[OpenRequests] Error getting user filter type:",S),"STANDARD"}},[]),y=h.useMemo(()=>yT(g),[g]),f=g==="DEALER",b=S=>({search:p.searchTerm||void 0,status:S&&!f&&p.statusFilter!=="all"?p.statusFilter:void 0,priority:!f&&p.priorityFilter!=="all"?p.priorityFilter:void 0,templateType:!f&&p.templateTypeFilter!=="all"?p.templateTypeFilter:void 0,sortBy:p.sortBy,sortOrder:p.sortOrder}),v=h.useCallback(async(S=1,N)=>{try{S===1&&(n(!0),a([]));const P=await Is.listOpenForMe({page:S,limit:u,search:N==null?void 0:N.search,status:N==null?void 0:N.status,priority:N==null?void 0:N.priority,templateType:N==null?void 0:N.templateType,sortBy:N==null?void 0:N.sortBy,sortOrder:N==null?void 0:N.sortOrder}),R=Array.isArray(P==null?void 0:P.data)?P.data:[],O=P==null?void 0:P.pagination;O&&(p.setCurrentPage(O.page||1),d(O.totalPages||1),m(O.total||0));const E=R.map(M=>{var C,j,U,$;const B=M.submittedAt||M.submitted_at||M.createdAt||M.created_at;return{id:M.requestNumber||M.request_number||M.requestId,requestId:M.requestId,displayId:M.requestNumber||M.request_number||M.requestId,title:M.title,description:M.description,status:(M.status||"").toString().toLowerCase().replace("_","-"),priority:(M.priority||"").toString().toLowerCase(),initiator:{name:((C=M.initiator)==null?void 0:C.displayName)||((j=M.initiator)==null?void 0:j.email)||"—",avatar:(((U=M.initiator)==null?void 0:U.displayName)||(($=M.initiator)==null?void 0:$.email)||"NA").split(" ").map(_=>_[0]).join("").slice(0,2).toUpperCase()},currentApprover:M.currentApprover?{name:M.currentApprover.name||M.currentApprover.email||"—",avatar:(M.currentApprover.name||M.currentApprover.email||"CA").split(" ").map(_=>_[0]).join("").slice(0,2).toUpperCase(),sla:M.currentApprover.sla}:void 0,createdAt:B||"—",approvalStep:M.currentLevel?`Step ${M.currentLevel} of ${M.totalLevels||"?"}`:void 0,department:M.department,currentLevelSLA:M.currentLevelSLA,templateType:M.templateType||M.template_type}});a(E)}finally{n(!1),l(!1)}},[u,p]);x.current=v;const A=h.useCallback(()=>{l(!0),v(p.currentPage,b(!0))},[p.currentPage,v]),w=h.useCallback(S=>{S>=1&&S<=o&&(p.setCurrentPage(S),v(S,b(!0)))},[o,p,v]),T=()=>{const S=[];let P=Math.max(1,p.currentPage-Math.floor(2.5)),R=Math.min(o,P+5-1);R-P<4&&(P=Math.max(1,R-5+1));for(let O=P;O<=R;O++)S.push(O);return S},k=h.useRef(!1);h.useEffect(()=>{if(!k.current){k.current=!0;const S=p.currentPage||1;v(S,b(!0))}},[]);const L=h.useRef({searchTerm:p.searchTerm,statusFilter:p.statusFilter,priorityFilter:p.priorityFilter,templateTypeFilter:p.templateTypeFilter,sortBy:p.sortBy,sortOrder:p.sortOrder,isDealer:f});h.useEffect(()=>{if(!k.current)return;const S=L.current;if(!(S.searchTerm!==p.searchTerm||S.statusFilter!==p.statusFilter||S.priorityFilter!==p.priorityFilter||S.templateTypeFilter!==p.templateTypeFilter||S.sortBy!==p.sortBy||S.sortOrder!==p.sortOrder||S.isDealer!==f))return;const P=setTimeout(()=>{p.setCurrentPage(1),v(1,b(!0)),L.current={searchTerm:p.searchTerm,statusFilter:p.statusFilter,priorityFilter:p.priorityFilter,templateTypeFilter:p.templateTypeFilter,sortBy:p.sortBy,sortOrder:p.sortOrder,isDealer:f}},p.searchTerm?500:0);return()=>clearTimeout(P)},[p.searchTerm,p.statusFilter,p.priorityFilter,p.templateTypeFilter,p.sortBy,p.sortOrder,f]);const D=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(Pe,{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(ne,{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…":`${c||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:A,disabled:i,children:[e.jsx(Bt,{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(y,{searchTerm:p.searchTerm,statusFilter:p.statusFilter,priorityFilter:p.priorityFilter,templateTypeFilter:p.templateTypeFilter,sortBy:p.sortBy,sortOrder:p.sortOrder,onSearchChange:p.setSearchTerm,onStatusFilterChange:p.setStatusFilter,onPriorityFilterChange:p.setPriorityFilter,onTemplateTypeFilterChange:p.setTemplateTypeFilter,onSortByChange:p.setSortBy,onSortOrderChange:p.setSortOrder,onClearFilters:p.clearFilters,activeFiltersCount:p.activeFiltersCount}),e.jsx("div",{className:"space-y-3",children:D.map(S=>{const N=jT(S.priority),P=NT(S.status);return e.jsx(te,{className:"group hover:shadow-lg transition-all duration-200 cursor-pointer border border-gray-200 hover:border-blue-400 hover:scale-[1.002]",onClick:()=>t==null?void 0:t(S.id,S.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 ${N.color} border shadow-sm`,children:e.jsx(N.icon,{className:`w-5 h-5 ${N.iconColor}`})})}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-2.5",children:[e.jsxs("div",{className:"flex items-center gap-2.5 flex-wrap",children:[e.jsx("h3",{className:"text-base font-bold text-gray-900 group-hover:text-blue-600 transition-colors",children:S.displayId||S.id}),e.jsxs(ne,{variant:"outline",className:`${P.color} text-xs px-2.5 py-0.5 font-semibold shrink-0`,children:[e.jsx(P.icon,{className:"w-3.5 h-3.5 mr-1"}),P.label||S.status]}),S.department&&e.jsx(ne,{variant:"secondary",className:"bg-blue-50 text-blue-700 text-xs px-2.5 py-0.5 hidden sm:inline-flex",children:S.department}),e.jsx(ne,{variant:"outline",className:`${N.color} text-xs px-2.5 py-0.5 capitalize hidden md:inline-flex`,children:S.priority}),(()=>{const R=(S==null?void 0:S.templateType)||(S==null?void 0:S.template_type)||"",O=(R==null?void 0:R.toUpperCase())||"";let E="Non-Templatized",M="bg-purple-100 !text-purple-600 border-purple-200";return O==="DEALER CLAIM"?(E="Dealer Claim",M="bg-blue-100 !text-blue-700 border-blue-200"):O==="TEMPLATE"&&(E="Template"),e.jsx(ne,{variant:"outline",className:`${M} text-xs px-2.5 py-0.5 shrink-0 hidden md:inline-flex`,"data-testid":"template-type-badge",children:E})})()]}),e.jsx("h4",{className:"text-sm font-semibold text-gray-800 line-clamp-1 leading-relaxed",children:S.title}),S.currentLevelSLA&&(()=>{var B;const R=!!(S.isPaused||(B=S.pauseInfo)!=null&&B.isPaused||S.status==="paused"),O=S.currentLevelSLA.percentageUsed||0,M=R?{bg:"bg-gray-100 border border-gray-300",progress:"bg-gray-500",text:"text-gray-600",icon:"text-gray-600"}:O>=100?{bg:"bg-red-50 border border-red-200",progress:"bg-red-600",text:"text-red-600",icon:"text-blue-600"}:O>=75?{bg:"bg-orange-50 border border-orange-200",progress:"bg-orange-500",text:"text-orange-600",icon:"text-blue-600"}:O>=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 ${M.bg}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[R?e.jsx(yn,{className:`w-3.5 h-3.5 ${M.icon}`}):e.jsx(Xe,{className:`w-3.5 h-3.5 ${M.icon}`}),e.jsxs("span",{className:"text-xs font-medium text-gray-900",children:["TAT: ",O,"% ",R&&"(paused)"]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"text-gray-600",children:S.currentLevelSLA.elapsedText}),e.jsxs("span",{className:`font-semibold ${M.text}`,children:[S.currentLevelSLA.remainingText," left"]})]})]}),e.jsx(la,{value:O,className:"h-1.5",indicatorClassName:M.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(rs,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(ns,{className:"bg-gradient-to-br from-slate-700 to-slate-900 text-white text-[10px] font-bold",children:S.initiator.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:S.initiator.name})]}),S.currentApprover&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(rs,{className:"h-6 w-6 ring-2 ring-yellow-200 shadow-sm",children:e.jsx(ns,{className:"bg-yellow-500 text-white text-[10px] font-bold",children:S.currentApprover.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:S.currentApprover.name})]}),S.approvalStep&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ge,{className:"w-3.5 h-3.5 text-blue-500"}),e.jsx("span",{className:"font-medium",children:S.approvalStep})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(it,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",S.createdAt!=="—"?ha(S.createdAt):"—"]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(ds,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})},S.id)})}),D.length===0&&e.jsx(te,{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(Pe,{className:"h-8 w-8 text-gray-400"})}),e.jsx("h3",{className:"text-xl font-semibold text-gray-900 mb-2",children:"No requests found"}),e.jsx("p",{className:"text-gray-600 text-center max-w-md",children:p.searchTerm||p.activeFiltersCount>0?"Try adjusting your filters or search terms to see more results.":"No open requests available at the moment."}),p.activeFiltersCount>0&&e.jsx(F,{variant:"outline",className:"mt-4",onClick:p.clearFilters,children:"Clear all filters"})]})}),o>1&&!r&&e.jsx(te,{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 ",(p.currentPage-1)*u+1," to ",Math.min(p.currentPage*u,c)," of ",c," open requests"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(F,{variant:"outline",size:"sm",onClick:()=>w(p.currentPage-1),disabled:p.currentPage===1,className:"h-8 w-8 p-0",children:e.jsx(ds,{className:"h-4 w-4 rotate-180"})}),p.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:"..."})]}),T().map(S=>e.jsx(F,{variant:S===p.currentPage?"default":"outline",size:"sm",onClick:()=>w(S),className:`h-8 w-8 p-0 ${S===p.currentPage?"bg-re-green text-white hover:bg-re-green/90":""}`,children:S},S)),p.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(p.currentPage+1),disabled:p.currentPage===o,className:"h-8 w-8 p-0",children:e.jsx(ds,{className:"h-4 w-4"})})]})]})})})]})}function CT({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(Pe,{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(ne,{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(Bt,{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 AT(t){switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:pa,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Vt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Vt,iconColor:"text-gray-600"}}}function ST(t){switch(t){case"closed":return{color:"bg-slate-100 text-slate-800 border-slate-300",icon:De,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:jt,iconColor:"text-red-600",label:"Rejected",description:"Request was declined"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ge,iconColor:"text-gray-600",label:t,description:""}}}function TT({request:t,onViewRequest:s}){const a=AT(t.priority),r=ST(t.status),n=a.icon,i=r.icon;return e.jsx(te,{className:"group hover:shadow-lg transition-all duration-200 cursor-pointer border border-gray-200 hover:border-blue-400 hover:scale-[1.002]",onClick:()=>s==null?void 0:s(t.id,t.title),"data-testid":`closed-request-card-${t.id}`,children:e.jsx(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(ne,{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(ne,{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(ne,{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 d="Non-Templatized",c="bg-purple-100 !text-purple-600 border-purple-200";return o==="DEALER CLAIM"?(d="Dealer Claim",c="bg-blue-100 !text-blue-700 border-blue-200"):o==="TEMPLATE"&&(d="Template"),e.jsx(ne,{variant:"outline",className:`${c} text-xs px-2.5 py-0.5 shrink-0 hidden md:inline-flex`,"data-testid":"template-type-badge",children:d})})()]}),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(rs,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(ns,{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(De,{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(it,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",t.createdAt!=="—"?ha(t.createdAt,!0):"—"]})]}),t.dueDate&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(De,{className:"w-3.5 h-3.5 text-slate-600"}),e.jsxs("span",{className:"font-medium",children:["Closed: ",ha(t.dueDate,!0)]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(ds,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})})}function kT({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(TT,{request:r,onViewRequest:a},r.id))})}function RT({searchTerm:t,activeFiltersCount:s,onClearFilters:a}){return e.jsx(te,{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(Pe,{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 DT(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 PT({pagination:t,onPageChange:s}){const{currentPage:a,totalPages:r,totalRecords:n,itemsPerPage:i}=t;if(r<=1)return null;const l=DT(a,r);return e.jsx(te,{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(ds,{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(ds,{className:"h-4 w-4"})})]})]})})})}function IT(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 ET(t){return t.map(IT)}function FT({itemsPerPage:t=10}={}){const[s,a]=h.useState([]),[r,n]=h.useState(!1),[i,l]=h.useState(!1),[o,d]=h.useState({currentPage:1,totalPages:1,totalRecords:0,itemsPerPage:t}),c=h.useCallback(async(u=1,x)=>{try{u===1&&(n(!0),a([]));const p=await Is.listClosedByMe({page:u,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(p==null?void 0:p.data)?p.data:[],y=ET(g);a(y);const f=p==null?void 0:p.pagination;f&&d({currentPage:f.page||1,totalPages:f.totalPages||1,totalRecords:f.total||0,itemsPerPage:t})}catch(p){console.error("[ClosedRequests] Error fetching requests:",p),a([])}finally{n(!1),l(!1)}},[t]),m=h.useCallback(u=>{l(!0),c(o.currentPage,u)},[c,o.currentPage]);return{requests:s,loading:r,refreshing:i,pagination:o,fetchRequests:c,handleRefresh:m}}const MT={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",sortBy:"created",sortOrder:"desc",currentPage:1},tg=zr({name:"closedRequests",initialState:MT,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:_T,setStatusFilter:LT,setPriorityFilter:OT,setTemplateTypeFilter:$T,setSortBy:UT,setSortOrder:BT,setCurrentPage:VT,clearFilters:zT}=tg.actions;function HT({onFiltersChange:t,debounceMs:s=500}={}){const a=kn(),r=h.useRef(null),n=h.useRef(!0),{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:d,sortBy:c,sortOrder:m,currentPage:u}=Wr(k=>k.closedRequests),x=h.useCallback(k=>a(_T(k)),[a]),p=h.useCallback(k=>a(LT(k)),[a]),g=h.useCallback(k=>a(OT(k)),[a]),y=h.useCallback(k=>a($T(k)),[a]),f=h.useCallback(k=>a(UT(k)),[a]),b=h.useCallback(k=>a(BT(k)),[a]),v=h.useCallback(k=>a(VT(k)),[a]),A=h.useCallback(()=>({search:i,status:l,priority:o,templateType:d!=="all"?d:void 0,sortBy:c,sortOrder:m}),[i,l,o,d,c,m]);h.useEffect(()=>{if(n.current){n.current=!1;return}r.current&&clearTimeout(r.current);const k=setTimeout(()=>{t&&t(A())},i?s:0);return r.current=k,()=>{r.current&&clearTimeout(r.current)}},[i,l,o,d,c,m,t,A,s]);const w=h.useCallback(()=>{a(zT())},[a]),T=[i,o!=="all"?o:null,l!=="all"?l:null,d!=="all"?d:null].filter(Boolean).length;return{searchTerm:i,priorityFilter:o,statusFilter:l,templateTypeFilter:d,sortBy:c,sortOrder:m,currentPage:u,setSearchTerm:x,setPriorityFilter:g,setStatusFilter:p,setTemplateTypeFilter:y,setSortBy:f,setSortOrder:b,setCurrentPage:v,clearFilters:w,activeFiltersCount:T,getFilters:A}}function WT({onViewRequest:t}){const s=FT({itemsPerPage:10}),a=h.useRef(s.fetchRequests);a.current=s.fetchRequests;const r=HT(),n=h.useMemo(()=>{try{const u=at.getUserData();return _o(u)}catch(u){return console.error("[ClosedRequests] Error getting user filter type:",u),"STANDARD"}},[]),i=h.useMemo(()=>bT(n),[n]),l=n==="DEALER",o=h.useRef({searchTerm:r.searchTerm,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,templateTypeFilter:r.templateTypeFilter,sortBy:r.sortBy,sortOrder:r.sortOrder}),d=h.useRef(!1);h.useEffect(()=>{const u=r.currentPage||1;a.current(u,{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}),d.current=!0},[l]),h.useEffect(()=>{if(!d.current)return;const u=o.current;if(!(u.searchTerm!==r.searchTerm||u.statusFilter!==r.statusFilter||u.priorityFilter!==r.priorityFilter||u.templateTypeFilter!==r.templateTypeFilter||u.sortBy!==r.sortBy||u.sortOrder!==r.sortOrder))return;const p=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!==u.searchTerm?500:0);return()=>clearTimeout(p)},[r.searchTerm,r.statusFilter,r.priorityFilter,r.templateTypeFilter,r.sortBy,r.sortOrder,l]);const c=h.useCallback(u=>{u>=1&&u<=s.pagination.totalPages&&(r.setCurrentPage(u),s.fetchRequests(u,{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=h.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(CT,{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(kT,{requests:s.requests,loading:s.loading,onViewRequest:t}),s.requests.length===0&&!s.loading&&e.jsx(RT,{searchTerm:r.searchTerm,activeFiltersCount:r.activeFiltersCount,onClearFilters:r.clearFilters}),!s.loading&&e.jsx(PT,{pagination:s.pagination,onPageChange:c})]})}function GT(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 KT(t){return GT(t)?"DEALER_CLAIM":"CUSTOM"}function YT(t,s){return`/request/${t}`}class ZT extends h.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 XT({requestId:t,onBack:s,dynamicRequests:a=[]}){const n=vr().requestId||t||"",{user:i}=Jt(),{apiRequest:l,loading:o}=yc(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(Bt,{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 d=KT(l),c=fT(d);return e.jsx(c,{requestId:t,onBack:s,dynamicRequests:a})}function QT(t){return e.jsx(ZT,{children:e.jsx(XT,{...t})})}function JT({onViewSummary:t}){const s=Fa(),[a,r]=h.useState([]),[n,i]=h.useState(!0),[l,o]=h.useState(""),[d,c]=h.useState(1),[m,u]=h.useState(1),[x,p]=h.useState(0),g=10,y=h.useCallback(async(A=1)=>{try{i(!0);const w=await rS({page:A,limit:g});r(w.data||[]),u(w.pagination.totalPages||1),p(w.pagination.total||0),c(w.pagination.page||1)}catch(w){console.error("Failed to fetch shared summaries:",w),Q.error("Failed to load shared summaries")}finally{i(!1)}},[]);h.useEffect(()=>{y(1)},[y]);const f=async A=>{try{await Hp(A),r(w=>w.map(T=>T.sharedSummaryId===A?{...T,isRead:!0,viewedAt:new Date().toISOString()}:T)),t?t(A):s(`/shared-summaries/${A}`)}catch(w){console.error("Failed to mark as viewed:",w),t?t(A):s(`/shared-summaries/${A}`)}},b=A=>{A>=1&&A<=m&&y(A)},v=a.filter(A=>{var T,k,L,D;if(!l)return!0;const w=l.toLowerCase();return((T=A.title)==null?void 0:T.toLowerCase().includes(w))||((k=A.requestNumber)==null?void 0:k.toLowerCase().includes(w))||((L=A.initiatorName)==null?void 0:L.toLowerCase().includes(w))||((D=A.sharedByName)==null?void 0:D.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(As,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(_e,{placeholder:"Search by title, request number, or user...",value:l,onChange:A=>o(A.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(Ze,{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(Pe,{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(A=>e.jsx("div",{className:`bg-white rounded-lg shadow-sm border-2 transition-all cursor-pointer hover:shadow-md ${A.isRead?"border-gray-200":"border-blue-300 bg-blue-50"}`,onClick:()=>f(A.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:[A.isRead?e.jsx(x0,{className:"h-4 w-4 text-gray-400 flex-shrink-0"}):e.jsx(ht,{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:A.title}),!A.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:A.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(_t,{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:A.initiatorName})]})]}),e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(_t,{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:A.sharedByName})]})]}),e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(it,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Shared: ",Ye(new Date(A.sharedAt),"MMM dd, yyyy HH:mm")]})]}),A.viewedAt&&e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(ht,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Viewed: ",Ye(new Date(A.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(A.sharedSummaryId)},children:"View"})]})})},A.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 ",(d-1)*g+1," to ",Math.min(d*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:()=>b(d-1),disabled:d===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 ",d," of ",m]}),e.jsx(F,{variant:"outline",size:"sm",onClick:()=>b(d+1),disabled:d===m,className:"text-xs sm:text-sm",children:"Next"})]})]})]})]})})}function qT(){const{sharedSummaryId:t}=vr(),s=Fa(),[a,r]=h.useState(null),[n,i]=h.useState(!0);h.useEffect(()=>{if(!t){s("/shared-summaries");return}(async()=>{var m,u;try{i(!0);try{await Hp(t)}catch(p){console.warn("Failed to mark as viewed:",p)}const x=await bc(t);r(x)}catch(x){console.error("Failed to fetch summary details:",x),Q.error(((u=(m=x==null?void 0:x.response)==null?void 0:m.data)==null?void 0:u.message)||"Failed to load summary"),s("/shared-summaries")}finally{i(!1)}})()},[t,s]);const l=c=>{const m=c.toLowerCase();return m==="approved"?e.jsx(De,{className:"h-4 w-4 text-green-600"}):m==="rejected"?e.jsx(jt,{className:"h-4 w-4 text-red-600"}):m==="pending"||m==="in progress"?e.jsx(Xe,{className:"h-4 w-4 text-orange-600"}):e.jsx(Pe,{className:"h-4 w-4 text-gray-600"})},o=c=>{const m=c.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"},d=(c,m)=>c&&c.trim()&&c.trim().toUpperCase()!=="N/A"?c: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(Ze,{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(Js,{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(ne,{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(ra,{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:d(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:Ye(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((c,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 ",c.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:c.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:d(c.designation,c.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(c.status),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:c.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:Ye(new Date(c.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:c.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:d(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(ne,{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(ra,{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(Pe,{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 e5(){const{requestId:t}=vr(),s=Fa(),a=i=>{s(`/${i}`)},r=()=>{s("/new-request")},n=()=>{s("/login")};return e.jsx(Ns,{currentPage:"work-notes",onNavigate:a,onNewRequest:r,onLogout:n,children:e.jsx("div",{className:"h-full w-full overflow-hidden",children:e.jsx(zp,{requestId:t||""})})})}function sg({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(ne,{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 Hs({label:t,value:s,icon:a,iconColor:r,gradient:n,textColor:i,valueColor:l,testId:o="stats-card",onClick:d}){return e.jsx(te,{className:`${n} border transition-shadow ${d?"cursor-pointer hover:shadow-lg":"hover:shadow-md"}`,"data-testid":o,onClick:d,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 t5({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(Hs,{label:"Total",value:t.total,icon:Pe,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(Hs,{label:"Pending",value:t.pending,icon:Xe,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(Hs,{label:"Paused",value:t.paused,icon:Ha,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(Hs,{label:"Approved",value:t.approved,icon:De,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(Hs,{label:"Rejected",value:t.rejected,icon:jt,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(Hs,{label:"Draft",value:t.draft,icon:Ii,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(Hs,{label:"Closed",value:t.closed,icon:Ei,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 s5({searchTerm:t,statusFilter:s,priorityFilter:a,templateTypeFilter:r,onSearchChange:n,onStatusChange:i,onPriorityChange:l,onTemplateTypeChange:o}){return e.jsx(te,{className:"border-gray-200","data-testid":"my-requests-filters",children:e.jsx(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(As,{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(_e,{placeholder:"Search requests by title, description, or ID...",value:t,onChange:d=>n(d.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(Ve,{value:s,onValueChange:i,children:[e.jsx(He,{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(ze,{placeholder:"Status"})}),e.jsxs(We,{children:[e.jsx(K,{value:"all",children:"All Status"}),e.jsx(K,{value:"draft",children:"Draft"}),e.jsx(K,{value:"pending",children:"Pending"}),e.jsx(K,{value:"paused",children:"Paused"}),e.jsx(K,{value:"approved",children:"Approved"}),e.jsx(K,{value:"rejected",children:"Rejected"}),e.jsx(K,{value:"closed",children:"Closed"})]})]}),e.jsxs(Ve,{value:a,onValueChange:l,children:[e.jsx(He,{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(ze,{placeholder:"Priority"})}),e.jsxs(We,{children:[e.jsx(K,{value:"all",children:"All Priority"}),e.jsx(K,{value:"express",children:"Express"}),e.jsx(K,{value:"standard",children:"Standard"})]})]}),e.jsxs(Ve,{value:r,onValueChange:o,children:[e.jsx(He,{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(ze,{placeholder:"Template Type"})}),e.jsxs(We,{children:[e.jsx(K,{value:"all",children:"All Templates"}),e.jsx(K,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(K,{value:"DEALER CLAIM",children:"Dealer Claim"})]})]})]})]})})})}function a5(t){switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:pa,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Vt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Vt,iconColor:"text-gray-600"}}}function r5(t){switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:De,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:jt,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:Xe,iconColor:"text-yellow-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:De,iconColor:"text-gray-600"};case"draft":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ii,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ge,iconColor:"text-gray-600"}}}const n5=t=>{if(!t)return"";if(typeof document>"u")return t.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim();const s=document.createElement("div");s.innerHTML=t;let a=s.textContent||s.innerText||"";return a=a.replace(/\s+/g," ").trim(),a};function i5({request:t,index:s,onViewRequest:a}){var o;const r=r5(t.status),n=a5(t.priority),i=r.icon,l=n.icon;return e.jsx(gs.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:s*.1},children:e.jsx(te,{className:"group hover:shadow-lg transition-all duration-300 cursor-pointer border border-gray-200 shadow-sm hover:shadow-md",onClick:()=>a(t.id,t.title,t.status),"data-testid":`request-card-${t.id}`,children:e.jsx(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(ne,{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(ne,{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(Ha,{className:"w-3 h-3 mr-1"}),"Paused"]}),e.jsxs(ne,{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 d=(t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"",c=(d==null?void 0:d.toUpperCase())||"";let m="Non-Templatized",u="bg-purple-100 !text-purple-600 border-purple-200";return c==="DEALER CLAIM"?(m="Dealer Claim",u="bg-blue-100 !text-blue-700 border-blue-200"):c==="TEMPLATE"&&(m="Template"),e.jsx(ne,{variant:"outline",className:`${u} font-medium text-xs shrink-0`,"data-testid":"template-type-badge",children:m})})()]}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 mb-2 sm:mb-3 line-clamp-2 leading-relaxed","data-testid":"request-description",children:n5(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:"})," ",ha(t.submittedDate)]})]})]}),e.jsx(ds,{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(_t,{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(Ks,{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(Xe,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{"data-testid":"submitted-timestamp",children:["Submitted: ",ha(t.submittedDate)]})]})]})]})})})})}function l5({requests:t,loading:s,searchTerm:a,statusFilter:r,priorityFilter:n,onViewRequest:i}){if(s)return e.jsx(te,{"data-testid":"loading-state",children:e.jsx(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(te,{"data-testid":"empty-state",children:e.jsxs(ae,{className:"p-12 text-center",children:[e.jsx(Pe,{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(i5,{request:l,index:o,onViewRequest:i},l.id))})}function o5(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 ag(t){return Array.isArray(t)?t.map(o5):[]}function c5({itemsPerPage:t=10}={}){const[s,a]=h.useState([]),[r,n]=h.useState(!1),[i,l]=h.useState(!1),[o,d]=h.useState({currentPage:1,totalPages:1,totalRecords:0,itemsPerPage:t}),c=h.useCallback(async(m=1,u)=>{try{m===1&&(n(!0),a([]));const x=await Is.listMyInitiatedWorkflows({page:m,limit:t,search:u==null?void 0:u.search,status:u==null?void 0:u.status,priority:u==null?void 0:u.priority,templateType:u==null?void 0:u.templateType}),p=Array.isArray(x==null?void 0:x.data)?x.data:[],g=ag(p);a(g),l(!0);const y=x==null?void 0:x.pagination;y&&d({currentPage:y.page||1,totalPages:y.totalPages||1,totalRecords:y.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:c}}const d5={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",currentPage:1},rg=zr({name:"myRequests",initialState:d5,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:m5,setStatusFilter:u5,setPriorityFilter:x5,setTemplateTypeFilter:h5,setCurrentPage:p5,clearFilters:g5}=rg.actions;function f5({onFiltersChange:t,debounceMs:s=500}={}){const a=kn(),r=h.useRef(null),n=h.useRef(!0),{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:d,currentPage:c}=Wr(b=>b.myRequests),m=h.useCallback(b=>a(m5(b)),[a]),u=h.useCallback(b=>a(u5(b)),[a]),x=h.useCallback(b=>a(x5(b)),[a]),p=h.useCallback(b=>a(h5(b)),[a]),g=h.useCallback(b=>a(p5(b)),[a]),y=h.useCallback(()=>({search:i,status:l,priority:o,templateType:d}),[i,l,o,d]);h.useEffect(()=>{if(n.current){n.current=!1;return}r.current&&clearTimeout(r.current);const b=setTimeout(()=>{t&&t(y())},i?s:0);return r.current=b,()=>{r.current&&clearTimeout(r.current)}},[i,l,o,d,t,y,s]);const f=h.useCallback(()=>{a(g5())},[a]);return{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:d,currentPage:c,setSearchTerm:m,setStatusFilter:u,setPriorityFilter:x,setTemplateTypeFilter:p,setCurrentPage:g,getFilters:y,resetFilters:f}}function y5({onViewRequest:t,dynamicRequests:s=[]}){const{user:a}=Jt(),r=c5({itemsPerPage:10}),n=h.useRef(r.fetchMyRequests);n.current=r.fetchMyRequests;const i=f5(),l=h.useRef({searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,templateTypeFilter:i.templateTypeFilter}),o=h.useRef(!1);h.useEffect(()=>{const b=i.currentPage||1;n.current(b,{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},[]),h.useEffect(()=>{if(!o.current)return;const b=l.current;if(!(b.searchTerm!==i.searchTerm||b.statusFilter!==i.statusFilter||b.priorityFilter!==i.priorityFilter||b.templateTypeFilter!==i.templateTypeFilter))return;const A=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!==b.searchTerm?500:0);return()=>clearTimeout(A)},[i.searchTerm,i.statusFilter,i.priorityFilter,i.templateTypeFilter]);const[d,c]=h.useState(null),[m,u]=h.useState(!1),x=h.useCallback(async()=>{if(a!=null&&a.userId)try{u(!0);const b=await Ct.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);c({total:b.totalRequests||0,pending:b.openRequests||0,paused:b.pausedRequests||0,approved:b.approvedRequests||0,rejected:b.rejectedRequests||0,draft:b.draftRequests||0,closed:b.closedRequests||0})}catch(b){console.error("Failed to fetch backend stats:",b),c(null)}finally{u(!1)}},[a==null?void 0:a.userId,i.searchTerm,i.priorityFilter,i.templateTypeFilter]);h.useEffect(()=>{const b=setTimeout(()=>{x()},i.searchTerm?500:0);return()=>clearTimeout(b)},[i.searchTerm,i.priorityFilter,i.templateTypeFilter,x]);const p=ag(s),g=r.hasFetchedFromApi?r.requests:p,y=h.useMemo(()=>d?{total:d.total||0,pending:d.pending||0,paused:d.paused||0,approved:d.approved||0,rejected:d.rejected||0,draft:d.draft||0,closed:d.closed||0}:{total:0,pending:0,paused:0,approved:0,rejected:0,draft:0,closed:0},[d]),f=h.useCallback(b=>{b>=1&&b<=r.pagination.totalPages&&(i.setCurrentPage(b),r.fetchMyRequests(b,{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(sg,{icon:Pe,title:"My Requests",description:"Track and manage all your submitted requests",badge:{value:`${y.total} total`,label:"requests",loading:r.loading||m},testId:"my-requests-header"}),e.jsx(t5,{stats:y,onStatusFilter:b=>{i.setStatusFilter(b)}}),e.jsx(s5,{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(l5,{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 ng({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(sg,{icon:Pe,title:i(),description:l(),testId:"requests-header"}),e.jsx(ne,{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(Bt,{className:"w-4 h-4 mr-2 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Nt,{className:"w-4 h-4 mr-2"}),"Export"]})})]})}function ig({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(Hs,{label:"Total",value:t.total,icon:Pe,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(Hs,{label:"Pending",value:t.pending,icon:Xe,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(Hs,{label:"Paused",value:t.paused,icon:Ha,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(Hs,{label:"Approved",value:t.approved,icon:De,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(Hs,{label:"Rejected",value:t.rejected,icon:jt,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(Hs,{label:"Closed",value:t.closed,icon:Ei,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 b5=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:pa,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Vt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Vt,iconColor:"text-gray-600"}}},v5=t=>{switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:De,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:jt,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:Xe,iconColor:"text-yellow-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:De,iconColor:"text-gray-600"};case"draft":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ii,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ge,iconColor:"text-gray-600"}}},j5=t=>{if(!t)return"";if(typeof document>"u")return t.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim();const s=document.createElement("div");s.innerHTML=t;let a=s.textContent||s.innerText||"";return a=a.replace(/\s+/g," ").trim(),a};function N5({request:t,index:s,onViewRequest:a}){var o;const r=v5(t.status),n=b5(t.priority),i=r.icon,l=n.icon;return e.jsx(gs.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:s*.1},children:e.jsx(te,{className:"group hover:shadow-lg transition-all duration-300 cursor-pointer border border-gray-200 shadow-sm hover:shadow-md",onClick:()=>a(t.id,t.title,t.status),"data-testid":`request-card-${t.id}`,children:e.jsx(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(ne,{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(ne,{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(Ha,{className:"w-3 h-3 mr-1"}),"Paused"]}),e.jsxs(ne,{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 d=(t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"",c=(d==null?void 0:d.toUpperCase())||"";let m="Non-Templatized",u="bg-purple-100 !text-purple-600 border-purple-200";return c==="DEALER CLAIM"?(m="Dealer Claim",u="bg-blue-100 !text-blue-700 border-blue-200"):c==="TEMPLATE"&&(m="Template"),e.jsx(ne,{variant:"outline",className:`${u} font-medium text-xs shrink-0`,"data-testid":"template-type-badge",children:m})})(),t.department&&e.jsx(ne,{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:j5(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:"})," ",ha(t.submittedDate)]})]})]}),e.jsx(ds,{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(_t,{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(Ks,{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(Xe,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{"data-testid":"submitted-timestamp",children:["Submitted: ",ha(t.submittedDate)]})]})]})]})})})})}function lg({requests:t,loading:s,hasActiveFilters:a,onViewRequest:r}){return s?e.jsx(te,{"data-testid":"loading-state",children:e.jsx(ae,{className:"p-6 text-sm text-gray-600",children:"Loading requests…"})}):t.length===0?e.jsx(te,{"data-testid":"empty-state",children:e.jsxs(ae,{className:"p-12 text-center",children:[e.jsx(Pe,{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(N5,{request:n,index:i,onViewRequest:r},n.id))})}const w5={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},og=zr({name:"requests",initialState:w5,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:C5,setStatusFilter:A5,setPriorityFilter:S5,setTemplateTypeFilter:T5,setSlaComplianceFilter:k5,setDepartmentFilter:R5,setInitiatorFilter:D5,setApproverFilter:P5,setApproverFilterType:I5,setDateRange:Su,setCustomStartDate:Dl,setCustomEndDate:Pl,setShowCustomDatePicker:Wn,setCurrentPage:E5,clearFilters:F5}=og.actions;function cg(){const t=kn(),{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,slaComplianceFilter:i,departmentFilter:l,initiatorFilter:o,approverFilter:d,approverFilterType:c,dateRange:m,customStartDate:u,customEndDate:x,showCustomDatePicker:p,currentPage:g}=Wr(j=>j.requests),y=h.useCallback(j=>t(C5(j)),[t]),f=h.useCallback(j=>t(A5(j)),[t]),b=h.useCallback(j=>t(S5(j)),[t]),v=h.useCallback(j=>t(T5(j)),[t]),A=h.useCallback(j=>t(k5(j)),[t]),w=h.useCallback(j=>t(R5(j)),[t]),T=h.useCallback(j=>t(D5(j)),[t]),k=h.useCallback(j=>t(P5(j)),[t]),L=h.useCallback(j=>t(I5(j)),[t]),D=h.useCallback(j=>t(Su(j)),[t]),S=h.useCallback(j=>t(Dl(j)),[t]),N=h.useCallback(j=>t(Pl(j)),[t]),P=h.useCallback(j=>t(Wn(j)),[t]),R=h.useCallback(j=>t(E5(j)),[t]),O=h.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:d!=="all"?d:void 0,approverType:d!=="all"?c:void 0,dateRange:m,startDate:u,endDate:x}),[s,a,r,n,i,l,o,d,c,m,u,x]),E=h.useCallback(()=>{t(F5())},[t]),M=h.useCallback(j=>{const U=j;t(Su(U)),U!=="custom"?(t(Dl(void 0)),t(Pl(void 0)),t(Wn(!1))):t(Wn(!0))},[t]),B=h.useCallback(()=>{u&&x&&(u>x&&(t(Dl(x)),t(Pl(u))),t(Wn(!1)))},[u,x,t]);return{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,slaComplianceFilter:i,departmentFilter:l,initiatorFilter:o,approverFilter:d,approverFilterType:c,dateRange:m,customStartDate:u,customEndDate:x,showCustomDatePicker:p,currentPage:g,hasActiveFilters:!!(s||a!=="all"||r!=="all"||n!=="all"||i!=="all"||l!=="all"||o!=="all"||d!=="all"||m!=="all"||u||x),setSearchTerm:y,setStatusFilter:f,setPriorityFilter:b,setTemplateTypeFilter:v,setSlaComplianceFilter:A,setDepartmentFilter:w,setInitiatorFilter:T,setApproverFilter:k,setApproverFilterType:L,setDateRange:D,setCustomStartDate:S,setCustomEndDate:N,setShowCustomDatePicker:P,setCurrentPage:R,getFilters:O,clearFilters:E,handleDateRangeChange:M,handleApplyCustomDate:B}}function yi({allUsers:t,filterValue:s,onFilterChange:a}){const[r,n]=h.useState(""),[i,l]=h.useState([]),[o,d]=h.useState(!1),[c,m]=h.useState(null),u=h.useRef(null);h.useEffect(()=>{if(s!=="all"&&t.length>0){const y=t.find(f=>f.userId===s);y&&(m(y),n(y.displayName||y.email))}},[s,t]),h.useEffect(()=>()=>{u.current&&clearTimeout(u.current)},[]);const x=h.useCallback(y=>{if(n(y),u.current&&clearTimeout(u.current),!y||y.trim().length<2){l([]),d(!1);return}u.current=setTimeout(()=>{const f=y.toLowerCase().trim(),b=t.filter(v=>{const A=(v.email||"").toLowerCase(),w=(v.displayName||"").toLowerCase();return A.includes(f)||w.includes(f)});l(b.slice(0,10)),d(b.length>0)},300)},[t]),p=h.useCallback(y=>{m(y),a(y.userId),n(y.displayName||y.email),d(!1),l([])},[a]),g=h.useCallback(()=>{m(null),a("all"),n(""),d(!1),l([])},[a]);return{searchQuery:r,searchResults:i,showResults:o,selectedUser:c,handleSearch:x,handleSelect:p,handleClear:g,setShowResults:d}}function M5(t){var c,m,u,x,p,g,y;const s=t.submittedAt||t.submitted_at||t.createdAt||t.created_at,a=(t.priority||"").toString().toLowerCase(),r=(t.status||"").toString().toUpperCase();let n="—",i="—";const 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(b=>{const v=(b.status||"").toString().toUpperCase();return v==="PENDING"||v==="IN_PROGRESS"});if(f)n=f.approverName||((c=f.approver)==null?void 0:c.name)||((m=f.approver)==null?void 0:m.displayName)||f.approverEmail||((u=f.approver)==null?void 0:u.email)||"—";else{const v=[...t.approvals].sort((A,w)=>{const T=A.levelNumber||A.level_number||0;return(w.levelNumber||w.level_number||0)-T})[0];v&&(n=v.approverName||((x=v.approver)==null?void 0:x.name)||((p=v.approver)==null?void 0:p.displayName)||v.approverEmail||((g=v.approver)==null?void 0:g.email)||"—")}}const o=t.currentLevel||t.current_level||t.currentLevelNumber||t.current_level_number,d=t.totalLevels||t.total_levels||t.totalLevelsCount||t.total_levels_count;if(o&&d)i=`${o} of ${d}`;else if(t.approvals&&Array.isArray(t.approvals)&&t.approvals.length>0){const f=t.approvals.find(b=>{const v=(b.status||"").toString().toUpperCase();return v==="PENDING"||v==="IN_PROGRESS"});if(f){const b=f.levelNumber||f.level_number||0,v=d||t.approvals.length;i=`${b} of ${v}`}else d&&(i=`${d} of ${d}`)}else t.currentStep&&t.totalSteps&&(i=`${t.currentStep} of ${t.totalSteps}`);return{id:t.requestNumber||t.request_number||t.requestId||t.id||t.request_id,requestId:t.requestId||t.id||t.request_id,displayId:t.requestNumber||t.request_number||t.id,title:t.title,description:t.description,status:r.toLowerCase().replace("_","-"),priority:a,department:t.department||((y=t.initiator)==null?void 0:y.department),submittedDate:t.submittedAt||(t.createdAt?new Date(t.createdAt).toISOString().split("T")[0]:void 0),createdAt:s,currentApprover:n,approverLevel:i,templateType:t.templateType||t.template_type,workflowType:t.workflowType||t.workflow_type,templateName:t.templateName||t.template_name}}function dg(t){return Array.isArray(t)?t.map(M5):[]}function _5(t,s,a,r,n,i){if(t.length>0){const l=t.length,o=t.filter(p=>{const g=(p.status||"").toString().toUpperCase();return g==="PENDING"||g==="IN_PROGRESS"}).length,d=t.filter(p=>(p.status||"").toString().toUpperCase()==="APPROVED").length,c=t.filter(p=>(p.status||"").toString().toUpperCase()==="REJECTED").length,m=t.filter(p=>(p.status||"").toString().toUpperCase()==="DRAFT").length,u=t.filter(p=>(p.status||"").toString().toUpperCase()==="CLOSED").length,x=t.filter(p=>(p.status||"").toString().toUpperCase()==="PAUSED").length;return{total:l,pending:o,paused:x,approved:d,rejected:c,draft:m,closed:u}}else return s&&a?{total:a.total,pending:a.pending,paused:a.paused||0,approved:a.approved,rejected:a.rejected,draft:a.draft,closed:a.closed}:{total:n||i.length,pending:i.filter(o=>o.status==="pending"||o.status==="in-progress").length,paused:i.filter(o=>o.status==="paused").length,approved:i.filter(o=>o.status==="approved").length,rejected:i.filter(o=>o.status==="rejected").length,draft:i.filter(o=>o.status==="draft").length,closed:i.filter(o=>o.status==="closed").length}}var mg={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(vi,function(){return function(a,r){r.prototype.isSameOrBefore=function(n,i){return this.isSame(n,i)||this.isBefore(n,i)}}})})(mg);var L5=mg.exports;const ug=ji(L5);var xg={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(vi,function(){return function(a,r){r.prototype.isSameOrAfter=function(n,i){return this.isSame(n,i)||this.isAfter(n,i)}}})})(xg);var O5=xg.exports;const hg=ji(O5);Ht.extend(hg);Ht.extend(ug);function $5(t,s){let a=[...t];if(s.search){const r=s.search.toLowerCase();a=a.filter(n=>{var i,l,o,d;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))||((d=n.request_number)==null?void 0:d.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,d,c,m,u;return(((l=n.currentApprover)==null?void 0:l.userId)||((o=n.currentApprover)==null?void 0:o.user_id)||((c=(d=n.approvals)==null?void 0:d.find(x=>{const p=(x.status||"").toString().toUpperCase();return p==="IN_PROGRESS"||p==="PENDING"}))==null?void 0:c.approverId)||((u=(m=n.approvals)==null?void 0:m.find(x=>{const p=(x.status||"").toString().toUpperCase();return p==="IN_PROGRESS"||p==="PENDING"}))==null?void 0:u.approver_id)||n.currentApproverId||n.current_approver_id)===s.approver}):a=a.filter(n=>{var 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(d=>{d.approverId&&i.push(d.approverId),d.approver_id&&i.push(d.approver_id)}),i.includes(s.approver||"")})),s.slaCompliance&&s.slaCompliance!=="all"&&(a=a.filter(r=>{var d,c,m,u,x,p,g,y,f,b,v,A;const n=s.slaCompliance||"";if(n.toLowerCase()==="compliant"){const w=(r.status||"").toString().toUpperCase();if(!(w==="APPROVED"||w==="REJECTED"||w==="CLOSED"))return!1;const k=((d=r.currentLevelSLA)==null?void 0:d.status)||((m=(c=r.currentApprover)==null?void 0:c.sla)==null?void 0:m.status)||((u=r.sla)==null?void 0:u.status)||((p=(x=r.summary)==null?void 0:x.sla)==null?void 0:p.status);return k?k!=="breached"&&k.toLowerCase()!=="breached":!0}const i=((g=r.currentLevelSLA)==null?void 0:g.status)||((f=(y=r.currentApprover)==null?void 0:y.sla)==null?void 0:f.status)||((b=r.sla)==null?void 0:b.status)||((A=(v=r.summary)==null?void 0:v.sla)==null?void 0:A.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 u=Ht(m).startOf("day").toDate(),x=Ht(r).startOf("day").toDate(),p=Ht(n).endOf("day").toDate();return u>=x&&u<=p}const o=Ht(l).startOf("day").toDate(),d=Ht(r).startOf("day").toDate(),c=Ht(n).endOf("day").toDate();return o>=d&&o<=c}))}return a}Ht.extend(ug);Ht.extend(hg);function U5(t){if(!t)return"N/A";try{const s=typeof t=="string"?new Date(t):t;return Ye(s,"yyyy-MM-dd HH:mm:ss")}catch{return"N/A"}}async function pg(t,s){const a=$5(t,s),r=[["Request Number","Title","Status","Priority","Initiator","Department","Current Approver","Approval Level","Submitted Date","Description"].join(",")];a.forEach(d=>{var v,A,w,T,k;const c=(d.status||"").toString().toLowerCase().replace("_","-"),m=(d.priority||"").toString().toLowerCase(),u=((v=d.initiator)==null?void 0:v.displayName)||((A=d.initiator)==null?void 0:A.email)||d.initiatorName||"N/A",x=d.department||((w=d.initiator)==null?void 0:w.department)||"N/A",p=((T=d.currentApprover)==null?void 0:T.displayName)||((k=d.currentApprover)==null?void 0:k.email)||d.currentApproverName||"N/A",g=d.currentApproverLevel||d.approvalLevel||d.currentLevel||"N/A",y=U5(d.submittedAt||d.createdAt||d.submitted_at||d.created_at),f=(d.description||"").replace(/"/g,'""').replace(/\n/g," ").replace(/\r/g,""),b=[d.requestNumber||d.request_number||"",`"${(d.title||"").replace(/"/g,'""')}"`,c,m,`"${u.replace(/"/g,'""')}"`,`"${x.replace(/"/g,'""')}"`,`"${p.replace(/"/g,'""')}"`,g,y,`"${f}"`];r.push(b.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 B5({page:t,itemsPerPage:s,filters:a,isOrgLevel:r}){var n,i,l,o;if(r){const d={};a!=null&&a.search&&(d.search=a.search),a!=null&&a.status&&a.status!=="all"&&(d.status=a.status),a!=null&&a.priority&&a.priority!=="all"&&(d.priority=a.priority),a!=null&&a.templateType&&a.templateType!=="all"&&(d.templateType=a.templateType),a!=null&&a.department&&a.department!=="all"&&(d.department=a.department),a!=null&&a.initiator&&a.initiator!=="all"&&(d.initiator=a.initiator),a!=null&&a.approver&&a.approver!=="all"&&(d.approver=a.approver,d.approverType=a.approverType||"current"),a!=null&&a.slaCompliance&&a.slaCompliance!=="all"&&(d.slaCompliance=a.slaCompliance),a!=null&&a.dateRange&&(d.dateRange=a.dateRange),a!=null&&a.startDate&&(d.startDate=(n=a.startDate)==null?void 0:n.toISOString()),a!=null&&a.endDate&&(d.endDate=(i=a.endDate)==null?void 0:i.toISOString());const c=await Is.listWorkflows({page:t,limit:s,...d});let m=[];Array.isArray(c==null?void 0:c.data)?m=c.data:Array.isArray(c)&&(m=c);const u=m.filter(g=>(g.status||"").toString().toUpperCase()!=="DRAFT"),x=(c==null?void 0:c.pagination)||{page:t,limit:s,total:u.length,totalPages:1};return{data:u,allData:[],filteredData:u,pagination:{page:x.page,limit:x.limit||s,total:x.total||u.length,totalPages:x.totalPages||1}}}else{const d={};a!=null&&a.search&&(d.search=a.search),a!=null&&a.status&&a.status!=="all"&&(d.status=a.status),a!=null&&a.priority&&a.priority!=="all"&&(d.priority=a.priority),a!=null&&a.templateType&&a.templateType!=="all"&&(d.templateType=a.templateType),a!=null&&a.department&&a.department!=="all"&&(d.department=a.department),a!=null&&a.initiator&&a.initiator!=="all"&&(d.initiator=a.initiator),a!=null&&a.slaCompliance&&a.slaCompliance!=="all"&&(d.slaCompliance=a.slaCompliance),a!=null&&a.dateRange&&(d.dateRange=a.dateRange),a!=null&&a.startDate&&(d.startDate=(l=a.startDate)==null?void 0:l.toISOString()),a!=null&&a.endDate&&(d.endDate=(o=a.endDate)==null?void 0:o.toISOString());const c=await Is.listParticipantRequests({page:t,limit:s,...d});let m=[];Array.isArray(c==null?void 0:c.data)?m=c.data:Array.isArray(c)&&(m=c);const u=m.filter(p=>(p.status||"").toString().toUpperCase()!=="DRAFT"),x=(c==null?void 0:c.pagination)||{page:t,limit:s,total:u.length,totalPages:1};return{data:u,allData:[],filteredData:u,pagination:x}}}async function V5(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 d=o.filter(c=>(c.status||"").toString().toUpperCase()!=="DRAFT");a.push(...d),r++,l!=null&&l.pagination?n=r<=l.pagination.totalPages:n=o.length===100}else n=!1}return a}function z5({onViewRequest:t}){const{user:s}=Jt(),a=Wr(W=>W.dashboard.viewAsUser),r=h.useMemo(()=>Mi(s),[s]),n=h.useMemo(()=>r&&!a,[r,a]),i=cg(),[l,o]=h.useState([]),[d,c]=h.useState(!1),[m,u]=h.useState(!1),[x,p]=h.useState(null),[g,y]=h.useState([]),[f,b]=h.useState(!1),[v,A]=h.useState([]),[w,T]=h.useState(1),[k,L]=h.useState(0),[D]=h.useState(10),S=yi({allUsers:v,filterValue:i.initiatorFilter,onFilterChange:i.setInitiatorFilter}),N=yi({allUsers:v,filterValue:i.approverFilter,onFilterChange:i.setApproverFilter}),P=h.useCallback(async(W,ce,Z,I)=>{try{const V=I==null?void 0:I.slaCompliance;if(V&&V!=="all"&&V!=="breached"&&V!=="compliant"){const X={};I!=null&&I.search&&(X.search=I.search),I!=null&&I.priority&&I.priority!=="all"&&(X.priority=I.priority),I!=null&&I.department&&I.department!=="all"&&(X.department=I.department),I!=null&&I.initiator&&I.initiator!=="all"&&(X.initiator=I.initiator),I!=null&&I.approver&&I.approver!=="all"&&(X.approver=I.approver,X.approverType=I.approverType||"current"),X.slaCompliance=V,W&&(X.dateRange=W),ce&&(X.startDate=ce.toISOString()),Z&&(X.endDate=Z.toISOString());const Y=n?await Is.listWorkflows({page:1,limit:1e3,...X}):await Is.listParticipantRequests({page:1,limit:1e3,...X}),G=Array.isArray(Y==null?void 0:Y.data)?Y.data:[],ie=G.length,me=G.filter(pe=>{const ve=(pe.status||"").toString().toUpperCase();return ve==="PENDING"||ve==="IN_PROGRESS"}).length,Te=G.filter(pe=>(pe.status||"").toString().toUpperCase()==="APPROVED").length,Se=G.filter(pe=>(pe.status||"").toString().toUpperCase()==="REJECTED").length,re=G.filter(pe=>(pe.status||"").toString().toUpperCase()==="CLOSED").length;p({total:ie,pending:me,paused:0,approved:Te,rejected:Se,draft:0,closed:re})}else{const X=await Ct.getRequestStats(W,ce?ce.toISOString():void 0,Z?Z.toISOString():void 0,void 0,I==null?void 0:I.priority,void 0,I==null?void 0:I.department,I==null?void 0:I.initiator,I==null?void 0:I.approver,I==null?void 0:I.approverType,I==null?void 0:I.search,I==null?void 0:I.slaCompliance,!n);p({total:X.totalRequests||0,pending:X.openRequests||0,paused:X.pausedRequests||0,approved:X.approvedRequests||0,rejected:X.rejectedRequests||0,draft:X.draftRequests||0,closed:X.closedRequests||0})}}catch(V){console.error("Failed to fetch backend stats:",V)}finally{}},[n]),R=h.useCallback(async()=>{try{b(!0);const W=await Ct.getDepartments();y(W)}catch{}finally{b(!1)}},[]),O=h.useCallback(async()=>{try{const ce=(await Ws.getAllUsers()).map(Z=>({userId:Z.userId,email:Z.email,displayName:Z.displayName||Z.email}));A(ce)}catch(W){console.error("Failed to fetch users:",W)}},[]),E=h.useRef(i),M=h.useRef(P);h.useEffect(()=>{E.current=i,M.current=P},[i,P]),h.useEffect(()=>{const W=new URLSearchParams(window.location.search),ce=W.get("approver"),Z=W.get("approverType"),I=W.get("slaCompliance"),V=W.get("dateRange"),z=W.get("startDate"),X=W.get("endDate");ce&&i.setApproverFilter(ce),(Z==="current"||Z==="any")&&i.setApproverFilterType(Z),I&&i.setSlaComplianceFilter(I),V&&i.setDateRange(V),z&&i.setCustomStartDate(new Date(z)),X&&i.setCustomEndDate(new Date(X))},[]);const B=h.useCallback(async(W=1)=>{try{W===1&&(c(!0),o([]));const ce=E.current.getFilters(),Z=await B5({page:W,itemsPerPage:D,filters:ce,isOrgLevel:n});o(Z.data),i.setCurrentPage(Z.pagination.page),T(Z.pagination.totalPages),L(Z.pagination.total)}catch{o([])}finally{c(!1)}},[D,n]),C=h.useCallback(async()=>{try{u(!0);const W=await V5(n);await pg(W,i.getFilters())}catch(W){console.error("Failed to export requests:",W),alert("Failed to export requests. Please try again.")}finally{u(!1)}},[n,i]);h.useEffect(()=>{R(),O()},[R,O]),h.useEffect(()=>{const W=setTimeout(()=>{const ce={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},Z=i.dateRange||"all";M.current(Z,i.customStartDate,i.customEndDate,ce)},i.searchTerm?500:0);return()=>clearTimeout(W)},[n,i.dateRange,i.customStartDate,i.customEndDate,i.priorityFilter,i.templateTypeFilter,i.departmentFilter,i.initiatorFilter,i.approverFilter,i.approverFilterType,i.searchTerm,i.slaComplianceFilter]);const j=h.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}),U=h.useRef(!1);h.useEffect(()=>{const W=i.currentPage||1;B(W),U.current=!0},[]),h.useEffect(()=>{if(!U.current)return;const W=j.current;if(!(W.searchTerm!==i.searchTerm||W.statusFilter!==i.statusFilter||W.priorityFilter!==i.priorityFilter||W.templateTypeFilter!==i.templateTypeFilter||W.slaComplianceFilter!==i.slaComplianceFilter||W.departmentFilter!==i.departmentFilter||W.initiatorFilter!==i.initiatorFilter||W.approverFilter!==i.approverFilter||W.approverFilterType!==i.approverFilterType||W.dateRange!==i.dateRange||W.customStartDate!==i.customStartDate||W.customEndDate!==i.customEndDate||W.isOrgLevel!==n))return;const Z=setTimeout(()=>{i.setCurrentPage(1),B(1),j.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!==W.searchTerm?500:0);return()=>clearTimeout(Z)},[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 $=h.useCallback(W=>{W>=1&&W<=w&&(i.setCurrentPage(W),B(W))},[w,B,i]),_=h.useMemo(()=>dg(l),[l]),se=h.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}:_5([],n,x,!1,k,_),[n,x,k,_]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"requests-page",children:[e.jsx(ng,{isOrgLevel:n,isAdmin:r,loading:d,exporting:m,onExport:C}),e.jsx(ig,{stats:se,onStatusFilter:W=>{i.setStatusFilter(W)}}),e.jsx(te,{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(Ya,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),i.hasActiveFilters&&e.jsx(ne,{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(Bt,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Gt,{}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 lg:grid-cols-6 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative md:col-span-3 lg:col-span-1",children:[e.jsx(As,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(_e,{placeholder:"Search requests...",value:i.searchTerm,onChange:W=>i.setSearchTerm(W.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(Ve,{value:i.statusFilter,onValueChange:i.setStatusFilter,children:[e.jsx(He,{className:"h-10","data-testid":"status-filter",children:e.jsx(ze,{placeholder:"All Status"})}),e.jsxs(We,{children:[e.jsx(K,{value:"all",children:"All Status"}),e.jsx(K,{value:"pending",children:"Pending"}),e.jsx(K,{value:"paused",children:"Paused"}),e.jsx(K,{value:"approved",children:"Approved"}),e.jsx(K,{value:"rejected",children:"Rejected"}),e.jsx(K,{value:"closed",children:"Closed"})]})]}),e.jsxs(Ve,{value:i.priorityFilter,onValueChange:i.setPriorityFilter,children:[e.jsx(He,{className:"h-10","data-testid":"priority-filter",children:e.jsx(ze,{placeholder:"All Priority"})}),e.jsxs(We,{children:[e.jsx(K,{value:"all",children:"All Priority"}),e.jsx(K,{value:"express",children:"Express"}),e.jsx(K,{value:"standard",children:"Standard"})]})]}),e.jsxs(Ve,{value:i.templateTypeFilter,onValueChange:i.setTemplateTypeFilter,children:[e.jsx(He,{className:"h-10","data-testid":"template-type-filter",children:e.jsx(ze,{placeholder:"All Templates"})}),e.jsxs(We,{children:[e.jsx(K,{value:"all",children:"All Templates"}),e.jsx(K,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(K,{value:"DEALER CLAIM",children:"Dealer Claim"})]})]}),e.jsxs(Ve,{value:i.departmentFilter,onValueChange:i.setDepartmentFilter,disabled:f||g.length===0,children:[e.jsx(He,{className:"h-10","data-testid":"department-filter",children:e.jsx(ze,{placeholder:f?"Loading...":"All Departments"})}),e.jsxs(We,{children:[e.jsx(K,{value:"all",children:"All Departments"}),g.map(W=>e.jsx(K,{value:W,children:W},W))]})]}),e.jsxs(Ve,{value:i.slaComplianceFilter,onValueChange:i.setSlaComplianceFilter,children:[e.jsx(He,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(ze,{placeholder:"All SLA Status"})}),e.jsxs(We,{children:[e.jsx(K,{value:"all",children:"All SLA Status"}),e.jsx(K,{value:"compliant",children:"Compliant"}),e.jsx(K,{value:"on-track",children:"On Track"}),e.jsx(K,{value:"approaching",children:"Approaching"}),e.jsx(K,{value:"critical",children:"Critical"}),e.jsx(K,{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(le,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:S.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:S.selectedUser.displayName||S.selectedUser.email}),e.jsx(F,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:S.handleClear,children:e.jsx(ft,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(_e,{placeholder:"Search initiator...",value:S.searchQuery,onChange:W=>S.handleSearch(W.target.value),onFocus:()=>{S.searchResults.length>0&&S.setShowResults(!0)},onBlur:()=>setTimeout(()=>S.setShowResults(!1),200),className:"h-10","data-testid":"initiator-search-input"}),S.showResults&&S.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:S.searchResults.map(W=>e.jsx("button",{type:"button",onClick:()=>S.handleSelect(W),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:W.displayName||W.email}),W.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:W.email})]})},W.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(le,{className:"text-sm font-medium text-gray-700",children:"Approver"}),i.approverFilter!=="all"&&e.jsxs(Ve,{value:i.approverFilterType,onValueChange:W=>i.setApproverFilterType(W),children:[e.jsx(He,{className:"h-7 w-32 text-xs",children:e.jsx(ze,{})}),e.jsxs(We,{children:[e.jsx(K,{value:"current",children:"Current Only"}),e.jsx(K,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:N.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:N.selectedUser.displayName||N.selectedUser.email}),e.jsx(F,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:N.handleClear,children:e.jsx(ft,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(_e,{placeholder:"Search approver...",value:N.searchQuery,onChange:W=>N.handleSearch(W.target.value),onFocus:()=>{N.searchResults.length>0&&N.setShowResults(!0)},onBlur:()=>setTimeout(()=>N.setShowResults(!1),200),className:"h-10","data-testid":"approver-search-input"}),N.showResults&&N.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:N.searchResults.map(W=>e.jsx("button",{type:"button",onClick:()=>N.handleSelect(W),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:W.displayName||W.email}),W.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:W.email})]})},W.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(it,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ve,{value:i.dateRange,onValueChange:i.handleDateRangeChange,children:[e.jsx(He,{className:"w-[160px] h-10",children:e.jsx(ze,{placeholder:"Date Range"})}),e.jsxs(We,{children:[e.jsx(K,{value:"all",children:"All Time"}),e.jsx(K,{value:"today",children:"Today"}),e.jsx(K,{value:"week",children:"This Week"}),e.jsx(K,{value:"month",children:"This Month"}),e.jsx(K,{value:"last7days",children:"Last 7 Days"}),e.jsx(K,{value:"last30days",children:"Last 30 Days"}),e.jsx(K,{value:"custom",children:"Custom Range"})]})]}),i.dateRange==="custom"&&e.jsxs(Ys,{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(it,{className:"w-4 h-4"}),i.customStartDate&&i.customEndDate?`${Ye(i.customStartDate,"MMM d, yyyy")} - ${Ye(i.customEndDate,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Xs,{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(le,{htmlFor:"start-date",children:"Start Date"}),e.jsx($s,{value:i.customStartDate||null,onChange:W=>{const ce=W?new Date(W):void 0;ce?(i.setCustomStartDate(ce),i.customEndDate&&ce>i.customEndDate&&i.setCustomEndDate(ce)):i.setCustomStartDate(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{htmlFor:"end-date",children:"End Date"}),e.jsx($s,{value:i.customEndDate||null,onChange:W=>{const ce=W?new Date(W):void 0;ce?(i.setCustomEndDate(ce),i.customStartDate&&ce<i.customStartDate&&i.setCustomStartDate(ce)):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(lg,{requests:_,loading:d,hasActiveFilters:i.hasActiveFilters,onViewRequest:t}),e.jsx(jr,{currentPage:i.currentPage||1,totalPages:w,totalRecords:k,itemsPerPage:D,onPageChange:$,loading:d,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}async function H5({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(d=>(d.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 Tu=100;async function W5(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:Tu,...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 d=o.filter(c=>(c.status||"").toString().toUpperCase()!=="DRAFT");s.push(...d),r++,l!=null&&l.pagination?a=r<=l.pagination.totalPages:a=o.length===Tu}}return s}function G5({onViewRequest:t}){const s=cg(),a=h.useMemo(()=>{try{const Z=at.getUserData();return _o(Z)}catch(Z){return console.error("[UserAllRequests] Error getting user filter type:",Z),"STANDARD"}},[]),r=h.useMemo(()=>vT(a),[a]),n=a==="DEALER",i=h.useCallback(()=>{const Z=s.getFilters();if(n){const{priority:I,templateType:V,department:z,slaCompliance:X,...Y}=Z;return Y}return Z},[s,n]),l=h.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,d]=h.useState([]),[c,m]=h.useState(!1),[u,x]=h.useState(!1),[p,g]=h.useState(null),[y,f]=h.useState([]),[b,v]=h.useState(!1),[A,w]=h.useState([]),[T,k]=h.useState(1),[L,D]=h.useState(0),[S]=h.useState(10),N=yi({allUsers:A,filterValue:s.initiatorFilter,onFilterChange:s.setInitiatorFilter}),P=yi({allUsers:A,filterValue:s.approverFilter,onFilterChange:s.setApproverFilter}),R=h.useCallback(async(Z,I,V,z)=>{try{const X=await Ct.getRequestStats(Z,I?I.toISOString():void 0,V?V.toISOString():void 0,void 0,z==null?void 0:z.priority,z==null?void 0:z.templateType,z==null?void 0:z.department,z==null?void 0:z.initiator,z==null?void 0:z.approver,z==null?void 0:z.approverType,z==null?void 0:z.search,z==null?void 0:z.slaCompliance,!0);g({total:X.totalRequests||0,pending:X.openRequests||0,paused:X.pausedRequests||0,approved:X.approvedRequests||0,rejected:X.rejectedRequests||0,draft:X.draftRequests||0,closed:X.closedRequests||0})}catch(X){console.error("Failed to fetch backend stats:",X)}},[]),O=h.useCallback(async()=>{try{v(!0);const Z=await Ct.getDepartments();f(Z)}catch{}finally{v(!1)}},[]),E=h.useCallback(async()=>{try{const I=(await Ws.getAllUsers()).map(V=>({userId:V.userId,email:V.email,displayName:V.displayName||V.email}));w(I)}catch(Z){console.error("Failed to fetch users:",Z)}},[]),M=h.useRef(s),B=h.useRef(R),C=h.useRef(i);h.useEffect(()=>{M.current=s,B.current=R,C.current=i},[s,R,i]);const j=h.useCallback(async(Z=1)=>{try{Z===1&&(m(!0),d([]));const I=C.current(),V=await H5({page:Z,itemsPerPage:S,filters:I});d(V.data),s.setCurrentPage(V.pagination.page),k(V.pagination.totalPages),D(V.pagination.total)}catch{d([])}finally{m(!1)}},[S,s]),U=h.useCallback(async()=>{try{x(!0);const Z=i(),I=await W5(Z);await pg(I,Z)}catch(Z){console.error("Failed to export requests:",Z),alert("Failed to export requests. Please try again.")}finally{x(!1)}},[i]);h.useEffect(()=>{O(),E()},[O,E]),h.useEffect(()=>{const Z=setTimeout(()=>{const I={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"&&(I.priority=s.priorityFilter),s.templateTypeFilter!=="all"&&(I.templateType=s.templateTypeFilter),s.departmentFilter!=="all"&&(I.department=s.departmentFilter),s.slaComplianceFilter!=="all"&&(I.slaCompliance=s.slaComplianceFilter));const V=s.dateRange==="all"?"all":s.dateRange||"month";B.current(V,s.customStartDate,s.customEndDate,I)},s.searchTerm?500:0);return()=>clearTimeout(Z)},[s.searchTerm,s.priorityFilter,s.slaComplianceFilter,s.departmentFilter,s.initiatorFilter,s.approverFilter,s.approverFilterType,s.dateRange,s.customStartDate,s.customEndDate,s.templateTypeFilter,n]);const $=h.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}),_=h.useRef(!1);h.useEffect(()=>{const Z=s.currentPage||1;j(Z),_.current=!0},[]),h.useEffect(()=>{if(!_.current)return;const Z=$.current;if(!(Z.searchTerm!==s.searchTerm||Z.statusFilter!==s.statusFilter||Z.priorityFilter!==s.priorityFilter||Z.templateTypeFilter!==s.templateTypeFilter||Z.slaComplianceFilter!==s.slaComplianceFilter||Z.departmentFilter!==s.departmentFilter||Z.initiatorFilter!==s.initiatorFilter||Z.approverFilter!==s.approverFilter||Z.approverFilterType!==s.approverFilterType||Z.dateRange!==s.dateRange||Z.customStartDate!==s.customStartDate||Z.customEndDate!==s.customEndDate))return;const V=setTimeout(()=>{s.setCurrentPage(1),j(1),$.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!==Z.searchTerm?500:0);return()=>clearTimeout(V)},[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 se=h.useCallback(Z=>{Z>=1&&Z<=T&&(s.setCurrentPage(Z),j(Z))},[T,j,s]),W=h.useMemo(()=>dg(o),[o]),ce=h.useMemo(()=>{if(p)return{total:p.total||0,pending:p.pending||0,paused:p.paused||0,approved:p.approved||0,rejected:p.rejected||0,draft:p.draft||0,closed:p.closed||0};const Z=W.filter(Y=>{const G=(Y.status||"").toString().toLowerCase();return G==="pending"||G==="in-progress"}).length,I=W.filter(Y=>(Y.status||"").toString().toLowerCase()==="paused").length,V=W.filter(Y=>(Y.status||"").toString().toLowerCase()==="approved").length,z=W.filter(Y=>(Y.status||"").toString().toLowerCase()==="rejected").length,X=W.filter(Y=>(Y.status||"").toString().toLowerCase()==="closed").length;return{total:L>0?L:W.length,pending:Z,paused:I,approved:V,rejected:z,draft:0,closed:X}},[p,L,W]);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(ng,{isOrgLevel:!1,isAdmin:!1,loading:c,exporting:u,onExport:U}),e.jsx(ig,{stats:ce,onStatusFilter:Z=>{s.setStatusFilter(Z)}}),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:y,loadingDepartments:b,initiatorSearch:N,approverSearch:P,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(lg,{requests:W,loading:c,hasActiveFilters:s.hasActiveFilters,onViewRequest:t}),e.jsx(jr,{currentPage:s.currentPage||1,totalPages:T,totalRecords:L,itemsPerPage:S,onPageChange:se,loading:c,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}function K5(){const t=Fa();return e.jsx("div",{className:"flex-1 p-3 lg:p-6 overflow-auto min-w-0","data-testid":"approver-performance-empty",children:e.jsx("div",{className:"max-w-7xl mx-auto p-4",children:e.jsx(te,{children:e.jsxs(ae,{className:"p-8 text-center",children:[e.jsx(Ge,{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(Js,{className:"w-4 h-4 mr-2"}),"Back"]})]})})})})}function Y5({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($t,{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(Bt,{className:`w-4 h-4 ${s?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:"Refresh"})]})]})}function Z5({approverStats:t}){const s=(t==null?void 0:t.tatCompliancePercent)??0;return e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4","data-testid":"approver-stats-cards",children:[e.jsxs(te,{children:[e.jsx(ue,{className:"pb-3",children:e.jsx(xe,{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(Vt,{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(la,{value:s,className:"mt-2 h-2"})]})]}),e.jsxs(te,{children:[e.jsx(ue,{className:"pb-3",children:e.jsx(xe,{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(De,{className:"w-5 h-5 text-blue-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Requests handled"})]})]}),e.jsxs(te,{children:[e.jsx(ue,{className:"pb-3",children:e.jsx(xe,{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(wo,{className:"w-5 h-5 text-purple-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:t.avgResponseHours<24?`${(t.avgResponseHours/8).toFixed(1)} working days`:`${(t.avgResponseHours/24).toFixed(1)} days`})]})]}),e.jsxs(te,{children:[e.jsx(ue,{className:"pb-3",children:e.jsx(xe,{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(Xe,{className:"w-5 h-5 text-orange-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Awaiting approval"})]})]})]})}function X5({approverName:t,approverStats:s,dateRange:a="all",customStartDate:r,customEndDate:n}){return e.jsxs(te,{"data-testid":"approver-actions-stats",children:[e.jsxs(ue,{children:[e.jsx(xe,{children:"Approver's Actions"}),e.jsxs(ke,{children:["Statistics for all requests by ",t," ",a&&a!=="all"?Cj(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($t,{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(De,{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(jt,{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(Xe,{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(Ei,{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(Pe,{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(Vt,{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(h0,{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(Ge,{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(di,{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 Q5({searchTerm:t,statusFilter:s,priorityFilter:a,slaComplianceFilter:r,dateRange:n,customStartDate:i,customEndDate:l,showCustomDatePicker:o,tempCustomStartDate:d,tempCustomEndDate:c,onSearchChange:m,onStatusChange:u,onPriorityChange:x,onSlaComplianceChange:p,onDateRangeChange:g,onShowCustomDatePickerChange:y,onTempStartDateChange:f,onTempEndDateChange:b,onApplyCustomDate:v,onClearFilters:A}){return e.jsxs(te,{"data-testid":"approver-performance-filters",children:[e.jsx(ue,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(xe,{children:"Filters"}),e.jsx(F,{variant:"ghost",size:"sm",onClick:A,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(As,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(_e,{placeholder:"Search requests...",value:t,onChange:w=>m(w.target.value),className:"pl-10","data-testid":"search-input"})]}),e.jsxs(Ve,{value:s,onValueChange:u,children:[e.jsx(He,{"data-testid":"status-filter",children:e.jsx(ze,{placeholder:"Status"})}),e.jsxs(We,{children:[e.jsx(K,{value:"all",children:"All Status"}),e.jsx(K,{value:"pending",children:"Pending"}),e.jsx(K,{value:"approved",children:"Approved"}),e.jsx(K,{value:"rejected",children:"Rejected"}),e.jsx(K,{value:"closed",children:"Closed"})]})]}),e.jsxs(Ve,{value:a,onValueChange:x,children:[e.jsx(He,{"data-testid":"priority-filter",children:e.jsx(ze,{placeholder:"Priority"})}),e.jsxs(We,{children:[e.jsx(K,{value:"all",children:"All Priority"}),e.jsx(K,{value:"express",children:"Express"}),e.jsx(K,{value:"standard",children:"Standard"})]})]}),e.jsxs(Ve,{value:r,onValueChange:p,children:[e.jsx(He,{"data-testid":"sla-compliance-filter",children:e.jsx(ze,{placeholder:"SLA Compliance"})}),e.jsxs(We,{children:[e.jsx(K,{value:"all",children:"All SLA"}),e.jsx(K,{value:"compliant",children:"Compliant"}),e.jsx(K,{value:"on-track",children:"On Track"}),e.jsx(K,{value:"approaching",children:"Approaching"}),e.jsx(K,{value:"critical",children:"Critical"}),e.jsx(K,{value:"breached",children:"Breached"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(it,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ve,{value:n,onValueChange:g,children:[e.jsx(He,{className:"flex-1","data-testid":"date-range-filter",children:e.jsx(ze,{placeholder:"Date Range"})}),e.jsxs(We,{children:[e.jsx(K,{value:"all",children:"All Time"}),e.jsx(K,{value:"today",children:"Today"}),e.jsx(K,{value:"week",children:"This Week"}),e.jsx(K,{value:"month",children:"This Month"}),e.jsx(K,{value:"last7days",children:"Last 7 Days"}),e.jsx(K,{value:"last30days",children:"Last 30 Days"}),e.jsx(K,{value:"custom",children:"Custom Range"})]})]}),n==="custom"&&e.jsxs(Ys,{open:o,onOpenChange:y,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(it,{className:"w-4 h-4"}),d&&c?`${Ye(d,"MMM d")} - ${Ye(c,"MMM d")}`:"Select dates"]})}),e.jsx(Xs,{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(le,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(_e,{id:"start-date",type:"date",value:d?Ye(d,"yyyy-MM-dd"):"",onChange:w=>{const T=w.target.value?new Date(w.target.value):void 0;T?(f(T),c&&T>c&&b(T)):f(void 0)},max:Ye(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(_e,{id:"end-date",type:"date",value:c?Ye(c,"yyyy-MM-dd"):"",onChange:w=>{const T=w.target.value?new Date(w.target.value):void 0;T?(b(T),d&&T<d&&f(T)):b(void 0)},min:d?Ye(d,"yyyy-MM-dd"):void 0,max:Ye(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:!d||!c,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:()=>{y(!1),f(i),b(l),(!i||!l)&&g("all")},"data-testid":"cancel-date-button",children:"Cancel"})]})]})})]})]})]})})]})}const J5=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ks,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Vt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Vt,iconColor:"text-gray-600"}}},q5=t=>{switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:De,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:jt,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:Xe,iconColor:"text-yellow-600"};case"in-progress":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Xe,iconColor:"text-blue-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:De,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Pe,iconColor:"text-gray-600"}}},ek=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 tk(t){if(!t)return"N/A";try{return Ye(new Date(t),"MMM d, yyyy")}catch{return"N/A"}}function sk(t){if(!t)return"N/A";try{return Ye(new Date(t),"MMM d, yyyy HH:mm")}catch{return"N/A"}}function bi(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=YT(s);n(l)}function ak({requests:t,loading:s,approverName:a,currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:l,onPageChange:o}){const d=Fa();return e.jsxs(te,{"data-testid":"approver-performance-request-list",children:[e.jsxs(ue,{children:[e.jsx(xe,{children:"Request Details"}),e.jsxs(ke,{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(Bt,{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(Pe,{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(c=>{const m=J5(c.priority),u=q5(c.status),x=ek(c.slaStatus||""),p=m.icon,g=u.icon;return e.jsx(te,{className:"hover:shadow-md transition-shadow cursor-pointer",onClick:()=>{bi({requestId:c.requestId,requestTitle:c.title,status:c.status,request:c,navigate:d})},"data-testid":`request-card-${c.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:c.requestNumber}),e.jsxs(ne,{className:m.color,"data-testid":"priority-badge",children:[e.jsx(p,{className:`w-3 h-3 mr-1 ${m.iconColor}`}),c.priority]}),e.jsxs(ne,{className:u.color,"data-testid":"status-badge",children:[e.jsx(g,{className:`w-3 h-3 mr-1 ${u.iconColor}`}),c.status]}),c.approvalStatus&&e.jsx(ne,{className:c.approvalStatus==="approved"||c.approvalStatus==="APPROVED"?"bg-green-100 text-green-800 border-green-200":c.approvalStatus==="rejected"||c.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:c.approvalStatus==="approved"||c.approvalStatus==="APPROVED"?e.jsxs(e.Fragment,{children:[e.jsx(De,{className:"w-3 h-3 mr-1"}),"Approved"]}):c.approvalStatus==="rejected"||c.approvalStatus==="REJECTED"?e.jsxs(e.Fragment,{children:[e.jsx(jt,{className:"w-3 h-3 mr-1"}),"Rejected"]}):e.jsxs(e.Fragment,{children:[e.jsx(Xe,{className:"w-3 h-3 mr-1"}),"Pending"]})}),c.slaStatus&&e.jsx(ne,{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:c.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(_t,{className:"w-3 h-3"}),c.initiatorName,c.initiatorDepartment&&e.jsxs("span",{className:"ml-1",children:["(",c.initiatorDepartment,")"]})]}),e.jsxs("span",{className:"flex items-center gap-1","data-testid":"submission-date",children:[e.jsx(Xe,{className:"w-3 h-3"}),"Submitted: ",tk(c.submissionDate)]}),c.approvalActionDate&&e.jsxs("span",{className:"flex items-center gap-1","data-testid":"action-date",children:[e.jsx(De,{className:"w-3 h-3"}),"Action: ",sk(c.approvalActionDate)]}),e.jsxs("span",{className:"flex items-center gap-1","data-testid":"approval-level",children:[e.jsx(Vt,{className:"w-3 h-3"}),"Level ",c.levelNumber," of ",c.totalLevels]}),c.levelElapsedHours&&c.levelElapsedHours>0&&e.jsxs("span",{className:"flex items-center gap-1","data-testid":"tat-info",children:[e.jsx(wo,{className:"w-3 h-3"}),Lt(c.levelElapsedHours)," / ",Lt(c.levelTatHours||0)," TAT"]})]})]}),e.jsx(F,{variant:"ghost",size:"sm",onClick:y=>{y.stopPropagation(),bi({requestId:c.requestId,requestTitle:c.title,status:c.status,request:c,navigate:d})},"data-testid":"view-request-button",children:e.jsx(ds,{className:"w-4 h-4"})})]})})},c.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 rk(){const[t]=dx(),[s,a]=h.useState(""),[r,n]=h.useState(t.get("status")||"all"),[i,l]=h.useState(t.get("priority")||"all"),[o,d]=h.useState(t.get("slaCompliance")||"all"),[c,m]=h.useState(t.get("dateRange")||"all"),[u,x]=h.useState(t.get("startDate")?new Date(t.get("startDate")):void 0),[p,g]=h.useState(t.get("endDate")?new Date(t.get("endDate")):void 0),[y,f]=h.useState(!1),[b,v]=h.useState(void 0),[A,w]=h.useState(void 0),T=h.useCallback(()=>{a(""),n("all"),l("all"),d("all"),m("all"),x(void 0),g(void 0),v(void 0),w(void 0),f(!1)},[]),k=h.useCallback(D=>{const S=D;m(S),S!=="custom"?(x(void 0),g(void 0),v(void 0),w(void 0),f(!1)):(v(u),w(p),f(!0))},[u,p]),L=h.useCallback(()=>{if(b&&A){if(b>A){const D=b;x(A),g(D),v(A),w(D)}else x(b),g(A);f(!1)}},[b,A]);return{searchTerm:s,statusFilter:r,priorityFilter:i,slaComplianceFilter:o,dateRange:c,customStartDate:u,customEndDate:p,showCustomDatePicker:y,tempCustomStartDate:b,tempCustomEndDate:A,setSearchTerm:a,setStatusFilter:n,setPriorityFilter:l,setSlaComplianceFilter:d,setDateRange:m,setCustomStartDate:x,setCustomEndDate:g,setShowCustomDatePicker:f,setTempCustomStartDate:v,setTempCustomEndDate:w,clearFilters:T,handleDateRangeChange:k,handleApplyCustomDate:L}}function nk({approverId:t,dateRange:s,customStartDate:a,customEndDate:r,statusFilter:n,priorityFilter:i,slaComplianceFilter:l,searchTerm:o,itemsPerPage:d}){const[c,m]=h.useState([]),[u,x]=h.useState(null),[p,g]=h.useState([]),[y,f]=h.useState(!0),[b,v]=h.useState(!1),[A,w]=h.useState(1),[T,k]=h.useState(1),[L,D]=h.useState(0),S=h.useRef(!0),N=h.useCallback(async()=>{if(t)try{const E=s==="all"?void 0:s,M=await Ct.getSingleApproverStats(t,E,a,r,i!=="all"?i:void 0,l!=="all"?l:void 0);x(M)}catch(E){console.error("[ApproverPerformance] Failed to fetch approver stats:",E),x(null)}},[t,s,a,r,i,l]),P=h.useCallback(async(E=1)=>{if(!t){f(!1);return}try{f(!0);const M=await Ct.getRequestsByApprover(t,E,d,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(M.requests),D(M.pagination.totalRecords),k(M.pagination.totalPages),w(M.pagination.currentPage),g(M.requests)}catch(M){console.error("Failed to fetch requests:",M)}finally{f(!1),v(!1)}},[t,s,a,r,n,i,l,o,d]);h.useEffect(()=>{S.current&&(S.current=!1,N(),P(1))},[]),h.useEffect(()=>{S.current||N()},[s,a,r,i,l]),h.useEffect(()=>{S.current||P(1)},[s,a,r,n,i,l,o]);const R=h.useCallback(()=>{v(!0),N(),P(1)},[N,P]),O=h.useCallback(E=>{P(E)},[P]);return{requests:c,approverStats:u,allFilteredRequests:p,loading:y,refreshing:b,currentPage:A,totalPages:T,totalRecords:L,handleRefresh:R,handlePageChange:O}}const ku=10;function ik(){const[t]=dx(),s=t.get("approverId")||"",a=t.get("approverName")||"Unknown Approver",r=rk(),n=nk({approverId:s,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,slaComplianceFilter:r.slaComplianceFilter,searchTerm:r.searchTerm,itemsPerPage:ku});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(Y5,{approverName:a,refreshing:n.refreshing,onRefresh:n.handleRefresh}),n.approverStats&&e.jsx(Z5,{approverStats:n.approverStats}),n.approverStats&&e.jsx(X5,{approverName:a,approverStats:n.approverStats,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate}),e.jsx(Q5,{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(ak,{requests:n.requests,loading:n.loading,approverName:a,currentPage:n.currentPage,totalPages:n.totalPages,totalRecords:n.totalRecords,itemsPerPage:ku,onPageChange:n.handlePageChange})]}):e.jsx(K5,{})}function lk(){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(te,{className:"relative overflow-hidden shadow-xl border-0",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900"}),e.jsx(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(rs,{className:"h-24 w-24 ring-4 ring-white/20 shadow-xl",children:[e.jsx(Li,{src:(t==null?void 0:t.picture)||""}),e.jsx(ns,{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(as,{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(ne,{className:"bg-yellow-400 text-slate-900 hover:bg-yellow-400 font-semibold",children:[e.jsx(as,{className:"w-3 h-3 mr-1"}),"Administrator"]}),tn(t)&&e.jsxs(ne,{className:"bg-blue-400 text-slate-900 hover:bg-blue-400 font-semibold",children:[e.jsx($t,{className:"w-3 h-3 mr-1"}),"Management"]}),(t==null?void 0:t.employeeId)&&e.jsxs(ne,{variant:"outline",className:"border-white/30 text-white bg-white/10",children:["ID: ",t.employeeId]})]})]})})})]})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(te,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(ue,{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(_t,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-lg text-gray-900",children:"Personal Information"}),e.jsx(ke,{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(_t,{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(_t,{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(_t,{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(Ci,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"Phone"}),e.jsx("p",{className:"text-base text-gray-900",children:t.phone})]})]})]})})]}),e.jsxs(te,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(ue,{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(Ld,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-lg text-gray-900",children:"Professional Information"}),e.jsx(ke,{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(_t,{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(fo,{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(Ld,{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(as,{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(ne,{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(De,{className:"w-4 h-4 text-green-600"})]})]})]})]})})]})]}),e.jsxs(te,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(ue,{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(it,{className:"h-5 w-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-lg text-gray-900",children:"Account Status"}),e.jsx(ke,{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(De,{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(ne,{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",ok="https://re-workflow-nt-dev.siplsolutions.com";function Il(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 ck(){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 dk(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:Il(Gn)})}else try{s=await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Il(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:Il(Gn)})}catch(o){const d=(l==null?void 0:l.message)||(o==null?void 0:o.message)||"Unknown error";throw d.includes("push service error")||d.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: ${d}`)}}}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(`${ok}/api/v1/workflows/notifications/subscribe`,{method:"POST",headers:i,credentials:"include",body:JSON.stringify(a)});if(!l.ok){const d=await l.json().catch(()=>({error:"Unknown error"}));throw new Error((d==null?void 0:d.error)||(d==null?void 0:d.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 mk(){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 ck()}catch(a){throw new Error(`Service worker registration failed: ${(a==null?void 0:a.message)||"Unknown error"}`)}try{await dk(s)}catch(a){throw a}}function mo({className:t,defaultValue:s,value:a,min:r=0,max:n=100,...i}){const l=h.useMemo(()=>Array.isArray(a)?a:Array.isArray(s)?s:[r,n],[a,s,r,n]);return e.jsxs(jf,{"data-slot":"slider",defaultValue:s,value:a,min:r,max:n,className:Re("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(Nf,{"data-slot":"slider-track",className:Re("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(wf,{"data-slot":"slider-range",className:Re("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full")})}),Array.from({length:l.length},(o,d)=>e.jsx(Cf,{"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"},d))]})}function uk({onConfigUpdate:t}){const[s,a]=h.useState([]),[r,n]=h.useState(!0),[i,l]=h.useState(null),[o,d]=h.useState(null),[c,m]=h.useState({}),[u,x]=h.useState(null);h.useEffect(()=>{p()},[]);const p=async()=>{var N,P;try{n(!0),d(null);const R=await Hi();a(R)}catch(R){d(((P=(N=R.response)==null?void 0:N.data)==null?void 0:P.error)||"Failed to load configurations")}finally{n(!1)}},g=async N=>{var P,R;try{l(N.configKey),d(null);const O=c[N.configKey]??N.configValue;if(N.validationRules){const E=parseFloat(O);if(N.valueType==="NUMBER"){if(N.validationRules.min!==void 0&&E<N.validationRules.min)throw new Error(`Value must be at least ${N.validationRules.min}`);if(N.validationRules.max!==void 0&&E>N.validationRules.max)throw new Error(`Value must be at most ${N.validationRules.max}`)}}await Ss(N.configKey,O),a(E=>E.map(M=>M.configKey===N.configKey?{...M,configValue:O}:M)),m(E=>{const M={...E};return delete M[N.configKey],M}),x(`${N.displayName} updated successfully`),setTimeout(()=>x(null),3e3),t&&t()}catch(O){d(O.message||((R=(P=O.response)==null?void 0:P.data)==null?void 0:R.error)||"Failed to save configuration")}finally{l(null)}},y=async N=>{var P,R;if(confirm(`Reset "${N.displayName}" to default value?`))try{l(N.configKey),d(null),await ZC(N.configKey),a(O=>O.map(E=>E.configKey===N.configKey?{...E,configValue:E.defaultValue||""}:E)),m(O=>{const E={...O};return delete E[N.configKey],E}),x(`${N.displayName} reset to default`),setTimeout(()=>x(null),3e3)}catch(O){d(((R=(P=O.response)==null?void 0:P.data)==null?void 0:R.error)||"Failed to reset configuration")}finally{l(null)}},f=(N,P)=>{m(R=>({...R,[N]:P}))},b=N=>c[N.configKey]??N.configValue,v=N=>c[N.configKey]!==void 0&&c[N.configKey]!==N.configValue,A=N=>{var O,E,M,B;const P=b(N),R=i===N.configKey;if(!N.isEditable)return e.jsxs("div",{className:"p-3 bg-slate-100 border border-slate-200 rounded-md",children:[e.jsx("p",{className:"text-sm text-slate-700 font-mono",children:N.configValue}),e.jsxs("p",{className:"text-xs text-slate-500 mt-1.5 flex items-center gap-1",children:[e.jsx(Ge,{className:"w-3 h-3"}),"This setting cannot be modified"]})]});switch(N.uiComponent||N.valueType.toLowerCase()){case"toggle":return e.jsxs("div",{className:"flex items-center justify-between p-3 bg-slate-50 border border-slate-200 rounded-md hover:bg-slate-100 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`w-2 h-2 rounded-full ${P==="true"?"bg-green-500":"bg-slate-400"}`}),e.jsx("span",{className:`text-sm font-medium ${P==="true"?"text-green-700":"text-slate-600"}`,children:P==="true"?"Enabled":"Disabled"})]}),e.jsx(Ps,{checked:P==="true",onCheckedChange:$=>f(N.configKey,$?"true":"false"),disabled:R})]});case"slider":const C=parseInt(P)||0,j=((O=N.validationRules)==null?void 0:O.min)||0,U=((E=N.validationRules)==null?void 0:E.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:[C,"%"]}),e.jsxs("span",{className:"text-xs text-slate-500 bg-slate-100 px-2 py-1 rounded-sm border border-slate-200",children:["Range: ",j,"-",U]})]}),e.jsx(mo,{value:[C],min:j,max:U,step:1,onValueChange:([$])=>{$!==void 0&&f(N.configKey,$.toString())},disabled:R,className:"w-full"})]});case"number":return e.jsx(_e,{type:"number",value:P,onChange:$=>f(N.configKey,$.target.value),disabled:R,min:(M=N.validationRules)==null?void 0:M.min,max:(B=N.validationRules)==null?void 0:B.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(_e,{type:"text",value:P,onChange:$=>f(N.configKey,$.target.value),disabled:R,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=N=>{switch(N){case"TAT_SETTINGS":return e.jsx(Xe,{className:"w-5 h-5"});case"DOCUMENT_POLICY":return e.jsx(Pe,{className:"w-5 h-5"});case"NOTIFICATION_RULES":return e.jsx(ks,{className:"w-5 h-5"});case"AI_CONFIGURATION":return e.jsx(Ai,{className:"w-5 h-5"});case"WORKFLOW_SHARING":return e.jsx(Br,{className:"w-5 h-5"});default:return e.jsx(za,{className:"w-5 h-5"})}},T=["DASHBOARD_LAYOUT"],k=["ALLOW_EXTERNAL_SHARING","NOTIFICATION_BATCH_DELAY_MS","AI_REMARK_MAX_CHARACTERS"],L=s.filter(N=>!T.includes(N.configCategory)&&!k.includes(N.configKey)),D=L.reduce((N,P)=>(N[P.configCategory]||(N[P.configCategory]=[]),N[P.configCategory].push(P),N),{});if(Object.keys(D).forEach(N=>{const P=D[N];P&&P.sort((R,O)=>R.sortOrder-O.sortOrder)}),r)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Ze,{className:"w-8 h-8 animate-spin text-gray-400"})});if(L.length===0)return e.jsx(te,{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(za,{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 S=Object.keys(D);return e.jsxs("div",{className:"space-y-6",children:[u&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-green-50 to-emerald-50 border border-green-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-green-500 rounded-md",children:e.jsx(De,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-green-900",children:u})]}),o&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-red-50 to-rose-50 border border-red-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-red-500 rounded-md",children:e.jsx(Ge,{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:()=>d(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsxs(Ln,{defaultValue:S[0],className:"w-full",children:[e.jsx(On,{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:S.map(N=>e.jsx(At,{value:N,className:"flex-1 min-w-[120px] text-[10px] xs:text-xs sm:text-sm font-medium py-2 sm:py-2.5 px-2 sm:px-3 rounded-sm data-[state=active]:bg-white data-[state=active]:shadow-sm data-[state=active]:text-slate-900 transition-all",children:e.jsx("span",{className:"truncate block",children:N.replace(/_/g," ")})},N))}),S.map(N=>{var P,R,O;return e.jsx(St,{value:N,className:"space-y-4 mt-6",children:e.jsxs(te,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ue,{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(N)})}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-lg font-semibold text-slate-900",children:N.replace(/_/g," ")}),e.jsxs(ke,{className:"text-sm",children:[((P=D[N])==null?void 0:P.length)||0," setting",(((R=D[N])==null?void 0:R.length)||0)!==1?"s":""," available"]})]})]})}),e.jsx(ae,{className:"space-y-6",children:(O=D[N])==null?void 0:O.map(E=>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(le,{className:"text-sm font-semibold text-slate-900",children:E.displayName}),v(E)&&e.jsx(ne,{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"}),E.requiresRestart&&e.jsx(ne,{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"})]}),E.description&&e.jsx("p",{className:"text-xs text-slate-600 mt-1 leading-relaxed",children:E.description}),E.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:E.defaultValue})]})]})}),A(E),E.isEditable&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(F,{size:"sm",onClick:()=>g(E),disabled:!v(E)||i===E.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===E.configKey?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-4 h-4 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Za,{className:"w-4 h-4"}),"Save Changes"]})}),E.defaultValue&&e.jsxs(F,{size:"sm",variant:"outline",onClick:()=>y(E),disabled:i===E.configKey,className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(p0,{className:"w-4 h-4"}),"Reset to Default"]})]})]},E.configKey))})]})},N)})]})]})}function xk(){const[t,s]=h.useState([]),[a,r]=h.useState(!0),[n,i]=h.useState(new Date().getFullYear()),[l,o]=h.useState(!1),[d,c]=h.useState(null),[m,u]=h.useState(null),[x,p]=h.useState(null),[g,y]=h.useState({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1});h.useEffect(()=>{f()},[n]);const f=async()=>{var N,P;try{r(!0),u(null);const R=await XC(n);s(R)}catch(R){u(((P=(N=R.response)==null?void 0:N.data)==null?void 0:P.error)||"Failed to load holidays")}finally{r(!1)}},b=()=>{y({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1}),c(null),o(!0)},v=N=>{y({holidayDate:N.holidayDate,holidayName:N.holidayName,description:N.description||"",holidayType:N.holidayType,isRecurring:N.isRecurring}),c(N),o(!0)},A=()=>{if(d)return;const N=new Date;return N.setDate(N.getDate()+1),N.toISOString().split("T")[0]},w=async()=>{var N,P;try{if(u(null),!g.holidayDate||!g.holidayName){u("Holiday date and name are required");return}d?(await JC(d.holidayId,g),p("Holiday updated successfully")):(await QC(g),p("Holiday created successfully")),await f(),o(!1),setTimeout(()=>p(null),3e3)}catch(R){u(((P=(N=R.response)==null?void 0:N.data)==null?void 0:P.error)||"Failed to save holiday")}},T=async N=>{var P,R;if(confirm(`Delete "${N.holidayName}"?`))try{u(null),await qC(N.holidayId),p("Holiday deleted successfully"),await f(),setTimeout(()=>p(null),3e3)}catch(O){u(((R=(P=O.response)==null?void 0:P.data)==null?void 0:R.error)||"Failed to delete holiday")}},k=N=>{switch(N){case"NATIONAL":return"bg-gradient-to-r from-red-50 to-rose-50 text-red-800 border-red-300";case"REGIONAL":return"bg-gradient-to-r from-blue-50 to-cyan-50 text-blue-800 border-blue-300";case"ORGANIZATIONAL":return"bg-gradient-to-r from-purple-50 to-violet-50 text-purple-800 border-purple-300";case"OPTIONAL":return"bg-gradient-to-r from-slate-50 to-gray-50 text-slate-700 border-slate-300"}},L=Array.from({length:5},(N,P)=>new Date().getFullYear()-1+P),D=t.reduce((N,P)=>{const R=new Date(P.holidayDate).toLocaleString("default",{month:"long"});return N[R]||(N[R]=[]),N[R].push(P),N},{}),S=Object.keys(D).sort((N,P)=>{const R=new Date(Date.parse(N+" 1, 2000")).getMonth(),O=new Date(Date.parse(P+" 1, 2000")).getMonth();return R-O});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(De,{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(Ge,{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:()=>u(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsx(te,{className:"shadow-lg border-0 rounded-md",children:e.jsx(ue,{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(it,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Holiday Calendar"}),e.jsx(ke,{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(Ve,{value:n.toString(),onValueChange:N=>i(parseInt(N)),children:[e.jsx(He,{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(ze,{})}),e.jsx(We,{className:"rounded-md",children:L.map(N=>e.jsx(K,{value:N.toString(),children:N},N))})]}),e.jsxs(F,{onClick:b,className:"gap-2 bg-re-green hover:bg-re-green/90 text-white shadow-sm flex-1 sm:flex-initial",children:[e.jsx(vs,{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(Ze,{className:"w-8 h-8 animate-spin text-gray-400"})}):t.length===0?e.jsx(te,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(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(it,{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:b,variant:"outline",className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(vs,{className:"w-4 h-4"}),"Add First Holiday"]})]})}):e.jsx("div",{className:"space-y-4 sm:space-y-6",children:S.map(N=>{var P,R,O;return e.jsxs(te,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ue,{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(xe,{className:"text-base sm:text-lg font-semibold text-slate-900",children:[N," ",n]}),e.jsxs(ke,{className:"text-xs sm:text-sm",children:[((P=D[N])==null?void 0:P.length)||0," holiday",(((R=D[N])==null?void 0:R.length)||0)!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-blue-50 rounded-md",children:e.jsx(it,{className:"w-4 h-4 text-blue-600"})})]})}),e.jsx(ae,{className:"space-y-3 pt-4",children:(O=D[N])==null?void 0:O.map(E=>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:E.holidayName}),e.jsx(ne,{variant:"outline",className:`${k(E.holidayType)} text-[10px] sm:text-xs font-medium shadow-sm`,children:E.holidayType}),E.isRecurring&&e.jsx(ne,{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:Zx(E.holidayDate)}),E.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-1.5 line-clamp-2",children:E.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(E),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(ci,{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:()=>T(E),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(Fi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Delete"})]})]})]},E.holidayId))})]},N)})}),e.jsx(mt,{open:l,onOpenChange:o,children:e.jsxs(ot,{className:"sm:max-w-[550px] max-h-[90vh] rounded-lg flex flex-col p-0",children:[e.jsx(ut,{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(it,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ct,{className:"text-xl font-semibold text-slate-900",children:d?"Edit Holiday":"Add New Holiday"}),e.jsx(It,{className:"text-sm text-slate-600 mt-1",children:d?"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(le,{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(_e,{id:"date",type:"date",value:g.holidayDate,onChange:N=>y({...g,holidayDate:N.target.value}),min:A(),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:d?"Select the holiday date":"Select the holiday date (minimum: tomorrow)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(le,{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(_e,{id:"name",placeholder:"e.g., Diwali, Republic Day, Christmas",value:g.holidayName,onChange:N=>y({...g,holidayName:N.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Enter the official name of the holiday"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(le,{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(_e,{id:"description",placeholder:"Add additional details about this holiday...",value:g.description,onChange:N=>y({...g,description:N.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Optional description or notes about the holiday"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{htmlFor:"type",className:"text-sm font-semibold text-slate-900",children:"Holiday Type"}),e.jsxs(Ve,{value:g.holidayType,onValueChange:N=>y({...g,holidayType:N}),children:[e.jsx(He,{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(ze,{})}),e.jsxs(We,{className:"rounded-lg",children:[e.jsx(K,{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(K,{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(K,{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(K,{value:"OPTIONAL",className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-slate-500"}),e.jsx("span",{children:"Optional"})]})})]})]}),e.jsx("p",{className:"text-xs text-slate-500",children:"Select the category of this holiday"})]}),e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-gradient-to-br from-slate-50 to-slate-100/50 border-2 border-slate-200 rounded-lg hover:border-slate-300 hover:bg-slate-100 transition-all cursor-pointer group",onClick:()=>y({...g,isRecurring:!g.isRecurring}),children:[e.jsx("input",{type:"checkbox",id:"recurring",checked:g.isRecurring,onChange:N=>y({...g,isRecurring:N.target.checked}),className:"mt-0.5 rounded border-slate-300 text-re-green focus:ring-2 focus:ring-re-green/20 focus:ring-offset-0 w-4 h-4 cursor-pointer"}),e.jsxs("div",{className:"flex-1",children:[e.jsx(le,{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(Tt,{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(it,{className:"w-4 h-4 mr-2"}),d?"Update Holiday":"Add Holiday"]})]})]})})]})}function hk(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function pk(){const[t,s]=h.useState(""),[a,r]=h.useState([]),[n,i]=h.useState(!1),[l,o]=h.useState(null),[d,c]=h.useState("USER"),[m,u]=h.useState(!1),[x,p]=h.useState(null),[g,y]=h.useState([]),[f,b]=h.useState(!1),[v,A]=h.useState({admins:0,management:0,users:0}),[w,T]=h.useState("ELEVATED"),[k,L]=h.useState(1),[D,S]=h.useState(1),[N,P]=h.useState(0),R=10,O=h.useRef(null),E=h.useRef(null),M=h.useCallback(hk(async I=>{var V,z,X;if(!I||!I.startsWith("@")||I.length<2){r([]),i(!1);return}i(!0);try{const Y=I.slice(1),ie=((V=(await Ws.searchUsers(Y,20)).data)==null?void 0:V.data)||[];r(ie)}catch(Y){console.error("Search failed:",Y),p({type:"error",text:((X=(z=Y.response)==null?void 0:z.data)==null?void 0:X.message)||"Failed to search users"})}finally{i(!1)}},300),[]),B=I=>{const V=I.target.value;s(V),M(V)},C=async I=>{o(I),s(I.email),r([]);const V=g.find(z=>z.email.toLowerCase()===I.email.toLowerCase()||z.userId===I.userId);if(V&&V.role)c(V.role);else try{const X=(await Ws.getAllUsers()).find(Y=>Y.email&&Y.email.toLowerCase()===I.email.toLowerCase()||Y.userId&&Y.userId===I.userId);X&&X.role?c(X.role):c("USER")}catch(z){console.error("Failed to check user role:",z),c("USER")}},j=async()=>{var I,V;if(!l||!d){p({type:"error",text:"Please select a user and role"});return}u(!0),p(null);try{await Ws.assignRole(l.email,d),p({type:"success",text:`Successfully assigned ${d} role to ${l.displayName||l.email}`}),o(null),s(""),c("USER"),await U(),await $()}catch(z){console.error("Role assignment failed:",z),p({type:"error",text:((V=(I=z.response)==null?void 0:I.data)==null?void 0:V.error)||"Failed to assign role"})}finally{u(!1)}},U=async(I=k)=>{var V,z,X,Y,G,ie;b(!0);try{const me=await Ws.getUsersByRole(w,I,R),Te=((z=(V=me.data)==null?void 0:V.data)==null?void 0:z.users)||[],Se=(Y=(X=me.data)==null?void 0:X.data)==null?void 0:Y.pagination,re=(ie=(G=me.data)==null?void 0:G.data)==null?void 0:ie.summary;y(Te),Se&&(L(Se.currentPage),S(Se.totalPages),P(Se.totalUsers)),re&&A({admins:re.ADMIN||0,management:re.MANAGEMENT||0,users:re.USER||0})}catch(me){console.error("Failed to fetch users:",me)}finally{b(!1)}},$=async()=>{var I,V,z,X,Y,G;try{const ie=await Ws.getRoleStatistics(),me=((V=(I=ie.data)==null?void 0:I.data)==null?void 0:V.statistics)||((z=ie.data)==null?void 0:z.statistics)||[];A({admins:parseInt(((X=me.find(Te=>Te.role==="ADMIN"))==null?void 0:X.count)||"0"),management:parseInt(((Y=me.find(Te=>Te.role==="MANAGEMENT"))==null?void 0:Y.count)||"0"),users:parseInt(((G=me.find(Te=>Te.role==="USER"))==null?void 0:G.count)||"0")})}catch(ie){console.error("Failed to fetch statistics:",ie)}};h.useEffect(()=>{U(1),$()},[w]);const _=I=>{T(I),L(1)},se=I=>{U(I)},W=I=>{T(I),L(1),requestAnimationFrame(()=>{const V=E.current;V&&V.scrollIntoView({behavior:"smooth",block:"start"})})};h.useEffect(()=>{const I=V=>{O.current&&!O.current.contains(V.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",I),()=>{document.removeEventListener("mousedown",I)}},[a]);const ce=I=>{switch(I){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"}},Z=I=>{switch(I){case"ADMIN":return e.jsx(Sr,{className:"w-5 h-5 text-slate-800"});case"MANAGEMENT":return e.jsx($t,{className:"w-5 h-5 text-slate-800"});default:return e.jsx(_t,{className:"w-5 h-5 text-slate-800"})}};return e.jsxs(te,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ue,{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(g0,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-lg font-semibold text-gray-900",children:"User Role Management"}),e.jsx(ke,{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(te,{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:()=>W("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(Sr,{className:"w-6 h-6 text-slate-800"})})]})})}),e.jsx(te,{className:`border-2 bg-gradient-to-br from-blue-50 to-blue-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${w==="MANAGEMENT"?"border-blue-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"management-count-card",onClick:()=>W("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($t,{className:"w-6 h-6 text-slate-800"})})]})})}),e.jsx(te,{className:`border-2 bg-gradient-to-br from-gray-50 to-gray-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${w==="USER"?"border-gray-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"user-count-card",onClick:()=>W("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(_t,{className:"w-6 h-6 text-slate-800"})})]})})})]}),e.jsx(Gt,{}),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:O,children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Search User"}),e.jsxs("div",{className:"relative",children:[e.jsx(As,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none"}),e.jsx(_e,{type:"text",placeholder:"Type @ to search users...",value:t,onChange:B,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(Ze,{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(I=>e.jsxs("button",{onClick:()=>C(I),className:"w-full text-left p-2 hover:bg-purple-50 rounded-lg transition-colors mb-1 last:mb-0","data-testid":`user-result-${I.email}`,children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:I.displayName||I.email}),e.jsx("p",{className:"text-xs text-gray-600",children:I.email}),I.department&&e.jsxs("p",{className:"text-xs text-gray-500",children:[I.department,I.designation?` • ${I.designation}`:""]})]},I.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(Ve,{value:d,onValueChange:I=>c(I),children:[e.jsx(He,{className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20","data-testid":"role-select",children:e.jsx(ze,{placeholder:"Select role"})}),e.jsxs(We,{children:[e.jsx(K,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_t,{className:"w-4 h-4 text-gray-600"}),e.jsx("span",{children:"User - Regular access"})]})}),e.jsx(K,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($t,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Management - Read all data"})]})}),e.jsx(K,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sr,{className:"w-4 h-4 text-yellow-600"}),e.jsx("span",{children:"Administrator - Full access"})]})})]})]})]}),e.jsx(F,{onClick:j,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(Ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Assigning Role..."]}):e.jsxs(e.Fragment,{children:[e.jsx(as,{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(De,{className:"w-5 h-5 text-green-600 shrink-0 mt-0.5"}):e.jsx(Ge,{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(Gt,{}),e.jsxs("div",{ref:E,children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-gray-900 mb-1",children:"User Management"}),e.jsxs("p",{className:"text-sm text-gray-600",children:["View and manage user roles (",N," ",w!=="ALL"&&w!=="ELEVATED"?w.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(Ve,{value:w,onValueChange:_,children:[e.jsx(He,{className:"w-[200px] h-10 border rounded-lg border-gray-300",children:e.jsx(ze,{placeholder:"Filter by role"})}),e.jsxs(We,{children:[e.jsx(K,{value:"ELEVATED",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(as,{className:"w-4 h-4 text-purple-600"}),e.jsxs("span",{children:["Elevated (",v.admins+v.management,")"]})]})}),e.jsx(K,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sr,{className:"w-4 h-4 text-yellow-600"}),e.jsxs("span",{children:["Admins (",v.admins,")"]})]})}),e.jsx(K,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($t,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Management (",v.management,")"]})]})}),e.jsx(K,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_t,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["Users (",v.users,")"]})]})}),e.jsx(K,{value:"ALL",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($t,{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(Ze,{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($t,{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(I=>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-${I.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 ${ce(I.role)} flex items-center justify-center shadow-sm`,children:Z(I.role)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-semibold text-gray-900 truncate",children:I.displayName}),e.jsx("p",{className:"text-sm text-gray-600 truncate",children:I.email}),I.department&&e.jsxs("p",{className:"text-xs text-gray-500 mt-1 truncate",children:[I.department,I.designation?` • ${I.designation}`:""]})]})]}),e.jsx(ne,{className:`${ce(I.role)} shrink-0`,"data-testid":`role-badge-${I.role}`,children:I.role})]})},I.userId))}),D>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 ",(k-1)*R+1," to ",Math.min(k*R,N)," of ",N," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(F,{variant:"outline",size:"sm",onClick:()=>se(k-1),disabled:k===1,"data-testid":"prev-page-button",children:"Previous"}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,D)},(I,V)=>{let z;return D<=5||k<=3?z=V+1:k>=D-2?z=D-4+V:z=k-2+V,e.jsx(F,{variant:k===z?"default":"outline",size:"sm",onClick:()=>se(z),className:`w-9 h-9 p-0 ${k===z?"bg-re-green hover:bg-re-green/90 text-white":""}`,"data-testid":`page-${z}-button`,children:z},z)})}),e.jsx(F,{variant:"outline",size:"sm",onClick:()=>se(k+1),disabled:k===D,"data-testid":"next-page-button",children:"Next"})]})]})]})})]})]})]})}function gk(){const[t,s]=h.useState([]),[a,r]=h.useState(!0),[n,i]=h.useState(!1),[l,o]=h.useState(null),[d,c]=h.useState(null),[m,u]=h.useState(null),[x,p]=h.useState({title:"",itemCode:"",taxationType:"",sapRefNo:""});h.useEffect(()=>{g()},[]);const g=async()=>{var T,k;try{r(!0),c(null);const L=await tA(!1);s(L)}catch(L){const D=((k=(T=L.response)==null?void 0:T.data)==null?void 0:k.error)||"Failed to load activity types";c(D),Q.error(D)}finally{r(!1)}},y=()=>{p({title:"",itemCode:"",taxationType:"",sapRefNo:""}),o(null),i(!0)},f=T=>{p({title:T.title,itemCode:T.itemCode||"",taxationType:T.taxationType||"",sapRefNo:T.sapRefNo||""}),o(T),i(!0)},b=async()=>{var T,k;try{if(c(null),!x.title.trim()){c("Activity type title is required");return}const L={title:x.title.trim(),itemCode:x.itemCode.trim()||null,taxationType:x.taxationType.trim()||null,sapRefNo:x.sapRefNo.trim()||null};l?(await aA(l.activityTypeId,L),u("Activity type updated successfully"),Q.success("Activity type updated successfully")):(await sA(L),u("Activity type created successfully"),Q.success("Activity type created successfully")),await g(),i(!1),setTimeout(()=>u(null),3e3)}catch(L){const D=((k=(T=L.response)==null?void 0:T.data)==null?void 0:k.error)||"Failed to save activity type";c(D),Q.error(D)}},v=async T=>{var k,L;if(confirm(`Delete "${T.title}"? This will deactivate the activity type.`))try{c(null),await rA(T.activityTypeId),u("Activity type deleted successfully"),Q.success("Activity type deleted successfully"),await g(),setTimeout(()=>u(null),3e3)}catch(D){const S=((L=(k=D.response)==null?void 0:k.data)==null?void 0:L.error)||"Failed to delete activity type";c(S),Q.error(S)}},A=t.filter(T=>T.isActive!==!1&&T.isActive!==void 0),w=t.filter(T=>T.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(De,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-green-900",children:m})]}),d&&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(Ge,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:d}),e.jsx(F,{size:"sm",variant:"ghost",onClick:()=>c(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsx(te,{className:"shadow-lg border-0 rounded-md",children:e.jsx(ue,{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(Pe,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Activity Types"}),e.jsx(ke,{className:"text-sm",children:"Manage dealer claim activity types"})]})]}),e.jsxs(F,{onClick:y,className:"gap-2 bg-re-green hover:bg-re-green/90 text-white shadow-sm",children:[e.jsx(vs,{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(Ze,{className:"w-8 h-8 animate-spin text-gray-400"})}):A.length===0?e.jsx(te,{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(Pe,{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:y,variant:"outline",className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(vs,{className:"w-4 h-4"}),"Add First Activity Type"]})]})}):e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[e.jsxs(te,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ue,{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(xe,{className:"text-base sm:text-lg font-semibold text-slate-900",children:"Active Activity Types"}),e.jsxs(ke,{className:"text-xs sm:text-sm",children:[A.length," active type",A.length!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-green-50 rounded-md",children:e.jsx(De,{className:"w-4 h-4 text-green-600"})})]})}),e.jsx(ae,{className:"space-y-3 pt-4",children:A.map(T=>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:T.title}),e.jsx(ne,{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:[T.itemCode&&e.jsxs("span",{className:"font-medium",children:["Item Code: ",e.jsx("span",{className:"text-slate-900",children:T.itemCode})]}),T.taxationType&&e.jsxs("span",{className:"font-medium",children:["Taxation: ",e.jsx("span",{className:"text-slate-900",children:T.taxationType})]}),T.sapRefNo&&e.jsxs("span",{className:"font-medium",children:["SAP Ref: ",e.jsx("span",{className:"text-slate-900",children:T.sapRefNo})]}),!T.itemCode&&!T.taxationType&&!T.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(T),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(ci,{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(T),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(Fi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Delete"})]})]})]},T.activityTypeId))})]}),w.length>0&&e.jsxs(te,{className:"shadow-lg border-0 rounded-md border-amber-200",children:[e.jsx(ue,{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(xe,{className:"text-base sm:text-lg font-semibold text-slate-900",children:"Inactive Activity Types"}),e.jsxs(ke,{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(Ge,{className:"w-4 h-4 text-amber-600"})})]})}),e.jsx(ae,{className:"space-y-3 pt-4",children:w.map(T=>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:T.title}),e.jsx(ne,{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(T),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(ci,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]})})]},T.activityTypeId))})]})]}),e.jsx(mt,{open:n,onOpenChange:i,children:e.jsxs(ot,{className:"sm:max-w-[550px] max-h-[90vh] rounded-lg flex flex-col p-0",children:[e.jsx(ut,{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(Pe,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ct,{className:"text-xl font-semibold text-slate-900",children:l?"Edit Activity Type":"Add New Activity Type"}),e.jsx(It,{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(le,{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(_e,{id:"title",placeholder:"e.g., Riders Mania Claims, Legal Claims Reimbursement",value:x.title,onChange:T=>p({...x,title:T.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(le,{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(_e,{id:"itemCode",placeholder:"e.g., 1, 2, 3",value:x.itemCode,onChange:T=>p({...x,itemCode:T.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(le,{htmlFor:"taxationType",className:"text-sm font-semibold text-slate-900",children:["Taxation Type ",e.jsx("span",{className:"text-slate-400 font-normal text-xs",children:"(Optional)"})]}),e.jsx(_e,{id:"taxationType",placeholder:"e.g., GST, VAT, Exempt",value:x.taxationType,onChange:T=>p({...x,taxationType:T.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 taxation type for the activity"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(le,{htmlFor:"sapRefNo",className:"text-sm font-semibold text-slate-900",children:["SAP Reference Number ",e.jsx("span",{className:"text-slate-400 font-normal text-xs",children:"(Optional)"})]}),e.jsx(_e,{id:"sapRefNo",placeholder:"e.g., SAP-12345",value:x.sapRefNo,onChange:T=>p({...x,sapRefNo:T.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 SAP reference number"})]})]}),e.jsxs(Tt,{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:b,disabled:!x.title.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(Pe,{className:"w-4 h-4 mr-2"}),l?"Update Activity Type":"Add Activity Type"]})]})]})})]})}function fk({open:t,onClose:s,success:a,message:r}){return e.jsx(mt,{open:t,onOpenChange:s,children:e.jsxs(ot,{className:"sm:max-w-md",children:[e.jsxs(ut,{children:[e.jsxs(ct,{className:"flex items-center gap-2",children:[e.jsx(ks,{className:"w-5 h-5 text-blue-600"}),"Push Notifications"]}),e.jsx(It,{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(De,{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(jt,{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(Tt,{children:e.jsx(F,{onClick:s,className:"w-full",children:a?"Done":"Close"})})]})})}const yk=async()=>(await Ne.get("/user/preferences/notifications")).data.data,bk=async t=>(await Ne.put("/user/preferences/notifications",t)).data.data;function vk({open:t,onClose:s}){const[a,r]=h.useState({emailNotificationsEnabled:!0,pushNotificationsEnabled:!0,inAppNotificationsEnabled:!0}),[n,i]=h.useState(!0),[l,o]=h.useState(null),[d,c]=h.useState(null),[m,u]=h.useState(null);h.useEffect(()=>{t&&x()},[t]);const x=async()=>{var g,y;try{i(!0),u(null);const f=await yk();r(f)}catch(f){console.error("[NotificationPreferences] Failed to load preferences:",f),u(((y=(g=f.response)==null?void 0:g.data)==null?void 0:y.message)||"Failed to load notification preferences")}finally{i(!1)}},p=async(g,y)=>{var f,b;try{o(g),u(null),c(null);const v={[g]:y},A=await bk(v);r(A),c(`${g==="emailNotificationsEnabled"?"Email":g==="pushNotificationsEnabled"?"Push":"In-App"} notifications ${y?"enabled":"disabled"}`),setTimeout(()=>c(null),3e3)}catch(v){console.error("[NotificationPreferences] Failed to update preference:",v),u(((b=(f=v.response)==null?void 0:f.data)==null?void 0:b.message)||"Failed to update notification preference"),x()}finally{o(null)}};return e.jsx(mt,{open:t,onOpenChange:s,children:e.jsxs(ot,{className:"sm:max-w-[600px] max-h-[85vh] overflow-y-auto",children:[e.jsx(ut,{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(za,{className:"h-6 w-6 text-white"})}),e.jsxs("div",{children:[e.jsx(ct,{className:"text-xl font-semibold",children:"Notification Preferences"}),e.jsx(It,{className:"text-sm",children:"Customize how you receive notifications for workflow updates"})]})]})}),e.jsx(Gt,{className:"my-4"}),n?e.jsx("div",{className:"p-12 flex items-center justify-center",children:e.jsx(Ze,{className:"w-8 h-8 animate-spin text-gray-400"})}):e.jsxs("div",{className:"space-y-6",children:[d&&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(De,{className:"w-4 h-4 text-green-600 shrink-0"}),e.jsx("p",{className:"text-sm text-green-800 font-medium",children:d})]}),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(Ge,{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(le,{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(Ze,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(Ps,{id:"email-notifications-modal",checked:a.emailNotificationsEnabled,onCheckedChange:g=>p("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(ks,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(le,{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(Ze,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(Ps,{id:"push-notifications-modal",checked:a.pushNotificationsEnabled,onCheckedChange:g=>p("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(le,{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(Ze,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(Ps,{id:"inapp-notifications-modal",checked:a.inAppNotificationsEnabled,onCheckedChange:g=>p("inAppNotificationsEnabled",g),disabled:l==="inAppNotificationsEnabled"})]})]})}),e.jsx(Gt,{}),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 jk(){const{user:t}=Jt(),s=cr(t),[a,r]=h.useState(!1),[n,i]=h.useState(!1),[l,o]=h.useState(),[d,c]=h.useState(!1),[m,u]=h.useState(!1),[x,p]=h.useState(!1),[g,y]=h.useState(!0),[f,b]=h.useState(!1);h.useEffect(()=>{v()},[]);const v=async()=>{try{y(!0);const w=await rb();p(w.length>0)}catch(w){console.error("Failed to check subscription status:",w),p(!1)}finally{y(!1)}},A=async()=>{c(!0),r(!1);try{if(!("Notification"in window)){i(!1),o("Notifications are not supported in this browser. Please use a modern browser like Chrome, Firefox, or Edge."),r(!0),c(!1);return}let w=Notification.permission;if(w==="denied"){i(!1),o(`Notification permission was previously denied. To enable notifications:
|
||
|
||
1. Click the lock icon (🔒) or info icon (ℹ️) in your browser's address bar
|
||
2. Find "Notifications" in the permissions list
|
||
3. Change it from "Block" to "Allow"
|
||
4. Refresh this page and try again
|
||
|
||
Alternatively, you can enable notifications in your browser's site settings.`),r(!0),c(!1);return}if(w==="default"&&(w=await Notification.requestPermission(),w==="denied")){i(!1),o(`Notification permission was denied. To enable notifications:
|
||
|
||
1. Click the lock icon (🔒) or info icon (ℹ️) in your browser's address bar
|
||
2. Find "Notifications" in the permissions list
|
||
3. Change it from "Block" to "Allow"
|
||
4. Refresh this page and try again`),r(!0),c(!1);return}if(w!=="granted"){i(!1),o("Notification permission is required to enable push notifications. Please grant permission and try again."),r(!0),c(!1);return}await mk(),i(!0),o("Push notifications have been successfully enabled! You will now receive notifications for workflow updates, approvals, and TAT alerts."),r(!0),await v()}catch(w){console.error("[Settings] Error enabling notifications:",w),i(!1);const T=(w==null?void 0:w.message)||"Unknown error occurred";o(T.includes("permission")?"Notification permission was denied. Please enable notifications in your browser settings and try again.":T.includes("Service worker")?"Service worker registration failed. Please refresh the page and try again.":T.includes("token")?"Authentication required. Please log in again and try enabling notifications.":`Unable to enable push notifications: ${T}`),r(!0)}finally{c(!1)}};return e.jsxs("div",{className:"min-h-screen pb-8",children:[e.jsxs("div",{className:"max-w-7xl mx-auto space-y-6",children:[e.jsxs(te,{className:"relative overflow-hidden shadow-2xl border-0 rounded-2xl",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900"}),e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_top_right,_var(--tw-gradient-stops))] from-yellow-400/20 via-transparent to-transparent"}),e.jsx(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(za,{className:"w-7 h-7 sm:w-8 sm:h-8 text-slate-900"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl sm:text-3xl lg:text-4xl font-bold text-white mb-1 sm:mb-2",children:"Settings"}),e.jsx("p",{className:"text-sm sm:text-base lg:text-lg text-gray-300",children:"Manage your account and preferences"})]})]})})]}),s?e.jsxs(Ln,{defaultValue:"user",className:"w-full",children:[e.jsxs(On,{className:"grid w-full grid-cols-2 lg:grid-cols-5 mb-8 bg-slate-100 p-1 rounded-xl h-auto gap-1",children:[e.jsxs(At,{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(za,{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(At,{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(as,{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(At,{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(ox,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Configuration"}),e.jsx("span",{className:"sm:hidden",children:"Config"})]}),e.jsxs(At,{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(it,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Holidays"}),e.jsx("span",{className:"sm:hidden",children:"Holidays"})]}),e.jsxs(At,{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(Pe,{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(St,{value:"user",className:"mt-0 space-y-0",children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6",children:[e.jsxs(te,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ue,{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(ks,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-lg font-semibold text-gray-900",children:"Browser Push Setup"}),e.jsx(ke,{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:[g?e.jsx("div",{className:"p-4 bg-gray-50 border border-gray-200 rounded-md flex items-center justify-center",children:e.jsx("p",{className:"text-sm text-gray-600",children:"Checking registration status..."})}):x?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:A,disabled:d||x,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(ks,{className:`w-4 h-4 mr-2 ${d?"animate-pulse":""}`}),d?"Registering...":x?"Already Registered":"Register Browser for Push"]})]})})]}),e.jsxs(te,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ue,{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(yn,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-lg font-semibold text-gray-900",children:"Security"}),e.jsx(ke,{className:"text-sm text-gray-600",children:"Password and security settings"})]})]})}),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:"Security settings will be available soon"})})})})]}),e.jsxs(te,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ue,{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(Od,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-lg font-semibold text-gray-900",children:"Appearance"}),e.jsx(ke,{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(te,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ue,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(as,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-lg font-semibold text-gray-900",children:"Preferences"}),e.jsx(ke,{className:"text-sm text-gray-600",children:"Notification and application preferences"})]})]})}),e.jsx(ae,{children:e.jsxs(F,{onClick:()=>u(!0),className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all",children:[e.jsx(as,{className:"w-4 h-4 mr-2"}),"Manage Preferences"]})})]})]})}),e.jsx(St,{value:"roles",className:"mt-0",children:e.jsx(pk,{})}),e.jsx(St,{value:"system",className:"mt-0",children:e.jsx(uk,{})}),e.jsx(St,{value:"holidays",className:"mt-0",children:e.jsx(xk,{})}),e.jsx(St,{value:"templates",className:"mt-0",children:f?e.jsxs("div",{className:"space-y-4",children:[e.jsx(te,{className:"shadow-lg border-0 rounded-md",children:e.jsx(ue,{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:()=>b(!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(Pe,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Dealer Claim Activity Settings"}),e.jsx(ke,{className:"text-sm",children:"Manage activity types for dealer claim workflows"})]})]})})})}),e.jsx(gk,{})]}):e.jsxs(te,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ue,{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(Pe,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Template Settings"}),e.jsx(ke,{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(te,{className:"shadow-md hover:shadow-lg transition-all duration-300 border border-slate-200 rounded-lg cursor-pointer group",onClick:()=>b(!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(Pe,{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(te,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ue,{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(ks,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-lg font-semibold text-gray-900",children:"Browser Push Setup"}),e.jsx(ke,{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:[g?e.jsx("div",{className:"p-4 bg-gray-50 border border-gray-200 rounded-md flex items-center justify-center",children:e.jsx("p",{className:"text-sm text-gray-600",children:"Checking registration status..."})}):x?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:A,disabled:d||x,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(ks,{className:`w-4 h-4 mr-2 ${d?"animate-pulse":""}`}),d?"Registering...":x?"Already Registered":"Register Browser for Push"]})]})})]}),e.jsxs(te,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ue,{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(yn,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-lg font-semibold text-gray-900",children:"Security"}),e.jsx(ke,{className:"text-sm text-gray-600",children:"Password and security settings"})]})]})}),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:"Security settings will be available soon"})})})})]}),e.jsxs(te,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ue,{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(Od,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-lg font-semibold text-gray-900",children:"Appearance"}),e.jsx(ke,{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(te,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(ue,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md group-hover:shadow-lg transition-shadow",children:e.jsx(as,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-lg font-semibold text-gray-900",children:"Preferences"}),e.jsx(ke,{className:"text-sm text-gray-600",children:"Notification and application preferences"})]})]})}),e.jsx(ae,{children:e.jsxs(F,{onClick:()=>u(!0),className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all",children:[e.jsx(as,{className:"w-4 h-4 mr-2"}),"Manage Preferences"]})})]})]})})]}),e.jsx(fk,{open:a,onClose:()=>r(!1),success:n,message:l}),e.jsx(vk,{open:m,onClose:()=>u(!1)})]})}function Nk({onNavigate:t}){const[s,a]=h.useState([]),[r,n]=h.useState(!0),[i,l]=h.useState(1),[o,d]=h.useState(1),[c,m]=h.useState(0),[u,x]=h.useState("all"),[p,g]=h.useState(!1),y=20,f=async(S=i,N=u==="unread")=>{var P,R;try{n(S===1);const O=await Va.list({page:S,limit:y,unreadOnly:N}),E=((P=O.data)==null?void 0:P.notifications)||[],M=((R=O.data)==null?void 0:R.pagination)||{},B=M.total||0,C=M.totalPages||1;a(E),m(B),d(C),l(S)}catch(O){console.error("[Notifications] Failed to fetch:",O)}finally{n(!1),g(!1)}};h.useEffect(()=>{l(1),f(1,u==="unread")},[u]);const b=async S=>{var N;try{if(S.isRead||(await Va.markAsRead(S.notificationId),a(P=>P.map(R=>R.notificationId===S.notificationId?{...R,isRead:!0}:R))),S.actionUrl&&t){const P=(N=S.metadata)==null?void 0:N.requestNumber;if(P){let R=`request/${P}`;(S.notificationType==="mention"||S.notificationType==="comment"||S.notificationType==="worknote")&&(R+="?tab=worknotes"),S.notificationType==="document_added"&&(R+="?tab=documents"),t(R)}}}catch(P){console.error("[Notifications] Error handling notification click:",P)}},v=async()=>{try{g(!0),await Va.markAllAsRead(),await f(i,u==="unread")}catch(S){console.error("[Notifications] Error marking all as read:",S),g(!1)}},A=async S=>{try{await Va.delete(S),a(N=>N.filter(P=>P.notificationId!==S)),m(N=>N-1)}catch(N){console.error("[Notifications] Error deleting notification:",N)}},w=()=>{g(!0),f(i,u==="unread")},T=S=>{S<1||S>o||(l(S),f(S,u==="unread"))},k=S=>{const N="w-6 h-6";switch(S){case"mention":case"comment":return e.jsx(Ds,{className:`${N} text-blue-600`});case"worknote":return e.jsx(Pe,{className:`${N} text-purple-600`});case"document_added":return e.jsx(Pe,{className:`${N} text-teal-600`});case"assignment":return e.jsx(Ti,{className:`${N} text-indigo-600`});case"approval":return e.jsx(De,{className:`${N} text-green-600`});case"rejection":return e.jsx(jt,{className:`${N} text-red-600`});case"tat_alert":return e.jsx(Xe,{className:`${N} text-orange-600`});case"tat_breach":return e.jsx(Ge,{className:`${N} text-red-600`});case"tat_breach_initiator":return e.jsx(os,{className:`${N} text-amber-600`});default:return e.jsx(ks,{className:`${N} text-gray-600`})}},L=S=>{switch(S==null?void 0:S.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"}},D=s.filter(S=>!S.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(ks,{className:"w-8 h-8 text-blue-600"}),"Notifications"]}),e.jsxs("p",{className:"text-gray-600 mt-1",children:[c," total notification",c!==1?"s":"",D>0&&` • ${D} unread`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(F,{variant:"outline",size:"sm",onClick:w,disabled:p,className:"gap-2",children:[e.jsx(Bt,{className:`w-4 h-4 ${p?"animate-spin":""}`}),"Refresh"]}),D>0&&e.jsxs(F,{variant:"outline",size:"sm",onClick:v,disabled:p,className:"gap-2",children:[e.jsx(f0,{className:"w-4 h-4"}),"Mark All Read"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(F,{variant:u==="all"?"default":"outline",size:"sm",onClick:()=>{x("all"),l(1)},children:"All Notifications"}),e.jsxs(F,{variant:u==="unread"?"default":"outline",size:"sm",onClick:()=>{x("unread"),l(1)},children:["Unread",D>0&&e.jsx(ne,{className:"ml-2 bg-red-500 text-white",children:D})]})]}),e.jsxs(te,{children:[e.jsxs(ue,{children:[e.jsx(xe,{children:"Recent Activity"}),e.jsx(ke,{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(ks,{className:"w-16 h-16 text-gray-300 mx-auto mb-4"}),e.jsx("p",{className:"text-lg font-medium text-gray-900 mb-2",children:"No notifications"}),e.jsx("p",{className:"text-sm text-gray-500",children:u==="unread"?"You're all caught up! No unread notifications.":"You don't have any notifications yet."})]}):e.jsx("div",{className:"space-y-2",children:s.map(S=>{var N;return e.jsx("div",{className:`p-4 rounded-lg border transition-all cursor-pointer hover:shadow-md ${S.isRead?"bg-white border-gray-200 hover:bg-gray-50":"bg-blue-50 border-blue-200 hover:bg-blue-100"}`,onClick:()=>b(S),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"shrink-0 mt-0.5",children:k(S.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 ${S.isRead?"font-semibold":"font-bold"} text-gray-900`,children:S.title}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[S.priority&&S.priority!=="LOW"&&e.jsx(ne,{variant:"outline",className:`text-xs ${L(S.priority)}`,children:S.priority}),!S.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:S.message}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:[Wu(new Date(S.createdAt),{addSuffix:!0}),((N=S.metadata)==null?void 0:N.requestNumber)&&e.jsxs("span",{className:"ml-2",children:["• ",S.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:P=>{P.stopPropagation(),A(S.notificationId)},children:e.jsx(Fi,{className:"w-3.5 h-3.5"})})]})]})]})},S.notificationId)})})})]}),!r&&o>1&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-gray-600",children:["Showing ",(i-1)*y+1," to ",Math.min(i*y,c)," of ",c," notifications"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(F,{variant:"outline",size:"sm",onClick:()=>T(i-1),disabled:i===1,children:[e.jsx(Ju,{className:"w-4 h-4"}),"Previous"]}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,o)},(S,N)=>{let P;return o<=5||i<=3?P=N+1:i>=o-2?P=o-4+N:P=i-2+N,e.jsx(F,{variant:i===P?"default":"outline",size:"sm",className:"w-9 h-9 p-0",onClick:()=>T(P),children:P},P)})}),e.jsxs(F,{variant:"outline",size:"sm",onClick:()=>T(i+1),disabled:i===o,children:["Next",e.jsx(bo,{className:"w-4 h-4"})]})]})]})]})}function wk({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(Js,{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(Pe,{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 jc({dateRange:t,customStartDate:s,customEndDate:a,showCustomDatePicker:r,tempCustomStartDate:n,tempCustomEndDate:i,onDateRangeChange:l,onShowCustomDatePickerChange:o,onStartDateChange:d,onEndDateChange:c,onApply:m,onCancel:u,testIdPrefix:x="date-filter"}){const p=s&&a?`${Ye(s,"d MMM yyyy")} - ${Ye(a,"d MMM yyyy")}`:"Select dates";return e.jsxs("div",{className:"flex items-center gap-2","data-testid":`${x}-container`,children:[e.jsx(it,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ve,{value:t,onValueChange:l,"data-testid":`${x}-select`,children:[e.jsx(He,{className:"w-[160px]",children:e.jsx(ze,{placeholder:"Date Range"})}),e.jsxs(We,{children:[e.jsx(K,{value:"today",children:"Today"}),e.jsx(K,{value:"week",children:"This Week"}),e.jsx(K,{value:"month",children:"This Month"}),e.jsx(K,{value:"custom",children:"Custom Range"})]})]}),t==="custom"&&e.jsxs(Ys,{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(it,{className:"w-4 h-4"}),p]})}),e.jsx(Xs,{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(le,{htmlFor:`${x}-start-date`,className:"text-sm font-medium",children:"Start Date"}),e.jsx($s,{value:n||null,onChange:g=>{const y=g?new Date(g):void 0;d(y)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full",id:`${x}-start-date`})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{htmlFor:`${x}-end-date`,className:"text-sm font-medium",children:"End Date"}),e.jsx($s,{value:i||null,onChange:g=>{const y=g?new Date(g):void 0;c(y)},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:u,"data-testid":`${x}-cancel-button`,children:"Cancel"})]})]})})]})]})}function Ck(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 gg(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 fg(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 Ak(t){return t>=20?"bg-red-600":t>=10?"bg-orange-500":"bg-amber-500"}function Sk({lifecycleRequests:t,loading:s,loadingPage:a,error:r,pagination:n,dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:d,tempCustomStartDate:c,tempCustomEndDate:m,exporting:u,onDateRangeChange:x,onShowCustomDatePickerChange:p,onStartDateChange:g,onEndDateChange:y,onApplyCustomDate:f,onCancelCustomDate:b,onPageChange:v,onExport:A,onViewRequest:w}){return e.jsxs(te,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"request-lifecycle-report",children:[e.jsxs(ue,{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(Dt,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-lg text-gray-900",children:"Request Lifecycle Report"}),e.jsx(ke,{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:A,disabled:u,"data-testid":"export-lifecycle-button",children:[e.jsx(Nt,{className:"w-4 h-4"}),u?"Exporting...":"Download CSV"]})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(jc,{dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:d,tempCustomStartDate:c,tempCustomEndDate:m,onDateRangeChange:x,onShowCustomDatePickerChange:p,onStartDateChange:g,onEndDateChange:y,onApply:f,onCancel:b,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(Ze,{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(Ge,{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(T=>e.jsx("div",{className:"border rounded-xl overflow-hidden","data-testid":`lifecycle-request-${T.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(T.requestId||T.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:k=>{k.stopPropagation(),w(T.requestId||T.id)},className:"font-semibold text-sm text-blue-600 hover:text-blue-800 hover:underline cursor-pointer transition-colors","data-testid":`lifecycle-request-link-${T.id}`,children:T.id}),e.jsx(ne,{className:gg(T.priority),"data-testid":`lifecycle-priority-${T.id}`,children:T.priority}),e.jsx(ne,{className:fg(T.status),"data-testid":`lifecycle-status-${T.id}`,children:T.status})]}),e.jsx("p",{className:"text-sm text-gray-700",children:T.title}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["Initiated by ",e.jsx("span",{className:"font-medium",children:T.initiator})," on ",T.initDate]}),T.currentStage&&!T.currentStage.includes("Level")&&e.jsxs("p",{className:"text-xs text-gray-400 mt-0.5",children:["Stage: ",T.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:T.currentStage}),e.jsxs("p",{className:"text-xs text-gray-400 mt-0.5",children:["(Level ",T.currentLevel,"/",T.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:T.overallTAT}),T.breachCount>0&&e.jsxs("p",{className:"text-xs text-red-500 mt-0.5",children:[T.breachCount," breach",T.breachCount>1?"es":""]})]}),e.jsx(F,{variant:"ghost",size:"sm",onClick:()=>w(T.requestId||T.id),className:"gap-1.5","data-testid":`lifecycle-view-button-${T.id}`,children:e.jsx(bo,{className:"w-4 h-4"})})]})]})})},T.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(Ze,{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 Nc({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:Re("w-full caption-bottom text-sm",t),...s})})}function wc({className:t,...s}){return e.jsx("thead",{"data-slot":"table-header",className:Re("[&_tr]:border-b",t),...s})}function Cc({className:t,...s}){return e.jsx("tbody",{"data-slot":"table-body",className:Re("[&_tr:last-child]:border-0",t),...s})}function br({className:t,...s}){return e.jsx("tr",{"data-slot":"table-row",className:Re("hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",t),...s})}function ss({className:t,...s}){return e.jsx("th",{"data-slot":"table-head",className:Re("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 Qt({className:t,...s}){return e.jsx("td",{"data-slot":"table-cell",className:Re("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",t),...s})}function Tk({activityLog:t,loading:s,loadingPage:a,error:r,pagination:n,dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:d,tempCustomStartDate:c,tempCustomEndDate:m,filterCategory:u,filterSeverity:x,exporting:p,onDateRangeChange:g,onShowCustomDatePickerChange:y,onStartDateChange:f,onEndDateChange:b,onApplyCustomDate:v,onCancelCustomDate:A,onCategoryChange:w,onSeverityChange:T,onClearFilters:k,onPageChange:L,onExport:D,onViewRequest:S}){const N=u!=="all"||x!=="all"||i!=="month"||l||o;return e.jsxs(te,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"user-activity-log-report",children:[e.jsxs(ue,{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(xe,{className:"text-lg text-gray-900",children:"User Activity Log Report"}),e.jsx(ke,{className:"text-gray-600",children:"Consolidated user actions and activity history"})]})]}),e.jsxs(F,{variant:"outline",size:"sm",className:"gap-2",onClick:D,disabled:p,"data-testid":"export-activity-button",children:[e.jsx(Nt,{className:"w-4 h-4"}),p?"Exporting...":"Download CSV"]})]}),e.jsxs("div",{className:"mt-4 flex items-center gap-4 flex-wrap",children:[e.jsx(jc,{dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:d,tempCustomStartDate:c,tempCustomEndDate:m,onDateRangeChange:g,onShowCustomDatePickerChange:y,onStartDateChange:f,onEndDateChange:b,onApply:v,onCancel:A,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(Ve,{value:u,onValueChange:w,"data-testid":"activity-category-filter",children:[e.jsx(He,{className:"w-40",children:e.jsx(ze,{placeholder:"All Categories"})}),e.jsxs(We,{children:[e.jsx(K,{value:"all",children:"All Categories"}),e.jsx(K,{value:"WORKFLOW",children:"Workflow"}),e.jsx(K,{value:"COLLABORATION",children:"Collaboration"}),e.jsx(K,{value:"DOCUMENT",children:"Document"}),e.jsx(K,{value:"AUTHENTICATION",children:"Authentication"}),e.jsx(K,{value:"SYSTEM",children:"System"}),e.jsx(K,{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(Ve,{value:x,onValueChange:T,"data-testid":"activity-severity-filter",children:[e.jsx(He,{className:"w-40",children:e.jsx(ze,{placeholder:"All Severities"})}),e.jsxs(We,{children:[e.jsx(K,{value:"all",children:"All Severities"}),e.jsx(K,{value:"INFO",children:"Info"}),e.jsx(K,{value:"WARNING",children:"Warning"}),e.jsx(K,{value:"ERROR",children:"Error"}),e.jsx(K,{value:"CRITICAL",children:"Critical"})]})]})]}),N&&e.jsx(F,{variant:"ghost",size:"sm",onClick:k,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(Ze,{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(Ge,{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(Nc,{children:[e.jsx(wc,{children:e.jsxs(br,{className:"bg-gray-50",children:[e.jsx(ss,{className:"font-semibold",children:"Timestamp"}),e.jsx(ss,{className:"font-semibold",children:"User"}),e.jsx(ss,{className:"font-semibold",children:"Action"}),e.jsx(ss,{className:"font-semibold",children:"Details"}),e.jsx(ss,{className:"font-semibold",children:"IP Address"}),e.jsx(ss,{className:"font-semibold",children:"Request ID"})]})}),e.jsx(Cc,{children:t.map((P,R)=>e.jsxs(br,{className:"hover:bg-gray-50","data-testid":`activity-row-${R}`,children:[e.jsx(Qt,{className:"text-xs font-medium",children:P.timestamp}),e.jsx(Qt,{className:"text-sm",children:P.user}),e.jsx(Qt,{children:e.jsx(ne,{className:Ck(P.action),"data-testid":`activity-action-${R}`,children:P.action})}),e.jsx(Qt,{className:"text-sm text-gray-600",children:P.details}),e.jsx(Qt,{className:"text-xs font-mono text-gray-500",children:P.ip&&P.ip!=="N/A"?e.jsx("span",{title:P.userAgent||"",children:P.ip}):e.jsx("span",{className:"text-gray-400 italic",title:"IP address not yet captured",children:"N/A"})}),e.jsx(Qt,{children:P.requestId!=="-"&&P.requestId!=="System Login"?e.jsx("button",{onClick:()=>{const O=P.requestId;O&&S(O)},className:"hover:underline","data-testid":`activity-request-link-${R}`,children:e.jsx(ne,{variant:"outline",className:"text-xs cursor-pointer hover:bg-blue-50 hover:border-blue-300 transition-colors",children:P.requestId})}):e.jsx("span",{className:"text-xs text-gray-400",children:"-"})})]},R))})]}),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(Ze,{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:()=>L(n.page-1),disabled:n.page<=1||a,"data-testid":"activity-pagination-prev",children:"Previous"}),e.jsx(F,{variant:"outline",size:"sm",onClick:()=>L(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"activity-pagination-next",children:"Next"})]})]})]})})]})}function kk({agingWorkflows:t,loading:s,loadingPage:a,error:r,pagination:n,threshold:i,thresholdError:l,dateRange:o,customStartDate:d,customEndDate:c,showCustomDatePicker:m,tempCustomStartDate:u,tempCustomEndDate:x,searchQuery:p,exporting:g,onThresholdChange:y,onThresholdBlur:f,onDateRangeChange:b,onShowCustomDatePickerChange:v,onStartDateChange:A,onEndDateChange:w,onApplyCustomDate:T,onCancelCustomDate:k,onSearchChange:L,onPageChange:D,onExport:S,onViewRequest:N}){return e.jsxs(te,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"workflow-aging-report",children:[e.jsxs(ue,{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(wo,{className:"h-5 w-5 text-amber-600"})}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-lg text-gray-900",children:"Workflow Aging Report"}),e.jsx(ke,{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(_e,{type:"number",min:"1",value:i,onChange:P=>y(P.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(ne,{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:S,disabled:g,"data-testid":"export-aging-button",children:[e.jsx(Nt,{className:"w-4 h-4"}),g?"Exporting...":"Download CSV"]})]})]}),e.jsxs("div",{className:"mt-4 flex items-center gap-4 flex-wrap",children:[e.jsx(jc,{dateRange:o,customStartDate:d,customEndDate:c,showCustomDatePicker:m,tempCustomStartDate:u,tempCustomEndDate:x,onDateRangeChange:b,onShowCustomDatePickerChange:v,onStartDateChange:A,onEndDateChange:w,onApply:T,onCancel:k,testIdPrefix:"aging"}),e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(As,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(_e,{placeholder:"Search by Request ID, Title, or Initiator...",value:p,onChange:P=>L(P.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(Ze,{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(Ge,{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(Nc,{children:[e.jsx(wc,{children:e.jsxs(br,{className:"bg-gray-50",children:[e.jsx(ss,{className:"font-semibold",children:"Request ID"}),e.jsx(ss,{className:"font-semibold",children:"Title"}),e.jsx(ss,{className:"font-semibold",children:"Initiator"}),e.jsx(ss,{className:"font-semibold",children:"Start Date"}),e.jsx(ss,{className:"font-semibold",children:"Days Open"}),e.jsx(ss,{className:"font-semibold",children:"Current Stage"}),e.jsx(ss,{className:"font-semibold",children:"Assigned To"}),e.jsx(ss,{className:"font-semibold",children:"Priority"}),e.jsx(ss,{className:"font-semibold",children:"Status"})]})}),e.jsx(Cc,{children:t.map(P=>e.jsxs(br,{className:"hover:bg-gray-50","data-testid":`aging-workflow-${P.id}`,children:[e.jsx(Qt,{className:"font-medium text-sm",children:e.jsx("button",{onClick:()=>N(P.requestId||P.id),className:"text-blue-600 hover:text-blue-800 hover:underline cursor-pointer transition-colors","data-testid":`aging-request-link-${P.id}`,children:P.id})}),e.jsx(Qt,{className:"text-sm",children:P.title}),e.jsx(Qt,{className:"text-sm",children:P.initiator}),e.jsx(Qt,{className:"text-sm text-gray-600",children:P.startDate}),e.jsx(Qt,{children:e.jsxs(ne,{className:`${Ak(P.daysOpen)} text-white border-transparent`,"data-testid":`aging-days-${P.id}`,children:[P.daysOpen," days",e.jsx("span",{className:"ml-1 text-xs opacity-75",children:"(business)"})]})}),e.jsx(Qt,{className:"text-sm",children:P.currentStage}),e.jsx(Qt,{className:"text-sm",children:P.assignedTo&&P.assignedTo!=="N/A"?P.assignedTo:e.jsx("span",{className:"text-gray-400 italic",title:"Assigned approver not available",children:"N/A"})}),e.jsx(Qt,{children:e.jsx(ne,{className:gg(P.priority),"data-testid":`aging-priority-${P.id}`,children:P.priority})}),e.jsx(Qt,{children:e.jsx(ne,{className:fg(P.status),"data-testid":`aging-status-${P.id}`,children:P.status})})]},P.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(Ze,{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:()=>D(n.page-1),disabled:n.page<=1||a,"data-testid":"aging-pagination-prev",children:"Previous"}),e.jsx(F,{variant:"outline",size:"sm",onClick:()=>D(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"aging-pagination-next",children:"Next"})]})]})]})})]})}function El(t="month"){const[s,a]=h.useState(t),[r,n]=h.useState(void 0),[i,l]=h.useState(void 0),[o,d]=h.useState(!1),[c,m]=h.useState(void 0),[u,x]=h.useState(void 0),p=h.useCallback(w=>{const T=w;a(T),T!=="custom"?(n(void 0),l(void 0),m(void 0),x(void 0),d(!1)):(m(r),x(i),d(!0))},[r,i]),g=h.useCallback(()=>{if(c&&u){if(c>u){const w=c;n(u),l(w),m(u),x(w)}else n(c),l(u);d(!1)}},[c,u]),y=h.useCallback(()=>{d(!1),m(r),x(i),(!r||!i)&&(n(void 0),l(void 0),a("month"))},[r,i]),f=h.useCallback(w=>{w?(m(w),u&&w>u&&x(w)):m(void 0)},[u]),b=h.useCallback(w=>{w?(x(w),c&&w<c&&m(w)):x(void 0)},[c]),v=h.useCallback(()=>r&&i?`${Ye(r,"MMM d, yyyy")} - ${Ye(i,"MMM d, yyyy")}`:"Select dates",[r,i]),A=h.useCallback(()=>{a("month"),n(void 0),l(void 0),d(!1),m(void 0),x(void 0)},[]);return{dateRange:s,customStartDate:r,customEndDate:i,showCustomDatePicker:o,tempCustomStartDate:c,tempCustomEndDate:u,setShowCustomDatePicker:d,handleDateRangeChange:p,handleApplyCustomDate:g,handleCancelCustomDate:y,handleStartDateChange:f,handleEndDateChange:b,getDisplayDateRange:v,reset:A}}function Rk(t){if(!t&&t!==0)return"N/A";const s=8;if(t<s)return Lt(t);const a=Math.floor(t/s),r=t%s;return r>0?`${a}d ${Lt(r)}`:`${a}d`}function yg(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 ur(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 bg(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 Dk=10;function Pk({dateRange:t,customStartDate:s,customEndDate:a}){const[r,n]=h.useState([]),[i,l]=h.useState(!0),[o,d]=h.useState(!1),[c,m]=h.useState(null),[u,x]=h.useState({page:1,totalPages:1,totalRecords:0}),p=h.useRef(!0),g=h.useCallback(async(y=1)=>{const f=y===1&&p.current;try{f?l(!0):d(!0),m(null);const b=await Ct.getLifecycleReport(y,Dk,t,s,a),v=b.lifecycleData.map(A=>{const w=Rk(A.overallTATHours);return{id:A.requestNumber,requestId:A.requestId,title:A.title,priority:A.priority||"medium",status:A.status,initiator:A.initiatorName||"Unknown",initDate:yg(A.submissionDate),currentStage:A.currentStageName||`Level ${A.currentLevel}`,overallTAT:w,currentLevel:A.currentLevel,totalLevels:A.totalLevels,breachCount:A.breachCount||0}});n(v),x({page:b.pagination.currentPage,totalPages:b.pagination.totalPages,totalRecords:b.pagination.totalRecords})}catch(b){console.error("Failed to fetch lifecycle data:",b),m((b==null?void 0:b.message)||"Failed to load lifecycle data")}finally{f?l(!1):d(!1)}f&&(p.current=!1)},[t,s,a]);return h.useEffect(()=>{t==="custom"&&(!s||!a)||g(1)},[t,s,a]),{lifecycleRequests:r,loading:i,loadingPage:o,error:c,pagination:u,fetchData:g}}const Ik=20;function Ek({dateRange:t,customStartDate:s,customEndDate:a,filterCategory:r,filterSeverity:n}){const[i,l]=h.useState([]),[o,d]=h.useState(!0),[c,m]=h.useState(!1),[u,x]=h.useState(null),[p,g]=h.useState({page:1,totalPages:1,totalRecords:0}),y=h.useRef(!0),f=h.useCallback(async(b=1)=>{const v=b===1&&y.current;try{v?d(!0):m(!0),x(null);const A=await Ct.getActivityLogReport(b,Ik,t,void 0,void 0,r&&r!=="all"?r:void 0,n&&n!=="all"?n:void 0,s,a),w=A.activities.map(T=>{const k=bg(T.type||"",T.details),L=(T.type||"").toLowerCase()==="login"||T.requestId==="00000000-0000-0000-0000-000000000001"||T.requestId==="SYSTEM_LOGIN",D=L?T.details||"User login":T.requestTitle||T.requestNumber||T.details||"N/A";return{timestamp:T.timestamp?yg(T.timestamp):"N/A",user:T.userName||"Unknown",action:k,details:D,ip:T.ipAddress||"N/A",userAgent:T.userAgent||null,requestId:L?"System Login":T.requestNumber||T.requestId||"-",userId:T.userId}});l(w),g({page:A.pagination.currentPage,totalPages:A.pagination.totalPages,totalRecords:A.pagination.totalRecords})}catch(A){console.error("Failed to fetch activity data:",A),x((A==null?void 0:A.message)||"Failed to load activity data")}finally{v?d(!1):m(!1)}v&&(y.current=!1)},[r,n,t,s,a]);return h.useEffect(()=>{t==="custom"&&(!s||!a)||f(1)},[r,n,t,s,a]),{activityLog:i,loading:o,loadingPage:c,error:u,pagination:p,fetchData:f}}const Fk=20;function Mk({threshold:t,dateRange:s,customStartDate:a,customEndDate:r,searchQuery:n=""}){const[i,l]=h.useState([]),[o,d]=h.useState(!0),[c,m]=h.useState(!1),[u,x]=h.useState(null),[p,g]=h.useState({page:1,totalPages:1,totalRecords:0}),y=h.useRef(!0),f=h.useCallback(async(v=1)=>{const A=v===1&&y.current;try{A?d(!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 T=await Ct.getWorkflowAgingReport(w,v,Fk,s,a,r),k=T.agingData.map(L=>({id:L.requestNumber||L.requestId,requestId:L.requestId,title:L.title,initiator:L.initiatorName||"Unknown",startDate:L.submissionDate?new Date(L.submissionDate).toLocaleDateString():"N/A",daysOpen:L.daysOpen,currentStage:L.currentStageName||`Level ${L.currentLevel}`,assignedTo:L.currentApproverName||"N/A",priority:L.priority||"medium",status:L.status||"pending"}));l(k),g({page:T.pagination.currentPage,totalPages:T.pagination.totalPages,totalRecords:T.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{A?d(!1):m(!1)}A&&(y.current=!1)},[t,s,a,r]),b=h.useMemo(()=>i.filter(v=>{var w,T,k;if(!n)return!0;const A=n.toLowerCase();return((w=v.id)==null?void 0:w.toLowerCase().includes(A))||((T=v.title)==null?void 0:T.toLowerCase().includes(A))||((k=v.initiator)==null?void 0:k.toLowerCase().includes(A))}),[i,n]);return h.useEffect(()=>{s==="custom"&&(!a||!r)||f(1)},[t,s,a,r]),{agingWorkflows:b,loading:o,loadingPage:c,error:u,pagination:p,fetchData:f}}function _k(t="7"){const[s,a]=h.useState(t),[r,n]=h.useState(null),i=h.useCallback(o=>{if(o===""){a(""),n(null);return}const d=parseInt(o,10);isNaN(d)||d<1?(n("Minimum threshold is 1 day"),a(o)):(n(null),a(o))},[]),l=h.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 Lk(t,s,a){const r=await Ct.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 ws(i.requestId||i.requestNumber),o=i.submissionDate?ur(i.submissionDate):"N/A",d=i.closureDate?ur(i.closureDate):"N/A",c=i.overallTATHours||0,m=c>0?(c/8).toFixed(2):"0",u=i.totalLevels||1,x=Math.min(Math.max(1,i.currentLevel||1),u),p=(l==null?void 0:l.approvals)||[];if(p.length===0){const g=[i.requestNumber||"",`"${(i.title||"").replace(/"/g,'""')}"`,i.priority||"medium",i.status||"",`"${(i.initiatorName||"Unknown").replace(/"/g,'""')}"`,o,d,u.toString(),x.toString(),c.toString(),m,(i.breachCount||0).toString(),"N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A"];n.push(g.join(","))}else p.forEach(g=>{const y=g.levelStartTime?ur(g.levelStartTime):"N/A",f=g.levelEndTime||g.completedAt?ur(g.levelEndTime||g.completedAt):"N/A",b=g.tatHours||0,v=g.tatDays||(b>0?(b/8).toFixed(2):"0");let A="N/A",w="N/A",T="N/A",k="N/A";if(g.levelStartTime){const D=new Date(g.levelStartTime);if(w=(((g.levelEndTime||g.completedAt?new Date(g.levelEndTime||g.completedAt):new Date).getTime()-D.getTime())/(1e3*60*60)).toFixed(2),b>0){const P=parseFloat(w);T=Math.max(0,b-P).toFixed(2),k=(P/b*100).toFixed(2),g.status==="APPROVED"||g.status==="REJECTED"?A=P<=b?"Compliant":"Breached":g.status==="IN_PROGRESS"||g.status==="PENDING"?A=P<=b?"On Track":"At Risk":A="N/A"}}const L=[i.requestNumber||"",`"${(i.title||"").replace(/"/g,'""')}"`,i.priority||"medium",i.status||"",`"${(i.initiatorName||"Unknown").replace(/"/g,'""')}"`,o,d,(i.totalLevels||0).toString(),(i.currentLevel||0).toString(),c.toString(),m,(i.breachCount||0).toString(),(g.levelNumber||"").toString(),`"${(g.levelName||`Level ${g.levelNumber}`).replace(/"/g,'""')}"`,`"${(g.approverName||"N/A").replace(/"/g,'""')}"`,`"${(g.approverEmail||"N/A").replace(/"/g,'""')}"`,g.status||"PENDING",y,f,b.toString(),v.toString(),A,w,T,k];n.push(L.join(","))})}catch(l){console.error(`Failed to fetch details for request ${i.requestNumber}:`,l);const o=i.submissionDate?ur(i.submissionDate):"N/A",d=i.overallTATHours||0,c=d>0?(d/8).toFixed(2):"0",m=i.totalLevels||1,u=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(),u.toString(),d.toString(),c,(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(","))}Ac(n,`lifecycle-report-end-to-end-${new Date().toISOString().split("T")[0]}.csv`)}async function Ok(t,s,a,r,n){const i=await Ct.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 d=bg(o.type||"",o.details),m=[o.timestamp?ur(o.timestamp):"N/A",`"${(o.userName||"Unknown").replace(/"/g,'""')}"`,`"${d.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(","))}),Ac(l,`activity-log-report-${new Date().toISOString().split("T")[0]}.csv`)}async function $k(t,s,a,r){const n=await Ct.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?ur(l.submissionDate):"N/A",d=[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(d.join(","))}),Ac(i,`workflow-aging-report-${new Date().toISOString().split("T")[0]}.csv`)}function Ac(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 Uk(){const[t,s]=h.useState(!1),[a,r]=h.useState(!1),[n,i]=h.useState(!1),l=h.useCallback(async(c,m,u)=>{try{s(!0),await Lk(c,m,u)}catch(x){console.error("Failed to export lifecycle data:",x),alert("Failed to export lifecycle data. Please try again.")}finally{s(!1)}},[]),o=h.useCallback(async(c,m,u,x,p)=>{try{r(!0),await Ok(c,m,u,x,p)}catch(g){console.error("Failed to export activity data:",g),alert("Failed to export activity data. Please try again.")}finally{r(!1)}},[]),d=h.useCallback(async(c,m,u,x)=>{try{i(!0),await $k(c,m,u,x)}catch(p){console.error("Failed to export aging data:",p),alert("Failed to export aging data. Please try again.")}finally{i(!1)}},[]);return{exportingLifecycle:t,exportingActivity:a,exportingAging:n,handleExportLifecycle:l,handleExportActivity:o,handleExportAging:d}}function Bk({onBack:t}){const s=Fa(),[a,r]=h.useState(""),[n,i]=h.useState("all"),[l,o]=h.useState("all"),d=El("month"),c=El("month"),m=El("month"),u=_k("7"),x=Pk({dateRange:d.dateRange,customStartDate:d.customStartDate,customEndDate:d.customEndDate}),p=Ek({dateRange:c.dateRange,customStartDate:c.customStartDate,customEndDate:c.customEndDate,filterCategory:n,filterSeverity:l}),g=Mk({threshold:u.threshold,dateRange:m.dateRange,customStartDate:m.customStartDate,customEndDate:m.customEndDate,searchQuery:a}),y=Uk(),f=h.useCallback(()=>{t?t():s("/dashboard")},[t,s]),b=h.useCallback(k=>{bi({requestId:k,navigate:s})},[s]),v=h.useCallback(()=>{y.handleExportLifecycle(d.dateRange,d.customStartDate,d.customEndDate)},[y,d]),A=h.useCallback(()=>{y.handleExportActivity(c.dateRange,c.customStartDate,c.customEndDate,n,l)},[y,c,n,l]),w=h.useCallback(()=>{const k=parseInt(u.threshold,10);!isNaN(k)&&k>=1&&y.handleExportAging(k,m.dateRange,m.customStartDate,m.customEndDate)},[y,u.threshold,m]),T=h.useCallback(()=>{i("all"),o("all"),c.reset()},[c]);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(wk,{onBack:f}),e.jsx(Sk,{lifecycleRequests:x.lifecycleRequests,loading:x.loading,loadingPage:x.loadingPage,error:x.error,pagination:x.pagination,dateRange:d.dateRange,customStartDate:d.customStartDate,customEndDate:d.customEndDate,showCustomDatePicker:d.showCustomDatePicker,tempCustomStartDate:d.tempCustomStartDate,tempCustomEndDate:d.tempCustomEndDate,exporting:y.exportingLifecycle,onDateRangeChange:d.handleDateRangeChange,onShowCustomDatePickerChange:d.setShowCustomDatePicker,onStartDateChange:d.handleStartDateChange,onEndDateChange:d.handleEndDateChange,onApplyCustomDate:d.handleApplyCustomDate,onCancelCustomDate:d.handleCancelCustomDate,onPageChange:x.fetchData,onExport:v,onViewRequest:b}),e.jsx(Tk,{activityLog:p.activityLog,loading:p.loading,loadingPage:p.loadingPage,error:p.error,pagination:p.pagination,dateRange:c.dateRange,customStartDate:c.customStartDate,customEndDate:c.customEndDate,showCustomDatePicker:c.showCustomDatePicker,tempCustomStartDate:c.tempCustomStartDate,tempCustomEndDate:c.tempCustomEndDate,filterCategory:n,filterSeverity:l,exporting:y.exportingActivity,onDateRangeChange:c.handleDateRangeChange,onShowCustomDatePickerChange:c.setShowCustomDatePicker,onStartDateChange:c.handleStartDateChange,onEndDateChange:c.handleEndDateChange,onApplyCustomDate:c.handleApplyCustomDate,onCancelCustomDate:c.handleCancelCustomDate,onCategoryChange:i,onSeverityChange:o,onClearFilters:T,onPageChange:p.fetchData,onExport:A,onViewRequest:b}),e.jsx(kk,{agingWorkflows:g.agingWorkflows,loading:g.loading,loadingPage:g.loadingPage,error:g.error,pagination:g.pagination,threshold:u.threshold,thresholdError:u.thresholdError,dateRange:m.dateRange,customStartDate:m.customStartDate,customEndDate:m.customEndDate,showCustomDatePicker:m.showCustomDatePicker,tempCustomStartDate:m.tempCustomStartDate,tempCustomEndDate:m.tempCustomEndDate,searchQuery:a,exporting:y.exportingAging,onThresholdChange:u.handleThresholdChange,onThresholdBlur:u.handleThresholdBlur,onDateRangeChange:m.handleDateRangeChange,onShowCustomDatePickerChange:m.setShowCustomDatePicker,onStartDateChange:m.handleStartDateChange,onEndDateChange:m.handleEndDateChange,onApplyCustomDate:m.handleApplyCustomDate,onCancelCustomDate:m.handleCancelCustomDate,onSearchChange:r,onPageChange:g.fetchData,onExport:w,onViewRequest:b})]})})}function Vk({defaultPeriod:t,refreshInterval:s,onDefaultPeriodChange:a,onRefreshIntervalChange:r}){const n=["Today","This Week","This Month","Last Month","This Quarter","This Year","Custom Range"];return e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{htmlFor:"default-period",children:"Default Reporting Period"}),e.jsxs(Ve,{value:t,onValueChange:a,children:[e.jsx(He,{id:"default-period",children:e.jsx(ze,{})}),e.jsx(We,{children:n.map(i=>e.jsx(K,{value:i,children:i},i))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{htmlFor:"refresh-interval",children:"Auto-Refresh Interval (minutes)"}),e.jsx(_e,{id:"refresh-interval",type:"number",min:"1",max:"60",value:s,onChange:i=>r(parseInt(i.target.value)||5)})]})]})}function zk({autoRefresh:t,realTimeUpdates:s,dataExport:a,onAutoRefreshChange:r,onRealTimeUpdatesChange:n,onDataExportChange:i}){return e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"font-medium",children:"Data Features"}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Enable Auto-Refresh"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Automatically refresh dashboard data at set intervals"})]}),e.jsx(Ps,{checked:t,onCheckedChange:r})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Enable Real-time Updates"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Show live updates when data changes occur"})]}),e.jsx(Ps,{checked:s,onCheckedChange:n})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Enable Data Export"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Allow users to export analytics data and reports"})]}),e.jsx(Ps,{checked:a,onCheckedChange:i})]})]})}const Hk=["CSV","Excel","PDF","JSON"];function Wk({exportFormats:t,onExportFormatsChange:s}){const a=(r,n)=>{s(n?[...t,r]:t.filter(i=>i!==r))};return e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{children:"Allowed Export Formats"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:Hk.map(r=>e.jsxs("div",{className:"flex items-center space-x-2 p-2 bg-muted/50 rounded",children:[e.jsx(vc,{id:`export-${r}`,checked:t.includes(r),onCheckedChange:n=>a(r,n)}),e.jsx(le,{htmlFor:`export-${r}`,className:"text-sm cursor-pointer",children:r})]},r))})]})}function Gk({dataRetention:t,onDataRetentionChange:s}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{htmlFor:"data-retention",children:"Historical Data Retention (months)"}),e.jsx(_e,{id:"data-retention",type:"number",min:"1",max:"120",value:t,onChange:a=>s(parseInt(a.target.value)||24)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Analytics data older than this will be archived or deleted"})]})}function Kk(){const[t,s]=h.useState({defaultPeriod:"This Month",refreshInterval:5,autoRefresh:!0,realTimeUpdates:!0,dataExport:!0,exportFormats:["CSV","Excel","PDF"],dataRetention:24}),a=()=>{Q.success("Analytics configuration saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(te,{children:[e.jsxs(ue,{children:[e.jsx(xe,{children:"Analytics & Reporting Configuration"}),e.jsx(ke,{children:"Configure default reporting periods, auto-refresh, export settings, and data retention"})]}),e.jsxs(ae,{className:"space-y-6",children:[e.jsx(Vk,{defaultPeriod:t.defaultPeriod,refreshInterval:t.refreshInterval,onDefaultPeriodChange:n=>r({defaultPeriod:n}),onRefreshIntervalChange:n=>r({refreshInterval:n})}),e.jsx(Gt,{}),e.jsx(zk,{autoRefresh:t.autoRefresh,realTimeUpdates:t.realTimeUpdates,dataExport:t.dataExport,onAutoRefreshChange:n=>r({autoRefresh:n}),onRealTimeUpdatesChange:n=>r({realTimeUpdates:n}),onDataExportChange:n=>r({dataExport:n})}),e.jsx(Gt,{}),e.jsx(Wk,{exportFormats:t.exportFormats,onExportFormatsChange:n=>r({exportFormats:n})}),e.jsx(Gk,{dataRetention:t.dataRetention,onDataRetentionChange:n=>r({dataRetention:n})}),e.jsxs(F,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(Za,{className:"w-4 h-4 mr-2"}),"Save Analytics Configuration"]})]})]})}const Yk=t=>{switch(t.toUpperCase()){case"ADMIN":return"bg-yellow-100 text-yellow-800 border-yellow-200";case"MANAGEMENT":return"bg-blue-100 text-blue-800 border-blue-200";case"USER":return"bg-gray-100 text-gray-800 border-gray-200";default:return"bg-gray-100 text-gray-800 border-gray-200"}},Zk=t=>t.split(" ").map(s=>s[0]).join("").toUpperCase().substring(0,2);function Xk({users:t,onEdit:s,onToggleStatus:a,onDelete:r}){return e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(Nc,{children:[e.jsx(wc,{children:e.jsxs(br,{children:[e.jsx(ss,{children:"User"}),e.jsx(ss,{children:"Role"}),e.jsx(ss,{children:"Department"}),e.jsx(ss,{children:"Status"}),e.jsx(ss,{className:"text-right",children:"Actions"})]})}),e.jsx(Cc,{children:t.length===0?e.jsx(br,{children:e.jsx(Qt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No users found"})}):t.map(n=>e.jsxs(br,{className:"hover:bg-muted/50",children:[e.jsx(Qt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(rs,{className:"size-10",children:e.jsx(ns,{className:"bg-re-green text-white",children:Zk(n.name)})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:n.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:n.email})]})]})}),e.jsx(Qt,{children:e.jsx(ne,{className:Yk(n.role),children:n.role})}),e.jsx(Qt,{children:n.department}),e.jsx(Qt,{children:e.jsxs(ne,{className:"bg-green-100 text-green-800 border-green-200",children:[e.jsx(Ts,{className:"w-3 h-3 mr-1"}),n.status]})}),e.jsx(Qt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(F,{variant:"ghost",size:"sm",onClick:()=>s(n.id),className:"h-8",children:e.jsx(Ii,{className:"w-4 h-4"})}),e.jsx(F,{variant:"ghost",size:"sm",onClick:()=>a(n.id),disabled:n.role.toUpperCase()==="ADMIN",className:"h-8",children:e.jsx(y0,{className:"w-4 h-4"})}),e.jsx(F,{variant:"ghost",size:"sm",onClick:()=>r(n.id),disabled:n.role.toUpperCase()==="ADMIN",className:"h-8 text-destructive hover:text-destructive",children:e.jsx(Fi,{className:"w-4 h-4"})})]})})]},n.id))})]})})}function Qk({stats:t}){return e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"p-4 bg-muted/50 rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Total Users"}),e.jsx("p",{className:"text-2xl font-semibold",children:t.total})]}),e.jsxs("div",{className:"p-4 bg-green-50 rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Active"}),e.jsx("p",{className:"text-2xl font-semibold text-green-600",children:t.active})]}),e.jsxs("div",{className:"p-4 bg-red-50 rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Inactive"}),e.jsx("p",{className:"text-2xl font-semibold text-red-600",children:t.inactive})]}),e.jsxs("div",{className:"p-4 bg-purple-50 rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Admins"}),e.jsx("p",{className:"text-2xl font-semibold text-purple-600",children:t.admins})]})]})}function Jk(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function qk(){const[t,s]=h.useState(""),[a,r]=h.useState([]),[n,i]=h.useState(!1),[l,o]=h.useState(null),[d,c]=h.useState("USER"),[m,u]=h.useState(!1),[x,p]=h.useState(!1),[g,y]=h.useState(null),[f,b]=h.useState([]),[v,A]=h.useState(!1),[w,T]=h.useState({admins:0,management:0,users:0,total:0,active:0,inactive:0}),[k,L]=h.useState("ELEVATED"),[D,S]=h.useState(1),[N,P]=h.useState(1),[R,O]=h.useState(0),E=10,M=h.useRef(null),B=h.useCallback(Jk(async X=>{var Y,G,ie;if(!X||!X.startsWith("@")||X.length<2){r([]),i(!1);return}i(!0);try{const me=X.slice(1),Se=((Y=(await Ws.searchUsers(me,20)).data)==null?void 0:Y.data)||[];r(Se)}catch(me){console.error("Search failed:",me),y({type:"error",text:((ie=(G=me.response)==null?void 0:G.data)==null?void 0:ie.message)||"Failed to search users"})}finally{i(!1)}},300),[]),C=X=>{const Y=X.target.value;s(Y),B(Y)},j=async X=>{var Y,G;try{const ie=f.find(re=>re.email.toLowerCase()===X.toLowerCase());if(ie)return ie.role;const Se=(((G=(Y=(await Ws.getUsersByRole("ALL",1,1e3)).data)==null?void 0:Y.data)==null?void 0:G.users)||[]).find(re=>{var pe;return((pe=re.email)==null?void 0:pe.toLowerCase())===X.toLowerCase()});return Se&&Se.role?Se.role:null}catch(ie){return console.error("Failed to fetch user role:",ie),null}},U=async X=>{o(X),s(X.email),r([]),p(!0);try{const Y=await j(X.email);c(Y||"USER")}catch(Y){console.error("Failed to fetch user role:",Y),c("USER")}finally{p(!1)}},$=async()=>{var X,Y;if(!l||!d){y({type:"error",text:"Please select a user and role"});return}u(!0),y(null);try{await Ws.assignRole(l.email,d),y({type:"success",text:`Successfully assigned ${d} role to ${l.displayName||l.email}`}),o(null),s(""),c("USER"),await _(),await se(),Q.success("Role assigned successfully")}catch(G){console.error("Role assignment failed:",G);const ie=((Y=(X=G.response)==null?void 0:X.data)==null?void 0:Y.error)||"Failed to assign role";y({type:"error",text:ie}),Q.error(ie)}finally{u(!1)}},_=async(X=D)=>{var Y,G,ie,me,Te,Se;A(!0);try{const re=await Ws.getUsersByRole(k,X,E),pe=((G=(Y=re.data)==null?void 0:Y.data)==null?void 0:G.users)||[],ve=(me=(ie=re.data)==null?void 0:ie.data)==null?void 0:me.pagination,be=(Se=(Te=re.data)==null?void 0:Te.data)==null?void 0:Se.summary;b(pe.map(Le=>({userId:Le.userId,email:Le.email,displayName:Le.displayName||Le.email,role:Le.role||"USER",department:Le.department,designation:Le.designation,isActive:Le.isActive!==!1}))),ve&&(S(ve.currentPage),P(ve.totalPages),O(ve.totalUsers)),be&&T(Le=>({...Le,admins:be.ADMIN||0,management:be.MANAGEMENT||0,users:be.USER||0,total:(be.ADMIN||0)+(be.MANAGEMENT||0)+(be.USER||0)}))}catch(re){console.error("Failed to fetch users:",re),Q.error("Failed to load users")}finally{A(!1)}},se=async()=>{var X,Y,G,ie,me,Te;try{const Se=await Ws.getRoleStatistics(),re=((Y=(X=Se.data)==null?void 0:X.data)==null?void 0:Y.statistics)||((G=Se.data)==null?void 0:G.statistics)||[],pe={admins:parseInt(((ie=re.find(ve=>ve.role==="ADMIN"))==null?void 0:ie.count)||"0"),management:parseInt(((me=re.find(ve=>ve.role==="MANAGEMENT"))==null?void 0:me.count)||"0"),users:parseInt(((Te=re.find(ve=>ve.role==="USER"))==null?void 0:Te.count)||"0")};T(ve=>({...ve,...pe,total:pe.admins+pe.management+pe.users,active:ve.active||pe.admins+pe.management+pe.users,inactive:ve.inactive||0}))}catch(Se){console.error("Failed to fetch statistics:",Se)}};h.useEffect(()=>{_(1),se()},[k]);const W=X=>{L(X),S(1)},ce=X=>{_(X)},Z=async(X,Y)=>{var G,ie;try{await Ws.updateUserRole(X,Y),Q.success("User role updated successfully"),await _(),await se()}catch(me){console.error("Failed to update user role:",me),Q.error(((ie=(G=me.response)==null?void 0:G.data)==null?void 0:ie.error)||"Failed to update user role")}},I=async X=>{f.find(G=>G.userId===X)&&Q.info("User status toggle functionality coming soon")},V=async X=>{const Y=f.find(G=>G.userId===X);if(Y){if(Y.role==="ADMIN"){Q.error("Cannot delete admin user");return}Q.info("User deletion functionality coming soon")}};h.useEffect(()=>{const X=Y=>{M.current&&!M.current.contains(Y.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",X),()=>{document.removeEventListener("mousedown",X)}},[a]);const z={total:w.total,active:w.active,inactive:w.inactive,admins:w.admins};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(Qk,{stats:z}),e.jsxs(te,{children:[e.jsx(ue,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(xe,{children:"Assign User Role"}),e.jsx(ke,{children:"Search for a user in Okta and assign them a role"})]}),e.jsx(F,{onClick:$,disabled:!l||m,className:"bg-re-green hover:bg-re-green/90",children:m?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Assigning..."]}):e.jsxs(e.Fragment,{children:[e.jsx(vs,{className:"w-4 h-4 mr-2"}),"Assign Role"]})})]})}),e.jsxs(ae,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",ref:M,children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:"relative flex-1",children:[e.jsx(As,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(_e,{type:"text",placeholder:"Type @ to search users...",value:t,onChange:C,className:"pl-10 border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),n&&e.jsx(Ze,{className:"absolute right-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-re-green animate-spin"})]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Start with @ to search users (e.g., @john)"}),a.length>0&&e.jsxs("div",{className:"border rounded-lg shadow-lg bg-white max-h-60 overflow-y-auto",children:[e.jsx("div",{className:"sticky top-0 bg-muted px-4 py-2 border-b",children:e.jsxs("p",{className:"text-xs font-semibold text-muted-foreground",children:[a.length," user",a.length>1?"s":""," found"]})}),e.jsx("div",{className:"p-3",children:a.map(X=>e.jsxs("button",{onClick:()=>U(X),className:"w-full text-left p-3 hover:bg-muted rounded-lg transition-colors mb-1 last:mb-0",children:[e.jsx("p",{className:"font-medium text-gray-900",children:X.displayName||X.email}),e.jsx("p",{className:"text-sm text-muted-foreground",children:X.email}),X.department&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[X.department,X.designation?` • ${X.designation}`:""]})]},X.userId))})]})]}),l&&e.jsx("div",{className:"border-2 border-re-green/20 bg-re-green/5 rounded-lg p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-re-green flex items-center justify-center text-white font-bold shadow-md",children:(l.displayName||l.email).charAt(0).toUpperCase()}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-gray-900",children:l.displayName||l.email}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l.email}),l.department&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[l.department,l.designation?` • ${l.designation}`:""]}),x&&e.jsxs("p",{className:"text-xs text-re-green mt-1 flex items-center gap-1",children:[e.jsx(Ze,{className:"w-3 h-3 animate-spin"}),"Checking current role..."]})]})]}),e.jsx(F,{variant:"ghost",size:"sm",onClick:()=>{o(null),s(""),c("USER"),p(!1)},children:"Clear"})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Select Role"}),e.jsxs(Ve,{value:d,onValueChange:X=>c(X),disabled:x,children:[e.jsx(He,{className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(ze,{placeholder:x?"Loading current role...":"Select role"})}),e.jsxs(We,{className:"rounded-lg",children:[e.jsx(K,{value:"USER",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_t,{className:"w-4 h-4 text-gray-600"}),e.jsx("span",{children:"User - Regular access"})]})}),e.jsx(K,{value:"MANAGEMENT",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($t,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Management - Read all data"})]})}),e.jsx(K,{value:"ADMIN",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sr,{className:"w-4 h-4 text-yellow-600"}),e.jsx("span",{children:"Administrator - Full access"})]})})]})]})]}),g&&e.jsx("div",{className:`border-2 rounded-lg p-4 ${g.type==="success"?"border-green-200 bg-green-50":"border-red-200 bg-red-50"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[g.type==="success"?e.jsx(De,{className:"w-5 h-5 text-green-600 shrink-0 mt-0.5"}):e.jsx(Ge,{className:"w-5 h-5 text-red-600 shrink-0 mt-0.5"}),e.jsx("p",{className:`text-sm ${g.type==="success"?"text-green-800":"text-red-800"}`,children:g.text})]})})]})]}),e.jsxs(te,{children:[e.jsx(ue,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs(xe,{className:"flex items-center gap-2",children:[e.jsx($t,{className:"w-5 h-5 text-re-green"}),"User Management"]}),e.jsxs(ke,{children:["View and manage user accounts and roles (",R," ",k!=="ALL"&&k!=="ELEVATED"?k.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(Ve,{value:k,onValueChange:W,children:[e.jsx(He,{className:"w-[200px] border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(ze,{placeholder:"Filter by role"})}),e.jsxs(We,{children:[e.jsx(K,{value:"ELEVATED",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(as,{className:"w-4 h-4 text-purple-600"}),e.jsxs("span",{children:["Elevated (",w.admins+w.management,")"]})]})}),e.jsx(K,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sr,{className:"w-4 h-4 text-yellow-600"}),e.jsxs("span",{children:["Admins (",w.admins,")"]})]})}),e.jsx(K,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($t,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Management (",w.management,")"]})]})}),e.jsx(K,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_t,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["Users (",w.users,")"]})]})}),e.jsx(K,{value:"ALL",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($t,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["All Users (",w.admins+w.management+w.users,")"]})]})})]})]})})]})}),e.jsx(ae,{className:"pt-6",children:v?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsx(Ze,{className:"w-6 h-6 animate-spin text-re-green mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading users..."})]}):f.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($t,{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:k==="ELEVATED"?"Assign ADMIN or MANAGEMENT roles to see users here":"No users match the selected filter"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Xk,{users:f.map(X=>({id:X.userId,name:X.displayName,email:X.email,role:X.role,department:X.department||"N/A",status:X.isActive?"active":"inactive"})),onEdit:X=>{const Y=f.find(G=>G.userId===X);if(Y){const G=Y.role==="USER"?"MANAGEMENT":Y.role==="MANAGEMENT"?"ADMIN":"USER";Z(X,G)}},onToggleStatus:I,onDelete:V}),N>1&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t mt-4",children:[e.jsxs("div",{className:"text-sm text-gray-600",children:["Showing ",(D-1)*E+1," to ",Math.min(D*E,R)," of ",R," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(F,{variant:"outline",size:"sm",onClick:()=>ce(D-1),disabled:D===1,children:"Previous"}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,N)},(X,Y)=>{let G;return N<=5||D<=3?G=Y+1:D>=N-2?G=N-4+Y:G=D-2+Y,e.jsx(F,{variant:D===G?"default":"outline",size:"sm",onClick:()=>ce(G),className:`w-9 h-9 p-0 ${D===G?"bg-re-green hover:bg-re-green/90":""}`,children:G},G)})}),e.jsx(F,{variant:"outline",size:"sm",onClick:()=>ce(D+1),disabled:D===N,children:"Next"})]})]})]})})]})]})}function e4({expressHours:t,standardHours:s,onExpressChange:a,onStandardChange:r}){return e.jsxs(te,{className:"border-0 shadow-sm",children:[e.jsxs(ue,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wi,{className:"w-5 h-5 text-re-green"}),e.jsx(xe,{className:"text-base font-semibold",children:"Priority TAT Settings"})]}),e.jsx(ke,{className:"text-sm",children:"Set default turnaround time in hours for each priority level"})]}),e.jsx(ae,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{htmlFor:"tat-express",className:"text-sm font-medium",children:"Express Priority (hours)"}),e.jsx(_e,{id:"tat-express",type:"number",min:"1",max:"168",value:t,onChange:n=>a(parseInt(n.target.value)||24),className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Xe,{className:"w-3 h-3"}),"Critical/Emergency requests (24/7, includes weekends)"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{htmlFor:"tat-standard",className:"text-sm font-medium",children:"Standard Priority (hours)"}),e.jsx(_e,{id:"tat-standard",type:"number",min:"1",max:"720",value:s,onChange:n=>r(parseInt(n.target.value)||72),className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Xe,{className:"w-3 h-3"}),"Regular priority requests (working hours only, excludes weekends & holidays)"]})]})]})})]})}function t4({reminderThreshold1:t,reminderThreshold2:s,onReminderThreshold1Change:a,onReminderThreshold2Change:r}){return e.jsxs(te,{className:"border-0 shadow-sm",children:[e.jsxs(ue,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ks,{className:"w-5 h-5 text-re-green"}),e.jsx(xe,{className:"text-base font-semibold",children:"Auto-Reminder & Escalation"})]}),e.jsx(ke,{className:"text-sm",children:"Configure automatic reminder thresholds based on TAT percentage"})]}),e.jsx(ae,{className:"space-y-6",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(le,{htmlFor:"reminder-threshold-1",className:"text-sm font-medium",children:"First Reminder Threshold"}),e.jsxs("span",{className:"text-lg font-semibold text-re-green",children:[t,"%"]})]}),e.jsx(mo,{id:"reminder-threshold-1",value:[t],min:1,max:100,step:1,onValueChange:([n])=>{n!==void 0&&a(n)},className:"w-full"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ks,{className:"w-3 h-3"}),"Send first gentle reminder when ",t,"% of TAT elapsed"]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(le,{htmlFor:"reminder-threshold-2",className:"text-sm font-medium",children:"Second Reminder Threshold (Escalation)"}),e.jsxs("span",{className:"text-lg font-semibold text-re-green",children:[s,"%"]})]}),e.jsx(mo,{id:"reminder-threshold-2",value:[s],min:1,max:100,step:1,onValueChange:([n])=>{n!==void 0&&r(n)},className:"w-full"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(os,{className:"w-3 h-3"}),"Send escalation warning when ",s,"% of TAT elapsed"]})]})]})})]})}const ln=[{value:1,label:"Monday"},{value:2,label:"Tuesday"},{value:3,label:"Wednesday"},{value:4,label:"Thursday"},{value:5,label:"Friday"},{value:6,label:"Saturday"},{value:7,label:"Sunday"}];function s4({workStartHour:t,workEndHour:s,workStartDay:a,workEndDay:r,onWorkStartHourChange:n,onWorkEndHourChange:i,onWorkStartDayChange:l,onWorkEndDayChange:o}){var d,c,m;return e.jsxs(te,{className:"border-0 shadow-sm",children:[e.jsxs(ue,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(it,{className:"w-5 h-5 text-re-green"}),e.jsx(xe,{className:"text-base font-semibold",children:"Working Hours Configuration"})]}),e.jsx(ke,{className:"text-sm",children:"Define your organization's working hours and days for TAT calculations"})]}),e.jsxs(ae,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{htmlFor:"work-start-hour",className:"text-sm font-medium",children:"Working Day Start Hour"}),e.jsx(_e,{id:"work-start-hour",type:"number",min:"0",max:"23",value:t,onChange:u=>n(parseInt(u.target.value)||9),className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Xe,{className:"w-3 h-3"}),"24-hour format (0-23). Default: 9 AM"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{htmlFor:"work-end-hour",className:"text-sm font-medium",children:"Working Day End Hour"}),e.jsx(_e,{id:"work-end-hour",type:"number",min:"0",max:"23",value:s,onChange:u=>i(parseInt(u.target.value)||18),className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Xe,{className:"w-3 h-3"}),"24-hour format (0-23). Default: 6 PM"]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{htmlFor:"work-start-day",className:"text-sm font-medium",children:"Working Week Start Day"}),e.jsxs(Ve,{value:a.toString(),onValueChange:u=>l(parseInt(u)),children:[e.jsx(He,{id:"work-start-day",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(ze,{placeholder:"Select start day"})}),e.jsx(We,{children:ln.map(u=>e.jsx(K,{value:u.value.toString(),children:u.label},u.value))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Day when the working week starts (1=Monday, 7=Sunday)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{htmlFor:"work-end-day",className:"text-sm font-medium",children:"Working Week End Day"}),e.jsxs(Ve,{value:r.toString(),onValueChange:u=>o(parseInt(u)),children:[e.jsx(He,{id:"work-end-day",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(ze,{placeholder:"Select end day"})}),e.jsx(We,{children:ln.map(u=>e.jsx(K,{value:u.value.toString(),children:u.label},u.value))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Day when the working week ends (1=Monday, 7=Sunday)"})]})]}),e.jsx("div",{className:"p-4 bg-blue-50 border border-blue-200 rounded-md",children:e.jsxs("p",{className:"text-sm text-blue-900",children:[e.jsx("strong",{children:"Current Configuration:"})," Working hours are from ",t,":00 to ",s,":00,",a===r?` ${(d=ln.find(u=>u.value===a))==null?void 0:d.label} only`:` ${(c=ln.find(u=>u.value===a))==null?void 0:c.label} to ${(m=ln.find(u=>u.value===r))==null?void 0:m.label}`]})})]})]})}function a4(){const[t,s]=h.useState(!0),[a,r]=h.useState(!1),[n,i]=h.useState({expressHours:24,standardHours:72,reminderThreshold1:50,reminderThreshold2:75,workStartHour:9,workEndHour:18,workStartDay:1,workEndDay:5});h.useEffect(()=>{l()},[]);const l=async()=>{try{s(!0);const c=await Hi("TAT_SETTINGS"),m={};c.forEach(u=>{m[u.configKey]=u.configValue}),i({expressHours:parseInt(m.DEFAULT_TAT_EXPRESS_HOURS||"24"),standardHours:parseInt(m.DEFAULT_TAT_STANDARD_HOURS||"72"),reminderThreshold1:parseInt(m.TAT_REMINDER_THRESHOLD_1||"50"),reminderThreshold2:parseInt(m.TAT_REMINDER_THRESHOLD_2||"75"),workStartHour:parseInt(m.WORK_START_HOUR||"9"),workEndHour:parseInt(m.WORK_END_HOUR||"18"),workStartDay:parseInt(m.WORK_START_DAY||"1"),workEndDay:parseInt(m.WORK_END_DAY||"5")})}catch(c){console.error("Failed to load TAT configurations:",c),Q.error("Failed to load TAT configurations")}finally{s(!1)}},o=async()=>{var c,m;try{r(!0),await Promise.all([Ss("DEFAULT_TAT_EXPRESS_HOURS",n.expressHours.toString()),Ss("DEFAULT_TAT_STANDARD_HOURS",n.standardHours.toString()),Ss("TAT_REMINDER_THRESHOLD_1",n.reminderThreshold1.toString()),Ss("TAT_REMINDER_THRESHOLD_2",n.reminderThreshold2.toString()),Ss("WORK_START_HOUR",n.workStartHour.toString()),Ss("WORK_END_HOUR",n.workEndHour.toString()),Ss("WORK_START_DAY",n.workStartDay.toString()),Ss("WORK_END_DAY",n.workEndDay.toString())]),Q.success("TAT configuration saved successfully"),await l()}catch(u){console.error("Failed to save TAT configuration:",u),Q.error(((m=(c=u.response)==null?void 0:c.data)==null?void 0:m.error)||"Failed to save TAT configuration")}finally{r(!1)}},d=c=>{i(m=>({...m,...c}))};return t?e.jsx(te,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(ae,{className:"p-12 text-center",children:[e.jsx(Ze,{className:"w-8 h-8 animate-spin text-re-green mx-auto mb-4"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Loading TAT configuration..."})]})}):e.jsxs(te,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ue,{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(Xe,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-lg font-semibold text-gray-900",children:"Turn Around Time (TAT) Configuration"}),e.jsx(ke,{className:"text-sm text-gray-600",children:"Set default TAT hours per priority level, working hours, and configure auto-escalation thresholds"})]})]})}),e.jsxs(ae,{className:"space-y-6",children:[e.jsx(e4,{expressHours:n.expressHours,standardHours:n.standardHours,onExpressChange:c=>d({expressHours:c}),onStandardChange:c=>d({standardHours:c})}),e.jsx(Gt,{}),e.jsx(s4,{workStartHour:n.workStartHour,workEndHour:n.workEndHour,workStartDay:n.workStartDay,workEndDay:n.workEndDay,onWorkStartHourChange:c=>d({workStartHour:c}),onWorkEndHourChange:c=>d({workEndHour:c}),onWorkStartDayChange:c=>d({workStartDay:c}),onWorkEndDayChange:c=>d({workEndDay:c})}),e.jsx(Gt,{}),e.jsx(t4,{reminderThreshold1:n.reminderThreshold1,reminderThreshold2:n.reminderThreshold2,onReminderThreshold1Change:c=>d({reminderThreshold1:c}),onReminderThreshold2Change:c=>d({reminderThreshold2:c})}),e.jsx("div",{className:"flex justify-end pt-4",children:e.jsx(F,{onClick:o,disabled:a,className:"bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:a?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Za,{className:"w-4 h-4 mr-2"}),"Save TAT Settings"]})})})]})]})}function r4({emailNotifications:t,inAppNotifications:s,autoReminders:a,onEmailNotificationsChange:r,onInAppNotificationsChange:n,onAutoRemindersChange:i}){return e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"font-medium",children:"Notification Channels"}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Email Notifications"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Send notifications via email"})]}),e.jsx(Ps,{checked:t,onCheckedChange:r})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"In-App Notifications"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Show notifications in the portal"})]}),e.jsx(Ps,{checked:s,onCheckedChange:n})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Auto-Reminders"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Automatically send reminders for pending approvals"})]}),e.jsx(Ps,{checked:a,onCheckedChange:i})]})]})}function n4({notificationFrequency:t,reminderFrequency:s,onNotificationFrequencyChange:a,onReminderFrequencyChange:r}){return e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{htmlFor:"notification-frequency",children:"Notification Frequency"}),e.jsxs(Ve,{value:t,onValueChange:a,children:[e.jsx(He,{id:"notification-frequency",children:e.jsx(ze,{placeholder:"Select frequency"})}),e.jsxs(We,{children:[e.jsx(K,{value:"Immediate",children:"Immediate"}),e.jsx(K,{value:"Hourly",children:"Hourly"}),e.jsx(K,{value:"Daily",children:"Daily"}),e.jsx(K,{value:"Weekly",children:"Weekly"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{htmlFor:"reminder-frequency",children:"Reminder Frequency (hours)"}),e.jsx(_e,{id:"reminder-frequency",type:"number",min:"1",max:"168",value:s,onChange:n=>r(parseInt(n.target.value)||12)})]})]})}function i4({emailTemplate:t,onEmailTemplateChange:s}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{htmlFor:"email-template",children:"Email Template Message"}),e.jsx(Es,{id:"email-template",rows:5,value:t,onChange:a=>s(a.target.value),className:"resize-none",placeholder:"Enter email template message..."}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Use placeholders: [Name], [Request ID], [TAT], [Status]"})]})}function l4(){const[t,s]=h.useState({emailNotifications:!0,inAppNotifications:!0,autoReminders:!0,notificationFrequency:"Immediate",reminderFrequency:12,emailTemplate:"Dear [Name], You have a pending approval request [Request ID] that requires your attention. TAT remaining: [TAT]. Please review at your earliest convenience."}),a=()=>{Q.success("Notification configuration saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(te,{children:[e.jsxs(ue,{children:[e.jsx(xe,{children:"Notification Configuration"}),e.jsx(ke,{children:"Configure notification channels, frequency, and message templates"})]}),e.jsxs(ae,{className:"space-y-6",children:[e.jsx(r4,{emailNotifications:t.emailNotifications,inAppNotifications:t.inAppNotifications,autoReminders:t.autoReminders,onEmailNotificationsChange:n=>r({emailNotifications:n}),onInAppNotificationsChange:n=>r({inAppNotifications:n}),onAutoRemindersChange:n=>r({autoReminders:n})}),e.jsx(Gt,{}),e.jsx(n4,{notificationFrequency:t.notificationFrequency,reminderFrequency:t.reminderFrequency,onNotificationFrequencyChange:n=>r({notificationFrequency:n}),onReminderFrequencyChange:n=>r({reminderFrequency:n})}),e.jsx(i4,{emailTemplate:t.emailTemplate,onEmailTemplateChange:n=>r({emailTemplate:n})}),e.jsxs(F,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(Za,{className:"w-4 h-4 mr-2"}),"Save Notification Settings"]})]})]})}function o4({maxFileSizeMB:t,retentionDays:s,onMaxFileSizeChange:a,onRetentionDaysChange:r}){const n=Math.round(s/365*10)/10;return e.jsxs(te,{className:"border-0 shadow-sm",children:[e.jsxs(ue,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bs,{className:"w-5 h-5 text-re-green"}),e.jsx(xe,{className:"text-base font-semibold",children:"Upload & Retention Settings"})]}),e.jsx(ke,{className:"text-sm",children:"Configure file size limits and document retention period"})]}),e.jsx(ae,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{htmlFor:"max-upload",className:"text-sm font-medium",children:"Maximum Upload Size (MB)"}),e.jsx(_e,{id:"max-upload",type:"number",min:"1",max:"100",value:t,onChange:i=>a(parseInt(i.target.value)||10),className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Bs,{className:"w-3 h-3"}),"Maximum allowed file size for document uploads"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{htmlFor:"retention",className:"text-sm font-medium",children:"Retention Period (Days)"}),e.jsx(_e,{id:"retention",type:"number",min:"30",max:"3650",value:s,onChange:i=>r(parseInt(i.target.value)||365),className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ei,{className:"w-3 h-3"}),"Days to retain documents after workflow closure (",n," years)"]})]})]})})]})}const c4=[{label:"PDF Documents",extensions:["pdf"]},{label:"Microsoft Word",extensions:["doc","docx"]},{label:"Microsoft Excel",extensions:["xls","xlsx"]},{label:"Microsoft PowerPoint",extensions:["ppt","pptx"]},{label:"Images",extensions:["jpg","jpeg","png","gif","bmp","webp"]},{label:"CSV Files",extensions:["csv"]},{label:"Text Files",extensions:["txt","rtf"]}];function d4({allowedFileTypes:t,onAllowedFileTypesChange:s}){const a=t.split(",").map(l=>l.trim().toLowerCase()),r=(l,o)=>{const d=new Set(a);o?l.forEach(c=>d.add(c)):l.forEach(c=>d.delete(c)),s(Array.from(d).join(","))},n=l=>l.some(o=>a.includes(o)),i=l=>{s(l)};return e.jsxs(te,{className:"border-0 shadow-sm",children:[e.jsxs(ue,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(No,{className:"w-5 h-5 text-re-green"}),e.jsx(xe,{className:"text-base font-semibold",children:"Allowed File Types"})]}),e.jsx(ke,{className:"text-sm",children:"Select which file types are allowed for upload"})]}),e.jsxs(ae,{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:c4.map(l=>{const o=n(l.extensions);return e.jsxs("div",{onClick:()=>r(l.extensions,!o),className:`flex items-center justify-between p-3 rounded-md border-2 cursor-pointer transition-all ${o?"bg-re-green/5 border-re-green/30 hover:border-re-green/50":"bg-gray-50 border-gray-200 hover:border-gray-300"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`w-4 h-4 rounded border-2 flex items-center justify-center ${o?"bg-re-green border-re-green":"bg-white border-gray-300"}`,children:o&&e.jsx("svg",{className:"w-3 h-3 text-white",fill:"currentColor",viewBox:"0 0 20 20",children:e.jsx("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})})}),e.jsx("span",{className:`text-sm font-medium ${o?"text-re-green":"text-gray-600"}`,children:l.label})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:l.extensions.join(", ")})]},l.label)})}),e.jsxs("div",{className:"space-y-2 pt-2",children:[e.jsx(le,{htmlFor:"file-types-manual",className:"text-sm font-medium",children:"File Extensions (comma-separated)"}),e.jsx(_e,{id:"file-types-manual",type:"text",value:t,onChange:l=>i(l.target.value),placeholder:"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20 font-mono text-sm"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Edit directly or use the checkboxes above. Separate extensions with commas."})]})]})]})}function m4(){const[t,s]=h.useState(!0),[a,r]=h.useState(!1),[n,i]=h.useState({maxFileSizeMB:10,retentionDays:365,allowedFileTypes:"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif"});h.useEffect(()=>{l()},[]);const l=async()=>{try{s(!0);const c=await Hi("DOCUMENT_POLICY"),m={};c.forEach(u=>{m[u.configKey]=u.configValue}),i({maxFileSizeMB:parseInt(m.MAX_FILE_SIZE_MB||"10"),retentionDays:parseInt(m.DOCUMENT_RETENTION_DAYS||"365"),allowedFileTypes:m.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif"})}catch(c){console.error("Failed to load document configurations:",c),Q.error("Failed to load document configurations")}finally{s(!1)}},o=async()=>{var c,m;try{r(!0),await Promise.all([Ss("MAX_FILE_SIZE_MB",n.maxFileSizeMB.toString()),Ss("DOCUMENT_RETENTION_DAYS",n.retentionDays.toString()),Ss("ALLOWED_FILE_TYPES",n.allowedFileTypes)]),Q.success("Document policy saved successfully"),await l()}catch(u){console.error("Failed to save document configuration:",u),Q.error(((m=(c=u.response)==null?void 0:c.data)==null?void 0:m.error)||"Failed to save document configuration")}finally{r(!1)}},d=c=>{i(m=>({...m,...c}))};return t?e.jsx(te,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(ae,{className:"p-12 text-center",children:[e.jsx(Ze,{className:"w-8 h-8 animate-spin text-re-green mx-auto mb-4"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Loading document policy configuration..."})]})}):e.jsxs(te,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ue,{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(Pe,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-lg font-semibold text-gray-900",children:"Document Upload Policy"}),e.jsx(ke,{className:"text-sm text-gray-600",children:"Configure file upload limits, allowed types, and retention policies"})]})]})}),e.jsxs(ae,{className:"space-y-6",children:[e.jsx(o4,{maxFileSizeMB:n.maxFileSizeMB,retentionDays:n.retentionDays,onMaxFileSizeChange:c=>d({maxFileSizeMB:c}),onRetentionDaysChange:c=>d({retentionDays:c})}),e.jsx(Gt,{}),e.jsx(d4,{allowedFileTypes:n.allowedFileTypes,onAllowedFileTypesChange:c=>d({allowedFileTypes:c})}),e.jsx("div",{className:"flex justify-end pt-4",children:e.jsx(F,{onClick:o,disabled:a,className:"bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:a?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Za,{className:"w-4 h-4 mr-2"}),"Save Document Policy"]})})})]})]})}function u4(){return e.jsx("div",{className:"p-4 bg-blue-50 border border-blue-200 rounded-lg",children:e.jsxs("p",{className:"text-sm text-blue-800",children:[e.jsx("strong",{children:"Note:"})," These settings control what information is visible to each role on their dashboard. Admins always have access to all metrics."]})})}const x4=["Total Requests","Open Requests","Approved Requests","Rejected Requests","My Pending Actions","TAT Compliance","Delayed Workflows","Average Cycle Time"],h4=t=>{switch(t){case"Initiator":return"bg-blue-100 text-blue-800";case"Approver":return"bg-green-100 text-green-800";case"Spectator":return"bg-gray-100 text-gray-800";default:return"bg-gray-100 text-gray-800"}};function p4({role:t,kpis:s,onKPIToggle:a}){return e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"font-medium flex items-center gap-2",children:e.jsxs(ne,{className:h4(t),children:[t," Dashboard"]})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-2 ml-4",children:x4.map(r=>e.jsxs("div",{className:"flex items-center space-x-2 p-2 bg-muted/50 rounded",children:[e.jsx(vc,{id:`${t.toLowerCase()}-${r}`,checked:s[r]||!1,onCheckedChange:n=>a(r,n===!0)}),e.jsx("label",{htmlFor:`${t.toLowerCase()}-${r}`,className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer",children:r})]},r))})]})}function g4(){const[t,s]=h.useState({Initiator:{"Total Requests":!0,"Open Requests":!0,"Approved Requests":!0,"Rejected Requests":!0,"My Pending Actions":!0,"TAT Compliance":!0,"Delayed Workflows":!0,"Average Cycle Time":!0},Approver:{"Total Requests":!0,"Open Requests":!0,"Approved Requests":!0,"Rejected Requests":!0,"My Pending Actions":!0,"TAT Compliance":!0,"Delayed Workflows":!0,"Average Cycle Time":!0},Spectator:{"Total Requests":!0,"Open Requests":!0,"Approved Requests":!0,"Rejected Requests":!0,"My Pending Actions":!0,"TAT Compliance":!0,"Delayed Workflows":!0,"Average Cycle Time":!0}}),a=()=>{Q.success("Dashboard layout saved successfully")},r=(i,l,o)=>{s(d=>({...d,[i]:{...d[i],[l]:o}}))},n=["Initiator","Approver","Spectator"];return e.jsxs(te,{children:[e.jsxs(ue,{children:[e.jsx(xe,{children:"Dashboard Layout Configuration"}),e.jsx(ke,{children:"Control which KPI cards are visible for each user role"})]}),e.jsxs(ae,{className:"space-y-4",children:[e.jsx(u4,{}),e.jsx("div",{className:"space-y-6",children:n.map(i=>e.jsx(p4,{role:i,kpis:t[i]||{},onKPIToggle:(l,o)=>r(i,l,o)},i))}),e.jsxs(F,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(Za,{className:"w-4 h-4 mr-2"}),"Save Dashboard Layout"]})]})]})}function f4({aiEnabled:t,onAiEnabledChange:s}){return e.jsxs(te,{className:"border-0 shadow-sm",children:[e.jsxs(ue,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cx,{className:"w-5 h-5 text-re-green"}),e.jsx(xe,{className:"text-base font-semibold",children:"Vertex AI Gemini Configuration"})]}),e.jsx(ke,{className:"text-sm",children:"Configure AI features. Model and region are configured via environment variables."})]}),e.jsx(ae,{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 border border-gray-200 rounded-md",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"Enable AI Features"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Master toggle to enable/disable all AI-powered features"})]}),e.jsx(Ps,{checked:t,onCheckedChange:s})]})})]})}function y4({aiRemarkGeneration:t,onRemarkGenerationChange:s}){return e.jsxs(te,{className:"border-0 shadow-sm",children:[e.jsxs(ue,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ai,{className:"w-5 h-5 text-re-green"}),e.jsx(xe,{className:"text-base font-semibold",children:"AI Features"})]}),e.jsx(ke,{className:"text-sm",children:"Enable/disable specific AI-powered features"})]}),e.jsx(ae,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 border border-gray-200 rounded-md hover:bg-gray-100 transition-colors",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"AI Remark Generation"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Automatically generate conclusion remarks for workflow closures"})]}),e.jsx(Ps,{checked:t,onCheckedChange:s})]})})})]})}function b4({maxRemarkChars:t,onMaxRemarkCharsChange:s}){return e.jsxs(te,{className:"border-0 shadow-sm",children:[e.jsxs(ue,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ox,{className:"w-5 h-5 text-re-green"}),e.jsx(xe,{className:"text-base font-semibold",children:"AI Parameters"})]}),e.jsx(ke,{className:"text-sm",children:"Configure AI generation parameters"})]}),e.jsx(ae,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{htmlFor:"max-remark-chars",className:"text-sm font-medium",children:"Maximum Remark Length"}),e.jsx(_e,{id:"max-remark-chars",type:"number",min:"500",max:"5000",value:t,onChange:a=>s(parseInt(a.target.value)||2e3),className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Maximum character length for AI-generated conclusion remarks (500-5000 characters)"})]})})]})}function v4(){const[t,s]=h.useState(!0),[a,r]=h.useState(!1),[n,i]=h.useState({aiEnabled:!0,aiRemarkGeneration:!0,maxRemarkChars:2e3});h.useEffect(()=>{l()},[]);const l=async()=>{try{s(!0);const c=await Hi("AI_CONFIGURATION"),m={};c.forEach(u=>{m[u.configKey]=u.configValue}),i({aiEnabled:m.AI_ENABLED==="true",aiRemarkGeneration:m.AI_REMARK_GENERATION_ENABLED==="true",maxRemarkChars:parseInt(m.AI_MAX_REMARK_LENGTH||"2000")})}catch(c){console.error("Failed to load AI configurations:",c),Q.error("Failed to load AI configurations")}finally{s(!1)}},o=async()=>{var c,m;try{r(!0),await Promise.all([Ss("AI_ENABLED",n.aiEnabled.toString()),Ss("AI_REMARK_GENERATION_ENABLED",n.aiRemarkGeneration.toString()),Ss("AI_MAX_REMARK_LENGTH",n.maxRemarkChars.toString())]),Q.success("AI configuration saved successfully"),await l()}catch(u){console.error("Failed to save AI configuration:",u),Q.error(((m=(c=u.response)==null?void 0:c.data)==null?void 0:m.error)||"Failed to save AI configuration")}finally{r(!1)}},d=c=>{i(m=>({...m,...c}))};return t?e.jsx(te,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(ae,{className:"p-12 text-center",children:[e.jsx(Ze,{className:"w-8 h-8 animate-spin text-re-green mx-auto mb-4"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Loading AI configuration..."})]})}):e.jsxs(te,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ue,{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(Ai,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-lg font-semibold text-gray-900",children:"AI Features Configuration"}),e.jsx(ke,{className:"text-sm text-gray-600",children:"Configure Vertex AI Gemini settings and enable/disable AI-powered features"})]})]})}),e.jsxs(ae,{className:"space-y-6",children:[e.jsx(f4,{aiEnabled:n.aiEnabled,onAiEnabledChange:c=>d({aiEnabled:c})}),e.jsx(Gt,{}),e.jsx(y4,{aiRemarkGeneration:n.aiRemarkGeneration,onRemarkGenerationChange:c=>d({aiRemarkGeneration:c})}),e.jsx(Gt,{}),e.jsx(b4,{maxRemarkChars:n.maxRemarkChars,onMaxRemarkCharsChange:c=>d({maxRemarkChars:c})}),e.jsx("div",{className:"flex justify-end pt-4",children:e.jsx(F,{onClick:o,disabled:a,className:"bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:a?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Za,{className:"w-4 h-4 mr-2"}),"Save AI Configuration"]})})})]})]})}const Ru=["Admin Only","Initiator Only","Approver Only","Initiator & Approver","Admin & Initiator","Admin & Approver","All Roles"];function j4({spectatorPermission:t,linkSharingPermission:s,onSpectatorPermissionChange:a,onLinkSharingPermissionChange:r}){return e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{htmlFor:"spectator-permission",children:"Spectator Addition Permission"}),e.jsxs(Ve,{value:t,onValueChange:a,children:[e.jsx(He,{id:"spectator-permission",children:e.jsx(ze,{placeholder:"Select permission"})}),e.jsx(We,{children:Ru.map(n=>e.jsx(K,{value:n,children:n},n))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{htmlFor:"link-sharing-permission",children:"Link Sharing Permission"}),e.jsxs(Ve,{value:s,onValueChange:r,children:[e.jsx(He,{id:"link-sharing-permission",children:e.jsx(ze,{placeholder:"Select permission"})}),e.jsx(We,{children:Ru.map(n=>e.jsx(K,{value:n,children:n},n))})]})]})]})}function N4({requirePassword:t,allowExternalSharing:s,onRequirePasswordChange:a,onAllowExternalSharingChange:r}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Require Password for Shared Links"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add password protection to workflow sharing links"})]}),e.jsx(Ps,{checked:t,onCheckedChange:a})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Allow External Sharing"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Enable sharing workflows with external users outside the organization"})]}),e.jsx(Ps,{checked:s,onCheckedChange:r})]})]})}function w4(){const[t,s]=h.useState({spectatorPermission:"Initiator & Approver",linkSharingPermission:"Admin & Initiator",requirePassword:!0,allowExternalSharing:!1}),a=()=>{Q.success("Sharing policy saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(te,{children:[e.jsxs(ue,{children:[e.jsx(xe,{children:"Workflow Sharing Policy"}),e.jsx(ke,{children:"Control who can add spectators and share workflow links"})]}),e.jsxs(ae,{className:"space-y-6",children:[e.jsx(j4,{spectatorPermission:t.spectatorPermission,linkSharingPermission:t.linkSharingPermission,onSpectatorPermissionChange:n=>r({spectatorPermission:n}),onLinkSharingPermissionChange:n=>r({linkSharingPermission:n})}),e.jsx(Gt,{}),e.jsx(N4,{requirePassword:t.requirePassword,allowExternalSharing:t.allowExternalSharing,onRequirePasswordChange:n=>r({requirePassword:n}),onAllowExternalSharingChange:n=>r({allowExternalSharing:n})}),e.jsxs(F,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(Za,{className:"w-4 h-4 mr-2"}),"Save Sharing Policy"]})]})]})}function C4(){const{user:t}=Jt(),[s,a]=h.useState(""),[r,n]=h.useState("sharing"),i=[{name:"Request Volume & Status",count:4,kpis:[{id:"total-requests",title:"Total Requests Created",description:"Count of all workflow requests created in a selected period.",value:5,change:12,changeType:"up",period:"Month",visibleTo:["Initiator","Management","Admin"],category:"Request Volume & Status",bgColor:"bg-blue-50",borderColor:"border-blue-200"},{id:"open-requests",title:"Open Requests",description:"Number of workflows currently in progress with age.",value:3,change:-5,changeType:"down",period:"Today",visibleTo:["Initiator","Management","Admin"],category:"Request Volume & Status",bgColor:"bg-blue-50",borderColor:"border-blue-200"},{id:"approved-requests",title:"Approved Requests",description:"Requests fully approved and closed.",value:1,change:8,changeType:"up",period:"Month",visibleTo:["Initiator","Management","Admin"],category:"Request Volume & Status",bgColor:"bg-blue-50",borderColor:"border-blue-200"},{id:"rejected-requests",title:"Rejected Requests",description:"Requests rejected at any approval stage.",value:1,period:"Month",visibleTo:["Initiator","Management","Admin"],category:"Request Volume & Status",bgColor:"bg-blue-50",borderColor:"border-blue-200"}]},{name:"TAT Efficiency",count:3,kpis:[{id:"avg-tat-compliance",title:"Average TAT Compliance %",description:"% of workflows completed within defined TAT vs breached ones at every level.",value:100,unit:"%",change:3,changeType:"up",period:"Month",visibleTo:["Initiator","Management","Admin"],category:"TAT Efficiency",bgColor:"bg-green-50",borderColor:"border-green-200"},{id:"avg-approval-cycle",title:"Avg Approval Cycle Time (Days)",description:"Average total time from creation to closure.",value:5.2,unit:" days",change:-15,changeType:"down",period:"Month",visibleTo:["Initiator","Management","Admin"],category:"TAT Efficiency",bgColor:"bg-green-50",borderColor:"border-green-200",thresholdBreached:!0},{id:"delayed-workflows",title:"Delayed Workflows",description:"Requests currently breaching their TAT.",value:0,change:-2,changeType:"down",period:"Today",visibleTo:["Initiator","Management","Admin"],category:"TAT Efficiency",bgColor:"bg-green-50",borderColor:"border-green-200"}]},{name:"Approver Load",count:2,kpis:[{id:"pending-actions",title:"Pending Actions (My Queue)",description:"Requests currently awaiting user's approval with age.",value:3,period:"Today",visibleTo:["Management","Admin"],category:"Approver Load",bgColor:"bg-orange-50",borderColor:"border-orange-200"},{id:"approvals-completed",title:"Approvals Completed (Today/Week)",description:"Count of actions taken within a time frame.",value:0,change:22,changeType:"up",period:"Week",visibleTo:["Management","Admin"],category:"Approver Load",bgColor:"bg-orange-50",borderColor:"border-orange-200"}]},{name:"Engagement & Quality",count:2,kpis:[{id:"comments-worknotes",title:"Comments / Work Notes Added",description:"Measures collaboration activity.",value:8,change:18,changeType:"up",period:"Week",visibleTo:["Management","Admin"],category:"Engagement & Quality",bgColor:"bg-purple-50",borderColor:"border-purple-200"},{id:"attachments-uploaded",title:"Attachments Uploaded",description:"Number of documents added to workflows.",value:16,change:10,changeType:"up",period:"Month",visibleTo:["Initiator","Management","Admin"],category:"Engagement & Quality",bgColor:"bg-purple-50",borderColor:"border-purple-200"}]},{name:"AI & Closure Insights",count:2,kpis:[{id:"avg-conclusion-length",title:"Avg Conclusion Remark Length",description:"Indicates depth of closure remarks (optional).",value:85,unit:" chars",change:5,changeType:"up",period:"Month",visibleTo:["Management","Admin"],category:"AI & Closure Insights",bgColor:"bg-pink-50",borderColor:"border-pink-200"},{id:"ai-summary-adoption",title:"AI Summary Adoption %",description:"How many closures used AI-generated text vs manual edits.",value:0,unit:"%",change:25,changeType:"up",period:"Month",visibleTo:["Management","Admin"],category:"AI & Closure Insights",bgColor:"bg-pink-50",borderColor:"border-pink-200"}]}],l=i.map(c=>({...c,kpis:c.kpis.filter(m=>m.title.toLowerCase().includes(s.toLowerCase())||m.description.toLowerCase().includes(s.toLowerCase())||m.category.toLowerCase().includes(s.toLowerCase()))})).filter(c=>c.kpis.length>0),o=i.reduce((c,m)=>c+m.count,0),d=c=>{switch(c){case"Initiator":return"bg-blue-100 text-blue-800 border-blue-200";case"Management":return"bg-orange-100 text-orange-800 border-orange-200";case"Admin":return"bg-purple-100 text-purple-800 border-purple-200";default:return"bg-gray-100 text-gray-800 border-gray-200"}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-re-black flex items-center gap-2",children:[e.jsx(as,{className:"w-8 h-8 text-re-green"}),"Admin Control Panel"]}),e.jsx("p",{className:"text-muted-foreground",children:"Manage users, configure system settings, and control portal behavior"})]}),e.jsxs(ne,{className:"bg-re-green/10 text-re-green border-re-green/20 px-4 py-2",children:[e.jsx(as,{className:"w-4 h-4 mr-2"}),"Administrator: ",(t==null?void 0:t.displayName)||"Admin User"]})]}),e.jsx(Gt,{}),e.jsxs(Ln,{value:r,onValueChange:n,className:"flex flex-col gap-2 space-y-4",children:[e.jsxs(On,{className:"text-muted-foreground items-center justify-center rounded-xl p-[3px] bg-muted grid w-full grid-cols-9 h-auto",children:[e.jsxs(At,{value:"kpi",className:"flex items-center gap-2",children:[e.jsx(di,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"KPI Config"})]}),e.jsxs(At,{value:"analytics",className:"flex items-center gap-2",children:[e.jsx(Ks,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Analytics"})]}),e.jsxs(At,{value:"users",className:"flex items-center gap-2",children:[e.jsx($t,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Users"})]}),e.jsxs(At,{value:"tat",className:"flex items-center gap-2",children:[e.jsx(Xe,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"TAT"})]}),e.jsxs(At,{value:"notifications",className:"flex items-center gap-2",children:[e.jsx(ks,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Notify"})]}),e.jsxs(At,{value:"documents",className:"flex items-center gap-2",children:[e.jsx(Pe,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Docs"})]}),e.jsxs(At,{value:"dashboard",className:"flex items-center gap-2",children:[e.jsx(b0,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Dashboard"})]}),e.jsxs(At,{value:"ai",className:"flex items-center gap-2",children:[e.jsx(cx,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"AI"})]}),e.jsxs(At,{value:"sharing",className:"flex items-center gap-2",children:[e.jsx(Br,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Sharing"})]})]}),e.jsx(St,{value:"kpi",className:"flex-1 outline-none space-y-4",children:e.jsxs(te,{children:[e.jsx(ue,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(xe,{children:"KPI Configuration"}),e.jsx(ke,{children:"Configure which KPIs are enabled, visible to specific roles, and set alert thresholds"})]}),e.jsxs(ne,{className:"bg-blue-50 text-blue-700",children:[o," / ",o," KPIs Active"]})]})}),e.jsxs(ae,{className:"space-y-6",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:"relative flex-1",children:[e.jsx(As,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(_e,{placeholder:"Search KPIs by name, description, or category...",value:s,onChange:c=>a(c.target.value),className:"pl-10"})]})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:i.map(c=>e.jsxs("div",{className:"p-4 bg-muted/50 rounded-lg",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:c.name}),e.jsx("p",{className:"text-2xl font-semibold",children:c.count})]},c.name))}),l.map(c=>e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dt,{className:"w-5 h-5 text-re-green"}),e.jsx("h3",{className:"font-semibold",children:c.name}),e.jsxs(ne,{variant:"outline",className:"ml-auto",children:[c.kpis.length," Active"]})]}),e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3",children:c.kpis.map(m=>e.jsx("div",{className:`p-4 border rounded-lg ${m.bgColor} ${m.borderColor} transition-all hover:shadow-md ${m.thresholdBreached?"ring-2 ring-orange-500":""}`,children:e.jsx("div",{className:"flex items-start justify-between gap-4",children:e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("h4",{className:"font-medium text-sm mb-1",children:m.title}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:m.description})]}),e.jsx(ne,{className:"bg-green-100 text-green-800 text-xs",children:"Active"})]}),e.jsxs("div",{className:"flex items-end gap-3 py-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"flex items-baseline gap-1",children:[e.jsx("span",{className:"text-4xl font-bold text-re-black",children:m.value}),m.unit&&e.jsx("span",{className:"text-lg text-muted-foreground",children:m.unit})]})}),m.change!==void 0&&e.jsxs("div",{className:`flex items-center gap-1 text-xs px-2 py-1 rounded ${m.changeType==="up"?"bg-green-100 text-green-700":"bg-red-100 text-red-700"}`,children:[m.changeType==="up"?e.jsx(v0,{className:"w-3 h-3"}):e.jsx(j0,{className:"w-3 h-3"}),e.jsxs("span",{className:"font-semibold",children:[Math.abs(m.change),"%"]})]})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Visible:"}),m.visibleTo.map(u=>e.jsx(ne,{className:`${d(u)} text-xs px-1.5 py-0`,children:u},u))]}),e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:["Period: ",m.period]}),m.thresholdBreached&&e.jsxs("div",{className:"flex items-center gap-1 text-orange-600",children:[e.jsx(Ge,{className:"w-3 h-3"}),e.jsx("span",{className:"font-medium",children:"Threshold Breached!"})]})]})]})]})})},m.id))})]},c.name))]})]})}),e.jsx(St,{value:"analytics",className:"flex-1 outline-none space-y-4",children:e.jsx(Kk,{})}),e.jsx(St,{value:"users",className:"flex-1 outline-none space-y-4",children:e.jsx(qk,{})}),e.jsx(St,{value:"tat",className:"flex-1 outline-none space-y-4",children:e.jsx(a4,{})}),e.jsx(St,{value:"notifications",className:"flex-1 outline-none space-y-4",children:e.jsx(l4,{})}),e.jsx(St,{value:"documents",className:"flex-1 outline-none space-y-4",children:e.jsx(m4,{})}),e.jsx(St,{value:"dashboard",className:"flex-1 outline-none space-y-4",children:e.jsx(g4,{})}),e.jsx(St,{value:"ai",className:"flex-1 outline-none space-y-4",children:e.jsx(v4,{})}),e.jsx(St,{value:"sharing",className:"flex-1 outline-none space-y-4",children:e.jsx(w4,{})})]})]})}function A4({isOpen:t,onClose:s,action:a,requestId:r,requestTitle:n,onSubmit:i}){const[l,o]=h.useState(""),[d,c]=h.useState(!1),m=async()=>{if(!(!l.trim()||l.length>500)){c(!0);try{await i(a,l.trim()),o(""),s()}catch(y){console.error("Error submitting approval action:",y)}finally{c(!1)}}},u=()=>{o(""),s()},p=a==="approve"?{title:"Approve Request",description:"Please provide your approval comments and remarks",icon:De,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:jt,iconColor:"text-red-600",buttonColor:"bg-red-600 hover:bg-red-700",badgeColor:"bg-red-100 text-red-800 border-red-200",placeholder:"Enter detailed reasons for rejection and any suggestions for improvement..."},g=p.icon;return e.jsx(mt,{open:t,onOpenChange:u,children:e.jsxs(ot,{className:"max-w-2xl bg-white",children:[e.jsxs(ut,{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:`p-2 rounded-lg ${a==="approve"?"bg-green-100":"bg-red-100"}`,children:e.jsx(g,{className:`w-6 h-6 ${p.iconColor}`})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ct,{className:"text-xl",children:p.title}),e.jsx(It,{className:"mt-1",children:p.description})]})]}),e.jsxs("div",{className:"space-y-3 p-4 bg-gray-50 rounded-lg border",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium text-gray-900",children:"Request ID:"}),e.jsx(ne,{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(ne,{className:p.badgeColor,variant:"outline",children:[e.jsx(g,{className:"w-3 h-3 mr-1"}),a==="approve"?"APPROVE":"REJECT"]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{htmlFor:"comment",className:"text-sm font-semibold text-gray-900",children:"Comments & Remarks *"}),e.jsx(Es,{id:"comment",placeholder:p.placeholder,value:l,onChange:y=>o(y.target.value.slice(0,500)),className:"min-h-[120px] resize-none",rows:6}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(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(De,{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(Tt,{className:"gap-2",children:[e.jsx(F,{variant:"outline",onClick:u,disabled:d,children:"Cancel"}),e.jsx(F,{onClick:m,disabled:!l.trim()||d||l.length>500,className:p.buttonColor,children:d?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 S4=(t,s,a,r,n,i,l,o)=>{let d=document.documentElement,c=["light","dark"];function m(p){(Array.isArray(t)?t:[t]).forEach(g=>{let y=g==="class",f=y&&i?n.map(b=>i[b]||b):n;y?(d.classList.remove(...f),d.classList.add(i&&i[p]?i[p]:p)):d.setAttribute(g,p)}),u(p)}function u(p){o&&c.includes(p)&&(d.style.colorScheme=p)}function x(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}if(r)m(r);else try{let p=localStorage.getItem(s)||a,g=l&&p==="system"?x():p;m(g)}catch{}},T4=h.createContext(void 0),k4={setTheme:t=>{},themes:[]},R4=()=>{var t;return(t=h.useContext(T4))!=null?t:k4};h.memo(({forcedTheme:t,storageKey:s,attribute:a,enableSystem:r,enableColorScheme:n,defaultTheme:i,value:l,themes:o,nonce:d,scriptProps:c})=>{let m=JSON.stringify([a,s,i,t,o,l,r,n]).slice(1,-1);return h.createElement("script",{...c,suppressHydrationWarning:!0,nonce:typeof window>"u"?d:"",dangerouslySetInnerHTML:{__html:`(${S4.toString()})(${m})`}})});const D4=({...t})=>{const{theme:s="system"}=R4();return e.jsx(N0,{theme:s,className:"toaster group",style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)"},...t})};function P4({open:t,onClose:s,onSelect:a,managers:r=[],errorType:n,message:i,isLoading:l=!1}){const o=d=>{a(d)};return e.jsx(mt,{open:t,onOpenChange:s,children:e.jsxs(ot,{className:"sm:max-w-[600px]",children:[e.jsxs(ut,{children:[e.jsx(ct,{className:"flex items-center gap-2",children:n==="NO_MANAGER_FOUND"?e.jsxs(e.Fragment,{children:[e.jsx(Ge,{className:"w-5 h-5 text-amber-500"}),"Manager Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ts,{className:"w-5 h-5 text-blue-500"}),"Select Your Manager"]})}),e.jsx(It,{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(Ge,{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(d=>e.jsx("div",{className:"border rounded-lg p-4 hover:bg-gray-50 transition-colors cursor-pointer",onClick:()=>!l&&o(d.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(_t,{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:d.displayName||`${d.firstName||""} ${d.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:d.email})]}),d.department&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500",children:[e.jsx(fo,{className:"w-4 h-4"}),e.jsx("span",{children:d.department})]})]})]})]}),e.jsx(F,{onClick:c=>{c.stopPropagation(),o(d.email)},disabled:l,className:"flex-shrink-0",size:"sm",children:"Select"})]})},d.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 I4({onViewRequest:t}){const{user:s}=Jt();return Mi(s)?e.jsx(z5,{onViewRequest:t}):e.jsx(G5,{onViewRequest:t})}function Du({onNavigate:t,onNewRequest:s}){const[a,r]=h.useState(!1),[n,i]=h.useState(!0);return h.useEffect(()=>{try{const l=at.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(xT,{onNavigate:t,onNewRequest:s}):e.jsx(Ij,{onNavigate:t,onNewRequest:s})}function E4({onLogout:t}){const s=Fa(),[a,r]=h.useState(null),[n,i]=h.useState([]),[l,o]=h.useState(""),[d,c]=h.useState(""),[m,u]=h.useState(!1),[x,p]=h.useState(null);h.useEffect(()=>{const k=localStorage.getItem("dynamicRequests");if(k)try{const L=JSON.parse(k);i(L)}catch(L){console.error("Error parsing dynamic requests:",L)}},[]),h.useEffect(()=>{n.length>0&&localStorage.setItem("dynamicRequests",JSON.stringify(n))},[n]);const g=k=>{if(k==="profile"){s("/profile");return}if(k==="settings"){s("/settings");return}k.startsWith("/")?s(k):s(`/${k}`)},y=(k,L,D,S)=>{o(k),c(L||"Unknown Request"),bi({requestId:k,status:D,request:S,navigate:s})},f=()=>{s(-1)},b=()=>{s("/new-request")},v=k=>{var S,N,P,R,O,E,M,B,C,j,U;if(k.templateType){k.templateType==="claim-management"&&s("/claim-management");return}if(k.backendId){s("/my-requests");return}const L=`RE-REQ-2024-${String(Object.keys(Mp).length+n.length+1).padStart(3,"0")}`,D={id:L,title:k.title,description:k.description||"",category:k.category||"General",subcategory:k.subcategory||"",status:"pending",priority:k.priority||"standard",amount:k.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:((S=k.approvers)==null?void 0:S.length)||1,currentApprover:((P=(N=k.approvers)==null?void 0:N[0])==null?void 0:P.name)||((E=(O=(R=k.approvers)==null?void 0:R[0])==null?void 0:O.email)==null?void 0:E.split("@")[0])||"Pending Assignment",approverLevel:`1 of ${((M=k.approvers)==null?void 0:M.length)||1}`,template:"custom",initiator:{name:"Current User",role:k.initiatorRole||"Employee",department:k.department||"General",email:"current.user@royalenfield.com",phone:"+91 98765 43290",avatar:"CU"},department:k.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:(k.approvers||[]).filter($=>$).map(($,_)=>{var ce;const se=($==null?void 0:$.name)||((ce=$==null?void 0:$.email)==null?void 0:ce.split("@")[0])||`Approver ${_+1}`,W=($==null?void 0:$.email)||"";return{step:_+1,approver:`${se}${W?` (${W})`:""}`,role:($==null?void 0:$.role)||`Level ${($==null?void 0:$.level)||_+1} Approver`,status:_===0?"pending":"waiting",tatHours:$!=null&&$.tat?typeof $.tat=="string"?parseInt($.tat):$.tat:48,elapsedHours:0,assignedAt:_===0?new Date().toISOString():null,comment:null,timestamp:null}}),documents:[],spectators:(k.spectators||[]).filter($=>$&&($.name||$.email)).map($=>{var se;const _=($==null?void 0:$.name)||((se=$==null?void 0:$.email)==null?void 0:se.split("@")[0])||"Observer";return{name:_,role:($==null?void 0:$.role)||($==null?void 0:$.department)||"Observer",avatar:_.split(" ").map(W=>W[0]).join("").toUpperCase().slice(0,2)||"OB"}}),auditTrail:[{type:"created",action:"Request Created",details:`Custom request "${k.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 ${((C=(B=k.approvers)==null?void 0:B[0])==null?void 0:C.name)||((U=(j=k.approvers)==null?void 0:j[0])==null?void 0:U.email)||"first approver"}`,user:"System",timestamp:new Date().toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0})}],tags:k.tags||["custom-request"]};i([...n,D]),s("/my-requests"),Q.success("Request Submitted Successfully!",{description:`Your request "${k.title}" (${L}) has been created and sent for approval.`,duration:5e3})},A=(k,L)=>new Promise(D=>{setTimeout(()=>{k==="approve"?Q.success("Request Approved",{description:"The request has been approved and forwarded to the next step.",duration:5e3}):Q.error("Request Rejected",{description:"The request has been rejected and returned to the initiator.",duration:5e3}),r(null),D(!0)},1e3)}),w=()=>{r(null)},T=async(k,L)=>{var D,S,N,P,R,O,E;try{const M={activityName:k.activityName,activityType:k.activityType,dealerCode:k.dealerCode,dealerName:k.dealerName,dealerEmail:k.dealerEmail||void 0,dealerPhone:k.dealerPhone||void 0,dealerAddress:k.dealerAddress||void 0,activityDate:k.activityDate?new Date(k.activityDate).toISOString():void 0,location:k.location,requestDescription:k.requestDescription,periodStartDate:k.periodStartDate?new Date(k.periodStartDate).toISOString():void 0,periodEndDate:k.periodEndDate?new Date(k.periodEndDate).toISOString():void 0,estimatedBudget:k.estimatedBudget||void 0,approvers:k.approvers||[]},B=await $S(M);if(!B||!B.request)throw new Error("Invalid response from server: Request object not found");const C=B.request;if(!C.requestNumber&&!C.requestId)throw new Error("Invalid response from server: Request identifier not found");u(!1),p(null),Q.success("Claim Request Submitted",{description:"Your claim management request has been created successfully."}),C.requestNumber?s(`/request/${C.requestNumber}`):C.requestId?s(`/request/${C.requestId}`):s("/my-requests")}catch(M){console.error("[App] Error creating claim request:",M);const B=(D=M==null?void 0:M.response)==null?void 0:D.data,C=(B==null?void 0:B.code)||((S=B==null?void 0:B.error)==null?void 0:S.code);if(C==="NO_MANAGER_FOUND"){p({errorType:"NO_MANAGER_FOUND",message:(B==null?void 0:B.message)||((N=B==null?void 0:B.error)==null?void 0:N.message)||"No reporting manager found. Please ensure your manager is correctly configured in the system.",pendingClaimData:k}),u(!0);return}if(C==="MULTIPLE_MANAGERS_FOUND"){const U=(B==null?void 0:B.managers)||((P=B==null?void 0:B.error)==null?void 0:P.managers)||[];p({errorType:"MULTIPLE_MANAGERS_FOUND",managers:U,message:(B==null?void 0:B.message)||((R=B==null?void 0:B.error)==null?void 0:R.message)||"Multiple managers found. Please select one.",pendingClaimData:k}),u(!0);return}const j=((E=(O=M==null?void 0:M.response)==null?void 0:O.data)==null?void 0:E.message)||(M==null?void 0:M.message)||"Failed to create claim request";Q.error("Failed to Submit Claim Request",{description:j})}};return e.jsxs("div",{className:"min-h-screen h-screen flex flex-col overflow-hidden bg-background",children:[e.jsxs(S0,{children:[e.jsx(es,{path:"/login/callback",element:e.jsx(Cx,{})}),e.jsx(es,{path:"/",element:e.jsx(Ns,{currentPage:"dashboard",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(Du,{onNavigate:g,onNewRequest:b})})}),e.jsx(es,{path:"/dashboard",element:e.jsx(Ns,{currentPage:"dashboard",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(Du,{onNavigate:g,onNewRequest:b})})}),e.jsx(es,{path:"/open-requests",element:e.jsx(Ns,{currentPage:"open-requests",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(wT,{onViewRequest:y})})}),e.jsx(es,{path:"/closed-requests",element:e.jsx(Ns,{currentPage:"closed-requests",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(WT,{onViewRequest:y})})}),e.jsx(es,{path:"/shared-summaries",element:e.jsx(Ns,{currentPage:"shared-summaries",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(JT,{})})}),e.jsx(es,{path:"/shared-summaries/:sharedSummaryId",element:e.jsx(Ns,{currentPage:"shared-summaries",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(qT,{})})}),e.jsx(es,{path:"/my-requests",element:e.jsx(Ns,{currentPage:"my-requests",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(y5,{onViewRequest:y,dynamicRequests:n})})}),e.jsx(es,{path:"/requests",element:e.jsx(Ns,{currentPage:"requests",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(I4,{onViewRequest:y})})}),e.jsx(es,{path:"/approver-performance",element:e.jsx(Ns,{currentPage:"approver-performance",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(ik,{})})}),e.jsx(es,{path:"/request/:requestId",element:e.jsx(Ns,{currentPage:"request-detail",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(QT,{requestId:"",onBack:f,dynamicRequests:n})})}),e.jsx(es,{path:"/work-notes/:requestId",element:e.jsx(e5,{})}),e.jsx(es,{path:"/new-request",element:e.jsx(wu,{onBack:f,onSubmit:v})}),e.jsx(es,{path:"/edit-request/:requestId",element:e.jsx(wu,{onBack:f,onSubmit:v,requestId:void 0,isEditMode:!0})}),e.jsx(es,{path:"/claim-management",element:e.jsx(sT,{onBack:f,onSubmit:T})}),e.jsx(es,{path:"/profile",element:e.jsx(Ns,{currentPage:"profile",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(lk,{})})}),e.jsx(es,{path:"/settings",element:e.jsx(Ns,{currentPage:"settings",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(jk,{})})}),e.jsx(es,{path:"/notifications",element:e.jsx(Ns,{currentPage:"notifications",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(Nk,{onNavigate:g})})}),e.jsx(es,{path:"/detailed-reports",element:e.jsx(Ns,{currentPage:"detailed-reports",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(Bk,{})})}),e.jsx(es,{path:"/admin",element:e.jsx(Ns,{currentPage:"admin",onNavigate:g,onNewRequest:b,onLogout:t,children:e.jsx(C4,{})})})]}),e.jsx(D4,{position:"top-right",toastOptions:{style:{background:"var(--card)",color:"var(--card-foreground)",border:"1px solid var(--border)"}}}),e.jsx(P4,{open:m,onClose:()=>{u(!1),p(null)},onSelect:async k=>{x!=null&&x.pendingClaimData&&await T(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(A4,{isOpen:!!a,onClose:w,action:a,requestId:l,requestTitle:d,onSubmit:A})]})}function F4(t){const{onLogout:s}=t||{};return e.jsx(A0,{children:e.jsx(E4,{onLogout:s})})}function M4(){const{isAuthenticated:t,isLoading:s,error:a,user:r,logout:n}=Jt(),[i,l]=h.useState(!1),o=typeof window<"u"&&window.location.pathname==="/login/callback",d=async()=>{try{if(!n){console.error("🔵 ERROR: logout function is undefined!");return}await n()}catch(c){console.error("🔵 Logout error in handleLogout:",c);try{localStorage.clear(),sessionStorage.clear(),window.location.href="/"}catch(m){console.error("🔵 Error during emergency cleanup:",m)}}};if(h.useEffect(()=>{},[t,s,a,r]),o){const c=typeof window<"u"?new URLSearchParams(window.location.search):null,m=c==null?void 0:c.get("code"),u=c==null?void 0:c.get("error");if(!m&&!u){console.log("🚪 AuthenticatedApp: Logout redirect detected, redirecting to home");const p=new URLSearchParams;return p.set("tanflow_logged_out","true"),p.set("logout",Date.now().toString()),window.location.replace(`/?${p.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(Ky,{}):e.jsx(Cx,{})}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(F4,{onLogout:d}),i&&e.jsx(Zy,{isOpen:i,onClose:()=>l(!1)})]}):e.jsx(Gy,{})}const si=()=>{try{return!0}catch{return!1}},_4=()=>{if(si())return null;try{return localStorage.getItem("token")}catch{return null}},L4={user:null,token:_4(),isAuthenticated:!1,isLoading:!1,error:null},vg=zr({name:"auth",initialState:L4,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,!si())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,!si())try{localStorage.removeItem("token")}catch{}},logout:t=>{if(t.isAuthenticated=!1,t.user=null,t.token=null,t.error=null,!si())try{localStorage.removeItem("token")}catch{}},clearError:t=>{t.error=null},updateUser:(t,s)=>{t.user=s.payload}}}),{loginStart:X4,loginSuccess:Q4,loginFailure:J4,logout:q4,clearError:eR,updateUser:tR}=vg.actions,O4=C0({reducer:{auth:vg.reducer,dashboard:Rx.reducer,requests:og.reducer,myRequests:rg.reducer,openRequests:Bx.reducer,closedRequests:tg.reducer},middleware:t=>t({serializableCheck:{ignoredActions:["persist/PERSIST"]}}),devTools:!1});Ol.createRoot(document.getElementById("root")).render(e.jsx(Tf.StrictMode,{children:e.jsx(G0,{store:O4,children:e.jsx(xy,{children:e.jsx(M4,{})})})}));export{Ne as a};
|
||
//# sourceMappingURL=index-F9w_cZ47.js.map
|